@tasker-systems/tasker 0.1.0-alpha.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.
@@ -0,0 +1,1349 @@
1
+ import { EventEmitter } from 'eventemitter3';
2
+ import { l as FfiStepEvent, p as StepExecutionResult, k as FfiDispatchMetrics, T as TaskerRuntime } from './runtime-interface-CE4viUt7.js';
3
+
4
+ /**
5
+ * Event emitter for TypeScript workers.
6
+ *
7
+ * Provides a type-safe event emitter wrapper that works across
8
+ * all supported runtimes (Bun, Node.js, Deno).
9
+ */
10
+
11
+ /**
12
+ * Event payload types
13
+ */
14
+ interface StepExecutionReceivedPayload {
15
+ event: FfiStepEvent;
16
+ receivedAt: Date;
17
+ }
18
+ interface StepExecutionStartedPayload {
19
+ eventId: string;
20
+ stepUuid: string;
21
+ taskUuid: string;
22
+ handlerName: string;
23
+ startedAt: Date;
24
+ }
25
+ interface StepExecutionCompletedPayload {
26
+ eventId: string;
27
+ stepUuid: string;
28
+ taskUuid: string;
29
+ result: StepExecutionResult;
30
+ executionTimeMs: number;
31
+ completedAt: Date;
32
+ }
33
+ interface StepExecutionFailedPayload {
34
+ eventId: string;
35
+ stepUuid: string;
36
+ taskUuid: string;
37
+ error: Error;
38
+ failedAt: Date;
39
+ }
40
+ interface StepCompletionSentPayload {
41
+ eventId: string;
42
+ stepUuid: string;
43
+ success: boolean;
44
+ sentAt: Date;
45
+ }
46
+ /** TAS-125: Checkpoint yield event payload */
47
+ interface StepCheckpointYieldSentPayload {
48
+ eventId: string;
49
+ stepUuid: string;
50
+ cursor: unknown;
51
+ itemsProcessed: number;
52
+ timestamp: Date;
53
+ }
54
+ interface WorkerEventPayload {
55
+ workerId?: string;
56
+ timestamp: Date;
57
+ message?: string;
58
+ }
59
+ interface WorkerErrorPayload {
60
+ error: Error;
61
+ timestamp: Date;
62
+ context?: Record<string, unknown>;
63
+ }
64
+ interface PollerCyclePayload {
65
+ eventsProcessed: number;
66
+ cycleNumber: number;
67
+ timestamp: Date;
68
+ }
69
+ interface MetricsPayload {
70
+ metrics: FfiDispatchMetrics;
71
+ timestamp: Date;
72
+ }
73
+ /**
74
+ * Event map for type-safe event handling
75
+ */
76
+ interface TaskerEventMap {
77
+ 'step.execution.received': StepExecutionReceivedPayload;
78
+ 'step.execution.started': StepExecutionStartedPayload;
79
+ 'step.execution.completed': StepExecutionCompletedPayload;
80
+ 'step.execution.failed': StepExecutionFailedPayload;
81
+ 'step.completion.sent': StepCompletionSentPayload;
82
+ 'step.execution.timeout': StepExecutionFailedPayload;
83
+ 'step.checkpoint_yield.sent': StepCheckpointYieldSentPayload;
84
+ 'worker.started': WorkerEventPayload;
85
+ 'worker.ready': WorkerEventPayload;
86
+ 'worker.shutdown.started': WorkerEventPayload;
87
+ 'worker.stopped': WorkerEventPayload;
88
+ 'worker.error': WorkerErrorPayload;
89
+ 'poller.started': WorkerEventPayload;
90
+ 'poller.stopped': WorkerEventPayload;
91
+ 'poller.cycle.complete': PollerCyclePayload;
92
+ 'poller.starvation.detected': MetricsPayload;
93
+ 'poller.error': WorkerErrorPayload;
94
+ 'metrics.updated': MetricsPayload;
95
+ 'metrics.error': WorkerErrorPayload;
96
+ }
97
+ /**
98
+ * Type-safe event emitter for Tasker events
99
+ */
100
+ declare class TaskerEventEmitter extends EventEmitter<TaskerEventMap> {
101
+ private readonly instanceId;
102
+ constructor();
103
+ /**
104
+ * Get the unique instance ID for this emitter
105
+ */
106
+ getInstanceId(): string;
107
+ /**
108
+ * Emit a step execution received event
109
+ */
110
+ emitStepReceived(event: FfiStepEvent): void;
111
+ /**
112
+ * Emit a step execution started event
113
+ */
114
+ emitStepStarted(eventId: string, stepUuid: string, taskUuid: string, handlerName: string): void;
115
+ /**
116
+ * Emit a step execution completed event
117
+ */
118
+ emitStepCompleted(eventId: string, stepUuid: string, taskUuid: string, result: StepExecutionResult, executionTimeMs: number): void;
119
+ /**
120
+ * Emit a step execution failed event
121
+ */
122
+ emitStepFailed(eventId: string, stepUuid: string, taskUuid: string, error: Error): void;
123
+ /**
124
+ * Emit a step completion sent event
125
+ */
126
+ emitCompletionSent(eventId: string, stepUuid: string, success: boolean): void;
127
+ /**
128
+ * Emit a worker started event
129
+ */
130
+ emitWorkerStarted(workerId?: string): void;
131
+ /**
132
+ * Emit a worker ready event
133
+ */
134
+ emitWorkerReady(workerId?: string): void;
135
+ /**
136
+ * Emit a worker shutdown started event
137
+ */
138
+ emitWorkerShutdownStarted(workerId?: string): void;
139
+ /**
140
+ * Emit a worker stopped event
141
+ */
142
+ emitWorkerStopped(workerId?: string): void;
143
+ /**
144
+ * Emit a worker error event
145
+ */
146
+ emitWorkerError(error: Error, context?: Record<string, unknown>): void;
147
+ /**
148
+ * Emit a metrics updated event
149
+ */
150
+ emitMetricsUpdated(metrics: FfiDispatchMetrics): void;
151
+ /**
152
+ * Emit a starvation detected event
153
+ */
154
+ emitStarvationDetected(metrics: FfiDispatchMetrics): void;
155
+ }
156
+
157
+ /**
158
+ * Standard event names for the TypeScript worker.
159
+ *
160
+ * These constants provide type-safe event names that match
161
+ * the event system used by other language workers.
162
+ */
163
+ /**
164
+ * Event names for step execution lifecycle
165
+ */
166
+ declare const StepEventNames: {
167
+ /** Emitted when a step execution event is received from the FFI layer */
168
+ readonly STEP_EXECUTION_RECEIVED: "step.execution.received";
169
+ /** Emitted when a step handler starts executing */
170
+ readonly STEP_EXECUTION_STARTED: "step.execution.started";
171
+ /** Emitted when a step handler completes successfully */
172
+ readonly STEP_EXECUTION_COMPLETED: "step.execution.completed";
173
+ /** Emitted when a step handler fails */
174
+ readonly STEP_EXECUTION_FAILED: "step.execution.failed";
175
+ /** Emitted when a step completion is sent back to Rust */
176
+ readonly STEP_COMPLETION_SENT: "step.completion.sent";
177
+ /** Emitted when a step handler times out */
178
+ readonly STEP_EXECUTION_TIMEOUT: "step.execution.timeout";
179
+ /** TAS-125: Emitted when a checkpoint yield is sent back to Rust */
180
+ readonly STEP_CHECKPOINT_YIELD_SENT: "step.checkpoint_yield.sent";
181
+ };
182
+ /**
183
+ * Event names for worker lifecycle
184
+ */
185
+ declare const WorkerEventNames: {
186
+ /** Emitted when the worker starts up */
187
+ readonly WORKER_STARTED: "worker.started";
188
+ /** Emitted when the worker is ready to process events */
189
+ readonly WORKER_READY: "worker.ready";
190
+ /** Emitted when graceful shutdown begins */
191
+ readonly WORKER_SHUTDOWN_STARTED: "worker.shutdown.started";
192
+ /** Emitted when the worker has fully stopped */
193
+ readonly WORKER_STOPPED: "worker.stopped";
194
+ /** Emitted when the worker encounters an error */
195
+ readonly WORKER_ERROR: "worker.error";
196
+ };
197
+ /**
198
+ * Event names for polling lifecycle
199
+ */
200
+ declare const PollerEventNames: {
201
+ /** Emitted when the poller starts */
202
+ readonly POLLER_STARTED: "poller.started";
203
+ /** Emitted when the poller stops */
204
+ readonly POLLER_STOPPED: "poller.stopped";
205
+ /** Emitted when a poll cycle completes */
206
+ readonly POLLER_CYCLE_COMPLETE: "poller.cycle.complete";
207
+ /** Emitted when starvation is detected */
208
+ readonly POLLER_STARVATION_DETECTED: "poller.starvation.detected";
209
+ /** Emitted when the poller encounters an error */
210
+ readonly POLLER_ERROR: "poller.error";
211
+ };
212
+ /**
213
+ * Event names for metrics
214
+ */
215
+ declare const MetricsEventNames: {
216
+ /** Emitted periodically with FFI dispatch metrics */
217
+ readonly METRICS_UPDATED: "metrics.updated";
218
+ /** Emitted when metrics collection fails */
219
+ readonly METRICS_ERROR: "metrics.error";
220
+ };
221
+ /**
222
+ * All event names combined
223
+ */
224
+ declare const EventNames: {
225
+ /** Emitted periodically with FFI dispatch metrics */
226
+ readonly METRICS_UPDATED: "metrics.updated";
227
+ /** Emitted when metrics collection fails */
228
+ readonly METRICS_ERROR: "metrics.error";
229
+ /** Emitted when the poller starts */
230
+ readonly POLLER_STARTED: "poller.started";
231
+ /** Emitted when the poller stops */
232
+ readonly POLLER_STOPPED: "poller.stopped";
233
+ /** Emitted when a poll cycle completes */
234
+ readonly POLLER_CYCLE_COMPLETE: "poller.cycle.complete";
235
+ /** Emitted when starvation is detected */
236
+ readonly POLLER_STARVATION_DETECTED: "poller.starvation.detected";
237
+ /** Emitted when the poller encounters an error */
238
+ readonly POLLER_ERROR: "poller.error";
239
+ /** Emitted when the worker starts up */
240
+ readonly WORKER_STARTED: "worker.started";
241
+ /** Emitted when the worker is ready to process events */
242
+ readonly WORKER_READY: "worker.ready";
243
+ /** Emitted when graceful shutdown begins */
244
+ readonly WORKER_SHUTDOWN_STARTED: "worker.shutdown.started";
245
+ /** Emitted when the worker has fully stopped */
246
+ readonly WORKER_STOPPED: "worker.stopped";
247
+ /** Emitted when the worker encounters an error */
248
+ readonly WORKER_ERROR: "worker.error";
249
+ /** Emitted when a step execution event is received from the FFI layer */
250
+ readonly STEP_EXECUTION_RECEIVED: "step.execution.received";
251
+ /** Emitted when a step handler starts executing */
252
+ readonly STEP_EXECUTION_STARTED: "step.execution.started";
253
+ /** Emitted when a step handler completes successfully */
254
+ readonly STEP_EXECUTION_COMPLETED: "step.execution.completed";
255
+ /** Emitted when a step handler fails */
256
+ readonly STEP_EXECUTION_FAILED: "step.execution.failed";
257
+ /** Emitted when a step completion is sent back to Rust */
258
+ readonly STEP_COMPLETION_SENT: "step.completion.sent";
259
+ /** Emitted when a step handler times out */
260
+ readonly STEP_EXECUTION_TIMEOUT: "step.execution.timeout";
261
+ /** TAS-125: Emitted when a checkpoint yield is sent back to Rust */
262
+ readonly STEP_CHECKPOINT_YIELD_SENT: "step.checkpoint_yield.sent";
263
+ };
264
+ /**
265
+ * Type representing all possible event names
266
+ */
267
+ type EventName = (typeof EventNames)[keyof typeof EventNames];
268
+ /**
269
+ * Type representing step event names
270
+ */
271
+ type StepEventName = (typeof StepEventNames)[keyof typeof StepEventNames];
272
+ /**
273
+ * Type representing worker event names
274
+ */
275
+ type WorkerEventName = (typeof WorkerEventNames)[keyof typeof WorkerEventNames];
276
+ /**
277
+ * Type representing poller event names
278
+ */
279
+ type PollerEventName = (typeof PollerEventNames)[keyof typeof PollerEventNames];
280
+ /**
281
+ * Type representing metrics event names
282
+ */
283
+ type MetricsEventName = (typeof MetricsEventNames)[keyof typeof MetricsEventNames];
284
+
285
+ /**
286
+ * Event poller for TypeScript workers.
287
+ *
288
+ * Provides a polling loop that retrieves step events from the Rust FFI layer
289
+ * and dispatches them to registered handlers. Uses a 10ms polling interval
290
+ * matching other language workers.
291
+ */
292
+
293
+ /**
294
+ * Configuration for the event poller
295
+ */
296
+ interface EventPollerConfig$1 {
297
+ /** Polling interval in milliseconds (default: 10) */
298
+ pollIntervalMs?: number;
299
+ /** Number of polls between starvation checks (default: 100) */
300
+ starvationCheckInterval?: number;
301
+ /** Number of polls between cleanup operations (default: 1000) */
302
+ cleanupInterval?: number;
303
+ /** Number of polls between metrics emissions (default: 100) */
304
+ metricsInterval?: number;
305
+ /** Maximum events to process per poll cycle (default: 100) */
306
+ maxEventsPerCycle?: number;
307
+ }
308
+ /**
309
+ * Callback for step event handling
310
+ */
311
+ type StepEventCallback = (event: FfiStepEvent) => Promise<void>;
312
+ /**
313
+ * Callback for error handling
314
+ */
315
+ type ErrorCallback = (error: Error) => void;
316
+ /**
317
+ * Callback for metrics handling
318
+ */
319
+ type MetricsCallback = (metrics: FfiDispatchMetrics) => void;
320
+ /**
321
+ * Event poller state
322
+ */
323
+ type PollerState = 'stopped' | 'running' | 'stopping';
324
+ /**
325
+ * Event poller for retrieving and dispatching step events from the FFI layer.
326
+ *
327
+ * The poller runs a continuous loop that:
328
+ * 1. Polls for step events at 10ms intervals
329
+ * 2. Dispatches received events to registered handlers
330
+ * 3. Periodically checks for starvation conditions
331
+ * 4. Performs cleanup of timed-out events
332
+ * 5. Emits metrics for monitoring
333
+ */
334
+ declare class EventPoller {
335
+ private readonly runtime;
336
+ private readonly config;
337
+ private readonly emitter;
338
+ private state;
339
+ private pollCount;
340
+ private cycleCount;
341
+ private intervalId;
342
+ private stepEventCallback;
343
+ private errorCallback;
344
+ private metricsCallback;
345
+ /**
346
+ * Create a new EventPoller.
347
+ *
348
+ * @param runtime - The FFI runtime for polling events
349
+ * @param emitter - The event emitter to dispatch events to (required, no fallback)
350
+ * @param config - Optional configuration for polling behavior
351
+ */
352
+ constructor(runtime: TaskerRuntime, emitter: TaskerEventEmitter, config?: EventPollerConfig$1);
353
+ /**
354
+ * Get the current poller state
355
+ */
356
+ getState(): PollerState;
357
+ /**
358
+ * Check if the poller is running
359
+ */
360
+ isRunning(): boolean;
361
+ /**
362
+ * Get the total number of polls executed
363
+ */
364
+ getPollCount(): number;
365
+ /**
366
+ * Get the total number of cycles completed
367
+ */
368
+ getCycleCount(): number;
369
+ /**
370
+ * Register a callback for step events
371
+ */
372
+ onStepEvent(callback: StepEventCallback): this;
373
+ /**
374
+ * Register a callback for errors
375
+ */
376
+ onError(callback: ErrorCallback): this;
377
+ /**
378
+ * Register a callback for metrics
379
+ */
380
+ onMetrics(callback: MetricsCallback): this;
381
+ /**
382
+ * Start the polling loop
383
+ */
384
+ start(): void;
385
+ /**
386
+ * Stop the polling loop
387
+ */
388
+ stop(): Promise<void>;
389
+ /**
390
+ * Execute a single poll cycle
391
+ */
392
+ private poll;
393
+ /**
394
+ * Handle a step event
395
+ */
396
+ private handleStepEvent;
397
+ /**
398
+ * Check for starvation conditions
399
+ */
400
+ private checkStarvation;
401
+ /**
402
+ * Emit current metrics
403
+ */
404
+ private emitMetrics;
405
+ /**
406
+ * Handle an error
407
+ */
408
+ private handleError;
409
+ }
410
+ /**
411
+ * Create an event poller with the given runtime, emitter, and configuration
412
+ */
413
+ declare function createEventPoller(runtime: TaskerRuntime, emitter: TaskerEventEmitter, config?: EventPollerConfig$1): EventPoller;
414
+
415
+ /**
416
+ * Standard error types for cross-language consistency.
417
+ *
418
+ * These values align with Ruby and Python worker implementations
419
+ * and are used by the orchestration layer for retry decisions.
420
+ *
421
+ * @see TAS-92 Cross-Language API Alignment
422
+ */
423
+ declare enum ErrorType {
424
+ /**
425
+ * Permanent, non-recoverable failure.
426
+ * Examples: invalid input, resource not found, authentication failure.
427
+ */
428
+ PERMANENT_ERROR = "permanent_error",
429
+ /**
430
+ * Transient failure that may succeed on retry.
431
+ * Examples: network timeout, service unavailable, rate limiting.
432
+ */
433
+ RETRYABLE_ERROR = "retryable_error",
434
+ /**
435
+ * Input validation failure.
436
+ * Examples: missing required field, invalid format, constraint violation.
437
+ */
438
+ VALIDATION_ERROR = "validation_error",
439
+ /**
440
+ * Operation timed out.
441
+ * Examples: HTTP request timeout, database query timeout.
442
+ */
443
+ TIMEOUT = "timeout",
444
+ /**
445
+ * Failure within the step handler itself.
446
+ * Examples: unhandled exception, handler misconfiguration.
447
+ */
448
+ HANDLER_ERROR = "handler_error"
449
+ }
450
+ /**
451
+ * Check if an error type is one of the standard values.
452
+ *
453
+ * @param errorType - The error type string to check
454
+ * @returns True if the error type matches one of the standard values
455
+ *
456
+ * @example
457
+ * isStandardErrorType('permanent_error'); // true
458
+ * isStandardErrorType('custom_error'); // false
459
+ */
460
+ declare function isStandardErrorType(errorType: string): boolean;
461
+ /**
462
+ * Get the recommended retryable flag for a given error type.
463
+ *
464
+ * @param errorType - The error type string
465
+ * @returns True if the error type is typically retryable
466
+ *
467
+ * @example
468
+ * isTypicallyRetryable('timeout'); // true
469
+ * isTypicallyRetryable('permanent_error'); // false
470
+ */
471
+ declare function isTypicallyRetryable(errorType: string): boolean;
472
+
473
+ /**
474
+ * Parameters for constructing a StepContext.
475
+ */
476
+ interface StepContextParams {
477
+ event: FfiStepEvent;
478
+ taskUuid: string;
479
+ stepUuid: string;
480
+ correlationId: string;
481
+ handlerName: string;
482
+ inputData: Record<string, unknown>;
483
+ dependencyResults: Record<string, unknown>;
484
+ stepConfig: Record<string, unknown>;
485
+ stepInputs: Record<string, unknown>;
486
+ retryCount: number;
487
+ maxRetries: number;
488
+ }
489
+ /**
490
+ * Context provided to step handlers during execution.
491
+ *
492
+ * Contains all information needed for a step handler to execute,
493
+ * including input data, dependency results, and configuration.
494
+ *
495
+ * Matches Python's StepContext and Ruby's StepContext (post-TAS-96).
496
+ *
497
+ * @example
498
+ * ```typescript
499
+ * class MyHandler extends StepHandler {
500
+ * async call(context: StepContext): Promise<StepHandlerResult> {
501
+ * const orderId = context.inputData['order_id'];
502
+ * const previousResult = context.getDependencyResult('step_1');
503
+ * // ... handler logic ...
504
+ * return this.success({ processed: true });
505
+ * }
506
+ * }
507
+ * ```
508
+ */
509
+ declare class StepContext {
510
+ /** The original FFI step event */
511
+ readonly event: FfiStepEvent;
512
+ /** Task UUID */
513
+ readonly taskUuid: string;
514
+ /** Step UUID */
515
+ readonly stepUuid: string;
516
+ /** Correlation ID for tracing */
517
+ readonly correlationId: string;
518
+ /** Name of the handler being executed */
519
+ readonly handlerName: string;
520
+ /** Input data for the handler (from task context) */
521
+ readonly inputData: Record<string, unknown>;
522
+ /** Results from dependent steps */
523
+ readonly dependencyResults: Record<string, unknown>;
524
+ /** Handler-specific configuration (from step_definition.handler.initialization) */
525
+ readonly stepConfig: Record<string, unknown>;
526
+ /** Step-specific inputs (from workflow_step.inputs, used for batch cursor config) */
527
+ readonly stepInputs: Record<string, unknown>;
528
+ /** Current retry attempt number */
529
+ readonly retryCount: number;
530
+ /** Maximum retry attempts allowed */
531
+ readonly maxRetries: number;
532
+ constructor(params: StepContextParams);
533
+ /**
534
+ * Create a StepContext from an FFI event.
535
+ *
536
+ * Extracts input data, dependency results, and configuration from
537
+ * the task_sequence_step payload.
538
+ *
539
+ * The FFI data structure mirrors the Ruby TaskSequenceStepWrapper:
540
+ * - task.context -> inputData (task context with user inputs)
541
+ * - dependency_results -> results from parent steps
542
+ * - step_definition.handler.initialization -> stepConfig
543
+ * - workflow_step.attempts -> retryCount
544
+ * - workflow_step.max_attempts -> maxRetries
545
+ * - workflow_step.inputs -> stepInputs
546
+ *
547
+ * @param event - The FFI step event
548
+ * @param handlerName - Name of the handler to execute
549
+ * @returns A StepContext populated from the event
550
+ */
551
+ static fromFfiEvent(event: FfiStepEvent, handlerName: string): StepContext;
552
+ /**
553
+ * Get the computed result value from a dependency step.
554
+ *
555
+ * This method extracts the actual computed value from a dependency result,
556
+ * unwrapping any nested structure. Matches Python's get_dependency_result().
557
+ *
558
+ * The dependency result structure can be:
559
+ * - {"result": actual_value} - unwraps to actual_value
560
+ * - primitive value - returns as-is
561
+ *
562
+ * @param stepName - Name of the dependency step
563
+ * @returns The computed result value, or null if not found
564
+ *
565
+ * @example
566
+ * ```typescript
567
+ * // Instead of:
568
+ * const step1Result = context.dependencyResults['step_1'] || {};
569
+ * const value = step1Result.result; // Might be nested!
570
+ *
571
+ * // Use:
572
+ * const value = context.getDependencyResult('step_1'); // Unwrapped
573
+ * ```
574
+ */
575
+ getDependencyResult(stepName: string): unknown;
576
+ /**
577
+ * Get a value from the input data.
578
+ *
579
+ * @param key - The key to look up in inputData
580
+ * @returns The value or undefined if not found
581
+ */
582
+ getInput<T = unknown>(key: string): T | undefined;
583
+ /**
584
+ * Get a value from the step configuration.
585
+ *
586
+ * @param key - The key to look up in stepConfig
587
+ * @returns The value or undefined if not found
588
+ */
589
+ getConfig<T = unknown>(key: string): T | undefined;
590
+ /**
591
+ * Check if this is a retry attempt.
592
+ *
593
+ * @returns True if retryCount > 0
594
+ */
595
+ isRetry(): boolean;
596
+ /**
597
+ * Check if this is the last allowed retry attempt.
598
+ *
599
+ * @returns True if retryCount >= maxRetries - 1
600
+ */
601
+ isLastRetry(): boolean;
602
+ /**
603
+ * Get a value from the input data with a default.
604
+ *
605
+ * @param key - The key to look up in inputData
606
+ * @param defaultValue - Value to return if key not found or undefined
607
+ * @returns The value or default if not found/undefined
608
+ *
609
+ * @example
610
+ * ```typescript
611
+ * const batchSize = context.getInputOr('batch_size', 100);
612
+ * ```
613
+ */
614
+ getInputOr<T = unknown>(key: string, defaultValue: T): T;
615
+ /**
616
+ * Extract a nested field from a dependency result.
617
+ *
618
+ * Useful when dependency results are complex objects and you need
619
+ * to extract a specific nested value without manual object traversal.
620
+ *
621
+ * @param stepName - Name of the dependency step
622
+ * @param path - Path elements to traverse into the result
623
+ * @returns The nested value, or null if not found
624
+ *
625
+ * @example
626
+ * ```typescript
627
+ * // Extract nested field from dependency result
628
+ * const csvPath = context.getDependencyField('analyze_csv', 'csv_file_path');
629
+ * // Multiple levels deep
630
+ * const value = context.getDependencyField('step_1', 'data', 'items');
631
+ * ```
632
+ */
633
+ getDependencyField(stepName: string, ...path: string[]): unknown;
634
+ /**
635
+ * Get the raw checkpoint data from the workflow step.
636
+ *
637
+ * @returns The checkpoint data object or null if not set
638
+ */
639
+ get checkpoint(): Record<string, unknown> | null;
640
+ /**
641
+ * Get the checkpoint cursor position.
642
+ *
643
+ * The cursor represents the current position in batch processing,
644
+ * allowing handlers to resume from where they left off.
645
+ *
646
+ * @returns The cursor value (number, string, or object) or null if not set
647
+ *
648
+ * @example
649
+ * ```typescript
650
+ * const cursor = context.checkpointCursor;
651
+ * const startFrom = cursor ?? 0;
652
+ * ```
653
+ */
654
+ get checkpointCursor(): unknown;
655
+ /**
656
+ * Get the number of items processed in the current batch run.
657
+ *
658
+ * @returns Number of items processed (0 if no checkpoint)
659
+ */
660
+ get checkpointItemsProcessed(): number;
661
+ /**
662
+ * Get the accumulated results from batch processing.
663
+ *
664
+ * Accumulated results allow handlers to maintain running totals
665
+ * or aggregated state across checkpoint boundaries.
666
+ *
667
+ * @returns The accumulated results object or null if not set
668
+ *
669
+ * @example
670
+ * ```typescript
671
+ * const totals = context.accumulatedResults ?? {};
672
+ * const currentSum = totals.sum ?? 0;
673
+ * ```
674
+ */
675
+ get accumulatedResults(): Record<string, unknown> | null;
676
+ /**
677
+ * Check if a checkpoint exists for this step.
678
+ *
679
+ * @returns True if a checkpoint cursor exists
680
+ *
681
+ * @example
682
+ * ```typescript
683
+ * if (context.hasCheckpoint()) {
684
+ * console.log(`Resuming from cursor: ${context.checkpointCursor}`);
685
+ * }
686
+ * ```
687
+ */
688
+ hasCheckpoint(): boolean;
689
+ /**
690
+ * Get all dependency result keys.
691
+ *
692
+ * @returns Array of step names that have dependency results
693
+ */
694
+ getDependencyResultKeys(): string[];
695
+ /**
696
+ * Get all dependency results matching a step name prefix.
697
+ *
698
+ * This is useful for batch processing where multiple worker steps
699
+ * share a common prefix (e.g., "process_batch_001", "process_batch_002").
700
+ *
701
+ * Returns the unwrapped result values (same as getDependencyResult).
702
+ *
703
+ * @param prefix - Step name prefix to match
704
+ * @returns Array of unwrapped result values from matching steps
705
+ *
706
+ * @example
707
+ * ```typescript
708
+ * // For batch worker results named: process_batch_001, process_batch_002, etc.
709
+ * const batchResults = context.getAllDependencyResults('process_batch_');
710
+ * const total = batchResults.reduce((sum, r) => sum + r.count, 0);
711
+ * ```
712
+ */
713
+ getAllDependencyResults(prefix: string): unknown[];
714
+ }
715
+
716
+ /**
717
+ * Configuration for a batch worker instance.
718
+ *
719
+ * Used by batchable handlers to define the work partition for each worker.
720
+ */
721
+ interface BatchWorkerConfig {
722
+ /** Unique identifier for this batch */
723
+ batch_id: string;
724
+ /** Starting cursor position (inclusive) */
725
+ cursor_start: number;
726
+ /** Ending cursor position (exclusive) */
727
+ cursor_end: number;
728
+ /** Number of rows/items in this batch */
729
+ row_count: number;
730
+ /** Index of this worker (0-based) */
731
+ worker_index: number;
732
+ /** Total number of workers processing this data */
733
+ total_workers: number;
734
+ /** Optional additional metadata for this batch */
735
+ metadata?: Record<string, unknown>;
736
+ }
737
+ /**
738
+ * Parameters for constructing a StepHandlerResult.
739
+ */
740
+ interface StepHandlerResultParams {
741
+ success: boolean;
742
+ result?: Record<string, unknown> | null;
743
+ errorMessage?: string | null;
744
+ errorType?: string | null;
745
+ errorCode?: string | null;
746
+ retryable?: boolean;
747
+ metadata?: Record<string, unknown>;
748
+ }
749
+ /**
750
+ * Result from a step handler execution.
751
+ *
752
+ * Step handlers return this to indicate success or failure,
753
+ * along with any output data or error details.
754
+ *
755
+ * Matches Python's StepHandlerResult and Ruby's StepHandlerCallResult.
756
+ *
757
+ * @example Success case
758
+ * ```typescript
759
+ * return StepHandlerResult.success({ processed: 100 });
760
+ * ```
761
+ *
762
+ * @example Failure case
763
+ * ```typescript
764
+ * return StepHandlerResult.failure(
765
+ * 'Validation failed',
766
+ * ErrorType.VALIDATION_ERROR,
767
+ * false
768
+ * );
769
+ * ```
770
+ *
771
+ * @example Failure with error code
772
+ * ```typescript
773
+ * return StepHandlerResult.failure(
774
+ * 'Payment gateway timeout',
775
+ * ErrorType.TIMEOUT,
776
+ * true,
777
+ * { gateway: 'stripe' },
778
+ * 'GATEWAY_TIMEOUT'
779
+ * );
780
+ * ```
781
+ */
782
+ declare class StepHandlerResult {
783
+ /** Whether the handler executed successfully */
784
+ readonly success: boolean;
785
+ /** Handler output data (success case) */
786
+ readonly result: Record<string, unknown> | null;
787
+ /** Error message (failure case) */
788
+ readonly errorMessage: string | null;
789
+ /** Error type/category for classification */
790
+ readonly errorType: string | null;
791
+ /** Optional application-specific error code */
792
+ readonly errorCode: string | null;
793
+ /** Whether the error is retryable */
794
+ readonly retryable: boolean;
795
+ /** Additional execution metadata */
796
+ readonly metadata: Record<string, unknown>;
797
+ constructor(params: StepHandlerResultParams);
798
+ /**
799
+ * Create a successful handler result.
800
+ *
801
+ * This is the primary factory method for creating success results.
802
+ * Aligned with Ruby and Python worker APIs.
803
+ *
804
+ * @param result - The handler output data
805
+ * @param metadata - Optional additional metadata
806
+ * @returns A StepHandlerResult indicating success
807
+ *
808
+ * @example
809
+ * ```typescript
810
+ * return StepHandlerResult.success(
811
+ * { processed: 100, skipped: 5 }
812
+ * );
813
+ * ```
814
+ */
815
+ static success(result: Record<string, unknown>, metadata?: Record<string, unknown>): StepHandlerResult;
816
+ /**
817
+ * Create a failure handler result.
818
+ *
819
+ * @param message - Human-readable error message
820
+ * @param errorType - Error type/category for classification. Use ErrorType enum.
821
+ * @param retryable - Whether the error is retryable (default: true)
822
+ * @param metadata - Optional additional metadata
823
+ * @param errorCode - Optional application-specific error code
824
+ * @returns A StepHandlerResult indicating failure
825
+ *
826
+ * @example
827
+ * ```typescript
828
+ * return StepHandlerResult.failure(
829
+ * 'Invalid input format',
830
+ * ErrorType.VALIDATION_ERROR,
831
+ * false
832
+ * );
833
+ * ```
834
+ *
835
+ * @example With error code
836
+ * ```typescript
837
+ * return StepHandlerResult.failure(
838
+ * 'Gateway timeout',
839
+ * ErrorType.TIMEOUT,
840
+ * true,
841
+ * { duration_ms: 30000 },
842
+ * 'GATEWAY_TIMEOUT'
843
+ * );
844
+ * ```
845
+ */
846
+ static failure(message: string, errorType?: ErrorType | string, retryable?: boolean, metadata?: Record<string, unknown>, errorCode?: string): StepHandlerResult;
847
+ /**
848
+ * Check if this result indicates success.
849
+ */
850
+ isSuccess(): boolean;
851
+ /**
852
+ * Check if this result indicates failure.
853
+ */
854
+ isFailure(): boolean;
855
+ /**
856
+ * Convert to JSON for serialization.
857
+ *
858
+ * Uses snake_case keys to match the Rust FFI contract.
859
+ */
860
+ toJSON(): Record<string, unknown>;
861
+ }
862
+
863
+ /**
864
+ * Public interface for executable handlers (TAS-93).
865
+ *
866
+ * This interface defines the contract that all handlers must fulfill
867
+ * to be executed by the resolver chain. Both StepHandler and
868
+ * MethodDispatchWrapper implement this interface.
869
+ *
870
+ * Use this type when you need to accept either a handler or a wrapped handler.
871
+ */
872
+ interface ExecutableHandler {
873
+ /** Unique identifier for this handler */
874
+ readonly name: string;
875
+ /** Version string for the handler */
876
+ readonly version: string;
877
+ /** List of capability strings the handler supports */
878
+ readonly capabilities: string[];
879
+ /**
880
+ * Execute the step handler logic.
881
+ *
882
+ * @param context - Execution context with input data and configuration
883
+ * @returns Promise resolving to handler result
884
+ */
885
+ call(context: StepContext): Promise<StepHandlerResult>;
886
+ /**
887
+ * Return JSON schema for handler configuration.
888
+ *
889
+ * @returns JSON schema object, or null if no schema is defined
890
+ */
891
+ configSchema(): Record<string, unknown> | null;
892
+ }
893
+ /**
894
+ * Interface for step handler class metadata.
895
+ *
896
+ * Handler classes must implement these static properties.
897
+ */
898
+ interface StepHandlerClass {
899
+ /** Unique identifier for this handler. Must match step definition. */
900
+ handlerName: string;
901
+ /** Version string for the handler (default: "1.0.0") */
902
+ handlerVersion?: string;
903
+ /** Constructor that creates a handler instance */
904
+ new (): StepHandler;
905
+ }
906
+ /**
907
+ * Abstract base class for step handlers.
908
+ *
909
+ * All step handlers must extend this class and implement
910
+ * the `call` method. The handlerName static property must be set
911
+ * to a unique identifier for the handler.
912
+ *
913
+ * TAS-131: TypeScript handlers are async by default. The `call` method
914
+ * returns a Promise, enabling use of async/await for I/O operations
915
+ * like HTTP requests, database queries, and file operations.
916
+ *
917
+ * Matches Python's StepHandler and Ruby's StepHandler base classes.
918
+ *
919
+ * @example
920
+ * ```typescript
921
+ * class ProcessOrderHandler extends StepHandler {
922
+ * static handlerName = 'process_order';
923
+ * static handlerVersion = '1.0.0';
924
+ *
925
+ * async call(context: StepContext): Promise<StepHandlerResult> {
926
+ * const orderId = context.getInput<string>('order_id');
927
+ * // Can use async operations like fetch, database queries, etc.
928
+ * const data = await fetchOrderDetails(orderId);
929
+ * return this.success({ order_id: orderId, status: 'processed', data });
930
+ * }
931
+ * }
932
+ * ```
933
+ */
934
+ declare abstract class StepHandler {
935
+ /**
936
+ * Unique identifier for this handler.
937
+ * Must be set by subclasses and match the step definition.
938
+ */
939
+ static handlerName: string;
940
+ /**
941
+ * Version string for the handler.
942
+ * Default: "1.0.0"
943
+ */
944
+ static handlerVersion: string;
945
+ /**
946
+ * Execute the step handler logic.
947
+ *
948
+ * This method is called by the execution subscriber when a step
949
+ * event is received that matches this handler's name.
950
+ *
951
+ * @param context - Execution context with input data, dependency results,
952
+ * and configuration
953
+ * @returns Promise resolving to StepHandlerResult indicating success or failure
954
+ *
955
+ * @example
956
+ * ```typescript
957
+ * async call(context: StepContext): Promise<StepHandlerResult> {
958
+ * try {
959
+ * const result = await processData(context.inputData);
960
+ * return this.success(result);
961
+ * } catch (error) {
962
+ * return this.failure(
963
+ * error.message,
964
+ * ErrorType.HANDLER_ERROR,
965
+ * true
966
+ * );
967
+ * }
968
+ * }
969
+ * ```
970
+ */
971
+ abstract call(context: StepContext): Promise<StepHandlerResult>;
972
+ /**
973
+ * Get the handler name.
974
+ *
975
+ * @returns The handlerName static property, or the class name if not set
976
+ */
977
+ get name(): string;
978
+ /**
979
+ * Get the handler version.
980
+ *
981
+ * @returns The handlerVersion static property
982
+ */
983
+ get version(): string;
984
+ /**
985
+ * Return handler capabilities.
986
+ *
987
+ * Override this to advertise specific capabilities for handler selection.
988
+ *
989
+ * @returns List of capability strings (default: ["process"])
990
+ */
991
+ get capabilities(): string[];
992
+ /**
993
+ * Return JSON schema for handler configuration.
994
+ *
995
+ * Override this to provide a schema for validating step_config.
996
+ *
997
+ * @returns JSON schema object, or null if no schema is defined
998
+ */
999
+ configSchema(): Record<string, unknown> | null;
1000
+ /**
1001
+ * Create a success result.
1002
+ *
1003
+ * Convenience method for creating success results.
1004
+ *
1005
+ * @param result - Result data object
1006
+ * @param metadata - Optional metadata object
1007
+ * @returns StepHandlerResult with success=true
1008
+ *
1009
+ * @example
1010
+ * ```typescript
1011
+ * return this.success({ processed: 100 });
1012
+ * ```
1013
+ */
1014
+ protected success(result: Record<string, unknown>, metadata?: Record<string, unknown>): StepHandlerResult;
1015
+ /**
1016
+ * Create a failure result.
1017
+ *
1018
+ * Convenience method for creating failure results.
1019
+ *
1020
+ * @param message - Error message
1021
+ * @param errorType - Error type classification. Use ErrorType enum for consistency.
1022
+ * @param retryable - Whether the error is retryable (default: true)
1023
+ * @param metadata - Optional metadata object
1024
+ * @param errorCode - Optional application-specific error code
1025
+ * @returns StepHandlerResult with success=false
1026
+ *
1027
+ * @example
1028
+ * ```typescript
1029
+ * return this.failure(
1030
+ * 'Invalid input',
1031
+ * ErrorType.VALIDATION_ERROR,
1032
+ * false
1033
+ * );
1034
+ * ```
1035
+ */
1036
+ protected failure(message: string, errorType?: ErrorType | string, retryable?: boolean, metadata?: Record<string, unknown>, errorCode?: string): StepHandlerResult;
1037
+ /**
1038
+ * Get a string representation of the handler.
1039
+ */
1040
+ toString(): string;
1041
+ }
1042
+
1043
+ /**
1044
+ * Step execution subscriber for TypeScript workers.
1045
+ *
1046
+ * Subscribes to step execution events from the EventPoller and dispatches
1047
+ * them to the appropriate handlers via the HandlerRegistry.
1048
+ *
1049
+ * Matches Python's StepExecutionSubscriber pattern (TAS-92 aligned).
1050
+ */
1051
+
1052
+ /**
1053
+ * Interface for handler registry required by StepExecutionSubscriber.
1054
+ *
1055
+ * TAS-93: Updated to support async resolution via ResolverChain.
1056
+ * Returns ExecutableHandler which includes both StepHandler and MethodDispatchWrapper.
1057
+ */
1058
+ interface HandlerRegistryInterface {
1059
+ /** Resolve and instantiate a handler by name (async for resolver chain support) */
1060
+ resolve(name: string): Promise<ExecutableHandler | null>;
1061
+ }
1062
+ /**
1063
+ * Configuration for the step execution subscriber.
1064
+ */
1065
+ interface StepExecutionSubscriberConfig {
1066
+ /** Worker ID for result attribution */
1067
+ workerId?: string;
1068
+ /** Maximum concurrent handler executions (default: 10) */
1069
+ maxConcurrent?: number;
1070
+ /** Handler execution timeout in milliseconds (default: 300000 = 5 minutes) */
1071
+ handlerTimeoutMs?: number;
1072
+ }
1073
+ /**
1074
+ * Subscribes to step execution events and dispatches them to handlers.
1075
+ *
1076
+ * This is the critical component that connects the FFI event stream
1077
+ * to TypeScript handler execution. It:
1078
+ * 1. Listens for step events from the EventPoller via EventEmitter
1079
+ * 2. Resolves the appropriate handler from the HandlerRegistry
1080
+ * 3. Creates a StepContext from the FFI event
1081
+ * 4. Executes the handler
1082
+ * 5. Submits the result back to Rust via FFI
1083
+ *
1084
+ * @example
1085
+ * ```typescript
1086
+ * const subscriber = new StepExecutionSubscriber(
1087
+ * eventEmitter,
1088
+ * handlerRegistry,
1089
+ * runtime,
1090
+ * { workerId: 'worker-1' }
1091
+ * );
1092
+ *
1093
+ * subscriber.start();
1094
+ *
1095
+ * // Later...
1096
+ * subscriber.stop();
1097
+ * ```
1098
+ */
1099
+ declare class StepExecutionSubscriber {
1100
+ private readonly emitter;
1101
+ private readonly registry;
1102
+ private readonly runtime;
1103
+ private readonly workerId;
1104
+ private readonly maxConcurrent;
1105
+ private readonly handlerTimeoutMs;
1106
+ private running;
1107
+ private activeHandlers;
1108
+ private processedCount;
1109
+ private errorCount;
1110
+ /**
1111
+ * Create a new StepExecutionSubscriber.
1112
+ *
1113
+ * @param emitter - The event emitter to subscribe to (required, no fallback)
1114
+ * @param registry - The handler registry for resolving step handlers
1115
+ * @param runtime - The FFI runtime for submitting results (required, no fallback)
1116
+ * @param config - Optional configuration for execution behavior
1117
+ */
1118
+ constructor(emitter: TaskerEventEmitter, registry: HandlerRegistryInterface, runtime: TaskerRuntime, config?: StepExecutionSubscriberConfig);
1119
+ /**
1120
+ * Start subscribing to step execution events.
1121
+ */
1122
+ start(): void;
1123
+ /**
1124
+ * Stop subscribing to step execution events.
1125
+ *
1126
+ * Note: Does not wait for in-flight handlers to complete.
1127
+ * Use waitForCompletion() if you need to wait.
1128
+ */
1129
+ stop(): void;
1130
+ /**
1131
+ * Check if the subscriber is running.
1132
+ */
1133
+ isRunning(): boolean;
1134
+ /**
1135
+ * Get the count of events processed.
1136
+ */
1137
+ getProcessedCount(): number;
1138
+ /**
1139
+ * Get the count of errors encountered.
1140
+ */
1141
+ getErrorCount(): number;
1142
+ /**
1143
+ * Get the count of currently active handlers.
1144
+ */
1145
+ getActiveHandlers(): number;
1146
+ /**
1147
+ * Wait for all active handlers to complete.
1148
+ *
1149
+ * @param timeoutMs - Maximum time to wait (default: 30000)
1150
+ * @returns True if all handlers completed, false if timeout
1151
+ */
1152
+ waitForCompletion(timeoutMs?: number): Promise<boolean>;
1153
+ /**
1154
+ * Handle a step execution event.
1155
+ */
1156
+ private handleEvent;
1157
+ /**
1158
+ * Process a step execution event.
1159
+ */
1160
+ private processEvent;
1161
+ /**
1162
+ * Execute a function with a timeout.
1163
+ */
1164
+ private executeWithTimeout;
1165
+ /**
1166
+ * Extract handler name from FFI event.
1167
+ *
1168
+ * The handler name is in step_definition.handler.callable
1169
+ */
1170
+ private extractHandlerName;
1171
+ /**
1172
+ * Submit a handler result via FFI.
1173
+ *
1174
+ * TAS-125: Detects checkpoint yields and routes them to checkpointYieldStepEvent
1175
+ * instead of the normal completion path.
1176
+ */
1177
+ private submitResult;
1178
+ /**
1179
+ * TAS-125: Submit a checkpoint yield via FFI.
1180
+ *
1181
+ * Called when a handler returns a checkpoint_yield result.
1182
+ * This persists the checkpoint and re-dispatches the step.
1183
+ */
1184
+ private submitCheckpointYield;
1185
+ /**
1186
+ * Submit an error result via FFI (for handler resolution/execution failures).
1187
+ */
1188
+ private submitErrorResult;
1189
+ /**
1190
+ * Build a StepExecutionResult from a handler result.
1191
+ *
1192
+ * IMPORTANT: metadata.retryable must be set for Rust's is_retryable() to work correctly.
1193
+ */
1194
+ private buildExecutionResult;
1195
+ /**
1196
+ * Build an error StepExecutionResult for handler resolution/execution failures.
1197
+ *
1198
+ * IMPORTANT: metadata.retryable must be set for Rust's is_retryable() to work correctly.
1199
+ */
1200
+ private buildErrorExecutionResult;
1201
+ /**
1202
+ * Send a completion result to Rust via FFI and handle the response.
1203
+ *
1204
+ * @returns true if the completion was accepted by Rust, false otherwise
1205
+ */
1206
+ private sendCompletionViaFfi;
1207
+ /**
1208
+ * Handle successful FFI completion submission.
1209
+ */
1210
+ private handleFfiSuccess;
1211
+ /**
1212
+ * Handle FFI completion rejection (event not in pending map).
1213
+ */
1214
+ private handleFfiRejection;
1215
+ /**
1216
+ * Handle FFI completion error.
1217
+ */
1218
+ private handleFfiError;
1219
+ }
1220
+
1221
+ /**
1222
+ * EventSystem - Unified event processing system for TypeScript workers.
1223
+ *
1224
+ * This class owns and manages the complete event flow:
1225
+ * - TaskerEventEmitter: Event bus for step events
1226
+ * - EventPoller: Polls FFI for step events, emits to emitter
1227
+ * - StepExecutionSubscriber: Subscribes to emitter, dispatches to handlers
1228
+ *
1229
+ * By owning all three components, EventSystem guarantees they share the
1230
+ * same emitter instance, eliminating reference sharing bugs.
1231
+ *
1232
+ * Design principles:
1233
+ * - Explicit construction: All dependencies injected via constructor
1234
+ * - Clear ownership: This class owns the emitter lifecycle
1235
+ * - Explicit lifecycle: start() and stop() methods with defined phases
1236
+ */
1237
+
1238
+ /**
1239
+ * Configuration for EventPoller within EventSystem.
1240
+ */
1241
+ interface EventPollerConfig {
1242
+ /** Polling interval in milliseconds (default: 10) */
1243
+ pollIntervalMs?: number;
1244
+ /** Number of polls between starvation checks (default: 100) */
1245
+ starvationCheckInterval?: number;
1246
+ /** Number of polls between cleanup operations (default: 1000) */
1247
+ cleanupInterval?: number;
1248
+ /** Number of polls between metrics emissions (default: 100) */
1249
+ metricsInterval?: number;
1250
+ /** Maximum events to process per poll cycle (default: 100) */
1251
+ maxEventsPerCycle?: number;
1252
+ }
1253
+ /**
1254
+ * Configuration for StepExecutionSubscriber within EventSystem.
1255
+ */
1256
+ interface SubscriberConfig {
1257
+ /** Unique identifier for this worker (default: typescript-worker-{pid}) */
1258
+ workerId?: string;
1259
+ /** Maximum number of concurrent handler executions (default: 10) */
1260
+ maxConcurrent?: number;
1261
+ /** Timeout for individual handler execution in milliseconds (default: 300000) */
1262
+ handlerTimeoutMs?: number;
1263
+ }
1264
+ /**
1265
+ * Complete configuration for EventSystem.
1266
+ */
1267
+ interface EventSystemConfig {
1268
+ /** Configuration for the event poller */
1269
+ poller?: EventPollerConfig;
1270
+ /** Configuration for the step execution subscriber */
1271
+ subscriber?: SubscriberConfig;
1272
+ }
1273
+ /**
1274
+ * Statistics about the event system's operation.
1275
+ */
1276
+ interface EventSystemStats {
1277
+ /** Whether the system is currently running */
1278
+ running: boolean;
1279
+ /** Total events processed by the subscriber */
1280
+ processedCount: number;
1281
+ /** Total errors encountered during processing */
1282
+ errorCount: number;
1283
+ /** Number of currently active handler executions */
1284
+ activeHandlers: number;
1285
+ /** Total poll cycles executed */
1286
+ pollCount: number;
1287
+ }
1288
+ /**
1289
+ * Unified event processing system.
1290
+ *
1291
+ * Owns the complete event flow: emitter → poller → subscriber.
1292
+ * Guarantees all components share the same emitter instance.
1293
+ *
1294
+ * @example
1295
+ * ```typescript
1296
+ * const eventSystem = new EventSystem(runtime, registry, {
1297
+ * poller: { pollIntervalMs: 10 },
1298
+ * subscriber: { workerId: 'worker-1', maxConcurrent: 10 },
1299
+ * });
1300
+ *
1301
+ * eventSystem.start();
1302
+ * // ... processing events ...
1303
+ * await eventSystem.stop();
1304
+ * ```
1305
+ */
1306
+ declare class EventSystem {
1307
+ private readonly emitter;
1308
+ private readonly poller;
1309
+ private readonly subscriber;
1310
+ private running;
1311
+ /**
1312
+ * Create a new EventSystem.
1313
+ *
1314
+ * @param runtime - The FFI runtime for polling events and submitting results
1315
+ * @param registry - The handler registry for resolving step handlers
1316
+ * @param config - Optional configuration for poller and subscriber
1317
+ */
1318
+ constructor(runtime: TaskerRuntime, registry: HandlerRegistryInterface, config?: EventSystemConfig);
1319
+ /**
1320
+ * Start the event system.
1321
+ *
1322
+ * Starts the subscriber first (to register listeners), then the poller.
1323
+ * This ensures no events are missed.
1324
+ */
1325
+ start(): void;
1326
+ /**
1327
+ * Stop the event system gracefully.
1328
+ *
1329
+ * Stops ingress first (poller), waits for in-flight handlers,
1330
+ * then stops the subscriber.
1331
+ *
1332
+ * @param drainTimeoutMs - Maximum time to wait for in-flight handlers (default: 30000)
1333
+ */
1334
+ stop(drainTimeoutMs?: number): Promise<void>;
1335
+ /**
1336
+ * Check if the event system is running.
1337
+ */
1338
+ isRunning(): boolean;
1339
+ /**
1340
+ * Get the event emitter (for testing or advanced use cases).
1341
+ */
1342
+ getEmitter(): TaskerEventEmitter;
1343
+ /**
1344
+ * Get current statistics about the event system.
1345
+ */
1346
+ getStats(): EventSystemStats;
1347
+ }
1348
+
1349
+ export { type MetricsCallback as A, type BatchWorkerConfig as B, type PollerState as C, type StepEventCallback as D, type ExecutableHandler as E, type EventSystemConfig as F, type EventSystemStats as G, type StepExecutionSubscriberConfig as H, ErrorType as I, isStandardErrorType as J, isTypicallyRetryable as K, type StepContextParams as L, type MetricsPayload as M, type StepHandlerResultParams as N, type PollerCyclePayload as P, StepHandlerResult as S, TaskerEventEmitter as T, type WorkerErrorPayload as W, StepHandler as a, StepContext as b, type StepHandlerClass as c, EventPoller as d, StepExecutionSubscriber as e, EventSystem as f, type StepCompletionSentPayload as g, type StepExecutionCompletedPayload as h, type StepExecutionFailedPayload as i, type StepExecutionReceivedPayload as j, type StepExecutionStartedPayload as k, type TaskerEventMap as l, type WorkerEventPayload as m, type EventName as n, EventNames as o, type MetricsEventName as p, MetricsEventNames as q, type PollerEventName as r, PollerEventNames as s, type StepEventName as t, StepEventNames as u, type WorkerEventName as v, WorkerEventNames as w, createEventPoller as x, type ErrorCallback as y, type EventPollerConfig$1 as z };