@hexabot-ai/agentic 3.4.0 → 3.5.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 (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
@@ -7,9 +7,10 @@
7
7
  import { z } from 'zod';
8
8
 
9
9
  import { defineAction } from '../action/action';
10
+ import type { TaskFrame, WorkflowCheckpoint } from '../checkpoint';
10
11
  import { BaseWorkflowContext } from '../context';
11
12
  import type { Settings, WorkflowDefinition } from '../dsl.types';
12
- import { ParallelSuspensionError } from '../errors';
13
+ import { WorkflowCheckpointInvalidError } from '../errors';
13
14
  import { compileWorkflow } from '../workflow-compiler';
14
15
  import {
15
16
  StepType,
@@ -75,6 +76,12 @@ class TestContext extends BaseWorkflowContext<
75
76
  }
76
77
  }
77
78
 
79
+ /** Round-trip a checkpoint through JSON, as a host database would. */
80
+ const persist = (checkpoint: WorkflowCheckpoint): WorkflowCheckpoint =>
81
+ JSON.parse(JSON.stringify(checkpoint));
82
+ /** Read the task frame of a checkpoint suspended on a top-level task. */
83
+ const suspendedTask = (checkpoint: WorkflowCheckpoint): TaskFrame =>
84
+ checkpoint.root.child as TaskFrame;
78
85
  const baseRetries = {
79
86
  enabled: true,
80
87
  max_attempts: 1,
@@ -568,7 +575,9 @@ describe('WorkflowRunner', () => {
568
575
  if (startResult.status !== 'suspended') {
569
576
  throw new Error('Workflow did not suspend as expected');
570
577
  }
571
- expect(startResult.step.id).toBe('0.wait_until_stop.0:wait_step[0]');
578
+ expect(startResult.waits[0].step.id).toBe(
579
+ '0.wait_until_stop.0:wait_step[0]',
580
+ );
572
581
 
573
582
  const firstResume = await runner.resume({
574
583
  resumeData: { reply: 'continue' },
@@ -577,7 +586,9 @@ describe('WorkflowRunner', () => {
577
586
  if (firstResume.status !== 'suspended') {
578
587
  throw new Error('Workflow did not suspend on second iteration');
579
588
  }
580
- expect(firstResume.step.id).toBe('0.wait_until_stop.0:wait_step[1]');
589
+ expect(firstResume.waits[0].step.id).toBe(
590
+ '0.wait_until_stop.0:wait_step[1]',
591
+ );
581
592
 
582
593
  const secondResume = await runner.resume({
583
594
  resumeData: { reply: 'stop' },
@@ -724,24 +735,23 @@ describe('WorkflowRunner', () => {
724
735
  const startResult = await runner.start({ inputData: {}, context });
725
736
  expect(startResult.status).toBe('suspended');
726
737
  if (startResult.status === 'suspended') {
727
- expect(startResult.reason).toBe('awaiting_user');
738
+ expect(startResult.waits[0].reason).toBe('awaiting_user');
728
739
  expect(runner.getStatus()).toBe('suspended');
729
- expect(runner.getSnapshot().actions[startResult.step.id]?.status).toBe(
730
- 'suspended',
731
- );
740
+ expect(
741
+ runner.getSnapshot().actions[startResult.waits[0].step.id]?.status,
742
+ ).toBe('suspended');
732
743
  }
733
744
 
734
745
  const resume = await runner.resume({ resumeData: { reply: 'Sure' } });
735
746
  expect(resume.status).toBe('finished');
736
747
  if (resume.status === 'finished') {
737
748
  expect(resume.output.reply).toBe('Sure');
738
- expect(runner.getLastResumeData()).toEqual({ reply: 'Sure' });
739
749
  }
740
750
 
741
751
  expect(() => context.workflow).toThrow();
742
752
  });
743
753
 
744
- it('fails when a parallel branch attempts to suspend', async () => {
754
+ it('suspends and resumes inside a parallel branch', async () => {
745
755
  const suspendAction = defineAction<
746
756
  unknown,
747
757
  { reply: string },
@@ -752,9 +762,11 @@ describe('WorkflowRunner', () => {
752
762
  inputSchema: z.any(),
753
763
  outputSchema: z.object({ reply: z.string() }),
754
764
  execute: async ({ context }) => {
755
- await context.workflow.suspend({ reason: 'not_allowed' });
765
+ const resumed = (await context.workflow.suspend({
766
+ reason: 'awaiting_reply',
767
+ })) as { reply: string };
756
768
 
757
- return { reply: 'unreachable' };
769
+ return { reply: resumed.reply };
758
770
  },
759
771
  });
760
772
  const definition: WorkflowDefinition = {
@@ -782,16 +794,22 @@ describe('WorkflowRunner', () => {
782
794
  context: new TestContext({}),
783
795
  });
784
796
 
785
- expect(result.status).toBe('failed');
786
- if (result.status === 'failed') {
787
- expect(result.error).toBeInstanceOf(ParallelSuspensionError);
797
+ expect(result.status).toBe('suspended');
798
+ if (result.status === 'suspended') {
799
+ expect(result.waits.map((wait) => wait.step.id)).toEqual([
800
+ '0.parallel.0:wait_step',
801
+ ]);
788
802
  }
789
803
  expect(
790
804
  runner.getSnapshot().actions['0.parallel.0:wait_step'],
791
- ).toMatchObject({
792
- status: 'failed',
793
- reason: 'workflow.suspend() is not supported inside a parallel block.',
794
- });
805
+ ).toMatchObject({ status: 'suspended', reason: 'awaiting_reply' });
806
+
807
+ const resumed = await runner.resume({ resumeData: { reply: 'done' } });
808
+
809
+ expect(resumed.status).toBe('finished');
810
+ if (resumed.status === 'finished') {
811
+ expect(resumed.output).toEqual({ reply: 'done' });
812
+ }
795
813
  });
796
814
 
797
815
  it('accepts emitter-like implementations without Node EventEmitter', async () => {
@@ -1027,7 +1045,7 @@ describe('WorkflowRunner', () => {
1027
1045
  throw new Error('workflow did not suspend');
1028
1046
  }
1029
1047
 
1030
- expect(startResult.step.id).toBe('0:wait_step');
1048
+ expect(startResult.waits[0].step.id).toBe('0:wait_step');
1031
1049
  expect(runner.getSnapshot().actions['0:wait_step']?.status).toBe(
1032
1050
  'suspended',
1033
1051
  );
@@ -1087,7 +1105,7 @@ describe('WorkflowRunner', () => {
1087
1105
  }
1088
1106
  });
1089
1107
 
1090
- it('throws when a persisted suspension cannot be rebuilt', async () => {
1108
+ it('refuses to restore a run without a checkpoint', () => {
1091
1109
  const noopAction = defineAction<
1092
1110
  unknown,
1093
1111
  { ok: boolean },
@@ -1109,23 +1127,16 @@ describe('WorkflowRunner', () => {
1109
1127
  const compiled = compileWorkflow(definition, {
1110
1128
  actions: { noop_action: noopAction },
1111
1129
  });
1112
- const persistedState: ExecutionState = {
1113
- input: {},
1114
- output: {},
1115
- iterationStack: [],
1116
- };
1117
1130
 
1118
- await expect(
1119
- WorkflowRunner.fromPersistedState(compiled, {
1120
- state: persistedState,
1131
+ expect(() =>
1132
+ WorkflowRunner.fromCheckpoint(compiled, {
1133
+ checkpoint: null,
1121
1134
  context: new TestContext({}),
1122
- snapshot: { status: 'suspended', actions: {} },
1123
- suspension: { stepId: 'unknown.step', reason: null, data: undefined },
1124
1135
  }),
1125
- ).rejects.toThrow('Unable to rebuild suspension for step unknown.step');
1136
+ ).toThrow(WorkflowCheckpointInvalidError);
1126
1137
  });
1127
1138
 
1128
- it('rebuilds loop suspension using the iteration suffix when iterationStack is missing', async () => {
1139
+ it('restores a loop suspension from a persisted checkpoint', async () => {
1129
1140
  const suspendAction = defineAction<
1130
1141
  { prompt: string },
1131
1142
  { reply: string },
@@ -1159,7 +1170,7 @@ describe('WorkflowRunner', () => {
1159
1170
  defs: createTaskDefs({
1160
1171
  wait_step: {
1161
1172
  action: 'loop_suspend_action',
1162
- inputs: { prompt: '="Ping"' },
1173
+ inputs: { prompt: '=$iteration.item' },
1163
1174
  },
1164
1175
  after_step: {
1165
1176
  action: 'after_loop_action',
@@ -1194,10 +1205,9 @@ describe('WorkflowRunner', () => {
1194
1205
  },
1195
1206
  });
1196
1207
  const runner = new WorkflowRunner(compiled);
1197
- const context = new TestContext({});
1198
1208
  const startResult = await runner.start({
1199
1209
  inputData: { items: ['first'] },
1200
- context,
1210
+ context: new TestContext({}),
1201
1211
  });
1202
1212
 
1203
1213
  expect(startResult.status).toBe('suspended');
@@ -1205,25 +1215,16 @@ describe('WorkflowRunner', () => {
1205
1215
  throw new Error('Workflow did not suspend as expected');
1206
1216
  }
1207
1217
 
1208
- expect(startResult.step.id).toBe('0.iterate.0:wait_step[0]');
1218
+ expect(startResult.waits[0]).toMatchObject({
1219
+ step: { id: '0.iterate.0:wait_step[0]' },
1220
+ reason: 'awaiting_reply',
1221
+ data: { prompt: 'first' },
1222
+ });
1209
1223
 
1210
- const runtimeState = (runner as unknown as { state: ExecutionState }).state;
1211
- const persistedState: ExecutionState = {
1212
- input: { ...runtimeState.input },
1213
- output: { ...runtimeState.output },
1214
- iteration: runtimeState.iteration,
1215
- accumulator: runtimeState.accumulator,
1216
- iterationStack: [],
1217
- };
1218
- const rebuilt = await WorkflowRunner.fromPersistedState(compiled, {
1219
- state: persistedState,
1224
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1225
+ checkpoint: persist(startResult.checkpoint),
1220
1226
  context: new TestContext({}),
1221
1227
  snapshot: startResult.snapshot,
1222
- suspension: {
1223
- stepId: startResult.step.id,
1224
- reason: startResult.reason ?? null,
1225
- data: startResult.data,
1226
- },
1227
1228
  });
1228
1229
  const resumeResult = await rebuilt.resume({
1229
1230
  resumeData: { reply: 'Pong' },
@@ -1235,7 +1236,7 @@ describe('WorkflowRunner', () => {
1235
1236
  }
1236
1237
  });
1237
1238
 
1238
- it('rebuilds a task suspended on a later suspend() call using suspend metadata and await history', async () => {
1239
+ it('restores a task suspended on a later suspend() call with its earlier results', async () => {
1239
1240
  const multiSuspendAction = defineAction<
1240
1241
  unknown,
1241
1242
  { firstReply: string; secondReply: string },
@@ -1290,9 +1291,11 @@ describe('WorkflowRunner', () => {
1290
1291
  throw new Error('Workflow did not suspend on first await point');
1291
1292
  }
1292
1293
 
1293
- expect(firstSuspension.suspendIndex).toBe(1);
1294
- expect(firstSuspension.suspendKey).toBe('index:1');
1295
- expect(firstSuspension.awaitResults).toEqual({});
1294
+ expect(firstSuspension.waits[0]).toMatchObject({
1295
+ waitId: '0:wait_step@index:1',
1296
+ suspendKey: 'index:1',
1297
+ });
1298
+ expect(suspendedTask(firstSuspension.checkpoint).awaitResults).toEqual({});
1296
1299
 
1297
1300
  const secondSuspension = await runner.resume({
1298
1301
  resumeData: { reply: 'first-answer' },
@@ -1302,33 +1305,19 @@ describe('WorkflowRunner', () => {
1302
1305
  throw new Error('Workflow did not suspend on second await point');
1303
1306
  }
1304
1307
 
1305
- expect(secondSuspension.suspendIndex).toBe(2);
1306
- expect(secondSuspension.suspendKey).toBe('index:2');
1307
- expect(secondSuspension.awaitResults).toEqual({
1308
- 'index:1': { reply: 'first-answer' },
1308
+ expect(secondSuspension.waits[0]).toMatchObject({
1309
+ waitId: '0:wait_step@index:2',
1310
+ suspendKey: 'index:2',
1311
+ reason: 'second_pause',
1312
+ });
1313
+ expect(suspendedTask(secondSuspension.checkpoint).awaitResults).toEqual({
1314
+ 'index:1': { value: { reply: 'first-answer' } },
1309
1315
  });
1310
1316
 
1311
- const runtimeState = runner.getState() as ExecutionState;
1312
- const persistedState: ExecutionState = {
1313
- input: { ...runtimeState.input },
1314
- output: { ...runtimeState.output },
1315
- iteration: runtimeState.iteration,
1316
- accumulator: runtimeState.accumulator,
1317
- iterationStack: [...runtimeState.iterationStack],
1318
- };
1319
- const rebuilt = await WorkflowRunner.fromPersistedState(compiled, {
1320
- state: persistedState,
1317
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1318
+ checkpoint: persist(secondSuspension.checkpoint),
1321
1319
  context: new TestContext({}),
1322
1320
  snapshot: secondSuspension.snapshot,
1323
- suspension: {
1324
- stepId: secondSuspension.step.id,
1325
- reason: secondSuspension.reason ?? null,
1326
- data: secondSuspension.data,
1327
- stepExecId: secondSuspension.stepExecId,
1328
- suspendIndex: secondSuspension.suspendIndex,
1329
- suspendKey: secondSuspension.suspendKey,
1330
- awaitResults: secondSuspension.awaitResults,
1331
- },
1332
1321
  });
1333
1322
  const finalResult = await rebuilt.resume({
1334
1323
  resumeData: { reply: 'second-answer' },
@@ -1341,7 +1330,7 @@ describe('WorkflowRunner', () => {
1341
1330
  }
1342
1331
  });
1343
1332
 
1344
- it('lets actions skip side effects via hasRecordedResult when replaying a resumed step', async () => {
1333
+ it('lets actions skip side effects via hasRecordedResult when a resumed body re-runs', async () => {
1345
1334
  const sideEffects: string[] = [];
1346
1335
  const spawnAction = defineAction<
1347
1336
  unknown,
@@ -1353,8 +1342,8 @@ describe('WorkflowRunner', () => {
1353
1342
  inputSchema: z.any(),
1354
1343
  outputSchema: z.object({ reply: z.string() }),
1355
1344
  execute: async ({ context }) => {
1356
- // Deterministic replay re-runs this body; the guard must prevent the
1357
- // side effect from executing a second time.
1345
+ // A resumed body re-runs; the guard must prevent the side effect
1346
+ // from executing a second time.
1358
1347
  if (!context.workflow.hasRecordedResult()) {
1359
1348
  sideEffects.push('spawn');
1360
1349
  }
@@ -1392,26 +1381,10 @@ describe('WorkflowRunner', () => {
1392
1381
 
1393
1382
  expect(sideEffects).toEqual(['spawn']);
1394
1383
 
1395
- const runtimeState = runner.getState() as ExecutionState;
1396
- const rebuilt = await WorkflowRunner.fromPersistedState(compiled, {
1397
- state: {
1398
- input: { ...runtimeState.input },
1399
- output: { ...runtimeState.output },
1400
- iteration: runtimeState.iteration,
1401
- accumulator: runtimeState.accumulator,
1402
- iterationStack: [...runtimeState.iterationStack],
1403
- },
1384
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1385
+ checkpoint: persist(startResult.checkpoint),
1404
1386
  context: new TestContext({}),
1405
1387
  snapshot: startResult.snapshot,
1406
- suspension: {
1407
- stepId: startResult.step.id,
1408
- reason: startResult.reason ?? null,
1409
- data: startResult.data,
1410
- stepExecId: startResult.stepExecId,
1411
- suspendIndex: startResult.suspendIndex,
1412
- suspendKey: startResult.suspendKey,
1413
- awaitResults: startResult.awaitResults,
1414
- },
1415
1388
  });
1416
1389
  const resumeResult = await rebuilt.resume({
1417
1390
  resumeData: { reply: 'child-finished' },
@@ -1422,11 +1395,10 @@ describe('WorkflowRunner', () => {
1422
1395
  expect(resumeResult.output.reply).toBe('child-finished');
1423
1396
  }
1424
1397
 
1425
- // The side effect must not run a second time during deterministic replay.
1426
1398
  expect(sideEffects).toEqual(['spawn']);
1427
1399
  });
1428
1400
 
1429
- it('reports recorded results only for suspensions that will replay immediately', async () => {
1401
+ it('reports recorded results only for suspensions that will resolve immediately', async () => {
1430
1402
  const observed: boolean[] = [];
1431
1403
  const multiSuspendAction = defineAction<
1432
1404
  unknown,
@@ -1479,6 +1451,7 @@ describe('WorkflowRunner', () => {
1479
1451
  context: new TestContext({}),
1480
1452
  });
1481
1453
  expect(firstSuspension.status).toBe('suspended');
1454
+ expect(observed).toEqual([false]);
1482
1455
 
1483
1456
  const secondSuspension = await runner.resume({
1484
1457
  resumeData: { reply: 'first-answer' },
@@ -1488,29 +1461,13 @@ describe('WorkflowRunner', () => {
1488
1461
  throw new Error('Workflow did not suspend on second await point');
1489
1462
  }
1490
1463
 
1491
- // In-memory execution never sees pre-recorded results.
1492
- expect(observed).toEqual([false, false]);
1493
-
1494
- const runtimeState = runner.getState() as ExecutionState;
1495
- const rebuilt = await WorkflowRunner.fromPersistedState(compiled, {
1496
- state: {
1497
- input: { ...runtimeState.input },
1498
- output: { ...runtimeState.output },
1499
- iteration: runtimeState.iteration,
1500
- accumulator: runtimeState.accumulator,
1501
- iterationStack: [...runtimeState.iterationStack],
1502
- },
1464
+ // The resumed body re-runs: the first suspension is answered, the second is new.
1465
+ expect(observed).toEqual([false, true, false]);
1466
+
1467
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1468
+ checkpoint: persist(secondSuspension.checkpoint),
1503
1469
  context: new TestContext({}),
1504
1470
  snapshot: secondSuspension.snapshot,
1505
- suspension: {
1506
- stepId: secondSuspension.step.id,
1507
- reason: secondSuspension.reason ?? null,
1508
- data: secondSuspension.data,
1509
- stepExecId: secondSuspension.stepExecId,
1510
- suspendIndex: secondSuspension.suspendIndex,
1511
- suspendKey: secondSuspension.suspendKey,
1512
- awaitResults: secondSuspension.awaitResults,
1513
- },
1514
1471
  });
1515
1472
  const finalResult = await rebuilt.resume({
1516
1473
  resumeData: { reply: 'second-answer' },
@@ -1522,11 +1479,88 @@ describe('WorkflowRunner', () => {
1522
1479
  expect(finalResult.output.secondReply).toBe('second-answer');
1523
1480
  }
1524
1481
 
1525
- // During replay both suspensions have recorded results awaiting them.
1526
- expect(observed).toEqual([false, false, true, true]);
1482
+ expect(observed).toEqual([false, true, false, true, true]);
1483
+ });
1484
+
1485
+ it('keeps a resume without payload recorded across later suspensions', async () => {
1486
+ const sideEffects: string[] = [];
1487
+ const acknowledged: unknown[] = [];
1488
+ const acknowledgeAction = defineAction<
1489
+ unknown,
1490
+ { reply: string },
1491
+ TestContext,
1492
+ Settings
1493
+ >({
1494
+ name: 'acknowledge_then_ask_action',
1495
+ inputSchema: z.any(),
1496
+ outputSchema: z.object({ reply: z.string() }),
1497
+ execute: async ({ context }) => {
1498
+ if (!context.workflow.hasRecordedResult()) {
1499
+ sideEffects.push('notify');
1500
+ }
1501
+
1502
+ acknowledged.push(
1503
+ await context.workflow.suspend({ reason: 'acknowledge' }),
1504
+ );
1505
+ const answer = (await context.workflow.suspend({
1506
+ reason: 'ask',
1507
+ })) as { reply: string };
1508
+
1509
+ return { reply: answer.reply };
1510
+ },
1511
+ });
1512
+ const definition: WorkflowDefinition = {
1513
+ defs: createTaskDefs({
1514
+ wait_step: {
1515
+ action: 'acknowledge_then_ask_action',
1516
+ inputs: {},
1517
+ },
1518
+ }),
1519
+ flow: [{ do: 'wait_step' }],
1520
+ outputs: { reply: '=$output.wait_step.reply' },
1521
+ };
1522
+ const compiled = compileWorkflow(definition, {
1523
+ actions: { acknowledge_then_ask_action: acknowledgeAction },
1524
+ });
1525
+ const runner = new WorkflowRunner(compiled);
1526
+ const firstSuspension = await runner.start({
1527
+ inputData: {},
1528
+ context: new TestContext({}),
1529
+ });
1530
+ expect(firstSuspension.status).toBe('suspended');
1531
+
1532
+ // An "acknowledge" button resumes without sending a body.
1533
+ const secondSuspension = await runner.resume({});
1534
+ expect(secondSuspension.status).toBe('suspended');
1535
+ if (secondSuspension.status !== 'suspended') {
1536
+ throw new Error('Workflow did not suspend on second await point');
1537
+ }
1538
+
1539
+ // Recorded as answered, without a value: JSON has no `undefined`.
1540
+ expect(suspendedTask(secondSuspension.checkpoint).awaitResults).toEqual({
1541
+ 'index:1': {},
1542
+ });
1543
+
1544
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1545
+ checkpoint: persist(secondSuspension.checkpoint),
1546
+ context: new TestContext({}),
1547
+ snapshot: secondSuspension.snapshot,
1548
+ });
1549
+ const finalResult = await rebuilt.resume({
1550
+ resumeData: { reply: 'answer' },
1551
+ });
1552
+
1553
+ expect(finalResult.status).toBe('finished');
1554
+ if (finalResult.status === 'finished') {
1555
+ expect(finalResult.output.reply).toBe('answer');
1556
+ }
1557
+
1558
+ expect(sideEffects).toEqual(['notify']);
1559
+ // Every pass resolves the acknowledgement to the same persisted value.
1560
+ expect(acknowledged).toEqual([undefined, undefined]);
1527
1561
  });
1528
1562
 
1529
- it('fails resume when replay suspension metadata does not match the workflow code path', async () => {
1563
+ it('fails resume when the resumed body no longer matches the checkpoint', async () => {
1530
1564
  const suspendAction = defineAction<
1531
1565
  unknown,
1532
1566
  { reply: string },
@@ -1567,26 +1601,15 @@ describe('WorkflowRunner', () => {
1567
1601
  throw new Error('Workflow did not suspend as expected');
1568
1602
  }
1569
1603
 
1570
- const runtimeState = runner.getState() as ExecutionState;
1571
- const rebuilt = await WorkflowRunner.fromPersistedState(compiled, {
1572
- state: {
1573
- input: { ...runtimeState.input },
1574
- output: { ...runtimeState.output },
1575
- iteration: runtimeState.iteration,
1576
- accumulator: runtimeState.accumulator,
1577
- iterationStack: [...runtimeState.iterationStack],
1578
- },
1604
+ // Simulate action code that changed between suspension and resume.
1605
+ const checkpoint = persist(startResult.checkpoint);
1606
+ suspendedTask(checkpoint).wait.reason = 'different_reason';
1607
+ checkpoint.waits[0].reason = 'different_reason';
1608
+
1609
+ const rebuilt = WorkflowRunner.fromCheckpoint(compiled, {
1610
+ checkpoint,
1579
1611
  context: new TestContext({}),
1580
1612
  snapshot: startResult.snapshot,
1581
- suspension: {
1582
- stepId: startResult.step.id,
1583
- reason: 'different_reason',
1584
- data: startResult.data,
1585
- stepExecId: startResult.stepExecId,
1586
- suspendIndex: startResult.suspendIndex,
1587
- suspendKey: startResult.suspendKey,
1588
- awaitResults: startResult.awaitResults,
1589
- },
1590
1613
  });
1591
1614
  const resumeResult = await rebuilt.resume({
1592
1615
  resumeData: { reply: 'value' },
@@ -1598,7 +1621,7 @@ describe('WorkflowRunner', () => {
1598
1621
  'NonDeterministicWorkflowError',
1599
1622
  );
1600
1623
  expect(String((resumeResult.error as Error).message)).toContain(
1601
- 'expected reason \"different_reason\"',
1624
+ 'expected reason "different_reason"',
1602
1625
  );
1603
1626
  }
1604
1627
  });
@@ -9,6 +9,11 @@ import { z } from 'zod';
9
9
  import { defineAction } from '../action/action';
10
10
  import { BaseWorkflowContext } from '../context';
11
11
  import { Settings, WorkflowDefinition, validateWorkflow } from '../dsl.types';
12
+ import {
13
+ WorkflowCheckpointInvalidError,
14
+ WorkflowDefinitionDriftError,
15
+ WorkflowWaitNotFoundError,
16
+ } from '../errors';
12
17
  import { Workflow, WorkflowEventEmitter } from '../workflow';
13
18
  import { EventEmitterLike } from '../workflow-event-emitter';
14
19
 
@@ -137,10 +142,10 @@ describe('Workflow execution', () => {
137
142
  });
138
143
  expect(startResult.status).toBe('suspended');
139
144
  if (startResult.status === 'suspended') {
140
- expect(startResult.reason).toBe('waiting_for_user');
141
- expect(runner.getSnapshot().actions[startResult.step.id]?.status).toBe(
142
- 'suspended',
143
- );
145
+ expect(startResult.waits[0].reason).toBe('waiting_for_user');
146
+ expect(
147
+ runner.getSnapshot().actions[startResult.waits[0].step.id]?.status,
148
+ ).toBe('suspended');
144
149
  }
145
150
 
146
151
  const resumeResult = await runner.resume({
@@ -310,11 +315,97 @@ describe('Workflow execution', () => {
310
315
  const context = new TestContext();
311
316
 
312
317
  await expect(workflow.run({}, context)).rejects.toMatchObject({
313
- stepId: '0:pause_step',
314
- reason: 'need_input',
318
+ message: 'Workflow run suspended at 0:pause_step (need_input)',
319
+ waits: [
320
+ {
321
+ waitId: '0:pause_step@index:1',
322
+ step: { id: '0:pause_step' },
323
+ reason: 'need_input',
324
+ data: { prompt: 'ok?' },
325
+ },
326
+ ],
315
327
  });
316
328
  expect(() => context.workflow).toThrow(
317
329
  'Workflow runtime is not attached to this context.',
318
330
  );
319
331
  });
332
+
333
+ it('validates a persisted checkpoint and restores a runner from it', async () => {
334
+ const askAction = defineAction<
335
+ unknown,
336
+ { reply: string },
337
+ TestContext,
338
+ Settings
339
+ >({
340
+ name: 'ask_action',
341
+ inputSchema: z.any(),
342
+ outputSchema: z.object({ reply: z.string() }),
343
+ execute: async ({ context }) =>
344
+ context.workflow.suspend<{ reply: string }>({ reason: 'need_input' }),
345
+ });
346
+ const definition: WorkflowDefinition = {
347
+ defs: createTaskDefs({ ask: { action: 'ask_action', inputs: {} } }),
348
+ flow: [{ do: 'ask' }],
349
+ outputs: { reply: '=$output.ask.reply' },
350
+ };
351
+ const options = { actions: { ask_action: askAction } };
352
+ const workflow = Workflow.fromDefinition(definition, options);
353
+ const runner = await workflow.buildAsyncRunner();
354
+ const started = await runner.start({
355
+ inputData: {},
356
+ context: new TestContext(),
357
+ });
358
+ if (started.status !== 'suspended') {
359
+ throw new Error('Expected the run to suspend');
360
+ }
361
+ const stored = JSON.parse(
362
+ JSON.stringify({
363
+ checkpoint: started.checkpoint,
364
+ snapshot: started.snapshot,
365
+ }),
366
+ );
367
+ const [wait] = started.waits;
368
+
369
+ expect(
370
+ workflow.validateCheckpoint(stored.checkpoint, { waitId: wait.waitId }),
371
+ ).toEqual({ ok: true, checkpoint: stored.checkpoint });
372
+
373
+ const unknownWait = workflow.validateCheckpoint(stored.checkpoint, {
374
+ waitId: 'other@index:1',
375
+ });
376
+ expect(unknownWait.ok).toBe(false);
377
+ if (!unknownWait.ok) {
378
+ expect(unknownWait.error).toBeInstanceOf(WorkflowWaitNotFoundError);
379
+ }
380
+
381
+ const changed = Workflow.fromDefinition(
382
+ { ...definition, outputs: { reply: '=$output.ask' } },
383
+ options,
384
+ ).validateCheckpoint(stored.checkpoint);
385
+ expect(changed.ok).toBe(false);
386
+ if (!changed.ok) {
387
+ expect(changed.error).toBeInstanceOf(WorkflowDefinitionDriftError);
388
+ }
389
+
390
+ expect(() =>
391
+ workflow.buildRunnerFromCheckpoint({
392
+ checkpoint: undefined,
393
+ context: new TestContext(),
394
+ }),
395
+ ).toThrow(WorkflowCheckpointInvalidError);
396
+
397
+ const restored = workflow.buildRunnerFromCheckpoint({
398
+ checkpoint: stored.checkpoint,
399
+ snapshot: stored.snapshot,
400
+ context: new TestContext(),
401
+ });
402
+
403
+ expect(restored.getStatus()).toBe('suspended');
404
+ expect(restored.getSnapshot().actions[wait.step.id]).toMatchObject({
405
+ status: 'suspended',
406
+ });
407
+ await expect(
408
+ restored.resume({ waitId: wait.waitId, resumeData: { reply: 'yes' } }),
409
+ ).resolves.toMatchObject({ status: 'finished', output: { reply: 'yes' } });
410
+ });
320
411
  });