@multiplier-labs/stepflow 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/.github/workflows/publish.yml +30 -0
  2. package/README.md +408 -0
  3. package/dist/chunk-FQCT3I2A.js +1512 -0
  4. package/dist/chunk-FQCT3I2A.js.map +1 -0
  5. package/dist/chunk-GXY66V7Q.js +111 -0
  6. package/dist/chunk-GXY66V7Q.js.map +1 -0
  7. package/dist/chunk-U5QGN3RT.js +715 -0
  8. package/dist/chunk-U5QGN3RT.js.map +1 -0
  9. package/dist/chunk-XCF4PLN7.js +575 -0
  10. package/dist/chunk-XCF4PLN7.js.map +1 -0
  11. package/dist/events/index.d.ts +346 -0
  12. package/dist/events/index.js +11 -0
  13. package/dist/events/index.js.map +1 -0
  14. package/dist/index-CPfGsmrp.d.ts +567 -0
  15. package/dist/index.d.ts +748 -0
  16. package/dist/index.js +1707 -0
  17. package/dist/index.js.map +1 -0
  18. package/dist/scheduler/index.d.ts +6 -0
  19. package/dist/scheduler/index.js +12 -0
  20. package/dist/scheduler/index.js.map +1 -0
  21. package/dist/storage/index.d.ts +402 -0
  22. package/dist/storage/index.js +13 -0
  23. package/dist/storage/index.js.map +1 -0
  24. package/dist/types-BVShq7zT.d.ts +150 -0
  25. package/dist/types-BlwFEGzj.d.ts +276 -0
  26. package/dist/types-DzkEqnQJ.d.ts +75 -0
  27. package/docs/github-packages-setup.md +97 -0
  28. package/docs/stepflow-api-reference.md +1662 -0
  29. package/package.json +85 -0
  30. package/src/core/engine.test.ts +1421 -0
  31. package/src/core/engine.ts +717 -0
  32. package/src/core/index.ts +7 -0
  33. package/src/core/orchestrator.ts +590 -0
  34. package/src/core/types.ts +242 -0
  35. package/src/events/index.ts +8 -0
  36. package/src/events/memory.test.ts +109 -0
  37. package/src/events/memory.ts +95 -0
  38. package/src/events/socketio.test.ts +428 -0
  39. package/src/events/socketio.ts +269 -0
  40. package/src/events/types.ts +121 -0
  41. package/src/events/webhook.test.ts +695 -0
  42. package/src/events/webhook.ts +591 -0
  43. package/src/index.ts +270 -0
  44. package/src/planning/index.ts +52 -0
  45. package/src/planning/planner.ts +601 -0
  46. package/src/planning/planning.test.ts +790 -0
  47. package/src/planning/registry.test.ts +445 -0
  48. package/src/planning/registry.ts +369 -0
  49. package/src/planning/types.ts +570 -0
  50. package/src/scheduler/cron.test.ts +480 -0
  51. package/src/scheduler/cron.ts +449 -0
  52. package/src/scheduler/index.ts +18 -0
  53. package/src/scheduler/postgres-persistence.test.ts +906 -0
  54. package/src/scheduler/postgres-persistence.ts +546 -0
  55. package/src/scheduler/sqlite-persistence.test.ts +235 -0
  56. package/src/scheduler/sqlite-persistence.ts +268 -0
  57. package/src/scheduler/types.ts +78 -0
  58. package/src/storage/index.ts +27 -0
  59. package/src/storage/memory.test.ts +399 -0
  60. package/src/storage/memory.ts +248 -0
  61. package/src/storage/postgres.ts +1550 -0
  62. package/src/storage/sqlite.test.ts +593 -0
  63. package/src/storage/sqlite.ts +662 -0
  64. package/src/storage/types.ts +368 -0
  65. package/src/utils/errors.test.ts +152 -0
  66. package/src/utils/errors.ts +191 -0
  67. package/src/utils/id.ts +21 -0
  68. package/src/utils/index.ts +8 -0
  69. package/src/utils/logger.test.ts +127 -0
  70. package/src/utils/logger.ts +96 -0
  71. package/src/utils/postgres-deps.ts +63 -0
  72. package/src/utils/retry.test.ts +197 -0
  73. package/src/utils/retry.ts +121 -0
  74. package/tsconfig.json +21 -0
  75. package/tsup.config.ts +14 -0
  76. package/vitest.config.ts +9 -0
@@ -0,0 +1,748 @@
1
+ import { a as WorkflowError, L as Logger, W as WorkflowKind, b as StepErrorStrategy, c as WorkflowStep } from './types-BVShq7zT.js';
2
+ export { d as RunResult, R as RunStatus, e as SpawnChildOptions, S as StepStatus, f as WorkflowContext, g as WorkflowDefinition, h as WorkflowHooks } from './types-BVShq7zT.js';
3
+ export { C as CronScheduler, a as CronSchedulerConfig, P as PostgresSchedulePersistence, b as PostgresSchedulePersistenceConfig, S as SQLiteSchedulePersistence, c as SQLiteSchedulePersistenceConfig, d as SchedulePersistence, e as Scheduler, f as StartRunOptions, T as TriggerType, W as WorkflowEngine, g as WorkflowEngineConfig, h as WorkflowSchedule } from './index-CPfGsmrp.js';
4
+ export { C as CreateRunInput, E as ExtendedListRunsOptions, a as ExtendedRunStatus, b as ExtendedStepStatus, c as ExtendedWorkflowRunRecord, L as ListEventsOptions, d as ListRunsOptions, P as PaginatedResult, S as StepRecord, e as StepResult, f as StepflowDatabase, g as StepflowRunsTable, h as StepflowStepResultsTable, i as StorageAdapter, U as UpdateRunInput, W as WorkflowEventRecord, j as WorkflowRunRecord, k as WorkflowRunStepRecord, l as WorkflowStorage } from './types-BlwFEGzj.js';
5
+ export { MemoryStorageAdapter, PostgresStorage, PostgresStorage as PostgresStorageAdapter, PostgresStorageConfig, SQLiteStorageAdapter, SQLiteStorageConfig } from './storage/index.js';
6
+ export { B as BuiltInEventType, E as EventCallback, a as EventTransport, U as Unsubscribe, W as WorkflowEvent, b as WorkflowEventType } from './types-DzkEqnQJ.js';
7
+ export { MemoryEventTransport, SocketIOAuthorizeFn, SocketIOEventTransport, SocketIOEventTransportConfig, SocketIOServer, SocketIOSocket, WebhookEndpoint, WebhookEventTransport, WebhookEventTransportConfig, WebhookPayload } from './events/index.js';
8
+ import 'better-sqlite3';
9
+ import 'pg';
10
+
11
+ /**
12
+ * Generate a unique ID for database records.
13
+ * Uses a ULID-like format: base36 timestamp + random suffix.
14
+ * This provides:
15
+ * - Rough time-ordering (useful for debugging)
16
+ * - High collision resistance
17
+ * - URL-safe characters
18
+ * - Cryptographically secure random component
19
+ *
20
+ * @returns A unique identifier string (approx 16 characters)
21
+ */
22
+ declare function generateId(): string;
23
+
24
+ /**
25
+ * Custom error classes for the workflow engine.
26
+ */
27
+
28
+ /**
29
+ * Base error class for workflow-related errors.
30
+ */
31
+ declare class WorkflowEngineError extends Error {
32
+ readonly code: string;
33
+ readonly details?: Record<string, unknown>;
34
+ constructor(code: string, message: string, details?: Record<string, unknown>);
35
+ /**
36
+ * Convert to a WorkflowError record for storage.
37
+ */
38
+ toRecord(): WorkflowError;
39
+ /**
40
+ * Create a WorkflowError record from any error.
41
+ */
42
+ static fromError(error: unknown, defaultCode?: string): WorkflowError;
43
+ }
44
+ /**
45
+ * Error thrown when a workflow is not found in the registry.
46
+ */
47
+ declare class WorkflowNotFoundError extends WorkflowEngineError {
48
+ constructor(kind: string);
49
+ }
50
+ /**
51
+ * Error thrown when a workflow is already registered.
52
+ */
53
+ declare class WorkflowAlreadyRegisteredError extends WorkflowEngineError {
54
+ constructor(kind: string);
55
+ }
56
+ /**
57
+ * Error thrown when a run is not found.
58
+ */
59
+ declare class RunNotFoundError extends WorkflowEngineError {
60
+ constructor(runId: string);
61
+ }
62
+ /**
63
+ * Error thrown when a step fails.
64
+ */
65
+ declare class StepError extends WorkflowEngineError {
66
+ readonly stepKey: string;
67
+ readonly attempt: number;
68
+ readonly cause?: Error;
69
+ constructor(stepKey: string, message: string, attempt: number, cause?: Error);
70
+ }
71
+ /**
72
+ * Error thrown when a step times out.
73
+ */
74
+ declare class StepTimeoutError extends WorkflowEngineError {
75
+ readonly stepKey: string;
76
+ readonly timeoutMs: number;
77
+ constructor(stepKey: string, timeoutMs: number);
78
+ }
79
+ /**
80
+ * Error thrown when a workflow is canceled.
81
+ */
82
+ declare class WorkflowCanceledError extends WorkflowEngineError {
83
+ constructor(runId: string);
84
+ }
85
+ /**
86
+ * Error thrown when waitForRun times out polling for a terminal status.
87
+ */
88
+ declare class WaitForRunTimeoutError extends WorkflowEngineError {
89
+ readonly runId: string;
90
+ readonly timeoutMs: number;
91
+ constructor(runId: string, timeoutMs: number);
92
+ }
93
+ /**
94
+ * Error thrown when a workflow times out.
95
+ */
96
+ declare class WorkflowTimeoutError extends WorkflowEngineError {
97
+ readonly timeoutMs: number;
98
+ constructor(runId: string, timeoutMs: number);
99
+ }
100
+
101
+ /**
102
+ * Logger utilities for the workflow engine.
103
+ */
104
+
105
+ /** Log level for ConsoleLogger. Levels are ordered: debug < info < warn < error. */
106
+ type LogLevel = "debug" | "info" | "warn" | "error";
107
+ /**
108
+ * Console-based logger implementation.
109
+ * Uses console.log with prefixes for different levels.
110
+ * Supports a configurable minimum log level (default: 'info').
111
+ */
112
+ declare class ConsoleLogger implements Logger {
113
+ private prefix;
114
+ private minLevel;
115
+ constructor(prefix?: string, level?: LogLevel);
116
+ debug(message: string, ...args: unknown[]): void;
117
+ info(message: string, ...args: unknown[]): void;
118
+ warn(message: string, ...args: unknown[]): void;
119
+ error(message: string, ...args: unknown[]): void;
120
+ }
121
+ /**
122
+ * Silent logger that does nothing.
123
+ * Useful for testing or when logs are not wanted.
124
+ */
125
+ declare class SilentLogger implements Logger {
126
+ debug(): void;
127
+ info(): void;
128
+ warn(): void;
129
+ error(): void;
130
+ }
131
+ /**
132
+ * Strip stack traces from a WorkflowError before persisting to storage.
133
+ * Stack traces expose internal file paths and should be kept in logs only.
134
+ */
135
+ declare function sanitizeErrorForStorage(error: WorkflowError): WorkflowError;
136
+ /**
137
+ * Create a scoped logger that includes run/step context.
138
+ */
139
+ declare function createScopedLogger(logger: Logger, runId: string, stepKey?: string): Logger;
140
+
141
+ /**
142
+ * Retry utilities for the workflow engine.
143
+ */
144
+ /**
145
+ * Options for retry behavior.
146
+ */
147
+ interface RetryOptions {
148
+ /** Maximum number of retry attempts (default: 3) */
149
+ maxRetries: number;
150
+ /** Initial delay between retries in ms (default: 1000) */
151
+ delay: number;
152
+ /** Backoff multiplier (default: 2) */
153
+ backoff: number;
154
+ /** Optional abort signal to cancel retries */
155
+ signal?: AbortSignal;
156
+ /** Optional callback before each retry */
157
+ onRetry?: (attempt: number, error: Error, nextDelay: number) => void;
158
+ }
159
+ /**
160
+ * Default retry options.
161
+ */
162
+ declare const DEFAULT_RETRY_OPTIONS: RetryOptions;
163
+ /**
164
+ * Sleep for a given number of milliseconds.
165
+ * Can be canceled via AbortSignal.
166
+ */
167
+ declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
168
+ /**
169
+ * Execute a function with retry logic.
170
+ *
171
+ * @param fn - The async function to execute
172
+ * @param options - Retry configuration
173
+ * @returns The result of the function
174
+ * @throws The last error if all retries are exhausted
175
+ */
176
+ declare function withRetry<T>(fn: () => Promise<T>, options?: Partial<RetryOptions>): Promise<T>;
177
+ /**
178
+ * Calculate the delay for a specific retry attempt.
179
+ */
180
+ declare function calculateRetryDelay(attempt: number, baseDelay: number, backoff: number): number;
181
+
182
+ /**
183
+ * Planning types for the workflow engine.
184
+ * Enables dynamic workflow orchestration through recipes and plans.
185
+ */
186
+
187
+ /**
188
+ * Comparison operators for recipe conditions.
189
+ */
190
+ type ConditionOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "contains" | "matches" | "exists" | "notExists";
191
+ /**
192
+ * A condition that determines when a recipe should be selected.
193
+ * Conditions are evaluated against the workflow input.
194
+ */
195
+ interface RecipeCondition {
196
+ /** Input field to check (supports dot notation for nested fields) */
197
+ field: string;
198
+ /** Comparison operator */
199
+ operator: ConditionOperator;
200
+ /** Value to compare against (not required for exists/notExists) */
201
+ value?: unknown;
202
+ }
203
+ /**
204
+ * Default parameters for a recipe.
205
+ */
206
+ interface RecipeDefaults {
207
+ /** Workflow-level timeout in ms */
208
+ timeout?: number;
209
+ /** Default max retries for steps */
210
+ maxRetries?: number;
211
+ /** Base retry delay in ms */
212
+ retryDelay?: number;
213
+ /** Retry backoff multiplier */
214
+ retryBackoff?: number;
215
+ /** Default error strategy for steps */
216
+ onError?: StepErrorStrategy;
217
+ }
218
+ /**
219
+ * Reference to a step handler function.
220
+ * The actual handler is resolved at plan execution time.
221
+ */
222
+ interface StepHandlerRef {
223
+ /** Unique handler identifier (e.g., 'handlers.loadDocument') */
224
+ id: string;
225
+ /** Human-readable description */
226
+ description?: string;
227
+ }
228
+ /**
229
+ * A step definition within a recipe.
230
+ * Similar to WorkflowStep but uses handler references instead of functions.
231
+ */
232
+ interface RecipeStep {
233
+ /** Unique step identifier within the recipe */
234
+ key: string;
235
+ /** Human-readable step name */
236
+ name: string;
237
+ /** Reference to the step handler function */
238
+ handlerRef: string;
239
+ /** Step-specific configuration passed to the handler */
240
+ config?: Record<string, unknown>;
241
+ /** Error handling strategy */
242
+ onError?: StepErrorStrategy;
243
+ /** Maximum retry attempts */
244
+ maxRetries?: number;
245
+ /** Retry delay in ms */
246
+ retryDelay?: number;
247
+ /** Retry backoff multiplier */
248
+ retryBackoff?: number;
249
+ /** Step timeout in ms */
250
+ timeout?: number;
251
+ /**
252
+ * Expression to evaluate for skipping (simple field reference).
253
+ * If the referenced field is truthy, the step is skipped.
254
+ * Example: 'input.skipValidation' or 'results.load.alreadyExists'
255
+ */
256
+ skipCondition?: string;
257
+ }
258
+ /**
259
+ * A recipe is a reusable workflow configuration template.
260
+ * Recipes define the steps to execute and conditions for selection.
261
+ */
262
+ interface Recipe {
263
+ /** Unique recipe identifier (e.g., 'summarize.comprehensive') */
264
+ id: string;
265
+ /** Human-readable name */
266
+ name: string;
267
+ /** Description of what this recipe does */
268
+ description?: string;
269
+ /** Target workflow type */
270
+ workflowKind: WorkflowKind;
271
+ /** Variant name (e.g., 'default', 'fast', 'thorough') */
272
+ variant: string;
273
+ /** Ordered list of steps to execute */
274
+ steps: RecipeStep[];
275
+ /** Default parameters for this recipe */
276
+ defaults?: RecipeDefaults;
277
+ /** Conditions for auto-selecting this recipe */
278
+ conditions?: RecipeCondition[];
279
+ /**
280
+ * Selection priority. Semantics differ by context:
281
+ * - {@link MemoryRecipeRegistry.getDefault}: lower number = higher precedence
282
+ * (used as fallback when no 'default' variant exists).
283
+ * - {@link RuleBasedPlanner.selectRecipe}: condition-based scoring (0-100) is
284
+ * the primary selection axis; this value is only a tiebreaker where higher
285
+ * numeric value wins.
286
+ */
287
+ priority?: number;
288
+ /** Tags for categorization and filtering */
289
+ tags?: string[];
290
+ }
291
+ /**
292
+ * Types of modifications that can be made to a plan.
293
+ */
294
+ type PlanModificationType = "add_step" | "remove_step" | "modify_step" | "reorder_steps" | "set_default";
295
+ /**
296
+ * A modification to apply to a recipe when generating a plan.
297
+ */
298
+ interface PlanModification {
299
+ /** Type of modification */
300
+ type: PlanModificationType;
301
+ /** Target step key (for step modifications) */
302
+ stepKey?: string;
303
+ /** New value or configuration */
304
+ value: unknown;
305
+ /** Human-readable reason for this modification */
306
+ reason: string;
307
+ }
308
+ /**
309
+ * A resolved step in a plan, ready for execution.
310
+ */
311
+ interface PlannedStep {
312
+ /** Unique step identifier */
313
+ key: string;
314
+ /** Human-readable step name */
315
+ name: string;
316
+ /** Reference to the step handler */
317
+ handlerRef: string;
318
+ /** Resolved configuration for this step */
319
+ config: Record<string, unknown>;
320
+ /** Error handling strategy */
321
+ onError?: StepErrorStrategy;
322
+ /** Maximum retry attempts */
323
+ maxRetries?: number;
324
+ /** Retry delay in ms */
325
+ retryDelay?: number;
326
+ /** Retry backoff multiplier */
327
+ retryBackoff?: number;
328
+ /** Step timeout in ms */
329
+ timeout?: number;
330
+ /** Skip condition expression */
331
+ skipCondition?: string;
332
+ }
333
+ /**
334
+ * A planned child workflow to spawn during execution.
335
+ */
336
+ interface ChildWorkflowPlan {
337
+ /** Workflow type to spawn */
338
+ kind: WorkflowKind;
339
+ /** Input for the child workflow */
340
+ input: Record<string, unknown>;
341
+ /** Whether to wait for the child to complete */
342
+ waitFor?: boolean;
343
+ /** Step key after which to spawn this workflow */
344
+ afterStep?: string;
345
+ /** Optional metadata for the child workflow */
346
+ metadata?: Record<string, unknown>;
347
+ }
348
+ /**
349
+ * Resource requirements estimated for a plan.
350
+ */
351
+ interface ResourceEstimate {
352
+ /** Estimated API calls */
353
+ apiCalls?: number;
354
+ /** Estimated LLM tokens */
355
+ tokens?: number;
356
+ /** Estimated duration in ms */
357
+ duration?: number;
358
+ /** Estimated memory usage in bytes */
359
+ memory?: number;
360
+ }
361
+ /**
362
+ * A plan is the output of planning - a concrete execution strategy.
363
+ */
364
+ interface Plan {
365
+ /** Unique plan identifier */
366
+ id: string;
367
+ /** Recipe this plan is based on */
368
+ recipeId: string;
369
+ /** Recipe variant used */
370
+ variant: string;
371
+ /** Modifications applied to the base recipe */
372
+ modifications: PlanModification[];
373
+ /** Final step sequence after modifications */
374
+ steps: PlannedStep[];
375
+ /** Child workflows to spawn */
376
+ childWorkflows?: ChildWorkflowPlan[];
377
+ /** Resolved default parameters */
378
+ defaults: RecipeDefaults;
379
+ /** Human-readable reasoning for plan decisions */
380
+ reasoning?: string;
381
+ /** Estimated resource requirements */
382
+ resourceEstimate?: ResourceEstimate;
383
+ /** When this plan was generated */
384
+ createdAt: Date;
385
+ }
386
+ /**
387
+ * Priority modes for planning.
388
+ */
389
+ type PlanningPriority = "speed" | "quality" | "cost" | "balanced";
390
+ /**
391
+ * Constraints that limit planning and execution.
392
+ */
393
+ interface PlanningConstraints {
394
+ /** Maximum allowed duration in ms */
395
+ maxDuration?: number;
396
+ /** Maximum API calls allowed */
397
+ maxApiCalls?: number;
398
+ /** Maximum LLM tokens allowed */
399
+ maxTokens?: number;
400
+ /** Optimization priority */
401
+ priority?: PlanningPriority;
402
+ }
403
+ /**
404
+ * User-provided hints to guide planning.
405
+ */
406
+ interface PlanningHints {
407
+ /** Preferred recipe variant */
408
+ preferredVariant?: string;
409
+ /** Specific recipe to use (bypasses selection) */
410
+ forceRecipeId?: string;
411
+ /** Steps to skip */
412
+ skipSteps?: string[];
413
+ /** Steps to include (even if normally skipped) */
414
+ includeSteps?: string[];
415
+ /** Focus areas (domain-specific) */
416
+ focusAreas?: string[];
417
+ /** Additional configuration to merge */
418
+ additionalConfig?: Record<string, unknown>;
419
+ }
420
+ /**
421
+ * Context provided to the planner for decision-making.
422
+ */
423
+ interface PlanningContext {
424
+ /** Parent workflow run ID (if spawned as child) */
425
+ parentRunId?: string;
426
+ /** Domain-specific metadata */
427
+ metadata?: Record<string, unknown>;
428
+ /** Resource constraints */
429
+ constraints?: PlanningConstraints;
430
+ /** User-provided hints */
431
+ hints?: PlanningHints;
432
+ }
433
+ /**
434
+ * Result of recipe selection.
435
+ */
436
+ interface RecipeSelectionResult {
437
+ /** Selected recipe */
438
+ recipe: Recipe;
439
+ /** Score indicating confidence (0-100) */
440
+ score: number;
441
+ /** Why this recipe was selected */
442
+ reason: string;
443
+ }
444
+ /**
445
+ * Validation result for a plan.
446
+ */
447
+ interface PlanValidationResult {
448
+ /** Whether the plan is valid */
449
+ valid: boolean;
450
+ /** Validation errors (if any) */
451
+ errors: string[];
452
+ /** Validation warnings */
453
+ warnings: string[];
454
+ }
455
+ /**
456
+ * Planner interface for generating execution plans.
457
+ */
458
+ interface Planner {
459
+ /**
460
+ * Select the best recipe for a workflow and input.
461
+ */
462
+ selectRecipe(workflowKind: WorkflowKind, input: Record<string, unknown>, context?: PlanningContext): Promise<RecipeSelectionResult>;
463
+ /**
464
+ * Generate a plan from a recipe and input.
465
+ */
466
+ generatePlan(recipe: Recipe, input: Record<string, unknown>, context?: PlanningContext): Promise<Plan>;
467
+ /**
468
+ * Combined operation: select recipe and generate plan.
469
+ */
470
+ plan(workflowKind: WorkflowKind, input: Record<string, unknown>, context?: PlanningContext): Promise<Plan>;
471
+ /**
472
+ * Validate a plan before execution.
473
+ */
474
+ validatePlan(plan: Plan): PlanValidationResult;
475
+ /**
476
+ * Estimate resources required for a plan.
477
+ */
478
+ estimateResources(plan: Plan): ResourceEstimate;
479
+ }
480
+ /**
481
+ * A registered step handler function.
482
+ */
483
+ interface RegisteredStepHandler<TInput = Record<string, unknown>> {
484
+ /** Unique handler identifier */
485
+ id: string;
486
+ /** Human-readable description */
487
+ description?: string;
488
+ /** The handler function */
489
+ handler: WorkflowStep<TInput>["handler"];
490
+ /** Tags for categorization */
491
+ tags?: string[];
492
+ }
493
+ /**
494
+ * Registry for step handlers.
495
+ * Allows recipes to reference handlers by ID.
496
+ */
497
+ interface StepHandlerRegistry {
498
+ /**
499
+ * Register a step handler.
500
+ */
501
+ register<TInput = Record<string, unknown>>(handler: RegisteredStepHandler<TInput>): void;
502
+ /**
503
+ * Get a handler by ID.
504
+ */
505
+ get(id: string): RegisteredStepHandler | undefined;
506
+ /**
507
+ * Check if a handler exists.
508
+ */
509
+ has(id: string): boolean;
510
+ /**
511
+ * List all registered handlers.
512
+ */
513
+ list(): RegisteredStepHandler[];
514
+ /**
515
+ * List handlers by tag.
516
+ */
517
+ listByTag(tag: string): RegisteredStepHandler[];
518
+ }
519
+ /**
520
+ * Options for querying recipes.
521
+ */
522
+ interface RecipeQueryOptions {
523
+ /** Filter by workflow kind */
524
+ workflowKind?: WorkflowKind;
525
+ /** Filter by variant */
526
+ variant?: string;
527
+ /** Filter by tags (any match) */
528
+ tags?: string[];
529
+ /** Only include recipes matching conditions */
530
+ matchConditions?: Record<string, unknown>;
531
+ }
532
+ /**
533
+ * Registry for recipes.
534
+ */
535
+ interface RecipeRegistry {
536
+ /**
537
+ * Register a recipe.
538
+ */
539
+ register(recipe: Recipe): void;
540
+ /**
541
+ * Register multiple recipes.
542
+ */
543
+ registerAll(recipes: Recipe[]): void;
544
+ /**
545
+ * Get a recipe by ID.
546
+ */
547
+ get(recipeId: string): Recipe | undefined;
548
+ /**
549
+ * Check if a recipe exists.
550
+ */
551
+ has(recipeId: string): boolean;
552
+ /**
553
+ * Get all recipes for a workflow kind.
554
+ */
555
+ getByKind(workflowKind: WorkflowKind): Recipe[];
556
+ /**
557
+ * Get a specific variant for a workflow kind.
558
+ */
559
+ getVariant(workflowKind: WorkflowKind, variant: string): Recipe | undefined;
560
+ /**
561
+ * Get the default recipe for a workflow kind.
562
+ */
563
+ getDefault(workflowKind: WorkflowKind): Recipe | undefined;
564
+ /**
565
+ * List all available variants for a workflow kind.
566
+ */
567
+ listVariants(workflowKind: WorkflowKind): string[];
568
+ /**
569
+ * Query recipes with filters.
570
+ */
571
+ query(options: RecipeQueryOptions): Recipe[];
572
+ /**
573
+ * List all registered recipes.
574
+ */
575
+ list(): Recipe[];
576
+ }
577
+
578
+ /**
579
+ * Recipe and Step Handler registries.
580
+ * Provides storage and retrieval of recipes and handlers.
581
+ */
582
+
583
+ /**
584
+ * In-memory implementation of the step handler registry.
585
+ */
586
+ declare class MemoryStepHandlerRegistry implements StepHandlerRegistry {
587
+ private handlers;
588
+ private tagIndex;
589
+ /** Register a step handler. Throws if a handler with the same ID is already registered. */
590
+ register<TInput = Record<string, unknown>>(handler: RegisteredStepHandler<TInput>): void;
591
+ /** Get a handler by its unique ID, or undefined if not registered. */
592
+ get(id: string): RegisteredStepHandler | undefined;
593
+ /** Check whether a handler with the given ID is registered. */
594
+ has(id: string): boolean;
595
+ /** List all registered step handlers. */
596
+ list(): RegisteredStepHandler[];
597
+ /** List all handlers tagged with the given tag. */
598
+ listByTag(tag: string): RegisteredStepHandler[];
599
+ /**
600
+ * Resolve a handler reference to a WorkflowStep handler function.
601
+ * Returns undefined if the handler is not found.
602
+ */
603
+ resolve(handlerRef: string): WorkflowStep["handler"] | undefined;
604
+ /**
605
+ * Clear all registered handlers (useful for testing).
606
+ */
607
+ clear(): void;
608
+ }
609
+ /**
610
+ * In-memory implementation of the recipe registry.
611
+ */
612
+ declare class MemoryRecipeRegistry implements RecipeRegistry {
613
+ private recipes;
614
+ private kindIndex;
615
+ private variantIndex;
616
+ private tagIndex;
617
+ /** Register a single recipe. Throws if a recipe with the same ID or kind:variant pair is already registered. */
618
+ register(recipe: Recipe): void;
619
+ /** Register multiple recipes at once. */
620
+ registerAll(recipes: Recipe[]): void;
621
+ /** Get a recipe by its unique ID, or undefined if not registered. */
622
+ get(recipeId: string): Recipe | undefined;
623
+ /** Check whether a recipe with the given ID is registered. */
624
+ has(recipeId: string): boolean;
625
+ /** Get all recipes registered for a given workflow kind. */
626
+ getByKind(workflowKind: WorkflowKind): Recipe[];
627
+ /** Get the recipe for a specific workflow kind and variant combination. */
628
+ getVariant(workflowKind: WorkflowKind, variant: string): Recipe | undefined;
629
+ /**
630
+ * Get the default recipe for a workflow kind.
631
+ * Returns the 'default' variant if one exists, otherwise falls back to the
632
+ * recipe with the lowest numeric priority value (lower number = higher precedence).
633
+ */
634
+ getDefault(workflowKind: WorkflowKind): Recipe | undefined;
635
+ /** List all variant names registered for a workflow kind. */
636
+ listVariants(workflowKind: WorkflowKind): string[];
637
+ /** Query recipes with optional filters for kind, variant, tags, and input conditions. */
638
+ query(options: RecipeQueryOptions): Recipe[];
639
+ /** List all registered recipes. */
640
+ list(): Recipe[];
641
+ /**
642
+ * Clear all registered recipes (useful for testing).
643
+ */
644
+ clear(): void;
645
+ /**
646
+ * Evaluate recipe conditions against an input.
647
+ * Returns true if all conditions match.
648
+ *
649
+ * Note: This intentionally mirrors the condition evaluation in planner.ts
650
+ * to keep registry queries independent of the planner implementation.
651
+ */
652
+ private evaluateConditions;
653
+ /**
654
+ * Get a nested value from an object using dot notation.
655
+ */
656
+ private getNestedValue;
657
+ /**
658
+ * Evaluate a single condition.
659
+ */
660
+ private evaluateCondition;
661
+ }
662
+ /**
663
+ * Create a combined registry that holds both recipes and step handlers.
664
+ */
665
+ interface CombinedRegistry {
666
+ recipes: MemoryRecipeRegistry;
667
+ handlers: MemoryStepHandlerRegistry;
668
+ }
669
+ /**
670
+ * Create a new combined registry instance.
671
+ */
672
+ declare function createRegistry(): CombinedRegistry;
673
+
674
+ /**
675
+ * Rule-based planner implementation.
676
+ * Selects recipes and generates plans based on conditions and input analysis.
677
+ */
678
+
679
+ /**
680
+ * Configuration for the RuleBasedPlanner.
681
+ */
682
+ interface RuleBasedPlannerConfig {
683
+ /** Recipe registry to use */
684
+ recipeRegistry: RecipeRegistry;
685
+ /** Step handler registry for validation */
686
+ handlerRegistry?: StepHandlerRegistry;
687
+ /** Whether to validate handler references during planning */
688
+ validateHandlers?: boolean;
689
+ /** Resource estimation defaults (used by estimateResources) */
690
+ resourceEstimates?: {
691
+ /** Estimated API calls per step (default: 1) */
692
+ apiCallsPerStep?: number;
693
+ /** Estimated tokens per step (default: 500) */
694
+ tokensPerStep?: number;
695
+ /** Estimated duration per step in ms (default: 2000) */
696
+ durationPerStep?: number;
697
+ /** Estimated API calls per child workflow (default: 5) */
698
+ apiCallsPerChild?: number;
699
+ };
700
+ }
701
+ /**
702
+ * Rule-based planner that selects recipes based on condition matching.
703
+ */
704
+ declare class RuleBasedPlanner implements Planner {
705
+ private recipeRegistry;
706
+ private handlerRegistry?;
707
+ private validateHandlers;
708
+ private resourceEstimates;
709
+ constructor(config: RuleBasedPlannerConfig);
710
+ /**
711
+ * Select the best recipe for a workflow kind and input.
712
+ */
713
+ selectRecipe(workflowKind: WorkflowKind, input: Record<string, unknown>, context?: PlanningContext): Promise<RecipeSelectionResult>;
714
+ /**
715
+ * Generate a plan from a recipe and input.
716
+ */
717
+ generatePlan(recipe: Recipe, input: Record<string, unknown>, context?: PlanningContext): Promise<Plan>;
718
+ /**
719
+ * Combined operation: select recipe and generate plan.
720
+ */
721
+ plan(workflowKind: WorkflowKind, input: Record<string, unknown>, context?: PlanningContext): Promise<Plan>;
722
+ /**
723
+ * Validate a plan before execution.
724
+ */
725
+ validatePlan(plan: Plan): PlanValidationResult;
726
+ /**
727
+ * Estimate resources required for a plan.
728
+ */
729
+ estimateResources(plan: Plan): ResourceEstimate;
730
+ /**
731
+ * Convert a recipe step to a planned step.
732
+ */
733
+ private recipeStepToPlannedStep;
734
+ /**
735
+ * Apply constraints to steps and generate modifications.
736
+ */
737
+ private applyConstraints;
738
+ /**
739
+ * Build a human-readable selection reason.
740
+ */
741
+ private buildSelectionReason;
742
+ /**
743
+ * Build reasoning text for a plan.
744
+ */
745
+ private buildPlanReasoning;
746
+ }
747
+
748
+ export { type ChildWorkflowPlan, type CombinedRegistry, type ConditionOperator, ConsoleLogger, DEFAULT_RETRY_OPTIONS, type LogLevel, Logger, MemoryRecipeRegistry, MemoryStepHandlerRegistry, type Plan, type PlanModification, type PlanModificationType, type PlanValidationResult, type PlannedStep, type Planner, type PlanningConstraints, type PlanningContext, type PlanningHints, type PlanningPriority, type Recipe, type RecipeCondition, type RecipeDefaults, type RecipeQueryOptions, type RecipeRegistry, type RecipeSelectionResult, type RecipeStep, type RegisteredStepHandler, type ResourceEstimate, type RetryOptions, RuleBasedPlanner, type RuleBasedPlannerConfig, RunNotFoundError, SilentLogger, StepError, StepErrorStrategy, type StepHandlerRef, type StepHandlerRegistry, StepTimeoutError, WaitForRunTimeoutError, WorkflowAlreadyRegisteredError, WorkflowCanceledError, WorkflowEngineError, WorkflowError, WorkflowKind, WorkflowNotFoundError, WorkflowStep, WorkflowTimeoutError, calculateRetryDelay, createRegistry, createScopedLogger, generateId, sanitizeErrorForStorage, sleep, withRetry };