@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
@@ -4,7 +4,10 @@ import type { WorkflowEngineHost } from './host';
4
4
  import { allowedEnv, RunLifecycle, snapshotActionResult, snapshotTransitions } from './run-lifecycle';
5
5
  import type {
6
6
  ActionResult,
7
+ FlowNodeDef,
8
+ FlowParallelNodeDef,
7
9
  TransitionFlowWorkflowDef,
10
+ Vars,
8
11
  WorkflowPersistenceAdapter,
9
12
  WorkflowRunOptions,
10
13
  WorkflowRunResult,
@@ -120,6 +123,7 @@ export class TransitionFlowDriver {
120
123
  env,
121
124
  options,
122
125
  defaultOnError,
126
+ signal: options.signal,
123
127
  });
124
128
  lastActionResult = step.result;
125
129
  if (step.result?.setVars) vars = mergeSetVars(vars, step.result.setVars);
@@ -137,6 +141,250 @@ export class TransitionFlowDriver {
137
141
  }
138
142
  }
139
143
 
144
+ // Structured parallel fork-join execution
145
+ if (current.type === 'parallel') {
146
+ if (!current.branches || !current.join) {
147
+ throw new FSMError(`Parallel node "${current.id}" must declare branches and join target`);
148
+ }
149
+ const parallelNode = current as FlowParallelNodeDef;
150
+ const concurrency = parallelNode.concurrencyLimit ?? 4;
151
+
152
+ if (!options.dryRun) {
153
+ const existingBranches = await this.options.persistence.listRunBranches(runId, parallelNode.id);
154
+ const branchControllers = new Map<string, AbortController>();
155
+ for (const b of parallelNode.branches) {
156
+ const ctrl = new AbortController();
157
+ branchControllers.set(b.id, ctrl);
158
+ if (options.signal) {
159
+ if (options.signal.aborted) ctrl.abort();
160
+ else options.signal.addEventListener('abort', () => ctrl.abort(), { once: true });
161
+ }
162
+ }
163
+
164
+ const abortSiblings = (failingBranchId: string) => {
165
+ if (parallelNode.failurePolicy === 'fail-fast') {
166
+ for (const [id, ctrl] of branchControllers.entries()) {
167
+ if (id !== failingBranchId) ctrl.abort();
168
+ }
169
+ }
170
+ };
171
+
172
+ const branchResults = await runWithConcurrencyLimit(
173
+ parallelNode.branches,
174
+ concurrency,
175
+ async (branch) => {
176
+ const existing = existingBranches.find((b) => b.branch_id === branch.id);
177
+ if (existing?.status === 'done') {
178
+ let restoredVars: Vars = {};
179
+ if (existing.output_vars_json) {
180
+ try {
181
+ restoredVars = JSON.parse(existing.output_vars_json);
182
+ } catch {
183
+ restoredVars = {};
184
+ }
185
+ }
186
+ return { ok: true, branchId: branch.id, setVars: restoredVars };
187
+ }
188
+
189
+ const branchCtrl = branchControllers.get(branch.id) ?? new AbortController();
190
+ const branchStartMs = Date.now();
191
+ let branchCurrent: FlowNodeDef | undefined;
192
+ let skipEnter = false;
193
+
194
+ if (existing?.status === 'paused') {
195
+ branchCurrent = nodes.get(existing.node) ?? nodes.get(branch.startNode);
196
+ skipEnter = (resumeMode ?? options.resumeMode ?? 'skip-enter') === 'skip-enter';
197
+ } else {
198
+ branchCurrent = nodes.get(branch.startNode);
199
+ await this.options.persistence.saveBranchStart(
200
+ runId,
201
+ parallelNode.id,
202
+ branch.id,
203
+ branch.startNode,
204
+ );
205
+ }
206
+
207
+ lifecycle.branchStarted(parallelNode.id, branch.id, branchCurrent?.id ?? branch.startNode);
208
+
209
+ let branchVars = { ...vars };
210
+ let branchSetVars: Vars = {};
211
+
212
+ while (branchCurrent && branchCurrent.id !== parallelNode.join) {
213
+ if (branchCtrl.signal.aborted) {
214
+ lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
215
+ await this.options.persistence.saveBranchFinalize(
216
+ runId,
217
+ branch.id,
218
+ 'cancelled',
219
+ Date.now() - branchStartMs,
220
+ undefined,
221
+ 'cancelled',
222
+ );
223
+ return { ok: false, branchId: branch.id, error: 'cancelled' };
224
+ }
225
+
226
+ if (skipEnter) {
227
+ skipEnter = false;
228
+ } else {
229
+ if (branchCurrent.action !== undefined) {
230
+ const step = await runActionStep(branchCurrent.action, branchVars, {
231
+ host: this.options.host,
232
+ persistence: this.options.persistence,
233
+ lifecycle,
234
+ workflowName: workflow.name,
235
+ stateOrNodeId: branchCurrent.id,
236
+ runId,
237
+ mode: 'transition-flow',
238
+ transitionsTaken,
239
+ env,
240
+ options,
241
+ defaultOnError,
242
+ signal: branchCtrl.signal,
243
+ });
244
+ if (step.result?.setVars) {
245
+ branchVars = mergeSetVars(branchVars, step.result.setVars);
246
+ branchSetVars = mergeSetVars(branchSetVars, step.result.setVars);
247
+ }
248
+ if (branchCtrl.signal.aborted) {
249
+ lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
250
+ await this.options.persistence.saveBranchFinalize(
251
+ runId,
252
+ branch.id,
253
+ 'cancelled',
254
+ Date.now() - branchStartMs,
255
+ undefined,
256
+ 'cancelled',
257
+ );
258
+ return { ok: false, branchId: branch.id, error: 'cancelled' };
259
+ }
260
+ if (step.outcome === 'fail') {
261
+ abortSiblings(branch.id);
262
+ const err = step.result?.error ?? 'action-failed';
263
+ lifecycle.branchFailed(parallelNode.id, branch.id, err);
264
+ await this.options.persistence.saveBranchFinalize(
265
+ runId,
266
+ branch.id,
267
+ 'failed',
268
+ Date.now() - branchStartMs,
269
+ undefined,
270
+ err,
271
+ );
272
+ return {
273
+ ok: false,
274
+ branchId: branch.id,
275
+ error: err,
276
+ };
277
+ }
278
+ if (step.outcome === 'terminal') {
279
+ break;
280
+ }
281
+ }
282
+
283
+ if (branchCurrent.pause === true) {
284
+ lifecycle.branchPaused(parallelNode.id, branch.id, branchCurrent.id);
285
+ await this.options.persistence.saveBranchFinalize(
286
+ runId,
287
+ branch.id,
288
+ 'paused',
289
+ Date.now() - branchStartMs,
290
+ branchSetVars,
291
+ );
292
+ return {
293
+ ok: true,
294
+ branchId: branch.id,
295
+ paused: true,
296
+ setVars: branchSetVars,
297
+ };
298
+ }
299
+ }
300
+
301
+ const outbound = workflow.edges.filter((e) => e.from === branchCurrent?.id);
302
+ if (outbound.length === 0 || terminal.has(branchCurrent.id)) {
303
+ break;
304
+ }
305
+ const edge = await firstPassingEdge(
306
+ outbound,
307
+ this.options.host,
308
+ {
309
+ runId,
310
+ current: branchCurrent.id,
311
+ vars: branchVars,
312
+ env,
313
+ workdir: options.workdir,
314
+ signal: branchCtrl.signal,
315
+ },
316
+ lifecycle,
317
+ );
318
+ if (edge === undefined) {
319
+ abortSiblings(branch.id);
320
+ lifecycle.branchFailed(parallelNode.id, branch.id, 'no-passing-edge');
321
+ await this.options.persistence.saveBranchFinalize(
322
+ runId,
323
+ branch.id,
324
+ 'failed',
325
+ Date.now() - branchStartMs,
326
+ undefined,
327
+ 'no-passing-edge',
328
+ );
329
+ return { ok: false, branchId: branch.id, error: 'no-passing-edge' };
330
+ }
331
+ branchCurrent = nodes.get(edge.to);
332
+ }
333
+
334
+ if (branchCtrl.signal.aborted) {
335
+ lifecycle.branchFailed(parallelNode.id, branch.id, 'cancelled');
336
+ await this.options.persistence.saveBranchFinalize(
337
+ runId,
338
+ branch.id,
339
+ 'cancelled',
340
+ Date.now() - branchStartMs,
341
+ undefined,
342
+ 'cancelled',
343
+ );
344
+ return { ok: false, branchId: branch.id, error: 'cancelled' };
345
+ }
346
+
347
+ lifecycle.branchDone(parallelNode.id, branch.id, Date.now() - branchStartMs, true);
348
+ await this.options.persistence.saveBranchFinalize(
349
+ runId,
350
+ branch.id,
351
+ 'done',
352
+ Date.now() - branchStartMs,
353
+ branchSetVars,
354
+ );
355
+ return { ok: true, branchId: branch.id, setVars: branchSetVars };
356
+ },
357
+ );
358
+
359
+ const failed = branchResults.find((r) => !r.ok);
360
+ if (failed) {
361
+ return await lifecycle.fail(current.id, transitionsTaken, failed.error ?? 'branch-failed');
362
+ }
363
+
364
+ const anyPaused = branchResults.some((r) => 'paused' in r && r.paused === true);
365
+ for (const res of branchResults) {
366
+ if (res.setVars) vars = mergeSetVars(vars, res.setVars);
367
+ }
368
+ if (anyPaused) {
369
+ return await lifecycle.pause(current.id, transitionsTaken, vars);
370
+ }
371
+ }
372
+
373
+ transitionsTaken += 1;
374
+ await this.options.persistence.commitJoin(runId, current.id, parallelNode.join, vars, {
375
+ phase: parallelNode.join,
376
+ status: 'running',
377
+ });
378
+
379
+ const joinNode = nodes.get(parallelNode.join);
380
+ if (joinNode === undefined) {
381
+ throw new FSMError(`Join target "${parallelNode.join}" is not declared`);
382
+ }
383
+ current = joinNode;
384
+ persistedViaHop = true;
385
+ continue;
386
+ }
387
+
140
388
  // 3. Stop when the node is terminal or no outgoing edge exists.
141
389
  const outbound = workflow.edges.filter((edge) => edge.from === current?.id);
142
390
  if (terminal.has(current.id) || outbound.length === 0) {
@@ -155,6 +403,7 @@ export class TransitionFlowDriver {
155
403
  lastActionResult,
156
404
  // Shell conditions must share the run workdir with actions (relative paths).
157
405
  workdir: options.workdir,
406
+ signal: options.signal,
158
407
  },
159
408
  lifecycle,
160
409
  );
@@ -216,3 +465,25 @@ async function firstPassingEdge(
216
465
  }
217
466
  return undefined;
218
467
  }
468
+
469
+ /** Execute tasks concurrently with a maximum concurrency limit. */
470
+ async function runWithConcurrencyLimit<T, R>(
471
+ items: readonly T[],
472
+ limit: number,
473
+ fn: (item: T) => Promise<R>,
474
+ ): Promise<R[]> {
475
+ const results: R[] = new Array(items.length);
476
+ let nextIndex = 0;
477
+ const workerCount = Math.max(1, Math.min(limit, items.length));
478
+ const workers = new Array(workerCount).fill(null).map(async () => {
479
+ while (nextIndex < items.length) {
480
+ const index = nextIndex++;
481
+ const item = items[index];
482
+ if (item !== undefined) {
483
+ results[index] = await fn(item);
484
+ }
485
+ }
486
+ });
487
+ await Promise.all(workers);
488
+ return results;
489
+ }
package/src/types.ts CHANGED
@@ -117,6 +117,19 @@ export interface StateMachineWorkflowDef {
117
117
  readonly extensions?: WorkflowExtensions;
118
118
  }
119
119
 
120
+ /** Join synchronization policy for parallel nodes. */
121
+ export type JoinPolicy = 'all';
122
+
123
+ /** Failure handling policy across parallel branches. */
124
+ export type FailurePolicy = 'collect' | 'fail-fast';
125
+
126
+ /** One branch in a structured parallel fork node. */
127
+ export interface FlowParallelBranchDef {
128
+ readonly id: string;
129
+ readonly startNode: string;
130
+ readonly description?: string;
131
+ }
132
+
120
133
  /** Transition-flow node definition. */
121
134
  export interface FlowNodeDef {
122
135
  readonly id: string;
@@ -128,6 +141,26 @@ export interface FlowNodeDef {
128
141
  readonly pause?: boolean;
129
142
  /** Author declaration that this node's action is safe to re-run after an interruption. See StateDef.resumeRerun. */
130
143
  readonly resumeRerun?: boolean;
144
+ /** Declared branches for parallel fork nodes (type: 'parallel'). */
145
+ readonly branches?: readonly FlowParallelBranchDef[];
146
+ /** Target join node ID where branches converge for parallel fork nodes. */
147
+ readonly join?: string;
148
+ /** Join synchronization policy for parallel nodes. Defaults to 'all'. */
149
+ readonly joinPolicy?: JoinPolicy;
150
+ /** Failure handling policy across parallel branches. Defaults to 'collect'. */
151
+ readonly failurePolicy?: FailurePolicy;
152
+ /** Maximum number of branches executed concurrently. Defaults to 4. */
153
+ readonly concurrencyLimit?: number;
154
+ }
155
+
156
+ /** Transition-flow parallel fork node definition. */
157
+ export interface FlowParallelNodeDef extends FlowNodeDef {
158
+ readonly type: 'parallel';
159
+ readonly branches: readonly FlowParallelBranchDef[];
160
+ readonly join: string;
161
+ readonly joinPolicy?: JoinPolicy;
162
+ readonly failurePolicy?: FailurePolicy;
163
+ readonly concurrencyLimit?: number;
131
164
  }
132
165
 
133
166
  /** Transition-flow edge definition. */
@@ -159,8 +192,37 @@ export interface TransitionFlowWorkflowDef {
159
192
  readonly extensions?: WorkflowExtensions;
160
193
  }
161
194
 
195
+ /** Dependency synchronization policy for DAG nodes. */
196
+ export type DependencyPolicy = 'all' | 'any';
197
+
198
+ /** Single node in a static dependency DAG workflow. */
199
+ export interface DagNodeDef {
200
+ readonly id: string;
201
+ readonly description?: string;
202
+ readonly action?: ActionDef;
203
+ readonly dependsOn?: readonly string[];
204
+ readonly dependencyPolicy?: DependencyPolicy;
205
+ readonly condition?: GuardDef;
206
+ readonly pause?: boolean;
207
+ readonly resumeRerun?: boolean;
208
+ }
209
+
210
+ /** Static dependency DAG workflow definition. */
211
+ export interface DagWorkflowDef {
212
+ readonly kind: 'dag';
213
+ readonly name: string;
214
+ readonly version?: string;
215
+ readonly description?: string;
216
+ readonly iterationBound?: number;
217
+ readonly defaultOnError?: OnErrorPolicy;
218
+ readonly vars?: Vars;
219
+ readonly env?: Env;
220
+ readonly nodes: readonly DagNodeDef[];
221
+ readonly extensions?: WorkflowExtensions;
222
+ }
223
+
162
224
  /** Discriminated workflow definition union. */
163
- export type WorkflowDef = StateMachineWorkflowDef | TransitionFlowWorkflowDef;
225
+ export type WorkflowDef = StateMachineWorkflowDef | TransitionFlowWorkflowDef | DagWorkflowDef;
164
226
 
165
227
  /** Action execution context passed to action runners. */
166
228
  export interface ActionRunContext {
@@ -174,6 +236,8 @@ export interface ActionRunContext {
174
236
  readonly metadata?: Record<string, unknown>;
175
237
  /** Optional event bus for in-process run observability. Action runners can emit workflow events through this. */
176
238
  readonly events?: EventBus<WorkflowEngineEvents>;
239
+ /** Optional cancellation signal for cooperative and process-group termination (task 0096). */
240
+ readonly signal?: AbortSignal;
177
241
  }
178
242
 
179
243
  /** Result of a single action execution. */
@@ -201,6 +265,8 @@ export interface GuardContext {
201
265
  /** Run env (allowed-env filtered) — guards resolve `${env.X}` identically to actions (task 0087 R5). */
202
266
  readonly env?: Record<string, string>;
203
267
  readonly lastActionResult?: ActionResult;
268
+ /** Optional cancellation signal for cooperative guard evaluation (task 0096). */
269
+ readonly signal?: AbortSignal;
204
270
  }
205
271
 
206
272
  /** Rich guard evaluation result. Boolean guard runners remain supported for compatibility. */
@@ -224,6 +290,8 @@ export interface WorkflowRunOptions {
224
290
  readonly metadata?: Record<string, unknown>;
225
291
  /** Optional event bus for structured run observability. */
226
292
  readonly events?: EventBus<WorkflowEngineEvents>;
293
+ /** Optional cancellation signal for aborting in-flight child processes and actions (task 0096). */
294
+ readonly signal?: AbortSignal;
227
295
  /** Run-level error policy override. Lowest precedence; action-level wins. */
228
296
  readonly onError?: OnErrorPolicy;
229
297
  /**
@@ -256,7 +324,7 @@ export interface WorkflowRunOptions {
256
324
  export interface WorkflowRunResult {
257
325
  readonly runId: string;
258
326
  readonly workflowName: string;
259
- readonly mode: 'state-machine' | 'transition-flow';
327
+ readonly mode: 'state-machine' | 'transition-flow' | 'dag';
260
328
  readonly status: WorkflowStatus;
261
329
  readonly finalState: string;
262
330
  readonly transitionsTaken: number;
@@ -319,6 +387,24 @@ export interface TransitionDenied {
319
387
  /** Discriminated union result for external transition requests. */
320
388
  export type TransitionRequestResult = TransitionAllowed | TransitionDenied;
321
389
 
390
+ /** Execution status of an individual branch in a parallel region. */
391
+ export type BranchStatus = 'pending' | 'running' | 'done' | 'failed' | 'cancelled' | 'paused';
392
+
393
+ /** Persisted branch execution record. */
394
+ export interface WorkflowBranchRecord {
395
+ readonly id: string;
396
+ readonly run_id: string;
397
+ readonly parallel_node: string;
398
+ readonly branch_id: string;
399
+ readonly status: BranchStatus;
400
+ readonly node: string;
401
+ readonly started_at: string;
402
+ readonly completed_at: string | null;
403
+ readonly duration_ms: number | null;
404
+ readonly output_vars_json: string | null;
405
+ readonly error: string | null;
406
+ }
407
+
322
408
  /** Persisted action run record — one row per action executed in a workflow run. */
323
409
  export interface ActionRunRecord {
324
410
  readonly id: string;
@@ -436,4 +522,25 @@ export interface WorkflowPersistenceAdapter {
436
522
  * updated record, or undefined when the run is missing or not running.
437
523
  */
438
524
  interruptRun(runId: string, reason: string): Promise<WorkflowRunRecord | undefined>;
525
+ /** Record the start of a branch execution in a parallel region. */
526
+ saveBranchStart(runId: string, parallelNode: string, branchId: string, startNode: string): Promise<string>;
527
+ /** Finalize a branch execution with terminal status, duration, output variables, and optional error. */
528
+ saveBranchFinalize(
529
+ runId: string,
530
+ branchId: string,
531
+ status: BranchStatus,
532
+ durationMs: number,
533
+ outputVars?: Vars,
534
+ error?: string,
535
+ ): Promise<void>;
536
+ /** List all branch records for a run, optionally filtered by parallel node ID. */
537
+ listRunBranches(runId: string, parallelNode?: string): Promise<readonly WorkflowBranchRecord[]>;
538
+ /** Atomically transition a parallel region to its join node and commit merged variables. */
539
+ commitJoin(
540
+ runId: string,
541
+ parallelNode: string,
542
+ joinNode: string,
543
+ mergedVars?: Vars,
544
+ phase?: { phase: string; status: WorkflowStatus },
545
+ ): Promise<void>;
439
546
  }