@multiplier-labs/stepflow 0.3.1

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 (76) hide show
  1. package/.github/workflows/publish.yml +30 -0
  2. package/README.md +408 -0
  3. package/dist/chunk-FQCT3I2A.js +1512 -0
  4. package/dist/chunk-FQCT3I2A.js.map +1 -0
  5. package/dist/chunk-GXY66V7Q.js +111 -0
  6. package/dist/chunk-GXY66V7Q.js.map +1 -0
  7. package/dist/chunk-U5QGN3RT.js +715 -0
  8. package/dist/chunk-U5QGN3RT.js.map +1 -0
  9. package/dist/chunk-XCF4PLN7.js +575 -0
  10. package/dist/chunk-XCF4PLN7.js.map +1 -0
  11. package/dist/events/index.d.ts +346 -0
  12. package/dist/events/index.js +11 -0
  13. package/dist/events/index.js.map +1 -0
  14. package/dist/index-CPfGsmrp.d.ts +567 -0
  15. package/dist/index.d.ts +748 -0
  16. package/dist/index.js +1707 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/scheduler/index.d.ts +6 -0
  19. package/dist/scheduler/index.js +12 -0
  20. package/dist/scheduler/index.js.map +1 -0
  21. package/dist/storage/index.d.ts +402 -0
  22. package/dist/storage/index.js +13 -0
  23. package/dist/storage/index.js.map +1 -0
  24. package/dist/types-BVShq7zT.d.ts +150 -0
  25. package/dist/types-BlwFEGzj.d.ts +276 -0
  26. package/dist/types-DzkEqnQJ.d.ts +75 -0
  27. package/docs/github-packages-setup.md +97 -0
  28. package/docs/stepflow-api-reference.md +1662 -0
  29. package/package.json +85 -0
  30. package/src/core/engine.test.ts +1421 -0
  31. package/src/core/engine.ts +717 -0
  32. package/src/core/index.ts +7 -0
  33. package/src/core/orchestrator.ts +590 -0
  34. package/src/core/types.ts +242 -0
  35. package/src/events/index.ts +8 -0
  36. package/src/events/memory.test.ts +109 -0
  37. package/src/events/memory.ts +95 -0
  38. package/src/events/socketio.test.ts +428 -0
  39. package/src/events/socketio.ts +269 -0
  40. package/src/events/types.ts +121 -0
  41. package/src/events/webhook.test.ts +695 -0
  42. package/src/events/webhook.ts +591 -0
  43. package/src/index.ts +270 -0
  44. package/src/planning/index.ts +52 -0
  45. package/src/planning/planner.ts +601 -0
  46. package/src/planning/planning.test.ts +790 -0
  47. package/src/planning/registry.test.ts +445 -0
  48. package/src/planning/registry.ts +369 -0
  49. package/src/planning/types.ts +570 -0
  50. package/src/scheduler/cron.test.ts +480 -0
  51. package/src/scheduler/cron.ts +449 -0
  52. package/src/scheduler/index.ts +18 -0
  53. package/src/scheduler/postgres-persistence.test.ts +906 -0
  54. package/src/scheduler/postgres-persistence.ts +546 -0
  55. package/src/scheduler/sqlite-persistence.test.ts +235 -0
  56. package/src/scheduler/sqlite-persistence.ts +268 -0
  57. package/src/scheduler/types.ts +78 -0
  58. package/src/storage/index.ts +27 -0
  59. package/src/storage/memory.test.ts +399 -0
  60. package/src/storage/memory.ts +248 -0
  61. package/src/storage/postgres.ts +1550 -0
  62. package/src/storage/sqlite.test.ts +593 -0
  63. package/src/storage/sqlite.ts +662 -0
  64. package/src/storage/types.ts +368 -0
  65. package/src/utils/errors.test.ts +152 -0
  66. package/src/utils/errors.ts +191 -0
  67. package/src/utils/id.ts +21 -0
  68. package/src/utils/index.ts +8 -0
  69. package/src/utils/logger.test.ts +127 -0
  70. package/src/utils/logger.ts +96 -0
  71. package/src/utils/postgres-deps.ts +63 -0
  72. package/src/utils/retry.test.ts +197 -0
  73. package/src/utils/retry.ts +121 -0
  74. package/tsconfig.json +21 -0
  75. package/tsup.config.ts +14 -0
  76. package/vitest.config.ts +9 -0
@@ -0,0 +1,590 @@
1
+ /**
2
+ * Workflow Orchestrator
3
+ *
4
+ * This module is the heart of the workflow execution system.
5
+ * It manages the execution of workflow steps, handles errors,
6
+ * emits events, and persists state.
7
+ */
8
+
9
+ import type {
10
+ WorkflowDefinition,
11
+ WorkflowStep,
12
+ WorkflowContext,
13
+ RunResult,
14
+ Logger,
15
+ SpawnChildOptions,
16
+ } from "./types";
17
+ import type { StorageAdapter } from "../storage/types";
18
+ import type { EventTransport, WorkflowEvent } from "../events/types";
19
+ import {
20
+ WorkflowEngineError,
21
+ StepError,
22
+ StepTimeoutError,
23
+ WorkflowCanceledError,
24
+ WorkflowTimeoutError,
25
+ } from "../utils/errors";
26
+ import { createScopedLogger } from "../utils/logger";
27
+ import { sleep, calculateRetryDelay } from "../utils/retry";
28
+
29
+ /**
30
+ * Checkpoint data for resuming workflows.
31
+ */
32
+ export interface WorkflowCheckpoint {
33
+ /** Set of step keys that have been completed */
34
+ completedStepKeys: Set<string>;
35
+ /** Accumulated results from completed steps */
36
+ results: Record<string, unknown>;
37
+ }
38
+
39
+ /**
40
+ * Options for executing a workflow.
41
+ */
42
+ export interface ExecuteOptions {
43
+ /** The run ID */
44
+ runId: string;
45
+ /** The workflow definition */
46
+ definition: WorkflowDefinition;
47
+ /** Input parameters */
48
+ input: Record<string, unknown>;
49
+ /** Optional metadata */
50
+ metadata?: Record<string, unknown>;
51
+ /** Storage adapter */
52
+ storage: StorageAdapter;
53
+ /** Event transport */
54
+ events: EventTransport;
55
+ /** Logger instance */
56
+ logger: Logger;
57
+ /** Abort controller for cancellation */
58
+ abortController: AbortController;
59
+ /** Function to spawn child workflows */
60
+ spawnChild: (options: SpawnChildOptions) => Promise<string>;
61
+ /** Optional checkpoint for resuming from a previous execution */
62
+ checkpoint?: WorkflowCheckpoint;
63
+ }
64
+
65
+ /**
66
+ * Execute a workflow definition.
67
+ * This is the main execution logic that runs all steps sequentially.
68
+ */
69
+ export async function executeWorkflow(
70
+ options: ExecuteOptions,
71
+ ): Promise<RunResult> {
72
+ const {
73
+ runId,
74
+ definition,
75
+ input,
76
+ metadata = {},
77
+ storage,
78
+ events,
79
+ logger,
80
+ abortController,
81
+ spawnChild,
82
+ checkpoint,
83
+ } = options;
84
+
85
+ const startTime = Date.now();
86
+ const isResume = !!checkpoint;
87
+
88
+ // Update run status to running (if not already)
89
+ // On resume, don't overwrite the original startedAt
90
+ await storage.updateRun(runId, {
91
+ status: "running",
92
+ ...(isResume ? {} : { startedAt: new Date() }),
93
+ });
94
+
95
+ emitEvent(events, logger, {
96
+ runId,
97
+ kind: definition.kind,
98
+ eventType: isResume ? "run.resumed" : "run.started",
99
+ timestamp: new Date(),
100
+ payload: isResume
101
+ ? { resumedFrom: Array.from(checkpoint.completedStepKeys) }
102
+ : undefined,
103
+ });
104
+
105
+ // Build the execution context, using checkpoint results if resuming
106
+ const context: WorkflowContext = {
107
+ runId,
108
+ stepId: "", // Will be set for each step before handler is called
109
+ kind: definition.kind,
110
+ input,
111
+ results: checkpoint?.results ? { ...checkpoint.results } : {},
112
+ metadata,
113
+ logger: createScopedLogger(logger, runId),
114
+ signal: abortController.signal,
115
+ spawnChild,
116
+ emit: (eventType: string, payload?: unknown) => {
117
+ emitEvent(events, logger, {
118
+ runId,
119
+ kind: definition.kind,
120
+ eventType,
121
+ timestamp: new Date(),
122
+ payload,
123
+ });
124
+ },
125
+ };
126
+
127
+ // Set up workflow-level timeout if specified
128
+ let workflowTimeoutId: ReturnType<typeof setTimeout> | undefined;
129
+ let workflowTimeoutError: WorkflowTimeoutError | undefined;
130
+
131
+ if (definition.timeout) {
132
+ workflowTimeoutId = setTimeout(() => {
133
+ workflowTimeoutError = new WorkflowTimeoutError(
134
+ runId,
135
+ definition.timeout!,
136
+ );
137
+ abortController.abort();
138
+ }, definition.timeout);
139
+ }
140
+
141
+ try {
142
+ // Execute beforeRun hook
143
+ if (definition.hooks?.beforeRun) {
144
+ await definition.hooks.beforeRun(context);
145
+ }
146
+
147
+ // Execute each step in sequence
148
+ for (const step of definition.steps) {
149
+ // Check for cancellation
150
+ if (abortController.signal.aborted) {
151
+ throw new WorkflowCanceledError(runId);
152
+ }
153
+
154
+ context.currentStep = step.key;
155
+
156
+ // Skip already completed steps when resuming
157
+ if (checkpoint?.completedStepKeys.has(step.key)) {
158
+ logger.info(
159
+ `Skipping step "${step.key}" (already completed in previous run)`,
160
+ );
161
+ emitEvent(events, logger, {
162
+ runId,
163
+ kind: definition.kind,
164
+ eventType: "step.skipped",
165
+ stepKey: step.key,
166
+ timestamp: new Date(),
167
+ payload: { reason: "checkpoint" },
168
+ });
169
+ continue;
170
+ }
171
+
172
+ // Check skip condition
173
+ if (step.skipIf) {
174
+ const shouldSkip = await step.skipIf(context);
175
+ if (shouldSkip) {
176
+ logger.info(`Skipping step "${step.key}" (condition met)`);
177
+
178
+ emitEvent(events, logger, {
179
+ runId,
180
+ kind: definition.kind,
181
+ eventType: "step.skipped",
182
+ stepKey: step.key,
183
+ timestamp: new Date(),
184
+ });
185
+
186
+ continue;
187
+ }
188
+ }
189
+
190
+ // Execute the step
191
+ const result = await executeStep(step, context, {
192
+ definition,
193
+ storage,
194
+ events,
195
+ logger,
196
+ abortController,
197
+ });
198
+
199
+ // Store result in context
200
+ context.results[step.key] = result;
201
+
202
+ // Save checkpoint (accumulated results)
203
+ await storage.updateRun(runId, {
204
+ context: { ...context.results },
205
+ });
206
+ }
207
+
208
+ // All steps completed successfully
209
+ // Clear workflow timeout
210
+ if (workflowTimeoutId) {
211
+ clearTimeout(workflowTimeoutId);
212
+ }
213
+
214
+ const duration = Date.now() - startTime;
215
+ const runResult: RunResult = {
216
+ status: "succeeded",
217
+ results: context.results,
218
+ duration,
219
+ };
220
+
221
+ // Execute afterRun hook
222
+ if (definition.hooks?.afterRun) {
223
+ await definition.hooks.afterRun(context, runResult);
224
+ }
225
+
226
+ // Update run status
227
+ await storage.updateRun(runId, {
228
+ status: "succeeded",
229
+ context: context.results,
230
+ finishedAt: new Date(),
231
+ });
232
+
233
+ emitEvent(events, logger, {
234
+ runId,
235
+ kind: definition.kind,
236
+ eventType: "run.completed",
237
+ timestamp: new Date(),
238
+ payload: { results: context.results, duration },
239
+ });
240
+
241
+ return runResult;
242
+ } catch (error) {
243
+ // Clear workflow timeout
244
+ if (workflowTimeoutId) {
245
+ clearTimeout(workflowTimeoutId);
246
+ }
247
+
248
+ const duration = Date.now() - startTime;
249
+
250
+ // Check if this was a workflow timeout (abort triggered by our timeout handler)
251
+ const actualError = workflowTimeoutError ?? error;
252
+ const workflowError = WorkflowEngineError.fromError(actualError);
253
+
254
+ // Determine final status
255
+ const isTimeout = actualError instanceof WorkflowTimeoutError;
256
+ const isCanceled =
257
+ !isTimeout && actualError instanceof WorkflowCanceledError;
258
+ const status = isCanceled ? "canceled" : "failed";
259
+ const eventType = isTimeout
260
+ ? "run.timeout"
261
+ : isCanceled
262
+ ? "run.canceled"
263
+ : "run.failed";
264
+
265
+ const runResult: RunResult = {
266
+ status,
267
+ results: context.results,
268
+ error: workflowError,
269
+ duration,
270
+ };
271
+
272
+ // Execute afterRun hook (even on failure)
273
+ if (definition.hooks?.afterRun) {
274
+ try {
275
+ await definition.hooks.afterRun(context, runResult);
276
+ } catch (hookError) {
277
+ logger.error("afterRun hook failed:", hookError);
278
+ }
279
+ }
280
+
281
+ // Update run status
282
+ await storage.updateRun(runId, {
283
+ status,
284
+ context: context.results,
285
+ error: workflowError,
286
+ finishedAt: new Date(),
287
+ });
288
+
289
+ emitEvent(events, logger, {
290
+ runId,
291
+ kind: definition.kind,
292
+ eventType,
293
+ timestamp: new Date(),
294
+ payload: { error: workflowError.message, duration },
295
+ });
296
+
297
+ return runResult;
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Options for executing a single step.
303
+ */
304
+ interface StepExecutionOptions<TInput = Record<string, unknown>> {
305
+ definition: WorkflowDefinition<TInput>;
306
+ storage: StorageAdapter;
307
+ events: EventTransport;
308
+ logger: Logger;
309
+ abortController: AbortController;
310
+ }
311
+
312
+ /**
313
+ * Execute a single workflow step with error handling and retries.
314
+ */
315
+ async function executeStep<TInput>(
316
+ step: WorkflowStep<TInput>,
317
+ context: WorkflowContext<TInput>,
318
+ options: StepExecutionOptions<TInput>,
319
+ ): Promise<unknown> {
320
+ const { definition, storage, events, logger, abortController } = options;
321
+
322
+ // Determine error strategy
323
+ const onError = step.onError ?? definition.defaultOnError ?? "fail";
324
+ const maxRetries = step.maxRetries ?? 3;
325
+ const retryDelay = step.retryDelay ?? 1000;
326
+ const retryBackoff = step.retryBackoff ?? 2;
327
+
328
+ let attempt = 0;
329
+ let lastError: Error | undefined;
330
+
331
+ while (true) {
332
+ attempt++;
333
+
334
+ // Check for cancellation
335
+ if (abortController.signal.aborted) {
336
+ throw new WorkflowCanceledError(context.runId);
337
+ }
338
+
339
+ // Create step record
340
+ const stepRecord = await storage.createStep({
341
+ runId: context.runId,
342
+ stepKey: step.key,
343
+ stepName: step.name,
344
+ status: "running",
345
+ attempt,
346
+ startedAt: new Date(),
347
+ });
348
+
349
+ // Set the current step's ID in context so handlers can track granular operations (e.g., token usage)
350
+ context.stepId = stepRecord.id;
351
+
352
+ // Emit step started event
353
+ emitEvent(events, logger, {
354
+ runId: context.runId,
355
+ kind: context.kind,
356
+ eventType: "step.started",
357
+ stepKey: step.key,
358
+ timestamp: new Date(),
359
+ payload: { attempt },
360
+ });
361
+
362
+ // Execute beforeStep hook
363
+ if (definition.hooks?.beforeStep) {
364
+ await definition.hooks.beforeStep(context, step);
365
+ }
366
+
367
+ try {
368
+ // Execute with optional timeout
369
+ // Always race against abort signal to support workflow-level timeouts
370
+ let result: unknown;
371
+
372
+ if (step.timeout) {
373
+ result = await executeWithTimeout(
374
+ () => step.handler(context),
375
+ step.timeout,
376
+ abortController.signal,
377
+ step.key,
378
+ );
379
+ } else {
380
+ // Race step handler against abort signal for workflow-level timeout support
381
+ result = await raceWithAbort(
382
+ step.handler(context),
383
+ abortController.signal,
384
+ );
385
+ }
386
+
387
+ // Step succeeded
388
+ await storage.updateStep(stepRecord.id, {
389
+ status: "succeeded",
390
+ result,
391
+ finishedAt: new Date(),
392
+ });
393
+
394
+ // Execute afterStep hook
395
+ if (definition.hooks?.afterStep) {
396
+ await definition.hooks.afterStep(context, step, result);
397
+ }
398
+
399
+ emitEvent(events, logger, {
400
+ runId: context.runId,
401
+ kind: context.kind,
402
+ eventType: "step.completed",
403
+ stepKey: step.key,
404
+ timestamp: new Date(),
405
+ payload: { result },
406
+ });
407
+
408
+ return result;
409
+ } catch (error) {
410
+ lastError = error instanceof Error ? error : new Error(String(error));
411
+
412
+ // Check if this is a cancellation (abort signal fired)
413
+ const isCanceled =
414
+ error instanceof WorkflowCanceledError ||
415
+ abortController.signal.aborted;
416
+
417
+ // Update step record with error
418
+ await storage.updateStep(stepRecord.id, {
419
+ status: isCanceled ? "canceled" : "failed",
420
+ error: WorkflowEngineError.fromError(error),
421
+ finishedAt: new Date(),
422
+ });
423
+
424
+ // If canceled, re-throw immediately without retry/skip logic
425
+ if (isCanceled) {
426
+ emitEvent(events, logger, {
427
+ runId: context.runId,
428
+ kind: context.kind,
429
+ eventType: "step.failed",
430
+ stepKey: step.key,
431
+ timestamp: new Date(),
432
+ payload: { error: lastError.message, attempt },
433
+ });
434
+ throw error;
435
+ }
436
+
437
+ // Execute onStepError hook
438
+ if (definition.hooks?.onStepError) {
439
+ try {
440
+ await definition.hooks.onStepError(context, step, lastError);
441
+ } catch (hookError) {
442
+ logger.error("onStepError hook failed:", hookError);
443
+ }
444
+ }
445
+
446
+ emitEvent(events, logger, {
447
+ runId: context.runId,
448
+ kind: context.kind,
449
+ eventType: "step.failed",
450
+ stepKey: step.key,
451
+ timestamp: new Date(),
452
+ payload: { error: lastError.message, attempt },
453
+ });
454
+
455
+ // Handle error based on strategy
456
+ if (onError === "skip") {
457
+ logger.warn(`Step "${step.key}" failed, skipping (strategy: skip)`);
458
+ emitEvent(events, logger, {
459
+ runId: context.runId,
460
+ kind: context.kind,
461
+ eventType: "step.skipped",
462
+ stepKey: step.key,
463
+ timestamp: new Date(),
464
+ payload: { reason: "error", error: lastError.message },
465
+ });
466
+ return undefined;
467
+ }
468
+
469
+ if (onError === "retry" && attempt <= maxRetries) {
470
+ const delay = calculateRetryDelay(attempt, retryDelay, retryBackoff);
471
+ logger.warn(
472
+ `Step "${step.key}" failed, retrying in ${delay}ms (attempt ${attempt}/${maxRetries})`,
473
+ );
474
+
475
+ emitEvent(events, logger, {
476
+ runId: context.runId,
477
+ kind: context.kind,
478
+ eventType: "step.retry",
479
+ stepKey: step.key,
480
+ timestamp: new Date(),
481
+ payload: { attempt, maxRetries, delay, error: lastError.message },
482
+ });
483
+
484
+ try {
485
+ await sleep(delay, abortController.signal);
486
+ } catch (sleepError) {
487
+ if (sleepError instanceof WorkflowCanceledError) {
488
+ await storage.updateStep(stepRecord.id, {
489
+ status: "canceled",
490
+ finishedAt: new Date(),
491
+ });
492
+ }
493
+ throw sleepError;
494
+ }
495
+ continue;
496
+ }
497
+
498
+ // Strategy is 'fail' or retries exhausted
499
+ throw new StepError(step.key, lastError.message, attempt, lastError);
500
+ }
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Execute a function with a timeout.
506
+ *
507
+ * Uses Promise.race to resolve as soon as either the function completes, the
508
+ * timeout fires, or the abort signal triggers. The `finally` block is critical:
509
+ * without it, the losing promise's timer/listener would remain active, leaking
510
+ * memory — especially problematic in long-running engines processing many steps.
511
+ */
512
+ async function executeWithTimeout<T>(
513
+ fn: () => Promise<T>,
514
+ timeoutMs: number,
515
+ signal: AbortSignal,
516
+ stepKey: string,
517
+ ): Promise<T> {
518
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
519
+ let onAbort: (() => void) | undefined;
520
+
521
+ try {
522
+ return await Promise.race([
523
+ fn(),
524
+ new Promise<never>((_, reject) => {
525
+ timeoutId = setTimeout(() => {
526
+ reject(new StepTimeoutError(stepKey, timeoutMs));
527
+ }, timeoutMs);
528
+
529
+ onAbort = () => {
530
+ clearTimeout(timeoutId);
531
+ reject(new WorkflowCanceledError("run"));
532
+ };
533
+ signal.addEventListener("abort", onAbort, { once: true });
534
+ }),
535
+ ]);
536
+ } finally {
537
+ if (timeoutId) clearTimeout(timeoutId);
538
+ if (onAbort) signal.removeEventListener("abort", onAbort);
539
+ }
540
+ }
541
+
542
+ /**
543
+ * Race a promise against an abort signal.
544
+ *
545
+ * Steps without their own timeout still need to respect workflow-level timeouts
546
+ * and cancellation. This wraps the step handler in a Promise.race so that an
547
+ * abort signal (from workflow timeout or user cancellation) can interrupt it.
548
+ *
549
+ * The `finally` cleanup removes the abort listener to prevent accumulating
550
+ * listeners on the signal across many steps — without it, each step would
551
+ * leave a dangling listener even after completing successfully.
552
+ */
553
+ async function raceWithAbort<T>(
554
+ promise: Promise<T>,
555
+ signal: AbortSignal,
556
+ ): Promise<T> {
557
+ if (signal.aborted) {
558
+ throw new WorkflowCanceledError("run");
559
+ }
560
+
561
+ let onAbort: (() => void) | undefined;
562
+
563
+ try {
564
+ return await Promise.race([
565
+ promise,
566
+ new Promise<never>((_, reject) => {
567
+ onAbort = () => reject(new WorkflowCanceledError("run"));
568
+ signal.addEventListener("abort", onAbort, { once: true });
569
+ }),
570
+ ]);
571
+ } finally {
572
+ if (onAbort) signal.removeEventListener("abort", onAbort);
573
+ }
574
+ }
575
+
576
+ /**
577
+ * Helper to emit an event.
578
+ */
579
+ function emitEvent(
580
+ events: EventTransport,
581
+ logger: Logger,
582
+ event: WorkflowEvent,
583
+ ): void {
584
+ try {
585
+ events.emit(event);
586
+ } catch (error) {
587
+ // Log but don't fail the workflow for event emission errors
588
+ logger.error("Failed to emit event:", error);
589
+ }
590
+ }