@ai-sdk/workflow 0.0.0-6b196531-20260710185421

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,1188 @@
1
+ import { LanguageModelV4, LanguageModelV4CallOptions, SharedV4ProviderOptions, LanguageModelV4Prompt, LanguageModelV4StreamPart } from '@ai-sdk/provider';
2
+ import { Context, HasRequiredKey, InferToolSetContext } from '@ai-sdk/provider-utils';
3
+ import { ToolSet, LanguageModel, Instructions, ToolChoice, TelemetryOptions as TelemetryOptions$1, StopCondition, ActiveTools, LanguageModelResponseMetadata, LanguageModelUsage, FinishReason, ToolCallRepairFunction, Experimental_SandboxSession, StepResult, GenerateTextOnStepEndCallback, ModelMessage, Experimental_LanguageModelStreamPart, UIMessage, UIMessageChunk, ChatTransport, PrepareSendMessagesRequest, PrepareReconnectToStreamRequest, ChatRequestOptions } from 'ai';
4
+ export { Experimental_LanguageModelStreamPart as ModelCallStreamPart, Output, ToolCallRepairFunction } from 'ai';
5
+
6
+ /**
7
+ * Shared types for AI SDK V4.
8
+ */
9
+
10
+ /**
11
+ * Language model type for AI SDK V4.
12
+ *
13
+ * This is a simple alias for LanguageModelV4 from @ai-sdk/provider.
14
+ */
15
+ type CompatibleLanguageModel = LanguageModelV4;
16
+
17
+ /**
18
+ * Callback function to be called after each step completes.
19
+ * Alias for the AI SDK's GenerateTextOnStepEndCallback, using
20
+ * WorkflowAgent-consistent naming.
21
+ */
22
+ type WorkflowAgentOnStepEndCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = GenerateTextOnStepEndCallback<TTools, TRuntimeContext>;
23
+ /**
24
+ * Callback function to be called after each step completes.
25
+ * Deprecated alias for `WorkflowAgentOnStepEndCallback`.
26
+ *
27
+ * @deprecated Use `WorkflowAgentOnStepEndCallback` instead.
28
+ */
29
+ type WorkflowAgentOnStepFinishCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = WorkflowAgentOnStepEndCallback<TTools, TRuntimeContext>;
30
+ /**
31
+ * Infer the type of the tools of a workflow agent.
32
+ */
33
+ type InferWorkflowAgentTools<WORKFLOW_AGENT> = WORKFLOW_AGENT extends WorkflowAgent<infer TOOLS, any> ? TOOLS : never;
34
+ /**
35
+ * Infer the UI message type of a workflow agent.
36
+ */
37
+ type InferWorkflowAgentUIMessage<_WORKFLOW_AGENT, MESSAGE_METADATA = unknown> = UIMessage<MESSAGE_METADATA>;
38
+
39
+ /**
40
+ * Output specification interface for structured outputs.
41
+ * Use `Output.object({ schema })` or `Output.text()` to create an output specification.
42
+ */
43
+ interface OutputSpecification<OUTPUT, PARTIAL> {
44
+ readonly name: string;
45
+ responseFormat: PromiseLike<LanguageModelV4CallOptions['responseFormat']>;
46
+ parsePartialOutput(options: {
47
+ text: string;
48
+ }): Promise<{
49
+ partial: PARTIAL;
50
+ } | undefined>;
51
+ parseCompleteOutput(options: {
52
+ text: string;
53
+ }, context: {
54
+ response: LanguageModelResponseMetadata;
55
+ usage: LanguageModelUsage;
56
+ finishReason: FinishReason;
57
+ }): Promise<OUTPUT>;
58
+ }
59
+ /**
60
+ * Provider-specific options type. This is equivalent to SharedV4ProviderOptions from @ai-sdk/provider.
61
+ */
62
+ type ProviderOptions = SharedV4ProviderOptions;
63
+ type WorkflowAgentToolsContextParameter<TTools extends ToolSet> = HasRequiredKey<InferToolSetContext<TTools>> extends true ? {
64
+ toolsContext: InferToolSetContext<TTools>;
65
+ } : {
66
+ toolsContext?: never;
67
+ };
68
+ type TelemetryOptions<TRuntimeContext extends Context = Context, TTools extends ToolSet = ToolSet> = TelemetryOptions$1<TRuntimeContext, TTools>;
69
+ /**
70
+ * A transformation that is applied to the stream.
71
+ */
72
+ type StreamTextTransform<TTools extends ToolSet> = (options: {
73
+ tools: TTools;
74
+ stopStream: () => void;
75
+ }) => TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart>;
76
+
77
+ /**
78
+ * Custom download function for URLs.
79
+ * The function receives an array of URLs with information about whether
80
+ * the model supports them directly.
81
+ */
82
+ type DownloadFunction = (options: {
83
+ url: URL;
84
+ isUrlSupportedByModel: boolean;
85
+ }[]) => PromiseLike<({
86
+ data: Uint8Array;
87
+ mediaType: string | undefined;
88
+ } | null)[]>;
89
+ /**
90
+ * Generation settings that can be passed to the model.
91
+ * These map directly to LanguageModelV4CallOptions.
92
+ */
93
+ interface GenerationSettings {
94
+ /**
95
+ * Maximum number of tokens to generate.
96
+ */
97
+ maxOutputTokens?: number;
98
+ /**
99
+ * Temperature setting. The range depends on the provider and model.
100
+ * It is recommended to set either `temperature` or `topP`, but not both.
101
+ */
102
+ temperature?: number;
103
+ /**
104
+ * Nucleus sampling. This is a number between 0 and 1.
105
+ * E.g. 0.1 would mean that only tokens with the top 10% probability mass are considered.
106
+ * It is recommended to set either `temperature` or `topP`, but not both.
107
+ */
108
+ topP?: number;
109
+ /**
110
+ * Only sample from the top K options for each subsequent token.
111
+ * Used to remove "long tail" low probability responses.
112
+ * Recommended for advanced use cases only. You usually only need to use temperature.
113
+ */
114
+ topK?: number;
115
+ /**
116
+ * Presence penalty setting. It affects the likelihood of the model to
117
+ * repeat information that is already in the prompt.
118
+ * The presence penalty is a number between -1 (increase repetition)
119
+ * and 1 (maximum penalty, decrease repetition). 0 means no penalty.
120
+ */
121
+ presencePenalty?: number;
122
+ /**
123
+ * Frequency penalty setting. It affects the likelihood of the model
124
+ * to repeatedly use the same words or phrases.
125
+ * The frequency penalty is a number between -1 (increase repetition)
126
+ * and 1 (maximum penalty, decrease repetition). 0 means no penalty.
127
+ */
128
+ frequencyPenalty?: number;
129
+ /**
130
+ * Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.
131
+ * Providers may have limits on the number of stop sequences.
132
+ */
133
+ stopSequences?: string[];
134
+ /**
135
+ * The seed (integer) to use for random sampling. If set and supported
136
+ * by the model, calls will generate deterministic results.
137
+ */
138
+ seed?: number;
139
+ /**
140
+ * Maximum number of retries. Set to 0 to disable retries.
141
+ * Note: In workflow context, retries are typically handled by the workflow step mechanism.
142
+ * @default 2
143
+ */
144
+ maxRetries?: number;
145
+ /**
146
+ * Abort signal for cancelling the operation.
147
+ */
148
+ abortSignal?: AbortSignal;
149
+ /**
150
+ * Additional HTTP headers to be sent with the request.
151
+ * Only applicable for HTTP-based providers.
152
+ */
153
+ headers?: Record<string, string | undefined>;
154
+ /**
155
+ * Reasoning effort level for the model. Controls how much reasoning
156
+ * the model performs before generating a response.
157
+ */
158
+ reasoning?: LanguageModelV4CallOptions['reasoning'];
159
+ /**
160
+ * Additional provider-specific options. They are passed through
161
+ * to the provider from the AI SDK and enable provider-specific
162
+ * functionality that can be fully encapsulated in the provider.
163
+ */
164
+ providerOptions?: ProviderOptions;
165
+ }
166
+ /**
167
+ * Information passed to the prepareStep callback.
168
+ */
169
+ interface PrepareStepInfo<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> {
170
+ /**
171
+ * The current model configuration (string or function).
172
+ * The function should return a LanguageModelV4 instance.
173
+ */
174
+ model: LanguageModel;
175
+ /**
176
+ * The current step number (0-indexed).
177
+ */
178
+ stepNumber: number;
179
+ /**
180
+ * All previous steps with their results.
181
+ */
182
+ steps: StepResult<TTools, TRuntimeContext>[];
183
+ /**
184
+ * The messages that will be sent to the model.
185
+ * This is the LanguageModelV4Prompt format used internally.
186
+ */
187
+ messages: LanguageModelV4Prompt;
188
+ /**
189
+ * The runtime context that flows through the agent loop.
190
+ * Treat the value as immutable; return a new `runtimeContext` from
191
+ * `prepareStep` to update it for the current and subsequent steps.
192
+ */
193
+ runtimeContext: TRuntimeContext;
194
+ /**
195
+ * Per-tool context, keyed by tool name. Each tool receives only its own
196
+ * validated entry as `context` during execution.
197
+ * Treat the value as immutable; return a new `toolsContext` from
198
+ * `prepareStep` to update it for the current and subsequent steps.
199
+ */
200
+ toolsContext: InferToolSetContext<TTools>;
201
+ /**
202
+ * The sandbox environment that the step is operating in.
203
+ */
204
+ experimental_sandbox?: Experimental_SandboxSession;
205
+ }
206
+ /**
207
+ * Return type from the prepareStep callback.
208
+ * All properties are optional - only return the ones you want to override.
209
+ */
210
+ interface PrepareStepResult<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> extends Partial<GenerationSettings> {
211
+ /**
212
+ * Override the model for this step.
213
+ */
214
+ model?: LanguageModel;
215
+ /**
216
+ * Override the system message for this step.
217
+ */
218
+ system?: string;
219
+ /**
220
+ * Override the messages for this step.
221
+ * Use this for context management or message injection.
222
+ */
223
+ messages?: LanguageModelV4Prompt;
224
+ /**
225
+ * Override the tool choice for this step.
226
+ */
227
+ toolChoice?: ToolChoice<ToolSet>;
228
+ /**
229
+ * Override the active tools for this step.
230
+ * Limits the tools that are available for the model to call.
231
+ */
232
+ activeTools?: string[];
233
+ /**
234
+ * Updated runtime context for the current and subsequent steps.
235
+ * Returning a value replaces the agent's runtime context.
236
+ */
237
+ runtimeContext?: TRuntimeContext;
238
+ /**
239
+ * Updated per-tool context for the current and subsequent steps.
240
+ * Returning a value replaces the agent's tools context.
241
+ */
242
+ toolsContext?: InferToolSetContext<TTools>;
243
+ /**
244
+ * Override the sandbox environment for this step.
245
+ */
246
+ experimental_sandbox?: Experimental_SandboxSession;
247
+ }
248
+ /**
249
+ * Callback function called before each step in the agent loop.
250
+ * Use this to modify settings, manage context, or implement dynamic behavior.
251
+ */
252
+ type PrepareStepCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = (info: PrepareStepInfo<TTools, TRuntimeContext>) => PrepareStepResult<TTools, TRuntimeContext> | undefined | Promise<PrepareStepResult<TTools, TRuntimeContext> | undefined>;
253
+ /**
254
+ * Options passed to the prepareCall callback.
255
+ */
256
+ interface PrepareCallOptions<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> extends Partial<GenerationSettings> {
257
+ model: LanguageModel;
258
+ tools: TTools;
259
+ instructions?: Instructions;
260
+ toolChoice?: ToolChoice<TTools>;
261
+ telemetry?: TelemetryOptions<TRuntimeContext, TTools>;
262
+ /**
263
+ * Runtime context that flows through the agent loop.
264
+ * Treat as immutable; return a new `runtimeContext` to update it for the call.
265
+ */
266
+ runtimeContext?: TRuntimeContext;
267
+ /**
268
+ * Per-tool context, keyed by tool name.
269
+ */
270
+ toolsContext?: InferToolSetContext<TTools>;
271
+ messages: ModelMessage[];
272
+ }
273
+ /**
274
+ * Result of the prepareCall callback. All fields are optional —
275
+ * only returned fields override the defaults.
276
+ * Note: `tools` cannot be overridden via prepareCall because they are
277
+ * bound at construction time for type safety.
278
+ */
279
+ type PrepareCallResult<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = Partial<Omit<PrepareCallOptions<TTools, TRuntimeContext>, 'tools'>>;
280
+ /**
281
+ * Callback called once before the agent loop starts to transform call parameters.
282
+ */
283
+ type PrepareCallCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = (options: PrepareCallOptions<TTools, TRuntimeContext>) => PrepareCallResult<TTools, TRuntimeContext> | Promise<PrepareCallResult<TTools, TRuntimeContext>>;
284
+ /**
285
+ * Configuration options for creating a {@link WorkflowAgent} instance.
286
+ */
287
+ type WorkflowAgentOptions<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = GenerationSettings & WorkflowAgentToolsContextParameter<TTools> & {
288
+ /**
289
+ * The id of the agent.
290
+ */
291
+ id?: string;
292
+ /**
293
+ * The model provider to use for the agent.
294
+ *
295
+ * This should be a string compatible with the Vercel AI Gateway (e.g., 'anthropic/claude-opus'),
296
+ * or a LanguageModelV4 instance from a provider.
297
+ */
298
+ model: LanguageModel;
299
+ /**
300
+ * A set of tools available to the agent.
301
+ * Tools can be implemented as workflow steps for automatic retries and persistence,
302
+ * or as regular workflow-level logic using core library features like sleep() and Hooks.
303
+ */
304
+ tools?: TTools;
305
+ /**
306
+ * Agent instructions. Can be a string, a SystemModelMessage, or an array of SystemModelMessages.
307
+ * Supports provider-specific options (e.g., caching) when using the SystemModelMessage form.
308
+ */
309
+ instructions?: Instructions;
310
+ /**
311
+ * Optional system prompt to guide the agent's behavior.
312
+ * @deprecated Use `instructions` instead.
313
+ */
314
+ system?: string;
315
+ /**
316
+ * The tool choice strategy. Default: 'auto'.
317
+ */
318
+ toolChoice?: ToolChoice<TTools>;
319
+ /**
320
+ * Optional telemetry configuration.
321
+ */
322
+ telemetry?: TelemetryOptions<TRuntimeContext, TTools>;
323
+ /**
324
+ * Default runtime context for every stream call on this agent.
325
+ *
326
+ * The runtime context flows through `prepareStep`, lifecycle callbacks,
327
+ * and step results.
328
+ * Treat as immutable; return a new `runtimeContext` from `prepareStep`
329
+ * to update it between steps.
330
+ *
331
+ * In workflow context, keep values serializable so they can cross workflow
332
+ * and step boundaries.
333
+ *
334
+ * Per-stream `runtimeContext` values passed to `stream()` override this default.
335
+ */
336
+ runtimeContext?: TRuntimeContext;
337
+ /**
338
+ * Default stop condition for the agent loop. When the condition is an array,
339
+ * any of the conditions can be met to stop the generation.
340
+ *
341
+ * Per-stream `stopWhen` values passed to `stream()` override this default.
342
+ */
343
+ stopWhen?: StopCondition<NoInfer<ToolSet>, any> | Array<StopCondition<NoInfer<ToolSet>, any>>;
344
+ /**
345
+ * Default set of active tools that limits which tools the model can call,
346
+ * without changing the tool call and result types in the result.
347
+ *
348
+ * Per-stream `activeTools` values passed to `stream()` override this default.
349
+ */
350
+ activeTools?: ActiveTools<NoInfer<TTools>>;
351
+ /**
352
+ * Default output specification for structured outputs.
353
+ * Use `Output.object({ schema })` for structured output or `Output.text()` for text output.
354
+ *
355
+ * Per-stream `output` values passed to `stream()` override this default.
356
+ */
357
+ output?: OutputSpecification<any, any>;
358
+ /**
359
+ * Default function that attempts to repair a tool call that failed to parse.
360
+ *
361
+ * Per-stream `repairToolCall` values passed to `stream()` override this default.
362
+ */
363
+ repairToolCall?: ToolCallRepairFunction<TTools>;
364
+ /**
365
+ * Default function that attempts to repair a tool call that failed to parse.
366
+ *
367
+ * Per-stream `repairToolCall` values passed to `stream()` override this default.
368
+ *
369
+ * @deprecated Use `repairToolCall` instead.
370
+ */
371
+ experimental_repairToolCall?: ToolCallRepairFunction<TTools>;
372
+ /**
373
+ * Default custom download function to use for URLs.
374
+ *
375
+ * Per-stream `experimental_download` values passed to `stream()` override this default.
376
+ */
377
+ experimental_download?: DownloadFunction;
378
+ /**
379
+ * Default sandbox environment passed through to tool execution as
380
+ * `experimental_sandbox`.
381
+ *
382
+ * Per-stream `experimental_sandbox` values passed to `stream()` override this default.
383
+ */
384
+ experimental_sandbox?: Experimental_SandboxSession;
385
+ /**
386
+ * Default callback function called before each step in the agent loop.
387
+ * Use this to modify settings, manage context, or inject messages dynamically
388
+ * for every stream call on this agent instance.
389
+ *
390
+ * Per-stream `prepareStep` values passed to `stream()` override this default.
391
+ */
392
+ prepareStep?: PrepareStepCallback<TTools, TRuntimeContext>;
393
+ /**
394
+ * Callback function to be called after each step completes.
395
+ */
396
+ onStepEnd?: WorkflowAgentOnStepEndCallback<TTools, TRuntimeContext>;
397
+ /**
398
+ * Callback function to be called after each step completes.
399
+ *
400
+ * @deprecated Use `onStepEnd` instead.
401
+ */
402
+ onStepFinish?: WorkflowAgentOnStepFinishCallback<TTools, TRuntimeContext>;
403
+ /**
404
+ * Callback that is called when the LLM response and all request tool executions are finished.
405
+ */
406
+ onEnd?: WorkflowAgentOnEndCallback<TTools, TRuntimeContext>;
407
+ /**
408
+ * Callback that is called when the LLM response and all request tool executions are finished.
409
+ *
410
+ * @deprecated Use `onEnd` instead.
411
+ */
412
+ onFinish?: WorkflowAgentOnFinishCallback<TTools, TRuntimeContext>;
413
+ /**
414
+ * Callback called when the agent starts streaming, before any LLM calls.
415
+ */
416
+ experimental_onStart?: WorkflowAgentOnStartCallback<TTools, TRuntimeContext>;
417
+ /**
418
+ * Callback called before each step (LLM call) begins.
419
+ */
420
+ experimental_onStepStart?: WorkflowAgentOnStepStartCallback<TTools, TRuntimeContext>;
421
+ /**
422
+ * Callback called before a tool's execute function runs.
423
+ */
424
+ onToolExecutionStart?: WorkflowAgentOnToolExecutionStartCallback<TTools>;
425
+ /**
426
+ * Callback called after a tool execution completes.
427
+ */
428
+ onToolExecutionEnd?: WorkflowAgentOnToolExecutionEndCallback<TTools>;
429
+ /**
430
+ * Prepare the parameters for the stream call.
431
+ * Called once before the agent loop starts. Use this to transform
432
+ * model, tools, instructions, or other settings based on runtime context.
433
+ */
434
+ prepareCall?: PrepareCallCallback<TTools, TRuntimeContext>;
435
+ /**
436
+ * Whether to allow system messages inside the `prompt` or `messages` fields.
437
+ * When `false` (the default), system messages in `prompt` or `messages` are
438
+ * rejected to prevent prompt-injection attacks. Set to `true` only when you
439
+ * intentionally interleave system messages with user messages.
440
+ *
441
+ * @default false
442
+ */
443
+ allowSystemInMessages?: boolean;
444
+ };
445
+ /**
446
+ * Callback that is called when the LLM response and all request tool executions are finished.
447
+ */
448
+ type WorkflowAgentOnEndCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context, OUTPUT = never> = (event: {
449
+ /**
450
+ * Details for all steps.
451
+ */
452
+ readonly steps: StepResult<TTools, TRuntimeContext>[];
453
+ /**
454
+ * The final messages including all tool calls and results.
455
+ */
456
+ readonly messages: ModelMessage[];
457
+ /**
458
+ * The text output from the last step.
459
+ */
460
+ readonly text: string;
461
+ /**
462
+ * The finish reason from the last step.
463
+ */
464
+ readonly finishReason: FinishReason;
465
+ /**
466
+ * The total token usage across all steps.
467
+ */
468
+ readonly usage: LanguageModelUsage;
469
+ /**
470
+ * The total token usage across all steps.
471
+ */
472
+ readonly totalUsage: LanguageModelUsage;
473
+ /**
474
+ * The runtime context at the end of the agent loop.
475
+ */
476
+ readonly runtimeContext: TRuntimeContext;
477
+ /**
478
+ * The per-tool context at the end of the agent loop.
479
+ */
480
+ readonly toolsContext: InferToolSetContext<TTools>;
481
+ /**
482
+ * The generated structured output. It uses the `output` specification.
483
+ * Only available when `output` is specified.
484
+ */
485
+ readonly output: OUTPUT;
486
+ }) => PromiseLike<void> | void;
487
+ /**
488
+ * Callback that is called when the LLM response and all request tool executions are finished.
489
+ *
490
+ * @deprecated Use `WorkflowAgentOnEndCallback` instead.
491
+ */
492
+ type WorkflowAgentOnFinishCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context, OUTPUT = never> = WorkflowAgentOnEndCallback<TTools, TRuntimeContext, OUTPUT>;
493
+ /**
494
+ * Callback that is invoked when an error occurs during streaming.
495
+ */
496
+ type WorkflowAgentOnErrorCallback = (event: {
497
+ error: unknown;
498
+ }) => PromiseLike<void> | void;
499
+ /**
500
+ * Callback that is set using the `onAbort` option.
501
+ */
502
+ type WorkflowAgentOnAbortCallback<TTools extends ToolSet = ToolSet> = (event: {
503
+ /**
504
+ * Details for all previously finished steps.
505
+ */
506
+ readonly steps: StepResult<TTools, any>[];
507
+ }) => PromiseLike<void> | void;
508
+ /**
509
+ * Callback that is called when the agent starts streaming, before any LLM calls.
510
+ */
511
+ type WorkflowAgentOnStartCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = (event: {
512
+ /** The model being used */
513
+ readonly model: LanguageModel;
514
+ /** The messages being sent */
515
+ readonly messages: ModelMessage[];
516
+ /** Shared runtime context for this agent loop */
517
+ readonly runtimeContext: TRuntimeContext;
518
+ /** Per-tool context map for this agent loop */
519
+ readonly toolsContext: InferToolSetContext<TTools>;
520
+ }) => PromiseLike<void> | void;
521
+ /**
522
+ * Callback that is called before each step (LLM call) begins.
523
+ */
524
+ type WorkflowAgentOnStepStartCallback<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> = (event: {
525
+ /** The current step number (0-based) */
526
+ readonly stepNumber: number;
527
+ /** The model being used for this step */
528
+ readonly model: LanguageModel;
529
+ /** The messages being sent for this step */
530
+ readonly messages: ModelMessage[];
531
+ /** Results from all previously finished steps */
532
+ readonly steps: ReadonlyArray<StepResult<TTools, TRuntimeContext>>;
533
+ /** Shared runtime context for this step */
534
+ readonly runtimeContext: TRuntimeContext;
535
+ /** Per-tool context map for this step */
536
+ readonly toolsContext: InferToolSetContext<TTools>;
537
+ }) => PromiseLike<void> | void;
538
+ /**
539
+ * Callback that is called before a tool's execute function runs.
540
+ */
541
+ type WorkflowAgentOnToolExecutionStartCallback<TTools extends ToolSet = ToolSet> = (event: {
542
+ /** The tool call being executed */
543
+ readonly toolCall: ToolCall;
544
+ /** The current step number (0-based) */
545
+ readonly stepNumber: number;
546
+ /** Messages sent to the language model for the step that produced the call */
547
+ readonly messages: ModelMessage[];
548
+ /** Tool-specific context passed to the tool */
549
+ readonly toolContext: InferToolSetContext<TTools>[keyof InferToolSetContext<TTools>] | undefined;
550
+ }) => PromiseLike<void> | void;
551
+ /**
552
+ * Callback that is called after a tool execution completes.
553
+ * Uses a discriminated union pattern: check `success` to determine
554
+ * whether `output` or `error` is available.
555
+ */
556
+ type WorkflowAgentOnToolExecutionEndCallback<TTools extends ToolSet = ToolSet> = (event: {
557
+ /** The tool call that was executed */
558
+ readonly toolCall: ToolCall;
559
+ /** The current step number (0-based) */
560
+ readonly stepNumber: number;
561
+ /** Execution time in milliseconds */
562
+ readonly durationMs: number;
563
+ /** Messages sent to the language model for the step that produced the call */
564
+ readonly messages: ModelMessage[];
565
+ /** Tool-specific context passed to the tool */
566
+ readonly toolContext: InferToolSetContext<TTools>[keyof InferToolSetContext<TTools>] | undefined;
567
+ /** Whether the tool call succeeded */
568
+ readonly success: true;
569
+ /** The tool result */
570
+ readonly output: unknown;
571
+ readonly error?: never;
572
+ } | {
573
+ /** The tool call that was executed */
574
+ readonly toolCall: ToolCall;
575
+ /** The current step number (0-based) */
576
+ readonly stepNumber: number;
577
+ /** Execution time in milliseconds */
578
+ readonly durationMs: number;
579
+ /** Messages sent to the language model for the step that produced the call */
580
+ readonly messages: ModelMessage[];
581
+ /** Tool-specific context passed to the tool */
582
+ readonly toolContext: InferToolSetContext<TTools>[keyof InferToolSetContext<TTools>] | undefined;
583
+ /** Whether the tool call succeeded */
584
+ readonly success: false;
585
+ /** The error that occurred */
586
+ readonly error: unknown;
587
+ readonly output?: never;
588
+ }) => PromiseLike<void> | void;
589
+ /**
590
+ * Options for the {@link WorkflowAgent.stream} method.
591
+ */
592
+ type WorkflowAgentStreamOptions<TTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context, OUTPUT = never, PARTIAL_OUTPUT = never> = Partial<GenerationSettings> & ({
593
+ /**
594
+ * A prompt. It can be either a text prompt or a list of messages.
595
+ *
596
+ * You can either use `prompt` or `messages` but not both.
597
+ */
598
+ prompt: string | Array<ModelMessage>;
599
+ /**
600
+ * A list of messages.
601
+ *
602
+ * You can either use `prompt` or `messages` but not both.
603
+ */
604
+ messages?: never;
605
+ } | {
606
+ /**
607
+ * The conversation messages to process. Should follow the AI SDK's ModelMessage format.
608
+ *
609
+ * You can either use `prompt` or `messages` but not both.
610
+ */
611
+ messages: Array<ModelMessage>;
612
+ /**
613
+ * A prompt. It can be either a text prompt or a list of messages.
614
+ *
615
+ * You can either use `prompt` or `messages` but not both.
616
+ */
617
+ prompt?: never;
618
+ }) & {
619
+ /**
620
+ * Optional system prompt override. If provided, overrides the system prompt from the constructor.
621
+ */
622
+ system?: string;
623
+ /**
624
+ * A WritableStream that receives raw LanguageModelV4StreamPart chunks in real-time
625
+ * as the model generates them. This enables streaming to the client without
626
+ * coupling WorkflowAgent to UIMessageChunk format.
627
+ *
628
+ * Convert to UIMessageChunks at the response boundary using
629
+ * `createUIMessageChunkTransform()` from `@ai-sdk/workflow`.
630
+ *
631
+ * @example
632
+ * ```typescript
633
+ * // In the workflow:
634
+ * await agent.stream({
635
+ * messages,
636
+ * writable: getWritable<ModelCallStreamPart>(),
637
+ * });
638
+ *
639
+ * // In the route handler:
640
+ * return createUIMessageStreamResponse({
641
+ * stream: run.readable.pipeThrough(createModelCallToUIChunkTransform()),
642
+ * });
643
+ * ```
644
+ */
645
+ writable?: WritableStream<Experimental_LanguageModelStreamPart<ToolSet>>;
646
+ /**
647
+ * Condition for stopping the generation when there are tool results in the last step.
648
+ * When the condition is an array, any of the conditions can be met to stop the generation.
649
+ */
650
+ stopWhen?: StopCondition<NoInfer<ToolSet>, any> | Array<StopCondition<NoInfer<ToolSet>, any>>;
651
+ /**
652
+ * The tool choice strategy. Default: 'auto'.
653
+ * Overrides the toolChoice from the constructor if provided.
654
+ */
655
+ toolChoice?: ToolChoice<TTools>;
656
+ /**
657
+ * Limits the tools that are available for the model to call without
658
+ * changing the tool call and result types in the result.
659
+ */
660
+ activeTools?: ActiveTools<NoInfer<TTools>>;
661
+ /**
662
+ * Optional telemetry configuration.
663
+ */
664
+ telemetry?: TelemetryOptions<TRuntimeContext, TTools>;
665
+ /**
666
+ * Runtime context that flows through the agent loop.
667
+ *
668
+ * Treat as immutable; return a new `runtimeContext` from `prepareStep`
669
+ * to update it between steps.
670
+ *
671
+ * In workflow context, keep values serializable so they can cross workflow
672
+ * and step boundaries.
673
+ *
674
+ * Overrides the constructor-level `runtimeContext` if provided.
675
+ */
676
+ runtimeContext?: TRuntimeContext;
677
+ /**
678
+ * Per-tool context, keyed by tool name. Each tool receives only its own
679
+ * validated entry as `context` during execution. Tools that declare a
680
+ * `contextSchema` validate their entry against the schema.
681
+ *
682
+ * In workflow context, keep values serializable so they can cross workflow
683
+ * and step boundaries.
684
+ *
685
+ * Overrides the constructor-level `toolsContext` if provided.
686
+ */
687
+ toolsContext?: InferToolSetContext<TTools>;
688
+ /**
689
+ * Optional specification for parsing structured outputs from the LLM response.
690
+ * Use `Output.object({ schema })` for structured output or `Output.text()` for text output.
691
+ *
692
+ * @example
693
+ * ```typescript
694
+ * import { Output } from '@workflow/ai';
695
+ * import { z } from 'zod';
696
+ *
697
+ * const result = await agent.stream({
698
+ * messages: [...],
699
+ * writable: getWritable(),
700
+ * output: Output.object({
701
+ * schema: z.object({
702
+ * sentiment: z.enum(['positive', 'negative', 'neutral']),
703
+ * confidence: z.number(),
704
+ * }),
705
+ * }),
706
+ * });
707
+ *
708
+ * console.log(result.output); // { sentiment: 'positive', confidence: 0.95 }
709
+ * ```
710
+ */
711
+ output?: OutputSpecification<OUTPUT, PARTIAL_OUTPUT>;
712
+ /**
713
+ * Whether to include raw chunks from the provider in the stream.
714
+ * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.
715
+ * This allows access to cutting-edge provider features not yet wrapped by the AI SDK.
716
+ * Defaults to false.
717
+ */
718
+ includeRawChunks?: boolean;
719
+ /**
720
+ * A function that attempts to repair a tool call that failed to parse.
721
+ */
722
+ repairToolCall?: ToolCallRepairFunction<TTools>;
723
+ /**
724
+ * A function that attempts to repair a tool call that failed to parse.
725
+ *
726
+ * @deprecated Use `repairToolCall` instead.
727
+ */
728
+ experimental_repairToolCall?: ToolCallRepairFunction<TTools>;
729
+ /**
730
+ * Optional stream transformations.
731
+ * They are applied in the order they are provided.
732
+ * The stream transformations must maintain the stream structure for streamText to work correctly.
733
+ */
734
+ experimental_transform?: StreamTextTransform<TTools> | Array<StreamTextTransform<TTools>>;
735
+ /**
736
+ * Custom download function to use for URLs.
737
+ * By default, files are downloaded if the model does not support the URL for the given media type.
738
+ */
739
+ experimental_download?: DownloadFunction;
740
+ /**
741
+ * Sandbox environment passed through to tool execution as
742
+ * `experimental_sandbox`. Overrides the constructor-level value if provided.
743
+ */
744
+ experimental_sandbox?: Experimental_SandboxSession;
745
+ /**
746
+ * Callback function to be called after each step completes.
747
+ */
748
+ onStepEnd?: WorkflowAgentOnStepEndCallback<TTools, TRuntimeContext>;
749
+ /**
750
+ * Callback function to be called after each step completes.
751
+ *
752
+ * @deprecated Use `onStepEnd` instead.
753
+ */
754
+ onStepFinish?: WorkflowAgentOnStepFinishCallback<TTools, TRuntimeContext>;
755
+ /**
756
+ * Callback that is invoked when an error occurs during streaming.
757
+ * You can use it to log errors.
758
+ */
759
+ onError?: WorkflowAgentOnErrorCallback;
760
+ /**
761
+ * Callback that is called when the LLM response and all request tool executions
762
+ * (for tools that have an `execute` function) are finished.
763
+ */
764
+ onEnd?: WorkflowAgentOnEndCallback<TTools, TRuntimeContext, OUTPUT>;
765
+ /**
766
+ * Callback that is called when the LLM response and all request tool executions
767
+ * (for tools that have an `execute` function) are finished.
768
+ *
769
+ * @deprecated Use `onEnd` instead.
770
+ */
771
+ onFinish?: WorkflowAgentOnFinishCallback<TTools, TRuntimeContext, OUTPUT>;
772
+ /**
773
+ * Callback that is called when the operation is aborted.
774
+ */
775
+ onAbort?: WorkflowAgentOnAbortCallback<TTools>;
776
+ /**
777
+ * Callback called when the agent starts streaming, before any LLM calls.
778
+ */
779
+ experimental_onStart?: WorkflowAgentOnStartCallback<TTools, TRuntimeContext>;
780
+ /**
781
+ * Callback called before each step (LLM call) begins.
782
+ */
783
+ experimental_onStepStart?: WorkflowAgentOnStepStartCallback<TTools, TRuntimeContext>;
784
+ /**
785
+ * Callback called before a tool's execute function runs.
786
+ */
787
+ onToolExecutionStart?: WorkflowAgentOnToolExecutionStartCallback<TTools>;
788
+ /**
789
+ * Callback called after a tool execution completes.
790
+ */
791
+ onToolExecutionEnd?: WorkflowAgentOnToolExecutionEndCallback<TTools>;
792
+ /**
793
+ * Callback function called before each step in the agent loop.
794
+ * Use this to modify settings, manage context, or inject messages dynamically.
795
+ *
796
+ * @example
797
+ * ```typescript
798
+ * prepareStep: async ({ messages, stepNumber }) => {
799
+ * // Inject messages from a queue
800
+ * const queuedMessages = await getQueuedMessages();
801
+ * if (queuedMessages.length > 0) {
802
+ * return {
803
+ * messages: [...messages, ...queuedMessages],
804
+ * };
805
+ * }
806
+ * return {};
807
+ * }
808
+ * ```
809
+ */
810
+ prepareStep?: PrepareStepCallback<TTools, TRuntimeContext>;
811
+ /**
812
+ * Timeout in milliseconds for the stream operation.
813
+ * When specified, creates an AbortSignal that will abort the operation after the given time.
814
+ * If both `timeout` and `abortSignal` are provided, whichever triggers first will abort.
815
+ */
816
+ timeout?: number;
817
+ /**
818
+ * Whether to send a 'finish' chunk to the writable stream when streaming completes.
819
+ * @default true
820
+ */
821
+ sendFinish?: boolean;
822
+ /**
823
+ * Whether to prevent the writable stream from being closed after streaming completes.
824
+ * @default false
825
+ */
826
+ preventClose?: boolean;
827
+ };
828
+ /**
829
+ * A tool call made by the model. Matches the AI SDK's tool call shape.
830
+ */
831
+ interface ToolCall {
832
+ /** Discriminator for content part arrays */
833
+ type: 'tool-call';
834
+ /** The unique identifier of the tool call */
835
+ toolCallId: string;
836
+ /** The name of the tool that was called */
837
+ toolName: string;
838
+ /** The parsed input arguments for the tool call */
839
+ input: unknown;
840
+ }
841
+ /**
842
+ * A tool result from executing a tool. Matches the AI SDK's tool result shape.
843
+ */
844
+ interface ToolResult {
845
+ /** Discriminator for content part arrays */
846
+ type: 'tool-result';
847
+ /** The tool call ID this result corresponds to */
848
+ toolCallId: string;
849
+ /** The name of the tool that was executed */
850
+ toolName: string;
851
+ /** The parsed input arguments that were passed to the tool */
852
+ input: unknown;
853
+ /** The output produced by the tool */
854
+ output: unknown;
855
+ }
856
+ /**
857
+ * Result of the WorkflowAgent.stream method.
858
+ */
859
+ interface WorkflowAgentStreamResult<TTools extends ToolSet = ToolSet, OUTPUT = never> {
860
+ /**
861
+ * The final messages including all tool calls and results.
862
+ */
863
+ messages: ModelMessage[];
864
+ /**
865
+ * Details for all steps.
866
+ */
867
+ steps: StepResult<TTools, any>[];
868
+ /**
869
+ * The tool calls from the last step.
870
+ * Includes all tool calls regardless of whether they were executed.
871
+ *
872
+ * When the agent stops because a tool without an `execute` function was called,
873
+ * this array will contain those calls. Compare with `toolResults` to find
874
+ * unresolved tool calls that need client-side handling:
875
+ *
876
+ * ```ts
877
+ * const unresolved = result.toolCalls.filter(
878
+ * tc => !result.toolResults.some(tr => tr.toolCallId === tc.toolCallId)
879
+ * );
880
+ * ```
881
+ *
882
+ * This matches the AI SDK's `GenerateTextResult.toolCalls` behavior.
883
+ */
884
+ toolCalls: ToolCall[];
885
+ /**
886
+ * The tool results from the last step.
887
+ * Only includes results for tools that were actually executed (server-side or provider-executed).
888
+ * Tools without an `execute` function will NOT have entries here.
889
+ *
890
+ * This matches the AI SDK's `GenerateTextResult.toolResults` behavior.
891
+ */
892
+ toolResults: ToolResult[];
893
+ /**
894
+ * The finish reason from the last step.
895
+ */
896
+ finishReason: FinishReason;
897
+ /**
898
+ * The total token usage across all steps.
899
+ */
900
+ totalUsage: LanguageModelUsage;
901
+ /**
902
+ * The generated structured output. It uses the `output` specification.
903
+ * Only available when `output` is specified.
904
+ */
905
+ output: OUTPUT;
906
+ }
907
+ /**
908
+ * A class for building durable AI agents within workflows.
909
+ *
910
+ * WorkflowAgent enables you to create AI-powered agents that can maintain state
911
+ * across workflow steps, call tools, and gracefully handle interruptions and resumptions.
912
+ * It integrates seamlessly with the AI SDK and the Workflow DevKit for
913
+ * production-grade reliability.
914
+ *
915
+ * @example
916
+ * ```typescript
917
+ * const agent = new WorkflowAgent({
918
+ * model: 'anthropic/claude-opus',
919
+ * tools: {
920
+ * getWeather: {
921
+ * description: 'Get weather for a location',
922
+ * inputSchema: z.object({ location: z.string() }),
923
+ * execute: getWeatherStep,
924
+ * },
925
+ * },
926
+ * instructions: 'You are a helpful weather assistant.',
927
+ * });
928
+ *
929
+ * const result = await agent.stream({
930
+ * messages: [{ role: 'user', content: 'What is the weather?' }],
931
+ * });
932
+ * ```
933
+ */
934
+ declare class WorkflowAgent<TBaseTools extends ToolSet = ToolSet, TRuntimeContext extends Context = Context> {
935
+ /**
936
+ * The id of the agent.
937
+ */
938
+ readonly id: string | undefined;
939
+ private model;
940
+ /**
941
+ * The tool set configured for this agent.
942
+ */
943
+ readonly tools: TBaseTools;
944
+ private instructions?;
945
+ private generationSettings;
946
+ private toolChoice?;
947
+ private telemetry?;
948
+ private runtimeContext?;
949
+ private toolsContext?;
950
+ private stopWhen?;
951
+ private activeTools?;
952
+ private output?;
953
+ private repairToolCall?;
954
+ private experimentalDownload?;
955
+ private experimentalSandbox?;
956
+ private prepareStep?;
957
+ private allowSystemInMessages;
958
+ private constructorOnStepEnd?;
959
+ private constructorOnEnd?;
960
+ private constructorOnStart?;
961
+ private constructorOnStepStart?;
962
+ private constructorOnToolExecutionStart?;
963
+ private constructorOnToolExecutionEnd?;
964
+ private prepareCall?;
965
+ constructor(options: WorkflowAgentOptions<TBaseTools, TRuntimeContext>);
966
+ generate(): void;
967
+ stream<TTools extends TBaseTools = TBaseTools, OUTPUT = never, PARTIAL_OUTPUT = never>(options: WorkflowAgentStreamOptions<TTools, TRuntimeContext, OUTPUT, PARTIAL_OUTPUT>): Promise<WorkflowAgentStreamResult<TTools, OUTPUT>>;
968
+ }
969
+
970
+ /**
971
+ * Convert a single ModelCallStreamPart to a UIMessageChunk.
972
+ * Returns undefined for parts that don't map to UI chunks.
973
+ */
974
+ declare function toUIMessageChunk(part: Experimental_LanguageModelStreamPart<ToolSet>): UIMessageChunk | undefined;
975
+ /**
976
+ * Create a TransformStream that converts ModelCallStreamPart to UIMessageChunk.
977
+ * Wraps toUIMessageChunk with start/start-step/finish-step lifecycle chunks.
978
+ */
979
+ declare function createModelCallToUIChunkTransform(): TransformStream<Experimental_LanguageModelStreamPart<ToolSet>, UIMessageChunk>;
980
+
981
+ interface SendMessagesOptions<UI_MESSAGE extends UIMessage> {
982
+ trigger: 'submit-message' | 'regenerate-message';
983
+ chatId: string;
984
+ messageId?: string;
985
+ messages: UI_MESSAGE[];
986
+ abortSignal?: AbortSignal;
987
+ }
988
+ interface ReconnectToStreamOptions {
989
+ chatId: string;
990
+ abortSignal?: AbortSignal;
991
+ /**
992
+ * Override the `startIndex` for this reconnection.
993
+ * Negative values read from the end of the stream.
994
+ * When omitted, falls back to the constructor's `initialStartIndex`.
995
+ */
996
+ startIndex?: number;
997
+ }
998
+ type OnChatSendMessage<UI_MESSAGE extends UIMessage> = (response: Response, options: SendMessagesOptions<UI_MESSAGE>) => void | Promise<void>;
999
+ type OnChatEnd = ({ chatId, chunkIndex, }: {
1000
+ chatId: string;
1001
+ chunkIndex: number;
1002
+ }) => void | Promise<void>;
1003
+ /**
1004
+ * Configuration options for the WorkflowChatTransport.
1005
+ *
1006
+ * @template UI_MESSAGE - The type of UI messages being sent and received,
1007
+ * must extend the UIMessage interface from the AI SDK.
1008
+ */
1009
+ interface WorkflowChatTransportOptions<UI_MESSAGE extends UIMessage> {
1010
+ /**
1011
+ * API endpoint for chat requests
1012
+ * Defaults to /api/chat if not provided
1013
+ */
1014
+ api?: string;
1015
+ /**
1016
+ * Custom fetch implementation to use for HTTP requests.
1017
+ * Defaults to the global fetch function if not provided.
1018
+ */
1019
+ fetch?: typeof fetch;
1020
+ /**
1021
+ * Callback invoked after successfully sending messages to the chat endpoint.
1022
+ * Useful for tracking chat history and inspecting response headers.
1023
+ *
1024
+ * @param response - The HTTP response object from the chat endpoint
1025
+ * @param options - The original options passed to sendMessages
1026
+ */
1027
+ onChatSendMessage?: OnChatSendMessage<UI_MESSAGE>;
1028
+ /**
1029
+ * Callback invoked when a chat stream ends (receives a "finish" chunk).
1030
+ * Useful for cleanup operations or state updates.
1031
+ *
1032
+ * @param chatId - The ID of the chat that ended
1033
+ * @param chunkIndex - The total number of chunks received
1034
+ */
1035
+ onChatEnd?: OnChatEnd;
1036
+ /**
1037
+ * Maximum number of consecutive errors allowed during reconnection attempts.
1038
+ * Defaults to 3 if not provided.
1039
+ */
1040
+ maxConsecutiveErrors?: number;
1041
+ /**
1042
+ * Default `startIndex` to use when reconnecting to a stream without a known
1043
+ * chunk position (i.e. the initial reconnection, not a retry).
1044
+ * Negative values read from the end of the stream (e.g. `-10` fetches the
1045
+ * last 10 chunks), which is useful for resuming a chat UI after a page
1046
+ * refresh without replaying the full conversation.
1047
+ *
1048
+ * Can be overridden per-call via `ReconnectToStreamOptions.startIndex`.
1049
+ *
1050
+ * Defaults to `0` (replay from the beginning).
1051
+ */
1052
+ initialStartIndex?: number;
1053
+ /**
1054
+ * Function to prepare the request for sending messages.
1055
+ * Allows customizing the API endpoint, headers, credentials, and body.
1056
+ */
1057
+ prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
1058
+ /**
1059
+ * Function to prepare the request for reconnecting to a stream.
1060
+ * Allows customizing the API endpoint, headers, and credentials.
1061
+ */
1062
+ prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
1063
+ }
1064
+ /**
1065
+ * A transport implementation for managing chat workflows with support for
1066
+ * streaming responses and automatic reconnection to interrupted streams.
1067
+ *
1068
+ * This class implements the ChatTransport interface from the AI SDK and provides
1069
+ * reliable message streaming with automatic recovery from network interruptions
1070
+ * or function timeouts.
1071
+ *
1072
+ * @template UI_MESSAGE - The type of UI messages being sent and received,
1073
+ * must extend the UIMessage interface from the AI SDK.
1074
+ *
1075
+ * @implements {ChatTransport<UI_MESSAGE>}
1076
+ */
1077
+ declare class WorkflowChatTransport<UI_MESSAGE extends UIMessage> implements ChatTransport<UI_MESSAGE> {
1078
+ private readonly api;
1079
+ private readonly fetch;
1080
+ private readonly onChatSendMessage?;
1081
+ private readonly onChatEnd?;
1082
+ private readonly maxConsecutiveErrors;
1083
+ private readonly initialStartIndex;
1084
+ private readonly prepareSendMessagesRequest?;
1085
+ private readonly prepareReconnectToStreamRequest?;
1086
+ /**
1087
+ * Creates a new WorkflowChatTransport instance.
1088
+ *
1089
+ * @param options - Configuration options for the transport
1090
+ * @param options.api - API endpoint for chat requests (defaults to '/api/chat')
1091
+ * @param options.fetch - Custom fetch implementation (defaults to global fetch)
1092
+ * @param options.onChatSendMessage - Callback after sending messages
1093
+ * @param options.onChatEnd - Callback when chat stream ends
1094
+ * @param options.maxConsecutiveErrors - Maximum consecutive errors for reconnection
1095
+ * @param options.prepareSendMessagesRequest - Function to prepare send messages request
1096
+ * @param options.prepareReconnectToStreamRequest - Function to prepare reconnect request
1097
+ */
1098
+ constructor(options?: WorkflowChatTransportOptions<UI_MESSAGE>);
1099
+ /**
1100
+ * Sends messages to the chat endpoint and returns a stream of response chunks.
1101
+ *
1102
+ * This method handles the entire chat lifecycle including:
1103
+ * - Sending messages to the /api/chat endpoint
1104
+ * - Streaming response chunks
1105
+ * - Automatic reconnection if the stream is interrupted
1106
+ *
1107
+ * @param options - Options for sending messages
1108
+ * @param options.trigger - The type of message submission ('submit-message' or 'regenerate-message')
1109
+ * @param options.chatId - Unique identifier for this chat session
1110
+ * @param options.messageId - Optional message ID for tracking specific messages
1111
+ * @param options.messages - Array of UI messages to send
1112
+ * @param options.abortSignal - Optional AbortSignal to cancel the request
1113
+ *
1114
+ * @returns A ReadableStream of UIMessageChunk objects containing the response
1115
+ * @throws Error if the fetch request fails or returns a non-OK status
1116
+ */
1117
+ sendMessages(options: SendMessagesOptions<UI_MESSAGE> & ChatRequestOptions): Promise<ReadableStream<UIMessageChunk>>;
1118
+ private sendMessagesIterator;
1119
+ /**
1120
+ * Reconnects to an existing chat stream that was previously interrupted.
1121
+ *
1122
+ * This method is useful for resuming a chat session after network issues,
1123
+ * page refreshes, or Vercel Function timeouts.
1124
+ *
1125
+ * @param options - Options for reconnecting to the stream
1126
+ * @param options.chatId - The chat ID to reconnect to
1127
+ *
1128
+ * @returns A ReadableStream of UIMessageChunk objects
1129
+ * @throws Error if the reconnection request fails or returns a non-OK status
1130
+ */
1131
+ reconnectToStream(options: ReconnectToStreamOptions & ChatRequestOptions): Promise<ReadableStream<UIMessageChunk> | null>;
1132
+ private reconnectToStreamIterator;
1133
+ private onFinish;
1134
+ }
1135
+
1136
+ /**
1137
+ * Normalizes the part framing of a UI message stream so it is always
1138
+ * well-formed for the AI SDK's stream consumer (`processUIMessageStream`,
1139
+ * which backs `useChat`/`readUIMessageStream`).
1140
+ *
1141
+ * ## Why this exists
1142
+ *
1143
+ * The consumer maintains a map of "active" text/reasoning parts keyed by id.
1144
+ * A `text-delta`/`text-end` for an id that has no open part is a fatal error
1145
+ * (`Received text-delta for missing text part with ID "0" ...`) that kills the
1146
+ * whole turn. Two properties of the durable streaming model make that error
1147
+ * reachable:
1148
+ *
1149
+ * - A workflow run owns a single shared stream, and the consumer resets its
1150
+ * active-part maps on every `finish-step`. Multi-step turns reuse the same
1151
+ * part id (commonly `"0"`) in each step, so a single dropped or duplicated
1152
+ * `*-start` across a step boundary orphans the rest of that step's content.
1153
+ * - The same stream is read across reconnects, and a stream-producing step can
1154
+ * run more than once (retry/redelivery, or the concurrent-worker duplication
1155
+ * tracked in vercel/workflow#2331 and #2039). Either can interleave or
1156
+ * duplicate chunks on the shared stream — e.g. a `finish-step` landing in the
1157
+ * middle of another execution's text part.
1158
+ *
1159
+ * Since the content is still flowing and only the framing is damaged, repairing
1160
+ * the framing here degrades the worst case to "text begins slightly into the
1161
+ * step" or "a duplicated tail is dropped" instead of a dead turn.
1162
+ *
1163
+ * ## What it does
1164
+ *
1165
+ * Mirrors the consumer's part-lifetime state machine, per part type, per step:
1166
+ * - resets tracking on `finish-step` (exactly where the consumer resets);
1167
+ * - synthesizes a missing `*-start` when an orphaned `*-delta`/`*-end` arrives;
1168
+ * - drops a re-delivered `*-start`/`*-delta`/`*-end` for a part already
1169
+ * open or ended in the current step (reconnect/replay overlap).
1170
+ *
1171
+ * A well-formed stream passes through unchanged.
1172
+ *
1173
+ * ## Scope: text and reasoning only
1174
+ *
1175
+ * `tool-input-delta` raises the same class of fatal error (`Received
1176
+ * tool-input-delta for missing tool call ...`), but tool parts are deliberately
1177
+ * left untouched: the consumer does not reset its tool-call map on `finish-step`
1178
+ * and tool-call ids are unique, so the step-boundary id-reuse orphaning that
1179
+ * makes text/reasoning fragile does not apply to them. If a future duplication
1180
+ * mode is found to orphan tool-input parts, extend the same machine to that
1181
+ * family rather than special-casing it.
1182
+ *
1183
+ * @param source the raw UI message chunk stream to normalize.
1184
+ * @yields the framing-corrected UI message chunks.
1185
+ */
1186
+ declare function normalizeUIMessageStreamParts(source: AsyncIterable<UIMessageChunk>): AsyncGenerator<UIMessageChunk>;
1187
+
1188
+ export { type CompatibleLanguageModel, type DownloadFunction, type GenerationSettings, type InferWorkflowAgentTools, type InferWorkflowAgentUIMessage, type OutputSpecification, type PrepareCallCallback, type PrepareCallOptions, type PrepareCallResult, type PrepareStepCallback, type PrepareStepInfo, type PrepareStepResult, type ProviderOptions, type ReconnectToStreamOptions, type SendMessagesOptions, type StreamTextTransform, type TelemetryOptions, WorkflowAgent, type WorkflowAgentOnAbortCallback, type WorkflowAgentOnEndCallback, type WorkflowAgentOnErrorCallback, type WorkflowAgentOnFinishCallback, type WorkflowAgentOnStartCallback, type WorkflowAgentOnStepEndCallback, type WorkflowAgentOnStepFinishCallback, type WorkflowAgentOnStepStartCallback, type WorkflowAgentOnToolExecutionEndCallback, type WorkflowAgentOnToolExecutionStartCallback, type WorkflowAgentOptions, type WorkflowAgentStreamOptions, type WorkflowAgentStreamResult, WorkflowChatTransport, type WorkflowChatTransportOptions, createModelCallToUIChunkTransform, normalizeUIMessageStreamParts, toUIMessageChunk };