ai 7.0.9 → 7.0.10
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.
- package/CHANGELOG.md +9 -0
- package/dist/index.js +25 -71
- package/dist/index.js.map +1 -1
- package/dist/internal/index.d.ts +1 -3
- package/dist/internal/index.js +17 -63
- package/dist/internal/index.js.map +1 -1
- package/docs/03-ai-sdk-core/16-mcp-tools.mdx +28 -0
- package/docs/03-ai-sdk-harnesses/02-harness-agent.mdx +4 -0
- package/docs/03-ai-sdk-harnesses/03-tools.mdx +49 -0
- package/docs/03-ai-sdk-harnesses/05-harness-adapters.mdx +7 -7
- package/docs/07-reference/01-ai-sdk-core/23-create-mcp-client.mdx +7 -0
- package/docs/08-migration-guides/23-migration-guide-7-0.mdx +19 -0
- package/package.json +3 -3
- package/src/util/prepare-retries.ts +2 -4
- package/src/util/retry-with-exponential-backoff.ts +27 -95
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../internal/index.ts","../../src/util/async-iterable-stream.ts","../../src/prompt/convert-to-language-model-prompt.ts","../../src/util/download/download.ts","../../src/version.ts","../../src/util/download/download-function.ts","../../src/prompt/file-part-data.ts","../../src/prompt/invalid-data-content-error.ts","../../src/prompt/split-data-url.ts","../../src/logger/log-warnings.ts","../../src/prompt/invalid-message-role-error.ts","../../src/error/missing-tool-result-error.ts","../../src/prompt/create-tool-model-output.ts","../../src/prompt/prepare-tool-choice.ts","../../src/prompt/prepare-tools.ts","../../src/util/is-non-empty-object.ts","../../src/prompt/standardize-prompt.ts","../../src/prompt/message.ts","../../src/types/provider-metadata.ts","../../src/types/json-value.ts","../../src/prompt/content-part.ts","../../src/error/invalid-argument-error.ts","../../src/prompt/prepare-language-model-call-options.ts","../../src/util/retry-with-exponential-backoff.ts","../../src/util/retry-error.ts","../../src/util/prepare-retries.ts","../../src/types/usage.ts","../../src/model/resolve-model.ts","../../src/error/index.ts","../../src/error/invalid-tool-approval-error.ts","../../src/error/invalid-tool-approval-signature-error.ts","../../src/error/invalid-tool-input-error.ts","../../src/error/tool-call-not-found-for-approval-error.ts","../../src/error/no-such-tool-error.ts","../../src/error/tool-call-repair-error.ts","../../src/error/unsupported-model-version-error.ts","../../src/util/log-v2-compatibility-warning.ts","../../src/model/as-embedding-model-v3.ts","../../src/model/as-embedding-model-v4.ts","../../src/model/as-image-model-v3.ts","../../src/model/as-image-model-v4.ts","../../src/model/as-language-model-v3.ts","../../src/model/as-language-model-v4.ts","../../src/model/as-reranking-model-v4.ts","../../src/model/as-speech-model-v3.ts","../../src/model/as-speech-model-v4.ts","../../src/model/as-transcription-model-v3.ts","../../src/model/as-transcription-model-v4.ts","../../src/model/as-provider-v3.ts","../../src/model/as-provider-v4.ts","../../src/util/merge-abort-signals.ts","../../src/util/merge-callbacks.ts","../../src/telemetry/create-telemetry-dispatcher.ts","../../src/telemetry/tracing-channel.ts","../../src/util/is-node-runtime.ts","../../src/telemetry/tracing-channel-publisher.ts","../../src/telemetry/telemetry-registry.ts","../../src/generate-text/reasoning.ts","../../src/generate-text/reasoning-output.ts","../../src/generate-text/step-result.ts","../../src/generate-text/restricted-telemetry-dispatcher.ts","../../src/generate-text/parse-tool-call.ts","../../src/generate-text/collect-tool-approvals.ts","../../src/generate-text/validate-tool-approvals.ts","../../src/generate-text/validate-tool-context.ts","../../src/generate-text/resolve-tool-approval.ts","../../src/generate-text/tool-approval-signature.ts","../../src/generate-text/to-response-messages.ts"],"sourcesContent":["// import globals\nimport '../src/global';\n\n// internal re-exports\nexport { convertAsyncIteratorToReadableStream } from '@ai-sdk/provider-utils';\n\n// internal\nexport { createAsyncIterableStream } from '../src/util/async-iterable-stream';\nexport {\n convertToLanguageModelPrompt,\n downloadAssets,\n mapToolResultOutput,\n} from '../src/prompt/convert-to-language-model-prompt';\nexport { createToolModelOutput } from '../src/prompt/create-tool-model-output';\nexport {\n createDefaultDownloadFunction,\n type DownloadFunction,\n} from '../src/util/download/download-function';\nexport { prepareToolChoice } from '../src/prompt/prepare-tool-choice';\nexport { prepareTools } from '../src/prompt/prepare-tools';\nexport { standardizePrompt } from '../src/prompt/standardize-prompt';\nexport {\n prepareLanguageModelCallOptions,\n /** @deprecated Use `prepareLanguageModelCallOptions` instead. */\n prepareLanguageModelCallOptions as prepareCallSettings,\n} from '../src/prompt/prepare-language-model-call-options';\nexport { prepareRetries } from '../src/util/prepare-retries';\nexport {\n addLanguageModelUsage,\n asLanguageModelUsage,\n createNullLanguageModelUsage,\n} from '../src/types/usage';\nexport { resolveLanguageModel } from '../src/model/resolve-model';\nexport { mergeAbortSignals } from '../src/util/merge-abort-signals';\nexport { mergeCallbacks } from '../src/util/merge-callbacks';\nexport { createTelemetryDispatcher } from '../src/telemetry/create-telemetry-dispatcher';\nexport { createRestrictedTelemetryDispatcher } from '../src/generate-text/restricted-telemetry-dispatcher';\nexport { DefaultStepResult } from '../src/generate-text/step-result';\nexport { parseToolCall } from '../src/generate-text/parse-tool-call';\nexport {\n collectToolApprovals,\n type CollectedToolApprovals,\n} from '../src/generate-text/collect-tool-approvals';\nexport { validateApprovedToolApprovals } from '../src/generate-text/validate-tool-approvals';\nexport { toResponseMessages } from '../src/generate-text/to-response-messages';\n","/**\n * A type that combines AsyncIterable and ReadableStream.\n * This allows a ReadableStream to be consumed using for-await-of syntax.\n */\nexport type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;\n\n/**\n * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.\n * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.\n *\n * @template T The type of the stream's chunks.\n * @param source The source ReadableStream to wrap.\n * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.\n */\nexport function createAsyncIterableStream<T>(\n source: ReadableStream<T>,\n): AsyncIterableStream<T> {\n // Pipe through a TransformStream to ensure a fresh, unlocked stream.\n const stream = source.pipeThrough(new TransformStream<T, T>());\n\n /**\n * Implements the async iterator protocol for the stream.\n * Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.\n */\n (stream as AsyncIterableStream<T>)[Symbol.asyncIterator] = function (\n this: ReadableStream<T>,\n ): AsyncIterator<T> {\n const reader = this.getReader();\n\n let finished = false;\n\n /**\n * Cleans up the reader by cancelling and releasing the lock.\n */\n async function cleanup(cancelStream: boolean) {\n if (finished) return;\n\n finished = true;\n try {\n if (cancelStream) {\n await reader.cancel?.();\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {}\n }\n }\n\n return {\n /**\n * Reads the next chunk from the stream.\n * @returns A promise resolving to the next IteratorResult.\n */\n async next(): Promise<IteratorResult<T>> {\n if (finished) {\n return { done: true, value: undefined };\n }\n\n const { done, value } = await reader.read();\n\n if (done) {\n await cleanup(true);\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n },\n\n /**\n * May be called on early exit (e.g., break from for-await) or after completion.\n * Ensures the stream is cancelled and resources are released.\n * @returns A promise resolving to a completed IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n await cleanup(true);\n return { done: true, value: undefined };\n },\n\n /**\n * Called on early exit with error.\n * Ensures the stream is cancelled and resources are released, then rethrows the error.\n * @param err The error to throw.\n * @returns A promise that rejects with the provided error.\n */\n async throw(err: unknown): Promise<IteratorResult<T>> {\n await cleanup(true);\n throw err;\n },\n };\n };\n\n return stream as AsyncIterableStream<T>;\n}\n","import type {\n LanguageModelV4FilePart,\n LanguageModelV4Message,\n LanguageModelV4Prompt,\n LanguageModelV4TextPart,\n LanguageModelV4ToolResultOutput,\n} from '@ai-sdk/provider';\nimport {\n asArray,\n detectMediaType,\n isFullMediaType,\n isUrlSupported,\n type CustomPart,\n type FilePart,\n type ImagePart,\n type ModelMessage,\n type ReasoningFilePart,\n type ReasoningPart,\n type TextPart,\n type ToolCallPart,\n type ToolResultOutput,\n type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport {\n createDefaultDownloadFunction,\n type DownloadFunction,\n} from '../util/download/download-function';\nimport { convertToLanguageModelV4FilePart } from './file-part-data';\nimport { logWarnings } from '../logger/log-warnings';\nimport type { Warning } from '../types/warning';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport type { StandardizedPrompt } from './standardize-prompt';\nimport { MissingToolResultsError } from '../error/missing-tool-result-error';\n\nexport async function convertToLanguageModelPrompt({\n prompt,\n supportedUrls,\n download = createDefaultDownloadFunction(),\n // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n}: {\n prompt: StandardizedPrompt;\n supportedUrls: Record<string, RegExp[]>;\n download: DownloadFunction | undefined;\n provider?: string;\n}): Promise<LanguageModelV4Prompt> {\n const downloadedAssets = await downloadAssets(\n prompt.messages,\n download,\n supportedUrls,\n );\n\n const approvalIdToToolCallId = new Map<string, string>();\n for (const message of prompt.messages) {\n if (message.role === 'assistant' && Array.isArray(message.content)) {\n for (const part of message.content) {\n if (\n part.type === 'tool-approval-request' &&\n 'approvalId' in part &&\n 'toolCallId' in part\n ) {\n approvalIdToToolCallId.set(\n part.approvalId as string,\n part.toolCallId as string,\n );\n }\n }\n }\n }\n\n const approvedToolCallIds = new Set<string>();\n for (const message of prompt.messages) {\n if (message.role === 'tool') {\n for (const part of message.content) {\n if (part.type === 'tool-approval-response') {\n const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n if (toolCallId) {\n approvedToolCallIds.add(toolCallId);\n }\n }\n }\n }\n }\n\n const messages = [\n ...(prompt.instructions != null\n ? typeof prompt.instructions === 'string'\n ? [{ role: 'system' as const, content: prompt.instructions }]\n : asArray(prompt.instructions).map(message => ({\n role: 'system' as const,\n content: message.content,\n providerOptions: message.providerOptions,\n }))\n : []),\n ...prompt.messages.map(message =>\n convertToLanguageModelMessage({ message, downloadedAssets, provider }),\n ),\n ];\n\n // combine consecutive tool messages into a single tool message\n const combinedMessages = [];\n for (const message of messages) {\n if (message.role !== 'tool') {\n combinedMessages.push(message);\n continue;\n }\n\n const lastCombinedMessage = combinedMessages.at(-1);\n if (lastCombinedMessage?.role === 'tool') {\n lastCombinedMessage.content.push(...message.content);\n } else {\n combinedMessages.push(message);\n }\n }\n\n const toolCallIds = new Set<string>();\n\n for (const message of combinedMessages) {\n switch (message.role) {\n case 'assistant': {\n for (const content of message.content) {\n if (content.type === 'tool-call' && !content.providerExecuted) {\n toolCallIds.add(content.toolCallId);\n }\n }\n break;\n }\n case 'tool': {\n for (const content of message.content) {\n if (content.type === 'tool-result') {\n toolCallIds.delete(content.toolCallId);\n }\n }\n break;\n }\n case 'user':\n case 'system':\n // remove approved tool calls from the set before checking:\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({\n toolCallIds: Array.from(toolCallIds),\n });\n }\n break;\n }\n }\n\n // remove approved tool calls from the set before checking:\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n }\n\n return combinedMessages.filter(\n // Filter out empty tool messages (e.g. if they only contained\n // tool-approval-response parts that were removed).\n // This prevents sending invalid empty messages to the provider.\n // Note: provider-executed tool-approval-response parts are preserved.\n message => message.role !== 'tool' || message.content.length > 0,\n );\n}\n\n/**\n * Convert a ModelMessage to a LanguageModelV4Message.\n *\n * @param message - The ModelMessage to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage({\n message,\n downloadedAssets,\n // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n}: {\n message: ModelMessage;\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >;\n provider?: string;\n}): LanguageModelV4Message {\n const warnings: Warning[] = [];\n\n const role = message.role;\n switch (role) {\n case 'system': {\n return {\n role: 'system',\n content: message.content,\n providerOptions: message.providerOptions,\n };\n }\n\n case 'user': {\n if (typeof message.content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: message.content }],\n providerOptions: message.providerOptions,\n };\n }\n\n const converted = {\n role: 'user' as const,\n content: message.content\n .map(part => {\n if (part.type === 'image') {\n warnings.push({\n type: 'deprecated',\n setting: '\"image\" content part',\n message: `The \"image\" content part type is deprecated. Use a \"file\" part with mediaType: 'image' (or a more specific image/* subtype) instead.`,\n });\n }\n return convertImagePartToFilePart(part);\n })\n .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n // remove empty text parts:\n .filter(part => part.type !== 'text' || part.text !== ''),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n case 'assistant': {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n providerOptions: message.providerOptions,\n };\n }\n\n const converted = {\n role: 'assistant' as const,\n content: message.content\n .filter(\n // remove empty text parts (no text, and no provider options):\n part =>\n part.type !== 'text' ||\n part.text !== '' ||\n part.providerOptions != null,\n )\n .filter(\n (\n part,\n ): part is\n | CustomPart\n | TextPart\n | FilePart\n | ReasoningPart\n | ReasoningFilePart\n | ToolCallPart\n | ToolResultPart => part.type !== 'tool-approval-request',\n )\n .map(part => {\n const providerOptions = part.providerOptions;\n\n switch (part.type) {\n case 'custom': {\n return {\n type: 'custom' as const,\n kind: part.kind,\n providerOptions,\n };\n }\n case 'file': {\n const { data, mediaType } = convertToLanguageModelV4FilePart(\n part.data,\n );\n return {\n type: 'file' as const,\n data,\n filename: part.filename,\n mediaType: mediaType ?? part.mediaType,\n providerOptions,\n };\n }\n case 'reasoning': {\n return {\n type: 'reasoning' as const,\n text: part.text,\n providerOptions,\n };\n }\n case 'reasoning-file': {\n const { data, mediaType } = convertToLanguageModelV4FilePart(\n part.data,\n );\n if (data.type !== 'data' && data.type !== 'url') {\n throw new Error(\n `Unsupported reasoning-file data type: ${data.type}`,\n );\n }\n return {\n type: 'reasoning-file' as const,\n data,\n mediaType: mediaType ?? part.mediaType,\n providerOptions,\n };\n }\n case 'text': {\n return {\n type: 'text' as const,\n text: part.text,\n providerOptions,\n };\n }\n case 'tool-call': {\n return {\n type: 'tool-call' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n providerExecuted: part.providerExecuted,\n providerOptions,\n };\n }\n case 'tool-result': {\n return {\n type: 'tool-result' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput({\n output: part.output,\n provider,\n warnings,\n downloadedAssets,\n }),\n providerOptions,\n };\n }\n }\n }),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n case 'tool': {\n const converted = {\n role: 'tool' as const,\n content: message.content\n .filter(\n // Only include tool-approval-response for provider-executed tools\n part =>\n part.type !== 'tool-approval-response' || part.providerExecuted,\n )\n .map(part => {\n switch (part.type) {\n case 'tool-result': {\n return {\n type: 'tool-result' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput({\n output: part.output,\n provider,\n warnings,\n downloadedAssets,\n }),\n providerOptions: part.providerOptions,\n };\n }\n case 'tool-approval-response': {\n return {\n type: 'tool-approval-response' as const,\n approvalId: part.approvalId,\n approved: part.approved,\n reason: part.reason,\n };\n }\n }\n }),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n }\n }\n}\n\n/*\n * Rewrites a legacy `ImagePart` into an equivalent `FilePart`. The default\n * `mediaType` for a bare `ImagePart` (no `mediaType`) is `\"image\"` (top-level\n * segment); an explicit `mediaType` is carried through verbatim. After this\n * pre-pass, only `TextPart` and `FilePart` ever reach the provider-facing\n * conversion logic.\n */\nfunction convertImagePartToFilePart(\n part: TextPart | ImagePart | FilePart,\n): TextPart | FilePart {\n if (part.type !== 'image') {\n return part;\n }\n return {\n type: 'file',\n data: part.image,\n mediaType: part.mediaType ?? 'image',\n providerOptions: part.providerOptions,\n };\n}\n\n/**\n * Downloads files from URLs in the user messages.\n */\nexport async function downloadAssets(\n messages: ModelMessage[],\n download: DownloadFunction,\n supportedUrls: Record<string, RegExp[]>,\n): Promise<\n Record<string, { mediaType: string | undefined; data: Uint8Array }>\n> {\n type ConvertedFile = {\n mediaType: string | undefined;\n data: LanguageModelV4FilePart['data'];\n };\n type UrlTaggedFile = {\n mediaType: string | undefined;\n data: { type: 'url'; url: URL };\n };\n\n const downloadableFiles: FilePart[] = [];\n\n for (const message of messages) {\n if (message.role === 'user' && Array.isArray(message.content)) {\n for (const part of message.content) {\n const filePart = convertImagePartToFilePart(part);\n\n if (filePart.type === 'file') {\n downloadableFiles.push(filePart);\n }\n }\n }\n\n if (message.role === 'tool') {\n for (const part of message.content) {\n if (part.type !== 'tool-result') {\n continue;\n }\n\n if (part.output.type !== 'content') {\n continue;\n }\n\n for (const contentPart of part.output.value) {\n if (contentPart.type === 'file') {\n downloadableFiles.push(contentPart);\n }\n }\n }\n }\n\n if (message.role === 'assistant' && Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type !== 'tool-result') {\n continue;\n }\n if (part.output.type !== 'content') {\n continue;\n }\n for (const contentPart of part.output.value) {\n if (contentPart.type === 'file') {\n downloadableFiles.push(contentPart);\n }\n }\n }\n }\n }\n\n const plannedDownloads = downloadableFiles\n .map((part): ConvertedFile => {\n const mediaType = part.mediaType;\n const { data } = convertToLanguageModelV4FilePart(part.data);\n return { mediaType, data };\n })\n .filter((part): part is UrlTaggedFile => part.data.type === 'url')\n .map(part => ({\n url: part.data.url,\n isUrlSupportedByModel:\n part.mediaType != null &&\n isUrlSupported({\n url: part.data.url.toString(),\n mediaType: part.mediaType,\n supportedUrls,\n }),\n }));\n // download in parallel:\n const downloadedFiles = await download(plannedDownloads);\n\n return Object.fromEntries(\n downloadedFiles\n .map((file, index) =>\n file == null\n ? null\n : [\n plannedDownloads[index].url.toString(),\n { data: file.data, mediaType: file.mediaType },\n ],\n )\n .filter(file => file != null),\n );\n}\n\n/**\n * Convert part of a user message to a LanguageModelV4Part.\n *\n * @param part - The part to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n part: TextPart | FilePart,\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >,\n): LanguageModelV4TextPart | LanguageModelV4FilePart {\n if (part.type === 'text') {\n return {\n type: 'text',\n text: part.text,\n providerOptions: part.providerOptions,\n };\n }\n\n const { data: normalizedData, mediaType: dataUrlMediaType } =\n convertToLanguageModelV4FilePart(part.data);\n\n let mediaType: string | undefined = dataUrlMediaType ?? part.mediaType;\n let data: LanguageModelV4FilePart['data'] = normalizedData;\n\n if (data.type === 'url') {\n const downloadedFile = downloadedAssets[data.url.toString()];\n if (downloadedFile) {\n data = { type: 'data', data: downloadedFile.data };\n if (\n downloadedFile.mediaType != null &&\n (mediaType == null || !isFullMediaType(mediaType))\n ) {\n mediaType = downloadedFile.mediaType;\n }\n }\n }\n\n if (\n data.type === 'data' &&\n (data.data instanceof Uint8Array || typeof data.data === 'string')\n ) {\n const imageMediaType = detectMediaType({\n data: data.data,\n topLevelType: 'image',\n });\n if (imageMediaType != null) {\n mediaType = imageMediaType;\n }\n }\n\n if (mediaType == null) {\n throw new Error(`Media type is missing for file part`);\n }\n\n return {\n type: 'file',\n mediaType,\n filename: part.filename,\n data,\n providerOptions: part.providerOptions,\n };\n}\n\nexport function mapToolResultOutput({\n output,\n // `provider` is only needed here to convert legacy \"file-id\" and \"image-file-id\" types to provider references, in case they are using string ID values.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n warnings = [],\n downloadedAssets,\n}: {\n output: ToolResultOutput;\n provider?: string;\n warnings?: Warning[];\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >;\n}): LanguageModelV4ToolResultOutput {\n if (output.type !== 'content') {\n return output;\n }\n\n return {\n type: 'content',\n value: output.value.map(item => {\n switch (item.type) {\n case 'file': {\n const convertedPart = convertPartToLanguageModelPart(\n item,\n downloadedAssets,\n );\n\n if (convertedPart.type !== 'file') {\n throw new Error(\n 'Expected tool result file content to convert to file.',\n );\n }\n\n return convertedPart;\n }\n case 'file-data': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-data\"',\n message: `The \"file-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'data' as const, data: item.data },\n filename: item.filename,\n mediaType: item.mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'file-url': {\n const mediaType = item.mediaType ?? getMediaTypeFromUrl(item.url);\n let message = `The \"file-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'url', url } instead.`;\n if (!item.mediaType) {\n const inferenceSuffix =\n mediaType === 'application/octet-stream'\n ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.`\n : `Inferred media type '${mediaType}' from URL.`;\n message = `The \"file-url\" tool result content part with URL \"${item.url}\" is missing a \"mediaType\". ${inferenceSuffix} ${message}`;\n }\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-url\"',\n message,\n });\n return {\n type: 'file' as const,\n data: { type: 'url' as const, url: new URL(item.url) },\n mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'file-id': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-id\"',\n message: `The \"file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: convertFileIdToProviderReference({\n fileId: item.fileId,\n provider,\n }),\n },\n mediaType: 'application',\n providerOptions: item.providerOptions,\n };\n }\n case 'file-reference': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-reference\"',\n message: `The \"file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: item.providerReference,\n },\n mediaType: 'application',\n providerOptions: item.providerOptions,\n };\n }\n // The \"image-*\" types are legacy and deprecated.\n // TODO: remove migration in v8 in combination with the removal of these types from the provider utils.\n case 'image-data': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-data\"',\n message: `The \"image-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'data' as const, data: item.data },\n mediaType: item.mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'image-url': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-url\"',\n message: `The \"image-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'url' as const, url: new URL(item.url) },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n case 'image-file-id': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-file-id\"',\n message: `The \"image-file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: convertFileIdToProviderReference({\n fileId: item.fileId,\n provider,\n }),\n },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n case 'image-file-reference': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-file-reference\"',\n message: `The \"image-file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: item.providerReference,\n },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n default:\n return item;\n }\n }),\n };\n}\n\nfunction convertFileIdToProviderReference({\n fileId,\n provider,\n}: {\n fileId: string | Record<string, string>;\n provider?: string;\n}): Record<string, string> {\n if (typeof fileId === 'object') {\n return fileId;\n }\n\n if (provider == null) {\n throw new Error(\n 'Cannot convert string fileId to provider reference without a provider ID. ' +\n 'Use a Record<string, string> fileId or switch to the file-reference type.',\n );\n }\n\n return { [provider]: fileId };\n}\n\n// Temporary private helper (see below).\nconst URL_EXTENSION_TO_MEDIA_TYPE: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n avif: 'image/avif',\n heic: 'image/heic',\n bmp: 'image/bmp',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n pdf: 'application/pdf',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n};\n\n/*\n * Attempts to infer an IANA media type from the file extension in a URL's\n * pathname. Returns `fallbackMediaType` when the extension is absent,\n * unrecognized, or the URL cannot be parsed.\n *\n * Temporary private helper as a best-effort solution for missing media types on \"file-url\" content parts.\n */\nfunction getMediaTypeFromUrl(\n url: string,\n fallbackMediaType = 'application/octet-stream',\n): string {\n try {\n const pathname = new URL(url).pathname;\n const fileExtension = pathname.split('.').pop()?.toLowerCase();\n if (\n fileExtension &&\n Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)\n ) {\n return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];\n }\n } catch {\n // ignore URL parse errors\n }\n return fallbackMediaType;\n}\n","import {\n cancelResponseBody,\n DownloadError,\n readResponseWithSizeLimit,\n DEFAULT_MAX_DOWNLOAD_SIZE,\n fetchWithValidatedRedirects,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../../version';\n\n/**\n * Download a file from a URL.\n *\n * @param url - The URL to download from.\n * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param abortSignal - An optional abort signal to cancel the download.\n * @returns The downloaded data and media type.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport const download = async ({\n url,\n maxBytes,\n abortSignal,\n}: {\n url: URL;\n maxBytes?: number;\n abortSignal?: AbortSignal;\n}) => {\n const urlText = url.toString();\n try {\n const headers = withUserAgentSuffix(\n {},\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const response = await fetchWithValidatedRedirects({\n url: urlText,\n headers,\n abortSignal,\n });\n\n if (!response.ok) {\n // Release the connection before rejecting so an error status from an\n // attacker-controlled origin cannot leak open sockets.\n await cancelResponseBody(response);\n throw new DownloadError({\n url: urlText,\n statusCode: response.status,\n statusText: response.statusText,\n });\n }\n\n const data = await readResponseWithSizeLimit({\n response,\n url: urlText,\n maxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n });\n\n return {\n data,\n mediaType: response.headers.get('content-type') ?? undefined,\n };\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n\n throw new DownloadError({ url: urlText, cause: error });\n }\n};\n","declare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { download as originalDownload } from './download';\n\n/**\n * Experimental. Can change in patch versions without warning.\n *\n * Download function. Called with the array of URLs and a boolean indicating\n * whether the URL is supported by the model.\n *\n * The download function can decide for each URL:\n * - to return null (which means that the URL should be passed to the model)\n * - to download the asset and return the data (incl. retries, authentication, etc.)\n *\n * Should throw DownloadError if the download fails.\n *\n * Should return an array of objects sorted by the order of the requested downloads.\n * For each object, the data should be a Uint8Array if the URL was downloaded.\n * For each object, the mediaType should be the media type of the downloaded asset.\n * For each object, the data should be null if the URL should be passed through as is.\n */\nexport type DownloadFunction = (\n options: Array<{\n url: URL;\n isUrlSupportedByModel: boolean;\n }>,\n) => PromiseLike<\n Array<{\n data: Uint8Array;\n mediaType: string | undefined;\n } | null>\n>;\n\n/**\n * Default download function.\n * Downloads the file if it is not supported by the model.\n */\nexport const createDefaultDownloadFunction =\n (download: typeof originalDownload = originalDownload): DownloadFunction =>\n requestedDownloads =>\n Promise.all(\n requestedDownloads.map(async requestedDownload =>\n requestedDownload.isUrlSupportedByModel\n ? null\n : await download(requestedDownload),\n ),\n );\n","import type { LanguageModelV4FilePart } from '@ai-sdk/provider';\nimport {\n isBuffer,\n isProviderReference,\n type DataContent,\n type FilePart,\n type ProviderReference,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { splitDataUrl } from './split-data-url';\n\ntype TaggedFileData = Extract<FilePart['data'], { type: string }>;\n\nfunction isTaggedFileData(value: unknown): value is TaggedFileData {\n if (typeof value !== 'object' || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === 'data' || type === 'url' || type === 'reference' || type === 'text'\n );\n}\n\ntype ConvertResult = {\n data: LanguageModelV4FilePart['data'];\n mediaType: string | undefined;\n};\n\nfunction convertUrlToFilePartData(url: URL): ConvertResult {\n if (url.protocol === 'data:') {\n const { mediaType, base64Content } = splitDataUrl(url.toString());\n\n if (mediaType == null || base64Content == null) {\n throw new InvalidDataContentError({\n content: url,\n message: `Invalid data URL format in content ${url.toString()}`,\n });\n }\n\n return { data: { type: 'data', data: base64Content }, mediaType };\n }\n\n return { data: { type: 'url', url }, mediaType: undefined };\n}\n\nfunction convertInlineDataToFilePartData(content: DataContent): ConvertResult {\n if (content instanceof Uint8Array) {\n return { data: { type: 'data', data: content }, mediaType: undefined };\n }\n if (content instanceof ArrayBuffer) {\n return {\n data: { type: 'data', data: new Uint8Array(content) },\n mediaType: undefined,\n };\n }\n if (isBuffer(content)) {\n return {\n data: { type: 'data', data: new Uint8Array(content) },\n mediaType: undefined,\n };\n }\n return {\n data: { type: 'data', data: content as string },\n mediaType: undefined,\n };\n}\n\n/**\n * Converts any legacy-or-tagged top-level `FilePart.data` /\n * `ReasoningFilePart.data` value into the tagged v4 provider prompt shape.\n *\n * Returns the tagged `data` together with the resolved mediaType (extracted\n * from a `data:` URL when applicable).\n */\nexport function convertToLanguageModelV4FilePart(\n content: FilePart['data'],\n): ConvertResult {\n if (isTaggedFileData(content)) {\n switch (content.type) {\n case 'data':\n if (\n typeof content.data === 'string' &&\n content.data.startsWith('data:')\n ) {\n throw new InvalidDataContentError({\n content: content.data,\n message:\n 'Data URLs are not valid inline data. Pass them as { type: \"url\", url } instead.',\n });\n }\n return convertInlineDataToFilePartData(content.data);\n case 'url':\n return convertUrlToFilePartData(content.url);\n case 'reference':\n return {\n data: { type: 'reference', reference: content.reference },\n mediaType: undefined,\n };\n case 'text':\n return {\n data: { type: 'text', text: content.text },\n mediaType: undefined,\n };\n }\n }\n\n if (content instanceof URL) {\n return convertUrlToFilePartData(content);\n }\n\n if (typeof content === 'string') {\n try {\n return convertUrlToFilePartData(new URL(content));\n } catch {\n return convertInlineDataToFilePartData(content);\n }\n }\n\n if (isProviderReference(content)) {\n return {\n data: { type: 'reference', reference: content as ProviderReference },\n mediaType: undefined,\n };\n }\n\n return convertInlineDataToFilePartData(content as DataContent);\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly content: unknown;\n\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n }: {\n content: unknown;\n cause?: unknown;\n message?: string;\n }) {\n super({ name, message, cause });\n\n this.content = content;\n }\n\n static isInstance(error: unknown): error is InvalidDataContentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function splitDataUrl(dataUrl: string): {\n mediaType: string | undefined;\n base64Content: string | undefined;\n} {\n try {\n const [header, base64Content] = dataUrl.split(',');\n return {\n mediaType: header.split(';')[0].split(':')[1],\n base64Content,\n };\n } catch {\n return {\n mediaType: undefined,\n base64Content: undefined,\n };\n }\n}\n","import type { Warning } from '../types';\n\n/**\n * A function for logging warnings.\n *\n * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger.\n *\n * @example\n * ```ts\n * globalThis.AI_SDK_LOG_WARNINGS = (options) => {\n * console.log('WARNINGS:', options.warnings, options.provider, options.model);\n * };\n * ```\n */\nexport type LogWarningsFunction = (options: {\n /**\n * The warnings returned by the model provider.\n */\n warnings: Warning[];\n\n /**\n * The provider id used for the call, if scoped to a specific provider.\n */\n provider?: string;\n\n /**\n * The model id used for the call, if scoped to a specific provider.\n */\n model?: string;\n}) => void;\n\n/**\n * Formats a warning object into a human-readable string with clear AI SDK branding.\n *\n * @param options - The options for formatting the warning.\n * @param options.warning - The warning to format.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n * @returns A formatted warning message string.\n */\nfunction formatWarning({\n warning,\n provider,\n model,\n}: {\n warning: Warning;\n provider?: string;\n model?: string;\n}): string {\n const scope =\n provider != null && model != null ? ` (${provider} / ${model})` : '';\n const prefix = `AI SDK Warning${scope}:`;\n\n switch (warning.type) {\n case 'unsupported': {\n let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n\n case 'compatibility': {\n let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n\n case 'deprecated': {\n return `${prefix} Deprecated: \"${warning.setting}\". ${warning.message}`;\n }\n\n case 'other': {\n return `${prefix} ${warning.message}`;\n }\n\n default: {\n // Fallback for any unknown warning types\n return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n }\n }\n}\n\nexport const FIRST_WARNING_INFO_MESSAGE =\n 'AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.';\n\nlet hasLoggedBefore = false;\n\n/**\n * Logs warnings to the console or uses a custom logger if configured.\n *\n * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:\n * - If set to `false`, warnings are suppressed.\n * - If set to a function, that function is called with the warnings.\n * - Otherwise, warnings are logged to the console using `console.warn`.\n *\n * @param options - The options containing warnings and context.\n * @param options.warnings - The warnings to log.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n */\nexport const logWarnings: LogWarningsFunction = options => {\n // if the warnings array is empty, do nothing\n if (options.warnings.length === 0) {\n return;\n }\n\n const logger = globalThis.AI_SDK_LOG_WARNINGS;\n\n // if the logger is set to false, do nothing\n if (logger === false) {\n return;\n }\n\n // use the provided logger if it is a function\n if (typeof logger === 'function') {\n logger(options);\n return;\n }\n\n // display information note on first call\n if (!hasLoggedBefore) {\n hasLoggedBefore = true;\n console.info(FIRST_WARNING_INFO_MESSAGE);\n }\n\n // default behavior: log warnings via process.emitWarning if available, otherwise console.warn\n for (const warning of options.warnings) {\n const message = formatWarning({\n warning,\n provider: options.provider,\n model: options.model,\n });\n if (\n typeof process !== 'undefined' &&\n typeof process.emitWarning === 'function'\n ) {\n process.emitWarning(message, {\n type: warning.type === 'deprecated' ? 'DeprecationWarning' : 'Warning',\n });\n } else {\n console.warn(message);\n }\n }\n};\n\n/**\n * Resets the internal logging state. Used for testing purposes.\n */\nexport const resetLogWarningsState = () => {\n hasLoggedBefore = false;\n};\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly role: string;\n\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n }: {\n role: string;\n message?: string;\n }) {\n super({ name, message });\n\n this.role = role;\n }\n\n static isInstance(error: unknown): error is InvalidMessageRoleError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MissingToolResultsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MissingToolResultsError extends AISDKError {\n private readonly [symbol] = true;\n\n readonly toolCallIds: string[];\n\n constructor({ toolCallIds }: { toolCallIds: string[] }) {\n super({\n name,\n message: `Tool result${\n toolCallIds.length > 1 ? 's are' : ' is'\n } missing for tool call${toolCallIds.length > 1 ? 's' : ''} ${toolCallIds.join(\n ', ',\n )}.`,\n });\n\n this.toolCallIds = toolCallIds;\n }\n\n static isInstance(error: unknown): error is MissingToolResultsError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { getErrorMessage, type JSONValue } from '@ai-sdk/provider';\nimport type { Tool, ToolResultOutput } from '@ai-sdk/provider-utils';\n\nexport async function createToolModelOutput({\n toolCallId,\n input,\n output,\n tool,\n errorMode,\n}: {\n toolCallId: string;\n input: unknown;\n output: unknown;\n tool: Tool | undefined;\n errorMode: 'none' | 'text' | 'json';\n}): Promise<ToolResultOutput> {\n if (errorMode === 'text') {\n return { type: 'error-text', value: getErrorMessage(output) };\n } else if (errorMode === 'json') {\n return { type: 'error-json', value: toJSONValue(output) };\n }\n\n if (tool?.toModelOutput) {\n return await tool.toModelOutput({ toolCallId, input, output });\n }\n\n return typeof output === 'string'\n ? { type: 'text', value: output }\n : { type: 'json', value: toJSONValue(output) };\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n return value === undefined ? null : (value as JSONValue);\n}\n","import type { LanguageModelV4ToolChoice } from '@ai-sdk/provider';\nimport type { ToolChoice } from '../types/language-model';\n\nexport function prepareToolChoice({\n toolChoice,\n}: {\n // use of any because it doesn't matter for tool choice preparation\n toolChoice: ToolChoice<any> | undefined;\n}): LanguageModelV4ToolChoice {\n return toolChoice == null\n ? { type: 'auto' }\n : typeof toolChoice === 'string'\n ? { type: toolChoice }\n : { type: 'tool' as const, toolName: toolChoice.toolName as string };\n}\n","import type {\n LanguageModelV4FunctionTool,\n LanguageModelV4ProviderTool,\n} from '@ai-sdk/provider';\nimport {\n asSchema,\n type Experimental_SandboxSession as SandboxSession,\n type InferToolSetContext,\n type Tool,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ToolOrder } from '../generate-text/tool-order';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\n\nexport async function prepareTools<TOOLS extends ToolSet>({\n tools,\n toolOrder,\n toolsContext = {} as InferToolSetContext<TOOLS>,\n experimental_sandbox: sandbox,\n}: {\n tools: TOOLS | undefined;\n toolOrder?: ToolOrder<TOOLS>;\n toolsContext?: InferToolSetContext<TOOLS>;\n experimental_sandbox?: SandboxSession;\n}): Promise<\n Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool> | undefined\n> {\n if (!isNonEmptyObject(tools)) {\n return undefined;\n }\n\n const languageModelTools: Array<\n LanguageModelV4FunctionTool | LanguageModelV4ProviderTool\n > = [];\n for (const [name, tool] of orderToolEntries({ tools, toolOrder })) {\n const toolType = tool.type;\n\n switch (toolType) {\n case undefined:\n case 'dynamic':\n case 'function': {\n const description = resolveToolDescription({\n tool,\n toolName: name,\n toolsContext,\n experimental_sandbox: sandbox,\n });\n const providerOptions = tool.providerOptions;\n const inputExamples = tool.inputExamples;\n const strict = tool.strict;\n\n languageModelTools.push({\n type: 'function' as const,\n name,\n inputSchema: await asSchema(tool.inputSchema).jsonSchema,\n ...(description != null ? { description } : {}),\n ...(inputExamples != null ? { inputExamples } : {}),\n ...(providerOptions != null ? { providerOptions } : {}),\n ...(strict != null ? { strict } : {}),\n });\n break;\n }\n case 'provider': {\n languageModelTools.push({\n type: 'provider' as const,\n name,\n id: tool.id,\n args: tool.args,\n });\n break;\n }\n default: {\n const exhaustiveCheck: never = toolType as never;\n throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n }\n }\n }\n\n return languageModelTools;\n}\n\nfunction orderToolEntries<TOOLS extends ToolSet>({\n tools,\n toolOrder,\n}: {\n tools: TOOLS;\n toolOrder?: ToolOrder<TOOLS>;\n}): Array<[string, Tool]> {\n if (toolOrder == null) {\n return Object.entries(tools);\n }\n\n const toolEntries = Object.entries(tools);\n\n const orderedTools = toolEntries\n .filter(([name]) => toolOrder.includes(name))\n .sort(\n ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB),\n );\n\n const unorderedTools = toolEntries\n .filter(([name]) => !toolOrder.includes(name))\n .sort(([nameA], [nameB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : 0));\n\n return [...orderedTools, ...unorderedTools];\n}\n\nfunction resolveToolDescription<TOOLS extends ToolSet>({\n tool,\n toolName,\n toolsContext,\n experimental_sandbox: sandbox,\n}: {\n tool: Tool;\n toolName: string;\n toolsContext: InferToolSetContext<TOOLS>;\n experimental_sandbox?: SandboxSession;\n}): string | undefined {\n return tool.description === undefined\n ? undefined\n : typeof tool.description === 'string'\n ? tool.description\n : tool.description({\n context: toolsContext[toolName as keyof InferToolSetContext<TOOLS>],\n experimental_sandbox: sandbox,\n });\n}\n","export function isNonEmptyObject(\n object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n return object != null && Object.keys(object).length > 0;\n}\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport {\n asArray,\n safeValidateTypes,\n type ModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { modelMessageSchema } from './message';\nimport type { Instructions, Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n /**\n * Instructions.\n */\n instructions: Instructions | undefined;\n\n /**\n * Messages.\n */\n messages: ModelMessage[];\n};\n\n/**\n * Converts a prompt input into a standardized prompt with validated model\n * messages.\n *\n * @param prompt - The prompt definition to standardize.\n * Set `allowSystemInMessages` to true to allow system messages in the\n * `prompt` or `messages` fields. System messages in the `instructions`\n * option are always allowed.\n * @returns The standardized prompt.\n * @throws {InvalidPromptError} When the prompt is invalid.\n */\nexport async function standardizePrompt({\n allowSystemInMessages = false,\n system,\n instructions = system,\n prompt,\n messages,\n}: Prompt): Promise<StandardizedPrompt> {\n if (prompt == null && messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (prompt != null && messages != null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt and messages cannot be defined at the same time',\n });\n }\n\n // validate that instructions is a string or a SystemModelMessage\n if (\n typeof instructions !== 'string' &&\n !asArray(instructions).every(message => message.role === 'system')\n ) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'instructions must be a string, SystemModelMessage, or array of SystemModelMessage',\n });\n }\n\n if (prompt != null && typeof prompt === 'string') {\n messages = [{ role: 'user', content: prompt }];\n } else if (prompt != null && Array.isArray(prompt)) {\n messages = prompt;\n } else if (messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (messages.length === 0) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must not be empty',\n });\n }\n\n if (\n !allowSystemInMessages &&\n messages.some(message => message.role === 'system')\n ) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'System messages are not allowed in the prompt or messages fields. Use the instructions option instead.',\n });\n }\n\n const validationResult = await safeValidateTypes({\n value: messages,\n schema: z.array(modelMessageSchema),\n });\n\n if (!validationResult.success) {\n throw new InvalidPromptError({\n prompt,\n message: 'The messages do not match the ModelMessage[] schema.',\n cause: validationResult.error,\n });\n }\n\n return { messages, instructions };\n}\n","import type {\n AssistantModelMessage,\n ModelMessage,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport {\n customPartSchema,\n filePartSchema,\n imagePartSchema,\n reasoningFilePartSchema,\n reasoningPartSchema,\n textPartSchema,\n toolApprovalRequestSchema,\n toolCallPartSchema,\n toolApprovalResponseSchema,\n toolResultPartSchema,\n} from './content-part';\n\nexport const systemModelMessageSchema: z.ZodType<SystemModelMessage> = z.object(\n {\n role: z.literal('system'),\n content: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n },\n);\n\nexport const userModelMessageSchema: z.ZodType<UserModelMessage> = z.object({\n role: z.literal('user'),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const assistantModelMessageSchema: z.ZodType<AssistantModelMessage> =\n z.object({\n role: z.literal('assistant'),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n customPartSchema,\n filePartSchema,\n reasoningPartSchema,\n reasoningFilePartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n toolApprovalRequestSchema,\n ]),\n ),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n });\n\nexport const toolModelMessageSchema: z.ZodType<ToolModelMessage> = z.object({\n role: z.literal('tool'),\n content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const modelMessageSchema: z.ZodType<ModelMessage> = z.union([\n systemModelMessageSchema,\n userModelMessageSchema,\n assistantModelMessageSchema,\n toolModelMessageSchema,\n]);\n","import type { SharedV4ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from './json-value';\n\n/**\n * Additional provider-specific metadata that is returned from the provider.\n *\n * This is needed to enable provider-specific functionality that can be\n * fully encapsulated in the provider.\n */\nexport type ProviderMetadata = SharedV4ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n z.string(),\n z.record(z.string(), jsonValueSchema.optional()),\n);\n","import type { JSONValue as OriginalJSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), jsonValueSchema.optional()),\n z.array(jsonValueSchema),\n ]),\n);\n\nexport type JSONValue = OriginalJSONValue;\n","import {\n isBuffer,\n type CustomPart,\n type DataContent,\n type FilePart,\n type ImagePart,\n type ProviderOptions,\n type ReasoningFilePart,\n type ReasoningPart,\n type TextPart,\n type ToolApprovalRequest,\n type ToolApprovalResponse,\n type ToolResultOutput,\n type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\n\nconst fileInlineDataSchema: z.ZodType<DataContent> = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom<Buffer>(isBuffer, { message: 'Must be a Buffer' }),\n]);\n\nconst providerReferenceSchema = z.record(z.string(), z.string());\n\n/**\n * @internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:\n * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n type: z.literal('image'),\n image: z.union([\n fileInlineDataSchema,\n z.instanceof(URL),\n providerReferenceSchema,\n ]),\n mediaType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nconst taggedFileDataSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n z.object({\n type: z.literal('reference'),\n reference: providerReferenceSchema,\n }),\n z.object({ type: z.literal('text'), text: z.string() }),\n]);\n\nconst taggedReasoningFileDataSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n]);\n\n/**\n * @internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n type: z.literal('file'),\n data: z.union([\n taggedFileDataSchema,\n fileInlineDataSchema,\n z.instanceof(URL),\n providerReferenceSchema,\n ]),\n filename: z.string().optional(),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const customPartSchema: z.ZodType<CustomPart> = z.object({\n type: z.literal('custom'),\n kind: z.string().transform(value => value as `${string}.${string}`),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningFilePartSchema: z.ZodType<ReasoningFilePart> = z.object({\n type: z.literal('reasoning-file'),\n data: z.union([\n taggedReasoningFileDataSchema,\n fileInlineDataSchema,\n z.instanceof(URL),\n ]),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: 'tool-call';\n\n /**\n * ID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n\n /**\n * Name of the tool that is being called.\n */\n toolName: string;\n\n /**\n * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n input: unknown;\n\n /**\n * Additional provider-specific metadata. 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 * @internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n type: z.literal('tool-call'),\n toolCallId: z.string(),\n toolName: z.string(),\n input: z.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n providerExecuted: z.boolean().optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc input is optional on Zod type\n\n/**\n * @internal\n */\nexport const outputSchema: z.ZodType<ToolResultOutput> = z.discriminatedUnion(\n 'type',\n [\n z.object({\n type: z.literal('text'),\n value: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('json'),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('execution-denied'),\n reason: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('error-text'),\n value: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('error-json'),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('content'),\n value: z.array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('file'),\n data: taggedFileDataSchema,\n mediaType: z.string(),\n filename: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-data'),\n data: z.string(),\n mediaType: z.string(),\n filename: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-url'),\n url: z.string(),\n mediaType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-id'),\n fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-reference'),\n providerReference: z.record(z.string(), z.string()),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-data'),\n data: z.string(),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-url'),\n url: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-file-id'),\n fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-file-reference'),\n providerReference: z.record(z.string(), z.string()),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('custom'),\n providerOptions: providerMetadataSchema.optional(),\n }),\n ]),\n ),\n }),\n ],\n);\n\n/**\n * @internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n type: z.literal('tool-result'),\n toolCallId: z.string(),\n toolName: z.string(),\n output: outputSchema,\n providerOptions: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n\n/**\n * @internal\n */\nexport const toolApprovalRequestSchema: z.ZodType<ToolApprovalRequest> =\n z.object({\n type: z.literal('tool-approval-request'),\n approvalId: z.string(),\n toolCallId: z.string(),\n });\n\n/**\n * @internal\n */\nexport const toolApprovalResponseSchema: z.ZodType<ToolApprovalResponse> =\n z.object({\n type: z.literal('tool-approval-response'),\n approvalId: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n });\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly parameter: string;\n readonly value: unknown;\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`,\n });\n\n this.parameter = parameter;\n this.value = value;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { LanguageModelCallOptions } from './language-model-call-options';\n\n/**\n * Validates model call options and returns a new object with normalized values.\n */\nexport function prepareLanguageModelCallOptions({\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n seed,\n stopSequences,\n reasoning,\n}: LanguageModelCallOptions): LanguageModelCallOptions {\n if (maxOutputTokens != null) {\n if (!Number.isInteger(maxOutputTokens)) {\n throw new InvalidArgumentError({\n parameter: 'maxOutputTokens',\n value: maxOutputTokens,\n message: 'maxOutputTokens must be an integer',\n });\n }\n\n if (maxOutputTokens < 1) {\n throw new InvalidArgumentError({\n parameter: 'maxOutputTokens',\n value: maxOutputTokens,\n message: 'maxOutputTokens must be >= 1',\n });\n }\n }\n\n if (temperature != null) {\n if (typeof temperature !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'temperature',\n value: temperature,\n message: 'temperature must be a number',\n });\n }\n }\n\n if (topP != null) {\n if (typeof topP !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topP',\n value: topP,\n message: 'topP must be a number',\n });\n }\n }\n\n if (topK != null) {\n if (typeof topK !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topK',\n value: topK,\n message: 'topK must be a number',\n });\n }\n }\n\n if (presencePenalty != null) {\n if (typeof presencePenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'presencePenalty',\n value: presencePenalty,\n message: 'presencePenalty must be a number',\n });\n }\n }\n\n if (frequencyPenalty != null) {\n if (typeof frequencyPenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: frequencyPenalty,\n message: 'frequencyPenalty must be a number',\n });\n }\n }\n\n if (seed != null) {\n if (!Number.isInteger(seed)) {\n throw new InvalidArgumentError({\n parameter: 'seed',\n value: seed,\n message: 'seed must be an integer',\n });\n }\n }\n\n return {\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences,\n seed,\n reasoning,\n };\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { GatewayError } from '@ai-sdk/gateway';\nimport { delay, getErrorMessage, isAbortError } from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nexport type RetryFunction = <OUTPUT>(\n fn: () => PromiseLike<OUTPUT>,\n) => PromiseLike<OUTPUT>;\n\nfunction getRetryDelayInMs({\n error,\n exponentialBackoffDelay,\n}: {\n error: APICallError | GatewayError;\n exponentialBackoffDelay: number;\n}): number {\n const headers = APICallError.isInstance(error)\n ? error.responseHeaders\n : APICallError.isInstance(error.cause)\n ? (error.cause as APICallError).responseHeaders\n : undefined;\n\n if (!headers) return exponentialBackoffDelay;\n\n let ms: number | undefined;\n\n // retry-ms is more precise than retry-after and used by e.g. OpenAI\n const retryAfterMs = headers['retry-after-ms'];\n if (retryAfterMs) {\n const timeoutMs = parseFloat(retryAfterMs);\n if (!Number.isNaN(timeoutMs)) {\n ms = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfter = headers['retry-after'];\n if (retryAfter && ms === undefined) {\n const timeoutSeconds = parseFloat(retryAfter);\n if (!Number.isNaN(timeoutSeconds)) {\n ms = timeoutSeconds * 1000;\n } else {\n ms = Date.parse(retryAfter) - Date.now();\n }\n }\n\n // check that the delay is reasonable:\n if (\n ms != null &&\n !Number.isNaN(ms) &&\n 0 <= ms &&\n (ms < 60 * 1000 || ms < exponentialBackoffDelay)\n ) {\n return ms;\n }\n\n return exponentialBackoffDelay;\n}\n\n/**\n * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,\n * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).\n * You can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoffRespectingRetryHeaders =\n ({\n maxRetries = 2,\n initialDelayInMs = 2000,\n backoffFactor = 2,\n abortSignal,\n }: {\n maxRetries?: number;\n initialDelayInMs?: number;\n backoffFactor?: number;\n abortSignal?: AbortSignal;\n } = {}): RetryFunction =>\n async <OUTPUT>(f: () => PromiseLike<OUTPUT>) =>\n _retryWithExponentialBackoff(f, {\n maxRetries,\n delayInMs: initialDelayInMs,\n backoffFactor,\n abortSignal,\n });\n\nasync function _retryWithExponentialBackoff<OUTPUT>(\n f: () => PromiseLike<OUTPUT>,\n {\n maxRetries,\n delayInMs,\n backoffFactor,\n abortSignal,\n }: {\n maxRetries: number;\n delayInMs: number;\n backoffFactor: number;\n abortSignal: AbortSignal | undefined;\n },\n errors: unknown[] = [],\n): Promise<OUTPUT> {\n try {\n return await f();\n } catch (error) {\n if (isAbortError(error)) {\n throw error; // don't retry when the request was aborted\n }\n\n if (maxRetries === 0) {\n throw error; // don't wrap the error when retries are disabled\n }\n\n const errorMessage = getErrorMessage(error);\n const newErrors = [...errors, error];\n const tryNumber = newErrors.length;\n\n if (tryNumber > maxRetries) {\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts. Last error: ${errorMessage}`,\n reason: 'maxRetriesExceeded',\n errors: newErrors,\n });\n }\n\n if (\n error instanceof Error &&\n ((APICallError.isInstance(error) && error.isRetryable === true) ||\n (GatewayError.isInstance(error) && error.isRetryable === true)) &&\n tryNumber <= maxRetries\n ) {\n await delay(\n getRetryDelayInMs({\n error: error as APICallError | GatewayError,\n exponentialBackoffDelay: delayInMs,\n }),\n { abortSignal },\n );\n\n return _retryWithExponentialBackoff(\n f,\n {\n maxRetries,\n delayInMs: backoffFactor * delayInMs,\n backoffFactor,\n abortSignal,\n },\n newErrors,\n );\n }\n\n if (tryNumber === 1) {\n throw error; // don't wrap the error when a non-retryable error occurs on the first try\n }\n\n throw new RetryError({\n message: `Failed after ${tryNumber} attempts with non-retryable error: '${errorMessage}'`,\n reason: 'errorNotRetryable',\n errors: newErrors,\n });\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super({ name, message });\n\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n static isInstance(error: unknown): error is RetryError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport {\n retryWithExponentialBackoffRespectingRetryHeaders,\n type RetryFunction,\n} from '../util/retry-with-exponential-backoff';\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n maxRetries,\n abortSignal,\n}: {\n maxRetries: number | undefined;\n abortSignal: AbortSignal | undefined;\n}): {\n maxRetries: number;\n retry: RetryFunction;\n} {\n if (maxRetries != null) {\n if (!Number.isInteger(maxRetries)) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be an integer',\n });\n }\n\n if (maxRetries < 0) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be >= 0',\n });\n }\n }\n\n const maxRetriesResult = maxRetries ?? 2;\n\n return {\n maxRetries: maxRetriesResult,\n retry: retryWithExponentialBackoffRespectingRetryHeaders({\n maxRetries: maxRetriesResult,\n abortSignal,\n }),\n };\n}\n","import type {\n ImageModelV4Usage,\n JSONObject,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n /**\n * The total number of input (prompt) tokens used.\n */\n inputTokens: number | undefined;\n\n /**\n * Detailed information about the input tokens.\n */\n inputTokenDetails: {\n /**\n * The number of non-cached input (prompt) tokens used.\n */\n noCacheTokens: number | undefined;\n\n /**\n * The number of cached input (prompt) tokens read.\n */\n cacheReadTokens: number | undefined;\n\n /**\n * The number of cached input (prompt) tokens written.\n */\n cacheWriteTokens: number | undefined;\n };\n\n /**\n * The number of total output (completion) tokens used.\n */\n outputTokens: number | undefined;\n\n /**\n * Detailed information about the output tokens.\n */\n outputTokenDetails: {\n /**\n * The number of text tokens used.\n */\n textTokens: number | undefined;\n\n /**\n * The number of reasoning tokens used.\n */\n reasoningTokens: number | undefined;\n };\n\n /**\n * The total number of tokens used.\n */\n totalTokens: number | undefined;\n\n /**\n * Raw usage information from the provider.\n *\n * This is the usage information in the shape that the provider returns.\n * It can include additional information that is not part of the standard usage information.\n */\n raw?: JSONObject;\n};\n\n/**\n * Represents the number of tokens used in an embedding.\n */\n// TODO replace with EmbeddingModelV4Usage once available in @ai-sdk/provider\nexport type EmbeddingModelUsage = {\n /**\n * The number of tokens used in the embedding.\n */\n tokens: number;\n};\n\nexport function asLanguageModelUsage(\n usage: LanguageModelV4Usage,\n): LanguageModelUsage {\n return {\n inputTokens: usage.inputTokens.total,\n inputTokenDetails: {\n noCacheTokens: usage.inputTokens.noCache,\n cacheReadTokens: usage.inputTokens.cacheRead,\n cacheWriteTokens: usage.inputTokens.cacheWrite,\n },\n outputTokens: usage.outputTokens.total,\n outputTokenDetails: {\n textTokens: usage.outputTokens.text,\n reasoningTokens: usage.outputTokens.reasoning,\n },\n totalTokens: addTokenCounts(\n usage.inputTokens.total,\n usage.outputTokens.total,\n ),\n raw: usage.raw,\n };\n}\n\nexport function createNullLanguageModelUsage(): LanguageModelUsage {\n return {\n inputTokens: undefined,\n inputTokenDetails: {\n noCacheTokens: undefined,\n cacheReadTokens: undefined,\n cacheWriteTokens: undefined,\n },\n outputTokens: undefined,\n outputTokenDetails: {\n textTokens: undefined,\n reasoningTokens: undefined,\n },\n totalTokens: undefined,\n raw: undefined,\n };\n}\n\nexport function addLanguageModelUsage(\n usage1: LanguageModelUsage,\n usage2: LanguageModelUsage,\n): LanguageModelUsage {\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n inputTokenDetails: {\n noCacheTokens: addTokenCounts(\n usage1.inputTokenDetails?.noCacheTokens,\n usage2.inputTokenDetails?.noCacheTokens,\n ),\n cacheReadTokens: addTokenCounts(\n usage1.inputTokenDetails?.cacheReadTokens,\n usage2.inputTokenDetails?.cacheReadTokens,\n ),\n cacheWriteTokens: addTokenCounts(\n usage1.inputTokenDetails?.cacheWriteTokens,\n usage2.inputTokenDetails?.cacheWriteTokens,\n ),\n },\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n outputTokenDetails: {\n textTokens: addTokenCounts(\n usage1.outputTokenDetails?.textTokens,\n usage2.outputTokenDetails?.textTokens,\n ),\n reasoningTokens: addTokenCounts(\n usage1.outputTokenDetails?.reasoningTokens,\n usage2.outputTokenDetails?.reasoningTokens,\n ),\n },\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n };\n}\n\nfunction addTokenCounts(\n tokenCount1: number | undefined,\n tokenCount2: number | undefined,\n): number | undefined {\n return tokenCount1 == null && tokenCount2 == null\n ? undefined\n : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n\n/**\n * Usage information for an image model call.\n */\nexport type ImageModelUsage = ImageModelV4Usage;\n\nexport function addImageModelUsage(\n usage1: ImageModelUsage,\n usage2: ImageModelUsage,\n): ImageModelUsage {\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n };\n}\n","import { gateway } from '@ai-sdk/gateway';\nimport type {\n EmbeddingModelV4,\n Experimental_VideoModelV4,\n ImageModelV4,\n LanguageModelV4,\n ProviderV4,\n RerankingModelV4,\n SpeechModelV4,\n TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport { UnsupportedModelVersionError } from '../error';\nimport type { EmbeddingModel } from '../types/embedding-model';\nimport type { LanguageModel } from '../types/language-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asVideoModelV4 } from './as-video-model-v4';\nimport { asProviderV4 } from './as-provider-v4';\nimport type { ImageModel } from '../types/image-model';\nimport type { RerankingModel } from '../types/reranking-model';\nimport type { VideoModel } from '../types/video-model';\n\nexport function resolveLanguageModel(model: LanguageModel): LanguageModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().languageModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asLanguageModelV4(model);\n}\n\nexport function resolveEmbeddingModel(model: EmbeddingModel): EmbeddingModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().embeddingModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asEmbeddingModelV4(model);\n}\n\nexport function resolveTranscriptionModel(\n model: TranscriptionModel,\n): TranscriptionModelV4 | undefined {\n if (typeof model === 'string') {\n return getGlobalProvider().transcriptionModel?.(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asTranscriptionModelV4(model);\n}\n\nexport function resolveSpeechModel(\n model: SpeechModel,\n): SpeechModelV4 | undefined {\n if (typeof model === 'string') {\n return getGlobalProvider().speechModel?.(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asSpeechModelV4(model);\n}\n\nexport function resolveImageModel(model: ImageModel): ImageModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().imageModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asImageModelV4(model);\n}\n\nexport function resolveVideoModel(\n model: VideoModel,\n): Experimental_VideoModelV4 {\n if (typeof model === 'string') {\n // Use raw global provider because videoModel is experimental\n // and not part of the ProviderV4 interface\n const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n // TODO AI SDK v7\n // @ts-expect-error - videoModel support is experimental\n const videoModel = provider.videoModel;\n\n if (!videoModel) {\n throw new Error(\n 'The default provider does not support video models. ' +\n 'Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\"model-id\")).',\n );\n }\n\n return videoModel(model);\n }\n\n if (!['v4', 'v3'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asVideoModelV4(model);\n}\n\nexport function resolveRerankingModel(model: RerankingModel): RerankingModelV4 {\n if (typeof model === 'string') {\n const provider = getGlobalProvider();\n const rerankingModel = provider.rerankingModel;\n\n if (!rerankingModel) {\n throw new Error(\n 'The default provider does not support reranking models. ' +\n 'Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).',\n );\n }\n\n return rerankingModel(model);\n }\n\n if (\n model.specificationVersion !== 'v4' &&\n model.specificationVersion !== 'v3'\n ) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asRerankingModelV4(model);\n}\n\nfunction getGlobalProvider(): ProviderV4 {\n const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n return asProviderV4(provider);\n}\n","export {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n NoSuchProviderReferenceError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport { InvalidArgumentError } from './invalid-argument-error';\nexport { InvalidStreamPartError } from './invalid-stream-part-error';\nexport { InvalidToolApprovalError } from './invalid-tool-approval-error';\nexport { InvalidToolApprovalSignatureError } from './invalid-tool-approval-signature-error';\nexport { InvalidToolInputError } from './invalid-tool-input-error';\nexport { ToolCallNotFoundForApprovalError } from './tool-call-not-found-for-approval-error';\nexport { MissingToolResultsError } from './missing-tool-result-error';\nexport { NoImageGeneratedError } from './no-image-generated-error';\nexport { NoObjectGeneratedError } from './no-object-generated-error';\nexport { NoOutputGeneratedError } from './no-output-generated-error';\nexport { NoSpeechGeneratedError } from './no-speech-generated-error';\nexport { NoTranscriptGeneratedError } from './no-transcript-generated-error';\nexport { NoVideoGeneratedError } from './no-video-generated-error';\nexport { NoSuchToolError } from './no-such-tool-error';\nexport { ToolCallRepairError } from './tool-call-repair-error';\nexport { UnsupportedModelVersionError } from './unsupported-model-version-error';\nexport { UIMessageStreamError } from './ui-message-stream-error';\nexport { InvalidDataContentError } from '../prompt/invalid-data-content-error';\nexport { InvalidMessageRoleError } from '../prompt/invalid-message-role-error';\nexport { MessageConversionError } from '../prompt/message-conversion-error';\nexport { DownloadError } from '@ai-sdk/provider-utils';\nexport { RetryError } from '../util/retry-error';\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly approvalId: string;\n\n constructor({ approvalId }: { approvalId: string }) {\n super({\n name,\n message:\n `Tool approval response references unknown approvalId: \"${approvalId}\". ` +\n `No matching tool-approval-request found in message history.`,\n });\n\n this.approvalId = approvalId;\n }\n\n static isInstance(error: unknown): error is InvalidToolApprovalError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalSignatureError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalSignatureError extends AISDKError {\n private readonly [symbol] = true;\n\n readonly approvalId: string;\n readonly toolCallId: string;\n\n constructor({\n approvalId,\n toolCallId,\n reason,\n }: {\n approvalId: string;\n toolCallId: string;\n reason: string;\n }) {\n super({\n name,\n message: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`,\n });\n this.approvalId = approvalId;\n this.toolCallId = toolCallId;\n }\n\n static isInstance(\n error: unknown,\n ): error is InvalidToolApprovalSignatureError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolInputError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolInputError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly toolInput: string;\n\n constructor({\n toolInput,\n toolName,\n cause,\n message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n toolInput: string;\n toolName: string;\n cause: unknown;\n }) {\n super({ name, message, cause });\n\n this.toolInput = toolInput;\n this.toolName = toolName;\n }\n\n static isInstance(error: unknown): error is InvalidToolInputError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_ToolCallNotFoundForApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallNotFoundForApprovalError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolCallId: string;\n readonly approvalId: string;\n\n constructor({\n toolCallId,\n approvalId,\n }: {\n toolCallId: string;\n approvalId: string;\n }) {\n super({\n name,\n message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`,\n });\n\n this.toolCallId = toolCallId;\n this.approvalId = approvalId;\n }\n\n static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly availableTools: string[] | undefined;\n\n constructor({\n toolName,\n availableTools = undefined,\n message = `Model tried to call unavailable tool '${toolName}'. ${\n availableTools === undefined\n ? 'No tools are available.'\n : `Available tools: ${availableTools.join(', ')}.`\n }`,\n }: {\n toolName: string;\n availableTools?: string[] | undefined;\n message?: string;\n }) {\n super({ name, message });\n\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n\n static isInstance(error: unknown): error is NoSuchToolError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\nimport type { InvalidToolInputError } from './invalid-tool-input-error';\nimport type { NoSuchToolError } from './no-such-tool-error';\n\nconst name = 'AI_ToolCallRepairError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallRepairError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalError: NoSuchToolError | InvalidToolInputError;\n\n constructor({\n cause,\n originalError,\n message = `Error repairing tool call: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n cause: unknown;\n originalError: NoSuchToolError | InvalidToolInputError;\n }) {\n super({ name, message, cause });\n this.originalError = originalError;\n }\n\n static isInstance(error: unknown): error is ToolCallRepairError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\n/**\n * Error that is thrown when a model with an unsupported version is used.\n */\nexport class UnsupportedModelVersionError extends AISDKError {\n readonly version: string;\n readonly provider: string;\n readonly modelId: string;\n\n constructor(options: { version: string; provider: string; modelId: string }) {\n super({\n name: 'AI_UnsupportedModelVersionError',\n message:\n `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". ` +\n `AI SDK 5 only supports models that implement specification version \"v2\".`,\n });\n\n this.version = options.version;\n this.provider = options.provider;\n this.modelId = options.modelId;\n }\n}\n","import { logWarnings } from '../logger/log-warnings';\n\nexport function logV2CompatibilityWarning({\n provider,\n modelId,\n}: {\n provider: string;\n modelId: string;\n}): void {\n logWarnings({\n warnings: [\n {\n type: 'compatibility',\n feature: 'specificationVersion',\n details: `Using v2 specification compatibility mode. Some features may not be available.`,\n },\n ],\n provider,\n model: modelId,\n });\n}\n","import type { EmbeddingModelV2, EmbeddingModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asEmbeddingModelV3(\n model: EmbeddingModelV2<string> | EmbeddingModelV3,\n): EmbeddingModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof EmbeddingModelV2<string>) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as EmbeddingModelV3;\n}\n","import type {\n EmbeddingModelV2,\n EmbeddingModelV3,\n EmbeddingModelV4,\n} from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\n\nexport function asEmbeddingModelV4(\n model: EmbeddingModelV2<string> | EmbeddingModelV3 | EmbeddingModelV4,\n): EmbeddingModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asEmbeddingModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof EmbeddingModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as EmbeddingModelV4;\n}\n","import type { ImageModelV2, ImageModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asImageModelV3(\n model: ImageModelV2 | ImageModelV3,\n): ImageModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof ImageModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as ImageModelV3;\n}\n","import type {\n ImageModelV2,\n ImageModelV3,\n ImageModelV4,\n} from '@ai-sdk/provider';\nimport { asImageModelV3 } from './as-image-model-v3';\n\nexport function asImageModelV4(\n model: ImageModelV2 | ImageModelV3 | ImageModelV4,\n): ImageModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asImageModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof ImageModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as ImageModelV4;\n}\n","import type {\n LanguageModelV2,\n LanguageModelV2FinishReason,\n LanguageModelV2StreamPart,\n LanguageModelV2Usage,\n LanguageModelV3,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asLanguageModelV3(\n model: LanguageModelV2 | LanguageModelV3,\n): LanguageModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof LanguageModelV2) {\n switch (prop) {\n case 'specificationVersion':\n return 'v3';\n case 'doGenerate':\n return async (...args: Parameters<LanguageModelV2['doGenerate']>) => {\n const result = await target.doGenerate(...args);\n return {\n ...result,\n finishReason: convertV2FinishReasonToV3(result.finishReason),\n usage: convertV2UsageToV3(result.usage),\n };\n };\n case 'doStream':\n return async (...args: Parameters<LanguageModelV2['doStream']>) => {\n const result = await target.doStream(...args);\n return {\n ...result,\n stream: convertV2StreamToV3(result.stream),\n };\n };\n default:\n return target[prop];\n }\n },\n }) as unknown as LanguageModelV3;\n}\n\nfunction convertV2StreamToV3(\n stream: ReadableStream<LanguageModelV2StreamPart>,\n): ReadableStream<LanguageModelV3StreamPart> {\n return stream.pipeThrough(\n new TransformStream<LanguageModelV2StreamPart, LanguageModelV3StreamPart>({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'finish':\n controller.enqueue({\n ...chunk,\n finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n usage: convertV2UsageToV3(chunk.usage),\n });\n break;\n default:\n // TODO: AI SDK 6 - no casting (stream parts need to be mapped)\n controller.enqueue(chunk as LanguageModelV3StreamPart);\n break;\n }\n },\n }),\n );\n}\n\nfunction convertV2FinishReasonToV3(\n finishReason: LanguageModelV2FinishReason,\n): LanguageModelV3FinishReason {\n return {\n unified: finishReason === 'unknown' ? 'other' : finishReason,\n raw: undefined,\n };\n}\n\nfunction convertV2UsageToV3(usage: LanguageModelV2Usage): LanguageModelV3Usage {\n return {\n inputTokens: {\n total: usage.inputTokens,\n noCache: undefined,\n cacheRead: usage.cachedInputTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: usage.outputTokens,\n text: undefined,\n reasoning: usage.reasoningTokens,\n },\n };\n}\n","import type {\n LanguageModelV2,\n LanguageModelV3,\n LanguageModelV4,\n} from '@ai-sdk/provider';\nimport { asLanguageModelV3 } from './as-language-model-v3';\n\nexport function asLanguageModelV4(\n model: LanguageModelV2 | LanguageModelV3 | LanguageModelV4,\n): LanguageModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asLanguageModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof LanguageModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as LanguageModelV4;\n}\n","import type { RerankingModelV3, RerankingModelV4 } from '@ai-sdk/provider';\n\nexport function asRerankingModelV4(\n model: RerankingModelV3 | RerankingModelV4,\n): RerankingModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n return new Proxy(model, {\n get(target, prop: keyof RerankingModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as RerankingModelV4;\n}\n","import type { SpeechModelV2, SpeechModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asSpeechModelV3(\n model: SpeechModelV3 | SpeechModelV2,\n): SpeechModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof SpeechModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as SpeechModelV3;\n}\n","import type {\n SpeechModelV2,\n SpeechModelV3,\n SpeechModelV4,\n} from '@ai-sdk/provider';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asSpeechModelV4(\n model: SpeechModelV2 | SpeechModelV3 | SpeechModelV4,\n): SpeechModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asSpeechModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof SpeechModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as SpeechModelV4;\n}\n","import type {\n TranscriptionModelV2,\n TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asTranscriptionModelV3(\n model: TranscriptionModelV3 | TranscriptionModelV2,\n): TranscriptionModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof TranscriptionModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as TranscriptionModelV3;\n}\n","import type {\n TranscriptionModelV2,\n TranscriptionModelV3,\n TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\n\nexport function asTranscriptionModelV4(\n model: TranscriptionModelV2 | TranscriptionModelV3 | TranscriptionModelV4,\n): TranscriptionModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asTranscriptionModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof TranscriptionModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as TranscriptionModelV4;\n}\n","import type { ProviderV2, ProviderV3 } from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\nimport { asImageModelV3 } from './as-image-model-v3';\nimport { asLanguageModelV3 } from './as-language-model-v3';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asProviderV3(provider: ProviderV2 | ProviderV3): ProviderV3 {\n if (\n 'specificationVersion' in provider &&\n provider.specificationVersion === 'v3'\n ) {\n return provider;\n }\n\n // v3 providers have already been returned\n const v2Provider: ProviderV2 = provider as ProviderV2;\n\n return {\n specificationVersion: 'v3',\n languageModel: (modelId: string) =>\n asLanguageModelV3(v2Provider.languageModel(modelId)),\n embeddingModel: (modelId: string) =>\n asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n imageModel: (modelId: string) =>\n asImageModelV3(v2Provider.imageModel(modelId)),\n transcriptionModel: v2Provider.transcriptionModel\n ? (modelId: string) =>\n asTranscriptionModelV3(v2Provider.transcriptionModel!(modelId))\n : undefined,\n speechModel: v2Provider.speechModel\n ? (modelId: string) => asSpeechModelV3(v2Provider.speechModel!(modelId))\n : undefined,\n rerankingModel: undefined, // v2 providers don't have reranking models\n };\n}\n","import type { ProviderV2, ProviderV3, ProviderV4 } from '@ai-sdk/provider';\nimport { asProviderV3 } from './as-provider-v3';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\n\nexport function asProviderV4(\n provider: ProviderV2 | ProviderV3 | ProviderV4,\n): ProviderV4 {\n if (\n 'specificationVersion' in provider &&\n provider.specificationVersion === 'v4'\n ) {\n return provider;\n }\n\n // first ensure we have at least a v3 provider:\n const v3Provider: ProviderV3 =\n !('specificationVersion' in provider) ||\n provider.specificationVersion !== 'v3'\n ? asProviderV3(provider as ProviderV2)\n : provider;\n\n return {\n specificationVersion: 'v4',\n languageModel: (modelId: string) =>\n asLanguageModelV4(v3Provider.languageModel(modelId)),\n embeddingModel: (modelId: string) =>\n asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),\n imageModel: (modelId: string) =>\n asImageModelV4(v3Provider.imageModel(modelId)),\n transcriptionModel: v3Provider.transcriptionModel\n ? (modelId: string) =>\n asTranscriptionModelV4(v3Provider.transcriptionModel!(modelId))\n : undefined,\n speechModel: v3Provider.speechModel\n ? (modelId: string) => asSpeechModelV4(v3Provider.speechModel!(modelId))\n : undefined,\n rerankingModel: v3Provider.rerankingModel\n ? (modelId: string) =>\n asRerankingModelV4(v3Provider.rerankingModel!(modelId))\n : undefined,\n };\n}\n","import { filterNullable } from '@ai-sdk/provider-utils';\n\n/**\n * Merges multiple abort sources into a single `AbortSignal`.\n * The returned signal will abort when any input signal aborts or when any\n * numeric timeout elapses, using the reason from the first source to abort.\n *\n * @param signals - Abort signals or timeout durations in milliseconds.\n * `null` and `undefined` values are ignored.\n * @returns An `AbortSignal` that aborts when any valid source aborts,\n * or `undefined` if no valid sources are provided.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | null | undefined | number)[]\n): AbortSignal | undefined {\n const validSignals = filterNullable(...signals).map(signal =>\n signal instanceof AbortSignal ? signal : AbortSignal.timeout(signal),\n );\n\n return validSignals.length === 0\n ? undefined\n : validSignals.length === 1\n ? validSignals[0]\n : AbortSignal.any(validSignals);\n}\n","import type { Callback } from '../util/callback';\n\n/**\n * Creates an async callback that invokes the provided callbacks in parallel.\n * Undefined callbacks are skipped, and thrown or rejected callback errors are\n * ignored.\n *\n * @param callbacks The callbacks to invoke for each event.\n * @returns A callback that forwards each event to all callbacks and waits for\n * them to settle.\n */\nexport function mergeCallbacks<EVENT>(\n ...callbacks: Array<Callback<EVENT> | undefined>\n): Callback<EVENT> {\n return async (event: EVENT) => {\n await Promise.allSettled(\n callbacks.map(async callback => {\n await callback?.(event);\n }),\n );\n };\n}\n","import { asArray } from '@ai-sdk/provider-utils';\nimport type { Callback } from '../util/callback';\nimport { mergeCallbacks } from '../util/merge-callbacks';\nimport type {\n InferTelemetryEvent,\n Telemetry,\n TelemetryDispatcher,\n} from './telemetry';\nimport {\n openTelemetryChannelSpanContext,\n runWithTracingChannelSpan,\n} from './tracing-channel-publisher';\nimport { getGlobalTelemetryIntegrations } from './telemetry-registry';\nimport type { TelemetryOptions } from './telemetry-options';\n\n/**\n * The subset of `TelemetryDispatcher` keys whose values are Callback callbacks.\n * This excludes dispatcher-only helpers and non-Callback properties such as\n * `executeLanguageModelCall` and `executeTool`.\n */\ntype TelemetryCallbackKey = Exclude<\n keyof {\n [K in keyof TelemetryDispatcher as TelemetryDispatcher[K] extends\n | Callback<any>\n | undefined\n ? K\n : never]: true;\n },\n 'runInTracingChannelSpan' | 'startTracingChannelContext'\n>;\n\n/**\n * Resolves the public event type accepted by a telemetry callback key.\n */\ntype TelemetryEvent<K extends TelemetryCallbackKey> =\n TelemetryDispatcher[K] extends Callback<infer EVENT> | undefined\n ? EVENT\n : never;\n\nfunction augmentEvent<EVENT>(\n event: EVENT,\n telemetry: Pick<\n TelemetryOptions,\n 'recordInputs' | 'recordOutputs' | 'functionId'\n >,\n): InferTelemetryEvent<EVENT> {\n return Object.assign(\n Object.create(Object.getPrototypeOf(event)),\n event,\n telemetry,\n );\n}\n\n/**\n * Creates a telemetry dispatcher that sends telemetry events\n * to the resolved set of integrations.\n *\n * When per-call integrations are provided, they take precedence over the globally\n * registered integrations for that call. When no per-call integrations are\n * provided, the globally registered integrations are used.\n *\n * @param args.telemetry - Optional per-call telemetry settings and integrations.\n *\n * @returns A telemetry dispatcher that fans out lifecycle events to the\n * resolved set of integrations.\n */\nexport function createTelemetryDispatcher({\n telemetry,\n}: {\n telemetry?: TelemetryOptions;\n // operationId: string;\n}): TelemetryDispatcher {\n // When telemetry is explicitly disabled, return a dispatcher\n // that performs no work and lets tool execution pass through unwrapped.\n if (telemetry?.isEnabled === false) {\n return {};\n }\n\n const localIntegrations = telemetry?.integrations;\n const integrations: Array<Telemetry> =\n localIntegrations != null\n ? asArray(localIntegrations)\n : getGlobalTelemetryIntegrations();\n\n const telemetryMetadata = {\n recordInputs: telemetry?.recordInputs,\n recordOutputs: telemetry?.recordOutputs,\n functionId: telemetry?.functionId,\n };\n\n const mergeTelemetryCallback = <KEY extends TelemetryCallbackKey>(\n key: KEY,\n ): Callback<TelemetryEvent<KEY>> => {\n const integrationCallbacks = (\n integrations\n .map(integration => integration[key]?.bind(integration))\n .filter(Boolean) as Array<\n Callback<InferTelemetryEvent<TelemetryEvent<KEY>>>\n >\n ).map(\n callback =>\n ((event: TelemetryEvent<KEY>) =>\n callback(augmentEvent(event, telemetryMetadata))) as Callback<\n TelemetryEvent<KEY>\n >,\n );\n\n const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);\n\n return async (event: TelemetryEvent<KEY>) => {\n await mergedIntegrationCallback(event);\n };\n };\n\n const executeLanguageModelCallWrappers = integrations\n .map(integration => integration.executeLanguageModelCall?.bind(integration))\n .filter(Boolean) as Array<\n NonNullable<Telemetry['executeLanguageModelCall']>\n >;\n\n const executeToolWrappers = integrations\n .map(integration => integration.executeTool?.bind(integration))\n .filter(Boolean) as Array<NonNullable<Telemetry['executeTool']>>;\n\n return {\n runInTracingChannelSpan: async ({ type, event, execute }) =>\n await runWithTracingChannelSpan(\n {\n type,\n event: augmentEvent(event, telemetryMetadata),\n },\n execute,\n ),\n\n startTracingChannelContext: ({ type, event, completion }) =>\n openTelemetryChannelSpanContext({\n message: {\n type,\n event: augmentEvent(event, telemetryMetadata),\n },\n completion,\n }),\n\n onStart: mergeTelemetryCallback('onStart'),\n onStepStart: mergeTelemetryCallback('onStepStart'),\n onLanguageModelCallStart: mergeTelemetryCallback(\n 'onLanguageModelCallStart',\n ),\n onLanguageModelCallEnd: mergeTelemetryCallback('onLanguageModelCallEnd'),\n onToolExecutionStart: mergeTelemetryCallback('onToolExecutionStart'),\n onToolExecutionEnd: mergeTelemetryCallback('onToolExecutionEnd'),\n // Fan out step-end events to both the new `onStepEnd` callback and the\n // deprecated `onStepFinish` callback so integrations that still implement\n // only `onStepFinish` keep receiving step-end events during the deprecation\n // window.\n onStepEnd: mergeCallbacks(\n mergeTelemetryCallback('onStepEnd'),\n mergeTelemetryCallback('onStepFinish'),\n ),\n onObjectStepStart: mergeTelemetryCallback('onObjectStepStart'),\n onObjectStepEnd: mergeTelemetryCallback('onObjectStepEnd'),\n onEmbedStart: mergeTelemetryCallback('onEmbedStart'),\n onEmbedEnd: mergeTelemetryCallback('onEmbedEnd'),\n onRerankStart: mergeTelemetryCallback('onRerankStart'),\n onRerankEnd: mergeTelemetryCallback('onRerankEnd'),\n onEnd: mergeTelemetryCallback('onEnd'),\n onAbort: mergeTelemetryCallback('onAbort'),\n onError: mergeTelemetryCallback('onError'),\n\n /**\n * Runs provider calls inside integration-specific context so\n * auto-instrumented provider requests can be associated with model work.\n */\n executeLanguageModelCall: async ({ execute, ...event }) => {\n const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n let wrappedExecute = execute;\n for (const executeWrapper of executeLanguageModelCallWrappers) {\n const innerExecute = wrappedExecute;\n wrappedExecute = () =>\n executeWrapper({ ...augmentedEvent, execute: innerExecute });\n }\n\n return await runWithTracingChannelSpan(\n { type: 'languageModelCall', event: augmentedEvent },\n wrappedExecute,\n );\n },\n\n /**\n * Composes all `executeTool` wrappers around the original tool execution.\n * Each wrapper receives an `execute` function that calls the next wrapper in\n * the chain, so integrations can establish nested telemetry context before\n * delegating to the underlying tool.\n */\n executeTool: async ({ execute, ...event }) => {\n const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n let wrappedExecute = execute;\n for (const executeWrapper of executeToolWrappers) {\n const innerExecute = wrappedExecute;\n wrappedExecute = () =>\n executeWrapper({ ...augmentedEvent, execute: innerExecute });\n }\n\n return await wrappedExecute();\n },\n };\n}\n","export const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nexport type TelemetryTracingEventType =\n | 'generateText'\n | 'streamText'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'rerank';\n\nexport type TelemetryTracingChannelMessage<EVENT = unknown> = {\n readonly type: TelemetryTracingEventType;\n readonly event: EVENT;\n};\n","export function isNodeRuntime(): boolean {\n return typeof process !== 'undefined' && process.release?.name === 'node';\n}\n","import type * as diagnosticsChannelModule from 'node:diagnostics_channel';\nimport type * as asyncHooksModule from 'node:async_hooks';\nimport {\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n type TelemetryTracingChannelMessage,\n} from './tracing-channel';\nimport { isNodeRuntime } from '../util/is-node-runtime';\n\ntype DiagnosticsChannel = typeof diagnosticsChannelModule;\ntype AsyncHooks = typeof asyncHooksModule;\ntype AsyncResource = asyncHooksModule.AsyncResource;\n\nexport type TracingChannelContext = {\n run<T>(execute: () => T): T;\n};\n\nlet diagnosticsChannelPromise:\n | Promise<DiagnosticsChannel | undefined>\n | undefined;\n\n/**\n * Loads Node's diagnostics channel module only when the current runtime supports\n * it. Unsupported runtimes and failed imports intentionally resolve to\n * undefined so telemetry tracing never crashes user code.\n */\nasync function loadDiagnosticsChannel(): Promise<\n DiagnosticsChannel | undefined\n> {\n if (!isNodeRuntime()) {\n return undefined;\n }\n\n if (diagnosticsChannelPromise == null) {\n diagnosticsChannelPromise = (\n import(\n /* webpackIgnore: true */\n 'node:diagnostics_channel'\n ) as Promise<DiagnosticsChannel>\n ).catch(() => undefined);\n }\n\n return diagnosticsChannelPromise;\n}\n\nfunction loadBuiltinModule<T>(id: string): T | undefined {\n const processWithBuiltins = globalThis.process as\n | {\n getBuiltinModule?: (id: string) => unknown;\n }\n | undefined;\n\n try {\n return processWithBuiltins?.getBuiltinModule?.(id) as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Runs an async operation inside the AI SDK telemetry tracing channel when\n * tracing subscribers may exist. Without Node diagnostics-channel support,\n * without tracingChannel support, or when the runtime reports no subscribers,\n * this is a direct pass-through.\n *\n * The execution bookkeeping preserves the original model/tool result or error\n * if tracing itself throws, and prevents falling back by calling `execute` a\n * second time.\n */\nexport async function runWithTracingChannelSpan<T>(\n message: TelemetryTracingChannelMessage,\n execute: () => PromiseLike<T>,\n): Promise<T> {\n const diagnosticsChannel = await loadDiagnosticsChannel();\n const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n );\n\n if (tracingChannel == null || tracingChannel.hasSubscribers === false) {\n return await execute();\n }\n\n let executePromise: Promise<T> | undefined;\n let executionResult: T | undefined;\n let executionError: unknown;\n let hasExecutionResult = false;\n let hasExecutionError = false;\n\n const tracedExecute = () => {\n try {\n executePromise = Promise.resolve(execute());\n } catch (error) {\n executePromise = Promise.reject(error);\n }\n\n executePromise = executePromise.then(\n result => {\n executionResult = result;\n hasExecutionResult = true;\n return result;\n },\n error => {\n executionError = error;\n hasExecutionError = true;\n throw error;\n },\n );\n\n return executePromise;\n };\n\n try {\n return await tracingChannel.tracePromise(tracedExecute, message);\n } catch {\n if (hasExecutionError) {\n throw executionError;\n }\n\n if (hasExecutionResult) {\n return executionResult as T;\n }\n\n if (executePromise != null) {\n return await executePromise;\n }\n\n return await execute();\n }\n}\n\n/**\n * Opens a long-lived tracing-channel span context and returns a runner that can\n * re-enter that context later without changing stream setup timing.\n */\nexport function openTelemetryChannelSpanContext({\n message,\n completion,\n}: {\n message: TelemetryTracingChannelMessage;\n completion: PromiseLike<unknown>;\n}): TracingChannelContext | undefined {\n if (!isNodeRuntime()) {\n return undefined;\n }\n\n const diagnosticsChannel = loadBuiltinModule<DiagnosticsChannel>(\n 'node:diagnostics_channel',\n );\n const asyncHooks = loadBuiltinModule<AsyncHooks>('node:async_hooks');\n const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n );\n\n if (\n tracingChannel == null ||\n tracingChannel.hasSubscribers === false ||\n asyncHooks == null\n ) {\n Promise.resolve(completion).catch(() => {});\n return undefined;\n }\n\n const context = message as TelemetryTracingChannelMessage & {\n result?: unknown;\n error?: unknown;\n };\n let asyncResource: AsyncResource | undefined;\n let asyncEndPublished = false;\n\n const safePublish = (publish: () => void) => {\n try {\n publish();\n } catch {\n // Diagnostics subscribers should never affect SDK stream behavior.\n }\n };\n\n const publishAsyncEnd = ({\n result,\n error,\n }: {\n result?: unknown;\n error?: unknown;\n }) => {\n if (asyncEndPublished) {\n return;\n }\n\n asyncEndPublished = true;\n\n if (error !== undefined) {\n context.error = error;\n safePublish(() => tracingChannel.error.publish(context));\n }\n\n if (result !== undefined) {\n context.result = result;\n }\n\n safePublish(() => tracingChannel.asyncEnd.publish(context));\n };\n\n safePublish(() => {\n tracingChannel.start.runStores(context, () => {\n asyncResource = new asyncHooks.AsyncResource('ai.telemetry');\n });\n });\n safePublish(() => tracingChannel.end.publish(context));\n\n void Promise.resolve(completion).then(\n result => publishAsyncEnd({ result }),\n error => publishAsyncEnd({ error }),\n );\n\n return {\n run: execute =>\n asyncResource == null\n ? execute()\n : asyncResource.runInAsyncScope(execute),\n };\n}\n","import type { Telemetry } from './telemetry';\n\n/**\n * Registers one or more telemetry integrations globally.\n */\nexport function registerTelemetry(...integrations: Telemetry[]): void {\n if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n }\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);\n}\n\nexport function getGlobalTelemetryIntegrations(): Telemetry[] {\n return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];\n}\n","import type { ReasoningPart, ReasoningFilePart } from '@ai-sdk/provider-utils';\n\nexport function asReasoningText(\n reasoningParts: Array<ReasoningPart | ReasoningFilePart>,\n): string | undefined {\n const reasoningText = reasoningParts\n .map(part => ('text' in part ? part.text : ''))\n .join('');\n return reasoningText.length > 0 ? reasoningText : undefined;\n}\n","import type {\n DataContent,\n ReasoningFilePart,\n ReasoningPart,\n} from '@ai-sdk/provider-utils';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport { DefaultGeneratedFile, type GeneratedFile } from './generated-file';\n\nfunction unwrapReasoningFileData(\n data: ReasoningFilePart['data'],\n): DataContent | URL {\n if (typeof data === 'object' && data !== null && 'type' in data) {\n return data.type === 'data' ? data.data : data.url;\n }\n return data;\n}\n\n/**\n * Reasoning output of a text generation. It contains a reasoning.\n */\nexport interface ReasoningOutput {\n type: 'reasoning';\n\n /**\n * The reasoning text.\n */\n text: string;\n\n /**\n * Additional provider-specific metadata. 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 providerMetadata?: ProviderMetadata;\n}\n\n/**\n * Reasoning file output of a text generation.\n * It contains a file generated as part of reasoning.\n */\nexport interface ReasoningFileOutput {\n type: 'reasoning-file';\n\n /**\n * The generated file.\n */\n file: GeneratedFile;\n\n /**\n * Additional provider-specific metadata. 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 providerMetadata?: ProviderMetadata;\n}\n\nexport function convertFromReasoningOutputs(\n parts: Array<ReasoningOutput | ReasoningFileOutput>,\n): Array<ReasoningPart | ReasoningFilePart> {\n return parts.map(part => {\n if (part.type === 'reasoning') {\n return {\n type: 'reasoning' as const,\n text: part.text,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n };\n }\n\n return {\n type: 'reasoning-file' as const,\n data: part.file.base64,\n mediaType: part.file.mediaType,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n };\n });\n}\n\nexport function convertToReasoningOutputs(\n parts: Array<ReasoningPart | ReasoningFilePart>,\n): Array<ReasoningOutput | ReasoningFileOutput> {\n return parts.map(part => {\n if (part.type === 'reasoning') {\n return {\n type: 'reasoning' as const,\n text: part.text,\n ...(part.providerOptions != null\n ? { providerMetadata: part.providerOptions as ProviderMetadata }\n : {}),\n };\n }\n\n const rawData = unwrapReasoningFileData(part.data);\n\n const fileData: string | Uint8Array =\n rawData instanceof ArrayBuffer\n ? new Uint8Array(rawData)\n : rawData instanceof URL\n ? rawData.toString()\n : (rawData as string | Uint8Array);\n\n return {\n type: 'reasoning-file' as const,\n file: new DefaultGeneratedFile({\n data: fileData,\n mediaType: part.mediaType,\n }),\n ...(part.providerOptions != null\n ? { providerMetadata: part.providerOptions as ProviderMetadata }\n : {}),\n };\n });\n}\n","import type {\n Context,\n InferToolSetContext,\n ReasoningFilePart,\n ReasoningPart,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n CallWarning,\n FinishReason,\n LanguageModelRequestMetadata,\n LanguageModelResponseMetadata,\n ProviderMetadata,\n} from '../types';\nimport type { Source } from '../types/language-model';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { ContentPart } from './content-part';\nimport type { GeneratedFile } from './generated-file';\nimport { asReasoningText } from './reasoning';\nimport {\n convertFromReasoningOutputs,\n type ReasoningFileOutput,\n type ReasoningOutput,\n} from './reasoning-output';\nimport type {\n DynamicToolCall,\n StaticToolCall,\n TypedToolCall,\n} from './tool-call';\nimport type {\n DynamicToolResult,\n StaticToolResult,\n TypedToolResult,\n} from './tool-result';\n\n/**\n * Timing statistics for the gaps between generated output chunks.\n */\nexport type OutputChunkTimingStats = {\n /** Shortest observed time between output chunks in milliseconds. */\n readonly min: number;\n\n /** 10th percentile time between output chunks in milliseconds. */\n readonly p10: number;\n\n /** Median time between output chunks in milliseconds. */\n readonly median: number;\n\n /** Average time between output chunks in milliseconds. */\n readonly avg: number;\n\n /** 90th percentile time between output chunks in milliseconds. */\n readonly p90: number;\n\n /** Longest observed time between output chunks in milliseconds. */\n readonly max: number;\n};\n\n/**\n * Performance metrics for a single step in the generation process.\n */\nexport type StepResultPerformance = {\n /**\n * Effective number of output tokens per second over the full language model\n * response.\n *\n * Calculated as `outputTokens / requestSeconds`.\n */\n readonly effectiveOutputTokensPerSecond: number;\n\n /**\n * Number of output tokens per second after the first generated output chunk\n * was received.\n *\n * Only available for streaming steps.\n *\n * Calculated as `outputTokens / outputStreamSeconds`.\n */\n readonly outputTokensPerSecond: number | undefined;\n\n /**\n * Number of input tokens processed per second before the first generated\n * output chunk was received.\n *\n * Only available for streaming steps.\n *\n * Calculated as `inputTokens / ttftSeconds`.\n */\n readonly inputTokensPerSecond: number | undefined;\n\n /**\n * Effective number of input and output tokens per second over the full\n * language model response.\n *\n * Calculated as `(inputTokens + outputTokens) / requestSeconds`.\n */\n readonly effectiveTotalTokensPerSecond: number;\n\n /**\n * Total time spent on the step in milliseconds.\n */\n readonly stepTimeMs: number;\n\n /**\n * Time spent waiting for the language model response in milliseconds.\n */\n readonly responseTimeMs: number;\n\n /**\n * Time spent executing each client-side tool call in milliseconds, keyed by\n * tool call ID.\n */\n readonly toolExecutionMs: Readonly<Record<string, number>>;\n\n /**\n * Time until the first generated output chunk was received in milliseconds.\n *\n * This includes text deltas, reasoning deltas, generated files, reasoning\n * files, tool input deltas, and tool calls.\n *\n * Only available for streaming steps.\n */\n readonly timeToFirstOutputMs: number | undefined;\n\n /**\n * Timing statistics for the gaps between generated output chunks in\n * milliseconds.\n *\n * Only available for streaming steps with at least two generated output\n * chunks.\n */\n readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats;\n};\n\n/**\n * The result of a single step in the generation process.\n */\nexport type StepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context = Context,\n> = {\n /**\n * Unique identifier for the generation call this step belongs to.\n */\n readonly callId: string;\n\n /**\n * Zero-based index of this step.\n */\n readonly stepNumber: number;\n\n /**\n * Information about the model that produced this step.\n */\n readonly model: {\n /** The provider of the model. */\n readonly provider: string;\n\n /** The ID of the model. */\n readonly modelId: string;\n };\n\n /**\n * Tool context.\n */\n readonly toolsContext: InferToolSetContext<TOOLS>;\n\n /**\n * The runtime context that was used as input for the step.\n */\n readonly runtimeContext: RUNTIME_CONTEXT;\n\n /**\n * The content that was generated in the last step.\n */\n readonly content: Array<ContentPart<TOOLS>>;\n\n /**\n * The generated text. Can be an empty string if the model has not generated any text.\n */\n readonly text: string;\n\n /**\n * The reasoning that was generated during the generation.\n */\n readonly reasoning: Array<ReasoningPart | ReasoningFilePart>;\n\n /**\n * The reasoning text that was generated during the generation.\n *\n * It is a concatenation of all reasoning parts (but excluding reasoning file parts).\n * Can be undefined if the model has only generated text.\n */\n readonly reasoningText: string | undefined;\n\n /**\n * The files that were generated during the generation.\n */\n readonly files: Array<GeneratedFile>;\n\n /**\n * The sources that were used to generate the text.\n */\n readonly sources: Array<Source>;\n\n /**\n * The tool calls that were made during the generation.\n */\n readonly toolCalls: Array<TypedToolCall<TOOLS>>;\n\n /**\n * The static tool calls that were made in the last step.\n */\n readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;\n\n /**\n * The dynamic tool calls that were made in the last step.\n */\n readonly dynamicToolCalls: Array<DynamicToolCall>;\n\n /**\n * The results of the tool calls.\n */\n readonly toolResults: Array<TypedToolResult<TOOLS>>;\n\n /**\n * The static tool results that were made in the last step.\n */\n readonly staticToolResults: Array<StaticToolResult<TOOLS>>;\n\n /**\n * The dynamic tool results that were made in the last step.\n */\n readonly dynamicToolResults: Array<DynamicToolResult>;\n\n /**\n * The unified reason why the generation finished.\n */\n readonly finishReason: FinishReason;\n\n /**\n * The raw reason why the generation finished (from the provider).\n */\n readonly rawFinishReason: string | undefined;\n\n /**\n * The token usage of the generated text.\n */\n readonly usage: LanguageModelUsage;\n\n /**\n * Performance metrics for the step.\n */\n readonly performance: StepResultPerformance;\n\n /**\n * Warnings from the model provider (e.g. unsupported settings).\n */\n readonly warnings: CallWarning[] | undefined;\n\n /**\n * Additional request information.\n */\n readonly request: LanguageModelRequestMetadata;\n\n /**\n * Additional response information.\n */\n readonly response: LanguageModelResponseMetadata;\n\n /**\n * Additional provider-specific metadata. They are passed through\n * from the provider to the AI SDK and enable provider-specific\n * results that can be fully encapsulated in the provider.\n */\n readonly providerMetadata: ProviderMetadata | undefined;\n};\n\nexport class DefaultStepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context = Context,\n> implements StepResult<TOOLS, RUNTIME_CONTEXT> {\n readonly callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n readonly stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n readonly model: StepResult<TOOLS, RUNTIME_CONTEXT>['model'];\n readonly toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n readonly runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n readonly content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n readonly finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n readonly rawFinishReason: StepResult<\n TOOLS,\n RUNTIME_CONTEXT\n >['rawFinishReason'];\n readonly usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n readonly performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n readonly warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n readonly response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n readonly providerMetadata: StepResult<\n TOOLS,\n RUNTIME_CONTEXT\n >['providerMetadata'];\n\n constructor({\n callId,\n stepNumber,\n provider,\n modelId,\n runtimeContext,\n toolsContext,\n content,\n finishReason,\n rawFinishReason,\n usage,\n performance,\n warnings,\n request,\n response,\n providerMetadata,\n }: {\n callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n provider: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['provider'];\n modelId: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['modelId'];\n runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];\n usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];\n }) {\n this.callId = callId;\n this.stepNumber = stepNumber;\n this.model = { provider, modelId };\n this.runtimeContext = runtimeContext;\n this.toolsContext = toolsContext;\n this.content = content;\n this.finishReason = finishReason;\n this.rawFinishReason = rawFinishReason;\n this.usage = usage;\n this.performance = performance;\n this.warnings = warnings;\n this.request = request;\n this.response = response;\n this.providerMetadata = providerMetadata;\n }\n\n get text() {\n return this.content\n .filter(part => part.type === 'text')\n .map(part => part.text)\n .join('');\n }\n\n get reasoning(): Array<ReasoningPart | ReasoningFilePart> {\n return convertFromReasoningOutputs(\n this.content.filter(\n (part): part is ReasoningOutput | ReasoningFileOutput =>\n part.type === 'reasoning' || part.type === 'reasoning-file',\n ),\n );\n }\n\n get reasoningText() {\n return asReasoningText(this.reasoning);\n }\n\n get files() {\n return this.content\n .filter(part => part.type === 'file')\n .map(part => part.file);\n }\n\n get sources() {\n return this.content.filter(part => part.type === 'source');\n }\n\n get toolCalls() {\n return this.content.filter(part => part.type === 'tool-call');\n }\n\n get staticToolCalls() {\n return this.toolCalls.filter(\n (toolCall): toolCall is StaticToolCall<TOOLS> =>\n toolCall.dynamic !== true,\n );\n }\n\n get dynamicToolCalls() {\n return this.toolCalls.filter(\n (toolCall): toolCall is DynamicToolCall => toolCall.dynamic === true,\n );\n }\n\n get toolResults() {\n return this.content.filter(part => part.type === 'tool-result');\n }\n\n get staticToolResults() {\n return this.toolResults.filter(\n (toolResult): toolResult is StaticToolResult<TOOLS> =>\n toolResult.dynamic !== true,\n );\n }\n\n get dynamicToolResults() {\n return this.toolResults.filter(\n (toolResult): toolResult is DynamicToolResult =>\n toolResult.dynamic === true,\n );\n }\n}\n","import type {\n Context,\n InferToolContext,\n InferToolSetContext,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type {\n IncludedContext,\n IncludedToolsContext,\n TelemetryOptions,\n} from '../telemetry/telemetry-options';\nimport type {\n GenerateTextOnAbortCallback,\n GenerateTextOnEndCallback,\n GenerateTextOnStartCallback,\n GenerateTextOnStepEndCallback,\n GenerateTextOnStepFinishCallback,\n GenerateTextOnStepStartCallback,\n} from './generate-text-events';\nimport type { Output } from './output';\nimport { DefaultStepResult, type StepResult } from './step-result';\nimport type {\n OnToolExecutionEndCallback,\n OnToolExecutionStartCallback,\n} from './tool-execution-events';\n\n/**\n * Telemetry dispatcher for text generation with callbacks typed to the\n * operation-specific tool set, runtime context, and output shape.\n */\nexport type RestrictedTelemetryDispatcher<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n OUTPUT extends Output,\n> = Omit<\n TelemetryDispatcher,\n | 'onStart'\n | 'onStepStart'\n | 'onStepEnd'\n | 'onStepFinish'\n | 'onEnd'\n | 'onAbort'\n | 'onToolExecutionStart'\n | 'onToolExecutionEnd'\n> & {\n onStart: GenerateTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n onStepStart: GenerateTextOnStepStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n onStepEnd: GenerateTextOnStepEndCallback<TOOLS, RUNTIME_CONTEXT>;\n /** @deprecated Use `onStepEnd` instead. */\n onStepFinish: GenerateTextOnStepFinishCallback<TOOLS, RUNTIME_CONTEXT>;\n onEnd: GenerateTextOnEndCallback<TOOLS, RUNTIME_CONTEXT>;\n onAbort?: GenerateTextOnAbortCallback<TOOLS, RUNTIME_CONTEXT>;\n onToolExecutionStart?: OnToolExecutionStartCallback<TOOLS>;\n onToolExecutionEnd?: OnToolExecutionEndCallback<TOOLS>;\n};\n\n/**\n * Returns a shallow copy of the runtime context with only top-level\n * properties marked for telemetry inclusion.\n */\nfunction filterIncludedContext<CONTEXT extends Context>({\n context,\n includeContext,\n}: {\n context: CONTEXT;\n includeContext: IncludedContext<CONTEXT>;\n}): Context {\n if (context == null) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(context).filter(\n ([key]) => includeContext?.[key as keyof CONTEXT] === true,\n ),\n );\n}\n\n/**\n * Creates a copy of a step result whose runtime context only contains\n * top-level properties marked for telemetry inclusion.\n */\nfunction restrictStepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n>({\n step,\n includeRuntimeContext,\n includeToolsContext,\n}: {\n step: StepResult<TOOLS, RUNTIME_CONTEXT>;\n includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n return new DefaultStepResult({\n callId: step.callId,\n stepNumber: step.stepNumber,\n provider: step.model.provider,\n modelId: step.model.modelId,\n runtimeContext: filterIncludedContext({\n context: step.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n toolsContext: filterToolsContext({\n toolsContext: step.toolsContext,\n includeToolsContext,\n }),\n content: step.content,\n finishReason: step.finishReason,\n rawFinishReason: step.rawFinishReason,\n usage: step.usage,\n performance: step.performance,\n warnings: step.warnings,\n request: step.request,\n response: step.response,\n providerMetadata: step.providerMetadata,\n });\n}\n\n/**\n * Returns a shallow copy of the tools context with only top-level properties\n * marked for telemetry inclusion for each tool.\n */\nfunction filterToolsContext<TOOLS extends ToolSet>({\n toolsContext,\n includeToolsContext,\n}: {\n toolsContext: InferToolSetContext<TOOLS>;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}): InferToolSetContext<TOOLS> {\n if (includeToolsContext == null) {\n return {} as InferToolSetContext<TOOLS>;\n }\n\n return Object.fromEntries(\n Object.entries(toolsContext).map(([toolName, toolContext]) => [\n toolName,\n filterToolContext({\n toolName,\n toolContext,\n includeToolsContext,\n }),\n ]),\n ) as InferToolSetContext<TOOLS>;\n}\n\nfunction filterToolContext<TOOLS extends ToolSet>({\n toolName,\n toolContext,\n includeToolsContext,\n}: {\n toolName: string;\n toolContext: unknown;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n const includeToolContext = (\n includeToolsContext as\n | Record<\n string,\n IncludedContext<InferToolContext<TOOLS[typeof toolName]>>\n >\n | undefined\n )?.[toolName];\n\n return filterIncludedContext({\n context: toolContext as InferToolContext<TOOLS[typeof toolName]>,\n includeContext: includeToolContext,\n });\n}\n\n/**\n * Creates a telemetry dispatcher that only includes configured runtime context\n * properties in text-generation lifecycle events before dispatching them.\n */\nexport function createRestrictedTelemetryDispatcher<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n OUTPUT extends Output,\n>({\n telemetry,\n includeRuntimeContext,\n includeToolsContext,\n}: {\n telemetry?: TelemetryOptions<RUNTIME_CONTEXT, TOOLS>;\n includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n includeToolsContext?: IncludedToolsContext<TOOLS>;\n}): RestrictedTelemetryDispatcher<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n const telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\n return {\n ...telemetryDispatcher,\n onStart: event =>\n telemetryDispatcher.onStart?.({\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n }),\n onStepStart: event =>\n telemetryDispatcher.onStepStart?.({\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n steps: event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n }),\n onStepEnd: event =>\n telemetryDispatcher.onStepEnd?.(\n restrictStepResult({\n step: event,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n onStepFinish: event =>\n telemetryDispatcher.onStepEnd?.(\n restrictStepResult({\n step: event,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n onEnd: event =>\n telemetryDispatcher.onEnd?.(\n ((restrictedSteps: StepResult<TOOLS, Context>[]) => {\n return {\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n steps: restrictedSteps,\n finalStep: restrictedSteps.at(-1)!,\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n };\n })(\n event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n ),\n ),\n onAbort: event =>\n telemetryDispatcher.onAbort?.({\n ...event,\n steps: event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n }),\n onToolExecutionStart: event =>\n telemetryDispatcher.onToolExecutionStart?.({\n ...event,\n toolContext: filterToolContext({\n toolName: event.toolCall.toolName,\n toolContext: event.toolContext,\n includeToolsContext,\n }),\n }),\n onToolExecutionEnd: event =>\n telemetryDispatcher.onToolExecutionEnd?.({\n ...event,\n toolContext: filterToolContext({\n toolName: event.toolCall.toolName,\n toolContext: event.toolContext,\n includeToolsContext,\n }),\n }),\n };\n}\n","import type { LanguageModelV4ToolCall } from '@ai-sdk/provider';\nimport {\n asSchema,\n safeParseJSON,\n safeValidateTypes,\n type InferToolInput,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport { NoSuchToolError } from '../error/no-such-tool-error';\nimport { ToolCallRepairError } from '../error/tool-call-repair-error';\nimport type { Instructions } from '../prompt';\nimport type { DynamicToolCall, TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { ToolInputRefinement } from './tool-input-refinement';\n\nexport async function parseToolCall<TOOLS extends ToolSet>({\n toolCall,\n tools,\n repairToolCall,\n refineToolInput,\n messages,\n instructions,\n}: {\n toolCall: LanguageModelV4ToolCall;\n tools: TOOLS | undefined;\n repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n refineToolInput?: ToolInputRefinement<TOOLS> | undefined;\n instructions: Instructions | undefined;\n messages: ModelMessage[];\n}): Promise<TypedToolCall<TOOLS>> {\n try {\n if (tools == null) {\n // provider-executed dynamic tools are not part of our list of tools:\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await refineParsedToolCallInput({\n toolCall: await parseProviderExecutedDynamicToolCall(toolCall),\n refineToolInput,\n });\n }\n\n throw new NoSuchToolError({ toolName: toolCall.toolName });\n }\n\n try {\n return await refineParsedToolCallInput({\n toolCall: await doParseToolCall({ toolCall, tools }),\n refineToolInput,\n });\n } catch (error) {\n if (\n repairToolCall == null ||\n !(\n NoSuchToolError.isInstance(error) ||\n InvalidToolInputError.isInstance(error)\n )\n ) {\n throw error;\n }\n\n let repairedToolCall: LanguageModelV4ToolCall | null = null;\n\n try {\n repairedToolCall = await repairToolCall({\n toolCall,\n tools,\n inputSchema: async ({ toolName }) => {\n const { inputSchema } = tools[toolName];\n return await asSchema(inputSchema).jsonSchema;\n },\n instructions,\n system: instructions,\n messages,\n error,\n });\n } catch (repairError) {\n throw new ToolCallRepairError({\n cause: repairError,\n originalError: error,\n });\n }\n\n // no repaired tool call returned\n if (repairedToolCall == null) {\n throw error;\n }\n\n return await refineParsedToolCallInput({\n toolCall: await doParseToolCall({ toolCall: repairedToolCall, tools }),\n refineToolInput,\n });\n }\n } catch (error) {\n // use parsed input when possible\n const parsedInput = await safeParseJSON({ text: toolCall.input });\n const input = parsedInput.success ? parsedInput.value : toolCall.input;\n const tool = tools?.[toolCall.toolName];\n\n // TODO AI SDK 6: special invalid tool call parts\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input,\n dynamic: true,\n invalid: true,\n error,\n title: tool?.title,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool?.metadata != null ? { toolMetadata: tool.metadata } : {}),\n };\n }\n}\n\nasync function refineParsedToolCallInput<TOOLS extends ToolSet>({\n toolCall,\n refineToolInput,\n}: {\n toolCall: TypedToolCall<TOOLS>;\n refineToolInput: ToolInputRefinement<TOOLS> | undefined;\n}): Promise<TypedToolCall<TOOLS>> {\n const refine = refineToolInput?.[toolCall.toolName];\n\n if (refine == null) {\n return toolCall;\n }\n\n return {\n ...toolCall,\n input: await refine(toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>),\n } as TypedToolCall<TOOLS>;\n}\n\nasync function parseProviderExecutedDynamicToolCall(\n toolCall: LanguageModelV4ToolCall,\n): Promise<DynamicToolCall> {\n const parseResult =\n toolCall.input.trim() === ''\n ? { success: true as const, value: {} }\n : await safeParseJSON({ text: toolCall.input });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName: toolCall.toolName,\n toolInput: toolCall.input,\n cause: parseResult.error,\n });\n }\n\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: toolCall.providerMetadata,\n };\n}\n\nasync function doParseToolCall<TOOLS extends ToolSet>({\n toolCall,\n tools,\n}: {\n toolCall: LanguageModelV4ToolCall;\n tools: TOOLS;\n}): Promise<TypedToolCall<TOOLS>> {\n const toolName = toolCall.toolName as keyof TOOLS & string;\n\n const tool = tools[toolName];\n\n if (tool == null) {\n // provider-executed dynamic tools are not part of our list of tools:\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await parseProviderExecutedDynamicToolCall(toolCall);\n }\n\n throw new NoSuchToolError({\n toolName: toolCall.toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n const schema = asSchema(tool.inputSchema);\n\n // when the tool call has no arguments, we try passing an empty object to the schema\n // (many LLMs generate empty strings for tool calls with no arguments)\n const parseResult =\n toolCall.input.trim() === ''\n ? await safeValidateTypes({ value: {}, schema })\n : await safeParseJSON({ text: toolCall.input, schema });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: toolCall.input,\n cause: parseResult.error,\n });\n }\n\n return tool.type === 'dynamic'\n ? {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n dynamic: true,\n title: tool.title,\n }\n : {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n title: tool.title,\n };\n}\n","import type {\n ModelMessage,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalError } from '../error/invalid-tool-approval-error';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport type { TypedToolCall } from './tool-call';\nimport type { TypedToolResult } from './tool-result';\n\nexport type CollectedToolApprovals<TOOLS extends ToolSet> = {\n approvalRequest: ToolApprovalRequest;\n approvalResponse: ToolApprovalResponse;\n toolCall: TypedToolCall<TOOLS>;\n};\n\n/**\n * If the last message is a tool message, this function collects all tool approvals\n * from that message.\n */\nexport function collectToolApprovals<TOOLS extends ToolSet>({\n messages,\n}: {\n messages: ModelMessage[];\n}): {\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n} {\n const lastMessage = messages.at(-1);\n\n if (lastMessage?.role != 'tool') {\n return {\n approvedToolApprovals: [],\n deniedToolApprovals: [],\n };\n }\n\n // gather tool calls and prepare lookup\n const toolCallsByToolCallId: Record<string, TypedToolCall<TOOLS>> = {};\n for (const message of messages) {\n if (message.role === 'assistant' && typeof message.content !== 'string') {\n const content = message.content;\n for (const part of content) {\n if (part.type === 'tool-call') {\n toolCallsByToolCallId[part.toolCallId] = part as TypedToolCall<TOOLS>;\n }\n }\n }\n }\n\n // gather approval responses and prepare lookup\n const toolApprovalRequestsByApprovalId: Record<string, ToolApprovalRequest> =\n {};\n for (const message of messages) {\n if (message.role === 'assistant' && typeof message.content !== 'string') {\n const content = message.content;\n for (const part of content) {\n if (part.type === 'tool-approval-request') {\n toolApprovalRequestsByApprovalId[part.approvalId] = part;\n }\n }\n }\n }\n\n // gather tool results from the last tool message\n const toolResults: Record<string, TypedToolResult<TOOLS>> = {};\n for (const part of lastMessage.content) {\n if (part.type === 'tool-result') {\n toolResults[part.toolCallId] = part as TypedToolResult<TOOLS>;\n }\n }\n\n const approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n const deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n\n const approvalResponses = lastMessage.content.filter(\n part => part.type === 'tool-approval-response',\n );\n for (const approvalResponse of approvalResponses) {\n const approvalRequest =\n toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\n if (approvalRequest == null) {\n throw new InvalidToolApprovalError({\n approvalId: approvalResponse.approvalId,\n });\n }\n\n if (toolResults[approvalRequest.toolCallId] != null) {\n continue;\n }\n\n const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n if (toolCall == null) {\n throw new ToolCallNotFoundForApprovalError({\n toolCallId: approvalRequest.toolCallId,\n approvalId: approvalRequest.approvalId,\n });\n }\n\n const approval: CollectedToolApprovals<TOOLS> = {\n approvalRequest,\n approvalResponse,\n toolCall,\n };\n\n if (approvalResponse.approved) {\n approvedToolApprovals.push(approval);\n } else {\n deniedToolApprovals.push(approval);\n }\n }\n\n return { approvedToolApprovals, deniedToolApprovals };\n}\n","import {\n asSchema,\n isExecutableTool,\n safeValidateTypes,\n type Context,\n type InferToolSetContext,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalSignatureError } from '../error/invalid-tool-approval-signature-error';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport type { CollectedToolApprovals } from './collect-tool-approvals';\nimport { resolveToolApproval } from './resolve-tool-approval';\nimport { verifyToolApprovalSignature } from './tool-approval-signature';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\n\n/**\n * Re-validates approved tool approvals reconstructed from client-supplied\n * message history before they are executed. Checks HMAC signature (when\n * configured), input schema, and approval policy.\n */\nexport async function validateApprovedToolApprovals<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n approvedToolApprovals,\n tools,\n toolApproval,\n messages,\n toolsContext,\n runtimeContext,\n toolApprovalSecret,\n}: {\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n tools: TOOLS | undefined;\n toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n messages: ModelMessage[];\n toolsContext: InferToolSetContext<TOOLS>;\n runtimeContext: RUNTIME_CONTEXT;\n toolApprovalSecret?: string | Uint8Array;\n}): Promise<{\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n}> {\n const approved: Array<CollectedToolApprovals<TOOLS>> = [];\n const denied: Array<CollectedToolApprovals<TOOLS>> = [];\n\n for (const approval of approvedToolApprovals) {\n const { toolCall, approvalRequest } = approval;\n const tool = tools?.[toolCall.toolName];\n\n if (toolApprovalSecret != null) {\n if (approvalRequest.signature == null) {\n throw new InvalidToolApprovalSignatureError({\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n reason: 'missing signature',\n });\n }\n\n const valid = await verifyToolApprovalSignature({\n secret: toolApprovalSecret,\n signature: approvalRequest.signature,\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n });\n\n if (!valid) {\n throw new InvalidToolApprovalSignatureError({\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n reason: 'invalid signature',\n });\n }\n }\n\n if (isExecutableTool(tool) && tool.inputSchema != null) {\n const validation = await safeValidateTypes({\n value: toolCall.input,\n schema: asSchema(tool.inputSchema),\n });\n\n if (!validation.success) {\n throw new InvalidToolInputError({\n toolName: toolCall.toolName,\n toolInput: JSON.stringify(toolCall.input),\n cause: validation.error,\n });\n }\n }\n\n const approvalStatus = await resolveToolApproval({\n tools,\n toolApproval,\n toolCall,\n messages,\n toolsContext,\n runtimeContext,\n });\n\n if (approvalStatus.type === 'denied') {\n denied.push({\n ...approval,\n approvalResponse: {\n ...approval.approvalResponse,\n approved: false,\n reason: approvalStatus.reason ?? approval.approvalResponse.reason,\n },\n });\n } else {\n approved.push(approval);\n }\n }\n\n return { approvedToolApprovals: approved, deniedToolApprovals: denied };\n}\n","import { validateTypes, type FlexibleSchema } from '@ai-sdk/provider-utils';\n/**\n * Validates a tool context value against the tool's optional context schema.\n *\n * When no context schema is defined, the original context value is returned as-is.\n * Otherwise, the context is validated and normalized through the schema before\n * being passed into tool execution and approval hooks.\n *\n * @throws {TypeValidationError} When the provided tool context does not match\n * the tool's declared `contextSchema`.\n */\nexport async function validateToolContext<CONTEXT>({\n toolName,\n context,\n contextSchema,\n}: {\n toolName: string;\n context: unknown;\n contextSchema: FlexibleSchema<CONTEXT> | undefined;\n}): Promise<CONTEXT> {\n if (contextSchema == null) {\n return context as CONTEXT;\n }\n\n return await validateTypes({\n value: context,\n schema: contextSchema,\n context: {\n field: 'tool context',\n entityName: toolName,\n },\n });\n}\n","import type {\n Context,\n InferToolInput,\n InferToolSetContext,\n ModelMessage,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n ToolApprovalConfiguration,\n ToolApprovalStatus,\n} from './tool-approval-configuration';\nimport type { TypedToolCall } from './tool-call';\nimport { validateToolContext } from './validate-tool-context';\n\n/**\n * Resolves the approval state for a tool call by checking user-supplied and tool-defined\n * approval settings, and normalizes the result to the object status shape.\n * User-defined approval settings take precedence over tool-defined settings.\n * If no approval settings are provided, the tool call does not require approval.\n */\nexport async function resolveToolApproval<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n tools,\n toolCall,\n toolApproval,\n messages,\n toolsContext,\n runtimeContext,\n}: {\n /**\n * Tools that are available for the model to call.\n */\n tools: TOOLS | undefined;\n\n /**\n * Valid tool call.\n */\n toolCall: TypedToolCall<TOOLS>;\n\n /**\n * User-defined approval configuration for tools.\n *\n * This configuration takes precedence over tool-defined approval settings.\n */\n toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n\n /**\n * Messages that were sent to the language model to initiate the response that contained the tool call.\n */\n messages: ModelMessage[];\n\n /**\n * Tool context as defined by the tool's context schema.\n */\n toolsContext: InferToolSetContext<TOOLS>;\n\n /**\n * User-defined runtime context (same as `runtimeContext` on `generateText` / `streamText`).\n */\n runtimeContext: RUNTIME_CONTEXT;\n}): Promise<Exclude<ToolApprovalStatus, string | undefined>> {\n // user-defined generic tool approval\n if (toolApproval != null && typeof toolApproval === 'function') {\n return normalizeToolApprovalStatus(\n await toolApproval({\n toolCall,\n tools,\n toolsContext,\n messages,\n runtimeContext,\n }),\n );\n }\n\n const toolName = toolCall.toolName;\n const tool = tools?.[toolName];\n\n // assume that the input has been validated and matches the tool's input schema\n const input = toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>;\n\n // user-defined per-tool approval\n const userDefinedToolApprovalStatus = toolApproval?.[toolName];\n if (userDefinedToolApprovalStatus != null) {\n const approvalStatus: ToolApprovalStatus | undefined =\n typeof userDefinedToolApprovalStatus === 'function'\n ? await userDefinedToolApprovalStatus(input, {\n toolCallId: toolCall.toolCallId,\n messages,\n toolContext: await validateToolContext({\n toolName,\n context:\n toolsContext?.[toolName as keyof InferToolSetContext<TOOLS>],\n contextSchema: tool?.contextSchema,\n }),\n runtimeContext,\n })\n : userDefinedToolApprovalStatus;\n\n return normalizeToolApprovalStatus(approvalStatus);\n }\n\n // tool-defined approval\n if (tool?.needsApproval == null) {\n return { type: 'not-applicable' };\n }\n\n const needsApproval =\n typeof tool.needsApproval === 'function'\n ? await tool.needsApproval(input, {\n toolCallId: toolCall.toolCallId,\n messages,\n context: await validateToolContext({\n toolName,\n context:\n toolsContext?.[toolName as keyof InferToolSetContext<TOOLS>],\n contextSchema: tool?.contextSchema,\n }),\n })\n : tool.needsApproval;\n\n return needsApproval ? { type: 'user-approval' } : { type: 'not-applicable' };\n}\n\nfunction normalizeToolApprovalStatus(\n status: ToolApprovalStatus | undefined,\n): Exclude<ToolApprovalStatus, string | undefined> {\n return status === undefined\n ? { type: 'not-applicable' }\n : typeof status === 'string'\n ? { type: status }\n : status;\n}\n","import {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\n\nconst encoder = new TextEncoder();\n\nfunction canonicalJSON(value: unknown): string {\n if (value === null || value === undefined) {\n return JSON.stringify(value);\n }\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJSON).join(',')}]`;\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const entries = keys.map(\n k =>\n `${JSON.stringify(k)}:${canonicalJSON((value as Record<string, unknown>)[k])}`,\n );\n return `{${entries.join(',')}}`;\n}\n\nfunction toBase64url(bytes: Uint8Array): string {\n return convertUint8ArrayToBase64(bytes)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n}\n\nfunction fromBase64url(str: string): Uint8Array {\n return convertBase64ToUint8Array(str);\n}\n\nasync function importKey(secret: string | Uint8Array): Promise<CryptoKey> {\n const keyData = typeof secret === 'string' ? encoder.encode(secret) : secret;\n return crypto.subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n}\n\nasync function hashInput(input: unknown): Promise<string> {\n const canonical = canonicalJSON(input);\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n encoder.encode(canonical),\n );\n return toBase64url(new Uint8Array(digest));\n}\n\nfunction buildPayload(\n approvalId: string,\n toolCallId: string,\n toolName: string,\n inputDigest: string,\n): Uint8Array {\n return encoder.encode(\n `${approvalId}\\n${toolCallId}\\n${toolName}\\n${inputDigest}`,\n );\n}\n\nexport async function signToolApproval({\n secret,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<string> {\n const key = await importKey(secret);\n const inputDigest = await hashInput(input);\n const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n const sig = await crypto.subtle.sign('HMAC', key, payload);\n return toBase64url(new Uint8Array(sig));\n}\n\nexport async function verifyToolApprovalSignature({\n secret,\n signature,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array;\n signature: string;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<boolean> {\n const key = await importKey(secret);\n const inputDigest = await hashInput(input);\n const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n const sigBytes = fromBase64url(signature);\n return crypto.subtle.verify('HMAC', key, sigBytes, payload);\n}\n\nexport async function maybeSignApproval({\n secret,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array | undefined;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<string | undefined> {\n if (secret == null) return undefined;\n return signToolApproval({ secret, approvalId, toolCallId, toolName, input });\n}\n","import type {\n AssistantContent,\n AssistantModelMessage,\n ToolContent,\n ToolModelMessage,\n} from '../prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport type { ContentPart } from './content-part';\nimport type { ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Converts the result of a `generateText` or `streamText` call to a list of response messages.\n */\nexport async function toResponseMessages<TOOLS extends ToolSet>({\n content: inputContent,\n tools,\n}: {\n content: Array<ContentPart<TOOLS>>;\n tools: TOOLS | undefined;\n}): Promise<Array<AssistantModelMessage | ToolModelMessage>> {\n const responseMessages: Array<AssistantModelMessage | ToolModelMessage> = [];\n\n const content: AssistantContent = [];\n for (const part of inputContent) {\n // Skip sources - they are response-only content that no provider expects back\n if (part.type === 'source') {\n continue;\n }\n\n // Skip non-provider-executed tool results/errors (they go in the tool message)\n if (\n (part.type === 'tool-result' || part.type === 'tool-error') &&\n !part.providerExecuted\n ) {\n continue;\n }\n\n // Skip empty text\n if (part.type === 'text' && part.text.length === 0) {\n continue;\n }\n\n switch (part.type) {\n case 'text':\n content.push({\n type: 'text',\n text: part.text,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'custom':\n content.push({\n type: 'custom',\n kind: part.kind,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'reasoning':\n content.push({\n type: 'reasoning',\n text: part.text,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'file':\n content.push({\n type: 'file',\n data: part.file.base64,\n mediaType: part.file.mediaType,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'reasoning-file':\n content.push({\n type: 'reasoning-file',\n data: part.file.base64,\n mediaType: part.file.mediaType,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'tool-call':\n content.push({\n type: 'tool-call',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input:\n part.invalid && typeof part.input !== 'object' ? {} : part.input,\n providerExecuted: part.providerExecuted,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'tool-result': {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.output,\n errorMode: 'none',\n });\n content.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata,\n });\n break;\n }\n case 'tool-error': {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.error,\n errorMode: 'json',\n });\n content.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata,\n });\n break;\n }\n case 'tool-approval-request':\n content.push({\n type: 'tool-approval-request',\n approvalId: part.approvalId,\n toolCallId: part.toolCall.toolCallId,\n isAutomatic: part.isAutomatic,\n ...(part.signature != null ? { signature: part.signature } : {}),\n });\n break;\n }\n }\n\n if (content.length > 0) {\n responseMessages.push({\n role: 'assistant',\n content,\n });\n }\n\n const toolResultContent: ToolContent = [];\n for (const part of inputContent) {\n if (\n part.type !== 'tool-approval-response' &&\n part.type !== 'tool-result' &&\n part.type !== 'tool-error'\n ) {\n continue;\n }\n\n if (part.type === 'tool-approval-response') {\n toolResultContent.push({\n type: 'tool-approval-response',\n approvalId: part.approvalId,\n approved: part.approved,\n reason: part.reason,\n providerExecuted: part.providerExecuted,\n });\n\n // when the tool approval is denied,\n // we need to add an execution-denied tool result\n // since there is no corresponding tool result for the tool call\n if (part.approved === false) {\n toolResultContent.push({\n type: 'tool-result',\n toolCallId: part.toolCall.toolCallId,\n toolName: part.toolCall.toolName,\n output: {\n type: 'execution-denied' as const,\n reason: part.reason,\n },\n });\n }\n continue;\n }\n\n if (part.providerExecuted) {\n continue;\n }\n\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.type === 'tool-result' ? part.output : part.error,\n errorMode: part.type === 'tool-error' ? 'text' : 'none',\n });\n\n toolResultContent.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n });\n }\n\n if (toolResultContent.length > 0) {\n responseMessages.push({\n role: 'tool',\n content: toolResultContent,\n });\n }\n\n return responseMessages;\n}\n"],"mappings":";AAIA,SAAS,4CAA4C;;;ACU9C,SAAS,0BACd,QACwB;AAExB,QAAM,SAAS,OAAO,YAAY,IAAI,gBAAsB,CAAC;AAM7D,EAAC,OAAkC,OAAO,aAAa,IAAI,WAEvC;AAClB,UAAM,SAAS,KAAK,UAAU;AAE9B,QAAI,WAAW;AAKf,mBAAe,QAAQ,cAAuB;AAlClD,UAAAA;AAmCM,UAAI;AAAU;AAEd,iBAAW;AACX,UAAI;AACF,YAAI,cAAc;AAChB,kBAAMA,OAAA,OAAO,WAAP,gBAAAA,KAAA;AAAA,QACR;AAAA,MACF,UAAE;AACA,YAAI;AACF,iBAAO,YAAY;AAAA,QACrB,SAAQ;AAAA,QAAC;AAAA,MACX;AAAA,IACF;AAEA,WAAO;AAAA;AAAA;AAAA;AAAA;AAAA,MAKL,MAAM,OAAmC;AACvC,YAAI,UAAU;AACZ,iBAAO,EAAE,MAAM,MAAM,OAAO,OAAU;AAAA,QACxC;AAEA,cAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAE1C,YAAI,MAAM;AACR,gBAAM,QAAQ,IAAI;AAClB,iBAAO,EAAE,MAAM,MAAM,OAAO,OAAU;AAAA,QACxC;AAEA,eAAO,EAAE,MAAM,OAAO,MAAM;AAAA,MAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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_a","download","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","download","_a","name","asArray","z","z","z","z","isBuffer","z","z","isBuffer","z","asArray","z","AISDKError","name","marker","symbol","_a","getErrorMessage","AISDKError","name","marker","symbol","_a","getErrorMessage","_a","AISDKError","APICallError","InvalidPromptError","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","DownloadError","_a","asArray","_a","_a","_a","asArray","_a","_a","asSchema","safeValidateTypes","asSchema","safeValidateTypes","asSchema","safeValidateTypes","_a","safeValidateTypes","asSchema"]}
|
|
1
|
+
{"version":3,"sources":["../../internal/index.ts","../../src/util/async-iterable-stream.ts","../../src/prompt/convert-to-language-model-prompt.ts","../../src/util/download/download.ts","../../src/version.ts","../../src/util/download/download-function.ts","../../src/prompt/file-part-data.ts","../../src/prompt/invalid-data-content-error.ts","../../src/prompt/split-data-url.ts","../../src/logger/log-warnings.ts","../../src/prompt/invalid-message-role-error.ts","../../src/error/missing-tool-result-error.ts","../../src/prompt/create-tool-model-output.ts","../../src/prompt/prepare-tool-choice.ts","../../src/prompt/prepare-tools.ts","../../src/util/is-non-empty-object.ts","../../src/prompt/standardize-prompt.ts","../../src/prompt/message.ts","../../src/types/provider-metadata.ts","../../src/types/json-value.ts","../../src/prompt/content-part.ts","../../src/error/invalid-argument-error.ts","../../src/prompt/prepare-language-model-call-options.ts","../../src/util/retry-with-exponential-backoff.ts","../../src/util/retry-error.ts","../../src/util/prepare-retries.ts","../../src/types/usage.ts","../../src/model/resolve-model.ts","../../src/error/index.ts","../../src/error/invalid-tool-approval-error.ts","../../src/error/invalid-tool-approval-signature-error.ts","../../src/error/invalid-tool-input-error.ts","../../src/error/tool-call-not-found-for-approval-error.ts","../../src/error/no-such-tool-error.ts","../../src/error/tool-call-repair-error.ts","../../src/error/unsupported-model-version-error.ts","../../src/util/log-v2-compatibility-warning.ts","../../src/model/as-embedding-model-v3.ts","../../src/model/as-embedding-model-v4.ts","../../src/model/as-image-model-v3.ts","../../src/model/as-image-model-v4.ts","../../src/model/as-language-model-v3.ts","../../src/model/as-language-model-v4.ts","../../src/model/as-reranking-model-v4.ts","../../src/model/as-speech-model-v3.ts","../../src/model/as-speech-model-v4.ts","../../src/model/as-transcription-model-v3.ts","../../src/model/as-transcription-model-v4.ts","../../src/model/as-provider-v3.ts","../../src/model/as-provider-v4.ts","../../src/util/merge-abort-signals.ts","../../src/util/merge-callbacks.ts","../../src/telemetry/create-telemetry-dispatcher.ts","../../src/telemetry/tracing-channel.ts","../../src/util/is-node-runtime.ts","../../src/telemetry/tracing-channel-publisher.ts","../../src/telemetry/telemetry-registry.ts","../../src/generate-text/reasoning.ts","../../src/generate-text/reasoning-output.ts","../../src/generate-text/step-result.ts","../../src/generate-text/restricted-telemetry-dispatcher.ts","../../src/generate-text/parse-tool-call.ts","../../src/generate-text/collect-tool-approvals.ts","../../src/generate-text/validate-tool-approvals.ts","../../src/generate-text/validate-tool-context.ts","../../src/generate-text/resolve-tool-approval.ts","../../src/generate-text/tool-approval-signature.ts","../../src/generate-text/to-response-messages.ts"],"sourcesContent":["// import globals\nimport '../src/global';\n\n// internal re-exports\nexport { convertAsyncIteratorToReadableStream } from '@ai-sdk/provider-utils';\n\n// internal\nexport { createAsyncIterableStream } from '../src/util/async-iterable-stream';\nexport {\n convertToLanguageModelPrompt,\n downloadAssets,\n mapToolResultOutput,\n} from '../src/prompt/convert-to-language-model-prompt';\nexport { createToolModelOutput } from '../src/prompt/create-tool-model-output';\nexport {\n createDefaultDownloadFunction,\n type DownloadFunction,\n} from '../src/util/download/download-function';\nexport { prepareToolChoice } from '../src/prompt/prepare-tool-choice';\nexport { prepareTools } from '../src/prompt/prepare-tools';\nexport { standardizePrompt } from '../src/prompt/standardize-prompt';\nexport {\n prepareLanguageModelCallOptions,\n /** @deprecated Use `prepareLanguageModelCallOptions` instead. */\n prepareLanguageModelCallOptions as prepareCallSettings,\n} from '../src/prompt/prepare-language-model-call-options';\nexport { prepareRetries } from '../src/util/prepare-retries';\nexport {\n addLanguageModelUsage,\n asLanguageModelUsage,\n createNullLanguageModelUsage,\n} from '../src/types/usage';\nexport { resolveLanguageModel } from '../src/model/resolve-model';\nexport { mergeAbortSignals } from '../src/util/merge-abort-signals';\nexport { mergeCallbacks } from '../src/util/merge-callbacks';\nexport { createTelemetryDispatcher } from '../src/telemetry/create-telemetry-dispatcher';\nexport { createRestrictedTelemetryDispatcher } from '../src/generate-text/restricted-telemetry-dispatcher';\nexport { DefaultStepResult } from '../src/generate-text/step-result';\nexport { parseToolCall } from '../src/generate-text/parse-tool-call';\nexport {\n collectToolApprovals,\n type CollectedToolApprovals,\n} from '../src/generate-text/collect-tool-approvals';\nexport { validateApprovedToolApprovals } from '../src/generate-text/validate-tool-approvals';\nexport { toResponseMessages } from '../src/generate-text/to-response-messages';\n","/**\n * A type that combines AsyncIterable and ReadableStream.\n * This allows a ReadableStream to be consumed using for-await-of syntax.\n */\nexport type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;\n\n/**\n * Wraps a ReadableStream and returns an object that is both a ReadableStream and an AsyncIterable.\n * This enables consumption of the stream using for-await-of, with proper resource cleanup on early exit or error.\n *\n * @template T The type of the stream's chunks.\n * @param source The source ReadableStream to wrap.\n * @returns An AsyncIterableStream that can be used as both a ReadableStream and an AsyncIterable.\n */\nexport function createAsyncIterableStream<T>(\n source: ReadableStream<T>,\n): AsyncIterableStream<T> {\n // Pipe through a TransformStream to ensure a fresh, unlocked stream.\n const stream = source.pipeThrough(new TransformStream<T, T>());\n\n /**\n * Implements the async iterator protocol for the stream.\n * Ensures proper cleanup (cancelling and releasing the reader) on completion, early exit, or error.\n */\n (stream as AsyncIterableStream<T>)[Symbol.asyncIterator] = function (\n this: ReadableStream<T>,\n ): AsyncIterator<T> {\n const reader = this.getReader();\n\n let finished = false;\n\n /**\n * Cleans up the reader by cancelling and releasing the lock.\n */\n async function cleanup(cancelStream: boolean) {\n if (finished) return;\n\n finished = true;\n try {\n if (cancelStream) {\n await reader.cancel?.();\n }\n } finally {\n try {\n reader.releaseLock();\n } catch {}\n }\n }\n\n return {\n /**\n * Reads the next chunk from the stream.\n * @returns A promise resolving to the next IteratorResult.\n */\n async next(): Promise<IteratorResult<T>> {\n if (finished) {\n return { done: true, value: undefined };\n }\n\n const { done, value } = await reader.read();\n\n if (done) {\n await cleanup(true);\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n },\n\n /**\n * May be called on early exit (e.g., break from for-await) or after completion.\n * Ensures the stream is cancelled and resources are released.\n * @returns A promise resolving to a completed IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n await cleanup(true);\n return { done: true, value: undefined };\n },\n\n /**\n * Called on early exit with error.\n * Ensures the stream is cancelled and resources are released, then rethrows the error.\n * @param err The error to throw.\n * @returns A promise that rejects with the provided error.\n */\n async throw(err: unknown): Promise<IteratorResult<T>> {\n await cleanup(true);\n throw err;\n },\n };\n };\n\n return stream as AsyncIterableStream<T>;\n}\n","import type {\n LanguageModelV4FilePart,\n LanguageModelV4Message,\n LanguageModelV4Prompt,\n LanguageModelV4TextPart,\n LanguageModelV4ToolResultOutput,\n} from '@ai-sdk/provider';\nimport {\n asArray,\n detectMediaType,\n isFullMediaType,\n isUrlSupported,\n type CustomPart,\n type FilePart,\n type ImagePart,\n type ModelMessage,\n type ReasoningFilePart,\n type ReasoningPart,\n type TextPart,\n type ToolCallPart,\n type ToolResultOutput,\n type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport {\n createDefaultDownloadFunction,\n type DownloadFunction,\n} from '../util/download/download-function';\nimport { convertToLanguageModelV4FilePart } from './file-part-data';\nimport { logWarnings } from '../logger/log-warnings';\nimport type { Warning } from '../types/warning';\nimport { InvalidMessageRoleError } from './invalid-message-role-error';\nimport type { StandardizedPrompt } from './standardize-prompt';\nimport { MissingToolResultsError } from '../error/missing-tool-result-error';\n\nexport async function convertToLanguageModelPrompt({\n prompt,\n supportedUrls,\n download = createDefaultDownloadFunction(),\n // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n}: {\n prompt: StandardizedPrompt;\n supportedUrls: Record<string, RegExp[]>;\n download: DownloadFunction | undefined;\n provider?: string;\n}): Promise<LanguageModelV4Prompt> {\n const downloadedAssets = await downloadAssets(\n prompt.messages,\n download,\n supportedUrls,\n );\n\n const approvalIdToToolCallId = new Map<string, string>();\n for (const message of prompt.messages) {\n if (message.role === 'assistant' && Array.isArray(message.content)) {\n for (const part of message.content) {\n if (\n part.type === 'tool-approval-request' &&\n 'approvalId' in part &&\n 'toolCallId' in part\n ) {\n approvalIdToToolCallId.set(\n part.approvalId as string,\n part.toolCallId as string,\n );\n }\n }\n }\n }\n\n const approvedToolCallIds = new Set<string>();\n for (const message of prompt.messages) {\n if (message.role === 'tool') {\n for (const part of message.content) {\n if (part.type === 'tool-approval-response') {\n const toolCallId = approvalIdToToolCallId.get(part.approvalId);\n if (toolCallId) {\n approvedToolCallIds.add(toolCallId);\n }\n }\n }\n }\n }\n\n const messages = [\n ...(prompt.instructions != null\n ? typeof prompt.instructions === 'string'\n ? [{ role: 'system' as const, content: prompt.instructions }]\n : asArray(prompt.instructions).map(message => ({\n role: 'system' as const,\n content: message.content,\n providerOptions: message.providerOptions,\n }))\n : []),\n ...prompt.messages.map(message =>\n convertToLanguageModelMessage({ message, downloadedAssets, provider }),\n ),\n ];\n\n // combine consecutive tool messages into a single tool message\n const combinedMessages = [];\n for (const message of messages) {\n if (message.role !== 'tool') {\n combinedMessages.push(message);\n continue;\n }\n\n const lastCombinedMessage = combinedMessages.at(-1);\n if (lastCombinedMessage?.role === 'tool') {\n lastCombinedMessage.content.push(...message.content);\n } else {\n combinedMessages.push(message);\n }\n }\n\n const toolCallIds = new Set<string>();\n\n for (const message of combinedMessages) {\n switch (message.role) {\n case 'assistant': {\n for (const content of message.content) {\n if (content.type === 'tool-call' && !content.providerExecuted) {\n toolCallIds.add(content.toolCallId);\n }\n }\n break;\n }\n case 'tool': {\n for (const content of message.content) {\n if (content.type === 'tool-result') {\n toolCallIds.delete(content.toolCallId);\n }\n }\n break;\n }\n case 'user':\n case 'system':\n // remove approved tool calls from the set before checking:\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({\n toolCallIds: Array.from(toolCallIds),\n });\n }\n break;\n }\n }\n\n // remove approved tool calls from the set before checking:\n for (const id of approvedToolCallIds) {\n toolCallIds.delete(id);\n }\n\n if (toolCallIds.size > 0) {\n throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n }\n\n return combinedMessages.filter(\n // Filter out empty tool messages (e.g. if they only contained\n // tool-approval-response parts that were removed).\n // This prevents sending invalid empty messages to the provider.\n // Note: provider-executed tool-approval-response parts are preserved.\n message => message.role !== 'tool' || message.content.length > 0,\n );\n}\n\n/**\n * Convert a ModelMessage to a LanguageModelV4Message.\n *\n * @param message - The ModelMessage to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n */\nexport function convertToLanguageModelMessage({\n message,\n downloadedAssets,\n // `provider` is only needed here to convert legacy tool output types via `mapToolResultOutput`.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n}: {\n message: ModelMessage;\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >;\n provider?: string;\n}): LanguageModelV4Message {\n const warnings: Warning[] = [];\n\n const role = message.role;\n switch (role) {\n case 'system': {\n return {\n role: 'system',\n content: message.content,\n providerOptions: message.providerOptions,\n };\n }\n\n case 'user': {\n if (typeof message.content === 'string') {\n return {\n role: 'user',\n content: [{ type: 'text', text: message.content }],\n providerOptions: message.providerOptions,\n };\n }\n\n const converted = {\n role: 'user' as const,\n content: message.content\n .map(part => {\n if (part.type === 'image') {\n warnings.push({\n type: 'deprecated',\n setting: '\"image\" content part',\n message: `The \"image\" content part type is deprecated. Use a \"file\" part with mediaType: 'image' (or a more specific image/* subtype) instead.`,\n });\n }\n return convertImagePartToFilePart(part);\n })\n .map(part => convertPartToLanguageModelPart(part, downloadedAssets))\n // remove empty text parts:\n .filter(part => part.type !== 'text' || part.text !== ''),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n case 'assistant': {\n if (typeof message.content === 'string') {\n return {\n role: 'assistant',\n content: [{ type: 'text', text: message.content }],\n providerOptions: message.providerOptions,\n };\n }\n\n const converted = {\n role: 'assistant' as const,\n content: message.content\n .filter(\n // remove empty text parts (no text, and no provider options):\n part =>\n part.type !== 'text' ||\n part.text !== '' ||\n part.providerOptions != null,\n )\n .filter(\n (\n part,\n ): part is\n | CustomPart\n | TextPart\n | FilePart\n | ReasoningPart\n | ReasoningFilePart\n | ToolCallPart\n | ToolResultPart => part.type !== 'tool-approval-request',\n )\n .map(part => {\n const providerOptions = part.providerOptions;\n\n switch (part.type) {\n case 'custom': {\n return {\n type: 'custom' as const,\n kind: part.kind,\n providerOptions,\n };\n }\n case 'file': {\n const { data, mediaType } = convertToLanguageModelV4FilePart(\n part.data,\n );\n return {\n type: 'file' as const,\n data,\n filename: part.filename,\n mediaType: mediaType ?? part.mediaType,\n providerOptions,\n };\n }\n case 'reasoning': {\n return {\n type: 'reasoning' as const,\n text: part.text,\n providerOptions,\n };\n }\n case 'reasoning-file': {\n const { data, mediaType } = convertToLanguageModelV4FilePart(\n part.data,\n );\n if (data.type !== 'data' && data.type !== 'url') {\n throw new Error(\n `Unsupported reasoning-file data type: ${data.type}`,\n );\n }\n return {\n type: 'reasoning-file' as const,\n data,\n mediaType: mediaType ?? part.mediaType,\n providerOptions,\n };\n }\n case 'text': {\n return {\n type: 'text' as const,\n text: part.text,\n providerOptions,\n };\n }\n case 'tool-call': {\n return {\n type: 'tool-call' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input: part.input,\n providerExecuted: part.providerExecuted,\n providerOptions,\n };\n }\n case 'tool-result': {\n return {\n type: 'tool-result' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput({\n output: part.output,\n provider,\n warnings,\n downloadedAssets,\n }),\n providerOptions,\n };\n }\n }\n }),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n case 'tool': {\n const converted = {\n role: 'tool' as const,\n content: message.content\n .filter(\n // Only include tool-approval-response for provider-executed tools\n part =>\n part.type !== 'tool-approval-response' || part.providerExecuted,\n )\n .map(part => {\n switch (part.type) {\n case 'tool-result': {\n return {\n type: 'tool-result' as const,\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output: mapToolResultOutput({\n output: part.output,\n provider,\n warnings,\n downloadedAssets,\n }),\n providerOptions: part.providerOptions,\n };\n }\n case 'tool-approval-response': {\n return {\n type: 'tool-approval-response' as const,\n approvalId: part.approvalId,\n approved: part.approved,\n reason: part.reason,\n };\n }\n }\n }),\n providerOptions: message.providerOptions,\n };\n if (warnings.length > 0) {\n logWarnings({ warnings });\n }\n return converted;\n }\n\n default: {\n const _exhaustiveCheck: never = role;\n throw new InvalidMessageRoleError({ role: _exhaustiveCheck });\n }\n }\n}\n\n/*\n * Rewrites a legacy `ImagePart` into an equivalent `FilePart`. The default\n * `mediaType` for a bare `ImagePart` (no `mediaType`) is `\"image\"` (top-level\n * segment); an explicit `mediaType` is carried through verbatim. After this\n * pre-pass, only `TextPart` and `FilePart` ever reach the provider-facing\n * conversion logic.\n */\nfunction convertImagePartToFilePart(\n part: TextPart | ImagePart | FilePart,\n): TextPart | FilePart {\n if (part.type !== 'image') {\n return part;\n }\n return {\n type: 'file',\n data: part.image,\n mediaType: part.mediaType ?? 'image',\n providerOptions: part.providerOptions,\n };\n}\n\n/**\n * Downloads files from URLs in the user messages.\n */\nexport async function downloadAssets(\n messages: ModelMessage[],\n download: DownloadFunction,\n supportedUrls: Record<string, RegExp[]>,\n): Promise<\n Record<string, { mediaType: string | undefined; data: Uint8Array }>\n> {\n type ConvertedFile = {\n mediaType: string | undefined;\n data: LanguageModelV4FilePart['data'];\n };\n type UrlTaggedFile = {\n mediaType: string | undefined;\n data: { type: 'url'; url: URL };\n };\n\n const downloadableFiles: FilePart[] = [];\n\n for (const message of messages) {\n if (message.role === 'user' && Array.isArray(message.content)) {\n for (const part of message.content) {\n const filePart = convertImagePartToFilePart(part);\n\n if (filePart.type === 'file') {\n downloadableFiles.push(filePart);\n }\n }\n }\n\n if (message.role === 'tool') {\n for (const part of message.content) {\n if (part.type !== 'tool-result') {\n continue;\n }\n\n if (part.output.type !== 'content') {\n continue;\n }\n\n for (const contentPart of part.output.value) {\n if (contentPart.type === 'file') {\n downloadableFiles.push(contentPart);\n }\n }\n }\n }\n\n if (message.role === 'assistant' && Array.isArray(message.content)) {\n for (const part of message.content) {\n if (part.type !== 'tool-result') {\n continue;\n }\n if (part.output.type !== 'content') {\n continue;\n }\n for (const contentPart of part.output.value) {\n if (contentPart.type === 'file') {\n downloadableFiles.push(contentPart);\n }\n }\n }\n }\n }\n\n const plannedDownloads = downloadableFiles\n .map((part): ConvertedFile => {\n const mediaType = part.mediaType;\n const { data } = convertToLanguageModelV4FilePart(part.data);\n return { mediaType, data };\n })\n .filter((part): part is UrlTaggedFile => part.data.type === 'url')\n .map(part => ({\n url: part.data.url,\n isUrlSupportedByModel:\n part.mediaType != null &&\n isUrlSupported({\n url: part.data.url.toString(),\n mediaType: part.mediaType,\n supportedUrls,\n }),\n }));\n // download in parallel:\n const downloadedFiles = await download(plannedDownloads);\n\n return Object.fromEntries(\n downloadedFiles\n .map((file, index) =>\n file == null\n ? null\n : [\n plannedDownloads[index].url.toString(),\n { data: file.data, mediaType: file.mediaType },\n ],\n )\n .filter(file => file != null),\n );\n}\n\n/**\n * Convert part of a user message to a LanguageModelV4Part.\n *\n * @param part - The part to convert.\n * @param downloadedAssets - A map of URLs to their downloaded data. Only\n * available if the model does not support URLs, null otherwise.\n * @returns The converted part.\n */\nfunction convertPartToLanguageModelPart(\n part: TextPart | FilePart,\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >,\n): LanguageModelV4TextPart | LanguageModelV4FilePart {\n if (part.type === 'text') {\n return {\n type: 'text',\n text: part.text,\n providerOptions: part.providerOptions,\n };\n }\n\n const { data: normalizedData, mediaType: dataUrlMediaType } =\n convertToLanguageModelV4FilePart(part.data);\n\n let mediaType: string | undefined = dataUrlMediaType ?? part.mediaType;\n let data: LanguageModelV4FilePart['data'] = normalizedData;\n\n if (data.type === 'url') {\n const downloadedFile = downloadedAssets[data.url.toString()];\n if (downloadedFile) {\n data = { type: 'data', data: downloadedFile.data };\n if (\n downloadedFile.mediaType != null &&\n (mediaType == null || !isFullMediaType(mediaType))\n ) {\n mediaType = downloadedFile.mediaType;\n }\n }\n }\n\n if (\n data.type === 'data' &&\n (data.data instanceof Uint8Array || typeof data.data === 'string')\n ) {\n const imageMediaType = detectMediaType({\n data: data.data,\n topLevelType: 'image',\n });\n if (imageMediaType != null) {\n mediaType = imageMediaType;\n }\n }\n\n if (mediaType == null) {\n throw new Error(`Media type is missing for file part`);\n }\n\n return {\n type: 'file',\n mediaType,\n filename: part.filename,\n data,\n providerOptions: part.providerOptions,\n };\n}\n\nexport function mapToolResultOutput({\n output,\n // `provider` is only needed here to convert legacy \"file-id\" and \"image-file-id\" types to provider references, in case they are using string ID values.\n // TODO: remove in v8 when \"file-id\" and \"image-file-id\" types are removed\n provider,\n warnings = [],\n downloadedAssets,\n}: {\n output: ToolResultOutput;\n provider?: string;\n warnings?: Warning[];\n downloadedAssets: Record<\n string,\n { mediaType: string | undefined; data: Uint8Array }\n >;\n}): LanguageModelV4ToolResultOutput {\n if (output.type !== 'content') {\n return output;\n }\n\n return {\n type: 'content',\n value: output.value.map(item => {\n switch (item.type) {\n case 'file': {\n const convertedPart = convertPartToLanguageModelPart(\n item,\n downloadedAssets,\n );\n\n if (convertedPart.type !== 'file') {\n throw new Error(\n 'Expected tool result file content to convert to file.',\n );\n }\n\n return convertedPart;\n }\n case 'file-data': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-data\"',\n message: `The \"file-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'data' as const, data: item.data },\n filename: item.filename,\n mediaType: item.mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'file-url': {\n const mediaType = item.mediaType ?? getMediaTypeFromUrl(item.url);\n let message = `The \"file-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'url', url } instead.`;\n if (!item.mediaType) {\n const inferenceSuffix =\n mediaType === 'application/octet-stream'\n ? `Unable to infer media type from URL. Defaulting to 'application/octet-stream'.`\n : `Inferred media type '${mediaType}' from URL.`;\n message = `The \"file-url\" tool result content part with URL \"${item.url}\" is missing a \"mediaType\". ${inferenceSuffix} ${message}`;\n }\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-url\"',\n message,\n });\n return {\n type: 'file' as const,\n data: { type: 'url' as const, url: new URL(item.url) },\n mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'file-id': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-id\"',\n message: `The \"file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: convertFileIdToProviderReference({\n fileId: item.fileId,\n provider,\n }),\n },\n mediaType: 'application',\n providerOptions: item.providerOptions,\n };\n }\n case 'file-reference': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"file-reference\"',\n message: `The \"file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: item.providerReference,\n },\n mediaType: 'application',\n providerOptions: item.providerOptions,\n };\n }\n // The \"image-*\" types are legacy and deprecated.\n // TODO: remove migration in v8 in combination with the removal of these types from the provider utils.\n case 'image-data': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-data\"',\n message: `The \"image-data\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'data', data } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'data' as const, data: item.data },\n mediaType: item.mediaType,\n providerOptions: item.providerOptions,\n };\n }\n case 'image-url': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-url\"',\n message: `The \"image-url\" type for tool result content is deprecated. Use the \"file\" type with mediaType 'image' (or a specific image/* subtype) and { type: 'url', url } instead.`,\n });\n return {\n type: 'file' as const,\n data: { type: 'url' as const, url: new URL(item.url) },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n case 'image-file-id': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-file-id\"',\n message: `The \"image-file-id\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: convertFileIdToProviderReference({\n fileId: item.fileId,\n provider,\n }),\n },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n case 'image-file-reference': {\n warnings.push({\n type: 'deprecated',\n setting: '\"tool-result\" content of type \"image-file-reference\"',\n message: `The \"image-file-reference\" type for tool result content is deprecated. Use the \"file\" type with mediaType and { type: 'reference', reference } instead.`,\n });\n return {\n type: 'file' as const,\n data: {\n type: 'reference' as const,\n reference: item.providerReference,\n },\n mediaType: 'image',\n providerOptions: item.providerOptions,\n };\n }\n default:\n return item;\n }\n }),\n };\n}\n\nfunction convertFileIdToProviderReference({\n fileId,\n provider,\n}: {\n fileId: string | Record<string, string>;\n provider?: string;\n}): Record<string, string> {\n if (typeof fileId === 'object') {\n return fileId;\n }\n\n if (provider == null) {\n throw new Error(\n 'Cannot convert string fileId to provider reference without a provider ID. ' +\n 'Use a Record<string, string> fileId or switch to the file-reference type.',\n );\n }\n\n return { [provider]: fileId };\n}\n\n// Temporary private helper (see below).\nconst URL_EXTENSION_TO_MEDIA_TYPE: Record<string, string> = {\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n png: 'image/png',\n gif: 'image/gif',\n webp: 'image/webp',\n svg: 'image/svg+xml',\n avif: 'image/avif',\n heic: 'image/heic',\n bmp: 'image/bmp',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n pdf: 'application/pdf',\n mp4: 'video/mp4',\n webm: 'video/webm',\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n};\n\n/*\n * Attempts to infer an IANA media type from the file extension in a URL's\n * pathname. Returns `fallbackMediaType` when the extension is absent,\n * unrecognized, or the URL cannot be parsed.\n *\n * Temporary private helper as a best-effort solution for missing media types on \"file-url\" content parts.\n */\nfunction getMediaTypeFromUrl(\n url: string,\n fallbackMediaType = 'application/octet-stream',\n): string {\n try {\n const pathname = new URL(url).pathname;\n const fileExtension = pathname.split('.').pop()?.toLowerCase();\n if (\n fileExtension &&\n Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, fileExtension)\n ) {\n return URL_EXTENSION_TO_MEDIA_TYPE[fileExtension];\n }\n } catch {\n // ignore URL parse errors\n }\n return fallbackMediaType;\n}\n","import {\n cancelResponseBody,\n DownloadError,\n readResponseWithSizeLimit,\n DEFAULT_MAX_DOWNLOAD_SIZE,\n fetchWithValidatedRedirects,\n withUserAgentSuffix,\n getRuntimeEnvironmentUserAgent,\n} from '@ai-sdk/provider-utils';\nimport { VERSION } from '../../version';\n\n/**\n * Download a file from a URL.\n *\n * @param url - The URL to download from.\n * @param maxBytes - Maximum allowed download size in bytes. Defaults to 100 MiB.\n * @param abortSignal - An optional abort signal to cancel the download.\n * @returns The downloaded data and media type.\n *\n * @throws DownloadError if the download fails or exceeds maxBytes.\n */\nexport const download = async ({\n url,\n maxBytes,\n abortSignal,\n}: {\n url: URL;\n maxBytes?: number;\n abortSignal?: AbortSignal;\n}) => {\n const urlText = url.toString();\n try {\n const headers = withUserAgentSuffix(\n {},\n `ai-sdk/${VERSION}`,\n getRuntimeEnvironmentUserAgent(),\n );\n\n const response = await fetchWithValidatedRedirects({\n url: urlText,\n headers,\n abortSignal,\n });\n\n if (!response.ok) {\n // Release the connection before rejecting so an error status from an\n // attacker-controlled origin cannot leak open sockets.\n await cancelResponseBody(response);\n throw new DownloadError({\n url: urlText,\n statusCode: response.status,\n statusText: response.statusText,\n });\n }\n\n const data = await readResponseWithSizeLimit({\n response,\n url: urlText,\n maxBytes: maxBytes ?? DEFAULT_MAX_DOWNLOAD_SIZE,\n });\n\n return {\n data,\n mediaType: response.headers.get('content-type') ?? undefined,\n };\n } catch (error) {\n if (DownloadError.isInstance(error)) {\n throw error;\n }\n\n throw new DownloadError({ url: urlText, cause: error });\n }\n};\n","declare const __PACKAGE_VERSION__: string | undefined;\nexport const VERSION: string =\n typeof __PACKAGE_VERSION__ !== 'undefined'\n ? __PACKAGE_VERSION__\n : '0.0.0-test';\n","import { download as originalDownload } from './download';\n\n/**\n * Experimental. Can change in patch versions without warning.\n *\n * Download function. Called with the array of URLs and a boolean indicating\n * whether the URL is supported by the model.\n *\n * The download function can decide for each URL:\n * - to return null (which means that the URL should be passed to the model)\n * - to download the asset and return the data (incl. retries, authentication, etc.)\n *\n * Should throw DownloadError if the download fails.\n *\n * Should return an array of objects sorted by the order of the requested downloads.\n * For each object, the data should be a Uint8Array if the URL was downloaded.\n * For each object, the mediaType should be the media type of the downloaded asset.\n * For each object, the data should be null if the URL should be passed through as is.\n */\nexport type DownloadFunction = (\n options: Array<{\n url: URL;\n isUrlSupportedByModel: boolean;\n }>,\n) => PromiseLike<\n Array<{\n data: Uint8Array;\n mediaType: string | undefined;\n } | null>\n>;\n\n/**\n * Default download function.\n * Downloads the file if it is not supported by the model.\n */\nexport const createDefaultDownloadFunction =\n (download: typeof originalDownload = originalDownload): DownloadFunction =>\n requestedDownloads =>\n Promise.all(\n requestedDownloads.map(async requestedDownload =>\n requestedDownload.isUrlSupportedByModel\n ? null\n : await download(requestedDownload),\n ),\n );\n","import type { LanguageModelV4FilePart } from '@ai-sdk/provider';\nimport {\n isBuffer,\n isProviderReference,\n type DataContent,\n type FilePart,\n type ProviderReference,\n} from '@ai-sdk/provider-utils';\nimport { InvalidDataContentError } from './invalid-data-content-error';\nimport { splitDataUrl } from './split-data-url';\n\ntype TaggedFileData = Extract<FilePart['data'], { type: string }>;\n\nfunction isTaggedFileData(value: unknown): value is TaggedFileData {\n if (typeof value !== 'object' || value === null) return false;\n const type = (value as { type?: unknown }).type;\n return (\n type === 'data' || type === 'url' || type === 'reference' || type === 'text'\n );\n}\n\ntype ConvertResult = {\n data: LanguageModelV4FilePart['data'];\n mediaType: string | undefined;\n};\n\nfunction convertUrlToFilePartData(url: URL): ConvertResult {\n if (url.protocol === 'data:') {\n const { mediaType, base64Content } = splitDataUrl(url.toString());\n\n if (mediaType == null || base64Content == null) {\n throw new InvalidDataContentError({\n content: url,\n message: `Invalid data URL format in content ${url.toString()}`,\n });\n }\n\n return { data: { type: 'data', data: base64Content }, mediaType };\n }\n\n return { data: { type: 'url', url }, mediaType: undefined };\n}\n\nfunction convertInlineDataToFilePartData(content: DataContent): ConvertResult {\n if (content instanceof Uint8Array) {\n return { data: { type: 'data', data: content }, mediaType: undefined };\n }\n if (content instanceof ArrayBuffer) {\n return {\n data: { type: 'data', data: new Uint8Array(content) },\n mediaType: undefined,\n };\n }\n if (isBuffer(content)) {\n return {\n data: { type: 'data', data: new Uint8Array(content) },\n mediaType: undefined,\n };\n }\n return {\n data: { type: 'data', data: content as string },\n mediaType: undefined,\n };\n}\n\n/**\n * Converts any legacy-or-tagged top-level `FilePart.data` /\n * `ReasoningFilePart.data` value into the tagged v4 provider prompt shape.\n *\n * Returns the tagged `data` together with the resolved mediaType (extracted\n * from a `data:` URL when applicable).\n */\nexport function convertToLanguageModelV4FilePart(\n content: FilePart['data'],\n): ConvertResult {\n if (isTaggedFileData(content)) {\n switch (content.type) {\n case 'data':\n if (\n typeof content.data === 'string' &&\n content.data.startsWith('data:')\n ) {\n throw new InvalidDataContentError({\n content: content.data,\n message:\n 'Data URLs are not valid inline data. Pass them as { type: \"url\", url } instead.',\n });\n }\n return convertInlineDataToFilePartData(content.data);\n case 'url':\n return convertUrlToFilePartData(content.url);\n case 'reference':\n return {\n data: { type: 'reference', reference: content.reference },\n mediaType: undefined,\n };\n case 'text':\n return {\n data: { type: 'text', text: content.text },\n mediaType: undefined,\n };\n }\n }\n\n if (content instanceof URL) {\n return convertUrlToFilePartData(content);\n }\n\n if (typeof content === 'string') {\n try {\n return convertUrlToFilePartData(new URL(content));\n } catch {\n return convertInlineDataToFilePartData(content);\n }\n }\n\n if (isProviderReference(content)) {\n return {\n data: { type: 'reference', reference: content as ProviderReference },\n mediaType: undefined,\n };\n }\n\n return convertInlineDataToFilePartData(content as DataContent);\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidDataContentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidDataContentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly content: unknown;\n\n constructor({\n content,\n cause,\n message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.`,\n }: {\n content: unknown;\n cause?: unknown;\n message?: string;\n }) {\n super({ name, message, cause });\n\n this.content = content;\n }\n\n static isInstance(error: unknown): error is InvalidDataContentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","export function splitDataUrl(dataUrl: string): {\n mediaType: string | undefined;\n base64Content: string | undefined;\n} {\n try {\n const [header, base64Content] = dataUrl.split(',');\n return {\n mediaType: header.split(';')[0].split(':')[1],\n base64Content,\n };\n } catch {\n return {\n mediaType: undefined,\n base64Content: undefined,\n };\n }\n}\n","import type { Warning } from '../types';\n\n/**\n * A function for logging warnings.\n *\n * You can assign it to the `AI_SDK_LOG_WARNINGS` global variable to use it as the default warning logger.\n *\n * @example\n * ```ts\n * globalThis.AI_SDK_LOG_WARNINGS = (options) => {\n * console.log('WARNINGS:', options.warnings, options.provider, options.model);\n * };\n * ```\n */\nexport type LogWarningsFunction = (options: {\n /**\n * The warnings returned by the model provider.\n */\n warnings: Warning[];\n\n /**\n * The provider id used for the call, if scoped to a specific provider.\n */\n provider?: string;\n\n /**\n * The model id used for the call, if scoped to a specific provider.\n */\n model?: string;\n}) => void;\n\n/**\n * Formats a warning object into a human-readable string with clear AI SDK branding.\n *\n * @param options - The options for formatting the warning.\n * @param options.warning - The warning to format.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n * @returns A formatted warning message string.\n */\nfunction formatWarning({\n warning,\n provider,\n model,\n}: {\n warning: Warning;\n provider?: string;\n model?: string;\n}): string {\n const scope =\n provider != null && model != null ? ` (${provider} / ${model})` : '';\n const prefix = `AI SDK Warning${scope}:`;\n\n switch (warning.type) {\n case 'unsupported': {\n let message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n\n case 'compatibility': {\n let message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n if (warning.details) {\n message += ` ${warning.details}`;\n }\n return message;\n }\n\n case 'deprecated': {\n return `${prefix} Deprecated: \"${warning.setting}\". ${warning.message}`;\n }\n\n case 'other': {\n return `${prefix} ${warning.message}`;\n }\n\n default: {\n // Fallback for any unknown warning types\n return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n }\n }\n}\n\nexport const FIRST_WARNING_INFO_MESSAGE =\n 'AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.';\n\nlet hasLoggedBefore = false;\n\n/**\n * Logs warnings to the console or uses a custom logger if configured.\n *\n * The behavior can be customized via the `AI_SDK_LOG_WARNINGS` global variable:\n * - If set to `false`, warnings are suppressed.\n * - If set to a function, that function is called with the warnings.\n * - Otherwise, warnings are logged to the console using `console.warn`.\n *\n * @param options - The options containing warnings and context.\n * @param options.warnings - The warnings to log.\n * @param options.provider - The provider id used for the call, if scoped to a specific provider.\n * @param options.model - The model id used for the call, if scoped to a specific provider.\n */\nexport const logWarnings: LogWarningsFunction = options => {\n // if the warnings array is empty, do nothing\n if (options.warnings.length === 0) {\n return;\n }\n\n const logger = globalThis.AI_SDK_LOG_WARNINGS;\n\n // if the logger is set to false, do nothing\n if (logger === false) {\n return;\n }\n\n // use the provided logger if it is a function\n if (typeof logger === 'function') {\n logger(options);\n return;\n }\n\n // display information note on first call\n if (!hasLoggedBefore) {\n hasLoggedBefore = true;\n console.info(FIRST_WARNING_INFO_MESSAGE);\n }\n\n // default behavior: log warnings via process.emitWarning if available, otherwise console.warn\n for (const warning of options.warnings) {\n const message = formatWarning({\n warning,\n provider: options.provider,\n model: options.model,\n });\n if (\n typeof process !== 'undefined' &&\n typeof process.emitWarning === 'function'\n ) {\n process.emitWarning(message, {\n type: warning.type === 'deprecated' ? 'DeprecationWarning' : 'Warning',\n });\n } else {\n console.warn(message);\n }\n }\n};\n\n/**\n * Resets the internal logging state. Used for testing purposes.\n */\nexport const resetLogWarningsState = () => {\n hasLoggedBefore = false;\n};\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidMessageRoleError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidMessageRoleError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly role: string;\n\n constructor({\n role,\n message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".`,\n }: {\n role: string;\n message?: string;\n }) {\n super({ name, message });\n\n this.role = role;\n }\n\n static isInstance(error: unknown): error is InvalidMessageRoleError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_MissingToolResultsError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class MissingToolResultsError extends AISDKError {\n private readonly [symbol] = true;\n\n readonly toolCallIds: string[];\n\n constructor({ toolCallIds }: { toolCallIds: string[] }) {\n super({\n name,\n message: `Tool result${\n toolCallIds.length > 1 ? 's are' : ' is'\n } missing for tool call${toolCallIds.length > 1 ? 's' : ''} ${toolCallIds.join(\n ', ',\n )}.`,\n });\n\n this.toolCallIds = toolCallIds;\n }\n\n static isInstance(error: unknown): error is MissingToolResultsError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { getErrorMessage, type JSONValue } from '@ai-sdk/provider';\nimport type { Tool, ToolResultOutput } from '@ai-sdk/provider-utils';\n\nexport async function createToolModelOutput({\n toolCallId,\n input,\n output,\n tool,\n errorMode,\n}: {\n toolCallId: string;\n input: unknown;\n output: unknown;\n tool: Tool | undefined;\n errorMode: 'none' | 'text' | 'json';\n}): Promise<ToolResultOutput> {\n if (errorMode === 'text') {\n return { type: 'error-text', value: getErrorMessage(output) };\n } else if (errorMode === 'json') {\n return { type: 'error-json', value: toJSONValue(output) };\n }\n\n if (tool?.toModelOutput) {\n return await tool.toModelOutput({ toolCallId, input, output });\n }\n\n return typeof output === 'string'\n ? { type: 'text', value: output }\n : { type: 'json', value: toJSONValue(output) };\n}\n\nfunction toJSONValue(value: unknown): JSONValue {\n return value === undefined ? null : (value as JSONValue);\n}\n","import type { LanguageModelV4ToolChoice } from '@ai-sdk/provider';\nimport type { ToolChoice } from '../types/language-model';\n\nexport function prepareToolChoice({\n toolChoice,\n}: {\n // use of any because it doesn't matter for tool choice preparation\n toolChoice: ToolChoice<any> | undefined;\n}): LanguageModelV4ToolChoice {\n return toolChoice == null\n ? { type: 'auto' }\n : typeof toolChoice === 'string'\n ? { type: toolChoice }\n : { type: 'tool' as const, toolName: toolChoice.toolName as string };\n}\n","import type {\n LanguageModelV4FunctionTool,\n LanguageModelV4ProviderTool,\n} from '@ai-sdk/provider';\nimport {\n asSchema,\n type Experimental_SandboxSession as SandboxSession,\n type InferToolSetContext,\n type Tool,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type { ToolOrder } from '../generate-text/tool-order';\nimport { isNonEmptyObject } from '../util/is-non-empty-object';\n\nexport async function prepareTools<TOOLS extends ToolSet>({\n tools,\n toolOrder,\n toolsContext = {} as InferToolSetContext<TOOLS>,\n experimental_sandbox: sandbox,\n}: {\n tools: TOOLS | undefined;\n toolOrder?: ToolOrder<TOOLS>;\n toolsContext?: InferToolSetContext<TOOLS>;\n experimental_sandbox?: SandboxSession;\n}): Promise<\n Array<LanguageModelV4FunctionTool | LanguageModelV4ProviderTool> | undefined\n> {\n if (!isNonEmptyObject(tools)) {\n return undefined;\n }\n\n const languageModelTools: Array<\n LanguageModelV4FunctionTool | LanguageModelV4ProviderTool\n > = [];\n for (const [name, tool] of orderToolEntries({ tools, toolOrder })) {\n const toolType = tool.type;\n\n switch (toolType) {\n case undefined:\n case 'dynamic':\n case 'function': {\n const description = resolveToolDescription({\n tool,\n toolName: name,\n toolsContext,\n experimental_sandbox: sandbox,\n });\n const providerOptions = tool.providerOptions;\n const inputExamples = tool.inputExamples;\n const strict = tool.strict;\n\n languageModelTools.push({\n type: 'function' as const,\n name,\n inputSchema: await asSchema(tool.inputSchema).jsonSchema,\n ...(description != null ? { description } : {}),\n ...(inputExamples != null ? { inputExamples } : {}),\n ...(providerOptions != null ? { providerOptions } : {}),\n ...(strict != null ? { strict } : {}),\n });\n break;\n }\n case 'provider': {\n languageModelTools.push({\n type: 'provider' as const,\n name,\n id: tool.id,\n args: tool.args,\n });\n break;\n }\n default: {\n const exhaustiveCheck: never = toolType as never;\n throw new Error(`Unsupported tool type: ${exhaustiveCheck}`);\n }\n }\n }\n\n return languageModelTools;\n}\n\nfunction orderToolEntries<TOOLS extends ToolSet>({\n tools,\n toolOrder,\n}: {\n tools: TOOLS;\n toolOrder?: ToolOrder<TOOLS>;\n}): Array<[string, Tool]> {\n if (toolOrder == null) {\n return Object.entries(tools);\n }\n\n const toolEntries = Object.entries(tools);\n\n const orderedTools = toolEntries\n .filter(([name]) => toolOrder.includes(name))\n .sort(\n ([nameA], [nameB]) => toolOrder.indexOf(nameA) - toolOrder.indexOf(nameB),\n );\n\n const unorderedTools = toolEntries\n .filter(([name]) => !toolOrder.includes(name))\n .sort(([nameA], [nameB]) => (nameA < nameB ? -1 : nameA > nameB ? 1 : 0));\n\n return [...orderedTools, ...unorderedTools];\n}\n\nfunction resolveToolDescription<TOOLS extends ToolSet>({\n tool,\n toolName,\n toolsContext,\n experimental_sandbox: sandbox,\n}: {\n tool: Tool;\n toolName: string;\n toolsContext: InferToolSetContext<TOOLS>;\n experimental_sandbox?: SandboxSession;\n}): string | undefined {\n return tool.description === undefined\n ? undefined\n : typeof tool.description === 'string'\n ? tool.description\n : tool.description({\n context: toolsContext[toolName as keyof InferToolSetContext<TOOLS>],\n experimental_sandbox: sandbox,\n });\n}\n","export function isNonEmptyObject(\n object: Record<string, unknown> | undefined | null,\n): object is Record<string, unknown> {\n return object != null && Object.keys(object).length > 0;\n}\n","import { InvalidPromptError } from '@ai-sdk/provider';\nimport {\n asArray,\n safeValidateTypes,\n type ModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { modelMessageSchema } from './message';\nimport type { Instructions, Prompt } from './prompt';\n\nexport type StandardizedPrompt = {\n /**\n * Instructions.\n */\n instructions: Instructions | undefined;\n\n /**\n * Messages.\n */\n messages: ModelMessage[];\n};\n\n/**\n * Converts a prompt input into a standardized prompt with validated model\n * messages.\n *\n * @param prompt - The prompt definition to standardize.\n * Set `allowSystemInMessages` to true to allow system messages in the\n * `prompt` or `messages` fields. System messages in the `instructions`\n * option are always allowed.\n * @returns The standardized prompt.\n * @throws {InvalidPromptError} When the prompt is invalid.\n */\nexport async function standardizePrompt({\n allowSystemInMessages = false,\n system,\n instructions = system,\n prompt,\n messages,\n}: Prompt): Promise<StandardizedPrompt> {\n if (prompt == null && messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (prompt != null && messages != null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt and messages cannot be defined at the same time',\n });\n }\n\n // validate that instructions is a string or a SystemModelMessage\n if (\n typeof instructions !== 'string' &&\n !asArray(instructions).every(message => message.role === 'system')\n ) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'instructions must be a string, SystemModelMessage, or array of SystemModelMessage',\n });\n }\n\n if (prompt != null && typeof prompt === 'string') {\n messages = [{ role: 'user', content: prompt }];\n } else if (prompt != null && Array.isArray(prompt)) {\n messages = prompt;\n } else if (messages == null) {\n throw new InvalidPromptError({\n prompt,\n message: 'prompt or messages must be defined',\n });\n }\n\n if (messages.length === 0) {\n throw new InvalidPromptError({\n prompt,\n message: 'messages must not be empty',\n });\n }\n\n if (\n !allowSystemInMessages &&\n messages.some(message => message.role === 'system')\n ) {\n throw new InvalidPromptError({\n prompt,\n message:\n 'System messages are not allowed in the prompt or messages fields. Use the instructions option instead.',\n });\n }\n\n const validationResult = await safeValidateTypes({\n value: messages,\n schema: z.array(modelMessageSchema),\n });\n\n if (!validationResult.success) {\n throw new InvalidPromptError({\n prompt,\n message: 'The messages do not match the ModelMessage[] schema.',\n cause: validationResult.error,\n });\n }\n\n return { messages, instructions };\n}\n","import type {\n AssistantModelMessage,\n ModelMessage,\n SystemModelMessage,\n ToolModelMessage,\n UserModelMessage,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { providerMetadataSchema } from '../types/provider-metadata';\nimport {\n customPartSchema,\n filePartSchema,\n imagePartSchema,\n reasoningFilePartSchema,\n reasoningPartSchema,\n textPartSchema,\n toolApprovalRequestSchema,\n toolCallPartSchema,\n toolApprovalResponseSchema,\n toolResultPartSchema,\n} from './content-part';\n\nexport const systemModelMessageSchema: z.ZodType<SystemModelMessage> = z.object(\n {\n role: z.literal('system'),\n content: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n },\n);\n\nexport const userModelMessageSchema: z.ZodType<UserModelMessage> = z.object({\n role: z.literal('user'),\n content: z.union([\n z.string(),\n z.array(z.union([textPartSchema, imagePartSchema, filePartSchema])),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const assistantModelMessageSchema: z.ZodType<AssistantModelMessage> =\n z.object({\n role: z.literal('assistant'),\n content: z.union([\n z.string(),\n z.array(\n z.union([\n textPartSchema,\n customPartSchema,\n filePartSchema,\n reasoningPartSchema,\n reasoningFilePartSchema,\n toolCallPartSchema,\n toolResultPartSchema,\n toolApprovalRequestSchema,\n ]),\n ),\n ]),\n providerOptions: providerMetadataSchema.optional(),\n });\n\nexport const toolModelMessageSchema: z.ZodType<ToolModelMessage> = z.object({\n role: z.literal('tool'),\n content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nexport const modelMessageSchema: z.ZodType<ModelMessage> = z.union([\n systemModelMessageSchema,\n userModelMessageSchema,\n assistantModelMessageSchema,\n toolModelMessageSchema,\n]);\n","import type { SharedV4ProviderMetadata } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from './json-value';\n\n/**\n * Additional provider-specific metadata that is returned from the provider.\n *\n * This is needed to enable provider-specific functionality that can be\n * fully encapsulated in the provider.\n */\nexport type ProviderMetadata = SharedV4ProviderMetadata;\n\nexport const providerMetadataSchema: z.ZodType<ProviderMetadata> = z.record(\n z.string(),\n z.record(z.string(), jsonValueSchema.optional()),\n);\n","import type { JSONValue as OriginalJSONValue } from '@ai-sdk/provider';\nimport { z } from 'zod/v4';\n\nexport const jsonValueSchema: z.ZodType<JSONValue> = z.lazy(() =>\n z.union([\n z.null(),\n z.string(),\n z.number(),\n z.boolean(),\n z.record(z.string(), jsonValueSchema.optional()),\n z.array(jsonValueSchema),\n ]),\n);\n\nexport type JSONValue = OriginalJSONValue;\n","import {\n isBuffer,\n type CustomPart,\n type DataContent,\n type FilePart,\n type ImagePart,\n type ProviderOptions,\n type ReasoningFilePart,\n type ReasoningPart,\n type TextPart,\n type ToolApprovalRequest,\n type ToolApprovalResponse,\n type ToolResultOutput,\n type ToolResultPart,\n} from '@ai-sdk/provider-utils';\nimport { z } from 'zod/v4';\nimport { jsonValueSchema } from '../types/json-value';\nimport { providerMetadataSchema } from '../types/provider-metadata';\n\nconst fileInlineDataSchema: z.ZodType<DataContent> = z.union([\n z.string(),\n z.instanceof(Uint8Array),\n z.instanceof(ArrayBuffer),\n z.custom<Buffer>(isBuffer, { message: 'Must be a Buffer' }),\n]);\n\nconst providerReferenceSchema = z.record(z.string(), z.string());\n\n/**\n * @internal\n */\nexport const textPartSchema: z.ZodType<TextPart> = z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:\n * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.\n */\nexport const imagePartSchema: z.ZodType<ImagePart> = z.object({\n type: z.literal('image'),\n image: z.union([\n fileInlineDataSchema,\n z.instanceof(URL),\n providerReferenceSchema,\n ]),\n mediaType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\nconst taggedFileDataSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n z.object({\n type: z.literal('reference'),\n reference: providerReferenceSchema,\n }),\n z.object({ type: z.literal('text'), text: z.string() }),\n]);\n\nconst taggedReasoningFileDataSchema = z.discriminatedUnion('type', [\n z.object({ type: z.literal('data'), data: fileInlineDataSchema }),\n z.object({ type: z.literal('url'), url: z.instanceof(URL) }),\n]);\n\n/**\n * @internal\n */\nexport const filePartSchema: z.ZodType<FilePart> = z.object({\n type: z.literal('file'),\n data: z.union([\n taggedFileDataSchema,\n fileInlineDataSchema,\n z.instanceof(URL),\n providerReferenceSchema,\n ]),\n filename: z.string().optional(),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningPartSchema: z.ZodType<ReasoningPart> = z.object({\n type: z.literal('reasoning'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const customPartSchema: z.ZodType<CustomPart> = z.object({\n type: z.literal('custom'),\n kind: z.string().transform(value => value as `${string}.${string}`),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * @internal\n */\nexport const reasoningFilePartSchema: z.ZodType<ReasoningFilePart> = z.object({\n type: z.literal('reasoning-file'),\n data: z.union([\n taggedReasoningFileDataSchema,\n fileInlineDataSchema,\n z.instanceof(URL),\n ]),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n});\n\n/**\n * Tool call content part of a prompt. It contains a tool call (usually generated by the AI model).\n */\nexport interface ToolCallPart {\n type: 'tool-call';\n\n /**\n * ID of the tool call. This ID is used to match the tool call with the tool result.\n */\n toolCallId: string;\n\n /**\n * Name of the tool that is being called.\n */\n toolName: string;\n\n /**\n * Arguments of the tool call. This is a JSON-serializable object that matches the tool's input schema.\n */\n input: unknown;\n\n /**\n * Additional provider-specific metadata. 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 * @internal\n */\nexport const toolCallPartSchema: z.ZodType<ToolCallPart> = z.object({\n type: z.literal('tool-call'),\n toolCallId: z.string(),\n toolName: z.string(),\n input: z.unknown(),\n providerOptions: providerMetadataSchema.optional(),\n providerExecuted: z.boolean().optional(),\n}) as z.ZodType<ToolCallPart>; // necessary bc input is optional on Zod type\n\n/**\n * @internal\n */\nexport const outputSchema: z.ZodType<ToolResultOutput> = z.discriminatedUnion(\n 'type',\n [\n z.object({\n type: z.literal('text'),\n value: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('json'),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('execution-denied'),\n reason: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('error-text'),\n value: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('error-json'),\n value: jsonValueSchema,\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('content'),\n value: z.array(\n z.union([\n z.object({\n type: z.literal('text'),\n text: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('file'),\n data: taggedFileDataSchema,\n mediaType: z.string(),\n filename: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-data'),\n data: z.string(),\n mediaType: z.string(),\n filename: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-url'),\n url: z.string(),\n mediaType: z.string().optional(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-id'),\n fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('file-reference'),\n providerReference: z.record(z.string(), z.string()),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-data'),\n data: z.string(),\n mediaType: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-url'),\n url: z.string(),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-file-id'),\n fileId: z.union([z.string(), z.record(z.string(), z.string())]),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n // Deprecated.\n type: z.literal('image-file-reference'),\n providerReference: z.record(z.string(), z.string()),\n providerOptions: providerMetadataSchema.optional(),\n }),\n z.object({\n type: z.literal('custom'),\n providerOptions: providerMetadataSchema.optional(),\n }),\n ]),\n ),\n }),\n ],\n);\n\n/**\n * @internal\n */\nexport const toolResultPartSchema: z.ZodType<ToolResultPart> = z.object({\n type: z.literal('tool-result'),\n toolCallId: z.string(),\n toolName: z.string(),\n output: outputSchema,\n providerOptions: providerMetadataSchema.optional(),\n}) as z.ZodType<ToolResultPart>; // necessary bc result is optional on Zod type\n\n/**\n * @internal\n */\nexport const toolApprovalRequestSchema: z.ZodType<ToolApprovalRequest> =\n z.object({\n type: z.literal('tool-approval-request'),\n approvalId: z.string(),\n toolCallId: z.string(),\n });\n\n/**\n * @internal\n */\nexport const toolApprovalResponseSchema: z.ZodType<ToolApprovalResponse> =\n z.object({\n type: z.literal('tool-approval-response'),\n approvalId: z.string(),\n approved: z.boolean(),\n reason: z.string().optional(),\n });\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidArgumentError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidArgumentError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly parameter: string;\n readonly value: unknown;\n\n constructor({\n parameter,\n value,\n message,\n }: {\n parameter: string;\n value: unknown;\n message: string;\n }) {\n super({\n name,\n message: `Invalid argument for parameter ${parameter}: ${message}`,\n });\n\n this.parameter = parameter;\n this.value = value;\n }\n\n static isInstance(error: unknown): error is InvalidArgumentError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { LanguageModelCallOptions } from './language-model-call-options';\n\n/**\n * Validates model call options and returns a new object with normalized values.\n */\nexport function prepareLanguageModelCallOptions({\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n seed,\n stopSequences,\n reasoning,\n}: LanguageModelCallOptions): LanguageModelCallOptions {\n if (maxOutputTokens != null) {\n if (!Number.isInteger(maxOutputTokens)) {\n throw new InvalidArgumentError({\n parameter: 'maxOutputTokens',\n value: maxOutputTokens,\n message: 'maxOutputTokens must be an integer',\n });\n }\n\n if (maxOutputTokens < 1) {\n throw new InvalidArgumentError({\n parameter: 'maxOutputTokens',\n value: maxOutputTokens,\n message: 'maxOutputTokens must be >= 1',\n });\n }\n }\n\n if (temperature != null) {\n if (typeof temperature !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'temperature',\n value: temperature,\n message: 'temperature must be a number',\n });\n }\n }\n\n if (topP != null) {\n if (typeof topP !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topP',\n value: topP,\n message: 'topP must be a number',\n });\n }\n }\n\n if (topK != null) {\n if (typeof topK !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'topK',\n value: topK,\n message: 'topK must be a number',\n });\n }\n }\n\n if (presencePenalty != null) {\n if (typeof presencePenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'presencePenalty',\n value: presencePenalty,\n message: 'presencePenalty must be a number',\n });\n }\n }\n\n if (frequencyPenalty != null) {\n if (typeof frequencyPenalty !== 'number') {\n throw new InvalidArgumentError({\n parameter: 'frequencyPenalty',\n value: frequencyPenalty,\n message: 'frequencyPenalty must be a number',\n });\n }\n }\n\n if (seed != null) {\n if (!Number.isInteger(seed)) {\n throw new InvalidArgumentError({\n parameter: 'seed',\n value: seed,\n message: 'seed must be an integer',\n });\n }\n }\n\n return {\n maxOutputTokens,\n temperature,\n topP,\n topK,\n presencePenalty,\n frequencyPenalty,\n stopSequences,\n seed,\n reasoning,\n };\n}\n","import { APICallError } from '@ai-sdk/provider';\nimport { GatewayError } from '@ai-sdk/gateway';\nimport {\n retryWithExponentialBackoff,\n type RetryFunction,\n} from '@ai-sdk/provider-utils';\nimport { RetryError } from './retry-error';\n\nfunction getRetryDelayInMs({\n error,\n exponentialBackoffDelay,\n}: {\n error: APICallError | GatewayError;\n exponentialBackoffDelay: number;\n}): number {\n const headers = APICallError.isInstance(error)\n ? error.responseHeaders\n : APICallError.isInstance(error.cause)\n ? (error.cause as APICallError).responseHeaders\n : undefined;\n\n if (!headers) return exponentialBackoffDelay;\n\n let ms: number | undefined;\n\n // retry-ms is more precise than retry-after and used by e.g. OpenAI\n const retryAfterMs = headers['retry-after-ms'];\n if (retryAfterMs) {\n const timeoutMs = parseFloat(retryAfterMs);\n if (!Number.isNaN(timeoutMs)) {\n ms = timeoutMs;\n }\n }\n\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfter = headers['retry-after'];\n if (retryAfter && ms === undefined) {\n const timeoutSeconds = parseFloat(retryAfter);\n if (!Number.isNaN(timeoutSeconds)) {\n ms = timeoutSeconds * 1000;\n } else {\n ms = Date.parse(retryAfter) - Date.now();\n }\n }\n\n // check that the delay is reasonable:\n if (\n ms != null &&\n !Number.isNaN(ms) &&\n 0 <= ms &&\n (ms < 60 * 1000 || ms < exponentialBackoffDelay)\n ) {\n return ms;\n }\n\n return exponentialBackoffDelay;\n}\n\n/**\n * The `retryWithExponentialBackoffRespectingRetryHeaders` strategy retries a failed API call with an exponential backoff,\n * while respecting rate limit headers (retry-after-ms and retry-after) if they are provided and reasonable (0-60 seconds).\n * You can configure the maximum number of retries, the initial delay, and the backoff factor.\n */\nexport const retryWithExponentialBackoffRespectingRetryHeaders = ({\n maxRetries = 2,\n initialDelayInMs = 2000,\n backoffFactor = 2,\n abortSignal,\n}: {\n maxRetries?: number;\n initialDelayInMs?: number;\n backoffFactor?: number;\n abortSignal?: AbortSignal;\n} = {}): RetryFunction =>\n retryWithExponentialBackoff({\n maxRetries,\n initialDelayInMs,\n backoffFactor,\n abortSignal,\n shouldRetry: error =>\n error instanceof Error &&\n ((APICallError.isInstance(error) && error.isRetryable === true) ||\n (GatewayError.isInstance(error) && error.isRetryable === true)),\n getDelayInMs: ({ error, exponentialBackoffDelay }) =>\n getRetryDelayInMs({\n error: error as APICallError | GatewayError,\n exponentialBackoffDelay,\n }),\n createRetryError: ({ message, reason, errors }) =>\n new RetryError({ message, reason, errors }),\n });\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_RetryError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport type RetryErrorReason =\n | 'maxRetriesExceeded'\n | 'errorNotRetryable'\n | 'abort';\n\nexport class RetryError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n // note: property order determines debugging output\n readonly reason: RetryErrorReason;\n readonly lastError: unknown;\n readonly errors: Array<unknown>;\n\n constructor({\n message,\n reason,\n errors,\n }: {\n message: string;\n reason: RetryErrorReason;\n errors: Array<unknown>;\n }) {\n super({ name, message });\n\n this.reason = reason;\n this.errors = errors;\n\n // separate our last error to make debugging via log easier:\n this.lastError = errors[errors.length - 1];\n }\n\n static isInstance(error: unknown): error is RetryError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { InvalidArgumentError } from '../error/invalid-argument-error';\nimport type { RetryFunction } from '@ai-sdk/provider-utils';\nimport { retryWithExponentialBackoffRespectingRetryHeaders } from '../util/retry-with-exponential-backoff';\n/**\n * Validate and prepare retries.\n */\nexport function prepareRetries({\n maxRetries,\n abortSignal,\n}: {\n maxRetries: number | undefined;\n abortSignal: AbortSignal | undefined;\n}): {\n maxRetries: number;\n retry: RetryFunction;\n} {\n if (maxRetries != null) {\n if (!Number.isInteger(maxRetries)) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be an integer',\n });\n }\n\n if (maxRetries < 0) {\n throw new InvalidArgumentError({\n parameter: 'maxRetries',\n value: maxRetries,\n message: 'maxRetries must be >= 0',\n });\n }\n }\n\n const maxRetriesResult = maxRetries ?? 2;\n\n return {\n maxRetries: maxRetriesResult,\n retry: retryWithExponentialBackoffRespectingRetryHeaders({\n maxRetries: maxRetriesResult,\n abortSignal,\n }),\n };\n}\n","import type {\n ImageModelV4Usage,\n JSONObject,\n LanguageModelV4Usage,\n} from '@ai-sdk/provider';\n\n/**\n * Represents the number of tokens used in a prompt and completion.\n */\nexport type LanguageModelUsage = {\n /**\n * The total number of input (prompt) tokens used.\n */\n inputTokens: number | undefined;\n\n /**\n * Detailed information about the input tokens.\n */\n inputTokenDetails: {\n /**\n * The number of non-cached input (prompt) tokens used.\n */\n noCacheTokens: number | undefined;\n\n /**\n * The number of cached input (prompt) tokens read.\n */\n cacheReadTokens: number | undefined;\n\n /**\n * The number of cached input (prompt) tokens written.\n */\n cacheWriteTokens: number | undefined;\n };\n\n /**\n * The number of total output (completion) tokens used.\n */\n outputTokens: number | undefined;\n\n /**\n * Detailed information about the output tokens.\n */\n outputTokenDetails: {\n /**\n * The number of text tokens used.\n */\n textTokens: number | undefined;\n\n /**\n * The number of reasoning tokens used.\n */\n reasoningTokens: number | undefined;\n };\n\n /**\n * The total number of tokens used.\n */\n totalTokens: number | undefined;\n\n /**\n * Raw usage information from the provider.\n *\n * This is the usage information in the shape that the provider returns.\n * It can include additional information that is not part of the standard usage information.\n */\n raw?: JSONObject;\n};\n\n/**\n * Represents the number of tokens used in an embedding.\n */\n// TODO replace with EmbeddingModelV4Usage once available in @ai-sdk/provider\nexport type EmbeddingModelUsage = {\n /**\n * The number of tokens used in the embedding.\n */\n tokens: number;\n};\n\nexport function asLanguageModelUsage(\n usage: LanguageModelV4Usage,\n): LanguageModelUsage {\n return {\n inputTokens: usage.inputTokens.total,\n inputTokenDetails: {\n noCacheTokens: usage.inputTokens.noCache,\n cacheReadTokens: usage.inputTokens.cacheRead,\n cacheWriteTokens: usage.inputTokens.cacheWrite,\n },\n outputTokens: usage.outputTokens.total,\n outputTokenDetails: {\n textTokens: usage.outputTokens.text,\n reasoningTokens: usage.outputTokens.reasoning,\n },\n totalTokens: addTokenCounts(\n usage.inputTokens.total,\n usage.outputTokens.total,\n ),\n raw: usage.raw,\n };\n}\n\nexport function createNullLanguageModelUsage(): LanguageModelUsage {\n return {\n inputTokens: undefined,\n inputTokenDetails: {\n noCacheTokens: undefined,\n cacheReadTokens: undefined,\n cacheWriteTokens: undefined,\n },\n outputTokens: undefined,\n outputTokenDetails: {\n textTokens: undefined,\n reasoningTokens: undefined,\n },\n totalTokens: undefined,\n raw: undefined,\n };\n}\n\nexport function addLanguageModelUsage(\n usage1: LanguageModelUsage,\n usage2: LanguageModelUsage,\n): LanguageModelUsage {\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n inputTokenDetails: {\n noCacheTokens: addTokenCounts(\n usage1.inputTokenDetails?.noCacheTokens,\n usage2.inputTokenDetails?.noCacheTokens,\n ),\n cacheReadTokens: addTokenCounts(\n usage1.inputTokenDetails?.cacheReadTokens,\n usage2.inputTokenDetails?.cacheReadTokens,\n ),\n cacheWriteTokens: addTokenCounts(\n usage1.inputTokenDetails?.cacheWriteTokens,\n usage2.inputTokenDetails?.cacheWriteTokens,\n ),\n },\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n outputTokenDetails: {\n textTokens: addTokenCounts(\n usage1.outputTokenDetails?.textTokens,\n usage2.outputTokenDetails?.textTokens,\n ),\n reasoningTokens: addTokenCounts(\n usage1.outputTokenDetails?.reasoningTokens,\n usage2.outputTokenDetails?.reasoningTokens,\n ),\n },\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n };\n}\n\nfunction addTokenCounts(\n tokenCount1: number | undefined,\n tokenCount2: number | undefined,\n): number | undefined {\n return tokenCount1 == null && tokenCount2 == null\n ? undefined\n : (tokenCount1 ?? 0) + (tokenCount2 ?? 0);\n}\n\n/**\n * Usage information for an image model call.\n */\nexport type ImageModelUsage = ImageModelV4Usage;\n\nexport function addImageModelUsage(\n usage1: ImageModelUsage,\n usage2: ImageModelUsage,\n): ImageModelUsage {\n return {\n inputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n outputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n totalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n };\n}\n","import { gateway } from '@ai-sdk/gateway';\nimport type {\n EmbeddingModelV4,\n Experimental_VideoModelV4,\n ImageModelV4,\n LanguageModelV4,\n ProviderV4,\n RerankingModelV4,\n SpeechModelV4,\n TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport { UnsupportedModelVersionError } from '../error';\nimport type { EmbeddingModel } from '../types/embedding-model';\nimport type { LanguageModel } from '../types/language-model';\nimport type { SpeechModel } from '../types/speech-model';\nimport type { TranscriptionModel } from '../types/transcription-model';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asVideoModelV4 } from './as-video-model-v4';\nimport { asProviderV4 } from './as-provider-v4';\nimport type { ImageModel } from '../types/image-model';\nimport type { RerankingModel } from '../types/reranking-model';\nimport type { VideoModel } from '../types/video-model';\n\nexport function resolveLanguageModel(model: LanguageModel): LanguageModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().languageModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asLanguageModelV4(model);\n}\n\nexport function resolveEmbeddingModel(model: EmbeddingModel): EmbeddingModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().embeddingModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asEmbeddingModelV4(model);\n}\n\nexport function resolveTranscriptionModel(\n model: TranscriptionModel,\n): TranscriptionModelV4 | undefined {\n if (typeof model === 'string') {\n return getGlobalProvider().transcriptionModel?.(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asTranscriptionModelV4(model);\n}\n\nexport function resolveSpeechModel(\n model: SpeechModel,\n): SpeechModelV4 | undefined {\n if (typeof model === 'string') {\n return getGlobalProvider().speechModel?.(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asSpeechModelV4(model);\n}\n\nexport function resolveImageModel(model: ImageModel): ImageModelV4 {\n if (typeof model === 'string') {\n return getGlobalProvider().imageModel(model);\n }\n\n if (!['v4', 'v3', 'v2'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asImageModelV4(model);\n}\n\nexport function resolveVideoModel(\n model: VideoModel,\n): Experimental_VideoModelV4 {\n if (typeof model === 'string') {\n // Use raw global provider because videoModel is experimental\n // and not part of the ProviderV4 interface\n const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n // TODO AI SDK v7\n // @ts-expect-error - videoModel support is experimental\n const videoModel = provider.videoModel;\n\n if (!videoModel) {\n throw new Error(\n 'The default provider does not support video models. ' +\n 'Please use a Experimental_VideoModelV4 object from a provider (e.g., vertex.video(\"model-id\")).',\n );\n }\n\n return videoModel(model);\n }\n\n if (!['v4', 'v3'].includes(model.specificationVersion)) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asVideoModelV4(model);\n}\n\nexport function resolveRerankingModel(model: RerankingModel): RerankingModelV4 {\n if (typeof model === 'string') {\n const provider = getGlobalProvider();\n const rerankingModel = provider.rerankingModel;\n\n if (!rerankingModel) {\n throw new Error(\n 'The default provider does not support reranking models. ' +\n 'Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\"model-id\")).',\n );\n }\n\n return rerankingModel(model);\n }\n\n if (\n model.specificationVersion !== 'v4' &&\n model.specificationVersion !== 'v3'\n ) {\n const unsupportedModel: any = model;\n throw new UnsupportedModelVersionError({\n version: unsupportedModel.specificationVersion,\n provider: unsupportedModel.provider,\n modelId: unsupportedModel.modelId,\n });\n }\n\n return asRerankingModelV4(model);\n}\n\nfunction getGlobalProvider(): ProviderV4 {\n const provider = globalThis.AI_SDK_DEFAULT_PROVIDER ?? gateway;\n return asProviderV4(provider);\n}\n","export {\n AISDKError,\n APICallError,\n EmptyResponseBodyError,\n InvalidPromptError,\n InvalidResponseDataError,\n JSONParseError,\n LoadAPIKeyError,\n LoadSettingError,\n NoContentGeneratedError,\n NoSuchModelError,\n NoSuchProviderReferenceError,\n TooManyEmbeddingValuesForCallError,\n TypeValidationError,\n UnsupportedFunctionalityError,\n} from '@ai-sdk/provider';\n\nexport { InvalidArgumentError } from './invalid-argument-error';\nexport { InvalidStreamPartError } from './invalid-stream-part-error';\nexport { InvalidToolApprovalError } from './invalid-tool-approval-error';\nexport { InvalidToolApprovalSignatureError } from './invalid-tool-approval-signature-error';\nexport { InvalidToolInputError } from './invalid-tool-input-error';\nexport { ToolCallNotFoundForApprovalError } from './tool-call-not-found-for-approval-error';\nexport { MissingToolResultsError } from './missing-tool-result-error';\nexport { NoImageGeneratedError } from './no-image-generated-error';\nexport { NoObjectGeneratedError } from './no-object-generated-error';\nexport { NoOutputGeneratedError } from './no-output-generated-error';\nexport { NoSpeechGeneratedError } from './no-speech-generated-error';\nexport { NoTranscriptGeneratedError } from './no-transcript-generated-error';\nexport { NoVideoGeneratedError } from './no-video-generated-error';\nexport { NoSuchToolError } from './no-such-tool-error';\nexport { ToolCallRepairError } from './tool-call-repair-error';\nexport { UnsupportedModelVersionError } from './unsupported-model-version-error';\nexport { UIMessageStreamError } from './ui-message-stream-error';\nexport { InvalidDataContentError } from '../prompt/invalid-data-content-error';\nexport { InvalidMessageRoleError } from '../prompt/invalid-message-role-error';\nexport { MessageConversionError } from '../prompt/message-conversion-error';\nexport { DownloadError } from '@ai-sdk/provider-utils';\nexport { RetryError } from '../util/retry-error';\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly approvalId: string;\n\n constructor({ approvalId }: { approvalId: string }) {\n super({\n name,\n message:\n `Tool approval response references unknown approvalId: \"${approvalId}\". ` +\n `No matching tool-approval-request found in message history.`,\n });\n\n this.approvalId = approvalId;\n }\n\n static isInstance(error: unknown): error is InvalidToolApprovalError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolApprovalSignatureError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolApprovalSignatureError extends AISDKError {\n private readonly [symbol] = true;\n\n readonly approvalId: string;\n readonly toolCallId: string;\n\n constructor({\n approvalId,\n toolCallId,\n reason,\n }: {\n approvalId: string;\n toolCallId: string;\n reason: string;\n }) {\n super({\n name,\n message: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`,\n });\n this.approvalId = approvalId;\n this.toolCallId = toolCallId;\n }\n\n static isInstance(\n error: unknown,\n ): error is InvalidToolApprovalSignatureError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\n\nconst name = 'AI_InvalidToolInputError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class InvalidToolInputError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly toolInput: string;\n\n constructor({\n toolInput,\n toolName,\n cause,\n message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n toolInput: string;\n toolName: string;\n cause: unknown;\n }) {\n super({ name, message, cause });\n\n this.toolInput = toolInput;\n this.toolName = toolName;\n }\n\n static isInstance(error: unknown): error is InvalidToolInputError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_ToolCallNotFoundForApprovalError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallNotFoundForApprovalError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolCallId: string;\n readonly approvalId: string;\n\n constructor({\n toolCallId,\n approvalId,\n }: {\n toolCallId: string;\n approvalId: string;\n }) {\n super({\n name,\n message: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`,\n });\n\n this.toolCallId = toolCallId;\n this.approvalId = approvalId;\n }\n\n static isInstance(error: unknown): error is ToolCallNotFoundForApprovalError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\nconst name = 'AI_NoSuchToolError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class NoSuchToolError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly toolName: string;\n readonly availableTools: string[] | undefined;\n\n constructor({\n toolName,\n availableTools = undefined,\n message = `Model tried to call unavailable tool '${toolName}'. ${\n availableTools === undefined\n ? 'No tools are available.'\n : `Available tools: ${availableTools.join(', ')}.`\n }`,\n }: {\n toolName: string;\n availableTools?: string[] | undefined;\n message?: string;\n }) {\n super({ name, message });\n\n this.toolName = toolName;\n this.availableTools = availableTools;\n }\n\n static isInstance(error: unknown): error is NoSuchToolError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError, getErrorMessage } from '@ai-sdk/provider';\nimport type { InvalidToolInputError } from './invalid-tool-input-error';\nimport type { NoSuchToolError } from './no-such-tool-error';\n\nconst name = 'AI_ToolCallRepairError';\nconst marker = `vercel.ai.error.${name}`;\nconst symbol = Symbol.for(marker);\n\nexport class ToolCallRepairError extends AISDKError {\n private readonly [symbol] = true; // used in isInstance\n\n readonly originalError: NoSuchToolError | InvalidToolInputError;\n\n constructor({\n cause,\n originalError,\n message = `Error repairing tool call: ${getErrorMessage(cause)}`,\n }: {\n message?: string;\n cause: unknown;\n originalError: NoSuchToolError | InvalidToolInputError;\n }) {\n super({ name, message, cause });\n this.originalError = originalError;\n }\n\n static isInstance(error: unknown): error is ToolCallRepairError {\n return AISDKError.hasMarker(error, marker);\n }\n}\n","import { AISDKError } from '@ai-sdk/provider';\n\n/**\n * Error that is thrown when a model with an unsupported version is used.\n */\nexport class UnsupportedModelVersionError extends AISDKError {\n readonly version: string;\n readonly provider: string;\n readonly modelId: string;\n\n constructor(options: { version: string; provider: string; modelId: string }) {\n super({\n name: 'AI_UnsupportedModelVersionError',\n message:\n `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". ` +\n `AI SDK 5 only supports models that implement specification version \"v2\".`,\n });\n\n this.version = options.version;\n this.provider = options.provider;\n this.modelId = options.modelId;\n }\n}\n","import { logWarnings } from '../logger/log-warnings';\n\nexport function logV2CompatibilityWarning({\n provider,\n modelId,\n}: {\n provider: string;\n modelId: string;\n}): void {\n logWarnings({\n warnings: [\n {\n type: 'compatibility',\n feature: 'specificationVersion',\n details: `Using v2 specification compatibility mode. Some features may not be available.`,\n },\n ],\n provider,\n model: modelId,\n });\n}\n","import type { EmbeddingModelV2, EmbeddingModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asEmbeddingModelV3(\n model: EmbeddingModelV2<string> | EmbeddingModelV3,\n): EmbeddingModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof EmbeddingModelV2<string>) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as EmbeddingModelV3;\n}\n","import type {\n EmbeddingModelV2,\n EmbeddingModelV3,\n EmbeddingModelV4,\n} from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\n\nexport function asEmbeddingModelV4(\n model: EmbeddingModelV2<string> | EmbeddingModelV3 | EmbeddingModelV4,\n): EmbeddingModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asEmbeddingModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof EmbeddingModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as EmbeddingModelV4;\n}\n","import type { ImageModelV2, ImageModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asImageModelV3(\n model: ImageModelV2 | ImageModelV3,\n): ImageModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof ImageModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as ImageModelV3;\n}\n","import type {\n ImageModelV2,\n ImageModelV3,\n ImageModelV4,\n} from '@ai-sdk/provider';\nimport { asImageModelV3 } from './as-image-model-v3';\n\nexport function asImageModelV4(\n model: ImageModelV2 | ImageModelV3 | ImageModelV4,\n): ImageModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asImageModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof ImageModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as ImageModelV4;\n}\n","import type {\n LanguageModelV2,\n LanguageModelV2FinishReason,\n LanguageModelV2StreamPart,\n LanguageModelV2Usage,\n LanguageModelV3,\n LanguageModelV3FinishReason,\n LanguageModelV3StreamPart,\n LanguageModelV3Usage,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asLanguageModelV3(\n model: LanguageModelV2 | LanguageModelV3,\n): LanguageModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof LanguageModelV2) {\n switch (prop) {\n case 'specificationVersion':\n return 'v3';\n case 'doGenerate':\n return async (...args: Parameters<LanguageModelV2['doGenerate']>) => {\n const result = await target.doGenerate(...args);\n return {\n ...result,\n finishReason: convertV2FinishReasonToV3(result.finishReason),\n usage: convertV2UsageToV3(result.usage),\n };\n };\n case 'doStream':\n return async (...args: Parameters<LanguageModelV2['doStream']>) => {\n const result = await target.doStream(...args);\n return {\n ...result,\n stream: convertV2StreamToV3(result.stream),\n };\n };\n default:\n return target[prop];\n }\n },\n }) as unknown as LanguageModelV3;\n}\n\nfunction convertV2StreamToV3(\n stream: ReadableStream<LanguageModelV2StreamPart>,\n): ReadableStream<LanguageModelV3StreamPart> {\n return stream.pipeThrough(\n new TransformStream<LanguageModelV2StreamPart, LanguageModelV3StreamPart>({\n transform(chunk, controller) {\n switch (chunk.type) {\n case 'finish':\n controller.enqueue({\n ...chunk,\n finishReason: convertV2FinishReasonToV3(chunk.finishReason),\n usage: convertV2UsageToV3(chunk.usage),\n });\n break;\n default:\n // TODO: AI SDK 6 - no casting (stream parts need to be mapped)\n controller.enqueue(chunk as LanguageModelV3StreamPart);\n break;\n }\n },\n }),\n );\n}\n\nfunction convertV2FinishReasonToV3(\n finishReason: LanguageModelV2FinishReason,\n): LanguageModelV3FinishReason {\n return {\n unified: finishReason === 'unknown' ? 'other' : finishReason,\n raw: undefined,\n };\n}\n\nfunction convertV2UsageToV3(usage: LanguageModelV2Usage): LanguageModelV3Usage {\n return {\n inputTokens: {\n total: usage.inputTokens,\n noCache: undefined,\n cacheRead: usage.cachedInputTokens,\n cacheWrite: undefined,\n },\n outputTokens: {\n total: usage.outputTokens,\n text: undefined,\n reasoning: usage.reasoningTokens,\n },\n };\n}\n","import type {\n LanguageModelV2,\n LanguageModelV3,\n LanguageModelV4,\n} from '@ai-sdk/provider';\nimport { asLanguageModelV3 } from './as-language-model-v3';\n\nexport function asLanguageModelV4(\n model: LanguageModelV2 | LanguageModelV3 | LanguageModelV4,\n): LanguageModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asLanguageModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof LanguageModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as LanguageModelV4;\n}\n","import type { RerankingModelV3, RerankingModelV4 } from '@ai-sdk/provider';\n\nexport function asRerankingModelV4(\n model: RerankingModelV3 | RerankingModelV4,\n): RerankingModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n return new Proxy(model, {\n get(target, prop: keyof RerankingModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as RerankingModelV4;\n}\n","import type { SpeechModelV2, SpeechModelV3 } from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asSpeechModelV3(\n model: SpeechModelV3 | SpeechModelV2,\n): SpeechModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof SpeechModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as SpeechModelV3;\n}\n","import type {\n SpeechModelV2,\n SpeechModelV3,\n SpeechModelV4,\n} from '@ai-sdk/provider';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asSpeechModelV4(\n model: SpeechModelV2 | SpeechModelV3 | SpeechModelV4,\n): SpeechModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asSpeechModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof SpeechModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as SpeechModelV4;\n}\n","import type {\n TranscriptionModelV2,\n TranscriptionModelV3,\n} from '@ai-sdk/provider';\nimport { logV2CompatibilityWarning } from '../util/log-v2-compatibility-warning';\n\nexport function asTranscriptionModelV3(\n model: TranscriptionModelV3 | TranscriptionModelV2,\n): TranscriptionModelV3 {\n if (model.specificationVersion === 'v3') {\n return model;\n }\n\n logV2CompatibilityWarning({\n provider: model.provider,\n modelId: model.modelId,\n });\n\n // TODO this could break, we need to properly map v2 to v3\n // and support all relevant v3 properties:\n return new Proxy(model, {\n get(target, prop: keyof TranscriptionModelV2) {\n if (prop === 'specificationVersion') return 'v3';\n return target[prop];\n },\n }) as unknown as TranscriptionModelV3;\n}\n","import type {\n TranscriptionModelV2,\n TranscriptionModelV3,\n TranscriptionModelV4,\n} from '@ai-sdk/provider';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\n\nexport function asTranscriptionModelV4(\n model: TranscriptionModelV2 | TranscriptionModelV3 | TranscriptionModelV4,\n): TranscriptionModelV4 {\n if (model.specificationVersion === 'v4') {\n return model;\n }\n\n // first convert v2 to v3, then proxy v3 as v4:\n const v3Model =\n model.specificationVersion === 'v2' ? asTranscriptionModelV3(model) : model;\n\n return new Proxy(v3Model, {\n get(target, prop: keyof TranscriptionModelV3) {\n if (prop === 'specificationVersion') return 'v4';\n return target[prop];\n },\n }) as unknown as TranscriptionModelV4;\n}\n","import type { ProviderV2, ProviderV3 } from '@ai-sdk/provider';\nimport { asEmbeddingModelV3 } from './as-embedding-model-v3';\nimport { asImageModelV3 } from './as-image-model-v3';\nimport { asLanguageModelV3 } from './as-language-model-v3';\nimport { asTranscriptionModelV3 } from './as-transcription-model-v3';\nimport { asSpeechModelV3 } from './as-speech-model-v3';\n\nexport function asProviderV3(provider: ProviderV2 | ProviderV3): ProviderV3 {\n if (\n 'specificationVersion' in provider &&\n provider.specificationVersion === 'v3'\n ) {\n return provider;\n }\n\n // v3 providers have already been returned\n const v2Provider: ProviderV2 = provider as ProviderV2;\n\n return {\n specificationVersion: 'v3',\n languageModel: (modelId: string) =>\n asLanguageModelV3(v2Provider.languageModel(modelId)),\n embeddingModel: (modelId: string) =>\n asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n imageModel: (modelId: string) =>\n asImageModelV3(v2Provider.imageModel(modelId)),\n transcriptionModel: v2Provider.transcriptionModel\n ? (modelId: string) =>\n asTranscriptionModelV3(v2Provider.transcriptionModel!(modelId))\n : undefined,\n speechModel: v2Provider.speechModel\n ? (modelId: string) => asSpeechModelV3(v2Provider.speechModel!(modelId))\n : undefined,\n rerankingModel: undefined, // v2 providers don't have reranking models\n };\n}\n","import type { ProviderV2, ProviderV3, ProviderV4 } from '@ai-sdk/provider';\nimport { asProviderV3 } from './as-provider-v3';\nimport { asEmbeddingModelV4 } from './as-embedding-model-v4';\nimport { asImageModelV4 } from './as-image-model-v4';\nimport { asLanguageModelV4 } from './as-language-model-v4';\nimport { asRerankingModelV4 } from './as-reranking-model-v4';\nimport { asTranscriptionModelV4 } from './as-transcription-model-v4';\nimport { asSpeechModelV4 } from './as-speech-model-v4';\n\nexport function asProviderV4(\n provider: ProviderV2 | ProviderV3 | ProviderV4,\n): ProviderV4 {\n if (\n 'specificationVersion' in provider &&\n provider.specificationVersion === 'v4'\n ) {\n return provider;\n }\n\n // first ensure we have at least a v3 provider:\n const v3Provider: ProviderV3 =\n !('specificationVersion' in provider) ||\n provider.specificationVersion !== 'v3'\n ? asProviderV3(provider as ProviderV2)\n : provider;\n\n return {\n specificationVersion: 'v4',\n languageModel: (modelId: string) =>\n asLanguageModelV4(v3Provider.languageModel(modelId)),\n embeddingModel: (modelId: string) =>\n asEmbeddingModelV4(v3Provider.embeddingModel(modelId)),\n imageModel: (modelId: string) =>\n asImageModelV4(v3Provider.imageModel(modelId)),\n transcriptionModel: v3Provider.transcriptionModel\n ? (modelId: string) =>\n asTranscriptionModelV4(v3Provider.transcriptionModel!(modelId))\n : undefined,\n speechModel: v3Provider.speechModel\n ? (modelId: string) => asSpeechModelV4(v3Provider.speechModel!(modelId))\n : undefined,\n rerankingModel: v3Provider.rerankingModel\n ? (modelId: string) =>\n asRerankingModelV4(v3Provider.rerankingModel!(modelId))\n : undefined,\n };\n}\n","import { filterNullable } from '@ai-sdk/provider-utils';\n\n/**\n * Merges multiple abort sources into a single `AbortSignal`.\n * The returned signal will abort when any input signal aborts or when any\n * numeric timeout elapses, using the reason from the first source to abort.\n *\n * @param signals - Abort signals or timeout durations in milliseconds.\n * `null` and `undefined` values are ignored.\n * @returns An `AbortSignal` that aborts when any valid source aborts,\n * or `undefined` if no valid sources are provided.\n */\nexport function mergeAbortSignals(\n ...signals: (AbortSignal | null | undefined | number)[]\n): AbortSignal | undefined {\n const validSignals = filterNullable(...signals).map(signal =>\n signal instanceof AbortSignal ? signal : AbortSignal.timeout(signal),\n );\n\n return validSignals.length === 0\n ? undefined\n : validSignals.length === 1\n ? validSignals[0]\n : AbortSignal.any(validSignals);\n}\n","import type { Callback } from '../util/callback';\n\n/**\n * Creates an async callback that invokes the provided callbacks in parallel.\n * Undefined callbacks are skipped, and thrown or rejected callback errors are\n * ignored.\n *\n * @param callbacks The callbacks to invoke for each event.\n * @returns A callback that forwards each event to all callbacks and waits for\n * them to settle.\n */\nexport function mergeCallbacks<EVENT>(\n ...callbacks: Array<Callback<EVENT> | undefined>\n): Callback<EVENT> {\n return async (event: EVENT) => {\n await Promise.allSettled(\n callbacks.map(async callback => {\n await callback?.(event);\n }),\n );\n };\n}\n","import { asArray } from '@ai-sdk/provider-utils';\nimport type { Callback } from '../util/callback';\nimport { mergeCallbacks } from '../util/merge-callbacks';\nimport type {\n InferTelemetryEvent,\n Telemetry,\n TelemetryDispatcher,\n} from './telemetry';\nimport {\n openTelemetryChannelSpanContext,\n runWithTracingChannelSpan,\n} from './tracing-channel-publisher';\nimport { getGlobalTelemetryIntegrations } from './telemetry-registry';\nimport type { TelemetryOptions } from './telemetry-options';\n\n/**\n * The subset of `TelemetryDispatcher` keys whose values are Callback callbacks.\n * This excludes dispatcher-only helpers and non-Callback properties such as\n * `executeLanguageModelCall` and `executeTool`.\n */\ntype TelemetryCallbackKey = Exclude<\n keyof {\n [K in keyof TelemetryDispatcher as TelemetryDispatcher[K] extends\n | Callback<any>\n | undefined\n ? K\n : never]: true;\n },\n 'runInTracingChannelSpan' | 'startTracingChannelContext'\n>;\n\n/**\n * Resolves the public event type accepted by a telemetry callback key.\n */\ntype TelemetryEvent<K extends TelemetryCallbackKey> =\n TelemetryDispatcher[K] extends Callback<infer EVENT> | undefined\n ? EVENT\n : never;\n\nfunction augmentEvent<EVENT>(\n event: EVENT,\n telemetry: Pick<\n TelemetryOptions,\n 'recordInputs' | 'recordOutputs' | 'functionId'\n >,\n): InferTelemetryEvent<EVENT> {\n return Object.assign(\n Object.create(Object.getPrototypeOf(event)),\n event,\n telemetry,\n );\n}\n\n/**\n * Creates a telemetry dispatcher that sends telemetry events\n * to the resolved set of integrations.\n *\n * When per-call integrations are provided, they take precedence over the globally\n * registered integrations for that call. When no per-call integrations are\n * provided, the globally registered integrations are used.\n *\n * @param args.telemetry - Optional per-call telemetry settings and integrations.\n *\n * @returns A telemetry dispatcher that fans out lifecycle events to the\n * resolved set of integrations.\n */\nexport function createTelemetryDispatcher({\n telemetry,\n}: {\n telemetry?: TelemetryOptions;\n // operationId: string;\n}): TelemetryDispatcher {\n // When telemetry is explicitly disabled, return a dispatcher\n // that performs no work and lets tool execution pass through unwrapped.\n if (telemetry?.isEnabled === false) {\n return {};\n }\n\n const localIntegrations = telemetry?.integrations;\n const integrations: Array<Telemetry> =\n localIntegrations != null\n ? asArray(localIntegrations)\n : getGlobalTelemetryIntegrations();\n\n const telemetryMetadata = {\n recordInputs: telemetry?.recordInputs,\n recordOutputs: telemetry?.recordOutputs,\n functionId: telemetry?.functionId,\n };\n\n const mergeTelemetryCallback = <KEY extends TelemetryCallbackKey>(\n key: KEY,\n ): Callback<TelemetryEvent<KEY>> => {\n const integrationCallbacks = (\n integrations\n .map(integration => integration[key]?.bind(integration))\n .filter(Boolean) as Array<\n Callback<InferTelemetryEvent<TelemetryEvent<KEY>>>\n >\n ).map(\n callback =>\n ((event: TelemetryEvent<KEY>) =>\n callback(augmentEvent(event, telemetryMetadata))) as Callback<\n TelemetryEvent<KEY>\n >,\n );\n\n const mergedIntegrationCallback = mergeCallbacks(...integrationCallbacks);\n\n return async (event: TelemetryEvent<KEY>) => {\n await mergedIntegrationCallback(event);\n };\n };\n\n const executeLanguageModelCallWrappers = integrations\n .map(integration => integration.executeLanguageModelCall?.bind(integration))\n .filter(Boolean) as Array<\n NonNullable<Telemetry['executeLanguageModelCall']>\n >;\n\n const executeToolWrappers = integrations\n .map(integration => integration.executeTool?.bind(integration))\n .filter(Boolean) as Array<NonNullable<Telemetry['executeTool']>>;\n\n return {\n runInTracingChannelSpan: async ({ type, event, execute }) =>\n await runWithTracingChannelSpan(\n {\n type,\n event: augmentEvent(event, telemetryMetadata),\n },\n execute,\n ),\n\n startTracingChannelContext: ({ type, event, completion }) =>\n openTelemetryChannelSpanContext({\n message: {\n type,\n event: augmentEvent(event, telemetryMetadata),\n },\n completion,\n }),\n\n onStart: mergeTelemetryCallback('onStart'),\n onStepStart: mergeTelemetryCallback('onStepStart'),\n onLanguageModelCallStart: mergeTelemetryCallback(\n 'onLanguageModelCallStart',\n ),\n onLanguageModelCallEnd: mergeTelemetryCallback('onLanguageModelCallEnd'),\n onToolExecutionStart: mergeTelemetryCallback('onToolExecutionStart'),\n onToolExecutionEnd: mergeTelemetryCallback('onToolExecutionEnd'),\n // Fan out step-end events to both the new `onStepEnd` callback and the\n // deprecated `onStepFinish` callback so integrations that still implement\n // only `onStepFinish` keep receiving step-end events during the deprecation\n // window.\n onStepEnd: mergeCallbacks(\n mergeTelemetryCallback('onStepEnd'),\n mergeTelemetryCallback('onStepFinish'),\n ),\n onObjectStepStart: mergeTelemetryCallback('onObjectStepStart'),\n onObjectStepEnd: mergeTelemetryCallback('onObjectStepEnd'),\n onEmbedStart: mergeTelemetryCallback('onEmbedStart'),\n onEmbedEnd: mergeTelemetryCallback('onEmbedEnd'),\n onRerankStart: mergeTelemetryCallback('onRerankStart'),\n onRerankEnd: mergeTelemetryCallback('onRerankEnd'),\n onEnd: mergeTelemetryCallback('onEnd'),\n onAbort: mergeTelemetryCallback('onAbort'),\n onError: mergeTelemetryCallback('onError'),\n\n /**\n * Runs provider calls inside integration-specific context so\n * auto-instrumented provider requests can be associated with model work.\n */\n executeLanguageModelCall: async ({ execute, ...event }) => {\n const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n let wrappedExecute = execute;\n for (const executeWrapper of executeLanguageModelCallWrappers) {\n const innerExecute = wrappedExecute;\n wrappedExecute = () =>\n executeWrapper({ ...augmentedEvent, execute: innerExecute });\n }\n\n return await runWithTracingChannelSpan(\n { type: 'languageModelCall', event: augmentedEvent },\n wrappedExecute,\n );\n },\n\n /**\n * Composes all `executeTool` wrappers around the original tool execution.\n * Each wrapper receives an `execute` function that calls the next wrapper in\n * the chain, so integrations can establish nested telemetry context before\n * delegating to the underlying tool.\n */\n executeTool: async ({ execute, ...event }) => {\n const augmentedEvent = augmentEvent(event, telemetryMetadata);\n\n let wrappedExecute = execute;\n for (const executeWrapper of executeToolWrappers) {\n const innerExecute = wrappedExecute;\n wrappedExecute = () =>\n executeWrapper({ ...augmentedEvent, execute: innerExecute });\n }\n\n return await wrappedExecute();\n },\n };\n}\n","export const AI_SDK_TELEMETRY_TRACING_CHANNEL = 'ai:telemetry';\n\nexport type TelemetryTracingEventType =\n | 'generateText'\n | 'streamText'\n | 'step'\n | 'languageModelCall'\n | 'executeTool'\n | 'embed'\n | 'rerank';\n\nexport type TelemetryTracingChannelMessage<EVENT = unknown> = {\n readonly type: TelemetryTracingEventType;\n readonly event: EVENT;\n};\n","export function isNodeRuntime(): boolean {\n return typeof process !== 'undefined' && process.release?.name === 'node';\n}\n","import type * as diagnosticsChannelModule from 'node:diagnostics_channel';\nimport type * as asyncHooksModule from 'node:async_hooks';\nimport {\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n type TelemetryTracingChannelMessage,\n} from './tracing-channel';\nimport { isNodeRuntime } from '../util/is-node-runtime';\n\ntype DiagnosticsChannel = typeof diagnosticsChannelModule;\ntype AsyncHooks = typeof asyncHooksModule;\ntype AsyncResource = asyncHooksModule.AsyncResource;\n\nexport type TracingChannelContext = {\n run<T>(execute: () => T): T;\n};\n\nlet diagnosticsChannelPromise:\n | Promise<DiagnosticsChannel | undefined>\n | undefined;\n\n/**\n * Loads Node's diagnostics channel module only when the current runtime supports\n * it. Unsupported runtimes and failed imports intentionally resolve to\n * undefined so telemetry tracing never crashes user code.\n */\nasync function loadDiagnosticsChannel(): Promise<\n DiagnosticsChannel | undefined\n> {\n if (!isNodeRuntime()) {\n return undefined;\n }\n\n if (diagnosticsChannelPromise == null) {\n diagnosticsChannelPromise = (\n import(\n /* webpackIgnore: true */\n 'node:diagnostics_channel'\n ) as Promise<DiagnosticsChannel>\n ).catch(() => undefined);\n }\n\n return diagnosticsChannelPromise;\n}\n\nfunction loadBuiltinModule<T>(id: string): T | undefined {\n const processWithBuiltins = globalThis.process as\n | {\n getBuiltinModule?: (id: string) => unknown;\n }\n | undefined;\n\n try {\n return processWithBuiltins?.getBuiltinModule?.(id) as T | undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Runs an async operation inside the AI SDK telemetry tracing channel when\n * tracing subscribers may exist. Without Node diagnostics-channel support,\n * without tracingChannel support, or when the runtime reports no subscribers,\n * this is a direct pass-through.\n *\n * The execution bookkeeping preserves the original model/tool result or error\n * if tracing itself throws, and prevents falling back by calling `execute` a\n * second time.\n */\nexport async function runWithTracingChannelSpan<T>(\n message: TelemetryTracingChannelMessage,\n execute: () => PromiseLike<T>,\n): Promise<T> {\n const diagnosticsChannel = await loadDiagnosticsChannel();\n const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n );\n\n if (tracingChannel == null || tracingChannel.hasSubscribers === false) {\n return await execute();\n }\n\n let executePromise: Promise<T> | undefined;\n let executionResult: T | undefined;\n let executionError: unknown;\n let hasExecutionResult = false;\n let hasExecutionError = false;\n\n const tracedExecute = () => {\n try {\n executePromise = Promise.resolve(execute());\n } catch (error) {\n executePromise = Promise.reject(error);\n }\n\n executePromise = executePromise.then(\n result => {\n executionResult = result;\n hasExecutionResult = true;\n return result;\n },\n error => {\n executionError = error;\n hasExecutionError = true;\n throw error;\n },\n );\n\n return executePromise;\n };\n\n try {\n return await tracingChannel.tracePromise(tracedExecute, message);\n } catch {\n if (hasExecutionError) {\n throw executionError;\n }\n\n if (hasExecutionResult) {\n return executionResult as T;\n }\n\n if (executePromise != null) {\n return await executePromise;\n }\n\n return await execute();\n }\n}\n\n/**\n * Opens a long-lived tracing-channel span context and returns a runner that can\n * re-enter that context later without changing stream setup timing.\n */\nexport function openTelemetryChannelSpanContext({\n message,\n completion,\n}: {\n message: TelemetryTracingChannelMessage;\n completion: PromiseLike<unknown>;\n}): TracingChannelContext | undefined {\n if (!isNodeRuntime()) {\n return undefined;\n }\n\n const diagnosticsChannel = loadBuiltinModule<DiagnosticsChannel>(\n 'node:diagnostics_channel',\n );\n const asyncHooks = loadBuiltinModule<AsyncHooks>('node:async_hooks');\n const tracingChannel = diagnosticsChannel?.tracingChannel?.(\n AI_SDK_TELEMETRY_TRACING_CHANNEL,\n );\n\n if (\n tracingChannel == null ||\n tracingChannel.hasSubscribers === false ||\n asyncHooks == null\n ) {\n Promise.resolve(completion).catch(() => {});\n return undefined;\n }\n\n const context = message as TelemetryTracingChannelMessage & {\n result?: unknown;\n error?: unknown;\n };\n let asyncResource: AsyncResource | undefined;\n let asyncEndPublished = false;\n\n const safePublish = (publish: () => void) => {\n try {\n publish();\n } catch {\n // Diagnostics subscribers should never affect SDK stream behavior.\n }\n };\n\n const publishAsyncEnd = ({\n result,\n error,\n }: {\n result?: unknown;\n error?: unknown;\n }) => {\n if (asyncEndPublished) {\n return;\n }\n\n asyncEndPublished = true;\n\n if (error !== undefined) {\n context.error = error;\n safePublish(() => tracingChannel.error.publish(context));\n }\n\n if (result !== undefined) {\n context.result = result;\n }\n\n safePublish(() => tracingChannel.asyncEnd.publish(context));\n };\n\n safePublish(() => {\n tracingChannel.start.runStores(context, () => {\n asyncResource = new asyncHooks.AsyncResource('ai.telemetry');\n });\n });\n safePublish(() => tracingChannel.end.publish(context));\n\n void Promise.resolve(completion).then(\n result => publishAsyncEnd({ result }),\n error => publishAsyncEnd({ error }),\n );\n\n return {\n run: execute =>\n asyncResource == null\n ? execute()\n : asyncResource.runInAsyncScope(execute),\n };\n}\n","import type { Telemetry } from './telemetry';\n\n/**\n * Registers one or more telemetry integrations globally.\n */\nexport function registerTelemetry(...integrations: Telemetry[]): void {\n if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n }\n globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);\n}\n\nexport function getGlobalTelemetryIntegrations(): Telemetry[] {\n return globalThis.AI_SDK_TELEMETRY_INTEGRATIONS ?? [];\n}\n","import type { ReasoningPart, ReasoningFilePart } from '@ai-sdk/provider-utils';\n\nexport function asReasoningText(\n reasoningParts: Array<ReasoningPart | ReasoningFilePart>,\n): string | undefined {\n const reasoningText = reasoningParts\n .map(part => ('text' in part ? part.text : ''))\n .join('');\n return reasoningText.length > 0 ? reasoningText : undefined;\n}\n","import type {\n DataContent,\n ReasoningFilePart,\n ReasoningPart,\n} from '@ai-sdk/provider-utils';\nimport type { ProviderMetadata } from '../types/provider-metadata';\nimport { DefaultGeneratedFile, type GeneratedFile } from './generated-file';\n\nfunction unwrapReasoningFileData(\n data: ReasoningFilePart['data'],\n): DataContent | URL {\n if (typeof data === 'object' && data !== null && 'type' in data) {\n return data.type === 'data' ? data.data : data.url;\n }\n return data;\n}\n\n/**\n * Reasoning output of a text generation. It contains a reasoning.\n */\nexport interface ReasoningOutput {\n type: 'reasoning';\n\n /**\n * The reasoning text.\n */\n text: string;\n\n /**\n * Additional provider-specific metadata. 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 providerMetadata?: ProviderMetadata;\n}\n\n/**\n * Reasoning file output of a text generation.\n * It contains a file generated as part of reasoning.\n */\nexport interface ReasoningFileOutput {\n type: 'reasoning-file';\n\n /**\n * The generated file.\n */\n file: GeneratedFile;\n\n /**\n * Additional provider-specific metadata. 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 providerMetadata?: ProviderMetadata;\n}\n\nexport function convertFromReasoningOutputs(\n parts: Array<ReasoningOutput | ReasoningFileOutput>,\n): Array<ReasoningPart | ReasoningFilePart> {\n return parts.map(part => {\n if (part.type === 'reasoning') {\n return {\n type: 'reasoning' as const,\n text: part.text,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n };\n }\n\n return {\n type: 'reasoning-file' as const,\n data: part.file.base64,\n mediaType: part.file.mediaType,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n };\n });\n}\n\nexport function convertToReasoningOutputs(\n parts: Array<ReasoningPart | ReasoningFilePart>,\n): Array<ReasoningOutput | ReasoningFileOutput> {\n return parts.map(part => {\n if (part.type === 'reasoning') {\n return {\n type: 'reasoning' as const,\n text: part.text,\n ...(part.providerOptions != null\n ? { providerMetadata: part.providerOptions as ProviderMetadata }\n : {}),\n };\n }\n\n const rawData = unwrapReasoningFileData(part.data);\n\n const fileData: string | Uint8Array =\n rawData instanceof ArrayBuffer\n ? new Uint8Array(rawData)\n : rawData instanceof URL\n ? rawData.toString()\n : (rawData as string | Uint8Array);\n\n return {\n type: 'reasoning-file' as const,\n file: new DefaultGeneratedFile({\n data: fileData,\n mediaType: part.mediaType,\n }),\n ...(part.providerOptions != null\n ? { providerMetadata: part.providerOptions as ProviderMetadata }\n : {}),\n };\n });\n}\n","import type {\n Context,\n InferToolSetContext,\n ReasoningFilePart,\n ReasoningPart,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n CallWarning,\n FinishReason,\n LanguageModelRequestMetadata,\n LanguageModelResponseMetadata,\n ProviderMetadata,\n} from '../types';\nimport type { Source } from '../types/language-model';\nimport type { LanguageModelUsage } from '../types/usage';\nimport type { ContentPart } from './content-part';\nimport type { GeneratedFile } from './generated-file';\nimport { asReasoningText } from './reasoning';\nimport {\n convertFromReasoningOutputs,\n type ReasoningFileOutput,\n type ReasoningOutput,\n} from './reasoning-output';\nimport type {\n DynamicToolCall,\n StaticToolCall,\n TypedToolCall,\n} from './tool-call';\nimport type {\n DynamicToolResult,\n StaticToolResult,\n TypedToolResult,\n} from './tool-result';\n\n/**\n * Timing statistics for the gaps between generated output chunks.\n */\nexport type OutputChunkTimingStats = {\n /** Shortest observed time between output chunks in milliseconds. */\n readonly min: number;\n\n /** 10th percentile time between output chunks in milliseconds. */\n readonly p10: number;\n\n /** Median time between output chunks in milliseconds. */\n readonly median: number;\n\n /** Average time between output chunks in milliseconds. */\n readonly avg: number;\n\n /** 90th percentile time between output chunks in milliseconds. */\n readonly p90: number;\n\n /** Longest observed time between output chunks in milliseconds. */\n readonly max: number;\n};\n\n/**\n * Performance metrics for a single step in the generation process.\n */\nexport type StepResultPerformance = {\n /**\n * Effective number of output tokens per second over the full language model\n * response.\n *\n * Calculated as `outputTokens / requestSeconds`.\n */\n readonly effectiveOutputTokensPerSecond: number;\n\n /**\n * Number of output tokens per second after the first generated output chunk\n * was received.\n *\n * Only available for streaming steps.\n *\n * Calculated as `outputTokens / outputStreamSeconds`.\n */\n readonly outputTokensPerSecond: number | undefined;\n\n /**\n * Number of input tokens processed per second before the first generated\n * output chunk was received.\n *\n * Only available for streaming steps.\n *\n * Calculated as `inputTokens / ttftSeconds`.\n */\n readonly inputTokensPerSecond: number | undefined;\n\n /**\n * Effective number of input and output tokens per second over the full\n * language model response.\n *\n * Calculated as `(inputTokens + outputTokens) / requestSeconds`.\n */\n readonly effectiveTotalTokensPerSecond: number;\n\n /**\n * Total time spent on the step in milliseconds.\n */\n readonly stepTimeMs: number;\n\n /**\n * Time spent waiting for the language model response in milliseconds.\n */\n readonly responseTimeMs: number;\n\n /**\n * Time spent executing each client-side tool call in milliseconds, keyed by\n * tool call ID.\n */\n readonly toolExecutionMs: Readonly<Record<string, number>>;\n\n /**\n * Time until the first generated output chunk was received in milliseconds.\n *\n * This includes text deltas, reasoning deltas, generated files, reasoning\n * files, tool input deltas, and tool calls.\n *\n * Only available for streaming steps.\n */\n readonly timeToFirstOutputMs: number | undefined;\n\n /**\n * Timing statistics for the gaps between generated output chunks in\n * milliseconds.\n *\n * Only available for streaming steps with at least two generated output\n * chunks.\n */\n readonly timeBetweenOutputChunksMs?: OutputChunkTimingStats;\n};\n\n/**\n * The result of a single step in the generation process.\n */\nexport type StepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context = Context,\n> = {\n /**\n * Unique identifier for the generation call this step belongs to.\n */\n readonly callId: string;\n\n /**\n * Zero-based index of this step.\n */\n readonly stepNumber: number;\n\n /**\n * Information about the model that produced this step.\n */\n readonly model: {\n /** The provider of the model. */\n readonly provider: string;\n\n /** The ID of the model. */\n readonly modelId: string;\n };\n\n /**\n * Tool context.\n */\n readonly toolsContext: InferToolSetContext<TOOLS>;\n\n /**\n * The runtime context that was used as input for the step.\n */\n readonly runtimeContext: RUNTIME_CONTEXT;\n\n /**\n * The content that was generated in the last step.\n */\n readonly content: Array<ContentPart<TOOLS>>;\n\n /**\n * The generated text. Can be an empty string if the model has not generated any text.\n */\n readonly text: string;\n\n /**\n * The reasoning that was generated during the generation.\n */\n readonly reasoning: Array<ReasoningPart | ReasoningFilePart>;\n\n /**\n * The reasoning text that was generated during the generation.\n *\n * It is a concatenation of all reasoning parts (but excluding reasoning file parts).\n * Can be undefined if the model has only generated text.\n */\n readonly reasoningText: string | undefined;\n\n /**\n * The files that were generated during the generation.\n */\n readonly files: Array<GeneratedFile>;\n\n /**\n * The sources that were used to generate the text.\n */\n readonly sources: Array<Source>;\n\n /**\n * The tool calls that were made during the generation.\n */\n readonly toolCalls: Array<TypedToolCall<TOOLS>>;\n\n /**\n * The static tool calls that were made in the last step.\n */\n readonly staticToolCalls: Array<StaticToolCall<TOOLS>>;\n\n /**\n * The dynamic tool calls that were made in the last step.\n */\n readonly dynamicToolCalls: Array<DynamicToolCall>;\n\n /**\n * The results of the tool calls.\n */\n readonly toolResults: Array<TypedToolResult<TOOLS>>;\n\n /**\n * The static tool results that were made in the last step.\n */\n readonly staticToolResults: Array<StaticToolResult<TOOLS>>;\n\n /**\n * The dynamic tool results that were made in the last step.\n */\n readonly dynamicToolResults: Array<DynamicToolResult>;\n\n /**\n * The unified reason why the generation finished.\n */\n readonly finishReason: FinishReason;\n\n /**\n * The raw reason why the generation finished (from the provider).\n */\n readonly rawFinishReason: string | undefined;\n\n /**\n * The token usage of the generated text.\n */\n readonly usage: LanguageModelUsage;\n\n /**\n * Performance metrics for the step.\n */\n readonly performance: StepResultPerformance;\n\n /**\n * Warnings from the model provider (e.g. unsupported settings).\n */\n readonly warnings: CallWarning[] | undefined;\n\n /**\n * Additional request information.\n */\n readonly request: LanguageModelRequestMetadata;\n\n /**\n * Additional response information.\n */\n readonly response: LanguageModelResponseMetadata;\n\n /**\n * Additional provider-specific metadata. They are passed through\n * from the provider to the AI SDK and enable provider-specific\n * results that can be fully encapsulated in the provider.\n */\n readonly providerMetadata: ProviderMetadata | undefined;\n};\n\nexport class DefaultStepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context = Context,\n> implements StepResult<TOOLS, RUNTIME_CONTEXT> {\n readonly callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n readonly stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n readonly model: StepResult<TOOLS, RUNTIME_CONTEXT>['model'];\n readonly toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n readonly runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n readonly content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n readonly finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n readonly rawFinishReason: StepResult<\n TOOLS,\n RUNTIME_CONTEXT\n >['rawFinishReason'];\n readonly usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n readonly performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n readonly warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n readonly request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n readonly response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n readonly providerMetadata: StepResult<\n TOOLS,\n RUNTIME_CONTEXT\n >['providerMetadata'];\n\n constructor({\n callId,\n stepNumber,\n provider,\n modelId,\n runtimeContext,\n toolsContext,\n content,\n finishReason,\n rawFinishReason,\n usage,\n performance,\n warnings,\n request,\n response,\n providerMetadata,\n }: {\n callId: StepResult<TOOLS, RUNTIME_CONTEXT>['callId'];\n stepNumber: StepResult<TOOLS, RUNTIME_CONTEXT>['stepNumber'];\n provider: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['provider'];\n modelId: StepResult<TOOLS, RUNTIME_CONTEXT>['model']['modelId'];\n runtimeContext: StepResult<TOOLS, RUNTIME_CONTEXT>['runtimeContext'];\n toolsContext: StepResult<TOOLS, RUNTIME_CONTEXT>['toolsContext'];\n content: StepResult<TOOLS, RUNTIME_CONTEXT>['content'];\n finishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['finishReason'];\n rawFinishReason: StepResult<TOOLS, RUNTIME_CONTEXT>['rawFinishReason'];\n usage: StepResult<TOOLS, RUNTIME_CONTEXT>['usage'];\n performance: StepResult<TOOLS, RUNTIME_CONTEXT>['performance'];\n warnings: StepResult<TOOLS, RUNTIME_CONTEXT>['warnings'];\n request: StepResult<TOOLS, RUNTIME_CONTEXT>['request'];\n response: StepResult<TOOLS, RUNTIME_CONTEXT>['response'];\n providerMetadata: StepResult<TOOLS, RUNTIME_CONTEXT>['providerMetadata'];\n }) {\n this.callId = callId;\n this.stepNumber = stepNumber;\n this.model = { provider, modelId };\n this.runtimeContext = runtimeContext;\n this.toolsContext = toolsContext;\n this.content = content;\n this.finishReason = finishReason;\n this.rawFinishReason = rawFinishReason;\n this.usage = usage;\n this.performance = performance;\n this.warnings = warnings;\n this.request = request;\n this.response = response;\n this.providerMetadata = providerMetadata;\n }\n\n get text() {\n return this.content\n .filter(part => part.type === 'text')\n .map(part => part.text)\n .join('');\n }\n\n get reasoning(): Array<ReasoningPart | ReasoningFilePart> {\n return convertFromReasoningOutputs(\n this.content.filter(\n (part): part is ReasoningOutput | ReasoningFileOutput =>\n part.type === 'reasoning' || part.type === 'reasoning-file',\n ),\n );\n }\n\n get reasoningText() {\n return asReasoningText(this.reasoning);\n }\n\n get files() {\n return this.content\n .filter(part => part.type === 'file')\n .map(part => part.file);\n }\n\n get sources() {\n return this.content.filter(part => part.type === 'source');\n }\n\n get toolCalls() {\n return this.content.filter(part => part.type === 'tool-call');\n }\n\n get staticToolCalls() {\n return this.toolCalls.filter(\n (toolCall): toolCall is StaticToolCall<TOOLS> =>\n toolCall.dynamic !== true,\n );\n }\n\n get dynamicToolCalls() {\n return this.toolCalls.filter(\n (toolCall): toolCall is DynamicToolCall => toolCall.dynamic === true,\n );\n }\n\n get toolResults() {\n return this.content.filter(part => part.type === 'tool-result');\n }\n\n get staticToolResults() {\n return this.toolResults.filter(\n (toolResult): toolResult is StaticToolResult<TOOLS> =>\n toolResult.dynamic !== true,\n );\n }\n\n get dynamicToolResults() {\n return this.toolResults.filter(\n (toolResult): toolResult is DynamicToolResult =>\n toolResult.dynamic === true,\n );\n }\n}\n","import type {\n Context,\n InferToolContext,\n InferToolSetContext,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { createTelemetryDispatcher } from '../telemetry/create-telemetry-dispatcher';\nimport type { TelemetryDispatcher } from '../telemetry/telemetry';\nimport type {\n IncludedContext,\n IncludedToolsContext,\n TelemetryOptions,\n} from '../telemetry/telemetry-options';\nimport type {\n GenerateTextOnAbortCallback,\n GenerateTextOnEndCallback,\n GenerateTextOnStartCallback,\n GenerateTextOnStepEndCallback,\n GenerateTextOnStepFinishCallback,\n GenerateTextOnStepStartCallback,\n} from './generate-text-events';\nimport type { Output } from './output';\nimport { DefaultStepResult, type StepResult } from './step-result';\nimport type {\n OnToolExecutionEndCallback,\n OnToolExecutionStartCallback,\n} from './tool-execution-events';\n\n/**\n * Telemetry dispatcher for text generation with callbacks typed to the\n * operation-specific tool set, runtime context, and output shape.\n */\nexport type RestrictedTelemetryDispatcher<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n OUTPUT extends Output,\n> = Omit<\n TelemetryDispatcher,\n | 'onStart'\n | 'onStepStart'\n | 'onStepEnd'\n | 'onStepFinish'\n | 'onEnd'\n | 'onAbort'\n | 'onToolExecutionStart'\n | 'onToolExecutionEnd'\n> & {\n onStart: GenerateTextOnStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n onStepStart: GenerateTextOnStepStartCallback<TOOLS, RUNTIME_CONTEXT, OUTPUT>;\n onStepEnd: GenerateTextOnStepEndCallback<TOOLS, RUNTIME_CONTEXT>;\n /** @deprecated Use `onStepEnd` instead. */\n onStepFinish: GenerateTextOnStepFinishCallback<TOOLS, RUNTIME_CONTEXT>;\n onEnd: GenerateTextOnEndCallback<TOOLS, RUNTIME_CONTEXT>;\n onAbort?: GenerateTextOnAbortCallback<TOOLS, RUNTIME_CONTEXT>;\n onToolExecutionStart?: OnToolExecutionStartCallback<TOOLS>;\n onToolExecutionEnd?: OnToolExecutionEndCallback<TOOLS>;\n};\n\n/**\n * Returns a shallow copy of the runtime context with only top-level\n * properties marked for telemetry inclusion.\n */\nfunction filterIncludedContext<CONTEXT extends Context>({\n context,\n includeContext,\n}: {\n context: CONTEXT;\n includeContext: IncludedContext<CONTEXT>;\n}): Context {\n if (context == null) {\n return {};\n }\n\n return Object.fromEntries(\n Object.entries(context).filter(\n ([key]) => includeContext?.[key as keyof CONTEXT] === true,\n ),\n );\n}\n\n/**\n * Creates a copy of a step result whose runtime context only contains\n * top-level properties marked for telemetry inclusion.\n */\nfunction restrictStepResult<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n>({\n step,\n includeRuntimeContext,\n includeToolsContext,\n}: {\n step: StepResult<TOOLS, RUNTIME_CONTEXT>;\n includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n return new DefaultStepResult({\n callId: step.callId,\n stepNumber: step.stepNumber,\n provider: step.model.provider,\n modelId: step.model.modelId,\n runtimeContext: filterIncludedContext({\n context: step.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n toolsContext: filterToolsContext({\n toolsContext: step.toolsContext,\n includeToolsContext,\n }),\n content: step.content,\n finishReason: step.finishReason,\n rawFinishReason: step.rawFinishReason,\n usage: step.usage,\n performance: step.performance,\n warnings: step.warnings,\n request: step.request,\n response: step.response,\n providerMetadata: step.providerMetadata,\n });\n}\n\n/**\n * Returns a shallow copy of the tools context with only top-level properties\n * marked for telemetry inclusion for each tool.\n */\nfunction filterToolsContext<TOOLS extends ToolSet>({\n toolsContext,\n includeToolsContext,\n}: {\n toolsContext: InferToolSetContext<TOOLS>;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}): InferToolSetContext<TOOLS> {\n if (includeToolsContext == null) {\n return {} as InferToolSetContext<TOOLS>;\n }\n\n return Object.fromEntries(\n Object.entries(toolsContext).map(([toolName, toolContext]) => [\n toolName,\n filterToolContext({\n toolName,\n toolContext,\n includeToolsContext,\n }),\n ]),\n ) as InferToolSetContext<TOOLS>;\n}\n\nfunction filterToolContext<TOOLS extends ToolSet>({\n toolName,\n toolContext,\n includeToolsContext,\n}: {\n toolName: string;\n toolContext: unknown;\n includeToolsContext: IncludedToolsContext<TOOLS>;\n}) {\n const includeToolContext = (\n includeToolsContext as\n | Record<\n string,\n IncludedContext<InferToolContext<TOOLS[typeof toolName]>>\n >\n | undefined\n )?.[toolName];\n\n return filterIncludedContext({\n context: toolContext as InferToolContext<TOOLS[typeof toolName]>,\n includeContext: includeToolContext,\n });\n}\n\n/**\n * Creates a telemetry dispatcher that only includes configured runtime context\n * properties in text-generation lifecycle events before dispatching them.\n */\nexport function createRestrictedTelemetryDispatcher<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context,\n OUTPUT extends Output,\n>({\n telemetry,\n includeRuntimeContext,\n includeToolsContext,\n}: {\n telemetry?: TelemetryOptions<RUNTIME_CONTEXT, TOOLS>;\n includeRuntimeContext: IncludedContext<RUNTIME_CONTEXT>;\n includeToolsContext?: IncludedToolsContext<TOOLS>;\n}): RestrictedTelemetryDispatcher<TOOLS, RUNTIME_CONTEXT, OUTPUT> {\n const telemetryDispatcher = createTelemetryDispatcher({ telemetry });\n\n return {\n ...telemetryDispatcher,\n onStart: event =>\n telemetryDispatcher.onStart?.({\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n }),\n onStepStart: event =>\n telemetryDispatcher.onStepStart?.({\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n steps: event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n }),\n onStepEnd: event =>\n telemetryDispatcher.onStepEnd?.(\n restrictStepResult({\n step: event,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n onStepFinish: event =>\n telemetryDispatcher.onStepEnd?.(\n restrictStepResult({\n step: event,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n onEnd: event =>\n telemetryDispatcher.onEnd?.(\n ((restrictedSteps: StepResult<TOOLS, Context>[]) => {\n return {\n ...event,\n runtimeContext: filterIncludedContext({\n context: event.runtimeContext,\n includeContext: includeRuntimeContext,\n }),\n steps: restrictedSteps,\n finalStep: restrictedSteps.at(-1)!,\n toolsContext: filterToolsContext({\n toolsContext: event.toolsContext,\n includeToolsContext,\n }),\n };\n })(\n event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n ),\n ),\n onAbort: event =>\n telemetryDispatcher.onAbort?.({\n ...event,\n steps: event.steps.map(step =>\n restrictStepResult({\n step,\n includeRuntimeContext,\n includeToolsContext,\n }),\n ),\n }),\n onToolExecutionStart: event =>\n telemetryDispatcher.onToolExecutionStart?.({\n ...event,\n toolContext: filterToolContext({\n toolName: event.toolCall.toolName,\n toolContext: event.toolContext,\n includeToolsContext,\n }),\n }),\n onToolExecutionEnd: event =>\n telemetryDispatcher.onToolExecutionEnd?.({\n ...event,\n toolContext: filterToolContext({\n toolName: event.toolCall.toolName,\n toolContext: event.toolContext,\n includeToolsContext,\n }),\n }),\n };\n}\n","import type { LanguageModelV4ToolCall } from '@ai-sdk/provider';\nimport {\n asSchema,\n safeParseJSON,\n safeValidateTypes,\n type InferToolInput,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport { NoSuchToolError } from '../error/no-such-tool-error';\nimport { ToolCallRepairError } from '../error/tool-call-repair-error';\nimport type { Instructions } from '../prompt';\nimport type { DynamicToolCall, TypedToolCall } from './tool-call';\nimport type { ToolCallRepairFunction } from './tool-call-repair-function';\nimport type { ToolInputRefinement } from './tool-input-refinement';\n\nexport async function parseToolCall<TOOLS extends ToolSet>({\n toolCall,\n tools,\n repairToolCall,\n refineToolInput,\n messages,\n instructions,\n}: {\n toolCall: LanguageModelV4ToolCall;\n tools: TOOLS | undefined;\n repairToolCall: ToolCallRepairFunction<TOOLS> | undefined;\n refineToolInput?: ToolInputRefinement<TOOLS> | undefined;\n instructions: Instructions | undefined;\n messages: ModelMessage[];\n}): Promise<TypedToolCall<TOOLS>> {\n try {\n if (tools == null) {\n // provider-executed dynamic tools are not part of our list of tools:\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await refineParsedToolCallInput({\n toolCall: await parseProviderExecutedDynamicToolCall(toolCall),\n refineToolInput,\n });\n }\n\n throw new NoSuchToolError({ toolName: toolCall.toolName });\n }\n\n try {\n return await refineParsedToolCallInput({\n toolCall: await doParseToolCall({ toolCall, tools }),\n refineToolInput,\n });\n } catch (error) {\n if (\n repairToolCall == null ||\n !(\n NoSuchToolError.isInstance(error) ||\n InvalidToolInputError.isInstance(error)\n )\n ) {\n throw error;\n }\n\n let repairedToolCall: LanguageModelV4ToolCall | null = null;\n\n try {\n repairedToolCall = await repairToolCall({\n toolCall,\n tools,\n inputSchema: async ({ toolName }) => {\n const { inputSchema } = tools[toolName];\n return await asSchema(inputSchema).jsonSchema;\n },\n instructions,\n system: instructions,\n messages,\n error,\n });\n } catch (repairError) {\n throw new ToolCallRepairError({\n cause: repairError,\n originalError: error,\n });\n }\n\n // no repaired tool call returned\n if (repairedToolCall == null) {\n throw error;\n }\n\n return await refineParsedToolCallInput({\n toolCall: await doParseToolCall({ toolCall: repairedToolCall, tools }),\n refineToolInput,\n });\n }\n } catch (error) {\n // use parsed input when possible\n const parsedInput = await safeParseJSON({ text: toolCall.input });\n const input = parsedInput.success ? parsedInput.value : toolCall.input;\n const tool = tools?.[toolCall.toolName];\n\n // TODO AI SDK 6: special invalid tool call parts\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input,\n dynamic: true,\n invalid: true,\n error,\n title: tool?.title,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool?.metadata != null ? { toolMetadata: tool.metadata } : {}),\n };\n }\n}\n\nasync function refineParsedToolCallInput<TOOLS extends ToolSet>({\n toolCall,\n refineToolInput,\n}: {\n toolCall: TypedToolCall<TOOLS>;\n refineToolInput: ToolInputRefinement<TOOLS> | undefined;\n}): Promise<TypedToolCall<TOOLS>> {\n const refine = refineToolInput?.[toolCall.toolName];\n\n if (refine == null) {\n return toolCall;\n }\n\n return {\n ...toolCall,\n input: await refine(toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>),\n } as TypedToolCall<TOOLS>;\n}\n\nasync function parseProviderExecutedDynamicToolCall(\n toolCall: LanguageModelV4ToolCall,\n): Promise<DynamicToolCall> {\n const parseResult =\n toolCall.input.trim() === ''\n ? { success: true as const, value: {} }\n : await safeParseJSON({ text: toolCall.input });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName: toolCall.toolName,\n toolInput: toolCall.input,\n cause: parseResult.error,\n });\n }\n\n return {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: true,\n dynamic: true,\n providerMetadata: toolCall.providerMetadata,\n };\n}\n\nasync function doParseToolCall<TOOLS extends ToolSet>({\n toolCall,\n tools,\n}: {\n toolCall: LanguageModelV4ToolCall;\n tools: TOOLS;\n}): Promise<TypedToolCall<TOOLS>> {\n const toolName = toolCall.toolName as keyof TOOLS & string;\n\n const tool = tools[toolName];\n\n if (tool == null) {\n // provider-executed dynamic tools are not part of our list of tools:\n if (toolCall.providerExecuted && toolCall.dynamic) {\n return await parseProviderExecutedDynamicToolCall(toolCall);\n }\n\n throw new NoSuchToolError({\n toolName: toolCall.toolName,\n availableTools: Object.keys(tools),\n });\n }\n\n const schema = asSchema(tool.inputSchema);\n\n // when the tool call has no arguments, we try passing an empty object to the schema\n // (many LLMs generate empty strings for tool calls with no arguments)\n const parseResult =\n toolCall.input.trim() === ''\n ? await safeValidateTypes({ value: {}, schema })\n : await safeParseJSON({ text: toolCall.input, schema });\n\n if (parseResult.success === false) {\n throw new InvalidToolInputError({\n toolName,\n toolInput: toolCall.input,\n cause: parseResult.error,\n });\n }\n\n return tool.type === 'dynamic'\n ? {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n dynamic: true,\n title: tool.title,\n }\n : {\n type: 'tool-call',\n toolCallId: toolCall.toolCallId,\n toolName,\n input: parseResult.value,\n providerExecuted: toolCall.providerExecuted,\n providerMetadata: toolCall.providerMetadata,\n ...(tool.metadata != null ? { toolMetadata: tool.metadata } : {}),\n title: tool.title,\n };\n}\n","import type {\n ModelMessage,\n ToolApprovalRequest,\n ToolApprovalResponse,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalError } from '../error/invalid-tool-approval-error';\nimport { ToolCallNotFoundForApprovalError } from '../error/tool-call-not-found-for-approval-error';\nimport type { TypedToolCall } from './tool-call';\nimport type { TypedToolResult } from './tool-result';\n\nexport type CollectedToolApprovals<TOOLS extends ToolSet> = {\n approvalRequest: ToolApprovalRequest;\n approvalResponse: ToolApprovalResponse;\n toolCall: TypedToolCall<TOOLS>;\n};\n\n/**\n * If the last message is a tool message, this function collects all tool approvals\n * from that message.\n */\nexport function collectToolApprovals<TOOLS extends ToolSet>({\n messages,\n}: {\n messages: ModelMessage[];\n}): {\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n} {\n const lastMessage = messages.at(-1);\n\n if (lastMessage?.role != 'tool') {\n return {\n approvedToolApprovals: [],\n deniedToolApprovals: [],\n };\n }\n\n // gather tool calls and prepare lookup\n const toolCallsByToolCallId: Record<string, TypedToolCall<TOOLS>> = {};\n for (const message of messages) {\n if (message.role === 'assistant' && typeof message.content !== 'string') {\n const content = message.content;\n for (const part of content) {\n if (part.type === 'tool-call') {\n toolCallsByToolCallId[part.toolCallId] = part as TypedToolCall<TOOLS>;\n }\n }\n }\n }\n\n // gather approval responses and prepare lookup\n const toolApprovalRequestsByApprovalId: Record<string, ToolApprovalRequest> =\n {};\n for (const message of messages) {\n if (message.role === 'assistant' && typeof message.content !== 'string') {\n const content = message.content;\n for (const part of content) {\n if (part.type === 'tool-approval-request') {\n toolApprovalRequestsByApprovalId[part.approvalId] = part;\n }\n }\n }\n }\n\n // gather tool results from the last tool message\n const toolResults: Record<string, TypedToolResult<TOOLS>> = {};\n for (const part of lastMessage.content) {\n if (part.type === 'tool-result') {\n toolResults[part.toolCallId] = part as TypedToolResult<TOOLS>;\n }\n }\n\n const approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n const deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>> = [];\n\n const approvalResponses = lastMessage.content.filter(\n part => part.type === 'tool-approval-response',\n );\n for (const approvalResponse of approvalResponses) {\n const approvalRequest =\n toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\n if (approvalRequest == null) {\n throw new InvalidToolApprovalError({\n approvalId: approvalResponse.approvalId,\n });\n }\n\n if (toolResults[approvalRequest.toolCallId] != null) {\n continue;\n }\n\n const toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n if (toolCall == null) {\n throw new ToolCallNotFoundForApprovalError({\n toolCallId: approvalRequest.toolCallId,\n approvalId: approvalRequest.approvalId,\n });\n }\n\n const approval: CollectedToolApprovals<TOOLS> = {\n approvalRequest,\n approvalResponse,\n toolCall,\n };\n\n if (approvalResponse.approved) {\n approvedToolApprovals.push(approval);\n } else {\n deniedToolApprovals.push(approval);\n }\n }\n\n return { approvedToolApprovals, deniedToolApprovals };\n}\n","import {\n asSchema,\n isExecutableTool,\n safeValidateTypes,\n type Context,\n type InferToolSetContext,\n type ModelMessage,\n type ToolSet,\n} from '@ai-sdk/provider-utils';\nimport { InvalidToolApprovalSignatureError } from '../error/invalid-tool-approval-signature-error';\nimport { InvalidToolInputError } from '../error/invalid-tool-input-error';\nimport type { CollectedToolApprovals } from './collect-tool-approvals';\nimport { resolveToolApproval } from './resolve-tool-approval';\nimport { verifyToolApprovalSignature } from './tool-approval-signature';\nimport type { ToolApprovalConfiguration } from './tool-approval-configuration';\n\n/**\n * Re-validates approved tool approvals reconstructed from client-supplied\n * message history before they are executed. Checks HMAC signature (when\n * configured), input schema, and approval policy.\n */\nexport async function validateApprovedToolApprovals<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n approvedToolApprovals,\n tools,\n toolApproval,\n messages,\n toolsContext,\n runtimeContext,\n toolApprovalSecret,\n}: {\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n tools: TOOLS | undefined;\n toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n messages: ModelMessage[];\n toolsContext: InferToolSetContext<TOOLS>;\n runtimeContext: RUNTIME_CONTEXT;\n toolApprovalSecret?: string | Uint8Array;\n}): Promise<{\n approvedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n deniedToolApprovals: Array<CollectedToolApprovals<TOOLS>>;\n}> {\n const approved: Array<CollectedToolApprovals<TOOLS>> = [];\n const denied: Array<CollectedToolApprovals<TOOLS>> = [];\n\n for (const approval of approvedToolApprovals) {\n const { toolCall, approvalRequest } = approval;\n const tool = tools?.[toolCall.toolName];\n\n if (toolApprovalSecret != null) {\n if (approvalRequest.signature == null) {\n throw new InvalidToolApprovalSignatureError({\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n reason: 'missing signature',\n });\n }\n\n const valid = await verifyToolApprovalSignature({\n secret: toolApprovalSecret,\n signature: approvalRequest.signature,\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n toolName: toolCall.toolName,\n input: toolCall.input,\n });\n\n if (!valid) {\n throw new InvalidToolApprovalSignatureError({\n approvalId: approvalRequest.approvalId,\n toolCallId: toolCall.toolCallId,\n reason: 'invalid signature',\n });\n }\n }\n\n if (isExecutableTool(tool) && tool.inputSchema != null) {\n const validation = await safeValidateTypes({\n value: toolCall.input,\n schema: asSchema(tool.inputSchema),\n });\n\n if (!validation.success) {\n throw new InvalidToolInputError({\n toolName: toolCall.toolName,\n toolInput: JSON.stringify(toolCall.input),\n cause: validation.error,\n });\n }\n }\n\n const approvalStatus = await resolveToolApproval({\n tools,\n toolApproval,\n toolCall,\n messages,\n toolsContext,\n runtimeContext,\n });\n\n if (approvalStatus.type === 'denied') {\n denied.push({\n ...approval,\n approvalResponse: {\n ...approval.approvalResponse,\n approved: false,\n reason: approvalStatus.reason ?? approval.approvalResponse.reason,\n },\n });\n } else {\n approved.push(approval);\n }\n }\n\n return { approvedToolApprovals: approved, deniedToolApprovals: denied };\n}\n","import { validateTypes, type FlexibleSchema } from '@ai-sdk/provider-utils';\n/**\n * Validates a tool context value against the tool's optional context schema.\n *\n * When no context schema is defined, the original context value is returned as-is.\n * Otherwise, the context is validated and normalized through the schema before\n * being passed into tool execution and approval hooks.\n *\n * @throws {TypeValidationError} When the provided tool context does not match\n * the tool's declared `contextSchema`.\n */\nexport async function validateToolContext<CONTEXT>({\n toolName,\n context,\n contextSchema,\n}: {\n toolName: string;\n context: unknown;\n contextSchema: FlexibleSchema<CONTEXT> | undefined;\n}): Promise<CONTEXT> {\n if (contextSchema == null) {\n return context as CONTEXT;\n }\n\n return await validateTypes({\n value: context,\n schema: contextSchema,\n context: {\n field: 'tool context',\n entityName: toolName,\n },\n });\n}\n","import type {\n Context,\n InferToolInput,\n InferToolSetContext,\n ModelMessage,\n ToolSet,\n} from '@ai-sdk/provider-utils';\nimport type {\n ToolApprovalConfiguration,\n ToolApprovalStatus,\n} from './tool-approval-configuration';\nimport type { TypedToolCall } from './tool-call';\nimport { validateToolContext } from './validate-tool-context';\n\n/**\n * Resolves the approval state for a tool call by checking user-supplied and tool-defined\n * approval settings, and normalizes the result to the object status shape.\n * User-defined approval settings take precedence over tool-defined settings.\n * If no approval settings are provided, the tool call does not require approval.\n */\nexport async function resolveToolApproval<\n TOOLS extends ToolSet,\n RUNTIME_CONTEXT extends Context | unknown | never,\n>({\n tools,\n toolCall,\n toolApproval,\n messages,\n toolsContext,\n runtimeContext,\n}: {\n /**\n * Tools that are available for the model to call.\n */\n tools: TOOLS | undefined;\n\n /**\n * Valid tool call.\n */\n toolCall: TypedToolCall<TOOLS>;\n\n /**\n * User-defined approval configuration for tools.\n *\n * This configuration takes precedence over tool-defined approval settings.\n */\n toolApproval: ToolApprovalConfiguration<TOOLS, RUNTIME_CONTEXT> | undefined;\n\n /**\n * Messages that were sent to the language model to initiate the response that contained the tool call.\n */\n messages: ModelMessage[];\n\n /**\n * Tool context as defined by the tool's context schema.\n */\n toolsContext: InferToolSetContext<TOOLS>;\n\n /**\n * User-defined runtime context (same as `runtimeContext` on `generateText` / `streamText`).\n */\n runtimeContext: RUNTIME_CONTEXT;\n}): Promise<Exclude<ToolApprovalStatus, string | undefined>> {\n // user-defined generic tool approval\n if (toolApproval != null && typeof toolApproval === 'function') {\n return normalizeToolApprovalStatus(\n await toolApproval({\n toolCall,\n tools,\n toolsContext,\n messages,\n runtimeContext,\n }),\n );\n }\n\n const toolName = toolCall.toolName;\n const tool = tools?.[toolName];\n\n // assume that the input has been validated and matches the tool's input schema\n const input = toolCall.input as InferToolInput<TOOLS[keyof TOOLS]>;\n\n // user-defined per-tool approval\n const userDefinedToolApprovalStatus = toolApproval?.[toolName];\n if (userDefinedToolApprovalStatus != null) {\n const approvalStatus: ToolApprovalStatus | undefined =\n typeof userDefinedToolApprovalStatus === 'function'\n ? await userDefinedToolApprovalStatus(input, {\n toolCallId: toolCall.toolCallId,\n messages,\n toolContext: await validateToolContext({\n toolName,\n context:\n toolsContext?.[toolName as keyof InferToolSetContext<TOOLS>],\n contextSchema: tool?.contextSchema,\n }),\n runtimeContext,\n })\n : userDefinedToolApprovalStatus;\n\n return normalizeToolApprovalStatus(approvalStatus);\n }\n\n // tool-defined approval\n if (tool?.needsApproval == null) {\n return { type: 'not-applicable' };\n }\n\n const needsApproval =\n typeof tool.needsApproval === 'function'\n ? await tool.needsApproval(input, {\n toolCallId: toolCall.toolCallId,\n messages,\n context: await validateToolContext({\n toolName,\n context:\n toolsContext?.[toolName as keyof InferToolSetContext<TOOLS>],\n contextSchema: tool?.contextSchema,\n }),\n })\n : tool.needsApproval;\n\n return needsApproval ? { type: 'user-approval' } : { type: 'not-applicable' };\n}\n\nfunction normalizeToolApprovalStatus(\n status: ToolApprovalStatus | undefined,\n): Exclude<ToolApprovalStatus, string | undefined> {\n return status === undefined\n ? { type: 'not-applicable' }\n : typeof status === 'string'\n ? { type: status }\n : status;\n}\n","import {\n convertBase64ToUint8Array,\n convertUint8ArrayToBase64,\n} from '@ai-sdk/provider-utils';\n\nconst encoder = new TextEncoder();\n\nfunction canonicalJSON(value: unknown): string {\n if (value === null || value === undefined) {\n return JSON.stringify(value);\n }\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n if (Array.isArray(value)) {\n return `[${value.map(canonicalJSON).join(',')}]`;\n }\n const keys = Object.keys(value as Record<string, unknown>).sort();\n const entries = keys.map(\n k =>\n `${JSON.stringify(k)}:${canonicalJSON((value as Record<string, unknown>)[k])}`,\n );\n return `{${entries.join(',')}}`;\n}\n\nfunction toBase64url(bytes: Uint8Array): string {\n return convertUint8ArrayToBase64(bytes)\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/g, '');\n}\n\nfunction fromBase64url(str: string): Uint8Array {\n return convertBase64ToUint8Array(str);\n}\n\nasync function importKey(secret: string | Uint8Array): Promise<CryptoKey> {\n const keyData = typeof secret === 'string' ? encoder.encode(secret) : secret;\n return crypto.subtle.importKey(\n 'raw',\n keyData,\n { name: 'HMAC', hash: 'SHA-256' },\n false,\n ['sign', 'verify'],\n );\n}\n\nasync function hashInput(input: unknown): Promise<string> {\n const canonical = canonicalJSON(input);\n const digest = await crypto.subtle.digest(\n 'SHA-256',\n encoder.encode(canonical),\n );\n return toBase64url(new Uint8Array(digest));\n}\n\nfunction buildPayload(\n approvalId: string,\n toolCallId: string,\n toolName: string,\n inputDigest: string,\n): Uint8Array {\n return encoder.encode(\n `${approvalId}\\n${toolCallId}\\n${toolName}\\n${inputDigest}`,\n );\n}\n\nexport async function signToolApproval({\n secret,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<string> {\n const key = await importKey(secret);\n const inputDigest = await hashInput(input);\n const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n const sig = await crypto.subtle.sign('HMAC', key, payload);\n return toBase64url(new Uint8Array(sig));\n}\n\nexport async function verifyToolApprovalSignature({\n secret,\n signature,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array;\n signature: string;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<boolean> {\n const key = await importKey(secret);\n const inputDigest = await hashInput(input);\n const payload = buildPayload(approvalId, toolCallId, toolName, inputDigest);\n const sigBytes = fromBase64url(signature);\n return crypto.subtle.verify('HMAC', key, sigBytes, payload);\n}\n\nexport async function maybeSignApproval({\n secret,\n approvalId,\n toolCallId,\n toolName,\n input,\n}: {\n secret: string | Uint8Array | undefined;\n approvalId: string;\n toolCallId: string;\n toolName: string;\n input: unknown;\n}): Promise<string | undefined> {\n if (secret == null) return undefined;\n return signToolApproval({ secret, approvalId, toolCallId, toolName, input });\n}\n","import type {\n AssistantContent,\n AssistantModelMessage,\n ToolContent,\n ToolModelMessage,\n} from '../prompt';\nimport { createToolModelOutput } from '../prompt/create-tool-model-output';\nimport type { ContentPart } from './content-part';\nimport type { ToolSet } from '@ai-sdk/provider-utils';\n\n/**\n * Converts the result of a `generateText` or `streamText` call to a list of response messages.\n */\nexport async function toResponseMessages<TOOLS extends ToolSet>({\n content: inputContent,\n tools,\n}: {\n content: Array<ContentPart<TOOLS>>;\n tools: TOOLS | undefined;\n}): Promise<Array<AssistantModelMessage | ToolModelMessage>> {\n const responseMessages: Array<AssistantModelMessage | ToolModelMessage> = [];\n\n const content: AssistantContent = [];\n for (const part of inputContent) {\n // Skip sources - they are response-only content that no provider expects back\n if (part.type === 'source') {\n continue;\n }\n\n // Skip non-provider-executed tool results/errors (they go in the tool message)\n if (\n (part.type === 'tool-result' || part.type === 'tool-error') &&\n !part.providerExecuted\n ) {\n continue;\n }\n\n // Skip empty text\n if (part.type === 'text' && part.text.length === 0) {\n continue;\n }\n\n switch (part.type) {\n case 'text':\n content.push({\n type: 'text',\n text: part.text,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'custom':\n content.push({\n type: 'custom',\n kind: part.kind,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'reasoning':\n content.push({\n type: 'reasoning',\n text: part.text,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'file':\n content.push({\n type: 'file',\n data: part.file.base64,\n mediaType: part.file.mediaType,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'reasoning-file':\n content.push({\n type: 'reasoning-file',\n data: part.file.base64,\n mediaType: part.file.mediaType,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'tool-call':\n content.push({\n type: 'tool-call',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n input:\n part.invalid && typeof part.input !== 'object' ? {} : part.input,\n providerExecuted: part.providerExecuted,\n providerOptions: part.providerMetadata,\n });\n break;\n case 'tool-result': {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.output,\n errorMode: 'none',\n });\n content.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata,\n });\n break;\n }\n case 'tool-error': {\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.error,\n errorMode: 'json',\n });\n content.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n providerOptions: part.providerMetadata,\n });\n break;\n }\n case 'tool-approval-request':\n content.push({\n type: 'tool-approval-request',\n approvalId: part.approvalId,\n toolCallId: part.toolCall.toolCallId,\n isAutomatic: part.isAutomatic,\n ...(part.signature != null ? { signature: part.signature } : {}),\n });\n break;\n }\n }\n\n if (content.length > 0) {\n responseMessages.push({\n role: 'assistant',\n content,\n });\n }\n\n const toolResultContent: ToolContent = [];\n for (const part of inputContent) {\n if (\n part.type !== 'tool-approval-response' &&\n part.type !== 'tool-result' &&\n part.type !== 'tool-error'\n ) {\n continue;\n }\n\n if (part.type === 'tool-approval-response') {\n toolResultContent.push({\n type: 'tool-approval-response',\n approvalId: part.approvalId,\n approved: part.approved,\n reason: part.reason,\n providerExecuted: part.providerExecuted,\n });\n\n // when the tool approval is denied,\n // we need to add an execution-denied tool result\n // since there is no corresponding tool result for the tool call\n if (part.approved === false) {\n toolResultContent.push({\n type: 'tool-result',\n toolCallId: part.toolCall.toolCallId,\n toolName: part.toolCall.toolName,\n output: {\n type: 'execution-denied' as const,\n reason: part.reason,\n },\n });\n }\n continue;\n }\n\n if (part.providerExecuted) {\n continue;\n }\n\n const output = await createToolModelOutput({\n toolCallId: part.toolCallId,\n input: part.input,\n tool: tools?.[part.toolName],\n output: part.type === 'tool-result' ? part.output : part.error,\n errorMode: part.type === 'tool-error' ? 'text' : 'none',\n });\n\n toolResultContent.push({\n type: 'tool-result',\n toolCallId: part.toolCallId,\n toolName: part.toolName,\n output,\n ...(part.providerMetadata != null\n ? { providerOptions: part.providerMetadata }\n : {}),\n });\n }\n\n if (toolResultContent.length > 0) {\n responseMessages.push({\n role: 'tool',\n content: toolResultContent,\n });\n }\n\n return responseMessages;\n}\n"],"mappings":";AAIA,SAAS,4CAA4C;;;ACU9C,SAAS,0BACd,QACwB;AAExB,QAAM,SAAS,OAAO,YAAY,IAAI,gBAAsB,CAAC;AAM7D,EAAC,OAAkC,OAAO,aAAa,IAAI,WAEvC;AAClB,UAAM,SAAS,KAAK,UAAU;AAE9B,QAAI,WAAW;AAKf,mBAAe,QAAQ,cAAuB;AAlClD,UAAAA;AAmCM,UAAI;AAAU;AAEd,iBAAW;AACX,UAAI;AACF,YAAI,cAAc;AAChB,kBAAMA,OAAA,OAAO,WAAP,gBAAAA,KAAA;AAAA,QACR;AAAA,MACF,UAAE;AACA,YAAI;AACF,iBAAO,YAAY;AAAA,QACrB,SAAQ;AAAA,QAAC;AAAA,MACX;AAAA,IACF;AAEA,WAAO;AAAA;AAAA;AAAA;AAAA;AAAA,MAKL,MAAM,OAAmC;AACvC,YAAI,UAAU;AACZ,iBAAO,EAAE,MAAM,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N,MAAM;AAAA,YACN,QAAQ,KAAK;AAAA,UACf;AAAA,QACF,CAAC;AAAA,MACH;AACA;AAAA,IACF;AAEA,QAAI,KAAK,kBAAkB;AACzB;AAAA,IACF;AAEA,UAAM,SAAS,MAAM,sBAAsB;AAAA,MACzC,YAAY,KAAK;AAAA,MACjB,OAAO,KAAK;AAAA,MACZ,MAAM,+BAAQ,KAAK;AAAA,MACnB,QAAQ,KAAK,SAAS,gBAAgB,KAAK,SAAS,KAAK;AAAA,MACzD,WAAW,KAAK,SAAS,eAAe,SAAS;AAAA,IACnD,CAAC;AAED,sBAAkB,KAAK;AAAA,MACrB,MAAM;AAAA,MACN,YAAY,KAAK;AAAA,MACjB,UAAU,KAAK;AAAA,MACf;AAAA,MACA,GAAI,KAAK,oBAAoB,OACzB,EAAE,iBAAiB,KAAK,iBAAiB,IACzC,CAAC;AAAA,IACP,CAAC;AAAA,EACH;AAEA,MAAI,kBAAkB,SAAS,GAAG;AAChC,qBAAiB,KAAK;AAAA,MACpB,MAAM;AAAA,MACN,SAAS;AAAA,IACX,CAAC;AAAA,EACH;AAEA,SAAO;AACT;","names":["_a","_a","download","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","download","_a","name","asArray","z","z","z","z","isBuffer","z","z","isBuffer","z","asArray","z","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","_a","AISDKError","APICallError","InvalidPromptError","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","name","marker","symbol","_a","AISDKError","getErrorMessage","name","marker","symbol","_a","AISDKError","DownloadError","_a","asArray","_a","_a","_a","asArray","_a","_a","asSchema","safeValidateTypes","asSchema","safeValidateTypes","asSchema","safeValidateTypes","_a","safeValidateTypes","asSchema"]}
|