@gobing-ai/ts-dual-workflow-engine 0.5.12 → 0.5.15

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 (49) hide show
  1. package/README.md +23 -22
  2. package/dist/action-step.d.ts +1 -0
  3. package/dist/action-step.d.ts.map +1 -1
  4. package/dist/action-step.js +1 -0
  5. package/dist/config.d.ts.map +1 -1
  6. package/dist/config.js +137 -3
  7. package/dist/dag.d.ts +25 -0
  8. package/dist/dag.d.ts.map +1 -0
  9. package/dist/dag.js +215 -0
  10. package/dist/events.d.ts +33 -0
  11. package/dist/events.d.ts.map +1 -1
  12. package/dist/host.d.ts.map +1 -1
  13. package/dist/host.js +4 -3
  14. package/dist/index.d.ts +3 -2
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +2 -1
  17. package/dist/persistence.d.ts +24 -1
  18. package/dist/persistence.d.ts.map +1 -1
  19. package/dist/persistence.js +91 -0
  20. package/dist/run-lifecycle.d.ts +8 -0
  21. package/dist/run-lifecycle.d.ts.map +1 -1
  22. package/dist/run-lifecycle.js +71 -2
  23. package/dist/schema-sql.d.ts.map +1 -1
  24. package/dist/schema-sql.js +20 -0
  25. package/dist/schema.d.ts +180 -1
  26. package/dist/schema.d.ts.map +1 -1
  27. package/dist/schema.js +101 -14
  28. package/dist/service.d.ts.map +1 -1
  29. package/dist/service.js +17 -3
  30. package/dist/transition-flow.d.ts.map +1 -1
  31. package/dist/transition-flow.js +191 -0
  32. package/dist/types.d.ts +90 -2
  33. package/dist/types.d.ts.map +1 -1
  34. package/package.json +4 -4
  35. package/schemas/dag-workflow.schema.json +93 -0
  36. package/schemas/transition-flow-workflow.schema.json +34 -0
  37. package/src/action-step.ts +2 -0
  38. package/src/config.ts +152 -5
  39. package/src/dag.ts +297 -0
  40. package/src/events.ts +33 -0
  41. package/src/host.ts +4 -2
  42. package/src/index.ts +6 -0
  43. package/src/persistence.ts +155 -0
  44. package/src/run-lifecycle.ts +75 -2
  45. package/src/schema-sql.ts +20 -0
  46. package/src/schema.ts +104 -16
  47. package/src/service.ts +24 -7
  48. package/src/transition-flow.ts +271 -0
  49. package/src/types.ts +109 -2
package/src/events.ts CHANGED
@@ -145,4 +145,37 @@ export type WorkflowEngineEvents = {
145
145
  externalKey?: string;
146
146
  severity: EventSeverity;
147
147
  }) => void;
148
+ /** Emitted when an execution branch in a parallel region starts. */
149
+ 'workflow.branch.started': (data: {
150
+ runId: string;
151
+ parallelNode: string;
152
+ branchId: string;
153
+ node: string;
154
+ severity: EventSeverity;
155
+ }) => void;
156
+ /** Emitted when an execution branch in a parallel region finishes. */
157
+ 'workflow.branch.done': (data: {
158
+ runId: string;
159
+ parallelNode: string;
160
+ branchId: string;
161
+ durationMs: number;
162
+ ok: boolean;
163
+ severity: EventSeverity;
164
+ }) => void;
165
+ /** Emitted when an execution branch in a parallel region fails. */
166
+ 'workflow.branch.failed': (data: {
167
+ runId: string;
168
+ parallelNode: string;
169
+ branchId: string;
170
+ error?: string;
171
+ severity: EventSeverity;
172
+ }) => void;
173
+ /** Emitted when an execution branch in a parallel region pauses. */
174
+ 'workflow.branch.paused': (data: {
175
+ runId: string;
176
+ parallelNode: string;
177
+ branchId: string;
178
+ node: string;
179
+ severity: EventSeverity;
180
+ }) => void;
148
181
  };
package/src/host.ts CHANGED
@@ -163,6 +163,7 @@ async function spawnShellCommand(
163
163
  processExecutor: ProcessExecutor,
164
164
  options: Record<string, unknown>,
165
165
  workdir: string | undefined,
166
+ signal?: AbortSignal,
166
167
  ): Promise<ShellSpawnOutcome> {
167
168
  const command = stringOption(options, 'command');
168
169
  const explicitArgs = arrayOption(options, 'args');
@@ -177,6 +178,7 @@ async function spawnShellCommand(
177
178
  cwd: optionalStringOption(options, 'cwd', workdir),
178
179
  ...(env !== undefined ? { env, envMode: 'merge' as const } : {}),
179
180
  ...(timeout !== undefined ? { timeout } : {}),
181
+ ...(signal !== undefined ? { signal } : {}),
180
182
  rejectOnError: false,
181
183
  forceBuffered: true,
182
184
  });
@@ -204,7 +206,7 @@ export class ShellActionRunner implements ActionRunner {
204
206
  * the old behavior — fails with a null exit code for any line containing spaces.
205
207
  */
206
208
  async execute(options: Record<string, unknown>, context: ActionRunContext): Promise<ActionResult> {
207
- const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir);
209
+ const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir, context.signal);
208
210
  if (spawn.timedOut) {
209
211
  const timeout = optionalTimeoutOption(options);
210
212
  return {
@@ -229,7 +231,7 @@ export class ShellGuardRunner implements GuardRunner {
229
231
  constructor(private readonly processExecutor: ProcessExecutor) {}
230
232
 
231
233
  async evaluate(options: Record<string, unknown>, context: GuardContext): Promise<GuardEvaluationResult> {
232
- const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir);
234
+ const spawn = await spawnShellCommand(this.processExecutor, options, context.workdir, context.signal);
233
235
  return {
234
236
  passed: !spawn.timedOut && spawn.exitCode === 0,
235
237
  report: {
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { loadWorkflowDef, loadWorkflowDefFromText, validateWorkflowDef } from './config';
2
+ export { DagDriver, type DagDriverOptions } from './dag';
2
3
  export { FSMError, RunCollisionError, WorkflowResumeError, WorkflowValidationError } from './errors';
3
4
  export type { WorkflowEngineEvents } from './events';
4
5
  export {
@@ -33,6 +34,8 @@ export {
33
34
  } from './run-lifecycle';
34
35
  export {
35
36
  ActionDefSchema,
37
+ DagNodeDefSchema,
38
+ DagWorkflowDefSchema,
36
39
  GuardDefSchema,
37
40
  StateMachineWorkflowDefSchema,
38
41
  TransitionFlowWorkflowDefSchema,
@@ -50,6 +53,9 @@ export type {
50
53
  ActionRunContext,
51
54
  ActionRunner,
52
55
  ActionRunRecord,
56
+ DagNodeDef,
57
+ DagWorkflowDef,
58
+ DependencyPolicy,
53
59
  Env,
54
60
  FlowEdgeDef,
55
61
  FlowNodeDef,
@@ -3,7 +3,10 @@ import { RunCollisionError } from './errors';
3
3
  import { WORKFLOW_ENGINE_MIGRATIONS_SQL, WORKFLOW_ENGINE_SCHEMA_SQL } from './schema-sql';
4
4
  import type {
5
5
  ActionRedactor,
6
+ BranchStatus,
6
7
  ResumeOwnership,
8
+ Vars,
9
+ WorkflowBranchRecord,
7
10
  WorkflowPersistenceAdapter,
8
11
  WorkflowReseedResult,
9
12
  WorkflowRunRecord,
@@ -408,6 +411,85 @@ export class DbWorkflowPersistenceAdapter implements WorkflowPersistenceAdapter
408
411
  params.push(limit);
409
412
  return await this.db.queryAll<WorkflowRunRecord>(sql, ...params);
410
413
  }
414
+
415
+ /** Record the start of a branch execution in a parallel region. */
416
+ async saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string> {
417
+ await this.ensureSchema();
418
+ const id = crypto.randomUUID();
419
+ const now = Date.now();
420
+ await this.db.run(
421
+ `INSERT INTO workflow_branches (id, run_id, parallel_node, branch_id, status, node, started_at, created_at, updated_at)
422
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
423
+ ON CONFLICT(run_id, parallel_node, branch_id) DO UPDATE SET
424
+ status = 'running', node = excluded.node, started_at = excluded.started_at, completed_at = NULL, error = NULL, updated_at = excluded.updated_at`,
425
+ id,
426
+ runId,
427
+ parallelNode,
428
+ branchId,
429
+ 'running',
430
+ startNode,
431
+ new Date(now).toISOString(),
432
+ now,
433
+ now,
434
+ );
435
+ return id;
436
+ }
437
+
438
+ /** Finalize a branch execution with terminal status, duration, output variables, and optional error. */
439
+ async saveBranchFinalize(
440
+ runId: string,
441
+ branchId: string,
442
+ status: BranchStatus,
443
+ durationMs: number,
444
+ outputVars?: Vars,
445
+ error?: string,
446
+ ): Promise<void> {
447
+ await this.ensureSchema();
448
+ const now = Date.now();
449
+ await this.db.run(
450
+ `UPDATE workflow_branches
451
+ SET status = ?, duration_ms = ?, output_vars_json = ?, error = ?, completed_at = ?, updated_at = ?
452
+ WHERE run_id = ? AND branch_id = ?`,
453
+ status,
454
+ durationMs,
455
+ outputVars !== undefined ? JSON.stringify(outputVars) : null,
456
+ error ?? null,
457
+ new Date(now).toISOString(),
458
+ now,
459
+ runId,
460
+ branchId,
461
+ );
462
+ }
463
+
464
+ /** List all branch records for a run, optionally filtered by parallel node ID. */
465
+ async listRunBranches(runId: string, parallelNode?: string): Promise<readonly WorkflowBranchRecord[]> {
466
+ await this.ensureSchema();
467
+ if (parallelNode !== undefined) {
468
+ return await this.db.queryAll<WorkflowBranchRecord>(
469
+ 'SELECT * FROM workflow_branches WHERE run_id = ? AND parallel_node = ? ORDER BY created_at ASC',
470
+ runId,
471
+ parallelNode,
472
+ );
473
+ }
474
+ return await this.db.queryAll<WorkflowBranchRecord>(
475
+ 'SELECT * FROM workflow_branches WHERE run_id = ? ORDER BY created_at ASC',
476
+ runId,
477
+ );
478
+ }
479
+
480
+ /** Atomically transition a parallel region to its join node and commit merged variables. */
481
+ async commitJoin(
482
+ runId: string,
483
+ parallelNode: string,
484
+ joinNode: string,
485
+ mergedVars?: Vars,
486
+ phase?: { phase: string; status: WorkflowStatus },
487
+ ): Promise<void> {
488
+ await this.ensureSchema();
489
+ const data: Record<string, unknown> = {};
490
+ if (mergedVars !== undefined) data.effectiveVars = mergedVars;
491
+ await this.commitTransition(runId, parallelNode, joinNode, '__join__', joinNode, data, phase);
492
+ }
411
493
  }
412
494
 
413
495
  /** In-memory persistence adapter for tests and embedding. */
@@ -634,4 +716,77 @@ export class MemoryWorkflowPersistenceAdapter implements WorkflowPersistenceAdap
634
716
  runs.reverse();
635
717
  return runs.slice(0, options?.limit ?? 100);
636
718
  }
719
+
720
+ readonly branches = new Map<string, WorkflowBranchRecord>();
721
+
722
+ /** Record the start of a branch execution in a parallel region. */
723
+ async saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string> {
724
+ const id = crypto.randomUUID();
725
+ const now = Date.now();
726
+ const key = `${runId}:${parallelNode}:${branchId}`;
727
+ const record: WorkflowBranchRecord = {
728
+ id,
729
+ run_id: runId,
730
+ parallel_node: parallelNode,
731
+ branch_id: branchId,
732
+ status: 'running',
733
+ node: startNode,
734
+ started_at: new Date(now).toISOString(),
735
+ completed_at: null,
736
+ duration_ms: null,
737
+ output_vars_json: null,
738
+ error: null,
739
+ };
740
+ this.branches.set(key, record);
741
+ return id;
742
+ }
743
+
744
+ /** Finalize a branch execution with terminal status, duration, output variables, and optional error. */
745
+ async saveBranchFinalize(
746
+ runId: string,
747
+ branchId: string,
748
+ status: BranchStatus,
749
+ durationMs: number,
750
+ outputVars?: Vars,
751
+ error?: string,
752
+ ): Promise<void> {
753
+ const now = Date.now();
754
+ for (const [key, b] of this.branches.entries()) {
755
+ if (b.run_id === runId && b.branch_id === branchId) {
756
+ this.branches.set(key, {
757
+ ...b,
758
+ status,
759
+ duration_ms: durationMs,
760
+ completed_at: new Date(now).toISOString(),
761
+ output_vars_json: outputVars !== undefined ? JSON.stringify(outputVars) : null,
762
+ error: error ?? null,
763
+ });
764
+ break;
765
+ }
766
+ }
767
+ }
768
+
769
+ /** List all branch records for a run, optionally filtered by parallel node ID. */
770
+ async listRunBranches(runId: string, parallelNode?: string): Promise<readonly WorkflowBranchRecord[]> {
771
+ const result: WorkflowBranchRecord[] = [];
772
+ for (const b of this.branches.values()) {
773
+ if (b.run_id === runId && (parallelNode === undefined || b.parallel_node === parallelNode)) {
774
+ result.push(b);
775
+ }
776
+ }
777
+ return result;
778
+ }
779
+
780
+ /** Atomically transition a parallel region to its join node and commit merged variables. */
781
+ async commitJoin(
782
+ runId: string,
783
+ parallelNode: string,
784
+ joinNode: string,
785
+ mergedVars?: Vars,
786
+ phase?: { phase: string; status: WorkflowStatus },
787
+ ): Promise<void> {
788
+ const data: Record<string, unknown> = {};
789
+ if (mergedVars !== undefined) data.effectiveVars = mergedVars;
790
+ await this.commitTransition(runId, parallelNode, joinNode, '__join__', joinNode, data, phase);
791
+ }
637
792
  }
@@ -158,13 +158,16 @@ export class RunLifecycle {
158
158
  record = await deps.persistence.createOrAttachRun(proposed);
159
159
  if (record.owner_attempt !== proposed.owner_attempt) {
160
160
  const snapshot = await deps.persistence.loadLatestStateSnapshot(record.id);
161
+ const recordMode = record.mode;
161
162
  return {
162
163
  runId: record.id,
163
164
  workflowName: record.workflow_name,
164
165
  mode:
165
- record.mode === 'transition-flow'
166
+ recordMode === 'transition-flow'
166
167
  ? ('transition-flow' as const)
167
- : ('state-machine' as const),
168
+ : recordMode === 'dag'
169
+ ? ('dag' as const)
170
+ : ('state-machine' as const),
168
171
  status: record.status,
169
172
  finalState: snapshot?.state ?? '',
170
173
  transitionsTaken: snapshotTransitions(snapshot?.data),
@@ -483,6 +486,76 @@ export class RunLifecycle {
483
486
  });
484
487
  }
485
488
 
489
+ /** Emit when an execution branch in a parallel region starts. */
490
+ branchStarted(parallelNode: string, branchId: string, node: string): void {
491
+ addSpanEvent('workflow.branch.started', {
492
+ runId: this.runId,
493
+ parallelNode,
494
+ branchId,
495
+ node,
496
+ });
497
+ void this.events?.emit('workflow.branch.started', {
498
+ runId: this.runId,
499
+ parallelNode,
500
+ branchId,
501
+ node,
502
+ severity: 'info',
503
+ });
504
+ }
505
+
506
+ /** Emit when an execution branch in a parallel region finishes. */
507
+ branchDone(parallelNode: string, branchId: string, durationMs: number, ok: boolean): void {
508
+ addSpanEvent('workflow.branch.done', {
509
+ runId: this.runId,
510
+ parallelNode,
511
+ branchId,
512
+ durationMs,
513
+ ok,
514
+ });
515
+ void this.events?.emit('workflow.branch.done', {
516
+ runId: this.runId,
517
+ parallelNode,
518
+ branchId,
519
+ durationMs,
520
+ ok,
521
+ severity: ok ? 'info' : 'error',
522
+ });
523
+ }
524
+
525
+ /** Emit when an execution branch in a parallel region fails. */
526
+ branchFailed(parallelNode: string, branchId: string, error?: string): void {
527
+ addSpanEvent('workflow.branch.failed', {
528
+ runId: this.runId,
529
+ parallelNode,
530
+ branchId,
531
+ ...(error !== undefined ? { error } : {}),
532
+ });
533
+ void this.events?.emit('workflow.branch.failed', {
534
+ runId: this.runId,
535
+ parallelNode,
536
+ branchId,
537
+ error,
538
+ severity: 'error',
539
+ });
540
+ }
541
+
542
+ /** Emit when an execution branch in a parallel region pauses. */
543
+ branchPaused(parallelNode: string, branchId: string, node: string): void {
544
+ addSpanEvent('workflow.branch.paused', {
545
+ runId: this.runId,
546
+ parallelNode,
547
+ branchId,
548
+ node,
549
+ });
550
+ void this.events?.emit('workflow.branch.paused', {
551
+ runId: this.runId,
552
+ parallelNode,
553
+ branchId,
554
+ node,
555
+ severity: 'warning',
556
+ });
557
+ }
558
+
486
559
  private result(
487
560
  status: WorkflowStatus,
488
561
  finalState: string,
package/src/schema-sql.ts CHANGED
@@ -70,6 +70,26 @@ CREATE TABLE IF NOT EXISTS action_runs (
70
70
  updated_at INTEGER NOT NULL DEFAULT 0,
71
71
  FOREIGN KEY (run_id) REFERENCES runs(id)
72
72
  );
73
+
74
+ CREATE TABLE IF NOT EXISTS workflow_branches (
75
+ id TEXT PRIMARY KEY,
76
+ run_id TEXT NOT NULL,
77
+ parallel_node TEXT NOT NULL,
78
+ branch_id TEXT NOT NULL,
79
+ status TEXT NOT NULL,
80
+ node TEXT NOT NULL,
81
+ started_at TEXT NOT NULL,
82
+ completed_at TEXT,
83
+ duration_ms INTEGER,
84
+ output_vars_json TEXT,
85
+ error TEXT,
86
+ created_at INTEGER NOT NULL DEFAULT 0,
87
+ updated_at INTEGER NOT NULL DEFAULT 0,
88
+ FOREIGN KEY (run_id) REFERENCES runs(id)
89
+ );
90
+
91
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_workflow_branches_run_branch
92
+ ON workflow_branches (run_id, parallel_node, branch_id);
73
93
  `.trim();
74
94
 
75
95
  /** Guarded ALTERs adding the 0.5.0 ownership/interruption columns for databases created before them. */
package/src/schema.ts CHANGED
@@ -116,6 +116,72 @@ export const StateMachineWorkflowDefSchema = z
116
116
  })
117
117
  .strict();
118
118
 
119
+ /** Zod schema for structured parallel branch definitions. */
120
+ export const FlowParallelBranchDefSchema = z
121
+ .object({
122
+ id: z.string().min(1),
123
+ startNode: z.string().min(1),
124
+ description: z.string().optional(),
125
+ })
126
+ .strict();
127
+
128
+ /** Zod schema for transition-flow node definitions. */
129
+ export const FlowNodeDefSchema = z
130
+ .object({
131
+ id: z.string().min(1),
132
+ description: z.string().optional(),
133
+ type: z.enum(['action', 'gate', 'parallel', 'decision']).optional(),
134
+ action: ActionDefSchema.optional(),
135
+ /** When true, the engine pauses the run at this node instead of auto-advancing. */
136
+ pause: z.boolean().optional(),
137
+ /** Author declaration that re-running this node's action after an interruption is safe. */
138
+ resumeRerun: z.boolean().optional(),
139
+ /** Declared branches for parallel fork nodes (type: 'parallel'). */
140
+ branches: z.array(FlowParallelBranchDefSchema).optional(),
141
+ /** Target join node ID where branches converge for parallel fork nodes. */
142
+ join: z.string().min(1).optional(),
143
+ /** Join synchronization policy for parallel nodes. Defaults to 'all'. */
144
+ joinPolicy: z.enum(['all']).optional(),
145
+ /** Failure handling policy across parallel branches. Defaults to 'collect'. */
146
+ failurePolicy: z.enum(['collect', 'fail-fast']).optional(),
147
+ /** Maximum number of branches executed concurrently. Defaults to 4. */
148
+ concurrencyLimit: z.number().int().positive().optional(),
149
+ })
150
+ .strict()
151
+ .superRefine((node, ctx) => {
152
+ if (node.type === 'parallel') {
153
+ if (!node.branches || node.branches.length === 0) {
154
+ ctx.addIssue({
155
+ code: 'custom',
156
+ message: 'Parallel node must declare non-empty branches array',
157
+ path: ['branches'],
158
+ });
159
+ }
160
+ if (!node.join) {
161
+ ctx.addIssue({
162
+ code: 'custom',
163
+ message: 'Parallel node must declare join target node ID',
164
+ path: ['join'],
165
+ });
166
+ }
167
+ } else {
168
+ if (node.branches !== undefined) {
169
+ ctx.addIssue({
170
+ code: 'custom',
171
+ message: `Node "${node.id}" of type "${node.type ?? 'action'}" must not declare branches`,
172
+ path: ['branches'],
173
+ });
174
+ }
175
+ if (node.join !== undefined) {
176
+ ctx.addIssue({
177
+ code: 'custom',
178
+ message: `Node "${node.id}" of type "${node.type ?? 'action'}" must not declare join`,
179
+ path: ['join'],
180
+ });
181
+ }
182
+ }
183
+ });
184
+
119
185
  /** Zod schema for transition-flow workflow definitions. */
120
186
  export const TransitionFlowWorkflowDefSchema = z
121
187
  .object({
@@ -131,20 +197,7 @@ export const TransitionFlowWorkflowDefSchema = z
131
197
  defaultOnError: z.enum(['fail', 'continue']).optional(),
132
198
  vars: VarsSchema.optional(),
133
199
  env: EnvSchema.optional(),
134
- nodes: z.array(
135
- z
136
- .object({
137
- id: z.string().min(1),
138
- description: z.string().optional(),
139
- type: z.enum(['action', 'gate', 'parallel', 'decision']).optional(),
140
- action: ActionDefSchema.optional(),
141
- /** When true, the engine pauses the run at this node instead of auto-advancing. */
142
- pause: z.boolean().optional(),
143
- /** Author declaration that re-running this node's action after an interruption is safe. */
144
- resumeRerun: z.boolean().optional(),
145
- })
146
- .strict(),
147
- ),
200
+ nodes: z.array(FlowNodeDefSchema),
148
201
  edges: z.array(
149
202
  z
150
203
  .object({
@@ -159,5 +212,40 @@ export const TransitionFlowWorkflowDefSchema = z
159
212
  })
160
213
  .strict();
161
214
 
162
- /** Zod schema for either supported workflow definition shape. */
163
- export const WorkflowDefSchema = z.union([StateMachineWorkflowDefSchema, TransitionFlowWorkflowDefSchema]);
215
+ /** Zod schema for static dependency DAG node definitions. */
216
+ export const DagNodeDefSchema = z
217
+ .object({
218
+ id: z.string().min(1),
219
+ description: z.string().optional(),
220
+ action: ActionDefSchema.optional(),
221
+ dependsOn: z.array(z.string().min(1)).optional(),
222
+ dependencyPolicy: z.enum(['all', 'any']).optional(),
223
+ condition: GuardDefSchema.optional(),
224
+ pause: z.boolean().optional(),
225
+ resumeRerun: z.boolean().optional(),
226
+ })
227
+ .strict();
228
+
229
+ /** Zod schema for static dependency DAG workflow definitions. */
230
+ export const DagWorkflowDefSchema = z
231
+ .object({
232
+ $schema: z.string().optional(),
233
+ kind: z.literal('dag'),
234
+ name: z.string().min(1),
235
+ version: z.string().optional(),
236
+ description: z.string().optional(),
237
+ iterationBound: z.number().int().positive().optional(),
238
+ defaultOnError: z.enum(['fail', 'continue']).optional(),
239
+ vars: VarsSchema.optional(),
240
+ env: EnvSchema.optional(),
241
+ nodes: z.array(DagNodeDefSchema),
242
+ extensions: WorkflowExtensionsSchema.optional(),
243
+ })
244
+ .strict();
245
+
246
+ /** Zod schema for supported workflow definition shapes. */
247
+ export const WorkflowDefSchema = z.union([
248
+ StateMachineWorkflowDefSchema,
249
+ TransitionFlowWorkflowDefSchema,
250
+ DagWorkflowDefSchema,
251
+ ]);
package/src/service.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type BusLifecycleEvents, EventBus } from '@gobing-ai/ts-infra';
2
2
  import { loadWorkflowDef } from './config';
3
+ import { DagDriver } from './dag';
3
4
  import { FSMError, WorkflowResumeError } from './errors';
4
5
  import type { WorkflowEngineEvents } from './events';
5
6
  import type { WorkflowEngineHost } from './host';
@@ -66,10 +67,19 @@ export class WorkflowService {
66
67
  events,
67
68
  });
68
69
  }
69
- return await new StateMachineDriver({ host: this.host, persistence: this.persistence }).run(workflow, {
70
- ...options,
71
- events,
72
- });
70
+ if (workflow.kind === 'dag') {
71
+ return await new DagDriver({ host: this.host, persistence: this.persistence }).run(workflow, {
72
+ ...options,
73
+ events,
74
+ });
75
+ }
76
+ return await new StateMachineDriver({ host: this.host, persistence: this.persistence }).run(
77
+ workflow as StateMachineWorkflowDef,
78
+ {
79
+ ...options,
80
+ events,
81
+ },
82
+ );
73
83
  }
74
84
 
75
85
  /** Load and run a workflow file. */
@@ -131,10 +141,11 @@ export class WorkflowService {
131
141
 
132
142
  /** Reject a reseed target the workflow definition does not allow (state-machine states only). */
133
143
  private assertReseedTargetDeclared(workflow: WorkflowDef, runId: string, newState: string): void {
134
- if (workflow.kind === 'transition-flow') {
144
+ if (workflow.kind !== 'state-machine' && workflow.kind !== undefined) {
135
145
  throw new FSMError('reseedRun only supports state-machine workflows');
136
146
  }
137
- if (!workflow.states.some((state) => state.id === newState)) {
147
+ const sm = workflow as StateMachineWorkflowDef;
148
+ if (!sm.states.some((state) => state.id === newState)) {
138
149
  throw new FSMError(`Cannot reseed run "${runId}" to undeclared state "${newState}"`);
139
150
  }
140
151
  }
@@ -214,6 +225,12 @@ export class WorkflowService {
214
225
  persistence: this.persistence,
215
226
  }).resume(workflow, runId, currentState, extKey, mergedOptions);
216
227
  }
228
+ if (workflow.kind === 'dag') {
229
+ return await new DagDriver({
230
+ host: this.host,
231
+ persistence: this.persistence,
232
+ }).resume(workflow, runId, extKey, mergedOptions);
233
+ }
217
234
  return await new StateMachineDriver({
218
235
  host: this.host,
219
236
  persistence: this.persistence,
@@ -248,7 +265,7 @@ export class WorkflowService {
248
265
  ): void {
249
266
  if (resumeMode !== 'rerun-enter') return;
250
267
  const node =
251
- workflow.kind === 'transition-flow'
268
+ workflow.kind === 'transition-flow' || workflow.kind === 'dag'
252
269
  ? workflow.nodes.find((candidate) => candidate.id === currentState)
253
270
  : (workflow as StateMachineWorkflowDef).states.find((candidate) => candidate.id === currentState);
254
271
  if (node !== undefined && node.resumeRerun !== true) {