@ai-sdk/workflow 0.0.0-bf6e4b15-20260402200305

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 @@
1
+ {"version":3,"sources":["../src/workflow-agent.ts","../src/do-stream-step.ts","../src/serializable-schema.ts","../src/stream-text-iterator.ts","../src/to-ui-message-chunk.ts"],"sourcesContent":["import type {\n JSONValue,\n LanguageModelV4CallOptions,\n LanguageModelV4Prompt,\n LanguageModelV4StreamPart,\n LanguageModelV4ToolResultPart,\n SharedV4ProviderOptions,\n} from '@ai-sdk/provider';\nimport {\n asSchema,\n type Experimental_ModelCallStreamPart as ModelCallStreamPart,\n type FinishReason,\n type LanguageModelResponseMetadata,\n type LanguageModelUsage,\n type ModelMessage,\n Output,\n type StepResult,\n type StopCondition,\n type StreamTextOnStepFinishCallback,\n type SystemModelMessage,\n type ToolCallRepairFunction,\n type ToolChoice,\n type ToolSet,\n type UIMessage,\n} from 'ai';\nimport {\n convertToLanguageModelPrompt,\n mergeAbortSignals,\n standardizePrompt,\n} from 'ai/internal';\nimport { mergeCallbacks } from 'ai/internal';\nimport { recordSpan } from './telemetry.js';\nimport { streamTextIterator } from './stream-text-iterator.js';\nimport type { CompatibleLanguageModel } from './types.js';\n\n// Re-export for consumers\nexport type { CompatibleLanguageModel } from './types.js';\n\n/**\n * Infer the type of the tools of a workflow agent.\n */\nexport type InferWorkflowAgentTools<WORKFLOW_AGENT> =\n WORKFLOW_AGENT extends WorkflowAgent<infer TOOLS> ? TOOLS : never;\n\n/**\n * Infer the UI message type of a workflow agent.\n */\nexport type InferWorkflowAgentUIMessage<\n WORKFLOW_AGENT,\n MESSAGE_METADATA = unknown,\n> = UIMessage<MESSAGE_METADATA>;\n\n/**\n * Re-export the Output helper for structured output specifications.\n * Use `Output.object({ schema })` for structured output or `Output.text()` for text output.\n */\nexport { Output };\n\n/**\n * Output specification interface for structured outputs.\n * Use `Output.object({ schema })` or `Output.text()` to create an output specification.\n */\nexport interface OutputSpecification<OUTPUT, PARTIAL> {\n readonly name: string;\n responseFormat: PromiseLike<LanguageModelV4CallOptions['responseFormat']>;\n parsePartialOutput(options: {\n text: string;\n }): Promise<{ partial: PARTIAL } | undefined>;\n parseCompleteOutput(\n options: { text: string },\n context: {\n response: LanguageModelResponseMetadata;\n usage: LanguageModelUsage;\n finishReason: FinishReason;\n },\n ): Promise<OUTPUT>;\n}\n\n/**\n * Provider-specific options type. This is equivalent to SharedV4ProviderOptions from @ai-sdk/provider.\n */\nexport type ProviderOptions = SharedV4ProviderOptions;\n\n/**\n * Telemetry settings for observability.\n */\nexport interface TelemetrySettings {\n /**\n * Enable or disable telemetry. Defaults to true.\n */\n isEnabled?: boolean;\n\n /**\n * Identifier for this function. Used to group telemetry data by function.\n */\n functionId?: string;\n\n /**\n * Additional information to include in the telemetry data.\n */\n metadata?: Record<\n string,\n | string\n | number\n | boolean\n | Array<string | number | boolean>\n | null\n | undefined\n >;\n\n /**\n * Enable or disable input recording. Enabled by default.\n *\n * You might want to disable input recording to avoid recording sensitive\n * information, to reduce data transfers, or to increase performance.\n */\n recordInputs?: boolean;\n\n /**\n * Enable or disable output recording. Enabled by default.\n *\n * You might want to disable output recording to avoid recording sensitive\n * information, to reduce data transfers, or to increase performance.\n */\n recordOutputs?: boolean;\n\n /**\n * Custom tracer for the telemetry.\n */\n tracer?: unknown;\n}\n\n/**\n * A transformation that is applied to the stream.\n */\nexport type StreamTextTransform<TTools extends ToolSet> = (options: {\n tools: TTools;\n stopStream: () => void;\n}) => TransformStream<LanguageModelV4StreamPart, LanguageModelV4StreamPart>;\n\n/**\n * Function to repair a tool call that failed to parse.\n * Re-exported from the AI SDK core.\n */\nexport type { ToolCallRepairFunction } from 'ai';\n\n/**\n * Custom download function for URLs.\n * The function receives an array of URLs with information about whether\n * the model supports them directly.\n */\nexport type DownloadFunction = (\n options: {\n url: URL;\n isUrlSupportedByModel: boolean;\n }[],\n) => PromiseLike<\n ({ data: Uint8Array; mediaType: string | undefined } | null)[]\n>;\n\n/**\n * Generation settings that can be passed to the model.\n * These map directly to LanguageModelV4CallOptions.\n */\nexport interface GenerationSettings {\n /**\n * Maximum number of tokens to generate.\n */\n maxOutputTokens?: number;\n\n /**\n * Temperature setting. The range depends on the provider and model.\n * It is recommended to set either `temperature` or `topP`, but not both.\n */\n temperature?: number;\n\n /**\n * Nucleus sampling. This is a number between 0 and 1.\n * E.g. 0.1 would mean that only tokens with the top 10% probability mass are considered.\n * It is recommended to set either `temperature` or `topP`, but not both.\n */\n topP?: number;\n\n /**\n * Only sample from the top K options for each subsequent token.\n * Used to remove \"long tail\" low probability responses.\n * Recommended for advanced use cases only. You usually only need to use temperature.\n */\n topK?: number;\n\n /**\n * Presence penalty setting. It affects the likelihood of the model to\n * repeat information that is already in the prompt.\n * The presence penalty is a number between -1 (increase repetition)\n * and 1 (maximum penalty, decrease repetition). 0 means no penalty.\n */\n presencePenalty?: number;\n\n /**\n * Frequency penalty setting. It affects the likelihood of the model\n * to repeatedly use the same words or phrases.\n * The frequency penalty is a number between -1 (increase repetition)\n * and 1 (maximum penalty, decrease repetition). 0 means no penalty.\n */\n frequencyPenalty?: number;\n\n /**\n * Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.\n * Providers may have limits on the number of stop sequences.\n */\n stopSequences?: string[];\n\n /**\n * The seed (integer) to use for random sampling. If set and supported\n * by the model, calls will generate deterministic results.\n */\n seed?: number;\n\n /**\n * Maximum number of retries. Set to 0 to disable retries.\n * Note: In workflow context, retries are typically handled by the workflow step mechanism.\n * @default 2\n */\n maxRetries?: number;\n\n /**\n * Abort signal for cancelling the operation.\n */\n abortSignal?: AbortSignal;\n\n /**\n * Additional HTTP headers to be sent with the request.\n * Only applicable for HTTP-based providers.\n */\n headers?: Record<string, string | undefined>;\n\n /**\n * Additional provider-specific options. They are passed through\n * to the provider from the AI SDK and enable provider-specific\n * functionality that can be fully encapsulated in the provider.\n */\n providerOptions?: ProviderOptions;\n}\n\n/**\n * Information passed to the prepareStep callback.\n */\nexport interface PrepareStepInfo<TTools extends ToolSet = ToolSet> {\n /**\n * The current model configuration (string or function).\n * The function should return a LanguageModelV4 instance.\n */\n model: string | (() => Promise<CompatibleLanguageModel>);\n\n /**\n * The current step number (0-indexed).\n */\n stepNumber: number;\n\n /**\n * All previous steps with their results.\n */\n steps: StepResult<TTools, any>[];\n\n /**\n * The messages that will be sent to the model.\n * This is the LanguageModelV4Prompt format used internally.\n */\n messages: LanguageModelV4Prompt;\n\n /**\n * The context passed via the experimental_context setting (experimental).\n */\n experimental_context: unknown;\n}\n\n/**\n * Return type from the prepareStep callback.\n * All properties are optional - only return the ones you want to override.\n */\nexport interface PrepareStepResult extends Partial<GenerationSettings> {\n /**\n * Override the model for this step.\n * The function should return a LanguageModelV4 instance.\n */\n model?: string | (() => Promise<CompatibleLanguageModel>);\n\n /**\n * Override the system message for this step.\n */\n system?: string;\n\n /**\n * Override the messages for this step.\n * Use this for context management or message injection.\n */\n messages?: LanguageModelV4Prompt;\n\n /**\n * Override the tool choice for this step.\n */\n toolChoice?: ToolChoice<ToolSet>;\n\n /**\n * Override the active tools for this step.\n * Limits the tools that are available for the model to call.\n */\n activeTools?: string[];\n\n /**\n * Context that is passed into tool execution. Experimental.\n * Changing the context will affect the context in this step and all subsequent steps.\n */\n experimental_context?: unknown;\n}\n\n/**\n * Callback function called before each step in the agent loop.\n * Use this to modify settings, manage context, or implement dynamic behavior.\n */\nexport type PrepareStepCallback<TTools extends ToolSet = ToolSet> = (\n info: PrepareStepInfo<TTools>,\n) => PrepareStepResult | Promise<PrepareStepResult>;\n\n/**\n * Options passed to the prepareCall callback.\n */\nexport interface PrepareCallOptions<\n TTools extends ToolSet = ToolSet,\n> extends Partial<GenerationSettings> {\n model: string | (() => Promise<CompatibleLanguageModel>);\n tools: TTools;\n instructions?: string | SystemModelMessage | Array<SystemModelMessage>;\n toolChoice?: ToolChoice<TTools>;\n experimental_telemetry?: TelemetrySettings;\n experimental_context?: unknown;\n messages: ModelMessage[];\n}\n\n/**\n * Result of the prepareCall callback. All fields are optional —\n * only returned fields override the defaults.\n * Note: `tools` cannot be overridden via prepareCall because they are\n * bound at construction time for type safety.\n */\nexport type PrepareCallResult<TTools extends ToolSet = ToolSet> = Partial<\n Omit<PrepareCallOptions<TTools>, 'tools'>\n>;\n\n/**\n * Callback called once before the agent loop starts to transform call parameters.\n */\nexport type PrepareCallCallback<TTools extends ToolSet = ToolSet> = (\n options: PrepareCallOptions<TTools>,\n) => PrepareCallResult<TTools> | Promise<PrepareCallResult<TTools>>;\n\n/**\n * Configuration options for creating a {@link WorkflowAgent} instance.\n */\nexport interface WorkflowAgentOptions<\n TTools extends ToolSet = ToolSet,\n> extends GenerationSettings {\n /**\n * The model provider to use for the agent.\n *\n * This should be a string compatible with the Vercel AI Gateway (e.g., 'anthropic/claude-opus'),\n * or a step function that returns a LanguageModelV4 instance.\n */\n model: string | (() => Promise<CompatibleLanguageModel>);\n\n /**\n * A set of tools available to the agent.\n * Tools can be implemented as workflow steps for automatic retries and persistence,\n * or as regular workflow-level logic using core library features like sleep() and Hooks.\n */\n tools?: TTools;\n\n /**\n * Agent instructions. Can be a string, a SystemModelMessage, or an array of SystemModelMessages.\n * Supports provider-specific options (e.g., caching) when using the SystemModelMessage form.\n */\n instructions?: string | SystemModelMessage | Array<SystemModelMessage>;\n\n /**\n * Optional system prompt to guide the agent's behavior.\n * @deprecated Use `instructions` instead.\n */\n system?: string;\n\n /**\n * The tool choice strategy. Default: 'auto'.\n */\n toolChoice?: ToolChoice<TTools>;\n\n /**\n * Optional telemetry configuration (experimental).\n */\n experimental_telemetry?: TelemetrySettings;\n\n /**\n * Default context that is passed into tool execution for every stream call on this agent.\n *\n * Per-stream `experimental_context` values passed to `stream()` override this default.\n * Experimental (can break in patch releases).\n * @default undefined\n */\n experimental_context?: unknown;\n\n /**\n * Default callback function called before each step in the agent loop.\n * Use this to modify settings, manage context, or inject messages dynamically\n * for every stream call on this agent instance.\n *\n * Per-stream `prepareStep` values passed to `stream()` override this default.\n */\n prepareStep?: PrepareStepCallback<TTools>;\n\n /**\n * Callback function to be called after each step completes.\n */\n onStepFinish?: StreamTextOnStepFinishCallback<ToolSet, any>;\n\n /**\n * Callback that is called when the LLM response and all request tool executions are finished.\n */\n onFinish?: StreamTextOnFinishCallback<ToolSet>;\n\n /**\n * Callback called when the agent starts streaming, before any LLM calls.\n */\n experimental_onStart?: WorkflowAgentOnStartCallback;\n\n /**\n * Callback called before each step (LLM call) begins.\n */\n experimental_onStepStart?: WorkflowAgentOnStepStartCallback;\n\n /**\n * Callback called before a tool's execute function runs.\n */\n experimental_onToolCallStart?: WorkflowAgentOnToolCallStartCallback;\n\n /**\n * Callback called after a tool execution completes.\n */\n experimental_onToolCallFinish?: WorkflowAgentOnToolCallFinishCallback;\n\n /**\n * Prepare the parameters for the stream call.\n * Called once before the agent loop starts. Use this to transform\n * model, tools, instructions, or other settings based on runtime context.\n */\n prepareCall?: PrepareCallCallback<TTools>;\n}\n\n/**\n * Callback that is called when the LLM response and all request tool executions are finished.\n */\nexport type StreamTextOnFinishCallback<\n TTools extends ToolSet = ToolSet,\n OUTPUT = never,\n> = (event: {\n /**\n * Details for all steps.\n */\n readonly steps: StepResult<TTools, any>[];\n\n /**\n * The final messages including all tool calls and results.\n */\n readonly messages: ModelMessage[];\n\n /**\n * The text output from the last step.\n */\n readonly text: string;\n\n /**\n * The finish reason from the last step.\n */\n readonly finishReason: FinishReason;\n\n /**\n * The total token usage across all steps.\n */\n readonly totalUsage: LanguageModelUsage;\n\n /**\n * Context that is passed into tool execution.\n */\n readonly experimental_context: unknown;\n\n /**\n * The generated structured output. It uses the `experimental_output` specification.\n * Only available when `experimental_output` is specified.\n */\n readonly experimental_output: OUTPUT;\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is invoked when an error occurs during streaming.\n */\nexport type StreamTextOnErrorCallback = (event: {\n error: unknown;\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is set using the `onAbort` option.\n */\nexport type StreamTextOnAbortCallback<TTools extends ToolSet = ToolSet> =\n (event: {\n /**\n * Details for all previously finished steps.\n */\n readonly steps: StepResult<TTools, any>[];\n }) => PromiseLike<void> | void;\n\n/**\n * Callback that is called when the agent starts streaming, before any LLM calls.\n */\nexport type WorkflowAgentOnStartCallback = (event: {\n /** The model being used */\n readonly model: string | (() => Promise<CompatibleLanguageModel>);\n /** The messages being sent */\n readonly messages: ModelMessage[];\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is called before each step (LLM call) begins.\n */\nexport type WorkflowAgentOnStepStartCallback = (event: {\n /** The current step number (0-based) */\n readonly stepNumber: number;\n /** The model being used for this step */\n readonly model: string | (() => Promise<CompatibleLanguageModel>);\n /** The messages being sent for this step */\n readonly messages: ModelMessage[];\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is called before a tool's execute function runs.\n */\nexport type WorkflowAgentOnToolCallStartCallback = (event: {\n /** The tool call being executed */\n readonly toolCall: ToolCall;\n}) => PromiseLike<void> | void;\n\n/**\n * Callback that is called after a tool execution completes.\n */\nexport type WorkflowAgentOnToolCallFinishCallback = (event: {\n /** The tool call that was executed */\n readonly toolCall: ToolCall;\n /** The tool result (undefined if execution failed) */\n readonly result?: unknown;\n /** The error if execution failed */\n readonly error?: unknown;\n}) => PromiseLike<void> | void;\n\n/**\n * Options for the {@link WorkflowAgent.stream} method.\n */\nexport interface WorkflowAgentStreamOptions<\n TTools extends ToolSet = ToolSet,\n OUTPUT = never,\n PARTIAL_OUTPUT = never,\n> extends Partial<GenerationSettings> {\n /**\n * The conversation messages to process. Should follow the AI SDK's ModelMessage format.\n */\n messages: ModelMessage[];\n\n /**\n * Optional system prompt override. If provided, overrides the system prompt from the constructor.\n */\n system?: string;\n\n /**\n * A WritableStream that receives raw LanguageModelV4StreamPart chunks in real-time\n * as the model generates them. This enables streaming to the client without\n * coupling WorkflowAgent to UIMessageChunk format.\n *\n * Convert to UIMessageChunks at the response boundary using\n * `createUIMessageChunkTransform()` from `@ai-sdk/workflow`.\n *\n * @example\n * ```typescript\n * // In the workflow:\n * await agent.stream({\n * messages,\n * writable: getWritable<ModelCallStreamPart>(),\n * });\n *\n * // In the route handler:\n * return createUIMessageStreamResponse({\n * stream: run.readable.pipeThrough(createModelCallToUIChunkTransform()),\n * });\n * ```\n */\n writable?: WritableStream<ModelCallStreamPart<ToolSet>>;\n\n /**\n * Condition for stopping the generation when there are tool results in the last step.\n * When the condition is an array, any of the conditions can be met to stop the generation.\n */\n stopWhen?:\n | StopCondition<NoInfer<ToolSet>, any>\n | Array<StopCondition<NoInfer<ToolSet>, any>>;\n\n /**\n * Maximum number of sequential LLM calls (steps), e.g. when you use tool calls.\n * A maximum number can be set to prevent infinite loops in the case of misconfigured tools.\n * By default, it's unlimited (the agent loops until completion).\n */\n maxSteps?: number;\n\n /**\n * The tool choice strategy. Default: 'auto'.\n * Overrides the toolChoice from the constructor if provided.\n */\n toolChoice?: ToolChoice<TTools>;\n\n /**\n * Limits the tools that are available for the model to call without\n * changing the tool call and result types in the result.\n */\n activeTools?: Array<keyof NoInfer<TTools>>;\n\n /**\n * Optional telemetry configuration (experimental).\n */\n experimental_telemetry?: TelemetrySettings;\n\n /**\n * Context that is passed into tool execution.\n * Experimental (can break in patch releases).\n * @default undefined\n */\n experimental_context?: unknown;\n\n /**\n * Optional specification for parsing structured outputs from the LLM response.\n * Use `Output.object({ schema })` for structured output or `Output.text()` for text output.\n *\n * @example\n * ```typescript\n * import { Output } from '@workflow/ai';\n * import { z } from 'zod';\n *\n * const result = await agent.stream({\n * messages: [...],\n * writable: getWritable(),\n * experimental_output: Output.object({\n * schema: z.object({\n * sentiment: z.enum(['positive', 'negative', 'neutral']),\n * confidence: z.number(),\n * }),\n * }),\n * });\n *\n * console.log(result.experimental_output); // { sentiment: 'positive', confidence: 0.95 }\n * ```\n */\n experimental_output?: OutputSpecification<OUTPUT, PARTIAL_OUTPUT>;\n\n /**\n * Whether to include raw chunks from the provider in the stream.\n * When enabled, you will receive raw chunks with type 'raw' that contain the unprocessed data from the provider.\n * This allows access to cutting-edge provider features not yet wrapped by the AI SDK.\n * Defaults to false.\n */\n includeRawChunks?: boolean;\n\n /**\n * A function that attempts to repair a tool call that failed to parse.\n */\n experimental_repairToolCall?: ToolCallRepairFunction<TTools>;\n\n /**\n * Optional stream transformations.\n * They are applied in the order they are provided.\n * The stream transformations must maintain the stream structure for streamText to work correctly.\n */\n experimental_transform?:\n | StreamTextTransform<TTools>\n | Array<StreamTextTransform<TTools>>;\n\n /**\n * Custom download function to use for URLs.\n * By default, files are downloaded if the model does not support the URL for the given media type.\n */\n experimental_download?: DownloadFunction;\n\n /**\n * Callback function to be called after each step completes.\n */\n onStepFinish?: StreamTextOnStepFinishCallback<TTools, any>;\n\n /**\n * Callback that is invoked when an error occurs during streaming.\n * You can use it to log errors.\n */\n onError?: StreamTextOnErrorCallback;\n\n /**\n * Callback that is called when the LLM response and all request tool executions\n * (for tools that have an `execute` function) are finished.\n */\n onFinish?: StreamTextOnFinishCallback<TTools, OUTPUT>;\n\n /**\n * Callback that is called when the operation is aborted.\n */\n onAbort?: StreamTextOnAbortCallback<TTools>;\n\n /**\n * Callback called when the agent starts streaming, before any LLM calls.\n */\n experimental_onStart?: WorkflowAgentOnStartCallback;\n\n /**\n * Callback called before each step (LLM call) begins.\n */\n experimental_onStepStart?: WorkflowAgentOnStepStartCallback;\n\n /**\n * Callback called before a tool's execute function runs.\n */\n experimental_onToolCallStart?: WorkflowAgentOnToolCallStartCallback;\n\n /**\n * Callback called after a tool execution completes.\n */\n experimental_onToolCallFinish?: WorkflowAgentOnToolCallFinishCallback;\n\n /**\n * Callback function called before each step in the agent loop.\n * Use this to modify settings, manage context, or inject messages dynamically.\n *\n * @example\n * ```typescript\n * prepareStep: async ({ messages, stepNumber }) => {\n * // Inject messages from a queue\n * const queuedMessages = await getQueuedMessages();\n * if (queuedMessages.length > 0) {\n * return {\n * messages: [...messages, ...queuedMessages],\n * };\n * }\n * return {};\n * }\n * ```\n */\n prepareStep?: PrepareStepCallback<TTools>;\n\n /**\n * Timeout in milliseconds for the stream operation.\n * When specified, creates an AbortSignal that will abort the operation after the given time.\n * If both `timeout` and `abortSignal` are provided, whichever triggers first will abort.\n */\n timeout?: number;\n}\n\n/**\n * A tool call made by the model. Matches the AI SDK's tool call shape.\n */\nexport interface ToolCall {\n /** Discriminator for content part arrays */\n type: 'tool-call';\n /** The unique identifier of the tool call */\n toolCallId: string;\n /** The name of the tool that was called */\n toolName: string;\n /** The parsed input arguments for the tool call */\n input: unknown;\n}\n\n/**\n * A tool result from executing a tool. Matches the AI SDK's tool result shape.\n */\nexport interface ToolResult {\n /** Discriminator for content part arrays */\n type: 'tool-result';\n /** The tool call ID this result corresponds to */\n toolCallId: string;\n /** The name of the tool that was executed */\n toolName: string;\n /** The parsed input arguments that were passed to the tool */\n input: unknown;\n /** The output produced by the tool */\n output: unknown;\n}\n\n/**\n * Result of the WorkflowAgent.stream method.\n */\nexport interface WorkflowAgentStreamResult<\n TTools extends ToolSet = ToolSet,\n OUTPUT = never,\n> {\n /**\n * The final messages including all tool calls and results.\n */\n messages: ModelMessage[];\n\n /**\n * Details for all steps.\n */\n steps: StepResult<TTools, any>[];\n\n /**\n * The tool calls from the last step.\n * Includes all tool calls regardless of whether they were executed.\n *\n * When the agent stops because a tool without an `execute` function was called,\n * this array will contain those calls. Compare with `toolResults` to find\n * unresolved tool calls that need client-side handling:\n *\n * ```ts\n * const unresolved = result.toolCalls.filter(\n * tc => !result.toolResults.some(tr => tr.toolCallId === tc.toolCallId)\n * );\n * ```\n *\n * This matches the AI SDK's `GenerateTextResult.toolCalls` behavior.\n */\n toolCalls: ToolCall[];\n\n /**\n * The tool results from the last step.\n * Only includes results for tools that were actually executed (server-side or provider-executed).\n * Tools without an `execute` function will NOT have entries here.\n *\n * This matches the AI SDK's `GenerateTextResult.toolResults` behavior.\n */\n toolResults: ToolResult[];\n\n /**\n * The generated structured output. It uses the `experimental_output` specification.\n * Only available when `experimental_output` is specified.\n */\n experimental_output: OUTPUT;\n}\n\n/**\n * A class for building durable AI agents within workflows.\n *\n * WorkflowAgent enables you to create AI-powered agents that can maintain state\n * across workflow steps, call tools, and gracefully handle interruptions and resumptions.\n * It integrates seamlessly with the AI SDK and the Workflow DevKit for\n * production-grade reliability.\n *\n * @example\n * ```typescript\n * const agent = new WorkflowAgent({\n * model: 'anthropic/claude-opus',\n * tools: {\n * getWeather: {\n * description: 'Get weather for a location',\n * inputSchema: z.object({ location: z.string() }),\n * execute: getWeatherStep,\n * },\n * },\n * instructions: 'You are a helpful weather assistant.',\n * });\n *\n * const result = await agent.stream({\n * messages: [{ role: 'user', content: 'What is the weather?' }],\n * });\n * ```\n */\nexport class WorkflowAgent<TBaseTools extends ToolSet = ToolSet> {\n private model: string | (() => Promise<CompatibleLanguageModel>);\n /**\n * The tool set configured for this agent.\n */\n public readonly tools: TBaseTools;\n private instructions?:\n | string\n | SystemModelMessage\n | Array<SystemModelMessage>;\n private generationSettings: GenerationSettings;\n private toolChoice?: ToolChoice<TBaseTools>;\n private telemetry?: TelemetrySettings;\n private experimentalContext: unknown;\n private prepareStep?: PrepareStepCallback<TBaseTools>;\n private constructorOnStepFinish?: StreamTextOnStepFinishCallback<\n ToolSet,\n any\n >;\n private constructorOnFinish?: StreamTextOnFinishCallback<ToolSet>;\n private constructorOnStart?: WorkflowAgentOnStartCallback;\n private constructorOnStepStart?: WorkflowAgentOnStepStartCallback;\n private constructorOnToolCallStart?: WorkflowAgentOnToolCallStartCallback;\n private constructorOnToolCallFinish?: WorkflowAgentOnToolCallFinishCallback;\n private prepareCall?: PrepareCallCallback<TBaseTools>;\n\n constructor(options: WorkflowAgentOptions<TBaseTools>) {\n this.model = options.model;\n this.tools = (options.tools ?? {}) as TBaseTools;\n // `instructions` takes precedence over deprecated `system`\n this.instructions = options.instructions ?? options.system;\n this.toolChoice = options.toolChoice;\n this.telemetry = options.experimental_telemetry;\n this.experimentalContext = options.experimental_context;\n this.prepareStep = options.prepareStep;\n this.constructorOnStepFinish = options.onStepFinish;\n this.constructorOnFinish = options.onFinish;\n this.constructorOnStart = options.experimental_onStart;\n this.constructorOnStepStart = options.experimental_onStepStart;\n this.constructorOnToolCallStart = options.experimental_onToolCallStart;\n this.constructorOnToolCallFinish = options.experimental_onToolCallFinish;\n this.prepareCall = options.prepareCall;\n\n // Extract generation settings\n this.generationSettings = {\n maxOutputTokens: options.maxOutputTokens,\n temperature: options.temperature,\n topP: options.topP,\n topK: options.topK,\n presencePenalty: options.presencePenalty,\n frequencyPenalty: options.frequencyPenalty,\n stopSequences: options.stopSequences,\n seed: options.seed,\n maxRetries: options.maxRetries,\n abortSignal: options.abortSignal,\n headers: options.headers,\n providerOptions: options.providerOptions,\n };\n }\n\n generate() {\n throw new Error('Not implemented');\n }\n\n async stream<\n TTools extends TBaseTools = TBaseTools,\n OUTPUT = never,\n PARTIAL_OUTPUT = never,\n >(\n options: WorkflowAgentStreamOptions<TTools, OUTPUT, PARTIAL_OUTPUT>,\n ): Promise<WorkflowAgentStreamResult<TTools, OUTPUT>> {\n // Call prepareCall to transform parameters before the agent loop\n let effectiveModel: string | (() => Promise<CompatibleLanguageModel>) =\n this.model;\n let effectiveInstructions = options.system ?? this.instructions;\n let effectiveMessages = options.messages;\n let effectiveGenerationSettings = { ...this.generationSettings };\n let effectiveExperimentalContext =\n options.experimental_context ?? this.experimentalContext;\n let effectiveToolChoiceFromPrepare = options.toolChoice ?? this.toolChoice;\n let effectiveTelemetryFromPrepare =\n options.experimental_telemetry ?? this.telemetry;\n\n if (this.prepareCall) {\n const prepared = await this.prepareCall({\n model: effectiveModel,\n tools: this.tools,\n instructions: effectiveInstructions,\n toolChoice: effectiveToolChoiceFromPrepare as ToolChoice<TBaseTools>,\n experimental_telemetry: effectiveTelemetryFromPrepare,\n experimental_context: effectiveExperimentalContext,\n messages: effectiveMessages as ModelMessage[],\n ...effectiveGenerationSettings,\n } as PrepareCallOptions<TBaseTools>);\n\n if (prepared.model !== undefined) effectiveModel = prepared.model;\n if (prepared.instructions !== undefined)\n effectiveInstructions = prepared.instructions;\n if (prepared.messages !== undefined)\n effectiveMessages =\n prepared.messages as WorkflowAgentStreamOptions<TTools>['messages'];\n if (prepared.experimental_context !== undefined)\n effectiveExperimentalContext = prepared.experimental_context;\n if (prepared.toolChoice !== undefined)\n effectiveToolChoiceFromPrepare =\n prepared.toolChoice as ToolChoice<TBaseTools>;\n if (prepared.experimental_telemetry !== undefined)\n effectiveTelemetryFromPrepare = prepared.experimental_telemetry;\n if (prepared.maxOutputTokens !== undefined)\n effectiveGenerationSettings.maxOutputTokens = prepared.maxOutputTokens;\n if (prepared.temperature !== undefined)\n effectiveGenerationSettings.temperature = prepared.temperature;\n if (prepared.topP !== undefined)\n effectiveGenerationSettings.topP = prepared.topP;\n if (prepared.topK !== undefined)\n effectiveGenerationSettings.topK = prepared.topK;\n if (prepared.presencePenalty !== undefined)\n effectiveGenerationSettings.presencePenalty = prepared.presencePenalty;\n if (prepared.frequencyPenalty !== undefined)\n effectiveGenerationSettings.frequencyPenalty =\n prepared.frequencyPenalty;\n if (prepared.stopSequences !== undefined)\n effectiveGenerationSettings.stopSequences = prepared.stopSequences;\n if (prepared.seed !== undefined)\n effectiveGenerationSettings.seed = prepared.seed;\n if (prepared.headers !== undefined)\n effectiveGenerationSettings.headers = prepared.headers;\n if (prepared.providerOptions !== undefined)\n effectiveGenerationSettings.providerOptions = prepared.providerOptions;\n }\n\n const prompt = await standardizePrompt({\n system: effectiveInstructions,\n messages: effectiveMessages,\n });\n\n const modelPrompt = await convertToLanguageModelPrompt({\n prompt,\n supportedUrls: {},\n download: options.experimental_download,\n });\n\n const effectiveAbortSignal = mergeAbortSignals(\n options.abortSignal ?? effectiveGenerationSettings.abortSignal,\n options.timeout != null\n ? AbortSignal.timeout(options.timeout)\n : undefined,\n );\n\n // Merge generation settings: constructor defaults < prepareCall < stream options\n const mergedGenerationSettings: GenerationSettings = {\n ...effectiveGenerationSettings,\n ...(options.maxOutputTokens !== undefined && {\n maxOutputTokens: options.maxOutputTokens,\n }),\n ...(options.temperature !== undefined && {\n temperature: options.temperature,\n }),\n ...(options.topP !== undefined && { topP: options.topP }),\n ...(options.topK !== undefined && { topK: options.topK }),\n ...(options.presencePenalty !== undefined && {\n presencePenalty: options.presencePenalty,\n }),\n ...(options.frequencyPenalty !== undefined && {\n frequencyPenalty: options.frequencyPenalty,\n }),\n ...(options.stopSequences !== undefined && {\n stopSequences: options.stopSequences,\n }),\n ...(options.seed !== undefined && { seed: options.seed }),\n ...(options.maxRetries !== undefined && {\n maxRetries: options.maxRetries,\n }),\n ...(effectiveAbortSignal !== undefined && {\n abortSignal: effectiveAbortSignal,\n }),\n ...(options.headers !== undefined && { headers: options.headers }),\n ...(options.providerOptions !== undefined && {\n providerOptions: options.providerOptions,\n }),\n };\n\n // Merge constructor + stream callbacks (constructor first, then stream)\n const mergedOnStepFinish = mergeCallbacks(\n this.constructorOnStepFinish as\n | StreamTextOnStepFinishCallback<TTools, any>\n | undefined,\n options.onStepFinish,\n );\n const mergedOnFinish = mergeCallbacks(\n this.constructorOnFinish as\n | StreamTextOnFinishCallback<TTools, OUTPUT>\n | undefined,\n options.onFinish,\n );\n const mergedOnStart = mergeCallbacks(\n this.constructorOnStart,\n options.experimental_onStart,\n );\n const mergedOnStepStart = mergeCallbacks(\n this.constructorOnStepStart,\n options.experimental_onStepStart,\n );\n const mergedOnToolCallStart = mergeCallbacks(\n this.constructorOnToolCallStart,\n options.experimental_onToolCallStart,\n );\n const mergedOnToolCallFinish = mergeCallbacks(\n this.constructorOnToolCallFinish,\n options.experimental_onToolCallFinish,\n );\n\n // Determine effective tool choice\n const effectiveToolChoice = effectiveToolChoiceFromPrepare;\n\n // Merge telemetry settings\n const effectiveTelemetry = effectiveTelemetryFromPrepare;\n\n // Filter tools if activeTools is specified\n const effectiveTools =\n options.activeTools && options.activeTools.length > 0\n ? filterTools(this.tools, options.activeTools as string[])\n : this.tools;\n\n // Initialize context\n let experimentalContext = effectiveExperimentalContext;\n\n const steps: StepResult<TTools, any>[] = [];\n\n // Track tool calls and results from the last step for the result\n let lastStepToolCalls: ToolCall[] = [];\n let lastStepToolResults: ToolResult[] = [];\n\n // Call onStart before the agent loop\n if (mergedOnStart) {\n await mergedOnStart({\n model: effectiveModel,\n messages: effectiveMessages as ModelMessage[],\n });\n }\n\n // Helper to wrap executeTool with onToolCallStart/onToolCallFinish callbacks\n const executeToolWithCallbacks = async (\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n tools: ToolSet,\n messages: LanguageModelV4Prompt,\n context?: unknown,\n ): Promise<LanguageModelV4ToolResultPart> => {\n if (mergedOnToolCallStart) {\n await mergedOnToolCallStart({\n toolCall: {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n },\n });\n }\n let result: LanguageModelV4ToolResultPart;\n try {\n result = await executeTool(toolCall, tools, messages, context);\n } catch (err) {\n if (mergedOnToolCallFinish) {\n await mergedOnToolCallFinish({\n toolCall: {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n },\n error: err,\n });\n }\n throw err;\n }\n if (mergedOnToolCallFinish) {\n const isError =\n result.output &&\n 'type' in result.output &&\n (result.output.type === 'error-text' ||\n result.output.type === 'error-json');\n await mergedOnToolCallFinish({\n toolCall: {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n },\n ...(isError\n ? {\n error:\n 'value' in result.output ? result.output.value : undefined,\n }\n : {\n result:\n result.output && 'value' in result.output\n ? result.output.value\n : undefined,\n }),\n });\n }\n return result;\n };\n\n // Check for abort before starting\n if (mergedGenerationSettings.abortSignal?.aborted) {\n if (options.onAbort) {\n await options.onAbort({ steps });\n }\n return {\n messages: options.messages as unknown as ModelMessage[],\n steps,\n toolCalls: [],\n toolResults: [],\n experimental_output: undefined as OUTPUT,\n };\n }\n\n const iterator = streamTextIterator({\n model: effectiveModel,\n tools: effectiveTools as ToolSet,\n writable: options.writable,\n prompt: modelPrompt,\n stopConditions: options.stopWhen,\n maxSteps: options.maxSteps,\n onStepFinish: mergedOnStepFinish,\n onStepStart: mergedOnStepStart,\n onError: options.onError,\n prepareStep:\n options.prepareStep ??\n (this.prepareStep as PrepareStepCallback<ToolSet> | undefined),\n generationSettings: mergedGenerationSettings,\n toolChoice: effectiveToolChoice as ToolChoice<ToolSet>,\n experimental_context: experimentalContext,\n experimental_telemetry: effectiveTelemetry,\n includeRawChunks: options.includeRawChunks ?? false,\n repairToolCall:\n options.experimental_repairToolCall as ToolCallRepairFunction<ToolSet>,\n responseFormat: await options.experimental_output?.responseFormat,\n });\n\n // Track the final conversation messages from the iterator\n let finalMessages: LanguageModelV4Prompt | undefined;\n let encounteredError: unknown;\n let wasAborted = false;\n\n try {\n let result = await iterator.next();\n while (!result.done) {\n // Check for abort during iteration\n if (mergedGenerationSettings.abortSignal?.aborted) {\n wasAborted = true;\n if (options.onAbort) {\n await options.onAbort({ steps });\n }\n break;\n }\n\n const {\n toolCalls,\n messages: iterMessages,\n step,\n context,\n providerExecutedToolResults,\n } = result.value;\n if (step) {\n steps.push(step as unknown as StepResult<TTools, any>);\n }\n if (context !== undefined) {\n experimentalContext = context;\n }\n\n // Only execute tools if there are tool calls\n if (toolCalls.length > 0) {\n // Separate provider-executed tool calls from client-executed ones\n const nonProviderToolCalls = toolCalls.filter(\n tc => !tc.providerExecuted,\n );\n const providerToolCalls = toolCalls.filter(tc => tc.providerExecuted);\n\n // Further split non-provider tool calls into executable (has execute function)\n // and client-side (no execute function, needs external resolution)\n // Note: missing tools (!tool) are left to executeTool which will throw —\n // only tools that exist but lack execute are treated as client-side.\n const executableToolCalls = nonProviderToolCalls.filter(tc => {\n const tool = (effectiveTools as ToolSet)[tc.toolName];\n return !tool || typeof tool.execute === 'function';\n });\n const clientSideToolCalls = nonProviderToolCalls.filter(tc => {\n const tool = (effectiveTools as ToolSet)[tc.toolName];\n return tool && typeof tool.execute !== 'function';\n });\n\n // If there are client-side tool calls, stop the loop and return them\n // This matches AI SDK behavior: tools without execute pause the agent loop\n if (clientSideToolCalls.length > 0) {\n // Execute any executable tools that were also called in this step\n const executableResults = await Promise.all(\n executableToolCalls.map(\n (toolCall): Promise<LanguageModelV4ToolResultPart> =>\n executeToolWithCallbacks(\n toolCall,\n effectiveTools as ToolSet,\n iterMessages,\n experimentalContext,\n ),\n ),\n );\n\n // Collect provider tool results\n const providerResults: LanguageModelV4ToolResultPart[] =\n providerToolCalls.map(toolCall =>\n resolveProviderToolResult(\n toolCall,\n providerExecutedToolResults,\n ),\n );\n\n const resolvedResults = [...executableResults, ...providerResults];\n\n const allToolCalls: ToolCall[] = toolCalls.map(tc => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n }));\n\n const allToolResults: ToolResult[] = resolvedResults.map(r => ({\n type: 'tool-result' as const,\n toolCallId: r.toolCallId,\n toolName: r.toolName,\n input: toolCalls.find(tc => tc.toolCallId === r.toolCallId)\n ?.input,\n output: 'value' in r.output ? r.output.value : undefined,\n }));\n\n if (resolvedResults.length > 0) {\n iterMessages.push({\n role: 'tool',\n content: resolvedResults,\n });\n }\n\n const messages = iterMessages as unknown as ModelMessage[];\n\n if (mergedOnFinish && !wasAborted) {\n const lastStep = steps[steps.length - 1];\n await mergedOnFinish({\n steps,\n messages,\n text: lastStep?.text ?? '',\n finishReason: lastStep?.finishReason ?? 'other',\n totalUsage: aggregateUsage(steps),\n experimental_context: experimentalContext,\n experimental_output: undefined as OUTPUT,\n });\n }\n\n return {\n messages,\n steps,\n toolCalls: allToolCalls,\n toolResults: allToolResults,\n experimental_output: undefined as OUTPUT,\n };\n }\n\n // Execute client tools (all have execute functions at this point)\n const clientToolResults = await Promise.all(\n nonProviderToolCalls.map(\n (toolCall): Promise<LanguageModelV4ToolResultPart> =>\n executeToolWithCallbacks(\n toolCall,\n effectiveTools as ToolSet,\n iterMessages,\n experimentalContext,\n ),\n ),\n );\n\n // For provider-executed tools, use the results from the stream\n const providerToolResults: LanguageModelV4ToolResultPart[] =\n providerToolCalls.map(toolCall =>\n resolveProviderToolResult(toolCall, providerExecutedToolResults),\n );\n\n // Combine results in the original order\n const toolResults = toolCalls.map(tc => {\n const clientResult = clientToolResults.find(\n r => r.toolCallId === tc.toolCallId,\n );\n if (clientResult) return clientResult;\n const providerResult = providerToolResults.find(\n r => r.toolCallId === tc.toolCallId,\n );\n if (providerResult) return providerResult;\n // This should never happen, but return empty result as fallback\n return {\n type: 'tool-result' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n output: { type: 'text' as const, value: '' },\n };\n });\n\n // Track the tool calls and results for this step\n lastStepToolCalls = toolCalls.map(tc => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n }));\n lastStepToolResults = toolResults.map(r => ({\n type: 'tool-result' as const,\n toolCallId: r.toolCallId,\n toolName: r.toolName,\n input: toolCalls.find(tc => tc.toolCallId === r.toolCallId)?.input,\n output: 'value' in r.output ? r.output.value : undefined,\n }));\n\n result = await iterator.next(toolResults);\n } else {\n // Final step with no tool calls - reset tracking\n lastStepToolCalls = [];\n lastStepToolResults = [];\n result = await iterator.next([]);\n }\n }\n\n // When the iterator completes normally, result.value contains the final conversation prompt\n if (result.done) {\n finalMessages = result.value;\n }\n } catch (error) {\n encounteredError = error;\n // Check if this is an abort error\n if (error instanceof Error && error.name === 'AbortError') {\n wasAborted = true;\n if (options.onAbort) {\n await options.onAbort({ steps });\n }\n } else if (options.onError) {\n // Call onError for non-abort errors (including tool execution errors)\n await options.onError({ error });\n }\n // Don't throw yet - we want to call onFinish first\n }\n\n // Use the final messages from the iterator, or fall back to original messages\n const messages = (finalMessages ??\n options.messages) as unknown as ModelMessage[];\n\n // Parse structured output if experimental_output is specified\n let experimentalOutput: OUTPUT = undefined as OUTPUT;\n if (options.experimental_output && steps.length > 0) {\n const lastStep = steps[steps.length - 1];\n const text = lastStep.text;\n if (text) {\n try {\n experimentalOutput =\n await options.experimental_output.parseCompleteOutput(\n { text },\n {\n response: lastStep.response,\n usage: lastStep.usage,\n finishReason: lastStep.finishReason,\n },\n );\n } catch (parseError) {\n // If there's already an error, don't override it\n // If not, set this as the error\n if (!encounteredError) {\n encounteredError = parseError;\n }\n }\n }\n }\n\n // Call onFinish callback if provided (always call, even on errors, but not on abort)\n if (mergedOnFinish && !wasAborted) {\n const lastStep = steps[steps.length - 1];\n await mergedOnFinish({\n steps,\n messages: messages as ModelMessage[],\n text: lastStep?.text ?? '',\n finishReason: lastStep?.finishReason ?? 'other',\n totalUsage: aggregateUsage(steps),\n experimental_context: experimentalContext,\n experimental_output: experimentalOutput,\n });\n }\n\n // Re-throw any error that occurred\n if (encounteredError) {\n throw encounteredError;\n }\n\n return {\n messages: messages as ModelMessage[],\n steps,\n toolCalls: lastStepToolCalls,\n toolResults: lastStepToolResults,\n experimental_output: experimentalOutput,\n };\n }\n}\n\n/**\n * Filter tools to only include the specified active tools.\n */\n/**\n * Aggregate token usage across all steps.\n */\nfunction aggregateUsage(steps: StepResult<any, any>[]): LanguageModelUsage {\n let inputTokens = 0;\n let outputTokens = 0;\n for (const step of steps) {\n inputTokens += step.usage?.inputTokens ?? 0;\n outputTokens += step.usage?.outputTokens ?? 0;\n }\n return {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n } as LanguageModelUsage;\n}\n\nfunction filterTools<TTools extends ToolSet>(\n tools: TTools,\n activeTools: string[],\n): ToolSet {\n const filtered: ToolSet = {};\n for (const toolName of activeTools) {\n if (toolName in tools) {\n filtered[toolName] = tools[toolName];\n }\n }\n return filtered;\n}\n\n/**\n * Safely parse tool call input JSON. Returns the parsed value or the raw string\n * if parsing fails (e.g., for tool calls that were repaired).\n */\nfunction safeParseInput(input: string | undefined): unknown {\n try {\n return JSON.parse(input || '{}');\n } catch {\n return input;\n }\n}\n\n// Matches AI SDK's getErrorMessage from @ai-sdk/provider-utils\nfunction getErrorMessage(error: unknown): string {\n if (error == null) {\n return 'unknown error';\n }\n\n if (typeof error === 'string') {\n return error;\n }\n\n if (error instanceof Error) {\n return error.message;\n }\n\n return JSON.stringify(error);\n}\n\nfunction resolveProviderToolResult(\n toolCall: { toolCallId: string; toolName: string },\n providerExecutedToolResults?: Map<\n string,\n { toolCallId: string; toolName: string; result: unknown; isError?: boolean }\n >,\n): LanguageModelV4ToolResultPart {\n const streamResult = providerExecutedToolResults?.get(toolCall.toolCallId);\n if (!streamResult) {\n console.warn(\n `[WorkflowAgent] Provider-executed tool \"${toolCall.toolName}\" (${toolCall.toolCallId}) ` +\n `did not receive a result from the stream. This may indicate a provider issue.`,\n );\n return {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: {\n type: 'text' as const,\n value: '',\n },\n };\n }\n\n const result = streamResult.result;\n const isString = typeof result === 'string';\n\n return {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: isString\n ? streamResult.isError\n ? { type: 'error-text' as const, value: result }\n : { type: 'text' as const, value: result }\n : streamResult.isError\n ? {\n type: 'error-json' as const,\n value: result as JSONValue,\n }\n : {\n type: 'json' as const,\n value: result as JSONValue,\n },\n };\n}\n\nasync function executeTool(\n toolCall: { toolCallId: string; toolName: string; input: unknown },\n tools: ToolSet,\n messages: LanguageModelV4Prompt,\n experimentalContext?: unknown,\n): Promise<LanguageModelV4ToolResultPart> {\n const tool = tools[toolCall.toolName];\n if (!tool) throw new Error(`Tool \"${toolCall.toolName}\" not found`);\n if (typeof tool.execute !== 'function') {\n throw new Error(\n `Tool \"${toolCall.toolName}\" does not have an execute function. ` +\n `Client-side tools should be filtered before calling executeTool.`,\n );\n }\n // Input is already parsed and validated by streamModelCall's parseToolCall\n const parsedInput = toolCall.input;\n\n try {\n // Extract execute function to avoid binding `this` to the tool object.\n // If we called `tool.execute(...)` directly, JavaScript would bind `this`\n // to `tool`, which contains non-serializable properties like `inputSchema`.\n // When the execute function is a workflow step (marked with 'use step'),\n // the step system captures `this` for serialization, causing failures.\n const { execute } = tool;\n const toolResult = await execute(parsedInput, {\n toolCallId: toolCall.toolCallId,\n // Pass the conversation messages to the tool so it has context about the conversation\n messages,\n // Pass experimental context to the tool\n experimental_context: experimentalContext,\n });\n\n // Use the appropriate output type based on the result\n // AI SDK supports 'text' for strings and 'json' for objects\n const output =\n typeof toolResult === 'string'\n ? { type: 'text' as const, value: toolResult }\n : { type: 'json' as const, value: toolResult };\n\n return {\n type: 'tool-result' as const,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output,\n };\n } catch (error) {\n // Convert tool errors to error-text results sent back to the model,\n // allowing the agent to recover rather than killing the entire stream.\n // This aligns with AI SDK's streamText behavior for individual tool failures.\n return {\n type: 'tool-result',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n output: {\n type: 'error-text',\n value: getErrorMessage(error),\n },\n };\n }\n}\n","import type {\n LanguageModelV4CallOptions,\n LanguageModelV4Prompt,\n} from '@ai-sdk/provider';\nimport {\n type Experimental_ModelCallStreamPart as ModelCallStreamPart,\n experimental_streamModelCall as streamModelCall,\n type FinishReason,\n type LanguageModel,\n type LanguageModelUsage,\n type ModelMessage,\n type StepResult,\n type StopCondition,\n type ToolCallRepairFunction,\n type ToolChoice,\n type ToolSet,\n} from 'ai';\nimport { gateway } from 'ai';\nimport type { ProviderOptions, TelemetrySettings } from './workflow-agent.js';\nimport {\n resolveSerializableTools,\n type SerializableToolDef,\n} from './serializable-schema.js';\nimport type { CompatibleLanguageModel } from './types.js';\n\nexport type { Experimental_ModelCallStreamPart as ModelCallStreamPart } from 'ai';\n\nexport type ModelStopCondition = StopCondition<NoInfer<ToolSet>, any>;\n\n/**\n * Provider-executed tool result captured from the stream.\n */\nexport interface ProviderExecutedToolResult {\n toolCallId: string;\n toolName: string;\n result: unknown;\n isError?: boolean;\n}\n\n/**\n * Options for the doStreamStep function.\n */\nexport interface DoStreamStepOptions {\n maxOutputTokens?: number;\n temperature?: number;\n topP?: number;\n topK?: number;\n presencePenalty?: number;\n frequencyPenalty?: number;\n stopSequences?: string[];\n seed?: number;\n maxRetries?: number;\n abortSignal?: AbortSignal;\n headers?: Record<string, string | undefined>;\n providerOptions?: ProviderOptions;\n toolChoice?: ToolChoice<ToolSet>;\n includeRawChunks?: boolean;\n experimental_telemetry?: TelemetrySettings;\n repairToolCall?: ToolCallRepairFunction<ToolSet>;\n responseFormat?: LanguageModelV4CallOptions['responseFormat'];\n}\n\n/**\n * Parsed tool call from the stream (parsed by streamModelCall's transform).\n */\nexport interface ParsedToolCall {\n type: 'tool-call';\n toolCallId: string;\n toolName: string;\n input: unknown;\n providerExecuted?: boolean;\n providerMetadata?: Record<string, unknown>;\n dynamic?: boolean;\n invalid?: boolean;\n error?: unknown;\n}\n\n/**\n * Finish metadata from the stream.\n */\nexport interface StreamFinish {\n finishReason: FinishReason;\n rawFinishReason: string | undefined;\n usage: LanguageModelUsage;\n providerMetadata?: Record<string, unknown>;\n}\n\nexport async function doStreamStep(\n conversationPrompt: LanguageModelV4Prompt,\n modelInit: string | (() => Promise<CompatibleLanguageModel>),\n writable?: WritableStream<ModelCallStreamPart<ToolSet>>,\n serializedTools?: Record<string, SerializableToolDef>,\n options?: DoStreamStepOptions,\n) {\n 'use step';\n\n // Resolve model inside step (must happen here for serialization boundary)\n let model: CompatibleLanguageModel;\n if (typeof modelInit === 'string') {\n model = gateway.languageModel(modelInit) as CompatibleLanguageModel;\n } else if (typeof modelInit === 'function') {\n model = await modelInit();\n } else {\n throw new Error(\n 'Invalid \"model initialization\" argument. Must be a string or a function that returns a LanguageModel instance.',\n );\n }\n\n // Reconstruct tools from serializable definitions with Ajv validation.\n // Tools are serialized before crossing the step boundary because zod schemas\n // contain functions that can't be serialized by the workflow runtime.\n const tools = serializedTools\n ? resolveSerializableTools(serializedTools)\n : undefined;\n\n // streamModelCall handles: prompt standardization, tool preparation,\n // model.doStream(), retry logic, and stream part transformation\n // (tool call parsing, finish reason mapping, file wrapping).\n const { stream: modelStream } = await streamModelCall({\n model: model as LanguageModel,\n // streamModelCall expects Prompt (ModelMessage[]) but we pass the\n // pre-converted LanguageModelV4Prompt. standardizePrompt inside\n // streamModelCall handles both formats.\n messages: conversationPrompt as unknown as ModelMessage[],\n tools,\n toolChoice: options?.toolChoice,\n includeRawChunks: options?.includeRawChunks,\n providerOptions: options?.providerOptions,\n abortSignal: options?.abortSignal,\n headers: options?.headers,\n maxOutputTokens: options?.maxOutputTokens,\n temperature: options?.temperature,\n topP: options?.topP,\n topK: options?.topK,\n presencePenalty: options?.presencePenalty,\n frequencyPenalty: options?.frequencyPenalty,\n stopSequences: options?.stopSequences,\n seed: options?.seed,\n repairToolCall: options?.repairToolCall,\n });\n\n // Consume the stream: capture data and write to writable in real-time\n const toolCalls: ParsedToolCall[] = [];\n const providerExecutedToolResults = new Map<\n string,\n ProviderExecutedToolResult\n >();\n let finish: StreamFinish | undefined;\n\n // Aggregation for StepResult\n let text = '';\n const reasoningParts: Array<{ text: string }> = [];\n let responseMetadata:\n | { id?: string; timestamp?: Date; modelId?: string }\n | undefined;\n let warnings: unknown[] | undefined;\n\n // Acquire writer once before the loop to avoid per-chunk lock overhead\n const writer = writable?.getWriter();\n\n try {\n for await (const part of modelStream) {\n switch (part.type) {\n case 'text-delta':\n text += part.text;\n break;\n case 'reasoning-delta':\n reasoningParts.push({ text: part.text });\n break;\n case 'tool-call': {\n // parseToolCall adds dynamic/invalid/error at runtime\n const toolCallPart = part as typeof part & Partial<ParsedToolCall>;\n toolCalls.push({\n type: 'tool-call',\n toolCallId: toolCallPart.toolCallId,\n toolName: toolCallPart.toolName,\n input: toolCallPart.input,\n providerExecuted: toolCallPart.providerExecuted,\n providerMetadata: toolCallPart.providerMetadata as\n | Record<string, unknown>\n | undefined,\n dynamic: toolCallPart.dynamic,\n invalid: toolCallPart.invalid,\n error: toolCallPart.error,\n });\n break;\n }\n case 'tool-result':\n if (part.providerExecuted) {\n providerExecutedToolResults.set(part.toolCallId, {\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n result: part.output,\n isError: false,\n });\n }\n break;\n case 'tool-error': {\n const errorPart = part as typeof part & {\n providerExecuted?: boolean;\n };\n if (errorPart.providerExecuted) {\n providerExecutedToolResults.set(errorPart.toolCallId, {\n toolCallId: errorPart.toolCallId,\n toolName: errorPart.toolName,\n result: errorPart.error,\n isError: true,\n });\n }\n break;\n }\n case 'model-call-end':\n finish = {\n finishReason: part.finishReason,\n rawFinishReason: part.rawFinishReason,\n usage: part.usage,\n providerMetadata: part.providerMetadata as\n | Record<string, unknown>\n | undefined,\n };\n break;\n case 'model-call-start':\n warnings = part.warnings;\n break;\n case 'model-call-response-metadata':\n responseMetadata = part;\n break;\n }\n\n // Write to writable in real-time\n if (writer) {\n await writer.write(part);\n }\n }\n } finally {\n writer?.releaseLock();\n }\n\n // Build StepResult\n const reasoningText = reasoningParts.map(r => r.text).join('') || undefined;\n\n const step: StepResult<ToolSet, any> = {\n callId: 'workflow-agent',\n stepNumber: 0,\n model: {\n provider: responseMetadata?.modelId?.split(':')[0] ?? 'unknown',\n modelId: responseMetadata?.modelId ?? 'unknown',\n },\n functionId: undefined,\n metadata: undefined,\n experimental_context: undefined,\n content: [\n ...(text ? [{ type: 'text' as const, text }] : []),\n ...toolCalls\n .filter(tc => !tc.invalid)\n .map(tc => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n ...(tc.dynamic ? { dynamic: true as const } : {}),\n })),\n ],\n text,\n reasoning: reasoningParts.map(r => ({\n type: 'reasoning' as const,\n text: r.text,\n })),\n reasoningText,\n files: [],\n sources: [],\n toolCalls: toolCalls\n .filter(tc => !tc.invalid)\n .map(tc => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n ...(tc.dynamic ? { dynamic: true as const } : {}),\n })),\n staticToolCalls: [],\n dynamicToolCalls: toolCalls\n .filter(tc => !tc.invalid && tc.dynamic)\n .map(tc => ({\n type: 'tool-call' as const,\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n input: tc.input,\n dynamic: true as const,\n })),\n toolResults: [],\n staticToolResults: [],\n dynamicToolResults: [],\n finishReason: finish?.finishReason ?? 'other',\n rawFinishReason: finish?.rawFinishReason,\n usage:\n finish?.usage ??\n ({\n inputTokens: 0,\n inputTokenDetails: {\n noCacheTokens: undefined,\n cacheReadTokens: undefined,\n cacheWriteTokens: undefined,\n },\n outputTokens: 0,\n outputTokenDetails: {\n textTokens: undefined,\n reasoningTokens: undefined,\n },\n totalTokens: 0,\n } as LanguageModelUsage),\n warnings,\n request: { body: '' },\n response: {\n id: responseMetadata?.id ?? 'unknown',\n timestamp: responseMetadata?.timestamp ?? new Date(),\n modelId: responseMetadata?.modelId ?? 'unknown',\n messages: [],\n },\n providerMetadata: finish?.providerMetadata ?? {},\n } as StepResult<ToolSet, any>;\n\n return {\n toolCalls,\n finish,\n step,\n providerExecutedToolResults,\n };\n}\n","/**\n * Helpers for passing tool schemas across workflow step boundaries.\n *\n * Tool schemas (zod, valibot, arktype, etc.) contain functions that can't be\n * serialized by the workflow runtime. These helpers extract JSON Schema from\n * schemas, then reconstruct tools with Ajv validation inside step functions.\n *\n * Uses `asSchema()` from `@ai-sdk/provider-utils` for JSON Schema extraction,\n * which supports Standard Schema compatible libraries. When libraries adopt\n * `~standard.jsonSchema` (Standard Schema v2), extraction can be simplified\n * to use that interface directly.\n */\nimport type { JSONSchema7 } from '@ai-sdk/provider';\nimport { asSchema, jsonSchema } from '@ai-sdk/provider-utils';\nimport { tool, type ToolSet } from 'ai';\nimport Ajv from 'ajv';\n\n/**\n * Serializable tool definition — plain objects only, safe for workflow steps.\n */\nexport type SerializableToolDef = {\n description?: string;\n inputSchema: JSONSchema7;\n};\n\n/**\n * Converts a ToolSet (with zod/standard schemas and execute functions) to a\n * serializable record of tool definitions. Only description and inputSchema\n * (as JSON Schema) are preserved — execute functions are stripped since they\n * run outside the step.\n */\nexport function serializeToolSet(\n tools: ToolSet,\n): Record<string, SerializableToolDef> {\n return Object.fromEntries(\n Object.entries(tools).map(([name, t]) => [\n name,\n {\n description: t.description,\n inputSchema: asSchema(t.inputSchema).jsonSchema as JSONSchema7,\n },\n ]),\n );\n}\n\n/**\n * Reconstructs tool objects from serializable tool definitions inside a step.\n *\n * Wraps each tool's JSON Schema with `jsonSchema()` and validates tool call\n * arguments against the schema using Ajv. This provides runtime type safety\n * equivalent to using zod schemas directly with the AI SDK.\n */\nexport function resolveSerializableTools(\n tools: Record<string, SerializableToolDef>,\n): ToolSet {\n const ajv = new Ajv();\n\n return Object.fromEntries(\n Object.entries(tools).map(([name, t]) => {\n const validateFn = ajv.compile(t.inputSchema);\n\n return [\n name,\n tool({\n description: t.description,\n inputSchema: jsonSchema(t.inputSchema, {\n validate: value => {\n if (validateFn(value)) {\n return { success: true, value: value as any };\n }\n return {\n success: false,\n error: new Error(ajv.errorsText(validateFn.errors)),\n };\n },\n }),\n }),\n ];\n }),\n );\n}\n","import type {\n LanguageModelV4CallOptions,\n LanguageModelV4Prompt,\n LanguageModelV4ToolCall,\n LanguageModelV4ToolResultPart,\n} from '@ai-sdk/provider';\nimport type {\n Experimental_ModelCallStreamPart as ModelCallStreamPart,\n ModelMessage,\n StepResult,\n StreamTextOnStepFinishCallback,\n ToolCallRepairFunction,\n ToolChoice,\n ToolSet,\n} from 'ai';\nimport {\n doStreamStep,\n type ModelStopCondition,\n type ParsedToolCall,\n type ProviderExecutedToolResult,\n} from './do-stream-step.js';\nimport { serializeToolSet } from './serializable-schema.js';\nimport type {\n GenerationSettings,\n PrepareStepCallback,\n StreamTextOnErrorCallback,\n TelemetrySettings,\n WorkflowAgentOnStepStartCallback,\n} from './workflow-agent.js';\nimport type { CompatibleLanguageModel } from './types.js';\n\n// Re-export for consumers\nexport type { ProviderExecutedToolResult } from './do-stream-step.js';\n\n/**\n * The value yielded by the stream text iterator when tool calls are requested.\n * Contains both the tool calls and the current conversation messages.\n */\nexport interface StreamTextIteratorYieldValue {\n /** The tool calls requested by the model (parsed with typed inputs) */\n toolCalls: ParsedToolCall[];\n /** The conversation messages up to (and including) the tool call request */\n messages: LanguageModelV4Prompt;\n /** The step result from the current step */\n step?: StepResult<ToolSet, any>;\n /** The current experimental context */\n context?: unknown;\n /** Provider-executed tool results (keyed by tool call ID) */\n providerExecutedToolResults?: Map<string, ProviderExecutedToolResult>;\n}\n\n// This runs in the workflow context\nexport async function* streamTextIterator({\n prompt,\n tools = {},\n writable,\n model,\n stopConditions,\n maxSteps,\n onStepFinish,\n onStepStart,\n onError,\n prepareStep,\n generationSettings,\n toolChoice,\n experimental_context,\n experimental_telemetry,\n includeRawChunks = false,\n repairToolCall,\n responseFormat,\n}: {\n prompt: LanguageModelV4Prompt;\n tools: ToolSet;\n writable?: WritableStream<ModelCallStreamPart<ToolSet>>;\n model: string | (() => Promise<CompatibleLanguageModel>);\n stopConditions?: ModelStopCondition[] | ModelStopCondition;\n maxSteps?: number;\n onStepFinish?: StreamTextOnStepFinishCallback<any, any>;\n onStepStart?: WorkflowAgentOnStepStartCallback;\n onError?: StreamTextOnErrorCallback;\n prepareStep?: PrepareStepCallback<any>;\n generationSettings?: GenerationSettings;\n toolChoice?: ToolChoice<ToolSet>;\n experimental_context?: unknown;\n experimental_telemetry?: TelemetrySettings;\n includeRawChunks?: boolean;\n repairToolCall?: ToolCallRepairFunction<ToolSet>;\n responseFormat?: LanguageModelV4CallOptions['responseFormat'];\n}): AsyncGenerator<\n StreamTextIteratorYieldValue,\n LanguageModelV4Prompt,\n LanguageModelV4ToolResultPart[]\n> {\n let conversationPrompt = [...prompt]; // Create a mutable copy\n let currentModel: string | (() => Promise<CompatibleLanguageModel>) = model;\n let currentGenerationSettings = generationSettings ?? {};\n let currentToolChoice = toolChoice;\n let currentContext = experimental_context;\n let currentActiveTools: string[] | undefined;\n\n const steps: StepResult<any, any>[] = [];\n let done = false;\n let isFirstIteration = true;\n let stepNumber = 0;\n let lastStep: StepResult<any, any> | undefined;\n let lastStepWasToolCalls = false;\n\n // Default maxSteps to Infinity to preserve backwards compatibility\n // (agent loops until completion unless explicitly limited)\n const effectiveMaxSteps = maxSteps ?? Infinity;\n\n while (!done) {\n // Check if we've exceeded the maximum number of steps\n if (stepNumber >= effectiveMaxSteps) {\n break;\n }\n\n // Check for abort signal\n if (currentGenerationSettings.abortSignal?.aborted) {\n break;\n }\n\n // Call prepareStep callback before each step if provided\n if (prepareStep) {\n const prepareResult = await prepareStep({\n model: currentModel,\n stepNumber,\n steps,\n messages: conversationPrompt,\n experimental_context: currentContext,\n });\n\n // Apply any overrides from prepareStep\n if (prepareResult.model !== undefined) {\n currentModel = prepareResult.model;\n }\n // Apply messages override BEFORE system so the system message\n // isn't lost when messages replaces the prompt.\n if (prepareResult.messages !== undefined) {\n conversationPrompt = [...prepareResult.messages];\n }\n if (prepareResult.system !== undefined) {\n // Update or prepend system message in the conversation prompt.\n // Applied AFTER messages override so the system message isn't\n // lost when messages replaces the prompt.\n if (\n conversationPrompt.length > 0 &&\n conversationPrompt[0].role === 'system'\n ) {\n // Replace existing system message\n conversationPrompt[0] = {\n role: 'system',\n content: prepareResult.system,\n };\n } else {\n // Prepend new system message\n conversationPrompt.unshift({\n role: 'system',\n content: prepareResult.system,\n });\n }\n }\n if (prepareResult.experimental_context !== undefined) {\n currentContext = prepareResult.experimental_context;\n }\n if (prepareResult.activeTools !== undefined) {\n currentActiveTools = prepareResult.activeTools;\n }\n // Apply generation settings overrides\n if (prepareResult.maxOutputTokens !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n maxOutputTokens: prepareResult.maxOutputTokens,\n };\n }\n if (prepareResult.temperature !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n temperature: prepareResult.temperature,\n };\n }\n if (prepareResult.topP !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n topP: prepareResult.topP,\n };\n }\n if (prepareResult.topK !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n topK: prepareResult.topK,\n };\n }\n if (prepareResult.presencePenalty !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n presencePenalty: prepareResult.presencePenalty,\n };\n }\n if (prepareResult.frequencyPenalty !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n frequencyPenalty: prepareResult.frequencyPenalty,\n };\n }\n if (prepareResult.stopSequences !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n stopSequences: prepareResult.stopSequences,\n };\n }\n if (prepareResult.seed !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n seed: prepareResult.seed,\n };\n }\n if (prepareResult.maxRetries !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n maxRetries: prepareResult.maxRetries,\n };\n }\n if (prepareResult.headers !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n headers: prepareResult.headers,\n };\n }\n if (prepareResult.providerOptions !== undefined) {\n currentGenerationSettings = {\n ...currentGenerationSettings,\n providerOptions: prepareResult.providerOptions,\n };\n }\n if (prepareResult.toolChoice !== undefined) {\n currentToolChoice = prepareResult.toolChoice;\n }\n }\n\n if (onStepStart) {\n await onStepStart({\n stepNumber,\n model: currentModel,\n messages: conversationPrompt as unknown as ModelMessage[],\n });\n }\n\n try {\n // Filter tools if activeTools is specified\n const effectiveTools =\n currentActiveTools && currentActiveTools.length > 0\n ? filterToolSet(tools, currentActiveTools)\n : tools;\n\n // Serialize tools before crossing the step boundary — zod schemas\n // contain functions that can't be serialized by the workflow runtime.\n // Tools are reconstructed with Ajv validation inside doStreamStep.\n const serializedTools = serializeToolSet(effectiveTools);\n\n const { toolCalls, finish, step, providerExecutedToolResults } =\n await doStreamStep(\n conversationPrompt,\n currentModel,\n writable,\n serializedTools,\n {\n ...currentGenerationSettings,\n toolChoice: currentToolChoice,\n includeRawChunks,\n experimental_telemetry,\n repairToolCall,\n responseFormat,\n },\n );\n\n isFirstIteration = false;\n stepNumber++;\n steps.push(step);\n lastStep = step;\n lastStepWasToolCalls = false;\n\n const finishReason = finish?.finishReason;\n\n if (finishReason === 'tool-calls') {\n lastStepWasToolCalls = true;\n\n // Add assistant message with tool calls to the conversation\n // Note: providerMetadata from the tool call is mapped to providerOptions\n // in the prompt format, following the AI SDK convention. This is critical\n // for providers like Gemini that require thoughtSignature to be preserved\n // across multi-turn tool calls. Some fields are sanitized before mapping.\n conversationPrompt.push({\n role: 'assistant',\n content: toolCalls.map(toolCall => {\n const sanitizedMetadata = sanitizeProviderMetadataForToolCall(\n toolCall.providerMetadata,\n );\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n ...(sanitizedMetadata != null\n ? { providerOptions: sanitizedMetadata }\n : {}),\n };\n }) as typeof toolCalls,\n });\n\n // Yield the tool calls along with the current conversation messages\n // This allows executeTool to pass the conversation context to tool execute functions\n // Also include provider-executed tool results so they can be used instead of local execution\n const toolResults = yield {\n toolCalls,\n messages: conversationPrompt,\n step,\n context: currentContext,\n providerExecutedToolResults,\n };\n\n conversationPrompt.push({\n role: 'tool',\n content: toolResults,\n });\n\n if (stopConditions) {\n const stopConditionList = Array.isArray(stopConditions)\n ? stopConditions\n : [stopConditions];\n if (stopConditionList.some(test => test({ steps }))) {\n done = true;\n }\n }\n } else if (finishReason === 'stop') {\n // Add assistant message with text content to the conversation\n const textContent = step.content.filter(\n item => item.type === 'text',\n ) as Array<{ type: 'text'; text: string }>;\n\n if (textContent.length > 0) {\n conversationPrompt.push({\n role: 'assistant',\n content: textContent,\n });\n }\n\n done = true;\n } else if (finishReason === 'length') {\n // Model hit max tokens - stop but don't throw\n done = true;\n } else if (finishReason === 'content-filter') {\n // Content filter triggered - stop but don't throw\n done = true;\n } else if (finishReason === 'error') {\n // Model error - stop but don't throw\n done = true;\n } else if (finishReason === 'other') {\n // Other reason - stop but don't throw\n done = true;\n } else if (finishReason === 'unknown') {\n // Unknown reason - stop but don't throw\n done = true;\n } else if (!finishReason) {\n // No finish reason - this might happen on incomplete streams\n done = true;\n } else {\n throw new Error(\n `Unexpected finish reason: ${typeof finish?.finishReason === 'object' ? JSON.stringify(finish?.finishReason) : finish?.finishReason}`,\n );\n }\n\n if (onStepFinish) {\n await onStepFinish(step);\n }\n } catch (error) {\n if (onError) {\n await onError({ error });\n }\n throw error;\n }\n }\n\n // Yield the final step if it wasn't already yielded (tool-calls steps are yielded inside the loop)\n if (lastStep && !lastStepWasToolCalls) {\n yield {\n toolCalls: [],\n messages: conversationPrompt,\n step: lastStep,\n context: currentContext,\n };\n }\n\n return conversationPrompt;\n}\n\n/**\n * Filter a tool set to only include the specified active tools.\n */\nfunction filterToolSet(tools: ToolSet, activeTools: string[]): ToolSet {\n const filtered: ToolSet = {};\n for (const toolName of activeTools) {\n if (toolName in tools) {\n filtered[toolName] = tools[toolName];\n }\n }\n return filtered;\n}\n\n/**\n * Strip OpenAI's itemId from providerMetadata (requires reasoning items we don't preserve).\n * Preserves all other provider metadata (e.g., Gemini's thoughtSignature).\n */\nfunction sanitizeProviderMetadataForToolCall(\n metadata: unknown,\n): Record<string, unknown> | undefined {\n if (metadata == null) return undefined;\n\n const meta = metadata as Record<string, unknown>;\n\n // Check if OpenAI metadata exists and needs sanitization\n if ('openai' in meta && meta.openai != null) {\n const { openai, ...restProviders } = meta;\n const openaiMeta = openai as Record<string, unknown>;\n\n // Remove itemId from OpenAI metadata - it requires reasoning items we don't preserve\n const { itemId: _itemId, ...restOpenai } = openaiMeta;\n\n // Reconstruct metadata without itemId\n const hasOtherOpenaiFields = Object.keys(restOpenai).length > 0;\n const hasOtherProviders = Object.keys(restProviders).length > 0;\n\n if (hasOtherOpenaiFields && hasOtherProviders) {\n return { ...restProviders, openai: restOpenai };\n } else if (hasOtherOpenaiFields) {\n return { openai: restOpenai };\n } else if (hasOtherProviders) {\n return restProviders;\n }\n return undefined;\n }\n\n return meta;\n}\n","import { generateId, type ToolSet, type UIMessageChunk } from 'ai';\nimport type { Experimental_ModelCallStreamPart as ModelCallStreamPart } from 'ai';\n\n/**\n * Convert a single ModelCallStreamPart to a UIMessageChunk.\n * Returns undefined for parts that don't map to UI chunks.\n */\nexport function toUIMessageChunk(\n part: ModelCallStreamPart<ToolSet>,\n): UIMessageChunk | undefined {\n switch (part.type) {\n case 'text-start':\n return {\n type: 'text-start',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'text-delta':\n return {\n type: 'text-delta',\n id: part.id,\n delta: part.text,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'text-end':\n return {\n type: 'text-end',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'reasoning-start':\n return {\n type: 'reasoning-start',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'reasoning-delta':\n return {\n type: 'reasoning-delta',\n id: part.id,\n delta: part.text,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'reasoning-end':\n return {\n type: 'reasoning-end',\n id: part.id,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n\n case 'file': {\n const file = part.file;\n // GeneratedFile.base64 always has data (lazy-converted from Uint8Array if needed)\n return {\n type: 'file',\n mediaType: file.mediaType,\n url: `data:${file.mediaType};base64,${file.base64}`,\n };\n }\n\n case 'source': {\n if (part.sourceType === 'url') {\n return {\n type: 'source-url',\n sourceId: part.id,\n url: part.url,\n title: part.title,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n }\n if (part.sourceType === 'document') {\n return {\n type: 'source-document',\n sourceId: part.id,\n mediaType: part.mediaType,\n title: part.title,\n filename: part.filename,\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n }\n return undefined;\n }\n\n case 'tool-input-start':\n return {\n type: 'tool-input-start',\n toolCallId: part.id,\n toolName: part.toolName,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n };\n\n case 'tool-input-delta':\n return {\n type: 'tool-input-delta',\n toolCallId: part.id,\n inputTextDelta: part.delta,\n };\n\n case 'tool-call': {\n // parseToolCall adds invalid/error at runtime for failed parses\n const toolCallPart = part as typeof part & {\n invalid?: boolean;\n error?: unknown;\n };\n if (toolCallPart.invalid) {\n return {\n type: 'tool-input-error',\n toolCallId: toolCallPart.toolCallId,\n toolName: toolCallPart.toolName,\n input: toolCallPart.input,\n errorText:\n toolCallPart.error instanceof Error\n ? toolCallPart.error.message\n : String(toolCallPart.error ?? 'Invalid tool call'),\n };\n }\n return {\n type: 'tool-input-available',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n ...(part.providerExecuted != null\n ? { providerExecuted: part.providerExecuted }\n : {}),\n ...(part.providerMetadata != null\n ? { providerMetadata: part.providerMetadata }\n : {}),\n };\n }\n\n case 'tool-result':\n return {\n type: 'tool-output-available',\n toolCallId: part.toolCallId,\n output: part.output,\n };\n\n case 'tool-error':\n return {\n type: 'tool-output-error',\n toolCallId: part.toolCallId,\n errorText:\n part.error instanceof Error ? part.error.message : String(part.error),\n };\n\n case 'error': {\n const error = part.error;\n return {\n type: 'error',\n errorText: error instanceof Error ? error.message : String(error),\n };\n }\n\n // These don't produce UI chunks\n case 'tool-input-end':\n case 'model-call-start':\n case 'model-call-response-metadata':\n case 'model-call-end':\n case 'raw':\n return undefined;\n\n default:\n return undefined;\n }\n}\n\n/**\n * Create a TransformStream that converts ModelCallStreamPart to UIMessageChunk.\n * Wraps toUIMessageChunk with start/start-step/finish-step lifecycle chunks.\n */\nexport function createModelCallToUIChunkTransform(): TransformStream<\n ModelCallStreamPart<ToolSet>,\n UIMessageChunk\n> {\n return new TransformStream<ModelCallStreamPart<ToolSet>, UIMessageChunk>({\n start: controller => {\n controller.enqueue({ type: 'start', messageId: generateId() });\n controller.enqueue({ type: 'start-step' });\n },\n flush: controller => {\n controller.enqueue({ type: 'finish-step' });\n controller.enqueue({ type: 'finish' });\n },\n transform: (part, controller) => {\n const uiChunk = toUIMessageChunk(part);\n if (uiChunk) {\n controller.enqueue(uiChunk);\n }\n },\n });\n}\n"],"mappings":";AAQA;AAAA,EAOE;AAAA,OASK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB;;;AC1B/B;AAAA,EAEE,gCAAgC;AAAA,OAU3B;AACP,SAAS,eAAe;;;ACJxB,SAAS,UAAU,kBAAkB;AACrC,SAAS,YAA0B;AACnC,OAAO,SAAS;AAgBT,SAAS,iBACd,OACqC;AACrC,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM;AAAA,MACvC;AAAA,MACA;AAAA,QACE,aAAa,EAAE;AAAA,QACf,aAAa,SAAS,EAAE,WAAW,EAAE;AAAA,MACvC;AAAA,IACF,CAAC;AAAA,EACH;AACF;AASO,SAAS,yBACd,OACS;AACT,QAAM,MAAM,IAAI,IAAI;AAEpB,SAAO,OAAO;AAAA,IACZ,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM;AACvC,YAAM,aAAa,IAAI,QAAQ,EAAE,WAAW;AAE5C,aAAO;AAAA,QACL;AAAA,QACA,KAAK;AAAA,UACH,aAAa,EAAE;AAAA,UACf,aAAa,WAAW,EAAE,aAAa;AAAA,YACrC,UAAU,WAAS;AACjB,kBAAI,WAAW,KAAK,GAAG;AACrB,uBAAO,EAAE,SAAS,MAAM,MAAoB;AAAA,cAC9C;AACA,qBAAO;AAAA,gBACL,SAAS;AAAA,gBACT,OAAO,IAAI,MAAM,IAAI,WAAW,WAAW,MAAM,CAAC;AAAA,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B,QAAQ,KAAK;AAAA,MACf;AAAA,IAEF,KAAK;AACH,aAAO;AAAA,QACL,MAAM;AAAA,QACN,YAAY,KAAK;AAAA,QACjB,WACE,KAAK,iBAAiB,QAAQ,KAAK,MAAM,UAAU,OAAO,KAAK,KAAK;AAAA,MACxE;AAAA,IAEF,KAAK,SAAS;AACZ,YAAM,QAAQ,KAAK;AACnB,aAAO;AAAA,QACL,MAAM;AAAA,QACN,WAAW,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAClE;AAAA,IACF;AAAA;AAAA,IAGA,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IAET;AACE,aAAO;AAAA,EACX;AACF;AAMO,SAAS,oCAGd;AACA,SAAO,IAAI,gBAA8D;AAAA,IACvE,OAAO,gBAAc;AACnB,iBAAW,QAAQ,EAAE,MAAM,SAAS,WAAW,WAAW,EAAE,CAAC;AAC7D,iBAAW,QAAQ,EAAE,MAAM,aAAa,CAAC;AAAA,IAC3C;AAAA,IACA,OAAO,gBAAc;AACnB,iBAAW,QAAQ,EAAE,MAAM,cAAc,CAAC;AAC1C,iBAAW,QAAQ,EAAE,MAAM,SAAS,CAAC;AAAA,IACvC;AAAA,IACA,WAAW,CAAC,MAAM,eAAe;AAC/B,YAAM,UAAU,iBAAiB,IAAI;AACrC,UAAI,SAAS;AACX,mBAAW,QAAQ,OAAO;AAAA,MAC5B;AAAA,IACF;AAAA,EACF,CAAC;AACH;","names":["messages","tool","_a","tool"]}
package/package.json ADDED
@@ -0,0 +1,77 @@
1
+ {
2
+ "name": "@ai-sdk/workflow",
3
+ "version": "0.0.0-bf6e4b15-20260402200305",
4
+ "description": "WorkflowAgent for building AI agents with AI SDK",
5
+ "license": "Apache-2.0",
6
+ "main": "./dist/index.js",
7
+ "module": "./dist/index.mjs",
8
+ "types": "./dist/index.d.ts",
9
+ "source": "./src/index.ts",
10
+ "files": [
11
+ "dist/**/*",
12
+ "src",
13
+ "!src/**/*.test.ts",
14
+ "!src/**/*.test-d.ts",
15
+ "!src/**/__snapshots__",
16
+ "!src/**/__fixtures__",
17
+ "CHANGELOG.md",
18
+ "README.md"
19
+ ],
20
+ "exports": {
21
+ "./package.json": "./package.json",
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.mjs",
25
+ "require": "./dist/index.js"
26
+ }
27
+ },
28
+ "dependencies": {
29
+ "ajv": "^8.18.0",
30
+ "@ai-sdk/provider": "0.0.0-bf6e4b15-20260402200305",
31
+ "@ai-sdk/provider-utils": "0.0.0-bf6e4b15-20260402200305",
32
+ "ai": "0.0.0-bf6e4b15-20260402200305"
33
+ },
34
+ "devDependencies": {
35
+ "@types/node": "20.17.24",
36
+ "@workflow/vitest": "4.0.1-beta.8",
37
+ "tsup": "^8",
38
+ "typescript": "5.8.3",
39
+ "workflow": "4.2.0-beta.71",
40
+ "zod": "3.25.76",
41
+ "@vercel/ai-tsconfig": "0.0.0"
42
+ },
43
+ "peerDependencies": {
44
+ "zod": "^3.25.76 || ^4.1.8"
45
+ },
46
+ "engines": {
47
+ "node": ">=18"
48
+ },
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "homepage": "https://ai-sdk.dev/docs",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/vercel/ai.git"
56
+ },
57
+ "bugs": {
58
+ "url": "https://github.com/vercel/ai/issues"
59
+ },
60
+ "keywords": [
61
+ "ai",
62
+ "agent",
63
+ "workflow"
64
+ ],
65
+ "scripts": {
66
+ "build": "pnpm clean && tsup --tsconfig tsconfig.build.json",
67
+ "build:watch": "pnpm clean && tsup --watch --tsconfig tsconfig.build.json",
68
+ "clean": "del-cli dist *.tsbuildinfo",
69
+ "type-check": "tsc --build",
70
+ "test": "pnpm test:node && pnpm test:edge",
71
+ "test:update": "pnpm test:node -u",
72
+ "test:watch": "vitest --config vitest.node.config.js",
73
+ "test:edge": "vitest --config vitest.edge.config.js --run",
74
+ "test:integration": "vitest --config vitest.integration.config.mjs --run",
75
+ "test:node": "vitest --config vitest.node.config.js --run"
76
+ }
77
+ }