@gobing-ai/ts-dual-workflow-engine 0.5.14 → 0.5.16
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.
- package/README.md +53 -22
- package/dist/action-step.d.ts +1 -0
- package/dist/action-step.d.ts.map +1 -1
- package/dist/action-step.js +1 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +137 -3
- package/dist/dag.d.ts +25 -0
- package/dist/dag.d.ts.map +1 -0
- package/dist/dag.js +215 -0
- package/dist/events.d.ts +33 -0
- package/dist/events.d.ts.map +1 -1
- package/dist/host.d.ts.map +1 -1
- package/dist/host.js +4 -3
- package/dist/index.d.ts +3 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -1
- package/dist/persistence.d.ts +24 -1
- package/dist/persistence.d.ts.map +1 -1
- package/dist/persistence.js +91 -0
- package/dist/run-lifecycle.d.ts +8 -0
- package/dist/run-lifecycle.d.ts.map +1 -1
- package/dist/run-lifecycle.js +71 -2
- package/dist/schema-sql.d.ts.map +1 -1
- package/dist/schema-sql.js +20 -0
- package/dist/schema.d.ts +185 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +105 -14
- package/dist/service.d.ts +8 -0
- package/dist/service.d.ts.map +1 -1
- package/dist/service.js +55 -3
- package/dist/state-machine.d.ts.map +1 -1
- package/dist/state-machine.js +8 -4
- package/dist/transition-flow.d.ts.map +1 -1
- package/dist/transition-flow.js +199 -4
- package/dist/types.d.ts +109 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -4
- package/schemas/dag-workflow.schema.json +93 -0
- package/schemas/transition-flow-workflow.schema.json +34 -0
- package/src/action-step.ts +2 -0
- package/src/config.ts +152 -5
- package/src/dag.ts +297 -0
- package/src/events.ts +33 -0
- package/src/host.ts +4 -2
- package/src/index.ts +6 -0
- package/src/persistence.ts +155 -0
- package/src/run-lifecycle.ts +75 -2
- package/src/schema-sql.ts +20 -0
- package/src/schema.ts +108 -16
- package/src/service.ts +72 -7
- package/src/state-machine.ts +8 -3
- package/src/transition-flow.ts +279 -3
- package/src/types.ts +128 -2
package/src/persistence.ts
CHANGED
|
@@ -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
|
}
|
package/src/run-lifecycle.ts
CHANGED
|
@@ -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
|
-
|
|
166
|
+
recordMode === 'transition-flow'
|
|
166
167
|
? ('transition-flow' as const)
|
|
167
|
-
:
|
|
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
|
@@ -96,6 +96,8 @@ export const StateMachineWorkflowDefSchema = z
|
|
|
96
96
|
pause: z.boolean().optional(),
|
|
97
97
|
/** Author declaration that re-running this state's on-enter actions after an interruption is safe. */
|
|
98
98
|
resumeRerun: z.boolean().optional(),
|
|
99
|
+
/** Author opt-in for a fresh run to begin at this state (task 0102 R2). */
|
|
100
|
+
startable: z.boolean().optional(),
|
|
99
101
|
})
|
|
100
102
|
.strict(),
|
|
101
103
|
),
|
|
@@ -116,6 +118,74 @@ export const StateMachineWorkflowDefSchema = z
|
|
|
116
118
|
})
|
|
117
119
|
.strict();
|
|
118
120
|
|
|
121
|
+
/** Zod schema for structured parallel branch definitions. */
|
|
122
|
+
export const FlowParallelBranchDefSchema = z
|
|
123
|
+
.object({
|
|
124
|
+
id: z.string().min(1),
|
|
125
|
+
startNode: z.string().min(1),
|
|
126
|
+
description: z.string().optional(),
|
|
127
|
+
})
|
|
128
|
+
.strict();
|
|
129
|
+
|
|
130
|
+
/** Zod schema for transition-flow node definitions. */
|
|
131
|
+
export const FlowNodeDefSchema = z
|
|
132
|
+
.object({
|
|
133
|
+
id: z.string().min(1),
|
|
134
|
+
description: z.string().optional(),
|
|
135
|
+
type: z.enum(['action', 'gate', 'parallel', 'decision']).optional(),
|
|
136
|
+
action: ActionDefSchema.optional(),
|
|
137
|
+
/** When true, the engine pauses the run at this node instead of auto-advancing. */
|
|
138
|
+
pause: z.boolean().optional(),
|
|
139
|
+
/** Author declaration that re-running this node's action after an interruption is safe. */
|
|
140
|
+
resumeRerun: z.boolean().optional(),
|
|
141
|
+
/** Author opt-in for a fresh run to begin at this node (task 0102 R2). */
|
|
142
|
+
startable: z.boolean().optional(),
|
|
143
|
+
/** Declared branches for parallel fork nodes (type: 'parallel'). */
|
|
144
|
+
branches: z.array(FlowParallelBranchDefSchema).optional(),
|
|
145
|
+
/** Target join node ID where branches converge for parallel fork nodes. */
|
|
146
|
+
join: z.string().min(1).optional(),
|
|
147
|
+
/** Join synchronization policy for parallel nodes. Defaults to 'all'. */
|
|
148
|
+
joinPolicy: z.enum(['all']).optional(),
|
|
149
|
+
/** Failure handling policy across parallel branches. Defaults to 'collect'. */
|
|
150
|
+
failurePolicy: z.enum(['collect', 'fail-fast']).optional(),
|
|
151
|
+
/** Maximum number of branches executed concurrently. Defaults to 4. */
|
|
152
|
+
concurrencyLimit: z.number().int().positive().optional(),
|
|
153
|
+
})
|
|
154
|
+
.strict()
|
|
155
|
+
.superRefine((node, ctx) => {
|
|
156
|
+
if (node.type === 'parallel') {
|
|
157
|
+
if (!node.branches || node.branches.length === 0) {
|
|
158
|
+
ctx.addIssue({
|
|
159
|
+
code: 'custom',
|
|
160
|
+
message: 'Parallel node must declare non-empty branches array',
|
|
161
|
+
path: ['branches'],
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
if (!node.join) {
|
|
165
|
+
ctx.addIssue({
|
|
166
|
+
code: 'custom',
|
|
167
|
+
message: 'Parallel node must declare join target node ID',
|
|
168
|
+
path: ['join'],
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
} else {
|
|
172
|
+
if (node.branches !== undefined) {
|
|
173
|
+
ctx.addIssue({
|
|
174
|
+
code: 'custom',
|
|
175
|
+
message: `Node "${node.id}" of type "${node.type ?? 'action'}" must not declare branches`,
|
|
176
|
+
path: ['branches'],
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
if (node.join !== undefined) {
|
|
180
|
+
ctx.addIssue({
|
|
181
|
+
code: 'custom',
|
|
182
|
+
message: `Node "${node.id}" of type "${node.type ?? 'action'}" must not declare join`,
|
|
183
|
+
path: ['join'],
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
|
|
119
189
|
/** Zod schema for transition-flow workflow definitions. */
|
|
120
190
|
export const TransitionFlowWorkflowDefSchema = z
|
|
121
191
|
.object({
|
|
@@ -131,20 +201,7 @@ export const TransitionFlowWorkflowDefSchema = z
|
|
|
131
201
|
defaultOnError: z.enum(['fail', 'continue']).optional(),
|
|
132
202
|
vars: VarsSchema.optional(),
|
|
133
203
|
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
|
-
),
|
|
204
|
+
nodes: z.array(FlowNodeDefSchema),
|
|
148
205
|
edges: z.array(
|
|
149
206
|
z
|
|
150
207
|
.object({
|
|
@@ -159,5 +216,40 @@ export const TransitionFlowWorkflowDefSchema = z
|
|
|
159
216
|
})
|
|
160
217
|
.strict();
|
|
161
218
|
|
|
162
|
-
/** Zod schema for
|
|
163
|
-
export const
|
|
219
|
+
/** Zod schema for static dependency DAG node definitions. */
|
|
220
|
+
export const DagNodeDefSchema = z
|
|
221
|
+
.object({
|
|
222
|
+
id: z.string().min(1),
|
|
223
|
+
description: z.string().optional(),
|
|
224
|
+
action: ActionDefSchema.optional(),
|
|
225
|
+
dependsOn: z.array(z.string().min(1)).optional(),
|
|
226
|
+
dependencyPolicy: z.enum(['all', 'any']).optional(),
|
|
227
|
+
condition: GuardDefSchema.optional(),
|
|
228
|
+
pause: z.boolean().optional(),
|
|
229
|
+
resumeRerun: z.boolean().optional(),
|
|
230
|
+
})
|
|
231
|
+
.strict();
|
|
232
|
+
|
|
233
|
+
/** Zod schema for static dependency DAG workflow definitions. */
|
|
234
|
+
export const DagWorkflowDefSchema = z
|
|
235
|
+
.object({
|
|
236
|
+
$schema: z.string().optional(),
|
|
237
|
+
kind: z.literal('dag'),
|
|
238
|
+
name: z.string().min(1),
|
|
239
|
+
version: z.string().optional(),
|
|
240
|
+
description: z.string().optional(),
|
|
241
|
+
iterationBound: z.number().int().positive().optional(),
|
|
242
|
+
defaultOnError: z.enum(['fail', 'continue']).optional(),
|
|
243
|
+
vars: VarsSchema.optional(),
|
|
244
|
+
env: EnvSchema.optional(),
|
|
245
|
+
nodes: z.array(DagNodeDefSchema),
|
|
246
|
+
extensions: WorkflowExtensionsSchema.optional(),
|
|
247
|
+
})
|
|
248
|
+
.strict();
|
|
249
|
+
|
|
250
|
+
/** Zod schema for supported workflow definition shapes. */
|
|
251
|
+
export const WorkflowDefSchema = z.union([
|
|
252
|
+
StateMachineWorkflowDefSchema,
|
|
253
|
+
TransitionFlowWorkflowDefSchema,
|
|
254
|
+
DagWorkflowDefSchema,
|
|
255
|
+
]);
|
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';
|
|
@@ -60,16 +61,30 @@ export class WorkflowService {
|
|
|
60
61
|
/** Run an already-loaded workflow definition. */
|
|
61
62
|
async run(workflow: WorkflowDef, options: WorkflowRunOptions = {}): Promise<WorkflowRunResult> {
|
|
62
63
|
const events = this.resolveEvents(options.events);
|
|
64
|
+
// Refuse an illegal start point BEFORE any driver dispatch, i.e. before
|
|
65
|
+
// `RunLifecycle.run` creates the run row (task 0102 R3).
|
|
66
|
+
if (options.startState !== undefined) {
|
|
67
|
+
this.assertStartStateAllowed(workflow, options.startState);
|
|
68
|
+
}
|
|
63
69
|
if (workflow.kind === 'transition-flow') {
|
|
64
70
|
return await new TransitionFlowDriver({ host: this.host, persistence: this.persistence }).run(workflow, {
|
|
65
71
|
...options,
|
|
66
72
|
events,
|
|
67
73
|
});
|
|
68
74
|
}
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
75
|
+
if (workflow.kind === 'dag') {
|
|
76
|
+
return await new DagDriver({ host: this.host, persistence: this.persistence }).run(workflow, {
|
|
77
|
+
...options,
|
|
78
|
+
events,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return await new StateMachineDriver({ host: this.host, persistence: this.persistence }).run(
|
|
82
|
+
workflow as StateMachineWorkflowDef,
|
|
83
|
+
{
|
|
84
|
+
...options,
|
|
85
|
+
events,
|
|
86
|
+
},
|
|
87
|
+
);
|
|
73
88
|
}
|
|
74
89
|
|
|
75
90
|
/** Load and run a workflow file. */
|
|
@@ -131,14 +146,58 @@ export class WorkflowService {
|
|
|
131
146
|
|
|
132
147
|
/** Reject a reseed target the workflow definition does not allow (state-machine states only). */
|
|
133
148
|
private assertReseedTargetDeclared(workflow: WorkflowDef, runId: string, newState: string): void {
|
|
134
|
-
if (workflow.kind
|
|
149
|
+
if (workflow.kind !== 'state-machine' && workflow.kind !== undefined) {
|
|
135
150
|
throw new FSMError('reseedRun only supports state-machine workflows');
|
|
136
151
|
}
|
|
137
|
-
|
|
152
|
+
const sm = workflow as StateMachineWorkflowDef;
|
|
153
|
+
if (!sm.states.some((state) => state.id === newState)) {
|
|
138
154
|
throw new FSMError(`Cannot reseed run "${runId}" to undeclared state "${newState}"`);
|
|
139
155
|
}
|
|
140
156
|
}
|
|
141
157
|
|
|
158
|
+
/**
|
|
159
|
+
* Refuse an illegal `startState` before any run row exists (task 0102 R3). The
|
|
160
|
+
* target must be declared, non-terminal, non-failure, and opted in by the author
|
|
161
|
+
* with `startable: true`; `kind: 'dag'` is unsupported. This guard is the point of
|
|
162
|
+
* the feature — a mid-graph start on a state that assumed earlier artifacts must
|
|
163
|
+
* fail loud, never silently skip the work it expected.
|
|
164
|
+
*/
|
|
165
|
+
private assertStartStateAllowed(workflow: WorkflowDef, startState: string): void {
|
|
166
|
+
if (workflow.kind === 'dag') {
|
|
167
|
+
throw new FSMError(
|
|
168
|
+
`Cannot start at "${startState}": startState is not supported for kind: "dag" workflows`,
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
const nodes: readonly { readonly id: string; readonly startable?: boolean }[] =
|
|
172
|
+
workflow.kind === 'transition-flow' ? workflow.nodes : workflow.states;
|
|
173
|
+
const terminal: readonly string[] =
|
|
174
|
+
workflow.kind === 'transition-flow' ? (workflow.terminalNodes ?? []) : (workflow.terminalStates ?? []);
|
|
175
|
+
const failure: readonly string[] = workflow.kind === 'transition-flow' ? [] : (workflow.failureStates ?? []);
|
|
176
|
+
|
|
177
|
+
const declared = nodes.find((node) => node.id === startState);
|
|
178
|
+
if (declared === undefined) {
|
|
179
|
+
const startable = nodes.filter((node) => node.startable === true).map((node) => node.id);
|
|
180
|
+
throw new FSMError(
|
|
181
|
+
`Cannot start at "${startState}": it is not declared. ` +
|
|
182
|
+
(startable.length > 0
|
|
183
|
+
? `Startable ids: ${startable.join(', ')}`
|
|
184
|
+
: 'No state or node declares startable: true'),
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
if (failure.includes(startState)) {
|
|
188
|
+
throw new FSMError(`Cannot start at "${startState}": it is declared as a failure state`);
|
|
189
|
+
}
|
|
190
|
+
if (terminal.includes(startState)) {
|
|
191
|
+
throw new FSMError(`Cannot start at "${startState}": it is declared as a terminal state`);
|
|
192
|
+
}
|
|
193
|
+
if (declared.startable !== true) {
|
|
194
|
+
throw new FSMError(
|
|
195
|
+
`Cannot start at "${startState}": not marked startable: true. ` +
|
|
196
|
+
'Opt in from the definition — there is no caller override.',
|
|
197
|
+
);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
142
201
|
/** Persist the reseed and emit the corrective event with the run's external key. */
|
|
143
202
|
private async commitReseed(runId: string, newState: string, options?: WorkflowRunOptions): Promise<void> {
|
|
144
203
|
const run = await this.persistence.loadRun(runId);
|
|
@@ -214,6 +273,12 @@ export class WorkflowService {
|
|
|
214
273
|
persistence: this.persistence,
|
|
215
274
|
}).resume(workflow, runId, currentState, extKey, mergedOptions);
|
|
216
275
|
}
|
|
276
|
+
if (workflow.kind === 'dag') {
|
|
277
|
+
return await new DagDriver({
|
|
278
|
+
host: this.host,
|
|
279
|
+
persistence: this.persistence,
|
|
280
|
+
}).resume(workflow, runId, extKey, mergedOptions);
|
|
281
|
+
}
|
|
217
282
|
return await new StateMachineDriver({
|
|
218
283
|
host: this.host,
|
|
219
284
|
persistence: this.persistence,
|
|
@@ -248,7 +313,7 @@ export class WorkflowService {
|
|
|
248
313
|
): void {
|
|
249
314
|
if (resumeMode !== 'rerun-enter') return;
|
|
250
315
|
const node =
|
|
251
|
-
workflow.kind === 'transition-flow'
|
|
316
|
+
workflow.kind === 'transition-flow' || workflow.kind === 'dag'
|
|
252
317
|
? workflow.nodes.find((candidate) => candidate.id === currentState)
|
|
253
318
|
: (workflow as StateMachineWorkflowDef).states.find((candidate) => candidate.id === currentState);
|
|
254
319
|
if (node !== undefined && node.resumeRerun !== true) {
|
package/src/state-machine.ts
CHANGED
|
@@ -28,7 +28,7 @@ export class StateMachineDriver {
|
|
|
28
28
|
'state-machine',
|
|
29
29
|
{ persistence: this.options.persistence, events: options.events },
|
|
30
30
|
options,
|
|
31
|
-
(lifecycle) => this.loop(workflow, options, lifecycle),
|
|
31
|
+
(lifecycle) => this.loop(workflow, options, lifecycle, undefined, options.startState),
|
|
32
32
|
);
|
|
33
33
|
}
|
|
34
34
|
|
|
@@ -56,6 +56,7 @@ export class StateMachineDriver {
|
|
|
56
56
|
options: WorkflowRunOptions,
|
|
57
57
|
lifecycle: RunLifecycle,
|
|
58
58
|
resumeFromState?: string,
|
|
59
|
+
startAtState?: string,
|
|
59
60
|
): Promise<WorkflowRunResult> {
|
|
60
61
|
const runId = lifecycle.runId;
|
|
61
62
|
const states = new Map(workflow.states.map((state) => [state.id, state]));
|
|
@@ -63,7 +64,11 @@ export class StateMachineDriver {
|
|
|
63
64
|
const failure = new Set(workflow.failureStates ?? []);
|
|
64
65
|
let vars = mergeVars(workflow.vars, options.vars);
|
|
65
66
|
const env = allowedEnv(workflow.env?.allow ?? [], options.env);
|
|
66
|
-
|
|
67
|
+
// `startAtState` is a FRESH-run start point, so it deliberately does not enter the
|
|
68
|
+
// resume branch below: no snapshot load, no `resumeMode`, `transitionsTaken` stays 0,
|
|
69
|
+
// and the start state's on-enter actions execute (task 0102 R1).
|
|
70
|
+
const entryState = resumeFromState ?? startAtState;
|
|
71
|
+
let current = entryState !== undefined ? states.get(entryState) : states.get(workflow.initialState);
|
|
67
72
|
const snapshot =
|
|
68
73
|
resumeFromState === undefined ? undefined : await this.options.persistence.loadLatestStateSnapshot(runId);
|
|
69
74
|
let transitionsTaken = snapshotTransitions(snapshot?.data);
|
|
@@ -81,7 +86,7 @@ export class StateMachineDriver {
|
|
|
81
86
|
let declaredTerminalReason: string | undefined;
|
|
82
87
|
|
|
83
88
|
if (current === undefined) {
|
|
84
|
-
const label =
|
|
89
|
+
const label = entryState ?? workflow.initialState;
|
|
85
90
|
throw new FSMError(`State "${label}" is not declared`);
|
|
86
91
|
}
|
|
87
92
|
|