ai-workflows 2.1.3 → 2.3.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.
Files changed (188) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/CHANGELOG.md +8 -1
  3. package/README.md +2 -0
  4. package/dist/barrier.d.ts +6 -0
  5. package/dist/barrier.d.ts.map +1 -1
  6. package/dist/barrier.js +45 -7
  7. package/dist/barrier.js.map +1 -1
  8. package/dist/cascade-context.d.ts.map +1 -1
  9. package/dist/cascade-context.js +25 -25
  10. package/dist/cascade-context.js.map +1 -1
  11. package/dist/cascade-executor.d.ts.map +1 -1
  12. package/dist/cascade-executor.js +1 -1
  13. package/dist/cascade-executor.js.map +1 -1
  14. package/dist/context.d.ts.map +1 -1
  15. package/dist/context.js +23 -7
  16. package/dist/context.js.map +1 -1
  17. package/dist/cron-parser.d.ts +65 -0
  18. package/dist/cron-parser.d.ts.map +1 -0
  19. package/dist/cron-parser.js +294 -0
  20. package/dist/cron-parser.js.map +1 -0
  21. package/dist/cron-scheduler.d.ts +117 -0
  22. package/dist/cron-scheduler.d.ts.map +1 -0
  23. package/dist/cron-scheduler.js +176 -0
  24. package/dist/cron-scheduler.js.map +1 -0
  25. package/dist/database-context.d.ts +184 -0
  26. package/dist/database-context.d.ts.map +1 -0
  27. package/dist/database-context.js +428 -0
  28. package/dist/database-context.js.map +1 -0
  29. package/dist/digital-objects-adapter.d.ts +159 -0
  30. package/dist/digital-objects-adapter.d.ts.map +1 -0
  31. package/dist/digital-objects-adapter.js +229 -0
  32. package/dist/digital-objects-adapter.js.map +1 -0
  33. package/dist/durable-execution-cloudflare.d.ts +427 -0
  34. package/dist/durable-execution-cloudflare.d.ts.map +1 -0
  35. package/dist/durable-execution-cloudflare.js +510 -0
  36. package/dist/durable-execution-cloudflare.js.map +1 -0
  37. package/dist/durable-execution.d.ts +482 -0
  38. package/dist/durable-execution.d.ts.map +1 -0
  39. package/dist/durable-execution.js +594 -0
  40. package/dist/durable-execution.js.map +1 -0
  41. package/dist/durable-workflow.d.ts +176 -0
  42. package/dist/durable-workflow.d.ts.map +1 -0
  43. package/dist/durable-workflow.js +552 -0
  44. package/dist/durable-workflow.js.map +1 -0
  45. package/dist/graph/topological-sort.d.ts.map +1 -1
  46. package/dist/graph/topological-sort.js +5 -5
  47. package/dist/graph/topological-sort.js.map +1 -1
  48. package/dist/index.d.ts +4 -0
  49. package/dist/index.d.ts.map +1 -1
  50. package/dist/index.js +15 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/logger.d.ts +101 -0
  53. package/dist/logger.d.ts.map +1 -0
  54. package/dist/logger.js +115 -0
  55. package/dist/logger.js.map +1 -0
  56. package/dist/on.d.ts.map +1 -1
  57. package/dist/on.js +3 -3
  58. package/dist/on.js.map +1 -1
  59. package/dist/runtime.d.ts +169 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/runtime.js +275 -0
  62. package/dist/runtime.js.map +1 -0
  63. package/dist/send.d.ts.map +1 -1
  64. package/dist/send.js +4 -3
  65. package/dist/send.js.map +1 -1
  66. package/dist/telemetry.d.ts +150 -0
  67. package/dist/telemetry.d.ts.map +1 -0
  68. package/dist/telemetry.js +388 -0
  69. package/dist/telemetry.js.map +1 -0
  70. package/dist/timer-registry.d.ts +25 -0
  71. package/dist/timer-registry.d.ts.map +1 -1
  72. package/dist/timer-registry.js +42 -8
  73. package/dist/timer-registry.js.map +1 -1
  74. package/dist/types.d.ts +17 -6
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/types.js +1 -1
  77. package/dist/types.js.map +1 -1
  78. package/dist/worker/durable-step.d.ts +481 -0
  79. package/dist/worker/durable-step.d.ts.map +1 -0
  80. package/dist/worker/durable-step.js +606 -0
  81. package/dist/worker/durable-step.js.map +1 -0
  82. package/dist/worker/index.d.ts +106 -0
  83. package/dist/worker/index.d.ts.map +1 -0
  84. package/dist/worker/index.js +124 -0
  85. package/dist/worker/index.js.map +1 -0
  86. package/dist/worker/state-adapter.d.ts +230 -0
  87. package/dist/worker/state-adapter.d.ts.map +1 -0
  88. package/dist/worker/state-adapter.js +409 -0
  89. package/dist/worker/state-adapter.js.map +1 -0
  90. package/dist/worker/topological-executor.d.ts +282 -0
  91. package/dist/worker/topological-executor.d.ts.map +1 -0
  92. package/dist/worker/topological-executor.js +396 -0
  93. package/dist/worker/topological-executor.js.map +1 -0
  94. package/dist/worker/workflow-builder.d.ts +286 -0
  95. package/dist/worker/workflow-builder.d.ts.map +1 -0
  96. package/dist/worker/workflow-builder.js +565 -0
  97. package/dist/worker/workflow-builder.js.map +1 -0
  98. package/dist/worker.d.ts +800 -0
  99. package/dist/worker.d.ts.map +1 -0
  100. package/dist/worker.js +2428 -0
  101. package/dist/worker.js.map +1 -0
  102. package/dist/workflow-builder.d.ts +287 -0
  103. package/dist/workflow-builder.d.ts.map +1 -0
  104. package/dist/workflow-builder.js +762 -0
  105. package/dist/workflow-builder.js.map +1 -0
  106. package/dist/workflow.d.ts +14 -30
  107. package/dist/workflow.d.ts.map +1 -1
  108. package/dist/workflow.js +132 -292
  109. package/dist/workflow.js.map +1 -1
  110. package/examples/01-ecommerce-order-pipeline.ts +358 -0
  111. package/examples/02-content-moderation-cascade.ts +454 -0
  112. package/examples/03-scheduled-reporting-dependencies.ts +479 -0
  113. package/examples/04-database-persistence.ts +518 -0
  114. package/examples/README.md +173 -0
  115. package/package.json +30 -13
  116. package/src/__tests__/digital-objects-adapter.test.ts +274 -0
  117. package/src/__tests__/durable-workflow.test.ts +297 -0
  118. package/src/barrier.ts +48 -7
  119. package/src/cascade-context.ts +36 -29
  120. package/src/cascade-executor.ts +3 -2
  121. package/src/context.ts +41 -12
  122. package/src/cron-parser.ts +347 -0
  123. package/src/cron-scheduler.ts +239 -0
  124. package/src/database-context.ts +658 -0
  125. package/src/digital-objects-adapter.ts +351 -0
  126. package/src/durable-execution-cloudflare.ts +855 -0
  127. package/src/durable-execution.ts +1042 -0
  128. package/src/durable-workflow.ts +717 -0
  129. package/src/graph/topological-sort.ts +6 -8
  130. package/src/index.ts +69 -0
  131. package/src/logger.ts +148 -0
  132. package/src/on.ts +8 -9
  133. package/src/runtime.ts +436 -0
  134. package/src/send.ts +4 -5
  135. package/src/telemetry.ts +577 -0
  136. package/src/timer-registry.ts +44 -10
  137. package/src/types.ts +32 -17
  138. package/src/worker/durable-step.ts +976 -0
  139. package/src/worker/index.ts +216 -0
  140. package/src/worker/state-adapter.ts +589 -0
  141. package/src/worker/topological-executor.ts +625 -0
  142. package/src/worker/workflow-builder.ts +871 -0
  143. package/src/worker.ts +2906 -0
  144. package/src/workflow-builder.ts +1068 -0
  145. package/src/workflow.ts +188 -351
  146. package/test/barrier-join.test.ts +32 -24
  147. package/test/cascade-executor.test.ts +9 -16
  148. package/test/cron-parser.test.ts +314 -0
  149. package/test/cron-scheduler.test.ts +291 -0
  150. package/test/database-context.test.ts +770 -0
  151. package/test/db-provider-adapter.test.ts +862 -0
  152. package/test/durable-execution-cloudflare.test.ts +606 -0
  153. package/test/durable-execution-in-process.test.ts +286 -0
  154. package/test/durable-execution.test.ts +247 -0
  155. package/test/e2e/workflow-scenarios.e2e.test.ts +1039 -0
  156. package/test/integration.test.ts +442 -0
  157. package/test/rpc-surface.test.ts +946 -0
  158. package/test/runtime.test.ts +262 -0
  159. package/test/schedule-timer-cleanup.test.ts +30 -21
  160. package/test/send-race-conditions.test.ts +30 -40
  161. package/test/worker/durable-cascade.test.ts +1117 -0
  162. package/test/worker/durable-step.test.ts +723 -0
  163. package/test/worker/topological-executor.test.ts +1240 -0
  164. package/test/worker/workflow-builder.test.ts +1067 -0
  165. package/test/worker.test.ts +608 -0
  166. package/test/workflow-builder.test.ts +1670 -0
  167. package/test/workflow-cron.test.ts +256 -0
  168. package/test/workflow-state-adapter.test.ts +923 -0
  169. package/test/workflow.test.ts +25 -22
  170. package/tsconfig.json +3 -1
  171. package/vitest.config.ts +38 -1
  172. package/vitest.workers.config.ts +44 -0
  173. package/wrangler.jsonc +22 -0
  174. package/.turbo/turbo-test.log +0 -169
  175. package/LICENSE +0 -21
  176. package/src/context.js +0 -83
  177. package/src/every.js +0 -267
  178. package/src/index.js +0 -71
  179. package/src/on.js +0 -79
  180. package/src/send.js +0 -111
  181. package/src/types.js +0 -4
  182. package/src/workflow.js +0 -455
  183. package/test/context.test.js +0 -116
  184. package/test/every.test.js +0 -282
  185. package/test/on.test.js +0 -80
  186. package/test/send.test.js +0 -89
  187. package/test/workflow.test.js +0 -224
  188. package/vitest.config.js +0 -7
@@ -0,0 +1,481 @@
1
+ /**
2
+ * DurableStep - Wrapper for Cloudflare Workflows step semantics
3
+ *
4
+ * Provides durable execution, retries, sleep, and step metadata
5
+ * by wrapping Cloudflare Workflows' step.do() primitive. This is the
6
+ * foundation for building reliable, resumable workflow steps.
7
+ *
8
+ * ## Features
9
+ *
10
+ * - **Durable Execution**: Steps are persisted and can resume after failures
11
+ * - **Automatic Retries**: Configure retry behavior with backoff strategies
12
+ * - **Timeout Support**: Set per-step timeouts for long-running operations
13
+ * - **Step Context**: Access to nested durable operations and sleep
14
+ * - **Type Safety**: Full TypeScript generics for input/output types
15
+ * - **Cascade Pattern**: Tiered execution with code -> generative -> agentic -> human escalation
16
+ *
17
+ * ## Basic Usage
18
+ *
19
+ * @example
20
+ * ```typescript
21
+ * import { DurableStep } from 'ai-workflows/worker'
22
+ *
23
+ * // Simple step with type inference
24
+ * const fetchData = new DurableStep('fetch-data', async (input: { url: string }) => {
25
+ * const response = await fetch(input.url)
26
+ * return response.json()
27
+ * })
28
+ *
29
+ * // With retry configuration
30
+ * const processPayment = new DurableStep(
31
+ * 'process-payment',
32
+ * { retries: { limit: 3, delay: '1 second', backoff: 'exponential' } },
33
+ * async (input: { amount: number }) => {
34
+ * return { success: true }
35
+ * }
36
+ * )
37
+ *
38
+ * // Run with workflow step
39
+ * const result = await fetchData.run(step, { url: 'https://api.example.com' })
40
+ * ```
41
+ *
42
+ * ## Using StepContext
43
+ *
44
+ * @example
45
+ * ```typescript
46
+ * const complexStep = new DurableStep('complex', async (input, ctx) => {
47
+ * // Access step metadata
48
+ * console.log(`Attempt ${ctx.metadata.attempt} of step ${ctx.metadata.id}`)
49
+ *
50
+ * // Nested durable operation
51
+ * const result = await ctx.do('fetch-api', async () => {
52
+ * return fetch('https://api.example.com').then(r => r.json())
53
+ * })
54
+ *
55
+ * return result
56
+ * })
57
+ * ```
58
+ *
59
+ * ## Cascade Pattern
60
+ *
61
+ * @example
62
+ * ```typescript
63
+ * const processRefund = DurableStep.cascade('process-refund', {
64
+ * code: async (input) => {
65
+ * if (input.amount < 100) return { approved: true }
66
+ * throw new Error('Needs AI review')
67
+ * },
68
+ * generative: async (input, ctx) => {
69
+ * const result = await ctx.ai.run('@cf/meta/llama-3-8b-instruct', {
70
+ * messages: [{ role: 'user', content: 'Approve refund?' }]
71
+ * })
72
+ * return { approved: result.response.includes('yes') }
73
+ * },
74
+ * human: async (input, ctx) => {
75
+ * return ctx.requestHumanReview({ type: 'refund', data: input })
76
+ * }
77
+ * })
78
+ * ```
79
+ *
80
+ * @packageDocumentation
81
+ */
82
+ import { type CascadeContext as BaseCascadeContext, type FiveWHEvent } from '../cascade-context.js';
83
+ /**
84
+ * Configuration for retry behavior
85
+ */
86
+ export interface RetryConfig {
87
+ /** Maximum number of retry attempts */
88
+ limit: number;
89
+ /** Delay between retries (string like '1 second' or number in ms) */
90
+ delay?: string | number;
91
+ /** Backoff strategy */
92
+ backoff?: 'constant' | 'linear' | 'exponential';
93
+ }
94
+ /**
95
+ * Configuration for a step, matching Cloudflare WorkflowStepConfig
96
+ */
97
+ export interface StepConfig {
98
+ /** Retry configuration */
99
+ retries?: RetryConfig;
100
+ /** Timeout for the step (string like '30 seconds' or number in ms) */
101
+ timeout?: string | number;
102
+ }
103
+ /**
104
+ * Metadata about the current step execution
105
+ */
106
+ export interface StepMetadata {
107
+ /** Step identifier */
108
+ id: string;
109
+ /** Current attempt number (1-based) */
110
+ attempt: number;
111
+ /** Configured retry limit (0 if no retries configured) */
112
+ retries: number;
113
+ }
114
+ /**
115
+ * Interface for Cloudflare Workflows step object
116
+ */
117
+ export interface WorkflowStep {
118
+ do<T>(name: string, callback: () => Promise<T>): Promise<T>;
119
+ do<T>(name: string, config: StepConfig, callback: () => Promise<T>): Promise<T>;
120
+ sleep(name: string, duration: string | number): Promise<void>;
121
+ sleepUntil(name: string, timestamp: Date | number): Promise<void>;
122
+ }
123
+ /**
124
+ * Context provided to step functions for additional operations
125
+ */
126
+ export declare class StepContext {
127
+ private workflowStep;
128
+ private stepName;
129
+ private stepConfig;
130
+ private currentAttempt;
131
+ /**
132
+ * Create a new StepContext
133
+ *
134
+ * @param workflowStep - The underlying Cloudflare workflow step
135
+ * @param stepName - The name of the parent step
136
+ * @param stepConfig - Optional step configuration
137
+ * @param attempt - Current attempt number
138
+ */
139
+ constructor(workflowStep: WorkflowStep, stepName: string, stepConfig?: StepConfig, attempt?: number);
140
+ /**
141
+ * Metadata about the current step execution
142
+ */
143
+ get metadata(): StepMetadata;
144
+ /**
145
+ * Execute a named side effect durably
146
+ *
147
+ * @param name - Unique name for this side effect
148
+ * @param callback - Function to execute
149
+ * @returns Result of the callback
150
+ */
151
+ do<T>(name: string, callback: () => Promise<T>): Promise<T>;
152
+ /**
153
+ * Execute a named side effect durably with configuration
154
+ *
155
+ * @param name - Unique name for this side effect
156
+ * @param config - Step configuration (retries, timeout)
157
+ * @param callback - Function to execute
158
+ * @returns Result of the callback
159
+ */
160
+ do<T>(name: string, config: StepConfig, callback: () => Promise<T>): Promise<T>;
161
+ /**
162
+ * Sleep for a specified duration
163
+ *
164
+ * @param name - Unique name for this sleep operation
165
+ * @param duration - Duration to sleep (string like '5 seconds' or number in ms)
166
+ */
167
+ sleep(name: string, duration: string | number): Promise<void>;
168
+ /**
169
+ * Sleep until a specified timestamp
170
+ *
171
+ * @param name - Unique name for this sleep operation
172
+ * @param timestamp - Date or unix timestamp to sleep until
173
+ */
174
+ sleepUntil(name: string, timestamp: Date | number): Promise<void>;
175
+ }
176
+ /**
177
+ * Type for the step function
178
+ */
179
+ export type StepFunction<TInput, TOutput> = (input: TInput, ctx: StepContext) => Promise<TOutput>;
180
+ /**
181
+ * DurableStep - Wrapper for durable function execution
182
+ *
183
+ * Wraps a function for durable execution using Cloudflare Workflows'
184
+ * step.do() primitive. Provides retry configuration, timeout, and
185
+ * access to step context.
186
+ *
187
+ * @typeParam TInput - Input type for the step function
188
+ * @typeParam TOutput - Output type for the step function
189
+ */
190
+ export declare class DurableStep<TInput = void, TOutput = void> {
191
+ /** Step name */
192
+ readonly name: string;
193
+ /** Step configuration (retries, timeout) */
194
+ readonly config?: StepConfig;
195
+ /** The wrapped function */
196
+ readonly fn: (input: TInput, ctx: StepContext) => Promise<TOutput>;
197
+ /**
198
+ * Create a DurableStep with just a name and function
199
+ *
200
+ * @param name - Unique name for this step
201
+ * @param fn - Function to execute
202
+ */
203
+ constructor(name: string, fn: (input: TInput, ctx?: StepContext) => Promise<TOutput>);
204
+ /**
205
+ * Create a DurableStep with name, config, and function
206
+ *
207
+ * @param name - Unique name for this step
208
+ * @param config - Step configuration (retries, timeout)
209
+ * @param fn - Function to execute
210
+ */
211
+ constructor(name: string, config: StepConfig, fn: (input: TInput, ctx?: StepContext) => Promise<TOutput>);
212
+ /**
213
+ * Run the step with durable execution
214
+ *
215
+ * @param workflowStep - The Cloudflare workflow step object
216
+ * @param input - Input for the step function
217
+ * @returns Result of the step function
218
+ */
219
+ run(workflowStep: WorkflowStep, input: TInput): Promise<TOutput>;
220
+ /**
221
+ * Create a durable cascade step with tiered execution
222
+ *
223
+ * The cascade pattern executes tiers in order: code -> generative -> agentic -> human
224
+ * Each tier can short-circuit on success, or escalate to the next tier on failure.
225
+ *
226
+ * @param name - Unique name for this cascade step
227
+ * @param config - Cascade configuration with tier handlers
228
+ * @returns DurableCascadeStep instance
229
+ *
230
+ * @example
231
+ * ```typescript
232
+ * const processRefund = DurableStep.cascade('process-refund', {
233
+ * code: async (input) => {
234
+ * if (input.amount < 100) return { approved: true }
235
+ * throw new Error('Needs AI review')
236
+ * },
237
+ * generative: async (input, ctx) => {
238
+ * const result = await ctx.ai.run('@cf/meta/llama-3-8b-instruct', {
239
+ * messages: [{ role: 'user', content: 'Approve refund?' }]
240
+ * })
241
+ * return { approved: result.response.includes('yes') }
242
+ * },
243
+ * human: async (input, ctx) => {
244
+ * return ctx.requestHumanReview({ type: 'refund', data: input })
245
+ * }
246
+ * })
247
+ * ```
248
+ */
249
+ static cascade<TInput = unknown, TOutput = unknown>(name: string, config: CascadeConfig<TInput, TOutput>): DurableCascadeStep<TInput, TOutput>;
250
+ }
251
+ /**
252
+ * Tier names in cascade order
253
+ */
254
+ export type CascadeTier = 'code' | 'generative' | 'agentic' | 'human';
255
+ /**
256
+ * Default timeouts per tier in milliseconds
257
+ */
258
+ export declare const DEFAULT_CASCADE_TIMEOUTS: Record<CascadeTier, number>;
259
+ /**
260
+ * Ordered list of cascade tiers
261
+ */
262
+ export declare const CASCADE_TIER_ORDER: CascadeTier[];
263
+ /**
264
+ * Human review request
265
+ */
266
+ export interface HumanReviewRequest {
267
+ type: string;
268
+ data: unknown;
269
+ assignee?: string;
270
+ }
271
+ /**
272
+ * AI binding interface (matches Cloudflare AI binding)
273
+ */
274
+ export interface AiBinding {
275
+ run<T = unknown>(model: string, options: {
276
+ messages: Array<{
277
+ role: string;
278
+ content: string;
279
+ }>;
280
+ }): Promise<T & {
281
+ response?: string;
282
+ }>;
283
+ }
284
+ /**
285
+ * Context provided to cascade tier handlers
286
+ */
287
+ export interface CascadeTierContext<TInput = unknown> {
288
+ /** AI binding for generative/agentic tiers */
289
+ ai: AiBinding;
290
+ /** Previous tier errors (for context) */
291
+ previousErrors: Array<{
292
+ tier: CascadeTier;
293
+ error: string;
294
+ attempt: number;
295
+ }>;
296
+ /** Request human review */
297
+ requestHumanReview: (request: HumanReviewRequest) => Promise<{
298
+ reviewId: string;
299
+ status: string;
300
+ }>;
301
+ /** Cascade context for tracing */
302
+ cascadeContext: CascadeContext;
303
+ /** Input data */
304
+ input: TInput;
305
+ /** Current tier */
306
+ tier: CascadeTier;
307
+ }
308
+ /**
309
+ * Configuration for a specific tier
310
+ */
311
+ export interface CascadeTierConfig {
312
+ /** Timeout in milliseconds */
313
+ timeout?: number;
314
+ /** Retry configuration */
315
+ retries?: {
316
+ limit: number;
317
+ delay?: number;
318
+ backoff?: 'constant' | 'linear' | 'exponential';
319
+ };
320
+ /** Custom success condition */
321
+ successCondition?: (result: unknown) => boolean;
322
+ /** Custom error handler */
323
+ onError?: (error: Error, tier: CascadeTier) => void;
324
+ }
325
+ /**
326
+ * Result from a single tier execution
327
+ */
328
+ export interface CascadeTierResult<T = unknown> {
329
+ /** Tier that was executed */
330
+ tier: CascadeTier;
331
+ /** Whether the tier succeeded */
332
+ success: boolean;
333
+ /** Result value (if success) */
334
+ value?: T;
335
+ /** Error (if failure) */
336
+ error?: Error;
337
+ /** Whether the tier timed out */
338
+ timedOut?: boolean;
339
+ /** Duration in milliseconds */
340
+ duration: number;
341
+ /** Number of attempts */
342
+ attempts?: number;
343
+ }
344
+ /**
345
+ * Cascade execution context with tracing
346
+ * Note: This interface extends BaseCascadeContext with no changes.
347
+ * The 'steps' property is inherited from BaseCascadeContext.
348
+ */
349
+ export interface CascadeContext extends BaseCascadeContext {
350
+ }
351
+ /**
352
+ * Result from cascade execution
353
+ */
354
+ export interface CascadeResult<T = unknown> {
355
+ /** Final result value */
356
+ value: T;
357
+ /** Tier that produced the result */
358
+ tier: CascadeTier;
359
+ /** History of all tier executions */
360
+ history: CascadeTierResult<T>[];
361
+ /** Tiers that were skipped */
362
+ skippedTiers: CascadeTier[];
363
+ /** Cascade context with tracing info */
364
+ context: CascadeContext;
365
+ /** Execution metrics */
366
+ metrics: {
367
+ totalDuration: number;
368
+ tierDurations: Record<string, number>;
369
+ };
370
+ }
371
+ /**
372
+ * Handler for code tier (synchronous/deterministic)
373
+ */
374
+ export type CodeTierHandler<TInput, TOutput> = (input: TInput) => Promise<TOutput>;
375
+ /**
376
+ * Handler for AI tiers (generative, agentic)
377
+ */
378
+ export type AiTierHandler<TInput, TOutput> = (input: TInput, ctx: CascadeTierContext<TInput>) => Promise<TOutput>;
379
+ /**
380
+ * Handler for human tier
381
+ */
382
+ export type HumanTierHandler<TInput, TOutput> = (input: TInput, ctx: CascadeTierContext<TInput>) => Promise<TOutput>;
383
+ /**
384
+ * Configuration for DurableStep.cascade()
385
+ */
386
+ export interface CascadeConfig<TInput = unknown, TOutput = unknown> {
387
+ /** Code tier handler (deterministic, fast) */
388
+ code?: CodeTierHandler<TInput, TOutput>;
389
+ /** Generative AI tier handler */
390
+ generative?: AiTierHandler<TInput, TOutput>;
391
+ /** Agentic AI tier handler (multi-step reasoning) */
392
+ agentic?: AiTierHandler<TInput, TOutput>;
393
+ /** Human tier handler (human-in-the-loop) */
394
+ human?: HumanTierHandler<TInput, TOutput>;
395
+ /** Per-tier timeout configuration */
396
+ timeouts?: Partial<Record<CascadeTier, number>>;
397
+ /** Total cascade timeout */
398
+ totalTimeout?: number;
399
+ /** Per-tier configuration */
400
+ tierConfig?: Partial<Record<CascadeTier, CascadeTierConfig>>;
401
+ /** Event callback for 5W+H audit events */
402
+ onEvent?: (event: FiveWHEvent) => void;
403
+ /** Custom result merger */
404
+ resultMerger?: (results: CascadeTierResult<TOutput>[]) => TOutput;
405
+ /** Actor identifier for audit trail */
406
+ actor?: string;
407
+ }
408
+ /**
409
+ * Error thrown when all cascade tiers fail
410
+ */
411
+ export declare class AllTiersFailed extends Error {
412
+ readonly history: CascadeTierResult[];
413
+ constructor(history: CascadeTierResult[]);
414
+ }
415
+ /**
416
+ * Error thrown when cascade times out
417
+ */
418
+ export declare class CascadeTimeout extends Error {
419
+ readonly timeout: number;
420
+ readonly elapsed: number;
421
+ constructor(timeout: number, elapsed: number);
422
+ }
423
+ /**
424
+ * DurableCascadeStep - Durable tiered execution with cascade pattern
425
+ *
426
+ * Combines the cascade pattern (code -> generative -> agentic -> human)
427
+ * with Cloudflare Workflows durability guarantees.
428
+ */
429
+ export declare class DurableCascadeStep<TInput = unknown, TOutput = unknown> {
430
+ /** Cascade name */
431
+ readonly name: string;
432
+ /** Cascade configuration */
433
+ readonly config: CascadeConfig<TInput, TOutput>;
434
+ /** AI binding (injected at runtime) */
435
+ private ai?;
436
+ /** Human review handler */
437
+ private humanReviewHandler?;
438
+ constructor(name: string, config: CascadeConfig<TInput, TOutput>);
439
+ /**
440
+ * Set the AI binding for generative/agentic tiers
441
+ */
442
+ setAi(ai: AiBinding): this;
443
+ /**
444
+ * Set the human review handler
445
+ */
446
+ setHumanReviewHandler(handler: (request: HumanReviewRequest) => Promise<{
447
+ reviewId: string;
448
+ status: string;
449
+ }>): this;
450
+ /**
451
+ * Run the cascade with durable execution
452
+ */
453
+ run(workflowStep: WorkflowStep, input: TInput, options?: {
454
+ ai?: AiBinding;
455
+ humanReviewHandler?: (request: HumanReviewRequest) => Promise<{
456
+ reviewId: string;
457
+ status: string;
458
+ }>;
459
+ }): Promise<CascadeResult<TOutput>>;
460
+ /**
461
+ * Execute a single tier with durability
462
+ */
463
+ private executeTier;
464
+ /**
465
+ * Get the handler for a tier
466
+ */
467
+ private getTierHandler;
468
+ /**
469
+ * Get the next configured tier
470
+ */
471
+ private getNextConfiguredTier;
472
+ /**
473
+ * Emit a 5W+H event
474
+ */
475
+ private emitEvent;
476
+ /**
477
+ * Create a mock AI binding for testing
478
+ */
479
+ private createMockAi;
480
+ }
481
+ //# sourceMappingURL=durable-step.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"durable-step.d.ts","sourceRoot":"","sources":["../../src/worker/durable-step.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgFG;AAEH,OAAO,EAGL,KAAK,cAAc,IAAI,kBAAkB,EACzC,KAAK,WAAW,EACjB,MAAM,uBAAuB,CAAA;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