@multiplier-labs/stepflow 0.3.3 → 0.3.6

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 (84) hide show
  1. package/README.md +9 -0
  2. package/dist/{chunk-GYPNJBDP.js → chunk-D5HW7VEG.js} +269 -48
  3. package/dist/chunk-D5HW7VEG.js.map +1 -0
  4. package/dist/{chunk-KHTUWLVZ.js → chunk-FMPJBK2N.js} +55 -10
  5. package/dist/chunk-FMPJBK2N.js.map +1 -0
  6. package/dist/{chunk-ML35PIHX.js → chunk-JPXPB7U5.js} +52 -2
  7. package/dist/chunk-JPXPB7U5.js.map +1 -0
  8. package/dist/{chunk-4VOKMGP6.js → chunk-JUPZEBR3.js} +519 -522
  9. package/dist/chunk-JUPZEBR3.js.map +1 -0
  10. package/dist/events/index.d.ts +58 -3
  11. package/dist/events/index.js +1 -1
  12. package/dist/{index-Dzr437iW.d.ts → index-Cd0IZ40L.d.ts} +50 -11
  13. package/dist/index.d.ts +2 -12
  14. package/dist/index.js +764 -485
  15. package/dist/index.js.map +1 -1
  16. package/dist/scheduler/index.d.ts +1 -1
  17. package/dist/scheduler/index.js +2 -2
  18. package/dist/storage/index.d.ts +313 -47
  19. package/dist/storage/index.js +4 -2
  20. package/package.json +27 -13
  21. package/.codekin/reports/comments/2026-04-04_comment-assessment.md +0 -179
  22. package/.codekin/reports/complexity/2026-04-03_complexity-report.md +0 -152
  23. package/.codekin/reports/dependencies/2026-04-04_dependency-health.md +0 -94
  24. package/.codekin/reports/docs-audit/2026-04-04_docs-audit.md +0 -10
  25. package/.codekin/reports/security/2026-04-03_security-audit.md +0 -208
  26. package/.github/CODEOWNERS +0 -15
  27. package/.github/dependabot.yml +0 -23
  28. package/.github/workflows/ci.yml +0 -38
  29. package/.github/workflows/publish.yml +0 -36
  30. package/.github/workflows/security.yml +0 -29
  31. package/CHANGELOG.md +0 -34
  32. package/SECURITY.md +0 -40
  33. package/dist/chunk-4VOKMGP6.js.map +0 -1
  34. package/dist/chunk-GYPNJBDP.js.map +0 -1
  35. package/dist/chunk-KHTUWLVZ.js.map +0 -1
  36. package/dist/chunk-ML35PIHX.js.map +0 -1
  37. package/docs/github-packages-setup.md +0 -97
  38. package/docs/stepflow-api-reference.md +0 -1661
  39. package/src/core/engine.test.ts +0 -1365
  40. package/src/core/engine.ts +0 -692
  41. package/src/core/index.ts +0 -7
  42. package/src/core/orchestrator.ts +0 -571
  43. package/src/core/types.ts +0 -220
  44. package/src/events/index.ts +0 -8
  45. package/src/events/memory.test.ts +0 -107
  46. package/src/events/memory.ts +0 -92
  47. package/src/events/socketio.test.ts +0 -378
  48. package/src/events/socketio.ts +0 -262
  49. package/src/events/types.ts +0 -118
  50. package/src/events/webhook.test.ts +0 -657
  51. package/src/events/webhook.ts +0 -564
  52. package/src/index.ts +0 -270
  53. package/src/planning/index.ts +0 -55
  54. package/src/planning/planner.ts +0 -576
  55. package/src/planning/planning.test.ts +0 -727
  56. package/src/planning/registry.test.ts +0 -398
  57. package/src/planning/registry.ts +0 -365
  58. package/src/planning/types.ts +0 -566
  59. package/src/scheduler/cron.test.ts +0 -471
  60. package/src/scheduler/cron.ts +0 -414
  61. package/src/scheduler/index.ts +0 -8
  62. package/src/scheduler/postgres-persistence.ts +0 -518
  63. package/src/scheduler/sqlite-persistence.test.ts +0 -235
  64. package/src/scheduler/sqlite-persistence.ts +0 -261
  65. package/src/scheduler/types.ts +0 -73
  66. package/src/storage/index.ts +0 -27
  67. package/src/storage/memory.test.ts +0 -349
  68. package/src/storage/memory.ts +0 -227
  69. package/src/storage/postgres.ts +0 -1354
  70. package/src/storage/sqlite.test.ts +0 -466
  71. package/src/storage/sqlite.ts +0 -627
  72. package/src/storage/types.ts +0 -343
  73. package/src/utils/errors.test.ts +0 -150
  74. package/src/utils/errors.ts +0 -161
  75. package/src/utils/id.ts +0 -21
  76. package/src/utils/index.ts +0 -8
  77. package/src/utils/logger.test.ts +0 -121
  78. package/src/utils/logger.ts +0 -96
  79. package/src/utils/postgres-deps.ts +0 -63
  80. package/src/utils/retry.test.ts +0 -177
  81. package/src/utils/retry.ts +0 -121
  82. package/tsconfig.json +0 -21
  83. package/tsup.config.ts +0 -14
  84. package/vitest.config.ts +0 -9
@@ -1,692 +0,0 @@
1
- /**
2
- * Main WorkflowEngine class.
3
- *
4
- * This is the primary entry point for the workflow engine.
5
- * It provides methods for registering workflows, starting runs,
6
- * and managing workflow execution.
7
- */
8
-
9
- import type {
10
- WorkflowKind,
11
- WorkflowDefinition,
12
- WorkflowContext,
13
- Logger,
14
- SpawnChildOptions,
15
- } from './types';
16
- import type { StorageAdapter, WorkflowRunRecord } from '../storage/types';
17
- import type { EventTransport, EventCallback, Unsubscribe, WorkflowEvent } from '../events/types';
18
- import { MemoryStorageAdapter } from '../storage/memory';
19
- import { MemoryEventTransport } from '../events/memory';
20
- import { executeWorkflow } from './orchestrator';
21
- import {
22
- WorkflowNotFoundError,
23
- WorkflowAlreadyRegisteredError,
24
- RunNotFoundError,
25
- WaitForRunTimeoutError,
26
- } from '../utils/errors';
27
- import { ConsoleLogger } from '../utils/logger';
28
-
29
- // ============================================================================
30
- // Configuration Types
31
- // ============================================================================
32
-
33
- /**
34
- * Configuration for the workflow engine.
35
- */
36
- export interface WorkflowEngineConfig {
37
- /** Storage adapter for persistence (default: MemoryStorageAdapter) */
38
- storage?: StorageAdapter;
39
-
40
- /** Event transport for real-time updates (default: MemoryEventTransport) */
41
- events?: EventTransport;
42
-
43
- /** Logger instance (default: ConsoleLogger) */
44
- logger?: Logger;
45
-
46
- /** Global settings */
47
- settings?: {
48
- /** Default timeout for workflows in ms */
49
- defaultTimeout?: number;
50
-
51
- /** Maximum concurrent workflows */
52
- maxConcurrency?: number;
53
- };
54
- }
55
-
56
- /**
57
- * Options for starting a workflow run.
58
- */
59
- export interface StartRunOptions<TInput = Record<string, unknown>> {
60
- /** Workflow type to run */
61
- kind: WorkflowKind;
62
-
63
- /** Input parameters */
64
- input?: TInput;
65
-
66
- /** Optional metadata (e.g., userId, topicId) */
67
- metadata?: Record<string, unknown>;
68
-
69
- /** Parent run ID (for child workflows) */
70
- parentRunId?: string;
71
-
72
- /** Delay before starting (ms) */
73
- delay?: number;
74
-
75
- /** Priority for queue ordering (higher = runs first, default: 0) */
76
- priority?: number;
77
- }
78
-
79
- // ============================================================================
80
- // WorkflowEngine Class
81
- // ============================================================================
82
-
83
- /**
84
- * Main workflow engine class.
85
- *
86
- * @example
87
- * ```typescript
88
- * const engine = new WorkflowEngine({
89
- * storage: new MemoryStorageAdapter(),
90
- * });
91
- *
92
- * engine.registerWorkflow({
93
- * kind: 'my.workflow',
94
- * name: 'My Workflow',
95
- * steps: [
96
- * {
97
- * key: 'step1',
98
- * name: 'First Step',
99
- * handler: async (ctx) => {
100
- * return { message: 'Hello!' };
101
- * },
102
- * },
103
- * ],
104
- * });
105
- *
106
- * const runId = await engine.startRun({ kind: 'my.workflow' });
107
- * ```
108
- */
109
- /**
110
- * Queued run waiting to be executed when capacity is available.
111
- */
112
- interface QueuedRun {
113
- runId: string;
114
- definition: WorkflowDefinition;
115
- input: Record<string, unknown>;
116
- metadata?: Record<string, unknown>;
117
- priority: number;
118
- queuedAt: Date;
119
- }
120
-
121
- export class WorkflowEngine {
122
- private registry = new Map<WorkflowKind, WorkflowDefinition>();
123
- private storage: StorageAdapter;
124
- private events: EventTransport;
125
- private logger: Logger;
126
- private activeRuns = new Map<string, AbortController>();
127
- private settings: NonNullable<WorkflowEngineConfig['settings']>;
128
- private runQueue: QueuedRun[] = [];
129
-
130
- constructor(config: WorkflowEngineConfig = {}) {
131
- this.storage = config.storage ?? new MemoryStorageAdapter();
132
- this.events = config.events ?? new MemoryEventTransport();
133
- this.logger = config.logger ?? new ConsoleLogger();
134
- this.settings = config.settings ?? {};
135
- }
136
-
137
- /**
138
- * Initialize the engine and its storage/event adapters.
139
- * Call this before starting runs if your storage adapter requires initialization
140
- * (e.g., PostgresStorageAdapter).
141
- */
142
- async initialize(): Promise<void> {
143
- if (this.storage.initialize) {
144
- await this.storage.initialize();
145
- }
146
- }
147
-
148
- /**
149
- * Get the current number of active runs.
150
- */
151
- getActiveRunCount(): number {
152
- return this.activeRuns.size;
153
- }
154
-
155
- /**
156
- * Get the number of queued runs waiting for capacity.
157
- */
158
- getQueuedRunCount(): number {
159
- return this.runQueue.length;
160
- }
161
-
162
- /**
163
- * Check if capacity is available for a new run.
164
- */
165
- private hasCapacity(): boolean {
166
- const maxConcurrency = this.settings.maxConcurrency;
167
- if (maxConcurrency === undefined || maxConcurrency <= 0) {
168
- return true; // No limit
169
- }
170
- return this.activeRuns.size < maxConcurrency;
171
- }
172
-
173
- // ============================================================================
174
- // Workflow Registration
175
- // ============================================================================
176
-
177
- /**
178
- * Register a workflow definition.
179
- * Must be called before runs of this type can be started.
180
- *
181
- * @param definition - The workflow definition
182
- * @throws WorkflowAlreadyRegisteredError if already registered
183
- */
184
- registerWorkflow<TInput = Record<string, unknown>>(
185
- definition: WorkflowDefinition<TInput>
186
- ): void {
187
- if (this.registry.has(definition.kind)) {
188
- throw new WorkflowAlreadyRegisteredError(definition.kind);
189
- }
190
- this.registry.set(definition.kind, definition as WorkflowDefinition);
191
- this.logger.debug(`Registered workflow: ${definition.kind}`);
192
- }
193
-
194
- /**
195
- * Unregister a workflow definition.
196
- *
197
- * @param kind - The workflow kind to unregister
198
- * @returns true if the workflow was unregistered, false if not found
199
- */
200
- unregisterWorkflow(kind: WorkflowKind): boolean {
201
- const deleted = this.registry.delete(kind);
202
- if (deleted) {
203
- this.logger.debug(`Unregistered workflow: ${kind}`);
204
- }
205
- return deleted;
206
- }
207
-
208
- /**
209
- * Get a registered workflow definition.
210
- *
211
- * @param kind - The workflow kind
212
- * @returns The workflow definition or undefined
213
- */
214
- getWorkflow(kind: WorkflowKind): WorkflowDefinition | undefined {
215
- return this.registry.get(kind);
216
- }
217
-
218
- /**
219
- * Get all registered workflow kinds.
220
- */
221
- getRegisteredWorkflows(): WorkflowKind[] {
222
- return Array.from(this.registry.keys());
223
- }
224
-
225
- // ============================================================================
226
- // Run Management
227
- // ============================================================================
228
-
229
- /**
230
- * Start a new workflow run (non-blocking).
231
- * The run executes asynchronously and this method returns immediately.
232
- * If maxConcurrency is set and reached, the run is queued.
233
- *
234
- * @param options - Run options including kind and input
235
- * @returns The generated run ID
236
- * @throws WorkflowNotFoundError if the workflow kind is not registered
237
- */
238
- async startRun<TInput = Record<string, unknown>>(
239
- options: StartRunOptions<TInput>
240
- ): Promise<string> {
241
- const definition = this.registry.get(options.kind);
242
- if (!definition) {
243
- throw new WorkflowNotFoundError(options.kind);
244
- }
245
-
246
- // Create run record (status: queued)
247
- const run = await this.storage.createRun({
248
- kind: options.kind,
249
- status: 'queued',
250
- parentRunId: options.parentRunId,
251
- input: (options.input ?? {}) as Record<string, unknown>,
252
- metadata: options.metadata ?? {},
253
- context: {},
254
- });
255
-
256
- const runId = run.id;
257
-
258
- // Emit run created event
259
- this.events.emit({
260
- runId,
261
- kind: options.kind,
262
- eventType: 'run.created',
263
- timestamp: new Date(),
264
- payload: { input: options.input, metadata: options.metadata, priority: options.priority ?? 0 },
265
- });
266
-
267
- // Check if we have capacity to start immediately
268
- if (this.hasCapacity()) {
269
- // Start execution immediately
270
- this.executeRun(
271
- runId,
272
- definition,
273
- (options.input ?? {}) as Record<string, unknown>,
274
- options.metadata,
275
- options.delay
276
- );
277
- } else {
278
- // Queue the run for later execution
279
- this.queueRun({
280
- runId,
281
- definition,
282
- input: (options.input ?? {}) as Record<string, unknown>,
283
- metadata: options.metadata,
284
- priority: options.priority ?? 0,
285
- queuedAt: new Date(),
286
- });
287
-
288
- this.logger.debug(`Run ${runId} queued (${this.runQueue.length} in queue)`);
289
-
290
- // Emit queued event
291
- this.events.emit({
292
- runId,
293
- kind: options.kind,
294
- eventType: 'run.queued',
295
- timestamp: new Date(),
296
- payload: { queuePosition: this.runQueue.length },
297
- });
298
- }
299
-
300
- return runId;
301
- }
302
-
303
- /**
304
- * Queue a run in priority order.
305
- */
306
- private queueRun(queuedRun: QueuedRun): void {
307
- // Insert in priority order (higher priority first, then FIFO for same priority)
308
- let inserted = false;
309
- for (let i = 0; i < this.runQueue.length; i++) {
310
- if (queuedRun.priority > this.runQueue[i].priority) {
311
- this.runQueue.splice(i, 0, queuedRun);
312
- inserted = true;
313
- break;
314
- }
315
- }
316
- if (!inserted) {
317
- this.runQueue.push(queuedRun);
318
- }
319
- }
320
-
321
- /**
322
- * Execute a run (internal method).
323
- */
324
- private executeRun(
325
- runId: string,
326
- definition: WorkflowDefinition,
327
- input: Record<string, unknown>,
328
- metadata?: Record<string, unknown>,
329
- delay?: number
330
- ): void {
331
- this.launchRun(runId, definition, input, metadata, delay);
332
- }
333
-
334
- /**
335
- * Launch a workflow run asynchronously.
336
- * Shared by both executeRun (new runs) and resumeRun (checkpoint recovery).
337
- */
338
- private launchRun(
339
- runId: string,
340
- definition: WorkflowDefinition,
341
- input: Record<string, unknown>,
342
- metadata?: Record<string, unknown>,
343
- delay?: number,
344
- checkpoint?: { completedStepKeys: Set<string>; results: Record<string, unknown> }
345
- ): void {
346
- const abortController = new AbortController();
347
- this.activeRuns.set(runId, abortController);
348
-
349
- const execute = async () => {
350
- try {
351
- await executeWorkflow({
352
- runId,
353
- definition,
354
- input,
355
- metadata,
356
- storage: this.storage,
357
- events: this.events,
358
- logger: this.logger,
359
- abortController,
360
- spawnChild: (childOptions: SpawnChildOptions) => this.spawnChild(runId, childOptions),
361
- checkpoint,
362
- });
363
- } finally {
364
- this.activeRuns.delete(runId);
365
- this.processQueue();
366
- }
367
- };
368
-
369
- if (delay) {
370
- setTimeout(execute, delay);
371
- } else {
372
- setImmediate(execute);
373
- }
374
- }
375
-
376
- /**
377
- * Process the queue and start runs if capacity is available.
378
- */
379
- private processQueue(): void {
380
- while (this.hasCapacity() && this.runQueue.length > 0) {
381
- const next = this.runQueue.shift()!;
382
- this.logger.debug(`Starting queued run ${next.runId}`);
383
-
384
- // Emit dequeued event
385
- this.events.emit({
386
- runId: next.runId,
387
- kind: next.definition.kind,
388
- eventType: 'run.dequeued',
389
- timestamp: new Date(),
390
- });
391
-
392
- this.executeRun(
393
- next.runId,
394
- next.definition,
395
- next.input,
396
- next.metadata
397
- );
398
- }
399
- }
400
-
401
- /**
402
- * Start a child workflow from within a parent workflow.
403
- * Called internally by the context.spawnChild helper.
404
- */
405
- private async spawnChild(parentRunId: string, options: SpawnChildOptions): Promise<string> {
406
- return this.startRun({
407
- kind: options.kind,
408
- input: options.input,
409
- metadata: options.metadata,
410
- parentRunId,
411
- });
412
- }
413
-
414
- /**
415
- * Cancel a running workflow.
416
- * Signals the workflow to stop at the next cancellation point.
417
- *
418
- * @param runId - The run ID to cancel
419
- * @throws {RunNotFoundError} If no run with the given ID exists
420
- */
421
- async cancelRun(runId: string): Promise<void> {
422
- const run = await this.storage.getRun(runId);
423
- if (!run) {
424
- throw new RunNotFoundError(runId);
425
- }
426
-
427
- // Don't overwrite terminal statuses
428
- if (['succeeded', 'failed', 'canceled', 'timeout'].includes(run.status)) {
429
- return;
430
- }
431
-
432
- // Remove from queue if queued
433
- const queueIndex = this.runQueue.findIndex(q => q.runId === runId);
434
- if (queueIndex !== -1) {
435
- this.runQueue.splice(queueIndex, 1);
436
- }
437
-
438
- // Signal abort to the running workflow
439
- const controller = this.activeRuns.get(runId);
440
- if (controller) {
441
- controller.abort();
442
- }
443
-
444
- // Update status in storage (the orchestrator will also update on completion)
445
- await this.storage.updateRun(runId, {
446
- status: 'canceled',
447
- finishedAt: new Date(),
448
- });
449
-
450
- this.events.emit({
451
- runId,
452
- kind: run.kind,
453
- eventType: 'run.canceled',
454
- timestamp: new Date(),
455
- });
456
- }
457
-
458
- /**
459
- * Get the current status of a run.
460
- *
461
- * @param runId - The run ID to look up
462
- * @returns The run record or null if not found
463
- */
464
- async getRunStatus(runId: string): Promise<WorkflowRunRecord | null> {
465
- return this.storage.getRun(runId);
466
- }
467
-
468
- private static readonly TERMINAL_STATUSES = ['succeeded', 'failed', 'canceled', 'timeout'];
469
- private static readonly TERMINAL_EVENT_TYPES = ['run.completed', 'run.failed', 'run.canceled', 'run.timeout'];
470
-
471
- /**
472
- * Wait for a run to complete.
473
- * Subscribes to run events and resolves when a terminal event fires.
474
- * Falls back to an initial storage read to avoid race conditions.
475
- *
476
- * @param runId - The run ID to wait for
477
- * @param options - Wait options
478
- * @returns The final run record
479
- */
480
- async waitForRun(
481
- runId: string,
482
- options: { timeout?: number } = {}
483
- ): Promise<WorkflowRunRecord> {
484
- const timeout = options.timeout ?? 60000;
485
-
486
- // Check storage first to handle already-completed runs (avoids race condition)
487
- const existingRun = await this.storage.getRun(runId);
488
- if (!existingRun) {
489
- throw new RunNotFoundError(runId);
490
- }
491
- if (WorkflowEngine.TERMINAL_STATUSES.includes(existingRun.status)) {
492
- return existingRun;
493
- }
494
-
495
- return new Promise<WorkflowRunRecord>((resolve, reject) => {
496
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
497
- let unsubscribe: (() => void) | undefined;
498
-
499
- const cleanup = () => {
500
- if (timeoutId) clearTimeout(timeoutId);
501
- if (unsubscribe) unsubscribe();
502
- };
503
-
504
- // Set up timeout
505
- timeoutId = setTimeout(() => {
506
- cleanup();
507
- reject(new WaitForRunTimeoutError(runId, timeout));
508
- }, timeout);
509
-
510
- // Subscribe to run events
511
- unsubscribe = this.events.subscribe(runId, async (event) => {
512
- if (WorkflowEngine.TERMINAL_EVENT_TYPES.includes(event.eventType)) {
513
- cleanup();
514
- try {
515
- const run = await this.storage.getRun(runId);
516
- if (!run) {
517
- reject(new RunNotFoundError(runId));
518
- } else {
519
- resolve(run);
520
- }
521
- } catch (err) {
522
- reject(err);
523
- }
524
- }
525
- });
526
- });
527
- }
528
-
529
- // ============================================================================
530
- // Resume Support
531
- // ============================================================================
532
-
533
- /**
534
- * Resume an interrupted workflow run from its checkpoint.
535
- * The run must be in 'queued' or 'running' status.
536
- *
537
- * @param runId - The run ID to resume
538
- * @returns The run ID (same as input)
539
- * @throws {RunNotFoundError} If no run with the given ID exists
540
- * @throws {Error} If the run status is not 'queued' or 'running'
541
- * @throws {WorkflowNotFoundError} If the workflow kind is not registered
542
- */
543
- async resumeRun(runId: string): Promise<string> {
544
- const run = await this.storage.getRun(runId);
545
- if (!run) {
546
- throw new RunNotFoundError(runId);
547
- }
548
-
549
- // Check if run can be resumed
550
- if (!['queued', 'running'].includes(run.status)) {
551
- throw new Error(`Cannot resume run ${runId}: status is "${run.status}"`);
552
- }
553
-
554
- // Get the workflow definition
555
- const definition = this.registry.get(run.kind);
556
- if (!definition) {
557
- throw new WorkflowNotFoundError(run.kind);
558
- }
559
-
560
- // Check if already being executed
561
- if (this.activeRuns.has(runId)) {
562
- this.logger.warn(`Run ${runId} is already active, skipping resume`);
563
- return runId;
564
- }
565
-
566
- this.logger.info(`Resuming run ${runId} from checkpoint`);
567
-
568
- // Get completed step keys from the dedicated completedSteps field
569
- const completedStepKeys = new Set(run.completedSteps ?? []);
570
-
571
- this.launchRun(runId, definition, run.input, run.metadata, undefined, {
572
- completedStepKeys,
573
- results: run.context,
574
- });
575
-
576
- return runId;
577
- }
578
-
579
- /**
580
- * Get all runs that were interrupted and can be resumed.
581
- * Returns runs with status 'queued' or 'running'.
582
- */
583
- async getResumableRuns(): Promise<WorkflowRunRecord[]> {
584
- const result = await this.storage.listRuns({
585
- status: ['queued', 'running'],
586
- });
587
- return result.items;
588
- }
589
-
590
- /**
591
- * Resume all interrupted runs.
592
- * Useful for recovering after a server restart.
593
- *
594
- * @returns Array of resumed run IDs
595
- */
596
- async resumeAllInterrupted(): Promise<string[]> {
597
- const resumableRuns = await this.getResumableRuns();
598
- const resumedIds: string[] = [];
599
-
600
- for (const run of resumableRuns) {
601
- // Only resume if the workflow is registered
602
- if (this.registry.has(run.kind)) {
603
- try {
604
- await this.resumeRun(run.id);
605
- resumedIds.push(run.id);
606
- } catch (error) {
607
- this.logger.error(`Failed to resume run ${run.id}:`, error);
608
- }
609
- } else {
610
- this.logger.warn(`Cannot resume run ${run.id}: workflow "${run.kind}" not registered`);
611
- }
612
- }
613
-
614
- return resumedIds;
615
- }
616
-
617
- // ============================================================================
618
- // Event Subscription
619
- // ============================================================================
620
-
621
- /**
622
- * Subscribe to events for a specific run.
623
- *
624
- * @param runId - The run ID to subscribe to
625
- * @param callback - Event handler
626
- * @returns Unsubscribe function
627
- */
628
- subscribeToRun(runId: string, callback: EventCallback): Unsubscribe {
629
- return this.events.subscribe(runId, callback);
630
- }
631
-
632
- /**
633
- * Subscribe to all workflow events.
634
- *
635
- * @param callback - Event handler
636
- * @returns Unsubscribe function
637
- */
638
- subscribeToAll(callback: EventCallback): Unsubscribe {
639
- return this.events.subscribeAll(callback);
640
- }
641
-
642
- // ============================================================================
643
- // Storage Access
644
- // ============================================================================
645
-
646
- /**
647
- * Get the storage adapter.
648
- * Useful for querying runs and steps directly.
649
- */
650
- getStorage(): StorageAdapter {
651
- return this.storage;
652
- }
653
-
654
- /**
655
- * Get the event transport.
656
- * Useful for custom event handling.
657
- */
658
- getEvents(): EventTransport {
659
- return this.events;
660
- }
661
-
662
- // ============================================================================
663
- // Lifecycle
664
- // ============================================================================
665
-
666
- /**
667
- * Shutdown the engine gracefully.
668
- * Cancels all active runs and closes resources.
669
- */
670
- async shutdown(): Promise<void> {
671
- this.logger.info('Shutting down workflow engine...');
672
-
673
- // Cancel all active runs
674
- for (const [runId, controller] of this.activeRuns) {
675
- this.logger.debug(`Canceling active run: ${runId}`);
676
- controller.abort();
677
- }
678
-
679
- // Close event transport
680
- if (this.events.close) {
681
- this.events.close();
682
- }
683
-
684
- // Close storage adapter
685
- if (this.storage.close) {
686
- await this.storage.close();
687
- }
688
-
689
- this.activeRuns.clear();
690
- this.logger.info('Workflow engine shutdown complete');
691
- }
692
- }
package/src/core/index.ts DELETED
@@ -1,7 +0,0 @@
1
- /**
2
- * Core module exports.
3
- */
4
-
5
- export * from './types';
6
- export * from './engine';
7
- export * from './orchestrator';