@jagreehal/workflow 1.6.0 → 1.7.0

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.
@@ -145,6 +145,8 @@ interface WorkflowIR {
145
145
  /** When the IR was last updated */
146
146
  lastUpdatedAt: number;
147
147
  };
148
+ /** Hook executions (if any hooks are configured) */
149
+ hooks?: WorkflowHooks;
148
150
  }
149
151
 
150
152
  /**
@@ -326,6 +328,200 @@ declare function isDecisionNode(node: FlowNode): node is DecisionNode;
326
328
  * Check if a node has children.
327
329
  */
328
330
  declare function hasChildren(node: FlowNode): node is SequenceNode | ParallelNode | RaceNode | DecisionNode;
331
+ /**
332
+ * Snapshot of an active step's state at a point in time.
333
+ */
334
+ interface ActiveStepSnapshot {
335
+ id: string;
336
+ name?: string;
337
+ key?: string;
338
+ startTs: number;
339
+ retryCount: number;
340
+ timedOut: boolean;
341
+ timeoutMs?: number;
342
+ }
343
+ /**
344
+ * A snapshot of the complete IR state at a specific point in time.
345
+ * Used for time-travel debugging - each event creates a snapshot.
346
+ */
347
+ interface IRSnapshot {
348
+ /** Unique identifier for this snapshot */
349
+ id: string;
350
+ /** Index in the event sequence (0-based) */
351
+ eventIndex: number;
352
+ /** The event that triggered this snapshot */
353
+ event: unknown;
354
+ /** Complete IR state at this moment */
355
+ ir: WorkflowIR;
356
+ /** Timestamp when snapshot was taken */
357
+ timestamp: number;
358
+ /** Active step states at this moment (for debugging) */
359
+ activeSteps: Map<string, ActiveStepSnapshot>;
360
+ }
361
+ /**
362
+ * State of the time-travel controller.
363
+ */
364
+ interface TimeTravelState {
365
+ /** All recorded snapshots */
366
+ snapshots: IRSnapshot[];
367
+ /** Current snapshot index (for playback position) */
368
+ currentIndex: number;
369
+ /** Whether playback is active */
370
+ isPlaying: boolean;
371
+ /** Playback speed multiplier (1.0 = realtime, 2.0 = 2x speed) */
372
+ playbackSpeed: number;
373
+ /** Whether recording is active */
374
+ isRecording: boolean;
375
+ }
376
+ /**
377
+ * Performance metrics for a single node across multiple runs.
378
+ */
379
+ interface NodePerformance {
380
+ /** Node identifier (name or step ID) */
381
+ nodeId: string;
382
+ /** Average duration across all samples */
383
+ avgDurationMs: number;
384
+ /** Minimum duration observed */
385
+ minDurationMs: number;
386
+ /** Maximum duration observed */
387
+ maxDurationMs: number;
388
+ /** Standard deviation of durations */
389
+ stdDevMs: number;
390
+ /** Number of timing samples collected */
391
+ samples: number;
392
+ /** Retry frequency (0-1, where 1 = always retries) */
393
+ retryRate: number;
394
+ /** Timeout frequency (0-1) */
395
+ timeoutRate: number;
396
+ /** Error rate (0-1) */
397
+ errorRate: number;
398
+ /** Percentile data for distribution analysis */
399
+ percentiles: {
400
+ p50: number;
401
+ p90: number;
402
+ p95: number;
403
+ p99: number;
404
+ };
405
+ }
406
+ /**
407
+ * Heatmap data for visualizing performance across nodes.
408
+ */
409
+ interface HeatmapData {
410
+ /** Map of node ID to heat level (0-1, where 1 is hottest/slowest) */
411
+ heat: Map<string, number>;
412
+ /** The metric used for heat calculation */
413
+ metric: "duration" | "retryRate" | "errorRate";
414
+ /** Statistics used to compute heat values */
415
+ stats: {
416
+ /** Minimum value in the dataset */
417
+ min: number;
418
+ /** Maximum value in the dataset */
419
+ max: number;
420
+ /** Mean value */
421
+ mean: number;
422
+ /** Threshold above which a node is considered "hot" */
423
+ threshold: number;
424
+ };
425
+ }
426
+ /**
427
+ * Heat level for visual styling.
428
+ */
429
+ type HeatLevel = "cold" | "cool" | "neutral" | "warm" | "hot" | "critical";
430
+ /**
431
+ * Theme for the HTML visualizer.
432
+ */
433
+ type HTMLTheme = "light" | "dark" | "auto";
434
+ /**
435
+ * Layout direction for the workflow diagram.
436
+ */
437
+ type LayoutDirection = "TB" | "LR" | "BT" | "RL";
438
+ /**
439
+ * Options for the HTML renderer.
440
+ */
441
+ interface HTMLRenderOptions extends RenderOptions {
442
+ /** Enable interactive features (click to inspect, zoom/pan) */
443
+ interactive: boolean;
444
+ /** Include time-travel controls */
445
+ timeTravel: boolean;
446
+ /** Include performance heatmap overlay */
447
+ heatmap: boolean;
448
+ /** Animation duration for transitions (ms) */
449
+ animationDuration: number;
450
+ /** Color theme */
451
+ theme: HTMLTheme;
452
+ /** Diagram layout direction */
453
+ layout: LayoutDirection;
454
+ /** Heatmap data (if heatmap is enabled) */
455
+ heatmapData?: HeatmapData;
456
+ /** WebSocket URL for live updates (if streaming) */
457
+ wsUrl?: string;
458
+ }
459
+ /**
460
+ * Message sent from the web visualizer to the dev server.
461
+ */
462
+ interface WebVisualizerMessage {
463
+ type: "time_travel_seek" | "time_travel_play" | "time_travel_pause" | "time_travel_step_forward" | "time_travel_step_backward" | "request_snapshots" | "toggle_heatmap" | "set_heatmap_metric";
464
+ payload?: unknown;
465
+ }
466
+ /**
467
+ * Message sent from the dev server to the web visualizer.
468
+ */
469
+ interface ServerMessage {
470
+ type: "ir_update" | "snapshot" | "snapshots_list" | "performance_data" | "workflow_complete" | "time_travel_state";
471
+ payload: unknown;
472
+ }
473
+ /**
474
+ * Extended render options for the enhanced ASCII renderer.
475
+ */
476
+ interface EnhancedRenderOptions extends RenderOptions {
477
+ /** Show performance heatmap coloring */
478
+ showHeatmap?: boolean;
479
+ /** Heatmap data for coloring nodes */
480
+ heatmapData?: HeatmapData;
481
+ /** Show timing sparklines (requires historical data) */
482
+ showSparklines?: boolean;
483
+ /** Historical timing data for sparklines: nodeId → array of durations */
484
+ timingHistory?: Map<string, number[]>;
485
+ }
486
+ /**
487
+ * State of a hook execution.
488
+ */
489
+ type HookState = "pending" | "running" | "success" | "error";
490
+ /**
491
+ * Execution record for a workflow hook.
492
+ */
493
+ interface HookExecution {
494
+ /** Hook type identifier */
495
+ type: "shouldRun" | "onBeforeStart" | "onAfterStep";
496
+ /** Execution state */
497
+ state: HookState;
498
+ /** Timestamp when hook started */
499
+ ts: number;
500
+ /** Duration in milliseconds */
501
+ durationMs?: number;
502
+ /** Error if hook failed */
503
+ error?: unknown;
504
+ /** Additional context (e.g., stepKey for onAfterStep) */
505
+ context?: {
506
+ /** Step key for onAfterStep hooks */
507
+ stepKey?: string;
508
+ /** Result of shouldRun hook */
509
+ result?: boolean;
510
+ /** Whether workflow was skipped due to shouldRun returning false */
511
+ skipped?: boolean;
512
+ };
513
+ }
514
+ /**
515
+ * Hook execution summary for the workflow.
516
+ */
517
+ interface WorkflowHooks {
518
+ /** shouldRun hook execution (if configured) */
519
+ shouldRun?: HookExecution;
520
+ /** onBeforeStart hook execution (if configured) */
521
+ onBeforeStart?: HookExecution;
522
+ /** onAfterStep hook executions (keyed by stepKey) */
523
+ onAfterStep: Map<string, HookExecution>;
524
+ }
329
525
 
330
526
  /**
331
527
  * Parallel Detection - Heuristic detection of parallel execution from timing.
@@ -394,6 +590,18 @@ interface IRBuilderOptions {
394
590
  * Options for parallel detection.
395
591
  */
396
592
  parallelDetection?: ParallelDetectorOptions;
593
+ /**
594
+ * Enable snapshot recording for time-travel debugging.
595
+ * When true, the builder captures IR state after each event.
596
+ * Default: false
597
+ */
598
+ enableSnapshots?: boolean;
599
+ /**
600
+ * Maximum number of snapshots to keep (ring buffer behavior).
601
+ * When exceeded, oldest snapshots are discarded.
602
+ * Default: 1000
603
+ */
604
+ maxSnapshots?: number;
397
605
  }
398
606
  /**
399
607
  * Creates an IR builder that processes workflow events.
@@ -404,11 +612,23 @@ declare function createIRBuilder(options?: IRBuilderOptions): {
404
612
  handleDecisionEvent: (event: DecisionStartEvent | DecisionBranchEvent | DecisionEndEvent) => void;
405
613
  getIR: () => WorkflowIR;
406
614
  reset: () => void;
615
+ getSnapshots: () => IRSnapshot[];
616
+ getSnapshotAt: (index: number) => IRSnapshot | undefined;
617
+ getIRAt: (index: number) => WorkflowIR | undefined;
618
+ clearSnapshots: () => void;
407
619
  /** Check if there are active (running) steps */
408
620
  readonly hasActiveSteps: boolean;
409
621
  /** Get the current workflow state */
410
622
  readonly state: StepState;
623
+ /** Get the number of recorded snapshots */
624
+ readonly snapshotCount: number;
625
+ /** Check if snapshot recording is enabled */
626
+ readonly snapshotsEnabled: boolean;
411
627
  };
628
+ /**
629
+ * Type for the IR builder instance.
630
+ */
631
+ type IRBuilder = ReturnType<typeof createIRBuilder>;
412
632
 
413
633
  /**
414
634
  * ANSI color utilities for terminal output.
@@ -443,6 +663,26 @@ declare function asciiRenderer(): Renderer;
443
663
  */
444
664
  declare function mermaidRenderer(): Renderer;
445
665
 
666
+ /**
667
+ * HTML Renderer
668
+ *
669
+ * Renders the workflow IR as an interactive HTML page with:
670
+ * - SVG-based workflow diagram
671
+ * - Zoom and pan
672
+ * - Node inspection
673
+ * - Time-travel controls
674
+ * - Performance heatmap overlay
675
+ */
676
+
677
+ /**
678
+ * Create the HTML renderer.
679
+ */
680
+ declare function htmlRenderer(): Renderer;
681
+ /**
682
+ * Render workflow IR to HTML with custom options.
683
+ */
684
+ declare function renderToHTML(ir: WorkflowIR, options?: Partial<HTMLRenderOptions>): string;
685
+
446
686
  /**
447
687
  * Live Visualizer - Real-time terminal updates during workflow execution.
448
688
  *
@@ -676,6 +916,232 @@ interface SwitchTracker extends DecisionTracker {
676
916
  default(taken: boolean): void;
677
917
  }
678
918
 
919
+ /**
920
+ * Time Travel Debugger
921
+ *
922
+ * Records IR snapshots at each event, enabling:
923
+ * - Step-by-step forward/backward navigation
924
+ * - Seeking to any point in execution
925
+ * - Playback at various speeds
926
+ * - State inspection at any moment
927
+ */
928
+
929
+ /**
930
+ * Options for the time-travel controller.
931
+ */
932
+ interface TimeTravelOptions {
933
+ /** Maximum snapshots to store (ring buffer) */
934
+ maxSnapshots?: number;
935
+ /** Automatically record snapshots on each event */
936
+ autoRecord?: boolean;
937
+ /** IR builder options (passed through) */
938
+ builderOptions?: Omit<IRBuilderOptions, "enableSnapshots" | "maxSnapshots">;
939
+ }
940
+ /**
941
+ * Time-travel controller interface.
942
+ */
943
+ interface TimeTravelController {
944
+ /** Handle a workflow event (records snapshot if recording) */
945
+ handleEvent: (event: WorkflowEvent<unknown>) => void;
946
+ /** Navigate to specific snapshot index */
947
+ seek: (index: number) => WorkflowIR | undefined;
948
+ /** Move one step forward */
949
+ stepForward: () => WorkflowIR | undefined;
950
+ /** Move one step backward */
951
+ stepBackward: () => WorkflowIR | undefined;
952
+ /** Start playback at given speed (1.0 = realtime) */
953
+ play: (speed?: number) => void;
954
+ /** Pause playback */
955
+ pause: () => void;
956
+ /** Get current IR state */
957
+ getCurrentIR: () => WorkflowIR;
958
+ /** Get IR at specific snapshot index */
959
+ getIRAt: (index: number) => WorkflowIR | undefined;
960
+ /** Get all snapshots */
961
+ getSnapshots: () => IRSnapshot[];
962
+ /** Get snapshot at specific index */
963
+ getSnapshotAt: (index: number) => IRSnapshot | undefined;
964
+ /** Get current time-travel state */
965
+ getState: () => TimeTravelState;
966
+ /** Subscribe to state changes */
967
+ onStateChange: (callback: (state: TimeTravelState) => void) => () => void;
968
+ /** Start/resume recording */
969
+ startRecording: () => void;
970
+ /** Stop recording */
971
+ stopRecording: () => void;
972
+ /** Reset to initial state */
973
+ reset: () => void;
974
+ /** Get the underlying IR builder */
975
+ getBuilder: () => IRBuilder;
976
+ }
977
+ /**
978
+ * Create a time-travel controller for workflow debugging.
979
+ *
980
+ * @example
981
+ * ```typescript
982
+ * const controller = createTimeTravelController();
983
+ *
984
+ * // Feed events from workflow execution
985
+ * workflow.onEvent(event => controller.handleEvent(event));
986
+ *
987
+ * // After execution, explore the timeline
988
+ * controller.seek(0); // Go to start
989
+ * controller.stepForward(); // Step through
990
+ * controller.play(2); // Playback at 2x speed
991
+ * ```
992
+ */
993
+ declare function createTimeTravelController(options?: TimeTravelOptions): TimeTravelController;
994
+
995
+ /**
996
+ * Performance Analyzer
997
+ *
998
+ * Analyzes workflow execution data to identify:
999
+ * - Slow steps (bottlenecks)
1000
+ * - Retry patterns
1001
+ * - Error-prone steps
1002
+ * - Timing anomalies
1003
+ *
1004
+ * Aggregates metrics across multiple workflow runs to provide
1005
+ * statistical insights and heatmap visualization data.
1006
+ */
1007
+
1008
+ /**
1009
+ * A recorded workflow run for analysis.
1010
+ */
1011
+ interface WorkflowRun {
1012
+ /** Unique identifier for this run */
1013
+ id: string;
1014
+ /** Workflow start timestamp */
1015
+ startTime: number;
1016
+ /** All events from the workflow execution */
1017
+ events: WorkflowEvent<unknown>[];
1018
+ }
1019
+ /**
1020
+ * Performance analyzer interface.
1021
+ */
1022
+ interface PerformanceAnalyzer {
1023
+ /** Add a completed workflow run for analysis */
1024
+ addRun: (run: WorkflowRun) => void;
1025
+ /** Add events incrementally (alternative to addRun) */
1026
+ addEvent: (event: WorkflowEvent<unknown>) => void;
1027
+ /** Finalize current run (when using addEvent) */
1028
+ finalizeRun: (runId: string) => void;
1029
+ /** Get performance stats for a specific node */
1030
+ getNodePerformance: (nodeId: string) => NodePerformance | undefined;
1031
+ /** Get heatmap data for an IR */
1032
+ getHeatmap: (ir: WorkflowIR, metric?: "duration" | "retryRate" | "errorRate") => HeatmapData;
1033
+ /** Get slowest nodes */
1034
+ getSlowestNodes: (limit?: number) => NodePerformance[];
1035
+ /** Get error-prone nodes */
1036
+ getErrorProneNodes: (limit?: number) => NodePerformance[];
1037
+ /** Get retry-prone nodes */
1038
+ getRetryProneNodes: (limit?: number) => NodePerformance[];
1039
+ /** Get all performance data */
1040
+ getAllPerformance: () => Map<string, NodePerformance>;
1041
+ /** Export performance data as JSON */
1042
+ exportData: () => string;
1043
+ /** Import performance data from JSON */
1044
+ importData: (json: string) => void;
1045
+ /** Clear all collected data */
1046
+ clear: () => void;
1047
+ }
1048
+ /**
1049
+ * Get heat level from normalized value (0-1).
1050
+ */
1051
+ declare function getHeatLevel(heat: number): HeatLevel;
1052
+ /**
1053
+ * Create a performance analyzer for workflow metrics.
1054
+ *
1055
+ * @example
1056
+ * ```typescript
1057
+ * const analyzer = createPerformanceAnalyzer();
1058
+ *
1059
+ * // Add completed runs
1060
+ * analyzer.addRun({ id: 'run-1', startTime: Date.now(), events });
1061
+ *
1062
+ * // Get insights
1063
+ * const slowest = analyzer.getSlowestNodes(5);
1064
+ * const heatmap = analyzer.getHeatmap(ir, 'duration');
1065
+ * ```
1066
+ */
1067
+ declare function createPerformanceAnalyzer(): PerformanceAnalyzer;
1068
+
1069
+ /**
1070
+ * Development Server
1071
+ *
1072
+ * Provides a local HTTP server with WebSocket support for:
1073
+ * - Serving the HTML visualizer
1074
+ * - Live streaming workflow events
1075
+ * - Time-travel control from the browser
1076
+ * - Performance data broadcasting
1077
+ *
1078
+ * The `ws` package is an optional peer dependency.
1079
+ * Install it with: npm install ws
1080
+ */
1081
+
1082
+ /**
1083
+ * Options for the dev server.
1084
+ */
1085
+ interface DevServerOptions {
1086
+ /** Port to listen on (default: 3377) */
1087
+ port?: number;
1088
+ /** Hostname to bind to (default: localhost) */
1089
+ host?: string;
1090
+ /** Auto-open browser when starting (default: true) */
1091
+ autoOpen?: boolean;
1092
+ /** Workflow name for the visualizer title */
1093
+ workflowName?: string;
1094
+ /** Enable time-travel debugging (default: true) */
1095
+ timeTravel?: boolean;
1096
+ /** Enable performance heatmap (default: true) */
1097
+ heatmap?: boolean;
1098
+ /** Max snapshots for time-travel (default: 1000) */
1099
+ maxSnapshots?: number;
1100
+ }
1101
+ /**
1102
+ * Dev server interface.
1103
+ */
1104
+ interface DevServer {
1105
+ /** Start the server */
1106
+ start(): Promise<{
1107
+ port: number;
1108
+ url: string;
1109
+ }>;
1110
+ /** Stop the server */
1111
+ stop(): Promise<void>;
1112
+ /** Handle a workflow event (forwards to time-travel and broadcasts) */
1113
+ handleEvent(event: WorkflowEvent<unknown>): void;
1114
+ /** Push an IR update to all clients */
1115
+ pushUpdate(ir: WorkflowIR): void;
1116
+ /** Push heatmap data to all clients */
1117
+ pushHeatmap(data: HeatmapData): void;
1118
+ /** Mark workflow as complete */
1119
+ complete(): void;
1120
+ /** Get the time-travel controller */
1121
+ getTimeTravel(): TimeTravelController;
1122
+ /** Get the performance analyzer */
1123
+ getAnalyzer(): PerformanceAnalyzer;
1124
+ /** Get current IR */
1125
+ getCurrentIR(): WorkflowIR;
1126
+ }
1127
+ /**
1128
+ * Create a development server for the workflow visualizer.
1129
+ *
1130
+ * @example
1131
+ * ```typescript
1132
+ * const server = createDevServer({ port: 3377 });
1133
+ * await server.start();
1134
+ *
1135
+ * // Forward events from workflow execution
1136
+ * workflow.onEvent(event => server.handleEvent(event));
1137
+ *
1138
+ * // When done
1139
+ * server.complete();
1140
+ * await server.stop();
1141
+ * ```
1142
+ */
1143
+ declare function createDevServer(options?: DevServerOptions): Promise<DevServer>;
1144
+
679
1145
  /**
680
1146
  * Workflow Visualization Module
681
1147
  *
@@ -808,4 +1274,4 @@ declare function createEventCollector(options?: VisualizerOptions): {
808
1274
  visualizeAs: (format: OutputFormat) => string;
809
1275
  };
810
1276
 
811
- export { type BaseNode, type CollectableEvent, type ColorScheme, type DecisionBranch, type DecisionBranchEvent, type DecisionEndEvent, type DecisionEvent, type DecisionNode, type DecisionStartEvent, type DecisionTracker, type FlowNode, type IRBuilderOptions, type IfTracker, type LiveVisualizer, type LiveVisualizerOptions, type OutputFormat, type ParallelDetectorOptions, type ParallelNode, type RaceNode, type RenderOptions, type Renderer, type ScopeEndEvent, type ScopeEvent, type ScopeStartEvent, ScopeType, type SequenceNode, type StepNode, type StepSkippedEvent, type StepState, type SwitchTracker, type VisualizerOptions, type WorkflowIR, type WorkflowNode, type WorkflowVisualizer, asciiRenderer, createEventCollector, createIRBuilder, createLiveVisualizer, createParallelDetector, createVisualizer, defaultColorScheme, detectParallelGroups, hasChildren, isDecisionNode, isParallelNode, isRaceNode, isSequenceNode, isStepNode, mermaidRenderer, trackDecision, trackIf, trackSwitch, visualizeEvents };
1277
+ export { type ActiveStepSnapshot, type BaseNode, type CollectableEvent, type ColorScheme, type DecisionBranch, type DecisionBranchEvent, type DecisionEndEvent, type DecisionEvent, type DecisionNode, type DecisionStartEvent, type DecisionTracker, type DevServer, type DevServerOptions, type EnhancedRenderOptions, type FlowNode, type HTMLRenderOptions, type HTMLTheme, type HeatLevel, type HeatmapData, type HookExecution, type HookState, type IRBuilderOptions, type IRSnapshot, type IfTracker, type LayoutDirection, type LiveVisualizer, type LiveVisualizerOptions, type NodePerformance, type OutputFormat, type ParallelDetectorOptions, type ParallelNode, type PerformanceAnalyzer, type RaceNode, type RenderOptions, type Renderer, type ScopeEndEvent, type ScopeEvent, type ScopeStartEvent, ScopeType, type SequenceNode, type ServerMessage, type StepNode, type StepSkippedEvent, type StepState, type SwitchTracker, type TimeTravelController, type TimeTravelOptions, type TimeTravelState, type VisualizerOptions, type WebVisualizerMessage, type WorkflowHooks, type WorkflowIR, type WorkflowNode, type WorkflowRun, type WorkflowVisualizer, asciiRenderer, createDevServer, createEventCollector, createIRBuilder, createLiveVisualizer, createParallelDetector, createPerformanceAnalyzer, createTimeTravelController, createVisualizer, defaultColorScheme, detectParallelGroups, getHeatLevel, hasChildren, htmlRenderer, isDecisionNode, isParallelNode, isRaceNode, isSequenceNode, isStepNode, mermaidRenderer, renderToHTML, trackDecision, trackIf, trackSwitch, visualizeEvents };