@mastra/core
Version:
1 lines • 1.25 MB
Source Map (JSON)
{"version":3,"file":"message-list-Bc69E1sT.cjs","names":["partAny","getDisplayTransform","getTransformedToolPayload","hasTransformedToolPayload","filterEmptyTextParts","getSignalType","getSignalTagName","isUserSignalType","toSignalDataPart","resolveFilePartMediaTypeAndData","categorizeFileData","createDataUri","imageContentToString","MastraError","ErrorDomain","ErrorCategory","convertDataContentToBase64String","AISDKError","getErrorMessage","gateway","convertBase64ToUint8Array","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","fetchWithValidatedRedirects","cancelResponseBody","DownloadError","readResponseWithSizeLimit","DEFAULT_MAX_DOWNLOAD_SIZE","z","isUint8Array","isArrayBuffer","convertUint8ArrayToBase64","isUrlSupported","asSchema","InvalidPromptError","safeValidateTypes","GatewayAuthenticationError","APICallError","retryWithExponentialBackoff","GatewayError","executeTool","safeParseJSON","resolve","TypeValidationError","createIdGenerator","getErrorMessage$1","lazySchema","zodSchema","validateTypes","DelayedPromise","isAbortError","UnsupportedFunctionalityError","InvalidResponseDataError","sanitizeToolName","getDisplayTransform","getTransformedToolPayload","hasTransformedToolPayload","resolveFilePartMediaTypeAndData","categorizeFileData","isBase64Like","parseDataUri","isBase64DataUri","toBase64DataUri","imageContentToString","createDataUri","MastraError","ErrorDomain","ErrorCategory","isAbsoluteUrl","getTransformedToolPayload","hasTransformedToolPayload","sanitizeToolName","AIV6.isToolUIPart","resolveFilePartMediaTypeAndData","getImageCacheKey","isTransientSignalMessage","categorizeFileData","convertToCoreMessagesV4","deepEqual","DefaultGeneratedFileWithType","parseDataUri","convertDataContentToBase64String","convertToDataContent","detectMediaType","imageMediaTypeSignatures","categorizeFileData","createDataUri","resolveFilePartMediaTypeAndData","fetchWithRetry","MastraError","ErrorDomain","ErrorCategory","isUrlSupported","resolveFilePartMediaTypeAndData","resolveCurrentSpan","createSignal","isTransientSignalMessage","isCreatedAgentSignal","mastraDBMessageToSignal","convertInputToMastraDBMessage","convertAIV5UIToModelMessages","convertAIV4CoreToAIV5ModelMessages","isSendableFileData","aiV5ModelMessageToV2PromptMessage","aiV5PromptToAIV6Prompt","aiV5PromptToAIV7Prompt","aiV4CoreMessageToV1PromptMessage","getTransformedToolPayload","hasTransformedToolPayload","safeStringify","MastraError","ErrorDomain","ErrorCategory","randomUUID"],"sources":["../src/agent/message-list/utils/unwrap-legacy-tool-output.ts","../src/agent/message-list/detection/TypeDetector.ts","../src/agent/message-list/utils/response-item-metadata.ts","../src/agent/message-list/utils/provider-compat.ts","../src/agent/message-list/adapters/AIV4Adapter.ts","../../_vendored/ai_v6/dist/index.js","../src/agent/message-list/adapters/AIV5Adapter.ts","../src/agent/message-list/adapters/AIV6Adapter.ts","../src/agent/message-list/cache/reasoning-identity.ts","../src/agent/message-list/cache/stable-stringify.ts","../src/agent/message-list/cache/CacheKeyGenerator.ts","../src/memory/working-memory-utils.ts","../src/agent/filter-messages-for-persistence.ts","../src/agent/message-list/conversion/utils.ts","../src/agent/message-list/utils/stamp-part.ts","../src/agent/message-list/conversion/input-converter.ts","../src/agent/message-list/conversion/output-converter.ts","../src/agent/message-list/conversion/step-content.ts","../src/agent/message-list/merge/MessageMerger.ts","../src/agent/message-list/prompt/convert-file.ts","../src/agent/message-list/prompt/attachments-to-parts.ts","../src/agent/message-list/prompt/convert-to-mastra-v1.ts","../src/agent/message-list/prompt/download-assets.ts","../src/agent/message-list/prompt/unavailable-attachments.ts","../src/agent/message-list/state/serialization.ts","../src/agent/message-list/state/MessageStateManager.ts","../src/agent/message-list/utils/tool-invocation-state.ts","../src/agent/message-list/message-list.ts","../src/agent/message-list/utils/convert-messages.ts"],"sourcesContent":["const AI_SDK_TOOL_OUTPUT_TYPES = new Set(['text', 'json', 'error-text', 'error-json', 'content']);\n\n/** Unwraps the legacy raw UI tool-output shape only when `value` is its sole enumerable key. */\nexport function unwrapLegacyToolOutput(output: unknown): unknown {\n if (output === null || typeof output !== 'object') return output;\n\n const keys = Object.keys(output);\n return keys.length === 1 && keys[0] === 'value' ? (output as { value: unknown }).value : output;\n}\n\n/** Normalizes documented AI SDK output wrappers and the legacy sole-key `{ value }` envelope. */\nexport function normalizeToolOutput(\n output: unknown,\n { unwrapContent = true }: { unwrapContent?: boolean } = {},\n): { isError: boolean; output: unknown } {\n if (output === null || typeof output !== 'object') return { isError: false, output };\n\n const record = output as Record<string, unknown>;\n const keys = Object.keys(record);\n if (\n keys.length === 2 &&\n keys.includes('type') &&\n keys.includes('value') &&\n typeof record.type === 'string' &&\n AI_SDK_TOOL_OUTPUT_TYPES.has(record.type)\n ) {\n return {\n isError: record.type === 'error-text' || record.type === 'error-json',\n output: record.type === 'content' && !unwrapContent ? output : record.value,\n };\n }\n\n return { isError: false, output: unwrapLegacyToolOutput(output) };\n}\n","import type { Message as AIV4Message, UIMessage as UIMessageV4 } from '@internal/ai-sdk-v4';\n\nimport type { MastraDBMessage, MastraMessageV1 } from '../state/types';\nimport type { AIV5Type, AIV6Type, AIV7Type, AIV7ForwardCompatibleUIMessage, CoreMessageV4 } from '../types';\n\n/**\n * Type representing all possible message input formats\n */\nexport type MessageInput =\n | AIV7Type.UIMessage\n | AIV7ForwardCompatibleUIMessage\n | AIV7Type.ModelMessage\n | AIV6Type.UIMessage\n | AIV6Type.ModelMessage\n | AIV5Type.UIMessage\n | AIV5Type.ModelMessage\n | (UIMessageV4 & { metadata?: Record<string, unknown> })\n | AIV4Message\n | CoreMessageV4\n | MastraMessageV1\n | MastraDBMessage;\n\n/**\n * TypeDetector - Centralized type detection for different message formats\n *\n * This class provides consistent type detection across all message formats,\n * which is critical for:\n * - Determining which conversion path to use\n * - Validating incoming message formats\n * - Providing better TypeScript type narrowing\n *\n * The detection order is important because some formats share similar properties.\n */\nexport class TypeDetector {\n /**\n * Check if a message is a MastraDBMessage (format 2)\n */\n static isMastraDBMessage(msg: MessageInput): msg is MastraDBMessage {\n return Boolean(\n 'content' in msg &&\n msg.content &&\n !Array.isArray(msg.content) &&\n typeof msg.content !== 'string' &&\n 'format' in msg.content &&\n msg.content.format === 2,\n );\n }\n\n /**\n * Check if a message is a MastraMessageV1 (legacy format)\n */\n static isMastraMessageV1(msg: MessageInput): msg is MastraMessageV1 {\n return !TypeDetector.isMastraDBMessage(msg) && ('threadId' in msg || 'resourceId' in msg);\n }\n\n /**\n * Check if a message is either Mastra format (V1 or V2/DB)\n */\n static isMastraMessage(msg: MessageInput): msg is MastraDBMessage | MastraMessageV1 {\n return TypeDetector.isMastraDBMessage(msg) || TypeDetector.isMastraMessageV1(msg);\n }\n\n /**\n * Check if a message is an AIV4 UIMessage\n */\n static isAIV4UIMessage(msg: MessageInput): msg is UIMessageV4 {\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !TypeDetector.isAIV4CoreMessage(msg) &&\n 'parts' in msg &&\n !TypeDetector.hasAIV5UIMessageCharacteristics(msg)\n );\n }\n\n /**\n * Check if a message is an AIV6 UIMessage.\n *\n * At runtime, the v5 and v6 UI shapes overlap heavily. We only treat a\n * message as distinctly v6 if it uses v6-only parts, tool states, or fields.\n */\n static isAIV6UIMessage(msg: MessageInput): msg is AIV6Type.UIMessage {\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !TypeDetector.isAIV4CoreMessage(msg) &&\n 'parts' in msg &&\n TypeDetector.hasAIV6UIMessageCharacteristics(\n msg as AIV7Type.UIMessage | AIV6Type.UIMessage | AIV5Type.UIMessage | UIMessageV4 | AIV4Message,\n )\n );\n }\n\n /**\n * Check if a message is an AIV5 UIMessage\n */\n static isAIV5UIMessage(msg: MessageInput): msg is AIV5Type.UIMessage {\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !TypeDetector.isAIV6UIMessage(msg) &&\n !TypeDetector.isAIV5CoreMessage(msg) &&\n 'parts' in msg &&\n TypeDetector.hasAIV5UIMessageCharacteristics(msg)\n );\n }\n\n /**\n * Check if a message is an AIV4 CoreMessage\n */\n static isAIV4CoreMessage(msg: MessageInput): msg is CoreMessageV4 {\n // V4 CoreMessage has role and content like V5/V6, but content can be an\n // array of parts with v4-specific field names.\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !('parts' in msg) &&\n 'content' in msg &&\n !TypeDetector.hasAIV5CoreMessageCharacteristics(msg)\n );\n }\n\n /**\n * Check if a message is an AIV6 ModelMessage (CoreMessage equivalent).\n */\n static isAIV6CoreMessage(msg: MessageInput): msg is AIV6Type.ModelMessage {\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !('parts' in msg) &&\n 'content' in msg &&\n TypeDetector.hasAIV6CoreMessageCharacteristics(msg)\n );\n }\n\n /**\n * Check if a message is an AIV5 ModelMessage (CoreMessage equivalent)\n */\n static isAIV5CoreMessage(msg: MessageInput): msg is AIV5Type.ModelMessage {\n return (\n !TypeDetector.isMastraMessage(msg) &&\n !TypeDetector.isAIV6CoreMessage(msg) &&\n !('parts' in msg) &&\n 'content' in msg &&\n TypeDetector.hasAIV5CoreMessageCharacteristics(msg)\n );\n }\n\n /**\n * Check if a message has AIV6-only UI characteristics.\n */\n static hasAIV6UIMessageCharacteristics(\n msg:\n | AIV7Type.UIMessage\n | AIV7ForwardCompatibleUIMessage\n | AIV6Type.UIMessage\n | AIV5Type.UIMessage\n | UIMessageV4\n | AIV4Message,\n ): msg is AIV6Type.UIMessage {\n if (!('parts' in msg) || !msg.parts) return false;\n\n for (const part of msg.parts) {\n if (part.type === 'source-document') return true;\n if (part.type === 'dynamic-tool') return true;\n\n // v5 tool parts only ever carry `callProviderMetadata`, so the result half marks v6.\n // Without this an `output-available` part fell through to the v5 adapter, which\n // dropped the `mastra.modelOutput` projection riding on it (issue #22012).\n if ('resultProviderMetadata' in part) return true;\n\n if (\n 'toolCallId' in part &&\n 'state' in part &&\n (part.state === 'approval-requested' || part.state === 'approval-responded' || part.state === 'output-denied')\n ) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Check if a message has AIV5 UIMessage characteristics\n *\n * V5 UIMessages have specific part types and field names that differ from V4.\n */\n static hasAIV5UIMessageCharacteristics(\n msg:\n | AIV7Type.UIMessage\n | AIV7ForwardCompatibleUIMessage\n | AIV6Type.UIMessage\n | AIV5Type.UIMessage\n | UIMessageV4\n | AIV4Message,\n ): msg is AIV5Type.UIMessage {\n // AI SDK v4 has separate arrays of tool invocations, reasoning, and\n // attachments that do not preserve overall part ordering, so their\n // presence is a quick early signal that this is not a v5/v6 UI message.\n if (\n 'toolInvocations' in msg ||\n 'reasoning' in msg ||\n 'experimental_attachments' in msg ||\n 'data' in msg ||\n 'annotations' in msg\n // Don't check `content` here. That would fully narrow to v5 and is more\n // likely to misclassify a loosely constructed v5/v6 UI message.\n )\n return false;\n\n if (!msg.parts) return false; // likely an AIV4 Message\n\n for (const part of msg.parts) {\n if ('metadata' in part) return true;\n\n // Tool parts are the cleanest discriminator:\n // - v4 uses `tool-invocation`\n // - v5/v6 use `tool-${toolName}` / `dynamic-tool`\n if ('toolInvocation' in part) return false;\n if ('toolCallId' in part) return true;\n if (part.type === 'source') return false;\n if (part.type === 'source-url') return true;\n\n if (part.type === 'reasoning') {\n if ('state' in part || 'text' in part) return true; // v5/v6\n if ('reasoning' in part || 'details' in part) return false; // v4\n }\n\n if (part.type === 'file' && 'mediaType' in part) return true;\n }\n\n return false; // default to v4 for backwards compatibility\n }\n\n /**\n * Check if a message has AIV6-only core characteristics.\n */\n static hasAIV6CoreMessageCharacteristics(\n msg: CoreMessageV4 | AIV5Type.ModelMessage | AIV6Type.ModelMessage | AIV7Type.ModelMessage | AIV4Message,\n ): msg is AIV6Type.ModelMessage {\n if ('parts' in msg || !Array.isArray(msg.content)) return false;\n\n return msg.content.some(\n part =>\n part !== null &&\n typeof part === 'object' &&\n (part.type === 'tool-approval-request' || part.type === 'tool-approval-response'),\n );\n }\n\n /**\n * Check if a message has AIV5 CoreMessage characteristics\n *\n * V5 ModelMessages use different field names from v4\n * (for example `output` vs `result`, `input` vs `args`,\n * `mediaType` vs `mimeType`).\n */\n static hasAIV5CoreMessageCharacteristics(\n msg:\n | CoreMessageV4\n | AIV6Type.ModelMessage\n | AIV5Type.ModelMessage\n | AIV7Type.ModelMessage\n // This is here because the AIV4 Message type can omit parts entirely.\n | AIV4Message,\n ): msg is AIV5Type.ModelMessage {\n if ('experimental_providerMetadata' in msg) return false;\n // String or missing content is compatible with the v5 model format.\n if (!Array.isArray(msg.content)) return true;\n\n for (const part of msg.content) {\n if (part === null || typeof part !== 'object') continue;\n if (part.type === 'tool-result' && 'output' in part) return true;\n if (part.type === 'tool-call' && 'input' in part) return true;\n if (part.type === 'tool-result' && 'result' in part) return false;\n if (part.type === 'tool-call' && 'args' in part) return false;\n if ('mediaType' in part) return true;\n if ('mimeType' in part) return false;\n if ('experimental_providerMetadata' in part) return false;\n if (part.type === 'reasoning' && 'signature' in part) return false;\n if (part.type === 'redacted-reasoning') return false;\n }\n\n // If no distinguishing features are found, the message shape is still\n // compatible with the v5 model format.\n return true;\n }\n\n /**\n * Get the normalized role for a message\n * Maps `tool` to `assistant` because tool messages are displayed as part of\n * the assistant conversation.\n */\n static getRole(message: MessageInput): MastraDBMessage['role'] {\n if (message.role === 'assistant' || message.role === 'tool') return 'assistant';\n if (message.role === 'user') return 'user';\n if (message.role === 'system') return 'system';\n throw new Error(\n `BUG: add handling for message role ${message.role} in message ${JSON.stringify(message, null, 2)}`,\n );\n }\n}\n","export const RESPONSE_ITEM_ID_PROVIDERS = ['openai', 'azure'] as const;\n\nexport type ResponseItemIdProvider = (typeof RESPONSE_ITEM_ID_PROVIDERS)[number];\n\n/**\n * Key under a provider namespace holding the item id of a tool RESULT when it\n * differs from the call's item id. Some hosted tools on the OpenAI Responses\n * API (e.g. `tool_search`) give the call and its output distinct item ids\n * (`tsc_…` / `tso_…`). A merged tool part only has one `itemId` slot, so the\n * result id is kept alongside it; prompt conversion splits them back so each\n * side replays as its own `item_reference` (referencing one id twice fails\n * with \"Duplicate item found\").\n */\nexport const RESPONSE_RESULT_ITEM_ID_KEY = 'resultItemId';\n\nfunction formatResponseProviderItemKey(provider: ResponseItemIdProvider, itemId: string): string {\n // Keep the provider namespace in the key so matching Azure/OpenAI item IDs\n // cannot merge across provider-specific response streams.\n return `${provider}:${itemId}`;\n}\n\nexport function getResponseProviderItemId(\n providerMetadata: Record<string, unknown> | undefined,\n): { provider: ResponseItemIdProvider; itemId: string } | undefined {\n return getResponseProviderItemIds(providerMetadata)[0];\n}\n\nexport function getResponseProviderItemKey(providerMetadata: Record<string, unknown> | undefined): string | undefined {\n const item = getResponseProviderItemId(providerMetadata);\n return item ? formatResponseProviderItemKey(item.provider, item.itemId) : undefined;\n}\n\nexport function getResponseProviderItemIds(\n providerMetadata: Record<string, unknown> | undefined,\n): Array<{ provider: ResponseItemIdProvider; itemId: string }> {\n if (!providerMetadata) return [];\n\n const azureMetadata = providerMetadata.azure as Record<string, unknown> | undefined;\n const azureItemId = azureMetadata?.itemId;\n const openaiMetadata = providerMetadata.openai as Record<string, unknown> | undefined;\n const openaiItemId = openaiMetadata?.itemId;\n if (typeof azureItemId === 'string' && azureItemId === openaiItemId) {\n return [{ provider: 'azure', itemId: azureItemId }];\n }\n\n // AI SDK Responses metadata is expected to use exactly one provider namespace\n // per part. If a future proxy adds both, keep this deterministic.\n return RESPONSE_ITEM_ID_PROVIDERS.flatMap(provider => {\n const metadata = providerMetadata[provider] as Record<string, unknown> | undefined;\n const itemId = metadata?.itemId;\n return typeof itemId === 'string' ? [{ provider, itemId }] : [];\n });\n}\n\n/**\n * Preserves both item ids when a tool-call part and its tool-result carry\n * DIFFERENT Responses item ids for the same provider namespace. Returns\n * `merged` with the namespace rewritten to `{ itemId: <call id>,\n * resultItemId: <result id> }`; a no-op (returns `merged` unchanged) when\n * either side lacks an item id or both sides share one.\n */\nexport function preserveResponseItemIdsOnMerge(\n callMetadata: Record<string, unknown> | undefined,\n resultMetadata: Record<string, unknown> | undefined,\n merged: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n let result = merged;\n for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n const callItemId = (callMetadata?.[provider] as Record<string, unknown> | undefined)?.itemId;\n const resultItemId = (resultMetadata?.[provider] as Record<string, unknown> | undefined)?.itemId;\n if (typeof callItemId !== 'string' || typeof resultItemId !== 'string' || callItemId === resultItemId) {\n continue;\n }\n const namespace = (result?.[provider] ?? {}) as Record<string, unknown>;\n result = {\n ...result,\n [provider]: { ...namespace, itemId: callItemId, [RESPONSE_RESULT_ITEM_ID_KEY]: resultItemId },\n };\n }\n return result;\n}\n\n/**\n * Builds result-side provider metadata from a merged tool part's metadata:\n * `{ <provider>: { itemId: <resultItemId> } }` for each namespace carrying a\n * {@link RESPONSE_RESULT_ITEM_ID_KEY}. Returns undefined when no namespace\n * does (the common case — most tools share one item id across call/result).\n */\nexport function getResponseResultProviderMetadata(\n providerMetadata: Record<string, unknown> | undefined,\n): Record<string, Record<string, unknown>> | undefined {\n if (!providerMetadata) return undefined;\n let result: Record<string, Record<string, unknown>> | undefined;\n for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n const resultItemId = (providerMetadata[provider] as Record<string, unknown> | undefined)?.[\n RESPONSE_RESULT_ITEM_ID_KEY\n ];\n if (typeof resultItemId !== 'string') continue;\n result = { ...result, [provider]: { itemId: resultItemId } };\n }\n return result;\n}\n\n/**\n * Reads the result-side item id stored beside `itemId` in ONE provider\n * namespace. Callers that replay a specific namespace must read both ids from\n * that same namespace: a pair stored under `azure` says nothing about whether\n * an `openai` id can be replayed.\n */\nexport function getResponseResultItemId(\n providerMetadata: Record<string, unknown> | undefined,\n provider: ResponseItemIdProvider,\n): string | undefined {\n const resultItemId = (providerMetadata?.[provider] as Record<string, unknown> | undefined)?.[\n RESPONSE_RESULT_ITEM_ID_KEY\n ];\n return typeof resultItemId === 'string' ? resultItemId : undefined;\n}\n\n/**\n * Drops {@link RESPONSE_RESULT_ITEM_ID_KEY} from every namespace. The key is\n * Mastra's internal way of carrying a result id on a part with a single\n * metadata slot; it must never reach a provider or a public UI surface that\n * already has a dedicated slot for the result's metadata.\n */\nexport function omitResponseResultItemIds<T extends Record<string, unknown> | undefined>(providerMetadata: T): T {\n if (!providerMetadata) return providerMetadata;\n let result = providerMetadata;\n for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n const namespace = result[provider] as Record<string, unknown> | undefined;\n if (!namespace || !(RESPONSE_RESULT_ITEM_ID_KEY in namespace)) continue;\n const { [RESPONSE_RESULT_ITEM_ID_KEY]: _removed, ...rest } = namespace;\n result = { ...result, [provider]: rest };\n }\n return result;\n}\n\nexport function getResponseProviderItemKeys(providerMetadata: Record<string, unknown> | undefined): string[] {\n return getResponseProviderItemIds(providerMetadata).map(({ provider, itemId }) =>\n formatResponseProviderItemKey(provider, itemId),\n );\n}\n","import type { ModelMessage, ToolResultPart } from '@internal/ai-sdk-v5';\n\nimport type { IMastraLogger } from '../../../logger';\nimport type { MastraDBMessage } from '../state/types';\nimport { getResponseProviderItemId } from './response-item-metadata';\nimport type { ResponseItemIdProvider } from './response-item-metadata';\n\n/**\n * Tool result with input field (Anthropic requirement)\n */\nexport type ToolResultWithInput = ToolResultPart & {\n input: Record<string, unknown>;\n};\n\n// ============================================================================\n// Cross-provider Compatibility\n// ============================================================================\n\n/**\n * Removes provider-executed tool parts that a *different* provider produced.\n *\n * A provider-executed tool result is the provider's own payload, in the provider's\n * own shape, and each provider validates it against its own schema on the way back\n * in. Those shapes disagree — OpenAI's `web_search` result is an object, Anthropic's\n * is an array — and the tool names collide, so replaying one provider's stored result\n * to another throws during prompt conversion, before the request is even built. That\n * bricks the thread permanently rather than degrading one turn.\n *\n * These parts are deliberately exempt from `sanitizeOrphanedToolPairs` (their results\n * may legitimately be deferred), so they need dropping here instead. Only parts whose\n * origin message is stamped with a provider that differs from the target are removed;\n * unstamped history is left untouched, so nothing changes for threads that predate\n * provider stamping.\n *\n * Only the provider-executed parts are removed. Text and reasoning from the same foreign\n * turn stay, because they are provider-agnostic content rather than a provider's own\n * validated payload. The trade-off is that a later turn may still reference a search whose\n * results are no longer in context — an incomplete answer instead of an unusable thread.\n *\n * Matching is by exact provider string, not by vendor family, because provider ids are not\n * a uniform namespace: `ModelRouterLanguageModel` falls back to the configured provider id,\n * so values like `crof` sit alongside `anthropic.messages`. A same-vendor switch such as\n * `openai.responses` to `openai.chat` therefore also drops — the safe direction, since the\n * alternative is guessing that two providers share a payload shape.\n *\n * @param messages - Converted model messages about to be sent\n * @param dbMessages - Stored messages, read for the `provider` each assistant turn was generated by\n * @param targetProvider - Provider the prompt is being built for; when unknown, nothing is dropped\n * @param logger - Optional logger, warned once per dropped tool call\n * @returns The same array when nothing is dropped, otherwise a new array\n *\n * @see https://github.com/mastra-ai/mastra/issues/23082\n */\nexport function dropCrossProviderExecutedParts<T extends ModelMessage>(\n messages: T[],\n dbMessages: MastraDBMessage[],\n targetProvider: string | undefined,\n logger?: IMastraLogger,\n): T[] {\n if (!targetProvider) return messages;\n\n // Tool calls a *different* provider executed, keyed by call id.\n const foreign = new Map<string, { toolName: string; provider: string }>();\n for (const dbMessage of dbMessages) {\n if (dbMessage.role !== 'assistant' || dbMessage.content?.format !== 2) continue;\n\n const provider = (dbMessage.content.metadata as { provider?: unknown } | undefined)?.provider;\n if (typeof provider !== 'string' || provider === targetProvider) continue;\n\n for (const part of dbMessage.content.parts ?? []) {\n if (part.type !== 'tool-invocation' || !(part as { providerExecuted?: boolean }).providerExecuted) continue;\n foreign.set(part.toolInvocation.toolCallId, { toolName: part.toolInvocation.toolName, provider });\n }\n }\n\n if (foreign.size === 0) return messages;\n\n const isForeign = (part: unknown): boolean => {\n const candidate = part as { type?: string; toolCallId?: string };\n return (\n (candidate.type === 'tool-call' || candidate.type === 'tool-result') &&\n typeof candidate.toolCallId === 'string' &&\n foreign.has(candidate.toolCallId)\n );\n };\n\n // Warn only for parts actually present in this prompt: `dbMessages` routinely holds\n // more history than recall selected, so warning per stored entry would report drops\n // that never happened.\n const warned = new Set<string>();\n const warnOnce = (toolCallId: string) => {\n if (warned.has(toolCallId)) return;\n warned.add(toolCallId);\n const { toolName, provider } = foreign.get(toolCallId)!;\n logger?.warn(\n `Dropping provider-executed \"${toolName}\" result from an earlier turn: it was produced by \"${provider}\" and this request goes to \"${targetProvider}\", which cannot read the other provider's payload.`,\n { toolCallId },\n );\n };\n\n let dropped = false;\n const result = messages.map(message => {\n if (!Array.isArray(message.content) || !message.content.some(isForeign)) return message;\n dropped = true;\n return {\n ...message,\n content: message.content.filter(part => {\n if (!isForeign(part)) return true;\n warnOnce((part as { toolCallId: string }).toolCallId);\n return false;\n }),\n } as T;\n });\n\n return dropped ? result : messages;\n}\n\n// ============================================================================\n// Anthropic Compatibility\n// ============================================================================\n\n/**\n * Ensures model messages are compatible with Anthropic API requirements.\n *\n * Anthropic API requires tool-result parts to include an 'input' field\n * that matches the original tool call arguments.\n *\n * @param messages - Array of model messages to transform\n * @param dbMessages - MastraDB messages to look up tool call args from\n * @returns Messages with tool-result parts enriched with input field\n *\n * @see https://github.com/mastra-ai/mastra/issues/11376 - Anthropic models fail with empty object tool input\n */\nexport function ensureAnthropicCompatibleMessages(\n messages: ModelMessage[],\n dbMessages: MastraDBMessage[],\n): ModelMessage[] {\n return messages.map(msg => enrichToolResultsWithInput(msg, dbMessages));\n}\n\n/**\n * Tool call ids in the assistant message at `index` that already have a matching tool_result,\n * either inline in the same message or in the tool message immediately after it — the only\n * two positions providers accept.\n */\nfunction collectPairedToolCallIds(messages: ModelMessage[], index: number): Set<string> {\n const current = messages[index]!;\n if (!Array.isArray(current.content)) return new Set();\n\n const useIds = new Set<string>();\n const resultIds = new Set<string>();\n for (const part of current.content) {\n if (part.type === 'tool-call') useIds.add(part.toolCallId);\n else if (part.type === 'tool-result') resultIds.add(part.toolCallId);\n }\n\n const next = messages[index + 1];\n if (next && next.role === 'tool' && Array.isArray(next.content)) {\n for (const part of next.content) {\n if (part.type === 'tool-result') resultIds.add(part.toolCallId);\n }\n }\n\n return new Set([...useIds].filter(id => resultIds.has(id)));\n}\n\n/**\n * Removes orphan tool_use / tool_result blocks. Anthropic requires every tool_result\n * to be in the message immediately after its matching tool_use, and every tool_use\n * to have a matching tool_result in the next message. Recall windows can slice\n * through a parallel tool-call group and leave behind half a pair.\n */\nexport function sanitizeOrphanedToolPairs(messages: ModelMessage[]): ModelMessage[] {\n const filteredContents = messages.map(m => (Array.isArray(m.content) ? [...m.content] : null));\n\n for (let i = 0; i < messages.length; i++) {\n const current = messages[i]!;\n\n if (current.role === 'assistant' && Array.isArray(current.content)) {\n const validPairs = collectPairedToolCallIds(messages, i);\n const next = messages[i + 1];\n\n filteredContents[i] = filteredContents[i]!.filter(p => {\n if (p.type !== 'tool-call') return true;\n const tc = p as { toolCallId: string; providerExecuted?: boolean };\n // Provider-executed tools may be deferred (e.g. Anthropic web_search): the tool_use\n // can appear without a matching tool_result until the provider resumes on the next call.\n return tc.providerExecuted === true || validPairs.has(tc.toolCallId);\n });\n\n if (next && next.role === 'tool' && Array.isArray(next.content)) {\n filteredContents[i + 1] = filteredContents[i + 1]!.filter(\n p => p.type !== 'tool-result' || validPairs.has((p as { toolCallId: string }).toolCallId),\n );\n }\n } else if (current.role === 'tool' && Array.isArray(current.content)) {\n const prev = messages[i - 1];\n if (!prev || prev.role !== 'assistant' || !Array.isArray(prev.content)) {\n filteredContents[i] = filteredContents[i]!.filter(p => p.type !== 'tool-result');\n }\n }\n }\n\n const result: ModelMessage[] = [];\n for (let i = 0; i < messages.length; i++) {\n const original = messages[i]!;\n const filtered = filteredContents[i];\n if (filtered == null) {\n result.push(original);\n continue;\n }\n if (filtered.length === 0) continue;\n if (Array.isArray(original.content) && filtered.length === original.content.length) {\n result.push(original);\n continue;\n }\n result.push({ ...original, content: filtered } as ModelMessage);\n }\n\n return result;\n}\n\n/**\n * Keeps result-less tool calls in the prompt by pairing each one with a placeholder result.\n *\n * Used when the caller opted to keep suspended tool calls visible to the agent\n * (`filterIncompleteToolCalls: false`). Providers reject a tool_use with no matching\n * tool_result, so dropping the call is not the only option — synthesizing the missing\n * half keeps the pending call in context while satisfying the pairing requirement.\n *\n * Provider-executed calls are left alone: they may be legitimately deferred to the next\n * request, and giving them a result would resolve a call the provider intends to resume.\n *\n * @see https://github.com/mastra-ai/mastra/issues/20610\n */\nexport function pairOrphanedToolCalls(messages: ModelMessage[]): ModelMessage[] {\n const paired: ModelMessage[] = [];\n\n for (let i = 0; i < messages.length; i++) {\n const current = messages[i]!;\n paired.push(current);\n\n if (current.role !== 'assistant' || !Array.isArray(current.content)) continue;\n\n const pairedIds = collectPairedToolCallIds(messages, i);\n const placeholders: ToolResultPart[] = [];\n for (const part of current.content) {\n if (part.type !== 'tool-call') continue;\n const tc = part as { toolCallId: string; toolName: string; providerExecuted?: boolean };\n if (tc.providerExecuted === true || pairedIds.has(tc.toolCallId)) continue;\n placeholders.push({\n type: 'tool-result',\n toolCallId: tc.toolCallId,\n toolName: tc.toolName,\n output: { type: 'json', value: { status: 'pending' } },\n });\n }\n\n if (placeholders.length === 0) continue;\n\n const next = messages[i + 1];\n if (next && next.role === 'tool' && Array.isArray(next.content)) {\n paired.push({ ...next, content: [...next.content, ...placeholders] });\n i++;\n } else {\n paired.push({ role: 'tool', content: placeholders });\n }\n }\n\n // Every tool call is paired by now, so this only clears tool_results whose call is gone.\n return sanitizeOrphanedToolPairs(paired);\n}\n\n/**\n * Enriches a single message's tool-result parts with input field\n */\nfunction enrichToolResultsWithInput(message: ModelMessage, dbMessages: MastraDBMessage[]): ModelMessage {\n if (message.role !== 'tool' || !Array.isArray(message.content)) {\n return message;\n }\n\n return {\n ...message,\n content: message.content.map(part => {\n if (part.type === 'tool-result') {\n return {\n ...part,\n input: findToolCallArgs(dbMessages, part.toolCallId),\n } as ToolResultWithInput;\n }\n return part;\n }),\n } as ModelMessage;\n}\n\n// ============================================================================\n// OpenAI-compatible Responses Compatibility\n// ============================================================================\n\n/**\n * Checks if a message part has an OpenAI reasoning itemId.\n *\n * OpenAI Responses reasoning items are tracked via `providerMetadata.openai.itemId`.\n * Each reasoning item has a unique itemId that must be preserved for proper deduplication.\n *\n * @param part - A message part to check\n * @returns true if the part has an OpenAI itemId\n *\n * @see https://github.com/mastra-ai/mastra/issues/9005 - OpenAI reasoning items filtering\n */\nexport function hasOpenAIReasoningItemId(part: unknown): boolean {\n return Boolean(getOpenAIReasoningItemId(part));\n}\n\n/**\n * Checks if a message part has an OpenAI-compatible Responses itemId.\n *\n * Provider-neutral Responses item IDs are tracked via provider metadata or\n * provider options fields such as `openai.itemId` or `azure.itemId`.\n */\nexport function hasResponseProviderItemId(part: unknown): boolean {\n return Boolean(getResponseProviderItemIdFromPart(part));\n}\n\n/**\n * Extracts an OpenAI itemId from a message part if present.\n *\n * This only inspects `providerMetadata.openai.itemId`; use\n * `getResponseProviderItemIdFromPart` for provider-aware Azure/OpenAI lookups.\n *\n * @param part - A message part to extract from\n * @returns The itemId string or undefined if not present\n */\nexport function getOpenAIReasoningItemId(part: unknown): string | undefined {\n if (!part || typeof part !== 'object') return undefined;\n const partAny = part as Record<string, unknown>;\n const providerMetadata = partAny.providerMetadata as Record<string, unknown> | undefined;\n const openaiMetadata = providerMetadata?.openai as Record<string, unknown> | undefined;\n return typeof openaiMetadata?.itemId === 'string' ? openaiMetadata.itemId : undefined;\n}\n\nexport function getResponseProviderItemIdFromPart(\n part: unknown,\n): { provider: ResponseItemIdProvider; itemId: string } | undefined {\n if (!part || typeof part !== 'object') return undefined;\n const partAny = part as Record<string, unknown>;\n\n return (\n getResponseProviderItemId(partAny.providerMetadata as Record<string, unknown> | undefined) ||\n getResponseProviderItemId(partAny.providerOptions as Record<string, unknown> | undefined)\n );\n}\n\n// ============================================================================\n// Tool Call Args Lookup\n// ============================================================================\n\n/**\n * Finds the tool call args for a given toolCallId by searching through messages.\n * This is used to reconstruct the input field when converting tool-result parts to StaticToolResult.\n *\n * Searches through messages in reverse order (most recent first) for better performance.\n * Checks both content.parts (v2 format) and toolInvocations (legacy AIV4 format).\n *\n * @param messages - Array of MastraDB messages to search through\n * @param toolCallId - The ID of the tool call to find args for\n * @returns The args object from the matching tool call, or an empty object if not found\n */\nexport function findToolCallArgs(messages: MastraDBMessage[], toolCallId: string): Record<string, unknown> {\n // Search through all messages in reverse order (most recent first) for better performance\n for (let i = messages.length - 1; i >= 0; i--) {\n const msg = messages[i];\n if (!msg || msg.role !== 'assistant') {\n continue;\n }\n\n // Check both content.parts (v2 format) and toolInvocations (legacy format)\n if (msg.content.parts) {\n // Look for tool-invocation with matching toolCallId (can be in 'call' or 'result' state)\n const toolCallPart = msg.content.parts.find(\n p => p.type === 'tool-invocation' && p.toolInvocation.toolCallId === toolCallId,\n );\n\n if (toolCallPart && toolCallPart.type === 'tool-invocation') {\n const args = toolCallPart.toolInvocation.args || {};\n if (typeof args === 'object' && Object.keys(args).length > 0) {\n return args;\n }\n }\n }\n\n // Also check toolInvocations array (AIV4 format)\n if (msg.content.toolInvocations) {\n const toolInvocation = msg.content.toolInvocations.find(inv => inv.toolCallId === toolCallId);\n\n if (toolInvocation) {\n const args = toolInvocation.args || {};\n if (typeof args === 'object' && Object.keys(args).length > 0) {\n return args;\n }\n }\n }\n }\n\n // If not found in DB messages, return empty object\n return {};\n}\n","import type {\n UIMessage as UIMessageV4,\n CoreMessage as CoreMessageV4,\n ToolInvocation as ToolInvocationV4,\n} from '@internal/ai-sdk-v4';\n\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../../error';\nimport { getTransformedToolPayload, hasTransformedToolPayload } from '../../../tools/payload-transform';\nimport { TypeDetector } from '../detection/TypeDetector';\nimport { convertDataContentToBase64String } from '../prompt/data-content';\nimport type { ImageContent } from '../prompt/image-utils';\nimport {\n categorizeFileData,\n createDataUri,\n imageContentToString,\n resolveFilePartMediaTypeAndData,\n} from '../prompt/image-utils';\nimport type {\n MastraDBMessage,\n MastraMessageContentV2,\n MastraMessagePart,\n UIMessageV4Part,\n MessageSource,\n UIMessageWithMetadata,\n} from '../state/types';\nimport { findToolCallArgs } from '../utils/provider-compat';\n\nfunction getDisplayTransform(\n providerMetadata: unknown,\n phase: 'input-available' | 'output-available' | 'error',\n fallback: unknown,\n enabled = true,\n) {\n if (!enabled) {\n return fallback;\n }\n const transform = getTransformedToolPayload(providerMetadata, 'display', phase);\n return hasTransformedToolPayload(transform) ? transform.transformed : fallback;\n}\n\nfunction transformV4ToolInvocationForDisplay(\n invocation: NonNullable<MastraMessageContentV2['toolInvocations']>[number],\n providerMetadata: unknown,\n enabled: boolean,\n) {\n return {\n ...invocation,\n args: getDisplayTransform(providerMetadata, 'input-available', invocation.args, enabled),\n ...(invocation.state === 'result'\n ? {\n result: getDisplayTransform(\n providerMetadata,\n 'output-available',\n getDisplayTransform(providerMetadata, 'error', invocation.result, enabled),\n enabled,\n ),\n }\n : {}),\n };\n}\n\n/**\n * Cast Mastra parts (including data-* extensions) to the V4 UI parts type.\n * Data-* parts (e.g. data-tool-call-suspended) are not natively typed in AI SDK V4,\n * but must be preserved so features like HITL workflow resumption work after a page refresh.\n */\nfunction preserveExtendedParts(parts: MastraMessagePart[]): UIMessageV4Part[] {\n return parts as UIMessageV4Part[];\n}\n\n/**\n * Filter out empty text parts from message parts array.\n * Empty text blocks are not allowed by Anthropic's API and cause request failures.\n * This can happen during streaming when text-start/text-end events occur without actual content.\n * However, if the only part is an empty text part, it is preserved as a legitimate placeholder\n * (e.g. empty assistant messages between tool results and user messages).\n */\nfunction filterEmptyTextParts(parts: MastraMessagePart[]): MastraMessagePart[] {\n const hasNonEmptyParts = parts.some(part => !(part.type === 'text' && part.text === ''));\n if (!hasNonEmptyParts) return parts;\n return parts.filter(part => {\n if (part.type === 'text') {\n return part.text !== '';\n }\n return true;\n });\n}\n\nfunction getSignalType(message: MastraDBMessage): string | undefined {\n const signal = message.content.metadata?.signal;\n if (signal && typeof signal === 'object' && !Array.isArray(signal)) {\n const type = (signal as Record<string, unknown>).type;\n return typeof type === 'string' ? type : message.type;\n }\n\n return message.type;\n}\n\nfunction getSignalTagName(message: MastraDBMessage): string | undefined {\n const signal = message.content.metadata?.signal;\n if (signal && typeof signal === 'object' && !Array.isArray(signal)) {\n const tagName = (signal as Record<string, unknown>).tagName;\n if (typeof tagName === 'string') return tagName;\n }\n\n const type = getSignalType(message);\n if (type === 'user') return 'user';\n if (type === 'reactive') return message.type;\n return type;\n}\n\nfunction isUserSignalType(type: string | undefined): boolean {\n return type === 'user' || type === 'user-message';\n}\n\nfunction toSignalDataPart(message: MastraDBMessage, contents: string): MastraMessagePart {\n const signal =\n message.content.metadata?.signal && typeof message.content.metadata.signal === 'object'\n ? (message.content.metadata.signal as Record<string, unknown>)\n : {};\n const metadata =\n signal.metadata && typeof signal.metadata === 'object' && !Array.isArray(signal.metadata)\n ? (signal.metadata as Record<string, unknown>)\n : {};\n const attributes =\n signal.attributes && typeof signal.attributes === 'object' && !Array.isArray(signal.attributes)\n ? (signal.attributes as Record<string, unknown>)\n : {};\n\n const type = getSignalType(message) ?? 'signal';\n const tagName = getSignalTagName(message) ?? type;\n return {\n type: type === 'user' ? 'data-user-message' : 'data-signal',\n data: {\n id: typeof signal.id === 'string' ? signal.id : message.id,\n type,\n tagName,\n contents: 'contents' in signal ? signal.contents : contents,\n createdAt: typeof signal.createdAt === 'string' ? signal.createdAt : message.createdAt.toISOString(),\n ...(typeof signal.acceptedAt === 'string' ? { acceptedAt: signal.acceptedAt } : {}),\n ...(Object.keys(attributes).length ? { attributes } : {}),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n },\n } as MastraMessagePart;\n}\n\n// Re-export for backward compatibility\nexport type { UIMessageWithMetadata };\n\nexport interface AIV4AdapterContext {\n memoryInfo: { threadId?: string; resourceId?: string } | null;\n newMessageId(): string;\n generateCreatedAt(messageSource: MessageSource, start?: unknown): Date;\n /** Messages array for looking up tool call args */\n dbMessages?: MastraDBMessage[];\n}\n\n/**\n * AIV4Adapter - Handles conversions between MastraDBMessage and AI SDK V4 formats\n *\n * This adapter centralizes all AI SDK V4 (UIMessage and CoreMessage) conversion logic.\n */\nexport class AIV4Adapter {\n /**\n * Convert MastraDBMessage to AI SDK V4 UIMessage\n */\n static toUIMessage(m: MastraDBMessage, options?: { transformToolPayloads?: boolean }): UIMessageWithMetadata {\n const transformToolPayloads = options?.transformToolPayloads ?? true;\n const experimentalAttachments: UIMessageWithMetadata['experimental_attachments'] = m.content\n .experimental_attachments\n ? [...m.content.experimental_attachments]\n : [];\n const contentString =\n typeof m.content.content === `string` && m.content.content !== ''\n ? m.content.content\n : (m.content.parts ?? []).reduce((prev, part) => {\n if (part.type === `text`) {\n // return only the last text part like AI SDK does\n return part.text;\n }\n return prev;\n }, '');\n\n const parts: MastraMessageContentV2['parts'] = [];\n const sourceParts = m.content.parts ?? [];\n\n if (sourceParts.length) {\n for (const part of sourceParts) {\n if (part.type === `file`) {\n // Stored file parts can arrive in either the v4 (`mimeType`/`data`) or v5\n // (`mediaType`/`url`) shape; resolve both so a v5 part isn't read as `undefined`.\n const { mediaType: fileMimeType, data: fileData } = resolveFilePartMediaTypeAndData(part);\n // Normalize fileData to ensure it's a valid URL or data URI\n let normalizedUrl: string;\n if (typeof fileData === 'string') {\n const categorized = categorizeFileData(fileData, fileMimeType);\n if (categorized.type === 'raw') {\n // Raw base64 - convert to data URI\n normalizedUrl = createDataUri(fileData, fileMimeType || 'application/octet-stream');\n } else {\n // Already a URL, data URI, or provider file ID (e.g. OpenAI \"file-...\").\n // Provider file IDs are not parseable URLs; attachmentsToParts handles\n // them explicitly before constructing a URL.\n normalizedUrl = fileData;\n }\n } else {\n // Non-string payload (shouldn't happen for stored file parts, but handle it):\n // coerce to a string so `normalizedUrl` stays typed `string`.\n normalizedUrl = imageContentToString(fileData as ImageContent, fileMimeType);\n }\n\n experimentalAttachments.push({\n contentType: fileMimeType ?? 'application/octet-stream',\n url: normalizedUrl,\n });\n } else if (\n part.type === 'tool-invocation' &&\n (part.toolInvocation.state === 'call' || part.toolInvocation.state === 'partial-call')\n ) {\n // Filter out tool invocations with call or partial-call states\n continue;\n } else if (part.type === 'tool-invocation') {\n // Handle tool invocations with step number logic\n const isDeniedApproval = part.toolInvocation.state === 'output-denied';\n const isOutputError = part.toolInvocation.state === 'output-error';\n const toolInvocation = {\n ...part.toolInvocation,\n // v4 has no denied or output-error state and AI SDK v4's convertToCoreMessages\n // requires every completed tool invocation to carry a result. Downgrade both to\n // normal results so the error or denial is sent back to the model.\n // A downgraded output-error still has to read as a failure, so keep the isError\n // marker on it — otherwise a failed terminal tool looks like it succeeded.\n ...(isDeniedApproval || isOutputError ? { state: 'result' as const } : {}),\n ...(isOutputError ? { isError: true } : {}),\n args: getDisplayTransform(\n part.providerMetadata,\n 'input-available',\n part.toolInvocation.args,\n transformToolPayloads,\n ),\n ...(part.toolInvocation.state === 'result'\n ? {\n result: getDisplayTransform(\n part.providerMetadata,\n 'output-available',\n getDisplayTransform(\n part.providerMetadata,\n 'error',\n part.toolInvocation.result,\n transformToolPayloads,\n ),\n transformToolPayloads,\n ),\n }\n : isDeniedApproval\n ? { result: part.toolInvocation.approval?.reason ?? 'Tool call was not approved by the user' }\n : isOutputError\n ? { result: part.toolInvocation.errorText }\n : {}),\n };\n\n // Find the step number for this tool invocation\n let currentStep = -1;\n let toolStep = -1;\n for (const innerPart of sourceParts) {\n if (innerPart.type === `step-start`) currentStep++;\n if (\n innerPart.type === `tool-invocation` &&\n innerPart.toolInvocation.toolCallId === part.toolInvocation.toolCallId\n ) {\n toolStep = currentStep;\n break;\n }\n }\n\n if (toolStep >= 0) {\n const preparedInvocation = {\n step: toolStep,\n ...toolInvocation,\n };\n parts.push({\n type: 'tool-invocation',\n toolInvocation: preparedInvocation,\n });\n } else {\n parts.push({\n type: 'tool-invocation',\n toolInvocation,\n });\n }\n } else {\n parts.push(part);\n }\n }\n }\n\n if (parts.length === 0 && experimentalAttachments.length > 0) {\n // make sure we have atleast one part so this message doesn't get removed when converting to core message\n parts.push({ type: 'text', text: '' });\n }\n\n const signalType = m.role === 'signal' ? getSignalType(m) : undefined;\n const isUserMessageSignal = isUserSignalType(signalType);\n const v4Parts = preserveExtendedParts(\n m.role === 'signal' && !isUserMessageSignal ? [toSignalDataPart(m, m.content.content || contentString)] : parts,\n );\n\n if (m.role === `user`) {\n const uiMessage: UIMessageWithMetadata = {\n id: m.id,\n role: m.role,\n content: m.content.content || contentString,\n createdAt: m.createdAt,\n parts: v4Parts,\n experimental_attachments: experimentalAttachments,\n };\n // Preserve metadata if present\n if (m.content.metadata) {\n uiMessage.metadata = m.content.metadata;\n }\n return uiMessage;\n } else if (m.role === `assistant`) {\n const isSingleTextContentArray =\n Array.isArray(m.content.content) && m.content.content.length === 1 && m.content.content[0].type === `text`;\n\n const uiMessage: UIMessageWithMetadata = {\n id: m.id,\n role: m.role,\n content: isSingleTextContentArray ? contentString : m.content.content || contentString,\n createdAt: m.createdAt,\n parts: v4Parts,\n reasoning: undefined,\n toolInvocations:\n `toolInvocations` in m.content\n ? m.content.toolInvocations\n ?.filter(t => t.state === 'result')\n .map(toolInvocation => {\n const partProviderMetadata = m.content.parts?.find(\n part =>\n part.type === 'tool-invocation' && part.toolInvocation.toolCallId === toolInvocation.toolCallId,\n )?.providerMetadata;\n return transformV4ToolInvocationForDisplay(\n toolInvocation,\n partProviderMetadata,\n transformToolPayloads,\n );\n })\n : undefined,\n };\n // Preserve metadata if present\n if (m.content.metadata) {\n uiMessage.metadata = m.content.metadata;\n }\n return uiMessage;\n }\n\n const uiMessage: UIMessageWithMetadata = {\n id: m.id,\n role: m.role === 'signal' ? (isUserMessageSignal ? 'user' : 'system') : m.role,\n content: m.role === 'signal' && !isUserMessageSignal ? '' : m.content.content || contentString,\n createdAt: m.createdAt,\n parts: v4Parts,\n experimental_attachments: experimentalAttachments,\n };\n // Preserve metadata if present\n if (m.content.metadata) {\n uiMessage.metadata = m.content.metadata;\n }\n return uiMessage;\n }\n\n /**\n * Converts a MastraDBMessage system message directly to AIV4 CoreMessage format\n */\n static systemToV4Core(message: MastraDBMessage): CoreMessageV4 {\n if (message.role !== `system` || !message.content.content)\n throw new MastraError({\n id: 'INVALID_SYSTEM_MESSAGE_FORMAT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `Invalid system message format. System messages must include 'role' and 'content' properties. The content should be a string.`,\n details: {\n receivedMessage: JSON.stringify(message, null, 2),\n },\n });\n\n const coreMessage: CoreMessageV4 = { role: 'system', content: message.content.content };\n\n // Preserve message-level providerMetadata as experimental_providerMetadata (V4 field name)\n if (message.content.providerMetadata) {\n coreMessage.experimental_providerMetadata = message.content.providerMetadata;\n }\n\n return coreMessage;\n }\n\n /**\n * Convert AI SDK V4 UIMessage to MastraDBMessage\n */\n static fromUIMessage(\n message: UIMessageV4 | UIMessageWithMetadata,\n ctx: AIV4AdapterContext,\n messageSource: MessageSource,\n ): MastraDBMessage {\n // Filter out empty text parts to prevent Anthropic API errors\n const filteredParts = message.parts ? filterEmptyTextParts(message.parts) : [];\n\n const content: MastraMessageContentV2 = {\n format: 2,\n parts: filteredParts,\n };\n\n if (message.toolInvocations) content.toolInvocations = message.toolInvocations;\n if (message.reasoning) content.reasoning = message.reasoning;\n if (message.annotations) content.annotations = message.annotations;\n if (message.experimental_attachments) {\n content.experimental_attachments = message.experimental_attachments;\n }\n // Preserve metadata field if present\n if ('metadata' in message && message.metadata !== null && message.metadata !== undefined) {\n content.metadata = message.metadata as Record<string, unknown>;\n }\n\n return {\n id: message.id || ctx.newMessageId(),\n role: TypeDetector.getRole(message),\n createdAt: ctx.generateCreatedAt(messageSource, message.createdAt),\n threadId: ctx.memoryInfo?.threadId,\n resourceId: ctx.memoryInfo?.resourceId,\n content,\n } satisfies MastraDBMessage;\n }\n\n /**\n * Convert AI SDK V4 CoreMessage to MastraDBMessage\n */\n static fromCoreMessage(\n coreMessage: CoreMessageV4,\n ctx: AIV4AdapterContext,\n messageSource: MessageSource,\n ): MastraDBMessage {\n const id = `id` in coreMessage ? (coreMessage.id as string) : ctx.newMessageId();\n const parts: UIMessageV4['parts'] = [];\n const experimentalAttachments: UIMessageV4['experimental_attachments'] = [];\n const toolInvocations: ToolInvocationV4[] = [];\n\n const isSingleTextContent =\n messageSource === `response` &&\n Array.isArray(coreMessage.content) &&\n coreMessage.content.length === 1 &&\n coreMessage.content[0] &&\n coreMessage.content[0].type === `text` &&\n `text` in coreMessage.content[0] &&\n coreMessage.content[0].text;\n\n if (isSingleTextContent && messageSource === `response`) {\n coreMessage.content = isSingleTextContent;\n }\n\n if (typeof coreMessage.content === 'string') {\n parts.push({\n type: 'text',\n text: coreMessage.content,\n });\n } else if (Array.isArray(coreMessage.content)) {\n for (const aiV4Part of coreMessage.content) {\n switch (aiV4Part.type) {\n case 'text': {\n // Add step-start only after tool invocations, not at the beginning\n const prevPart = parts.at(-1);\n if (coreMessage.role === 'assistant' && prevPart && prevPart.type === 'tool-invocation') {\n parts.push({ type: 'step-start' });\n }\n\n const part: UIMessageV4Part = {\n type: 'text' as const,\n text: aiV4Part.text,\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n parts.push(part);\n break;\n }\n\n case 'tool-call': {\n const part: UIMessageV4Part = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n state: 'call',\n toolCallId: aiV4Part.toolCallId,\n toolName: aiV4Part.toolName,\n args: aiV4Part.args,\n },\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n parts.push(part);\n break;\n }\n\n case 'tool-result':\n {\n // Try to find args from the corresponding tool-call in previous messages\n let toolArgs: Record<string, unknown> = {};\n\n // First, check if there's a tool-call in the same message\n const toolCallInSameMsg = coreMessage.content.find(\n p => p.type === 'tool-call' && p.toolCallId === aiV4Part.toolCallId,\n );\n if (toolCallInSameMsg && toolCallInSameMsg.type === 'tool-call') {\n toolArgs = toolCallInSameMsg.args as Record<string, unknown>;\n }\n\n // If not found, look in previous messages for the corresponding tool-call\n if (Object.keys(toolArgs).length === 0 && ctx.dbMessages) {\n toolArgs = findToolCallArgs(ctx.dbMessages, aiV4Part.toolCallId);\n }\n\n // Only use part-level providerOptions if present\n const invocation: ToolInvocationV4 = {\n state: 'result' as const,\n toolCallId: aiV4Part.toolCallId,\n toolName: aiV4Part.toolName,\n result: aiV4Part.result ?? '',\n args: toolArgs,\n };\n\n const part: UIMessageV4Part = {\n type: 'tool-invocation',\n toolInvocation: invocation,\n };\n\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n\n parts.push(part);\n toolInvocations.push(invocation);\n }\n break;\n\n case 'reasoning':\n {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'reasoning',\n reasoning: aiV4Part.text,\n details: [{ type: 'text', text: aiV4Part.text, signature: aiV4Part.signature }],\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n parts.push(part);\n }\n break;\n case 'redacted-reasoning':\n {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'reasoning',\n reasoning: '',\n details: [{ type: 'redacted', data: aiV4Part.data }],\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n parts.push(part);\n }\n break;\n case 'image': {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'file' as const,\n data: imageContentToString(aiV4Part.image),\n mimeType: aiV4Part.mimeType!,\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n parts.push(part);\n break;\n }\n case 'file': {\n if (aiV4Part.data instanceof URL) {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'file' as const,\n data: aiV4Part.data.toString(),\n mimeType: aiV4Part.mimeType,\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n if (aiV4Part.filename) {\n (part as Record<string, unknown>).filename = aiV4Part.filename;\n }\n parts.push(part);\n } else if (typeof aiV4Part.data === 'string') {\n const categorized = categorizeFileData(aiV4Part.data, aiV4Part.mimeType);\n\n if (\n categorized.type === 'url' ||\n categorized.type === 'dataUri' ||\n // Provider file IDs (e.g. OpenAI \"file-...\") must be stored untouched,\n // not base64-converted, so they can be forwarded as { file_id } later.\n categorized.type === 'providerFileId'\n ) {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'file' as const,\n data: aiV4Part.data,\n mimeType: categorized.mimeType || 'image/png',\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n if (aiV4Part.filename) {\n (part as Record<string, unknown>).filename = aiV4Part.filename;\n }\n parts.push(part);\n } else {\n try {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'file' as const,\n mimeType: categorized.mimeType || 'image/png',\n data: convertDataContentToBase64String(aiV4Part.data),\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n if (aiV4Part.filename) {\n (part as Record<string, unknown>).filename = aiV4Part.filename;\n }\n parts.push(part);\n } catch (error) {\n console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${error}`, error);\n }\n }\n } else {\n try {\n const part: MastraDBMessage['content']['parts'][number] = {\n type: 'file' as const,\n mimeType: aiV4Part.mimeType,\n data: convertDataContentToBase64String(aiV4Part.data),\n };\n if (aiV4Part.providerOptions) {\n part.providerMetadata = aiV4Part.providerOptions;\n }\n if (aiV4Part.filename) {\n (part as Record<string, unknown>).filename = aiV4Part.filename;\n }\n parts.push(part);\n } catch (error) {\n console.error(`Failed to convert binary data to base64 in CoreMessage file part: ${error}`, error);\n }\n }\n break;\n }\n }\n }\n }\n\n // Filter out empty text parts to prevent Anthropic API errors\n const filteredParts = filterEmptyTextParts(parts);\n\n const content: MastraDBMessage['content'] = {\n format: 2,\n parts: filteredParts,\n };\n\n if (toolInvocations.length) content.toolInvocations = toolInvocations;\n if (typeof coreMessage.content === `string`) content.content = coreMessage.content;\n\n if (experimentalAttachments.length) content.experimental_attachments = experimentalAttachments;\n\n // V4 uses experimental_providerMetadata, V5 uses providerOptions\n if (coreMessage.providerOptions) {\n content.providerMetadata = coreMessage.providerOptions;\n } else if ('experimental_providerMetadata' in coreMessage && coreMessage.experimental_providerMetadata) {\n content.providerMetadata = coreMessage.experimental_providerMetadata;\n }\n\n if ('metadata' in coreMessage && coreMessage.metadata !== null && coreMessage.metadata !== undefined) {\n content.metadata = coreMessage.metadata as Record<string, unknown>;\n }\n\n const rawCreatedAt =\n 'metadata' in coreMessage &&\n coreMessage.metadata &&\n typeof coreMessage.metadata === 'object' &&\n 'createdAt' in coreMessage.metadata\n ? coreMessage.metadata.createdAt\n : undefined;\n\n return {\n id,\n role: TypeDetector.getRole(coreMessage),\n createdAt: ctx.generateCreatedAt(messageSource, rawCreatedAt),\n threadId: ctx.memoryInfo?.threadId,\n resourceId: ctx.memoryInfo?.resourceId,\n content,\n } satisfies MastraDBMessage;\n }\n}\n","import { i as gateway, n as GatewayError, r as createGatewayProvider, t as GatewayAuthenticationError } from \"./dist-ByO0vuJJ.js\";\nimport { $ as JSONParseError, A as jsonSchema, B as safeValidateTypes, D as isNonNullable, E as isArrayBuffer, H as tool, I as readResponseWithSizeLimit, J as APICallError, K as zodSchema, L as resolve, N as normalizeHeaders, O as isUint8Array, P as parseJsonEventStream, Q as InvalidResponseDataError, R as retryWithExponentialBackoff, S as getErrorMessage$1, T as isAbortError, U as validateTypes, W as withUserAgentSuffix, X as InvalidArgumentError$1, Y as EmptyResponseBodyError, Z as InvalidPromptError, _ as delay, a as EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER, at as TypeValidationError, b as fetchWithValidatedRedirects, ct as isJSONArray, d as convertUint8ArrayToBase64, et as LoadAPIKeyError, i as EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL, it as TooManyEmbeddingValuesForCallError, j as lazySchema, k as isUrlSupported, lt as isJSONObject, n as DelayedPromise, nt as NoContentGeneratedError, o as asSchema, ot as UnsupportedFunctionalityError, p as createIdGenerator, q as AISDKError, r as DownloadError, rt as NoSuchModelError, s as cancelResponseBody, st as getErrorMessage, t as DEFAULT_MAX_DOWNLOAD_SIZE, tt as LoadSettingError, u as convertBase64ToUint8Array, v as dynamicTool, w as getRuntimeEnvironmentUserAgent, x as generateId, y as executeTool, z as safeParseJSON } from \"./dist-BoOIE3nE.js\";\nimport { z } from \"zod/v4\";\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/version.mjs\nconst VERSION$1 = \"1.10.0\";\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/internal/semver.mjs\nconst re = /^(\\d+)\\.(\\d+)\\.(\\d+)(-(.+))?$/;\n/**\n* Create a function to test an API version to see if it is compatible with the provided ownVersion.\n*\n* The returned function has the following semantics:\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param ownVersion version which should be checked against\n*/\nfunction _makeCompatibilityCheck(ownVersion) {\n\tconst acceptedVersions = /* @__PURE__ */ new Set([ownVersion]);\n\tconst rejectedVersions = /* @__PURE__ */ new Set();\n\tconst myVersionMatch = ownVersion.match(re);\n\tif (!myVersionMatch) return () => false;\n\tconst ownVersionParsed = {\n\t\tmajor: +myVersionMatch[1],\n\t\tminor: +myVersionMatch[2],\n\t\tpatch: +myVersionMatch[3],\n\t\tprerelease: myVersionMatch[4]\n\t};\n\tif (ownVersionParsed.prerelease != null) return function isExactmatch(globalVersion) {\n\t\treturn globalVersion === ownVersion;\n\t};\n\tfunction _reject(v) {\n\t\trejectedVersions.add(v);\n\t\treturn false;\n\t}\n\tfunction _accept(v) {\n\t\tacceptedVersions.add(v);\n\t\treturn true;\n\t}\n\treturn function isCompatible(globalVersion) {\n\t\tif (acceptedVersions.has(globalVersion)) return true;\n\t\tif (rejectedVersions.has(globalVersion)) return false;\n\t\tconst globalVersionMatch = globalVersion.match(re);\n\t\tif (!globalVersionMatch) return _reject(globalVersion);\n\t\tconst globalVersionParsed = {\n\t\t\tmajor: +globalVersionMatch[1],\n\t\t\tminor: +globalVersionMatch[2],\n\t\t\tpatch: +globalVersionMatch[3],\n\t\t\tprerelease: globalVersionMatch[4]\n\t\t};\n\t\tif (globalVersionParsed.prerelease != null) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major !== globalVersionParsed.major) return _reject(globalVersion);\n\t\tif (ownVersionParsed.major === 0) {\n\t\t\tif (ownVersionParsed.minor === globalVersionParsed.minor && ownVersionParsed.patch <= globalVersionParsed.patch) return _accept(globalVersion);\n\t\t\treturn _reject(globalVersion);\n\t\t}\n\t\tif (ownVersionParsed.minor <= globalVersionParsed.minor) return _accept(globalVersion);\n\t\treturn _reject(globalVersion);\n\t};\n}\n/**\n* Test an API version to see if it is compatible with this API.\n*\n* - Exact match is always compatible\n* - Major versions must match exactly\n* - 1.x package cannot use global 2.x package\n* - 2.x package cannot use global 1.x package\n* - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API\n* - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects\n* - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3\n* - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor\n* - Patch and build tag differences are not considered at this time\n*\n* @param version version of the API requesting an instance of the global API\n*/\nconst isCompatible = _makeCompatibilityCheck(VERSION$1);\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/internal/global-utils.mjs\nconst major = VERSION$1.split(\".\")[0];\nconst GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);\nconst _global = typeof globalThis === \"object\" ? globalThis : typeof self === \"object\" ? self : typeof window === \"object\" ? window : typeof global === \"object\" ? global : {};\nfunction _makeGlobalApi() {\n\treturn Object.defineProperty({}, \"version\", {\n\t\tvalue: VERSION$1,\n\t\tenumerable: true,\n\t\twritable: false,\n\t\tconfigurable: false\n\t});\n}\nfunction registerGlobal(type, instance, diag, allowOverride = false) {\n\tvar _global$GLOBAL_OPENTE;\n\tconst api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_global$GLOBAL_OPENTE = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _global$GLOBAL_OPENTE !== void 0 ? _global$GLOBAL_OPENTE : _makeGlobalApi();\n\tif (!allowOverride && api[type]) {\n\t\tconst err = /* @__PURE__ */ new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tif (api.version !== \"1.10.0\") {\n\t\tconst err = /* @__PURE__ */ new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION$1}`);\n\t\tdiag.error(err.stack || err.message);\n\t\treturn false;\n\t}\n\tapi[type] = instance;\n\tdiag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION$1}.`);\n\treturn true;\n}\nlet _compatibleGlobalApi;\nfunction getGlobal(type) {\n\tconst api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\tif (api == null) return;\n\tif (api !== _compatibleGlobalApi) {\n\t\tif (!api.version || !isCompatible(api.version)) return;\n\t\t_compatibleGlobalApi = api;\n\t}\n\treturn api[type];\n}\nfunction unregisterGlobal(type, diag) {\n\tdiag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION$1}.`);\n\tconst api = _global[GLOBAL_OPENTELEMETRY_API_KEY];\n\tif (api) delete api[type];\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/diag/ComponentLogger.mjs\n/**\n* Component Logger which is meant to be used as part of any component which\n* will add automatically additional namespace in front of the log message.\n* It will then forward all message to global diag logger\n* @example\n* const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' });\n* cLogger.debug('test');\n* // @opentelemetry/instrumentation-http test\n*/\nvar DiagComponentLogger = class {\n\tconstructor(props) {\n\t\tthis._namespace = props.namespace || \"DiagComponentLogger\";\n\t}\n\tdebug(...args) {\n\t\treturn logProxy(\"debug\", this._namespace, args);\n\t}\n\terror(...args) {\n\t\treturn logProxy(\"error\", this._namespace, args);\n\t}\n\tinfo(...args) {\n\t\treturn logProxy(\"info\", this._namespace, args);\n\t}\n\twarn(...args) {\n\t\treturn logProxy(\"warn\", this._namespace, args);\n\t}\n\tverbose(...args) {\n\t\treturn logProxy(\"verbose\", this._namespace, args);\n\t}\n};\nfunction logProxy(funcName, namespace, args) {\n\tconst logger = getGlobal(\"diag\");\n\tif (!logger) return;\n\treturn logger[funcName](namespace, ...args);\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/diag/internal/logLevelLogger.mjs\nfunction createLogLevelDiagLogger(maxLevel, logger) {\n\tif (maxLevel < 0) maxLevel = 0;\n\telse if (maxLevel > 9999) maxLevel = 9999;\n\tlogger = logger || {};\n\tfunction _filterFunc(funcName, theLevel) {\n\t\tconst theFunc = logger[funcName];\n\t\tif (typeof theFunc === \"function\" && maxLevel >= theLevel) return theFunc.bind(logger);\n\t\treturn function() {};\n\t}\n\treturn {\n\t\terror: _filterFunc(\"error\", 30),\n\t\twarn: _filterFunc(\"warn\", 50),\n\t\tinfo: _filterFunc(\"info\", 60),\n\t\tdebug: _filterFunc(\"debug\", 70),\n\t\tverbose: _filterFunc(\"verbose\", 80)\n\t};\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/api/diag.mjs\nconst API_NAME$2 = \"diag\";\n/**\n* Singleton object which represents the entry point to the OpenTelemetry internal\n* diagnostic API\n*\n* @since 1.0.0\n*/\nvar DiagAPI = class DiagAPI {\n\t/** Get the singleton instance of the DiagAPI API */\n\tstatic instance() {\n\t\tif (!this._instance) this._instance = new DiagAPI();\n\t\treturn this._instance;\n\t}\n\t/**\n\t* Private internal constructor\n\t* @private\n\t*/\n\tconstructor() {\n\t\tfunction _logProxy(funcName) {\n\t\t\treturn function(...args) {\n\t\t\t\tconst logger = getGlobal(\"diag\");\n\t\t\t\tif (!logger) return;\n\t\t\t\treturn logger[funcName](...args);\n\t\t\t};\n\t\t}\n\t\tconst self = this;\n\t\tconst setLogger = (logger, optionsOrLogLevel = { logLevel: 60 }) => {\n\t\t\tvar _optionsOrLogLevel$lo;\n\t\t\tif (logger === self) {\n\t\t\t\tvar _err$stack;\n\t\t\t\tconst err = /* @__PURE__ */ new Error(\"Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation\");\n\t\t\t\tself.error((_err$stack = err.stack) !== null && _err$stack !== void 0 ? _err$stack : err.message);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (typeof optionsOrLogLevel === \"number\") optionsOrLogLevel = { logLevel: optionsOrLogLevel };\n\t\t\tconst oldLogger = getGlobal(\"diag\");\n\t\t\tconst newLogger = createLogLevelDiagLogger((_optionsOrLogLevel$lo = optionsOrLogLevel.logLevel) !== null && _optionsOrLogLevel$lo !== void 0 ? _optionsOrLogLevel$lo : 60, logger);\n\t\t\tif (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n\t\t\t\tvar _Error$stack;\n\t\t\t\tconst stack = (_Error$stack = (/* @__PURE__ */ new Error()).stack) !== null && _Error$stack !== void 0 ? _Error$stack : \"<failed to generate stacktrace>\";\n\t\t\t\toldLogger.warn(`Current logger will be overwritten from ${stack}`);\n\t\t\t\tnewLogger.warn(`Current logger will overwrite one already registered from ${stack}`);\n\t\t\t}\n\t\t\treturn registerGlobal(\"diag\", newLogger, self, true);\n\t\t};\n\t\tself.setLogger = setLogger;\n\t\tself.disable = () => {\n\t\t\tunregisterGlobal(API_NAME$2, self);\n\t\t};\n\t\tself.createComponentLogger = (options) => {\n\t\t\treturn new DiagComponentLogger(options);\n\t\t};\n\t\tself.verbose = _logProxy(\"verbose\");\n\t\tself.debug = _logProxy(\"debug\");\n\t\tself.info = _logProxy(\"info\");\n\t\tself.warn = _logProxy(\"warn\");\n\t\tself.error = _logProxy(\"error\");\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/context/context.mjs\n/**\n* Get a key to uniquely identify a context value\n*\n* @since 1.0.0\n*/\nfunction createContextKey(description) {\n\treturn Symbol.for(description);\n}\n/**\n* The root context is used as the default parent context when there is no active context\n*\n* @since 1.0.0\n*/\nconst ROOT_CONTEXT = new class BaseContext {\n\t/**\n\t* Construct a new context which inherits values from an optional parent context.\n\t*\n\t* @param parentContext a context from which to inherit values\n\t*/\n\tconstructor(parentContext) {\n\t\tconst self = this;\n\t\tself._currentContext = parentContext ? new Map(parentContext) : /* @__PURE__ */ new Map();\n\t\tself.getValue = (key) => self._currentContext.get(key);\n\t\tself.setValue = (key, value) => {\n\t\t\tconst context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.set(key, value);\n\t\t\treturn context;\n\t\t};\n\t\tself.deleteValue = (key) => {\n\t\t\tconst context = new BaseContext(self._currentContext);\n\t\t\tcontext._currentContext.delete(key);\n\t\t\treturn context;\n\t\t};\n\t}\n}();\n/**\n* @since 1.0.0\n*/\nconst INVALID_SPAN_CONTEXT = {\n\ttraceId: \"00000000000000000000000000000000\",\n\tspanId: \"0000000000000000\",\n\ttraceFlags: 0\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/NonRecordingSpan.mjs\n/**\n* The NonRecordingSpan is the default {@link Span} that is used when no Span\n* implementation is available. All operations are no-op including context\n* propagation.\n*/\nvar NonRecordingSpan = class {\n\tconstructor(spanContext = INVALID_SPAN_CONTEXT) {\n\t\tthis._spanContext = spanContext;\n\t}\n\tspanContext() {\n\t\treturn this._spanContext;\n\t}\n\tsetAttribute(_key, _value) {\n\t\treturn this;\n\t}\n\tsetAttributes(_attributes) {\n\t\treturn this;\n\t}\n\taddEvent(_name, _attributes) {\n\t\treturn this;\n\t}\n\taddLink(_link) {\n\t\treturn this;\n\t}\n\taddLinks(_links) {\n\t\treturn this;\n\t}\n\tsetStatus(_status) {\n\t\treturn this;\n\t}\n\tupdateName(_name) {\n\t\treturn this;\n\t}\n\tend(_endTime) {}\n\tisRecording() {\n\t\treturn false;\n\t}\n\trecordException(_exception, _time) {}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/spancontext-utils.mjs\nconst isHex = new Uint8Array([\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t0,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1,\n\t1\n]);\nfunction isValidHex(id, length) {\n\tif (typeof id !== \"string\" || id.length !== length) return false;\n\tlet r = 0;\n\tfor (let i = 0; i < id.length; i += 4) r += (isHex[id.charCodeAt(i)] | 0) + (isHex[id.charCodeAt(i + 1)] | 0) + (isHex[id.charCodeAt(i + 2)] | 0) + (isHex[id.charCodeAt(i + 3)] | 0);\n\treturn r === length;\n}\n/**\n* @since 1.0.0\n*/\nfunction isValidTraceId(traceId) {\n\treturn isValidHex(traceId, 32) && traceId !== \"00000000000000000000000000000000\";\n}\n/**\n* @since 1.0.0\n*/\nfunction isValidSpanId(spanId) {\n\treturn isValidHex(spanId, 16) && spanId !== \"0000000000000000\";\n}\n/**\n* Returns true if this {@link SpanContext} is valid.\n* @return true if this {@link SpanContext} is valid.\n*\n* @since 1.0.0\n*/\nfunction isSpanContextValid(spanContext) {\n\treturn isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId);\n}\n/**\n* Wrap the given {@link SpanContext} in a new non-recording {@link Span}\n*\n* @param spanContext span context to be wrapped\n* @returns a new non-recording {@link Span} with the provided context\n*/\nfunction wrapSpanContext(spanContext) {\n\treturn new NonRecordingSpan(spanContext);\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/context/NoopContextManager.mjs\nvar NoopContextManager = class {\n\tactive() {\n\t\treturn ROOT_CONTEXT;\n\t}\n\twith(_context, fn, thisArg, ...args) {\n\t\treturn fn.call(thisArg, ...args);\n\t}\n\tbind(_context, target) {\n\t\treturn target;\n\t}\n\tenable() {\n\t\treturn this;\n\t}\n\tdisable() {\n\t\treturn this;\n\t}\n\t/** @experimental This API is experimental and may change in minor releases without prior notice. */\n\tattach(_context) {\n\t\treturn { dispose() {} };\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/api/context.mjs\nconst API_NAME$1 = \"context\";\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\nconst NOOP_TOKEN = Object.freeze({ dispose: () => {} });\n/**\n* Singleton object which represents the entry point to the OpenTelemetry Context API\n*\n* @since 1.0.0\n*/\nvar ContextAPI = class ContextAPI {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tconstructor() {\n\t\tthis._attachUnsupportedWarned = false;\n\t}\n\t/** Get the singleton instance of the Context API */\n\tstatic getInstance() {\n\t\tif (!this._instance) this._instance = new ContextAPI();\n\t\treturn this._instance;\n\t}\n\t/**\n\t* Set the current context manager.\n\t*\n\t* @returns true if the context manager was successfully registered, else false\n\t*/\n\tsetGlobalContextManager(contextManager) {\n\t\treturn registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());\n\t}\n\t/**\n\t* Get the currently active context\n\t*/\n\tactive() {\n\t\treturn this._getContextManager().active();\n\t}\n\t/**\n\t* Execute a function with an active context\n\t*\n\t* @param context context to be active during function execution\n\t* @param fn function to execute in a context\n\t* @param thisArg optional receiver to be used for calling fn\n\t* @param args optional arguments forwarded to fn\n\t*/\n\twith(context, fn, thisArg, ...args) {\n\t\treturn this._getContextManager().with(context, fn, thisArg, ...args);\n\t}\n\t/**\n\t* Bind a context to a target function or event emitter\n\t*\n\t* @param context context to bind to the event emitter or function. Defaults to the currently active context\n\t* @param target function or event emitter to bind\n\t*/\n\tbind(context, target) {\n\t\treturn this._getContextManager().bind(context, target);\n\t}\n\t/**\n\t* Imperatively sets `context` as active, returning a {@link ContextManagementToken} whose\n\t* {@link ContextManagementToken.dispose} restores the previous context.\n\t*\n\t* This is a delicate, low-level API - prefer {@link with}/{@link bind}, which\n\t* restore context automatically. Use `attach` only to bridge callback\n\t* boundaries that `with` cannot wrap. Call `token.dispose()` when the\n\t* operation is done.\n\t*\n\t* **Caveat for async functions:** If called inside an async function before\n\t* the first `await`, the context change may leak into the caller's context\n\t* and remain active there. Prefer {@link with} for async code.\n\t*\n\t* Support is best-effort and varies by the active ContextManager (see\n\t* {@link ContextManager.attach}); if it does not implement `attach`, this logs\n\t* a warning and returns a no-op token.\n\t*\n\t* @param context The Context to attach\n\t* @returns A {@link ContextManagementToken} whose dispose() restores the previous Context\n\t* @since 1.10.0\n\t* @experimental This API is experimental and may change in minor releases without prior notice.\n\t*/\n\tattach(context) {\n\t\tconst contextManager = this._getContextManager();\n\t\tif (contextManager.attach) return contextManager.attach(context);\n\t\tif (!this._attachUnsupportedWarned) {\n\t\t\tthis._attachUnsupportedWarned = true;\n\t\t\tDiagAPI.instance().warn(\"The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.\");\n\t\t}\n\t\treturn NOOP_TOKEN;\n\t}\n\t_getContextManager() {\n\t\treturn getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;\n\t}\n\t/** Disable and remove the global context manager */\n\tdisable() {\n\t\tthis._getContextManager().disable();\n\t\tunregisterGlobal(API_NAME$1, DiagAPI.instance());\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/context-utils.mjs\n/**\n* span key\n*/\nconst SPAN_KEY = createContextKey(\"OpenTelemetry Context Key SPAN\");\n/**\n* Return the span if one exists\n*\n* @param context context to get span from\n*/\nfunction getSpan(context) {\n\treturn context.getValue(SPAN_KEY) || void 0;\n}\n/**\n* Gets the span from the current context, if one exists.\n*/\nfunction getActiveSpan() {\n\treturn getSpan(ContextAPI.getInstance().active());\n}\n/**\n* Set the span on a context\n*\n* @param context context to use as parent\n* @param span span to set active\n*/\nfunction setSpan(context, span) {\n\treturn context.setValue(SPAN_KEY, span);\n}\n/**\n* Remove current span stored in the context\n*\n* @param context context to delete span from\n*/\nfunction deleteSpan(context) {\n\treturn context.deleteValue(SPAN_KEY);\n}\n/**\n* Wrap span context in a NoopSpan and set as span in a new\n* context\n*\n* @param context context to set active span on\n* @param spanContext span context to be wrapped\n*/\nfunction setSpanContext(context, spanContext) {\n\treturn setSpan(context, new NonRecordingSpan(spanContext));\n}\n/**\n* Get the span context of the span if it exists.\n*\n* @param context context to get values from\n*/\nfunction getSpanContext(context) {\n\tvar _getSpan;\n\treturn (_getSpan = getSpan(context)) === null || _getSpan === void 0 ? void 0 : _getSpan.spanContext();\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/NoopTracer.mjs\nconst contextApi = ContextAPI.getInstance();\n/**\n* No-op implementations of {@link Tracer}.\n*/\nvar NoopTracer = class {\n\tstartSpan(name, options, context = contextApi.active()) {\n\t\tif (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();\n\t\tconst parentFromContext = context && getSpanContext(context);\n\t\tif (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);\n\t\telse return new NonRecordingSpan();\n\t}\n\tstartActiveSpan(name, arg2, arg3, arg4) {\n\t\tvar _ctx;\n\t\tlet opts;\n\t\tlet ctx;\n\t\tlet fn;\n\t\tif (arguments.length < 2) return;\n\t\telse if (arguments.length === 2) fn = arg2;\n\t\telse if (arguments.length === 3) {\n\t\t\topts = arg2;\n\t\t\tfn = arg3;\n\t\t} else {\n\t\t\topts = arg2;\n\t\t\tctx = arg3;\n\t\t\tfn = arg4;\n\t\t}\n\t\tconst parentContext = (_ctx = ctx) !== null && _ctx !== void 0 ? _ctx : contextApi.active();\n\t\tconst span = this.startSpan(name, opts, parentContext);\n\t\tconst contextWithSpanSet = setSpan(parentContext, span);\n\t\treturn contextApi.with(contextWithSpanSet, fn, void 0, span);\n\t}\n};\nfunction isSpanContext(spanContext) {\n\treturn spanContext !== null && typeof spanContext === \"object\" && \"spanId\" in spanContext && typeof spanContext[\"spanId\"] === \"string\" && \"traceId\" in spanContext && typeof spanContext[\"traceId\"] === \"string\" && \"traceFlags\" in spanContext && typeof spanContext[\"traceFlags\"] === \"number\";\n}\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/ProxyTracer.mjs\nconst NOOP_TRACER = new NoopTracer();\n/**\n* Proxy tracer provided by the proxy tracer provider\n*\n* @since 1.0.0\n*/\nvar ProxyTracer = class {\n\tconstructor(provider, name, version, options) {\n\t\tthis._provider = provider;\n\t\tthis.name = name;\n\t\tthis.version = version;\n\t\tthis.options = options;\n\t}\n\tstartSpan(name, options, context) {\n\t\treturn this._getTracer().startSpan(name, options, context);\n\t}\n\tstartActiveSpan(_name, _options, _context, _fn) {\n\t\tconst tracer = this._getTracer();\n\t\treturn Reflect.apply(tracer.startActiveSpan, tracer, arguments);\n\t}\n\t/**\n\t* Try to get a tracer from the proxy tracer provider.\n\t* If the proxy tracer provider has no delegate, return a noop tracer.\n\t*/\n\t_getTracer() {\n\t\tif (this._delegate) return this._delegate;\n\t\tconst tracer = this._provider.getDelegateTracer(this.name, this.version, this.options);\n\t\tif (!tracer) return NOOP_TRACER;\n\t\tthis._delegate = tracer;\n\t\treturn this._delegate;\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/status.mjs\n/**\n* An enumeration of status codes.\n*\n* @since 1.0.0\n*/\nlet SpanStatusCode = /* @__PURE__ */ function(SpanStatusCode) {\n\t/**\n\t* The default status.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"UNSET\"] = 0] = \"UNSET\";\n\t/**\n\t* The operation has been validated by an Application developer or\n\t* Operator to have completed successfully.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"OK\"] = 1] = \"OK\";\n\t/**\n\t* The operation contains an error.\n\t*/\n\tSpanStatusCode[SpanStatusCode[\"ERROR\"] = 2] = \"ERROR\";\n\treturn SpanStatusCode;\n}({});\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/NoopTracerProvider.mjs\n/**\n* An implementation of the {@link TracerProvider} which returns an impotent\n* Tracer for all calls to `getTracer`.\n*\n* All operations are no-op.\n*/\nvar NoopTracerProvider = class {\n\tgetTracer(_name, _version, _options) {\n\t\treturn new NoopTracer();\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace/ProxyTracerProvider.mjs\nconst NOOP_TRACER_PROVIDER = new NoopTracerProvider();\n/**\n* Tracer provider which provides {@link ProxyTracer}s.\n*\n* Before a delegate is set, tracers provided are NoOp.\n* When a delegate is set, traces are provided from the delegate.\n* When a delegate is set after tracers have already been provided,\n* all tracers already provided will use the provided delegate implementation.\n*\n* @deprecated This will be removed in the next major version.\n* @since 1.0.0\n*/\nvar ProxyTracerProvider = class {\n\t/**\n\t* Get a {@link ProxyTracer}\n\t*/\n\tgetTracer(name, version, options) {\n\t\tvar _this$getDelegateTrac;\n\t\treturn (_this$getDelegateTrac = this.getDelegateTracer(name, version, options)) !== null && _this$getDelegateTrac !== void 0 ? _this$getDelegateTrac : new ProxyTracer(this, name, version, options);\n\t}\n\tgetDelegate() {\n\t\tvar _this$_delegate;\n\t\treturn (_this$_delegate = this._delegate) !== null && _this$_delegate !== void 0 ? _this$_delegate : NOOP_TRACER_PROVIDER;\n\t}\n\t/**\n\t* Set the delegate tracer provider\n\t*/\n\tsetDelegate(delegate) {\n\t\tthis._delegate = delegate;\n\t}\n\tgetDelegateTracer(name, version, options) {\n\t\tvar _this$_delegate2;\n\t\treturn (_this$_delegate2 = this._delegate) === null || _this$_delegate2 === void 0 ? void 0 : _this$_delegate2.getTracer(name, version, options);\n\t}\n};\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/context-api.mjs\n/**\n* Entrypoint for context API\n* @since 1.0.0\n*/\nconst context = ContextAPI.getInstance();\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/api/trace.mjs\nconst API_NAME = \"trace\";\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.10.0/b8f3d057da5766efb2c51bd5d3719f0102eaf2997483bbab03a3ddcb7fd5379c/node_modules/@opentelemetry/api/dist/trace-api.mjs\n/**\n* Entrypoint for trace API\n*\n* @since 1.0.0\n*/\nconst trace = class TraceAPI {\n\t/** Empty private constructor prevents end users from constructing a new instance of the API */\n\tconstructor() {\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t\tthis.wrapSpanContext = wrapSpanContext;\n\t\tthis.isSpanContextValid = isSpanContextValid;\n\t\tthis.deleteSpan = deleteSpan;\n\t\tthis.getSpan = getSpan;\n\t\tthis.getActiveSpan = getActiveSpan;\n\t\tthis.getSpanContext = getSpanContext;\n\t\tthis.setSpan = setSpan;\n\t\tthis.setSpanContext = setSpanContext;\n\t}\n\t/** Get the singleton instance of the Trace API */\n\tstatic getInstance() {\n\t\tif (!this._instance) this._instance = new TraceAPI();\n\t\treturn this._instance;\n\t}\n\t/**\n\t* Set the current global tracer.\n\t*\n\t* @returns true if the tracer provider was successfully registered, else false\n\t*/\n\tsetGlobalTracerProvider(provider) {\n\t\tconst success = registerGlobal(API_NAME, this._proxyTracerProvider, DiagAPI.instance());\n\t\tif (success) this._proxyTracerProvider.setDelegate(provider);\n\t\treturn success;\n\t}\n\t/**\n\t* Returns the global tracer provider.\n\t*/\n\tgetTracerProvider() {\n\t\treturn getGlobal(API_NAME) || this._proxyTracerProvider;\n\t}\n\t/**\n\t* Returns a tracer from the global tracer provider.\n\t*/\n\tgetTracer(name, version) {\n\t\treturn this.getTracerProvider().getTracer(name, version);\n\t}\n\t/** Remove the global tracer provider */\n\tdisable() {\n\t\tunregisterGlobal(API_NAME, DiagAPI.instance());\n\t\tthis._proxyTracerProvider = new ProxyTracerProvider();\n\t}\n}.getInstance();\n// ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ai/6.0.322/c67f618b8d2280d9ecf686650c14a27c30c9a6a9c750b0a88a1d623a09d634cf/node_modules/ai/dist/index.mjs\nvar __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n\tfor (var name23 in all) __defProp(target, name23, {\n\t\tget: all[name23],\n\t\tenumerable: true\n\t});\n};\nvar name = \"AI_InvalidArgumentError\";\nvar marker = `vercel.ai.error.${name}`;\nvar symbol = Symbol.for(marker);\nvar _a;\nvar InvalidArgumentError = class extends AISDKError {\n\tconstructor({ parameter, value, message }) {\n\t\tsuper({\n\t\t\tname,\n\t\t\tmessage: `Invalid argument for parameter ${parameter}: ${message}`\n\t\t});\n\t\tthis[_a] = true;\n\t\tthis.parameter = parameter;\n\t\tthis.value = value;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker);\n\t}\n};\n_a = symbol;\nvar name2 = \"AI_InvalidStreamPartError\";\nvar marker2 = `vercel.ai.error.${name2}`;\nvar symbol2 = Symbol.for(marker2);\nvar _a2;\nvar InvalidStreamPartError = class extends AISDKError {\n\tconstructor({ chunk, message }) {\n\t\tsuper({\n\t\t\tname: name2,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a2] = true;\n\t\tthis.chunk = chunk;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker2);\n\t}\n};\n_a2 = symbol2;\nvar name3 = \"AI_InvalidToolApprovalError\";\nvar marker3 = `vercel.ai.error.${name3}`;\nvar symbol3 = Symbol.for(marker3);\nvar _a3;\nvar InvalidToolApprovalError = class extends AISDKError {\n\tconstructor({ approvalId }) {\n\t\tsuper({\n\t\t\tname: name3,\n\t\t\tmessage: `Tool approval response references unknown approvalId: \"${approvalId}\". No matching tool-approval-request found in message history.`\n\t\t});\n\t\tthis[_a3] = true;\n\t\tthis.approvalId = approvalId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker3);\n\t}\n};\n_a3 = symbol3;\nvar name4 = \"AI_InvalidToolApprovalSignatureError\";\nvar marker4 = `vercel.ai.error.${name4}`;\nvar symbol4 = Symbol.for(marker4);\nvar _a4;\nvar InvalidToolApprovalSignatureError = class extends AISDKError {\n\tconstructor({ approvalId, toolCallId, reason }) {\n\t\tsuper({\n\t\t\tname: name4,\n\t\t\tmessage: `Tool approval signature verification failed for approval \"${approvalId}\" (tool call \"${toolCallId}\"): ${reason}`\n\t\t});\n\t\tthis[_a4] = true;\n\t\tthis.approvalId = approvalId;\n\t\tthis.toolCallId = toolCallId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker4);\n\t}\n};\n_a4 = symbol4;\nvar name5 = \"AI_InvalidToolInputError\";\nvar marker5 = `vercel.ai.error.${name5}`;\nvar symbol5 = Symbol.for(marker5);\nvar _a5;\nvar InvalidToolInputError = class extends AISDKError {\n\tconstructor({ toolInput, toolName, cause, message = `Invalid input for tool ${toolName}: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name5,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a5] = true;\n\t\tthis.toolInput = toolInput;\n\t\tthis.toolName = toolName;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker5);\n\t}\n};\n_a5 = symbol5;\nvar name6 = \"AI_ToolCallNotFoundForApprovalError\";\nvar marker6 = `vercel.ai.error.${name6}`;\nvar symbol6 = Symbol.for(marker6);\nvar _a6;\nvar ToolCallNotFoundForApprovalError = class extends AISDKError {\n\tconstructor({ toolCallId, approvalId }) {\n\t\tsuper({\n\t\t\tname: name6,\n\t\t\tmessage: `Tool call \"${toolCallId}\" not found for approval request \"${approvalId}\".`\n\t\t});\n\t\tthis[_a6] = true;\n\t\tthis.toolCallId = toolCallId;\n\t\tthis.approvalId = approvalId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker6);\n\t}\n};\n_a6 = symbol6;\nvar name7 = \"AI_MissingToolResultsError\";\nvar marker7 = `vercel.ai.error.${name7}`;\nvar symbol7 = Symbol.for(marker7);\nvar _a7;\nvar MissingToolResultsError = class extends AISDKError {\n\tconstructor({ toolCallIds }) {\n\t\tsuper({\n\t\t\tname: name7,\n\t\t\tmessage: `Tool result${toolCallIds.length > 1 ? \"s are\" : \" is\"} missing for tool call${toolCallIds.length > 1 ? \"s\" : \"\"} ${toolCallIds.join(\", \")}.`\n\t\t});\n\t\tthis[_a7] = true;\n\t\tthis.toolCallIds = toolCallIds;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker7);\n\t}\n};\n_a7 = symbol7;\nvar name8 = \"AI_NoImageGeneratedError\";\nvar marker8 = `vercel.ai.error.${name8}`;\nvar symbol8 = Symbol.for(marker8);\nvar _a8;\nvar NoImageGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No image generated.\", cause, responses }) {\n\t\tsuper({\n\t\t\tname: name8,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a8] = true;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker8);\n\t}\n};\n_a8 = symbol8;\nvar name9 = \"AI_NoObjectGeneratedError\";\nvar marker9 = `vercel.ai.error.${name9}`;\nvar symbol9 = Symbol.for(marker9);\nvar _a9;\nvar NoObjectGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No object generated.\", cause, text: text2, response, usage, finishReason }) {\n\t\tsuper({\n\t\t\tname: name9,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a9] = true;\n\t\tthis.text = text2;\n\t\tthis.response = response;\n\t\tthis.usage = usage;\n\t\tthis.finishReason = finishReason;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker9);\n\t}\n};\n_a9 = symbol9;\nvar name10 = \"AI_NoOutputGeneratedError\";\nvar marker10 = `vercel.ai.error.${name10}`;\nvar symbol10 = Symbol.for(marker10);\nvar _a10;\nvar NoOutputGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No output generated.\", cause } = {}) {\n\t\tsuper({\n\t\t\tname: name10,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a10] = true;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker10);\n\t}\n};\n_a10 = symbol10;\nvar name11 = \"AI_NoSpeechGeneratedError\";\nvar marker11 = `vercel.ai.error.${name11}`;\nvar symbol11 = Symbol.for(marker11);\nvar _a11;\nvar NoSpeechGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name11,\n\t\t\tmessage: \"No speech audio generated.\"\n\t\t});\n\t\tthis[_a11] = true;\n\t\tthis.responses = options.responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker11);\n\t}\n};\n_a11 = symbol11;\nvar name12 = \"AI_NoTranscriptGeneratedError\";\nvar marker12 = `vercel.ai.error.${name12}`;\nvar symbol12 = Symbol.for(marker12);\nvar _a12;\nvar NoTranscriptGeneratedError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: name12,\n\t\t\tmessage: \"No transcript generated.\"\n\t\t});\n\t\tthis[_a12] = true;\n\t\tthis.responses = options.responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker12);\n\t}\n};\n_a12 = symbol12;\nvar name13 = \"AI_NoVideoGeneratedError\";\nvar marker13 = `vercel.ai.error.${name13}`;\nvar symbol13 = Symbol.for(marker13);\nvar _a13;\nvar NoVideoGeneratedError = class extends AISDKError {\n\tconstructor({ message = \"No video generated.\", cause, responses }) {\n\t\tsuper({\n\t\t\tname: name13,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a13] = true;\n\t\tthis.responses = responses;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker13);\n\t}\n\t/**\n\t* @deprecated use `isInstance` instead\n\t*/\n\tstatic isNoVideoGeneratedError(error) {\n\t\treturn error instanceof Error && error.name === name13 && typeof error.responses !== \"undefined\" ? true : false;\n\t}\n\t/**\n\t* @deprecated Do not use this method. It will be removed in the next major version.\n\t*/\n\ttoJSON() {\n\t\treturn {\n\t\t\tname: this.name,\n\t\t\tmessage: this.message,\n\t\t\tstack: this.stack,\n\t\t\tcause: this.cause,\n\t\t\tresponses: this.responses\n\t\t};\n\t}\n};\n_a13 = symbol13;\nvar name14 = \"AI_NoSuchToolError\";\nvar marker14 = `vercel.ai.error.${name14}`;\nvar symbol14 = Symbol.for(marker14);\nvar _a14;\nvar NoSuchToolError = class extends AISDKError {\n\tconstructor({ toolName, availableTools = void 0, message = `Model tried to call unavailable tool '${toolName}'. ${availableTools === void 0 ? \"No tools are available.\" : `Available tools: ${availableTools.join(\", \")}.`}` }) {\n\t\tsuper({\n\t\t\tname: name14,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a14] = true;\n\t\tthis.toolName = toolName;\n\t\tthis.availableTools = availableTools;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker14);\n\t}\n};\n_a14 = symbol14;\nvar name15 = \"AI_ToolChoiceViolationError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar ToolChoiceViolationError = class extends AISDKError {\n\tconstructor({ toolChoice, finishReason, provider, modelId, content, message = toolChoice.type === \"none\" ? \"Model response contained a tool call even though tool choice was none.\" : toolChoice.type === \"required\" ? \"Model response did not contain a tool call even though tool choice was required.\" : `Model response did not contain a call to the required tool '${toolChoice.toolName}'.` }) {\n\t\tsuper({\n\t\t\tname: name15,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a15] = true;\n\t\tthis.toolChoice = toolChoice;\n\t\tthis.finishReason = finishReason;\n\t\tthis.provider = provider;\n\t\tthis.modelId = modelId;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker15);\n\t}\n};\n_a15 = symbol15;\nvar name16 = \"AI_ToolCallRepairError\";\nvar marker16 = `vercel.ai.error.${name16}`;\nvar symbol16 = Symbol.for(marker16);\nvar _a16;\nvar ToolCallRepairError = class extends AISDKError {\n\tconstructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name16,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a16] = true;\n\t\tthis.originalError = originalError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker16);\n\t}\n};\n_a16 = symbol16;\nvar UnsupportedModelVersionError = class extends AISDKError {\n\tconstructor(options) {\n\t\tsuper({\n\t\t\tname: \"AI_UnsupportedModelVersionError\",\n\t\t\tmessage: `Unsupported model version ${options.version} for provider \"${options.provider}\" and model \"${options.modelId}\". AI SDK 5 only supports models that implement specification version \"v2\".`\n\t\t});\n\t\tthis.version = options.version;\n\t\tthis.provider = options.provider;\n\t\tthis.modelId = options.modelId;\n\t}\n};\nvar name17 = \"AI_UIMessageStreamError\";\nvar marker17 = `vercel.ai.error.${name17}`;\nvar symbol17 = Symbol.for(marker17);\nvar _a17;\nvar UIMessageStreamError = class extends AISDKError {\n\tconstructor({ chunkType, chunkId, message }) {\n\t\tsuper({\n\t\t\tname: name17,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a17] = true;\n\t\tthis.chunkType = chunkType;\n\t\tthis.chunkId = chunkId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker17);\n\t}\n};\n_a17 = symbol17;\nvar name18 = \"AI_InvalidDataContentError\";\nvar marker18 = `vercel.ai.error.${name18}`;\nvar symbol18 = Symbol.for(marker18);\nvar _a18;\nvar InvalidDataContentError = class extends AISDKError {\n\tconstructor({ content, cause, message = `Invalid data content. Expected a base64 string, Uint8Array, ArrayBuffer, or Buffer, but got ${typeof content}.` }) {\n\t\tsuper({\n\t\t\tname: name18,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a18] = true;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker18);\n\t}\n};\n_a18 = symbol18;\nvar name19 = \"AI_InvalidMessageRoleError\";\nvar marker19 = `vercel.ai.error.${name19}`;\nvar symbol19 = Symbol.for(marker19);\nvar _a19;\nvar InvalidMessageRoleError = class extends AISDKError {\n\tconstructor({ role, message = `Invalid message role: '${role}'. Must be one of: \"system\", \"user\", \"assistant\", \"tool\".` }) {\n\t\tsuper({\n\t\t\tname: name19,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a19] = true;\n\t\tthis.role = role;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker19);\n\t}\n};\n_a19 = symbol19;\nvar name20 = \"AI_MessageConversionError\";\nvar marker20 = `vercel.ai.error.${name20}`;\nvar symbol20 = Symbol.for(marker20);\nvar _a20;\nvar MessageConversionError = class extends AISDKError {\n\tconstructor({ originalMessage, message }) {\n\t\tsuper({\n\t\t\tname: name20,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a20] = true;\n\t\tthis.originalMessage = originalMessage;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker20);\n\t}\n};\n_a20 = symbol20;\nvar name21 = \"AI_RetryError\";\nvar marker21 = `vercel.ai.error.${name21}`;\nvar symbol21 = Symbol.for(marker21);\nvar _a21;\nvar RetryError = class extends AISDKError {\n\tconstructor({ message, reason, errors }) {\n\t\tsuper({\n\t\t\tname: name21,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a21] = true;\n\t\tthis.reason = reason;\n\t\tthis.errors = errors;\n\t\tthis.lastError = errors[errors.length - 1];\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker21);\n\t}\n};\n_a21 = symbol21;\nfunction asArray(value) {\n\treturn value === void 0 ? [] : Array.isArray(value) ? value : [value];\n}\nasync function notify(options) {\n\tfor (const callback of asArray(options.callbacks)) {\n\t\tif (callback == null) continue;\n\t\ttry {\n\t\t\tawait callback(options.event);\n\t\t} catch (_ignored) {}\n\t}\n}\nfunction formatWarning({ warning, provider, model }) {\n\tconst prefix = `AI SDK Warning (${provider} / ${model}):`;\n\tswitch (warning.type) {\n\t\tcase \"unsupported\": {\n\t\t\tlet message = `${prefix} The feature \"${warning.feature}\" is not supported.`;\n\t\t\tif (warning.details) message += ` ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"compatibility\": {\n\t\t\tlet message = `${prefix} The feature \"${warning.feature}\" is used in a compatibility mode.`;\n\t\t\tif (warning.details) message += ` ${warning.details}`;\n\t\t\treturn message;\n\t\t}\n\t\tcase \"other\": return `${prefix} ${warning.message}`;\n\t\tdefault: return `${prefix} ${JSON.stringify(warning, null, 2)}`;\n\t}\n}\nvar FIRST_WARNING_INFO_MESSAGE = \"AI SDK Warning System: To turn off warning logging, set the AI_SDK_LOG_WARNINGS global to false.\";\nvar hasLoggedBefore = false;\nvar logWarnings = (options) => {\n\tif (options.warnings.length === 0) return;\n\tconst logger = globalThis.AI_SDK_LOG_WARNINGS;\n\tif (logger === false) return;\n\tif (typeof logger === \"function\") {\n\t\tlogger(options);\n\t\treturn;\n\t}\n\tif (!hasLoggedBefore) {\n\t\thasLoggedBefore = true;\n\t\tconsole.info(FIRST_WARNING_INFO_MESSAGE);\n\t}\n\tfor (const warning of options.warnings) console.warn(formatWarning({\n\t\twarning,\n\t\tprovider: options.provider,\n\t\tmodel: options.model\n\t}));\n};\nfunction logV2CompatibilityWarning({ provider, modelId }) {\n\tlogWarnings({\n\t\twarnings: [{\n\t\t\ttype: \"compatibility\",\n\t\t\tfeature: \"specificationVersion\",\n\t\t\tdetails: `Using v2 specification compatibility mode. Some features may not be available.`\n\t\t}],\n\t\tprovider,\n\t\tmodel: modelId\n\t});\n}\nfunction asEmbeddingModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\nfunction asImageModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\nfunction asLanguageModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tswitch (prop) {\n\t\t\tcase \"specificationVersion\": return \"v3\";\n\t\t\tcase \"doGenerate\": return async (...args) => {\n\t\t\t\tconst result = await target.doGenerate(...args);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tfinishReason: convertV2FinishReasonToV3(result.finishReason),\n\t\t\t\t\tusage: convertV2UsageToV3(result.usage)\n\t\t\t\t};\n\t\t\t};\n\t\t\tcase \"doStream\": return async (...args) => {\n\t\t\t\tconst result = await target.doStream(...args);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tstream: convertV2StreamToV3(result.stream)\n\t\t\t\t};\n\t\t\t};\n\t\t\tdefault: return target[prop];\n\t\t}\n\t} });\n}\nfunction convertV2StreamToV3(stream) {\n\treturn stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tswitch (chunk.type) {\n\t\t\tcase \"finish\":\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t...chunk,\n\t\t\t\t\tfinishReason: convertV2FinishReasonToV3(chunk.finishReason),\n\t\t\t\t\tusage: convertV2UsageToV3(chunk.usage)\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: controller.enqueue(chunk);\n\t\t}\n\t} }));\n}\nfunction convertV2FinishReasonToV3(finishReason) {\n\treturn {\n\t\tunified: finishReason === \"unknown\" ? \"other\" : finishReason,\n\t\traw: void 0\n\t};\n}\nfunction convertV2UsageToV3(usage) {\n\treturn {\n\t\tinputTokens: {\n\t\t\ttotal: usage.inputTokens,\n\t\t\tnoCache: void 0,\n\t\t\tcacheRead: usage.cachedInputTokens,\n\t\t\tcacheWrite: void 0\n\t\t},\n\t\toutputTokens: {\n\t\t\ttotal: usage.outputTokens,\n\t\t\ttext: void 0,\n\t\t\treasoning: usage.reasoningTokens\n\t\t},\n\t\traw: usage.totalTokens == null ? void 0 : { totalTokens: usage.totalTokens }\n\t};\n}\nfunction asSpeechModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\nfunction asTranscriptionModelV3(model) {\n\tif (model.specificationVersion === \"v3\") return model;\n\tlogV2CompatibilityWarning({\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t});\n\treturn new Proxy(model, { get(target, prop) {\n\t\tif (prop === \"specificationVersion\") return \"v3\";\n\t\treturn target[prop];\n\t} });\n}\nfunction resolveLanguageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n\t\t\tconst unsupportedModel = model;\n\t\t\tthrow new UnsupportedModelVersionError({\n\t\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\t\tprovider: unsupportedModel.provider,\n\t\t\t\tmodelId: unsupportedModel.modelId\n\t\t\t});\n\t\t}\n\t\treturn asLanguageModelV3(model);\n\t}\n\treturn getGlobalProvider().languageModel(model);\n}\nfunction resolveEmbeddingModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n\t\t\tconst unsupportedModel = model;\n\t\t\tthrow new UnsupportedModelVersionError({\n\t\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\t\tprovider: unsupportedModel.provider,\n\t\t\t\tmodelId: unsupportedModel.modelId\n\t\t\t});\n\t\t}\n\t\treturn asEmbeddingModelV3(model);\n\t}\n\treturn getGlobalProvider().embeddingModel(model);\n}\nfunction resolveTranscriptionModel(model) {\n\tvar _a23, _b;\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n\t\t\tconst unsupportedModel = model;\n\t\t\tthrow new UnsupportedModelVersionError({\n\t\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\t\tprovider: unsupportedModel.provider,\n\t\t\t\tmodelId: unsupportedModel.modelId\n\t\t\t});\n\t\t}\n\t\treturn asTranscriptionModelV3(model);\n\t}\n\treturn (_b = (_a23 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a23, model);\n}\nfunction resolveSpeechModel(model) {\n\tvar _a23, _b;\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n\t\t\tconst unsupportedModel = model;\n\t\t\tthrow new UnsupportedModelVersionError({\n\t\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\t\tprovider: unsupportedModel.provider,\n\t\t\t\tmodelId: unsupportedModel.modelId\n\t\t\t});\n\t\t}\n\t\treturn asSpeechModelV3(model);\n\t}\n\treturn (_b = (_a23 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a23, model);\n}\nfunction resolveImageModel(model) {\n\tif (typeof model !== \"string\") {\n\t\tif (model.specificationVersion !== \"v3\" && model.specificationVersion !== \"v2\") {\n\t\t\tconst unsupportedModel = model;\n\t\t\tthrow new UnsupportedModelVersionError({\n\t\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\t\tprovider: unsupportedModel.provider,\n\t\t\t\tmodelId: unsupportedModel.modelId\n\t\t\t});\n\t\t}\n\t\treturn asImageModelV3(model);\n\t}\n\treturn getGlobalProvider().imageModel(model);\n}\nfunction resolveVideoModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst videoModel = getGlobalProvider().videoModel;\n\t\tif (!videoModel) throw new Error(\"The default provider does not support video models. Please use a Experimental_VideoModelV3 object from a provider (e.g., vertex.video(\\\"model-id\\\")).\");\n\t\treturn videoModel(model);\n\t}\n\tif (model.specificationVersion !== \"v3\") {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn model;\n}\nfunction resolveRerankingModel(model) {\n\tif (typeof model === \"string\") {\n\t\tconst rerankingModel = getGlobalProvider().rerankingModel;\n\t\tif (!rerankingModel) throw new Error(\"The default provider does not support reranking models. Please use a RerankingModel object from a provider (e.g., gateway.rerankingModel(\\\"model-id\\\")).\");\n\t\treturn rerankingModel(model);\n\t}\n\tif (model.specificationVersion !== \"v3\") {\n\t\tconst unsupportedModel = model;\n\t\tthrow new UnsupportedModelVersionError({\n\t\t\tversion: unsupportedModel.specificationVersion,\n\t\t\tprovider: unsupportedModel.provider,\n\t\t\tmodelId: unsupportedModel.modelId\n\t\t});\n\t}\n\treturn model;\n}\nfunction getGlobalProvider() {\n\tvar _a23;\n\treturn (_a23 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a23 : gateway;\n}\nfunction getTotalTimeoutMs(timeout) {\n\tif (timeout == null) return;\n\tif (typeof timeout === \"number\") return timeout;\n\treturn timeout.totalMs;\n}\nfunction getStepTimeoutMs(timeout) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.stepMs;\n}\nfunction getChunkTimeoutMs(timeout) {\n\tif (timeout == null || typeof timeout === \"number\") return;\n\treturn timeout.chunkMs;\n}\nvar imageMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"image/gif\",\n\t\tbytesPrefix: [\n\t\t\t71,\n\t\t\t73,\n\t\t\t70\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/png\",\n\t\tbytesPrefix: [\n\t\t\t137,\n\t\t\t80,\n\t\t\t78,\n\t\t\t71\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/jpeg\",\n\t\tbytesPrefix: [255, 216]\n\t},\n\t{\n\t\tmediaType: \"image/webp\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t69,\n\t\t\t66,\n\t\t\t80\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/bmp\",\n\t\tbytesPrefix: [66, 77]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t73,\n\t\t\t73,\n\t\t\t42,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/tiff\",\n\t\tbytesPrefix: [\n\t\t\t77,\n\t\t\t77,\n\t\t\t0,\n\t\t\t42\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/avif\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t97,\n\t\t\t118,\n\t\t\t105,\n\t\t\t102\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"image/heic\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t32,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t104,\n\t\t\t101,\n\t\t\t105,\n\t\t\t99\n\t\t]\n\t}\n];\nvar audioMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 251]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 250]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 243]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 242]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 227]\n\t},\n\t{\n\t\tmediaType: \"audio/mpeg\",\n\t\tbytesPrefix: [255, 226]\n\t},\n\t{\n\t\tmediaType: \"audio/wav\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\tnull,\n\t\t\t87,\n\t\t\t65,\n\t\t\t86,\n\t\t\t69\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/ogg\",\n\t\tbytesPrefix: [\n\t\t\t79,\n\t\t\t103,\n\t\t\t103,\n\t\t\t83\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/flac\",\n\t\tbytesPrefix: [\n\t\t\t102,\n\t\t\t76,\n\t\t\t97,\n\t\t\t67\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/aac\",\n\t\tbytesPrefix: [\n\t\t\t64,\n\t\t\t21,\n\t\t\t0,\n\t\t\t0\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/mp4\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"audio/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t}\n];\nvar videoMediaTypeSignatures = [\n\t{\n\t\tmediaType: \"video/mp4\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\tnull,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/webm\",\n\t\tbytesPrefix: [\n\t\t\t26,\n\t\t\t69,\n\t\t\t223,\n\t\t\t163\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/quicktime\",\n\t\tbytesPrefix: [\n\t\t\t0,\n\t\t\t0,\n\t\t\t0,\n\t\t\t20,\n\t\t\t102,\n\t\t\t116,\n\t\t\t121,\n\t\t\t112,\n\t\t\t113,\n\t\t\t116\n\t\t]\n\t},\n\t{\n\t\tmediaType: \"video/x-msvideo\",\n\t\tbytesPrefix: [\n\t\t\t82,\n\t\t\t73,\n\t\t\t70,\n\t\t\t70\n\t\t]\n\t}\n];\nvar DEFAULT_SNIFF_BYTES = 18;\nvar ID3_SCAN_BYTES = 131084;\nfunction decodePrefix(data, maxBytes) {\n\tif (typeof data !== \"string\") return data.length > maxBytes ? data.subarray(0, maxBytes) : data;\n\tconst maxChars = Math.ceil(maxBytes / 3) * 4;\n\tconst bytes = convertBase64ToUint8Array(data.substring(0, Math.min(data.length, maxChars)));\n\treturn bytes.length > maxBytes ? bytes.subarray(0, maxBytes) : bytes;\n}\nfunction hasID3(bytes) {\n\treturn bytes.length > 10 && bytes[0] === 73 && bytes[1] === 68 && bytes[2] === 51;\n}\nvar stripID3 = (bytes) => {\n\tconst id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;\n\treturn bytes.subarray(id3Size + 10);\n};\nfunction detectMediaType({ data, signatures }) {\n\tlet bytes = decodePrefix(data, DEFAULT_SNIFF_BYTES);\n\tif (hasID3(bytes)) bytes = stripID3(decodePrefix(data, ID3_SCAN_BYTES));\n\tfor (const signature of signatures) if (bytes.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => byte === null || bytes[index] === byte)) return signature.mediaType;\n}\nvar VERSION = \"6.0.322\";\nvar download = async ({ url, maxBytes, abortSignal }) => {\n\tvar _a23;\n\tconst urlText = url.toString();\n\ttry {\n\t\tconst headers = withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent());\n\t\tconst response = await fetchWithValidatedRedirects({\n\t\t\turl: urlText,\n\t\t\theaders,\n\t\t\tabortSignal\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tawait cancelResponseBody(response);\n\t\t\tthrow new DownloadError({\n\t\t\t\turl: urlText,\n\t\t\t\tstatusCode: response.status,\n\t\t\t\tstatusText: response.statusText\n\t\t\t});\n\t\t}\n\t\treturn {\n\t\t\tdata: await readResponseWithSizeLimit({\n\t\t\t\tresponse,\n\t\t\t\turl: urlText,\n\t\t\t\tmaxBytes: maxBytes != null ? maxBytes : DEFAULT_MAX_DOWNLOAD_SIZE\n\t\t\t}),\n\t\t\tmediaType: (_a23 = response.headers.get(\"content-type\")) != null ? _a23 : void 0\n\t\t};\n\t} catch (error) {\n\t\tif (DownloadError.isInstance(error)) throw error;\n\t\tthrow new DownloadError({\n\t\t\turl: urlText,\n\t\t\tcause: error\n\t\t});\n\t}\n};\nvar createDefaultDownloadFunction = (download2 = download, abortSignal) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : await download2({\n\t...requestedDownload,\n\tabortSignal\n})));\nfunction mergeObjects(base, overrides) {\n\tif (base === void 0 && overrides === void 0) return;\n\tif (base === void 0) return overrides;\n\tif (overrides === void 0) return base;\n\tconst result = { ...base };\n\tfor (const key in overrides) {\n\t\tif (key === \"__proto__\" || key === \"constructor\" || key === \"prototype\") continue;\n\t\tif (Object.prototype.hasOwnProperty.call(overrides, key)) {\n\t\t\tconst overridesValue = overrides[key];\n\t\t\tif (overridesValue === void 0) continue;\n\t\t\tconst baseValue = key in base ? base[key] : void 0;\n\t\t\tconst isSourceObject = overridesValue !== null && typeof overridesValue === \"object\" && !Array.isArray(overridesValue) && !(overridesValue instanceof Date) && !(overridesValue instanceof RegExp);\n\t\t\tconst isTargetObject = baseValue !== null && baseValue !== void 0 && typeof baseValue === \"object\" && !Array.isArray(baseValue) && !(baseValue instanceof Date) && !(baseValue instanceof RegExp);\n\t\t\tif (isSourceObject && isTargetObject) result[key] = mergeObjects(baseValue, overridesValue);\n\t\t\telse result[key] = overridesValue;\n\t\t}\n\t}\n\treturn result;\n}\nfunction splitDataUrl(dataUrl) {\n\ttry {\n\t\tconst [header, base64Content] = dataUrl.split(\",\");\n\t\treturn {\n\t\t\tmediaType: header.split(\";\")[0].split(\":\")[1],\n\t\t\tbase64Content\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tmediaType: void 0,\n\t\t\tbase64Content: void 0\n\t\t};\n\t}\n}\nvar dataContentSchema = z.union([\n\tz.string(),\n\tz.custom(isUint8Array, { message: \"Must be a Uint8Array\" }),\n\tz.custom(isArrayBuffer, { message: \"Must be an ArrayBuffer\" }),\n\tz.custom((value) => {\n\t\tvar _a23, _b;\n\t\treturn (_b = (_a23 = globalThis.Buffer) == null ? void 0 : _a23.isBuffer(value)) != null ? _b : false;\n\t}, { message: \"Must be a Buffer\" })\n]);\nfunction convertToLanguageModelV3DataContent(content) {\n\tlet originalUrl;\n\tif (isUint8Array(content)) return {\n\t\tdata: convertDataContentToUint8Array(content),\n\t\tmediaType: void 0\n\t};\n\tif (isArrayBuffer(content)) return {\n\t\tdata: new Uint8Array(content),\n\t\tmediaType: void 0\n\t};\n\tif (typeof content === \"string\") try {\n\t\tconst url = new URL(content);\n\t\toriginalUrl = url.toString() !== content ? content : void 0;\n\t\tcontent = url;\n\t} catch (error) {}\n\tif (content instanceof URL && content.protocol === \"data:\") {\n\t\tconst { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(content.toString());\n\t\tif (dataUrlMediaType == null || base64Content == null) throw new AISDKError({\n\t\t\tname: \"InvalidDataContentError\",\n\t\t\tmessage: `Invalid data URL format in content ${content.toString()}`\n\t\t});\n\t\treturn {\n\t\t\tdata: base64Content,\n\t\t\tmediaType: dataUrlMediaType\n\t\t};\n\t}\n\treturn {\n\t\tdata: content,\n\t\tmediaType: void 0,\n\t\t...originalUrl != null ? { originalUrl } : {}\n\t};\n}\nfunction convertDataContentToBase64String(content) {\n\tif (typeof content === \"string\") return content;\n\treturn convertUint8ArrayToBase64(convertDataContentToUint8Array(content));\n}\nfunction convertDataContentToUint8Array(content) {\n\tif (isUint8Array(content)) {\n\t\tif (content instanceof Uint8Array) return content;\n\t\tconst { buffer, byteOffset, byteLength } = content;\n\t\treturn new Uint8Array(buffer, byteOffset, byteLength);\n\t}\n\tif (typeof content === \"string\") try {\n\t\treturn convertBase64ToUint8Array(content);\n\t} catch (error) {\n\t\tthrow new InvalidDataContentError({\n\t\t\tmessage: \"Invalid data content. Content string is not a base64-encoded media.\",\n\t\t\tcontent,\n\t\t\tcause: error\n\t\t});\n\t}\n\tif (isArrayBuffer(content)) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\n}\nasync function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2, abortSignal }) {\n\tconst downloadedAssets = await downloadAssets(prompt.messages, download2 != null ? download2 : createDefaultDownloadFunction(void 0, abortSignal), supportedUrls);\n\tconst messages = [...prompt.system != null ? typeof prompt.system === \"string\" ? [{\n\t\trole: \"system\",\n\t\tcontent: prompt.system\n\t}] : asArray(prompt.system).map((message) => ({\n\t\trole: \"system\",\n\t\tcontent: message.content,\n\t\tproviderOptions: message.providerOptions\n\t})) : [], ...prompt.messages.map((message) => convertToLanguageModelMessage({\n\t\tmessage,\n\t\tdownloadedAssets\n\t}))];\n\tconst combinedMessages = [];\n\tfor (const message of messages) {\n\t\tif (message.role !== \"tool\") {\n\t\t\tcombinedMessages.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tconst lastCombinedMessage = combinedMessages.at(-1);\n\t\tif ((lastCombinedMessage == null ? void 0 : lastCombinedMessage.role) === \"tool\") {\n\t\t\tconst lastContentPart = lastCombinedMessage.content.at(-1);\n\t\t\tif (lastContentPart != null && lastCombinedMessage.providerOptions != null) lastContentPart.providerOptions = mergeObjects(lastCombinedMessage.providerOptions, lastContentPart.providerOptions);\n\t\t\tlastCombinedMessage.content.push(...message.content);\n\t\t\tlastCombinedMessage.providerOptions = message.providerOptions;\n\t\t} else combinedMessages.push(message);\n\t}\n\tconst toolCallIds = /* @__PURE__ */ new Set();\n\tfor (const message of combinedMessages) switch (message.role) {\n\t\tcase \"assistant\":\n\t\t\tfor (const content of message.content) if (content.type === \"tool-call\" && !content.providerExecuted) toolCallIds.add(content.toolCallId);\n\t\t\tbreak;\n\t\tcase \"tool\":\n\t\t\tfor (const content of message.content) if (content.type === \"tool-result\") toolCallIds.delete(content.toolCallId);\n\t\t\tbreak;\n\t\tcase \"user\":\n\t\tcase \"system\": if (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\t}\n\tif (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\treturn combinedMessages.filter((message) => message.role !== \"tool\" || message.content.length > 0);\n}\nfunction convertToLanguageModelMessage({ message, downloadedAssets }) {\n\tconst role = message.role;\n\tswitch (role) {\n\t\tcase \"system\": return {\n\t\t\trole: \"system\",\n\t\t\tcontent: message.content,\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tcase \"user\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.content.map((part) => convertPartToLanguageModelPart(part, downloadedAssets)).filter((part) => part.type !== \"text\" || part.text !== \"\"),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"assistant\":\n\t\t\tif (typeof message.content === \"string\") return {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: [{\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: message.content\n\t\t\t\t}],\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\t\treturn {\n\t\t\t\trole: \"assistant\",\n\t\t\t\tcontent: message.content.filter((part) => part.type !== \"text\" || part.text !== \"\" || part.providerOptions != null).filter((part) => part.type !== \"tool-approval-request\").map((part) => {\n\t\t\t\t\tconst providerOptions = part.providerOptions;\n\t\t\t\t\tswitch (part.type) {\n\t\t\t\t\t\tcase \"file\": {\n\t\t\t\t\t\t\tconst { data, mediaType } = convertToLanguageModelV3DataContent(part.data);\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\t\tdata,\n\t\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t\tmediaType: mediaType != null ? mediaType : part.mediaType,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t\tcase \"reasoning\": return {\n\t\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"text\": return {\n\t\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-call\": return {\n\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\toutput: mapToolResultOutput({\n\t\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\t\tdownloadedAssets\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tproviderOptions: message.providerOptions\n\t\t\t};\n\t\tcase \"tool\": return {\n\t\t\trole: \"tool\",\n\t\t\tcontent: message.content.filter((part) => part.type !== \"tool-approval-response\" || part.providerExecuted).map((part) => {\n\t\t\t\tswitch (part.type) {\n\t\t\t\t\tcase \"tool-result\": return {\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\toutput: mapToolResultOutput({\n\t\t\t\t\t\t\toutput: part.output,\n\t\t\t\t\t\t\tdownloadedAssets\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t\t\t};\n\t\t\t\t\tcase \"tool-approval-response\": return {\n\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\t\t\tapproved: part.approved,\n\t\t\t\t\t\treason: part.reason\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}),\n\t\t\tproviderOptions: message.providerOptions\n\t\t};\n\t\tdefault: throw new InvalidMessageRoleError({ role });\n\t}\n}\nasync function downloadAssets(messages, download2, supportedUrls) {\n\tvar _a23;\n\tconst downloadableFiles = [];\n\tfor (const message of messages) {\n\t\tif (message.role === \"user\" && Array.isArray(message.content)) {\n\t\t\tfor (const part of message.content) if (part.type === \"image\" || part.type === \"file\") downloadableFiles.push({\n\t\t\t\tdata: part.type === \"image\" ? part.image : part.data,\n\t\t\t\tmediaType: (_a23 = part.mediaType) != null ? _a23 : part.type === \"image\" ? \"image/*\" : void 0\n\t\t\t});\n\t\t}\n\t\tif (message.role === \"tool\" || message.role === \"assistant\") {\n\t\t\tif (!Array.isArray(message.content)) continue;\n\t\t\tfor (const part of message.content) {\n\t\t\t\tif (part.type !== \"tool-result\") continue;\n\t\t\t\tif (part.output.type !== \"content\") continue;\n\t\t\t\tfor (const contentPart of part.output.value) if (contentPart.type === \"image-url\" || contentPart.type === \"file-url\") downloadableFiles.push({\n\t\t\t\t\tdata: new URL(contentPart.url),\n\t\t\t\t\tmediaType: contentPart.type === \"image-url\" ? \"image/*\" : contentPart.mediaType\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t}\n\tconst plannedDownloads = downloadableFiles.map((part) => {\n\t\tconst mediaType = part.mediaType;\n\t\tconst { data } = convertToLanguageModelV3DataContent(part.data);\n\t\treturn {\n\t\t\tmediaType,\n\t\t\tdata\n\t\t};\n\t}).filter((part) => part.data instanceof URL).map((part) => ({\n\t\turl: part.data,\n\t\tisUrlSupportedByModel: part.mediaType != null && isUrlSupported({\n\t\t\turl: part.data.toString(),\n\t\t\tmediaType: part.mediaType,\n\t\t\tsupportedUrls\n\t\t})\n\t}));\n\tconst downloadedFiles = await download2(plannedDownloads);\n\treturn Object.fromEntries(downloadedFiles.map((file, index) => file == null ? null : [plannedDownloads[index].url.toString(), {\n\t\tdata: file.data,\n\t\tmediaType: file.mediaType\n\t}]).filter((file) => file != null));\n}\nfunction convertPartToLanguageModelPart(part, downloadedAssets) {\n\tvar _a23;\n\tif (part.type === \"text\") return {\n\t\ttype: \"text\",\n\t\ttext: part.text,\n\t\tproviderOptions: part.providerOptions\n\t};\n\tlet originalData;\n\tconst type = part.type;\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\toriginalData = part.image;\n\t\t\tbreak;\n\t\tcase \"file\":\n\t\t\toriginalData = part.data;\n\t\t\tbreak;\n\t\tdefault: throw new Error(`Unsupported part type: ${type}`);\n\t}\n\tconst { data: convertedData, mediaType: convertedMediaType, originalUrl } = convertToLanguageModelV3DataContent(originalData);\n\tlet mediaType = convertedMediaType != null ? convertedMediaType : part.mediaType;\n\tlet data = convertedData;\n\tif (data instanceof URL) {\n\t\tconst downloadedFile = downloadedAssets[data.toString()];\n\t\tif (downloadedFile) {\n\t\t\tdata = downloadedFile.data;\n\t\t\tmediaType ??= downloadedFile.mediaType;\n\t\t}\n\t}\n\tswitch (type) {\n\t\tcase \"image\":\n\t\t\tif (data instanceof Uint8Array || typeof data === \"string\") mediaType = (_a23 = detectMediaType({\n\t\t\t\tdata,\n\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t})) != null ? _a23 : mediaType;\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType: mediaType != null ? mediaType : \"image/*\",\n\t\t\t\tfilename: void 0,\n\t\t\t\tdata,\n\t\t\t\t...data instanceof URL && originalUrl != null ? { originalUrl } : {},\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t\tcase \"file\":\n\t\t\tif (mediaType == null) throw new Error(`Media type is missing for file part`);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType,\n\t\t\t\tfilename: part.filename,\n\t\t\t\tdata,\n\t\t\t\t...data instanceof URL && originalUrl != null ? { originalUrl } : {},\n\t\t\t\tproviderOptions: part.providerOptions\n\t\t\t};\n\t}\n}\nfunction mapToolResultOutput({ output, downloadedAssets }) {\n\tif (output.type !== \"content\") return output;\n\treturn {\n\t\ttype: \"content\",\n\t\tvalue: output.value.map((item) => {\n\t\t\tvar _a23, _b;\n\t\t\tif (item.type === \"image-url\") {\n\t\t\t\tconst downloadedFile = downloadedAssets[new URL(item.url).toString()];\n\t\t\t\tif (downloadedFile) return {\n\t\t\t\t\ttype: \"image-data\",\n\t\t\t\t\tdata: convertDataContentToBase64String(downloadedFile.data),\n\t\t\t\t\tmediaType: (_a23 = downloadedFile.mediaType) != null ? _a23 : \"image/*\",\n\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t};\n\t\t\t\treturn item;\n\t\t\t}\n\t\t\tif (item.type === \"file-url\") {\n\t\t\t\tconst downloadedFile = downloadedAssets[new URL(item.url).toString()];\n\t\t\t\tif (downloadedFile) return {\n\t\t\t\t\ttype: \"file-data\",\n\t\t\t\t\tdata: convertDataContentToBase64String(downloadedFile.data),\n\t\t\t\t\tmediaType: (_b = downloadedFile.mediaType) != null ? _b : \"application/octet-stream\",\n\t\t\t\t\tproviderOptions: item.providerOptions\n\t\t\t\t};\n\t\t\t\treturn item;\n\t\t\t}\n\t\t\tif (item.type !== \"media\") return item;\n\t\t\tif (item.mediaType.startsWith(\"image/\")) return {\n\t\t\t\ttype: \"image-data\",\n\t\t\t\tdata: item.data,\n\t\t\t\tmediaType: item.mediaType\n\t\t\t};\n\t\t\treturn {\n\t\t\t\ttype: \"file-data\",\n\t\t\t\tdata: item.data,\n\t\t\t\tmediaType: item.mediaType\n\t\t\t};\n\t\t})\n\t};\n}\nasync function createToolModelOutput({ toolCallId, input, output, tool: tool2, errorMode }) {\n\tif (errorMode === \"text\") return {\n\t\ttype: \"error-text\",\n\t\tvalue: getErrorMessage(output)\n\t};\n\telse if (errorMode === \"json\") return {\n\t\ttype: \"error-json\",\n\t\tvalue: toJSONValue(output)\n\t};\n\tif (tool2 == null ? void 0 : tool2.toModelOutput) return await tool2.toModelOutput({\n\t\ttoolCallId,\n\t\tinput,\n\t\toutput\n\t});\n\treturn typeof output === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalue: output\n\t} : {\n\t\ttype: \"json\",\n\t\tvalue: toJSONValue(output)\n\t};\n}\nfunction toJSONValue(value) {\n\treturn value === void 0 ? null : value;\n}\nfunction prepareCallSettings({ maxOutputTokens, temperature, topP, topK, presencePenalty, frequencyPenalty, seed, stopSequences }) {\n\tif (maxOutputTokens != null) {\n\t\tif (!Number.isInteger(maxOutputTokens)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be an integer\"\n\t\t});\n\t\tif (maxOutputTokens < 1) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxOutputTokens\",\n\t\t\tvalue: maxOutputTokens,\n\t\t\tmessage: \"maxOutputTokens must be >= 1\"\n\t\t});\n\t}\n\tif (temperature != null) {\n\t\tif (typeof temperature !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"temperature\",\n\t\t\tvalue: temperature,\n\t\t\tmessage: \"temperature must be a number\"\n\t\t});\n\t}\n\tif (topP != null) {\n\t\tif (typeof topP !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topP\",\n\t\t\tvalue: topP,\n\t\t\tmessage: \"topP must be a number\"\n\t\t});\n\t}\n\tif (topK != null) {\n\t\tif (typeof topK !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"topK\",\n\t\t\tvalue: topK,\n\t\t\tmessage: \"topK must be a number\"\n\t\t});\n\t}\n\tif (presencePenalty != null) {\n\t\tif (typeof presencePenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"presencePenalty\",\n\t\t\tvalue: presencePenalty,\n\t\t\tmessage: \"presencePenalty must be a number\"\n\t\t});\n\t}\n\tif (frequencyPenalty != null) {\n\t\tif (typeof frequencyPenalty !== \"number\") throw new InvalidArgumentError({\n\t\t\tparameter: \"frequencyPenalty\",\n\t\t\tvalue: frequencyPenalty,\n\t\t\tmessage: \"frequencyPenalty must be a number\"\n\t\t});\n\t}\n\tif (seed != null) {\n\t\tif (!Number.isInteger(seed)) throw new InvalidArgumentError({\n\t\t\tparameter: \"seed\",\n\t\t\tvalue: seed,\n\t\t\tmessage: \"seed must be an integer\"\n\t\t});\n\t}\n\treturn {\n\t\tmaxOutputTokens,\n\t\ttemperature,\n\t\ttopP,\n\t\ttopK,\n\t\tpresencePenalty,\n\t\tfrequencyPenalty,\n\t\tstopSequences,\n\t\tseed\n\t};\n}\nfunction isNonEmptyObject(object2) {\n\treturn object2 != null && Object.keys(object2).length > 0;\n}\nasync function prepareToolsAndToolChoice({ tools, toolChoice, activeTools }) {\n\tif (!isNonEmptyObject(tools)) return {\n\t\ttools: void 0,\n\t\ttoolChoice: void 0\n\t};\n\tconst filteredTools = activeTools != null ? Object.entries(tools).filter(([name23]) => activeTools.includes(name23)) : Object.entries(tools);\n\tconst languageModelTools = [];\n\tfor (const [name23, tool2] of filteredTools) {\n\t\tconst toolType = tool2.type;\n\t\tswitch (toolType) {\n\t\t\tcase void 0:\n\t\t\tcase \"dynamic\":\n\t\t\tcase \"function\":\n\t\t\t\tlanguageModelTools.push({\n\t\t\t\t\ttype: \"function\",\n\t\t\t\t\tname: name23,\n\t\t\t\t\tdescription: tool2.description,\n\t\t\t\t\tinputSchema: await asSchema(tool2.inputSchema).jsonSchema,\n\t\t\t\t\t...tool2.inputExamples != null ? { inputExamples: tool2.inputExamples } : {},\n\t\t\t\t\tproviderOptions: tool2.providerOptions,\n\t\t\t\t\t...tool2.strict != null ? { strict: tool2.strict } : {}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"provider\":\n\t\t\t\tlanguageModelTools.push({\n\t\t\t\t\ttype: \"provider\",\n\t\t\t\t\tname: name23,\n\t\t\t\t\tid: tool2.id,\n\t\t\t\t\targs: tool2.args\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unsupported tool type: ${toolType}`);\n\t\t}\n\t}\n\treturn {\n\t\ttools: languageModelTools,\n\t\ttoolChoice: toolChoice == null ? { type: \"auto\" } : typeof toolChoice === \"string\" ? { type: toolChoice } : {\n\t\t\ttype: \"tool\",\n\t\t\ttoolName: toolChoice.toolName\n\t\t}\n\t};\n}\nvar jsonValueSchema = z.lazy(() => z.union([\n\tz.null(),\n\tz.string(),\n\tz.number(),\n\tz.boolean(),\n\tz.record(z.string(), jsonValueSchema.optional()),\n\tz.array(jsonValueSchema)\n]));\nvar providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));\nvar textPartSchema = z.object({\n\ttype: z.literal(\"text\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar imagePartSchema = z.object({\n\ttype: z.literal(\"image\"),\n\timage: z.union([dataContentSchema, z.instanceof(URL)]),\n\tmediaType: z.string().optional(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar filePartSchema = z.object({\n\ttype: z.literal(\"file\"),\n\tdata: z.union([dataContentSchema, z.instanceof(URL)]),\n\tfilename: z.string().optional(),\n\tmediaType: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar reasoningPartSchema = z.object({\n\ttype: z.literal(\"reasoning\"),\n\ttext: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar toolCallPartSchema = z.object({\n\ttype: z.literal(\"tool-call\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\tinput: z.unknown(),\n\tproviderOptions: providerMetadataSchema.optional(),\n\tproviderExecuted: z.boolean().optional()\n});\nvar outputSchema = z.discriminatedUnion(\"type\", [\n\tz.object({\n\t\ttype: z.literal(\"text\"),\n\t\tvalue: z.string(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"execution-denied\"),\n\t\treason: z.string().optional(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-text\"),\n\t\tvalue: z.string(),\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"error-json\"),\n\t\tvalue: jsonValueSchema,\n\t\tproviderOptions: providerMetadataSchema.optional()\n\t}),\n\tz.object({\n\t\ttype: z.literal(\"content\"),\n\t\tvalue: z.array(z.union([\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"text\"),\n\t\t\t\ttext: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"media\"),\n\t\t\t\tdata: z.string(),\n\t\t\t\tmediaType: z.string()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-data\"),\n\t\t\t\tdata: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-url\"),\n\t\t\t\turl: z.string(),\n\t\t\t\tmediaType: z.string().optional(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file-id\"),\n\t\t\t\tfileId: z.union([z.string(), z.record(z.string(), z.string())]),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-data\"),\n\t\t\t\tdata: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-url\"),\n\t\t\t\turl: z.string(),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"image-file-id\"),\n\t\t\t\tfileId: z.union([z.string(), z.record(z.string(), z.string())]),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"custom\"),\n\t\t\t\tproviderOptions: providerMetadataSchema.optional()\n\t\t\t})\n\t\t]))\n\t})\n]);\nvar toolResultPartSchema = z.object({\n\ttype: z.literal(\"tool-result\"),\n\ttoolCallId: z.string(),\n\ttoolName: z.string(),\n\toutput: outputSchema,\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar toolApprovalRequestSchema = z.object({\n\ttype: z.literal(\"tool-approval-request\"),\n\tapprovalId: z.string(),\n\ttoolCallId: z.string(),\n\tsignature: z.string().optional(),\n\tinputSchemaInput: z.unknown().optional()\n});\nvar toolApprovalResponseSchema = z.object({\n\ttype: z.literal(\"tool-approval-response\"),\n\tapprovalId: z.string(),\n\tapproved: z.boolean(),\n\treason: z.string().optional()\n});\nvar systemModelMessageSchema = z.object({\n\trole: z.literal(\"system\"),\n\tcontent: z.string(),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar userModelMessageSchema = z.object({\n\trole: z.literal(\"user\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\timagePartSchema,\n\t\tfilePartSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar assistantModelMessageSchema = z.object({\n\trole: z.literal(\"assistant\"),\n\tcontent: z.union([z.string(), z.array(z.union([\n\t\ttextPartSchema,\n\t\tfilePartSchema,\n\t\treasoningPartSchema,\n\t\ttoolCallPartSchema,\n\t\ttoolResultPartSchema,\n\t\ttoolApprovalRequestSchema\n\t]))]),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar toolModelMessageSchema = z.object({\n\trole: z.literal(\"tool\"),\n\tcontent: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),\n\tproviderOptions: providerMetadataSchema.optional()\n});\nvar modelMessageSchema = z.union([\n\tsystemModelMessageSchema,\n\tuserModelMessageSchema,\n\tassistantModelMessageSchema,\n\ttoolModelMessageSchema\n]);\nasync function standardizePrompt({ allowSystemInMessages, system, prompt, messages }) {\n\tif (prompt == null && messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (prompt != null && messages != null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt and messages cannot be defined at the same time\"\n\t});\n\tif (typeof system !== \"string\" && !asArray(system).every((message) => message.role === \"system\")) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"system must be a string, SystemModelMessage, or array of SystemModelMessage\"\n\t});\n\tif (prompt != null && typeof prompt === \"string\") messages = [{\n\t\trole: \"user\",\n\t\tcontent: prompt\n\t}];\n\telse if (prompt != null && Array.isArray(prompt)) messages = prompt;\n\telse if (messages == null) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"prompt or messages must be defined\"\n\t});\n\tif (messages.length === 0) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"messages must not be empty\"\n\t});\n\tif (messages.some((message) => message.role === \"system\")) {\n\t\tif (allowSystemInMessages === false) throw new InvalidPromptError({\n\t\t\tprompt,\n\t\t\tmessage: \"System messages are not allowed in the prompt or messages fields. Use the system option instead.\"\n\t\t});\n\t\tif (allowSystemInMessages === void 0) console.warn(\"AI SDK Warning: System messages in the prompt or messages fields can be a security risk because they may enable prompt injection attacks. Use the system option instead when possible. Set allowSystemInMessages to true to suppress this warning, or false to throw an error.\");\n\t}\n\tconst validationResult = await safeValidateTypes({\n\t\tvalue: messages,\n\t\tschema: z.array(modelMessageSchema)\n\t});\n\tif (!validationResult.success) throw new InvalidPromptError({\n\t\tprompt,\n\t\tmessage: \"The messages do not match the ModelMessage[] schema.\",\n\t\tcause: validationResult.error\n\t});\n\treturn {\n\t\tmessages,\n\t\tsystem\n\t};\n}\nfunction wrapGatewayError(error) {\n\tif (!GatewayAuthenticationError.isInstance(error)) return error;\n\tconst isProductionEnv = (process == null ? void 0 : \"production\") === \"production\";\n\tconst moreInfoURL = \"https://ai-sdk.dev/unauthenticated-ai-gateway\";\n\tif (isProductionEnv) return new AISDKError({\n\t\tname: \"GatewayError\",\n\t\tmessage: `Unauthenticated. Configure AI_GATEWAY_API_KEY or use a provider module. Learn more: ${moreInfoURL}`\n\t});\n\treturn Object.assign(/* @__PURE__ */ new Error(`\\x1B[1m\\x1B[31mUnauthenticated request to AI Gateway.\\x1B[0m\n\nTo authenticate, set the \\x1B[33mAI_GATEWAY_API_KEY\\x1B[0m environment variable with your API key.\n\nAlternatively, you can use a provider module instead of the AI Gateway.\n\nLearn more: \\x1B[34m${moreInfoURL}\\x1B[0m\n\n`), { name: \"GatewayAuthenticationError\" });\n}\nfunction assembleOperationName({ operationId, telemetry }) {\n\treturn {\n\t\t\"operation.name\": `${operationId}${(telemetry == null ? void 0 : telemetry.functionId) != null ? ` ${telemetry.functionId}` : \"\"}`,\n\t\t\"resource.name\": telemetry == null ? void 0 : telemetry.functionId,\n\t\t\"ai.operationId\": operationId,\n\t\t\"ai.telemetry.functionId\": telemetry == null ? void 0 : telemetry.functionId\n\t};\n}\nfunction getBaseTelemetryAttributes({ model, settings, telemetry, headers }) {\n\tvar _a23;\n\treturn {\n\t\t\"ai.model.provider\": model.provider,\n\t\t\"ai.model.id\": model.modelId,\n\t\t...Object.entries(settings).reduce((attributes, [key, value]) => {\n\t\t\tif (key === \"timeout\") {\n\t\t\t\tconst totalTimeoutMs = getTotalTimeoutMs(value);\n\t\t\t\tif (totalTimeoutMs != null) attributes[`ai.settings.${key}`] = totalTimeoutMs;\n\t\t\t} else attributes[`ai.settings.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries((_a23 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a23 : {}).reduce((attributes, [key, value]) => {\n\t\t\tattributes[`ai.telemetry.metadata.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {}),\n\t\t...Object.entries(headers != null ? headers : {}).reduce((attributes, [key, value]) => {\n\t\t\tif (value !== void 0) attributes[`ai.request.headers.${key}`] = value;\n\t\t\treturn attributes;\n\t\t}, {})\n\t};\n}\nvar noopTracer = {\n\tstartSpan() {\n\t\treturn noopSpan;\n\t},\n\tstartActiveSpan(name23, arg1, arg2, arg3) {\n\t\tif (typeof arg1 === \"function\") return arg1(noopSpan);\n\t\tif (typeof arg2 === \"function\") return arg2(noopSpan);\n\t\tif (typeof arg3 === \"function\") return arg3(noopSpan);\n\t}\n};\nvar noopSpan = {\n\tspanContext() {\n\t\treturn noopSpanContext;\n\t},\n\tsetAttribute() {\n\t\treturn this;\n\t},\n\tsetAttributes() {\n\t\treturn this;\n\t},\n\taddEvent() {\n\t\treturn this;\n\t},\n\taddLink() {\n\t\treturn this;\n\t},\n\taddLinks() {\n\t\treturn this;\n\t},\n\tsetStatus() {\n\t\treturn this;\n\t},\n\tupdateName() {\n\t\treturn this;\n\t},\n\tend() {\n\t\treturn this;\n\t},\n\tisRecording() {\n\t\treturn false;\n\t},\n\trecordException() {\n\t\treturn this;\n\t}\n};\nvar noopSpanContext = {\n\ttraceId: \"\",\n\tspanId: \"\",\n\ttraceFlags: 0\n};\nfunction getTracer({ isEnabled = false, tracer } = {}) {\n\tif (!isEnabled) return noopTracer;\n\tif (tracer) return tracer;\n\treturn trace.getTracer(\"ai\");\n}\nasync function recordSpan({ name: name23, tracer, attributes, fn, endWhenDone = true, endOnError = endWhenDone }) {\n\treturn tracer.startActiveSpan(name23, { attributes: await attributes }, async (span) => {\n\t\tconst ctx = context.active();\n\t\ttry {\n\t\t\tconst result = await context.with(ctx, () => fn(span));\n\t\t\tif (endWhenDone) span.end();\n\t\t\treturn result;\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t} finally {\n\t\t\t\tif (endOnError) span.end();\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t});\n}\nfunction recordErrorOnSpan(span, error) {\n\tif (error instanceof Error) {\n\t\tspan.recordException({\n\t\t\tname: error.name,\n\t\t\tmessage: error.message,\n\t\t\tstack: error.stack\n\t\t});\n\t\tspan.setStatus({\n\t\t\tcode: SpanStatusCode.ERROR,\n\t\t\tmessage: error.message\n\t\t});\n\t} else span.setStatus({ code: SpanStatusCode.ERROR });\n}\nfunction isPrimitiveAttributeValue(value) {\n\treturn typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\";\n}\nfunction sanitizeAttributeValue(value) {\n\tif (!Array.isArray(value)) return value;\n\tconst primitiveTypes = new Set(value.filter(isPrimitiveAttributeValue).map((item) => typeof item));\n\tif (primitiveTypes.size !== 1) return;\n\tconst [primitiveType] = primitiveTypes;\n\tif (primitiveType === \"string\") return value.filter((item) => typeof item === \"string\");\n\tif (primitiveType === \"number\") return value.filter((item) => typeof item === \"number\");\n\treturn value.filter((item) => typeof item === \"boolean\");\n}\nasync function selectTelemetryAttributes({ telemetry, attributes }) {\n\tif ((telemetry == null ? void 0 : telemetry.isEnabled) !== true) return {};\n\tconst resultAttributes = {};\n\tfor (const [key, value] of Object.entries(attributes)) {\n\t\tif (value == null) continue;\n\t\tif (typeof value === \"object\" && \"input\" in value && typeof value.input === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordInputs) === false) continue;\n\t\t\tconst result = await value.input();\n\t\t\tif (result != null) {\n\t\t\t\tconst sanitized2 = sanitizeAttributeValue(result);\n\t\t\t\tif (sanitized2 != null) resultAttributes[key] = sanitized2;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (typeof value === \"object\" && \"output\" in value && typeof value.output === \"function\") {\n\t\t\tif ((telemetry == null ? void 0 : telemetry.recordOutputs) === false) continue;\n\t\t\tconst result = await value.output();\n\t\t\tif (result != null) {\n\t\t\t\tconst sanitized2 = sanitizeAttributeValue(result);\n\t\t\t\tif (sanitized2 != null) resultAttributes[key] = sanitized2;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tconst sanitized = sanitizeAttributeValue(value);\n\t\tif (sanitized != null) resultAttributes[key] = sanitized;\n\t}\n\treturn resultAttributes;\n}\nfunction stringifyForTelemetry(prompt) {\n\treturn JSON.stringify(prompt.map((message) => ({\n\t\t...message,\n\t\tcontent: typeof message.content === \"string\" ? message.content : message.content.map((part) => part.type === \"file\" ? {\n\t\t\t...part,\n\t\t\tdata: part.data instanceof Uint8Array ? convertDataContentToBase64String(part.data) : part.data\n\t\t} : part)\n\t})));\n}\nfunction registerTelemetryIntegration(integration) {\n\tif (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n\tglobalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(integration);\n}\nfunction getGlobalTelemetryIntegrations() {\n\tvar _a23;\n\treturn (_a23 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a23 : [];\n}\nfunction bindTelemetryIntegration(integration) {\n\tvar _a23, _b, _c, _d, _e, _f;\n\treturn {\n\t\tonStart: (_a23 = integration.onStart) == null ? void 0 : _a23.bind(integration),\n\t\tonStepStart: (_b = integration.onStepStart) == null ? void 0 : _b.bind(integration),\n\t\tonToolCallStart: (_c = integration.onToolCallStart) == null ? void 0 : _c.bind(integration),\n\t\tonToolCallFinish: (_d = integration.onToolCallFinish) == null ? void 0 : _d.bind(integration),\n\t\tonStepFinish: (_e = integration.onStepFinish) == null ? void 0 : _e.bind(integration),\n\t\tonFinish: (_f = integration.onFinish) == null ? void 0 : _f.bind(integration)\n\t};\n}\nfunction getGlobalTelemetryIntegration() {\n\tconst globalIntegrations = getGlobalTelemetryIntegrations();\n\treturn (integrations) => {\n\t\tconst localIntegrations = asArray(integrations);\n\t\tconst allIntegrations = [...globalIntegrations, ...localIntegrations];\n\t\tfunction createTelemetryComposite(getListenerFromIntegration) {\n\t\t\tconst listeners = allIntegrations.map(getListenerFromIntegration).filter(Boolean);\n\t\t\treturn async (event) => {\n\t\t\t\tfor (const listener of listeners) try {\n\t\t\t\t\tawait listener(event);\n\t\t\t\t} catch (_ignored) {}\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tonStart: createTelemetryComposite((integration) => integration.onStart),\n\t\t\tonStepStart: createTelemetryComposite((integration) => integration.onStepStart),\n\t\t\tonToolCallStart: createTelemetryComposite((integration) => integration.onToolCallStart),\n\t\t\tonToolCallFinish: createTelemetryComposite((integration) => integration.onToolCallFinish),\n\t\t\tonStepFinish: createTelemetryComposite((integration) => integration.onStepFinish),\n\t\t\tonFinish: createTelemetryComposite((integration) => integration.onFinish)\n\t\t};\n\t};\n}\nfunction asLanguageModelUsage(usage) {\n\treturn {\n\t\tinputTokens: usage.inputTokens.total,\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: usage.inputTokens.noCache,\n\t\t\tcacheReadTokens: usage.inputTokens.cacheRead,\n\t\t\tcacheWriteTokens: usage.inputTokens.cacheWrite\n\t\t},\n\t\toutputTokens: usage.outputTokens.total,\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: usage.outputTokens.text,\n\t\t\treasoningTokens: usage.outputTokens.reasoning\n\t\t},\n\t\ttotalTokens: addTokenCounts(usage.inputTokens.total, usage.outputTokens.total),\n\t\traw: usage.raw,\n\t\treasoningTokens: usage.outputTokens.reasoning,\n\t\tcachedInputTokens: usage.inputTokens.cacheRead\n\t};\n}\nfunction createNullLanguageModelUsage() {\n\treturn {\n\t\tinputTokens: void 0,\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: void 0,\n\t\t\tcacheReadTokens: void 0,\n\t\t\tcacheWriteTokens: void 0\n\t\t},\n\t\toutputTokens: void 0,\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: void 0,\n\t\t\treasoningTokens: void 0\n\t\t},\n\t\ttotalTokens: void 0,\n\t\traw: void 0\n\t};\n}\nfunction addLanguageModelUsage(usage1, usage2) {\n\tvar _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n\tconst raw = isNullLanguageModelUsage(usage1) ? usage2.raw : isNullLanguageModelUsage(usage2) ? usage1.raw : void 0;\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: addTokenCounts((_a23 = usage1.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens, (_b = usage2.inputTokenDetails) == null ? void 0 : _b.noCacheTokens),\n\t\t\tcacheReadTokens: addTokenCounts((_c = usage1.inputTokenDetails) == null ? void 0 : _c.cacheReadTokens, (_d = usage2.inputTokenDetails) == null ? void 0 : _d.cacheReadTokens),\n\t\t\tcacheWriteTokens: addTokenCounts((_e = usage1.inputTokenDetails) == null ? void 0 : _e.cacheWriteTokens, (_f = usage2.inputTokenDetails) == null ? void 0 : _f.cacheWriteTokens)\n\t\t},\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\toutputTokenDetails: {\n\t\t\ttextTokens: addTokenCounts((_g = usage1.outputTokenDetails) == null ? void 0 : _g.textTokens, (_h = usage2.outputTokenDetails) == null ? void 0 : _h.textTokens),\n\t\t\treasoningTokens: addTokenCounts((_i = usage1.outputTokenDetails) == null ? void 0 : _i.reasoningTokens, (_j = usage2.outputTokenDetails) == null ? void 0 : _j.reasoningTokens)\n\t\t},\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens),\n\t\treasoningTokens: addTokenCounts(usage1.reasoningTokens, usage2.reasoningTokens),\n\t\tcachedInputTokens: addTokenCounts(usage1.cachedInputTokens, usage2.cachedInputTokens),\n\t\t...raw == null ? {} : { raw }\n\t};\n}\nfunction isNullLanguageModelUsage(usage) {\n\tvar _a23, _b, _c, _d, _e;\n\treturn usage.inputTokens == null && ((_a23 = usage.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens) == null && ((_b = usage.inputTokenDetails) == null ? void 0 : _b.cacheReadTokens) == null && ((_c = usage.inputTokenDetails) == null ? void 0 : _c.cacheWriteTokens) == null && usage.outputTokens == null && ((_d = usage.outputTokenDetails) == null ? void 0 : _d.textTokens) == null && ((_e = usage.outputTokenDetails) == null ? void 0 : _e.reasoningTokens) == null && usage.totalTokens == null && usage.raw == null;\n}\nfunction addTokenCounts(tokenCount1, tokenCount2) {\n\treturn tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);\n}\nfunction addImageModelUsage(usage1, usage2) {\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\toutputTokens: addTokenCounts(usage1.outputTokens, usage2.outputTokens),\n\t\ttotalTokens: addTokenCounts(usage1.totalTokens, usage2.totalTokens)\n\t};\n}\nfunction getRetryDelayInMs({ error, exponentialBackoffDelay }) {\n\tconst headers = APICallError.isInstance(error) ? error.responseHeaders : APICallError.isInstance(error.cause) ? error.cause.responseHeaders : void 0;\n\tif (!headers) return exponentialBackoffDelay;\n\tlet ms;\n\tconst retryAfterMs = headers[\"retry-after-ms\"];\n\tif (retryAfterMs) {\n\t\tconst timeoutMs = parseFloat(retryAfterMs);\n\t\tif (!Number.isNaN(timeoutMs)) ms = timeoutMs;\n\t}\n\tconst retryAfter = headers[\"retry-after\"];\n\tif (retryAfter && ms === void 0) {\n\t\tconst timeoutSeconds = parseFloat(retryAfter);\n\t\tif (!Number.isNaN(timeoutSeconds)) ms = timeoutSeconds * 1e3;\n\t\telse ms = Date.parse(retryAfter) - Date.now();\n\t}\n\tif (ms != null && !Number.isNaN(ms) && 0 <= ms && (ms < 6e4 || ms < exponentialBackoffDelay)) return ms;\n\treturn exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal, additionalRetryableError } = {}) => retryWithExponentialBackoff({\n\tmaxRetries,\n\tinitialDelayInMs,\n\tbackoffFactor,\n\tabortSignal,\n\tshouldRetry: async (error) => error instanceof Error && (APICallError.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true) || additionalRetryableError != null && await additionalRetryableError(error),\n\tgetDelayInMs: ({ error, exponentialBackoffDelay }) => getRetryDelayInMs({\n\t\terror,\n\t\texponentialBackoffDelay\n\t}),\n\tcreateRetryError: ({ message, reason, errors }) => new RetryError({\n\t\tmessage,\n\t\treason,\n\t\terrors\n\t})\n});\nfunction prepareRetries({ maxRetries, abortSignal, additionalRetryableError }) {\n\tif (maxRetries != null) {\n\t\tif (!Number.isInteger(maxRetries)) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be an integer\"\n\t\t});\n\t\tif (maxRetries < 0) throw new InvalidArgumentError({\n\t\t\tparameter: \"maxRetries\",\n\t\t\tvalue: maxRetries,\n\t\t\tmessage: \"maxRetries must be >= 0\"\n\t\t});\n\t}\n\tconst maxRetriesResult = maxRetries != null ? maxRetries : 2;\n\treturn {\n\t\tmaxRetries: maxRetriesResult,\n\t\tretry: retryWithExponentialBackoffRespectingRetryHeaders({\n\t\t\tmaxRetries: maxRetriesResult,\n\t\t\tabortSignal,\n\t\t\tadditionalRetryableError\n\t\t})\n\t};\n}\nfunction setAbortTimeout({ abortController, label, timeoutMs }) {\n\tif (abortController == null || timeoutMs == null) return;\n\treturn setTimeout(() => abortController.abort(new DOMException(`${label} timeout of ${timeoutMs}ms exceeded`, \"TimeoutError\")), timeoutMs);\n}\nfunction collectToolApprovals({ messages }) {\n\tconst lastMessage = messages.at(-1);\n\tif ((lastMessage == null ? void 0 : lastMessage.role) != \"tool\") return {\n\t\tapprovedToolApprovals: [],\n\t\tdeniedToolApprovals: []\n\t};\n\tconst toolCallsByToolCallId = {};\n\tfor (const message of messages) if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n\t\tconst content = message.content;\n\t\tfor (const part of content) if (part.type === \"tool-call\") toolCallsByToolCallId[part.toolCallId] = part;\n\t}\n\tconst toolApprovalRequestsByApprovalId = {};\n\tfor (const message of messages) if (message.role === \"assistant\" && typeof message.content !== \"string\") {\n\t\tconst content = message.content;\n\t\tfor (const part of content) if (part.type === \"tool-approval-request\") toolApprovalRequestsByApprovalId[part.approvalId] = part;\n\t}\n\tconst toolResults = {};\n\tfor (const part of lastMessage.content) if (part.type === \"tool-result\") toolResults[part.toolCallId] = part;\n\tconst approvedToolApprovals = [];\n\tconst deniedToolApprovals = [];\n\tconst collectedToolCallIds = /* @__PURE__ */ new Set();\n\tconst approvalResponses = lastMessage.content.filter((part) => part.type === \"tool-approval-response\");\n\tfor (const approvalResponse of approvalResponses) {\n\t\tconst approvalRequest = toolApprovalRequestsByApprovalId[approvalResponse.approvalId];\n\t\tif (approvalRequest == null) throw new InvalidToolApprovalError({ approvalId: approvalResponse.approvalId });\n\t\tif (toolResults[approvalRequest.toolCallId] != null) continue;\n\t\tconst toolCall = toolCallsByToolCallId[approvalRequest.toolCallId];\n\t\tif (toolCall == null) throw new ToolCallNotFoundForApprovalError({\n\t\t\ttoolCallId: approvalRequest.toolCallId,\n\t\t\tapprovalId: approvalRequest.approvalId\n\t\t});\n\t\tif (collectedToolCallIds.has(toolCall.toolCallId)) continue;\n\t\tcollectedToolCallIds.add(toolCall.toolCallId);\n\t\tconst approval = {\n\t\t\tapprovalRequest,\n\t\t\tapprovalResponse,\n\t\t\ttoolCall\n\t\t};\n\t\tif (approvalResponse.approved) approvedToolApprovals.push(approval);\n\t\telse deniedToolApprovals.push(approval);\n\t}\n\treturn {\n\t\tapprovedToolApprovals,\n\t\tdeniedToolApprovals\n\t};\n}\nfunction now() {\n\tvar _a23, _b;\n\treturn (_b = (_a23 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a23.now()) != null ? _b : Date.now();\n}\nasync function executeToolCall({ toolCall, tools, tracer, telemetry, messages, abortSignal, experimental_context, stepNumber, model, onPreliminaryToolResult, onToolCallStart, onToolCallFinish }) {\n\tvar _a23;\n\tconst { toolName, toolCallId, input } = toolCall;\n\tconst tool2 = tools == null ? void 0 : tools[toolName];\n\tif ((tool2 == null ? void 0 : tool2.execute) == null) return;\n\tconst baseCallbackEvent = {\n\t\tstepNumber,\n\t\tmodel,\n\t\ttoolCall,\n\t\tmessages,\n\t\tabortSignal,\n\t\tfunctionId: telemetry == null ? void 0 : telemetry.functionId,\n\t\tmetadata: telemetry == null ? void 0 : telemetry.metadata,\n\t\texperimental_context\n\t};\n\treturn recordSpan({\n\t\tname: \"ai.toolCall\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.toolCall\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...Object.fromEntries(Object.entries((_a23 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a23 : {}).map(([key, value]) => [`ai.telemetry.metadata.${key}`, value])),\n\t\t\t\t\"ai.toolCall.name\": toolName,\n\t\t\t\t\"ai.toolCall.id\": toolCallId,\n\t\t\t\t\"ai.toolCall.args\": { output: () => JSON.stringify(input) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tlet output;\n\t\t\tawait notify({\n\t\t\t\tevent: baseCallbackEvent,\n\t\t\t\tcallbacks: onToolCallStart\n\t\t\t});\n\t\t\tconst startTime = now();\n\t\t\ttry {\n\t\t\t\tconst stream = executeTool({\n\t\t\t\t\texecute: tool2.execute.bind(tool2),\n\t\t\t\t\tinput,\n\t\t\t\t\toptions: {\n\t\t\t\t\t\ttoolCallId,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tfor await (const part of stream) if (part.type === \"preliminary\") onPreliminaryToolResult?.({\n\t\t\t\t\t...toolCall,\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\toutput: part.output,\n\t\t\t\t\tpreliminary: true\n\t\t\t\t});\n\t\t\t\telse output = part.output;\n\t\t\t} catch (error) {\n\t\t\t\tconst durationMs2 = now() - startTime;\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\t...baseCallbackEvent,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tdurationMs: durationMs2\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: onToolCallFinish\n\t\t\t\t});\n\t\t\t\trecordErrorOnSpan(span, error);\n\t\t\t\treturn {\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId,\n\t\t\t\t\ttoolName,\n\t\t\t\t\tinput,\n\t\t\t\t\terror,\n\t\t\t\t\tdynamic: tool2.type === \"dynamic\",\n\t\t\t\t\t...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n\t\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t};\n\t\t\t}\n\t\t\tconst durationMs = now() - startTime;\n\t\t\tawait notify({\n\t\t\t\tevent: {\n\t\t\t\t\t...baseCallbackEvent,\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\toutput,\n\t\t\t\t\tdurationMs\n\t\t\t\t},\n\t\t\t\tcallbacks: onToolCallFinish\n\t\t\t});\n\t\t\ttry {\n\t\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: { \"ai.toolCall.result\": { output: () => JSON.stringify(output) } }\n\t\t\t\t}));\n\t\t\t} catch (ignored) {}\n\t\t\treturn {\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId,\n\t\t\t\ttoolName,\n\t\t\t\tinput,\n\t\t\t\toutput,\n\t\t\t\tdynamic: tool2.type === \"dynamic\",\n\t\t\t\t...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t};\n\t\t}\n\t});\n}\nfunction extractReasoningContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"reasoning\");\n\treturn parts.length === 0 ? void 0 : parts.map((content2) => content2.text).join(\"\\n\");\n}\nfunction extractTextContent(content) {\n\tconst parts = content.filter((content2) => content2.type === \"text\");\n\tif (parts.length === 0) return;\n\treturn parts.map((content2) => content2.text).join(\"\");\n}\nfunction filterActiveTools({ tools, activeTools }) {\n\tif (tools == null || activeTools == null) return tools;\n\treturn Object.fromEntries(Object.entries(tools).filter(([name23]) => activeTools.includes(name23)));\n}\nvar DefaultGeneratedFile = class {\n\tconstructor({ data, mediaType }) {\n\t\tthis.base64Data = typeof data === \"string\" ? data : void 0;\n\t\tthis.uint8ArrayData = typeof data === \"string\" ? void 0 : convertDataContentToUint8Array(data);\n\t\tthis.mediaType = mediaType;\n\t}\n\tget base64() {\n\t\tif (this.base64Data == null) this.base64Data = convertUint8ArrayToBase64(this.uint8ArrayData);\n\t\treturn this.base64Data;\n\t}\n\tget uint8Array() {\n\t\tif (this.uint8ArrayData == null) this.uint8ArrayData = convertBase64ToUint8Array(this.base64Data);\n\t\treturn this.uint8ArrayData;\n\t}\n};\nvar DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {\n\tconstructor() {\n\t\tsuper(...arguments);\n\t\tthis.type = \"file\";\n\t}\n};\nasync function isApprovalNeeded({ tool: tool2, toolCall, messages, experimental_context }) {\n\tif (tool2.needsApproval == null) return false;\n\tif (typeof tool2.needsApproval === \"boolean\") return tool2.needsApproval;\n\treturn await tool2.needsApproval(toolCall.input, {\n\t\ttoolCallId: toolCall.toolCallId,\n\t\tmessages,\n\t\texperimental_context\n\t});\n}\nfunction isToolExecutionAllowedFinishReason(finishReason) {\n\treturn finishReason === \"stop\" || finishReason === \"tool-calls\";\n}\nvar encoder = new TextEncoder();\nfunction canonicalJSON(value) {\n\tif (value === null || value === void 0) return JSON.stringify(value);\n\tif (typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) return `[${value.map(canonicalJSON).join(\",\")}]`;\n\treturn `{${Object.keys(value).sort().map((k) => `${JSON.stringify(k)}:${canonicalJSON(value[k])}`).join(\",\")}}`;\n}\nfunction toBase64url(bytes) {\n\treturn convertUint8ArrayToBase64(bytes).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/g, \"\");\n}\nfunction fromBase64url(str) {\n\treturn convertBase64ToUint8Array(str);\n}\nasync function importKey(secret) {\n\tconst keyData = typeof secret === \"string\" ? encoder.encode(secret) : secret;\n\treturn crypto.subtle.importKey(\"raw\", keyData, {\n\t\tname: \"HMAC\",\n\t\thash: \"SHA-256\"\n\t}, false, [\"sign\", \"verify\"]);\n}\nasync function hashInput(input) {\n\tconst canonical = canonicalJSON(input);\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", encoder.encode(canonical));\n\treturn toBase64url(new Uint8Array(digest));\n}\nfunction buildPayload(approvalId, toolCallId, toolName, inputDigest) {\n\treturn encoder.encode(`${approvalId}\n${toolCallId}\n${toolName}\n${inputDigest}`);\n}\nasync function signToolApproval({ secret, approvalId, toolCallId, toolName, input }) {\n\tconst key = await importKey(secret);\n\tconst payload = buildPayload(approvalId, toolCallId, toolName, await hashInput(input));\n\tconst sig = await crypto.subtle.sign(\"HMAC\", key, payload);\n\treturn toBase64url(new Uint8Array(sig));\n}\nasync function verifyToolApprovalSignature({ secret, signature, approvalId, toolCallId, toolName, input }) {\n\tconst key = await importKey(secret);\n\tconst payload = buildPayload(approvalId, toolCallId, toolName, await hashInput(input));\n\tconst sigBytes = fromBase64url(signature);\n\treturn crypto.subtle.verify(\"HMAC\", key, sigBytes, payload);\n}\nasync function maybeSignApproval({ secret, approvalId, toolCallId, toolName, input }) {\n\tif (secret == null) return void 0;\n\treturn signToolApproval({\n\t\tsecret,\n\t\tapprovalId,\n\t\ttoolCallId,\n\t\ttoolName,\n\t\tinput\n\t});\n}\nfunction isDeepEqualData(obj1, obj2) {\n\tif (obj1 === obj2) return true;\n\tif (obj1 == null || obj2 == null) return false;\n\tif (typeof obj1 !== \"object\" && typeof obj2 !== \"object\") return obj1 === obj2;\n\tif (obj1.constructor !== obj2.constructor) return false;\n\tif (obj1 instanceof Date && obj2 instanceof Date) return obj1.getTime() === obj2.getTime();\n\tif (Array.isArray(obj1)) {\n\t\tif (obj1.length !== obj2.length) return false;\n\t\tfor (let i = 0; i < obj1.length; i++) if (!isDeepEqualData(obj1[i], obj2[i])) return false;\n\t\treturn true;\n\t}\n\tconst keys1 = Object.keys(obj1);\n\tconst keys2 = Object.keys(obj2);\n\tif (keys1.length !== keys2.length) return false;\n\tfor (const key of keys1) {\n\t\tif (!keys2.includes(key)) return false;\n\t\tif (!isDeepEqualData(obj1[key], obj2[key])) return false;\n\t}\n\treturn true;\n}\nasync function validateApprovedToolApprovals({ approvedToolApprovals, tools, messages, experimental_context, toolApprovalSecret }) {\n\tvar _a23;\n\tconst approved = [];\n\tconst denied = [];\n\tconst invalid = [];\n\tfor (const approval of approvedToolApprovals) {\n\t\tconst { toolCall, approvalRequest } = approval;\n\t\tconst tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n\t\tif (toolApprovalSecret != null) {\n\t\t\tif (approvalRequest.signature == null) throw new InvalidToolApprovalSignatureError({\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\treason: \"missing signature\"\n\t\t\t});\n\t\t\tif (!await verifyToolApprovalSignature({\n\t\t\t\tsecret: toolApprovalSecret,\n\t\t\t\tsignature: approvalRequest.signature,\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\tinput: toolCall.input\n\t\t\t})) throw new InvalidToolApprovalSignatureError({\n\t\t\t\tapprovalId: approvalRequest.approvalId,\n\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\treason: \"invalid signature\"\n\t\t\t});\n\t\t}\n\t\tif (tool2 != null && typeof tool2.execute === \"function\" && tool2.inputSchema != null) {\n\t\t\tconst hasInputSchemaInput = Object.prototype.hasOwnProperty.call(approvalRequest, \"inputSchemaInput\");\n\t\t\tconst validation = await safeValidateTypes({\n\t\t\t\tvalue: hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input,\n\t\t\t\tschema: asSchema(tool2.inputSchema)\n\t\t\t});\n\t\t\tlet validationError;\n\t\t\tif (!validation.success) validationError = validation.error;\n\t\t\telse if (!isDeepEqualData(validation.value, toolCall.input)) validationError = /* @__PURE__ */ new Error(\"Approved tool input does not match the validated schema output.\");\n\t\t\tif (validationError != null) {\n\t\t\t\tinvalid.push({\n\t\t\t\t\t...approval,\n\t\t\t\t\terror: new InvalidToolInputError({\n\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\ttoolInput: JSON.stringify(toolCall.input),\n\t\t\t\t\t\tcause: validationError\n\t\t\t\t\t})\n\t\t\t\t});\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tif (tool2 != null && await isApprovalNeeded({\n\t\t\ttool: tool2,\n\t\t\ttoolCall,\n\t\t\tmessages,\n\t\t\texperimental_context\n\t\t})) approved.push(approval);\n\t\telse denied.push({\n\t\t\t...approval,\n\t\t\tapprovalResponse: {\n\t\t\t\t...approval.approvalResponse,\n\t\t\t\tapproved: false,\n\t\t\t\treason: (_a23 = approval.approvalResponse.reason) != null ? _a23 : `Tool \"${toolCall.toolName}\" does not require approval`\n\t\t\t}\n\t\t});\n\t}\n\treturn {\n\t\tapprovedToolApprovals: approved,\n\t\tdeniedToolApprovals: denied,\n\t\tinvalidToolApprovals: invalid\n\t};\n}\nvar output_exports = {};\n__export(output_exports, {\n\tarray: () => array,\n\tchoice: () => choice,\n\tjson: () => json,\n\tobject: () => object,\n\ttext: () => text\n});\nfunction fixJson(input) {\n\tconst stack = [\"ROOT\"];\n\tlet lastValidIndex = -1;\n\tlet literalStart = null;\n\tlet unicodeEscapeDigits = 0;\n\tfunction isHexDigit(char) {\n\t\treturn char >= \"0\" && char <= \"9\" || char >= \"A\" && char <= \"F\" || char >= \"a\" && char <= \"f\";\n\t}\n\tfunction processValueStart(char, i, swapState) {\n\t\tswitch (char) {\n\t\t\tcase \"\\\"\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_STRING\");\n\t\t\t\tbreak;\n\t\t\tcase \"f\":\n\t\t\tcase \"t\":\n\t\t\tcase \"n\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tliteralStart = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_LITERAL\");\n\t\t\t\tbreak;\n\t\t\tcase \"-\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"0\":\n\t\t\tcase \"1\":\n\t\t\tcase \"2\":\n\t\t\tcase \"3\":\n\t\t\tcase \"4\":\n\t\t\tcase \"5\":\n\t\t\tcase \"6\":\n\t\t\tcase \"7\":\n\t\t\tcase \"8\":\n\t\t\tcase \"9\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_NUMBER\");\n\t\t\t\tbreak;\n\t\t\tcase \"{\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_OBJECT_START\");\n\t\t\t\tbreak;\n\t\t\tcase \"[\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(swapState);\n\t\t\t\tstack.push(\"INSIDE_ARRAY_START\");\n\t\t}\n\t}\n\tfunction processAfterObjectValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"}\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t}\n\t}\n\tfunction processAfterArrayValue(char, i) {\n\t\tswitch (char) {\n\t\t\tcase \",\":\n\t\t\t\tstack.pop();\n\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\tbreak;\n\t\t\tcase \"]\":\n\t\t\t\tlastValidIndex = i;\n\t\t\t\tstack.pop();\n\t\t}\n\t}\n\tfor (let i = 0; i < input.length; i++) {\n\t\tconst char = input[i];\n\t\tswitch (stack[stack.length - 1]) {\n\t\t\tcase \"ROOT\":\n\t\t\t\tprocessValueStart(char, i, \"FINISH\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_KEY\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_AFTER_KEY\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \":\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_OBJECT_BEFORE_VALUE\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_OBJECT_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\t\tprocessAfterObjectValue(char, i);\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"\\\"\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"\\\\\":\n\t\t\t\t\t\tstack.push(\"INSIDE_STRING_ESCAPE\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_START\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tstack.push(\"INSIDE_ARRAY_AFTER_COMMA\");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: lastValidIndex = i;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\t\t\tprocessValueStart(char, i, \"INSIDE_ARRAY_AFTER_VALUE\");\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_ESCAPE\":\n\t\t\t\tstack.pop();\n\t\t\t\tif (char === \"u\") {\n\t\t\t\t\tunicodeEscapeDigits = 0;\n\t\t\t\t\tstack.push(\"INSIDE_STRING_UNICODE_ESCAPE\");\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_STRING_UNICODE_ESCAPE\":\n\t\t\t\tif (isHexDigit(char)) {\n\t\t\t\t\tunicodeEscapeDigits++;\n\t\t\t\t\tif (unicodeEscapeDigits === 4) {\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_NUMBER\":\n\t\t\t\tswitch (char) {\n\t\t\t\t\tcase \"0\":\n\t\t\t\t\tcase \"1\":\n\t\t\t\t\tcase \"2\":\n\t\t\t\t\tcase \"3\":\n\t\t\t\t\tcase \"4\":\n\t\t\t\t\tcase \"5\":\n\t\t\t\t\tcase \"6\":\n\t\t\t\t\tcase \"7\":\n\t\t\t\t\tcase \"8\":\n\t\t\t\t\tcase \"9\":\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"e\":\n\t\t\t\t\tcase \"E\":\n\t\t\t\t\tcase \"-\":\n\t\t\t\t\tcase \".\": break;\n\t\t\t\t\tcase \",\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"}\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"]\":\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault: stack.pop();\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\tcase \"INSIDE_LITERAL\": {\n\t\t\t\tconst partialLiteral = input.substring(literalStart, i + 1);\n\t\t\t\tif (!\"false\".startsWith(partialLiteral) && !\"true\".startsWith(partialLiteral) && !\"null\".startsWith(partialLiteral)) {\n\t\t\t\t\tstack.pop();\n\t\t\t\t\tif (stack[stack.length - 1] === \"INSIDE_OBJECT_AFTER_VALUE\") processAfterObjectValue(char, i);\n\t\t\t\t\telse if (stack[stack.length - 1] === \"INSIDE_ARRAY_AFTER_VALUE\") processAfterArrayValue(char, i);\n\t\t\t\t} else lastValidIndex = i;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tlet result = input.slice(0, lastValidIndex + 1);\n\tfor (let i = stack.length - 1; i >= 0; i--) switch (stack[i]) {\n\t\tcase \"INSIDE_STRING\":\n\t\t\tresult += \"\\\"\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_OBJECT_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_KEY\":\n\t\tcase \"INSIDE_OBJECT_AFTER_COMMA\":\n\t\tcase \"INSIDE_OBJECT_START\":\n\t\tcase \"INSIDE_OBJECT_BEFORE_VALUE\":\n\t\tcase \"INSIDE_OBJECT_AFTER_VALUE\":\n\t\t\tresult += \"}\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_ARRAY_START\":\n\t\tcase \"INSIDE_ARRAY_AFTER_COMMA\":\n\t\tcase \"INSIDE_ARRAY_AFTER_VALUE\":\n\t\t\tresult += \"]\";\n\t\t\tbreak;\n\t\tcase \"INSIDE_LITERAL\": {\n\t\t\tconst partialLiteral = input.substring(literalStart, input.length);\n\t\t\tif (\"true\".startsWith(partialLiteral)) result += \"true\".slice(partialLiteral.length);\n\t\t\telse if (\"false\".startsWith(partialLiteral)) result += \"false\".slice(partialLiteral.length);\n\t\t\telse if (\"null\".startsWith(partialLiteral)) result += \"null\".slice(partialLiteral.length);\n\t\t}\n\t}\n\treturn result;\n}\nasync function parsePartialJson(jsonText) {\n\tif (jsonText === void 0) return {\n\t\tvalue: void 0,\n\t\tstate: \"undefined-input\"\n\t};\n\tlet result = await safeParseJSON({ text: jsonText });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"successful-parse\"\n\t};\n\tresult = await safeParseJSON({ text: fixJson(jsonText) });\n\tif (result.success) return {\n\t\tvalue: result.value,\n\t\tstate: \"repaired-parse\"\n\t};\n\treturn {\n\t\tvalue: void 0,\n\t\tstate: \"failed-parse\"\n\t};\n}\nvar text = () => ({\n\tname: \"text\",\n\tresponseFormat: Promise.resolve({ type: \"text\" }),\n\tasync parseCompleteOutput({ text: text2 }) {\n\t\treturn text2;\n\t},\n\tasync parsePartialOutput({ text: text2 }) {\n\t\treturn { partial: text2 };\n\t},\n\tcreateElementStreamTransform() {}\n});\nvar object = ({ schema: inputSchema, name: name23, description }) => {\n\tconst schema = asSchema(inputSchema);\n\treturn {\n\t\tname: \"object\",\n\t\tresponseFormat: resolve(schema.jsonSchema).then((jsonSchema2) => ({\n\t\t\ttype: \"json\",\n\t\t\tschema: jsonSchema2,\n\t\t\t...name23 != null && { name: name23 },\n\t\t\t...description != null && { description }\n\t\t})),\n\t\tasync parseCompleteOutput({ text: text2 }, context2) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\tvalue: parseResult.value,\n\t\t\t\tschema\n\t\t\t});\n\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: validationResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\treturn validationResult.value;\n\t\t},\n\t\tasync parsePartialOutput({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return { partial: result.value };\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\nvar array = ({ element: inputElementSchema, name: name23, description }) => {\n\tconst elementSchema = asSchema(inputElementSchema);\n\treturn {\n\t\tname: \"array\",\n\t\tresponseFormat: resolve(elementSchema.jsonSchema).then((jsonSchema2) => {\n\t\t\tconst { $schema, ...itemSchema } = jsonSchema2;\n\t\t\treturn {\n\t\t\t\ttype: \"json\",\n\t\t\t\tschema: {\n\t\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\t\ttype: \"object\",\n\t\t\t\t\tproperties: { elements: {\n\t\t\t\t\t\ttype: \"array\",\n\t\t\t\t\t\titems: itemSchema\n\t\t\t\t\t} },\n\t\t\t\t\trequired: [\"elements\"],\n\t\t\t\t\tadditionalProperties: false\n\t\t\t\t},\n\t\t\t\t...name23 != null && { name: name23 },\n\t\t\t\t...description != null && { description }\n\t\t\t};\n\t\t}),\n\t\tasync parseCompleteOutput({ text: text2 }, context2) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\tconst outerValue = parseResult.value;\n\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: new TypeValidationError({\n\t\t\t\t\tvalue: outerValue,\n\t\t\t\t\tcause: \"response must be an object with an elements array\"\n\t\t\t\t}),\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\tconst validatedElements = [];\n\t\t\tfor (const element of outerValue.elements) {\n\t\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema: elementSchema\n\t\t\t\t});\n\t\t\t\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\t\tcause: validationResult.error,\n\t\t\t\t\ttext: text2,\n\t\t\t\t\tresponse: context2.response,\n\t\t\t\t\tusage: context2.usage,\n\t\t\t\t\tfinishReason: context2.finishReason\n\t\t\t\t});\n\t\t\t\tvalidatedElements.push(validationResult.value);\n\t\t\t}\n\t\t\treturn validatedElements;\n\t\t},\n\t\tasync parsePartialOutput({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": {\n\t\t\t\t\tconst outerValue = result.value;\n\t\t\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"elements\" in outerValue) || !Array.isArray(outerValue.elements)) return;\n\t\t\t\t\tconst rawElements = result.state === \"repaired-parse\" && outerValue.elements.length > 0 ? outerValue.elements.slice(0, -1) : outerValue.elements;\n\t\t\t\t\tconst parsedElements = [];\n\t\t\t\t\tfor (const rawElement of rawElements) {\n\t\t\t\t\t\tconst validationResult = await safeValidateTypes({\n\t\t\t\t\t\t\tvalue: rawElement,\n\t\t\t\t\t\t\tschema: elementSchema\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (validationResult.success) parsedElements.push(validationResult.value);\n\t\t\t\t\t}\n\t\t\t\t\treturn { partial: parsedElements };\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\t\tif (partialOutput != null) for (; publishedElements < partialOutput.length; publishedElements++) controller.enqueue(partialOutput[publishedElements]);\n\t\t\t} });\n\t\t}\n\t};\n};\nvar choice = ({ options: choiceOptions, name: name23, description }) => {\n\treturn {\n\t\tname: \"choice\",\n\t\tresponseFormat: Promise.resolve({\n\t\t\ttype: \"json\",\n\t\t\tschema: {\n\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { result: {\n\t\t\t\t\ttype: \"string\",\n\t\t\t\t\tenum: choiceOptions\n\t\t\t\t} },\n\t\t\t\trequired: [\"result\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t},\n\t\t\t...name23 != null && { name: name23 },\n\t\t\t...description != null && { description }\n\t\t}),\n\t\tasync parseCompleteOutput({ text: text2 }, context2) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\tconst outerValue = parseResult.value;\n\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\" || !choiceOptions.includes(outerValue.result)) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\tcause: new TypeValidationError({\n\t\t\t\t\tvalue: outerValue,\n\t\t\t\t\tcause: \"response must be an object that contains a choice value.\"\n\t\t\t\t}),\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\treturn outerValue.result;\n\t\t},\n\t\tasync parsePartialOutput({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": {\n\t\t\t\t\tconst outerValue = result.value;\n\t\t\t\t\tif (outerValue == null || typeof outerValue !== \"object\" || !(\"result\" in outerValue) || typeof outerValue.result !== \"string\") return;\n\t\t\t\t\tconst potentialMatches = choiceOptions.filter((choiceOption) => choiceOption.startsWith(outerValue.result));\n\t\t\t\t\tif (result.state === \"successful-parse\") return potentialMatches.includes(outerValue.result) ? { partial: outerValue.result } : void 0;\n\t\t\t\t\telse return potentialMatches.length === 1 ? { partial: potentialMatches[0] } : void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\nvar json = ({ name: name23, description } = {}) => {\n\treturn {\n\t\tname: \"json\",\n\t\tresponseFormat: Promise.resolve({\n\t\t\ttype: \"json\",\n\t\t\t...name23 != null && { name: name23 },\n\t\t\t...description != null && { description }\n\t\t}),\n\t\tasync parseCompleteOutput({ text: text2 }, context2) {\n\t\t\tconst parseResult = await safeParseJSON({ text: text2 });\n\t\t\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: could not parse the response.\",\n\t\t\t\tcause: parseResult.error,\n\t\t\t\ttext: text2,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t});\n\t\t\treturn parseResult.value;\n\t\t},\n\t\tasync parsePartialOutput({ text: text2 }) {\n\t\t\tconst result = await parsePartialJson(text2);\n\t\t\tswitch (result.state) {\n\t\t\t\tcase \"failed-parse\":\n\t\t\t\tcase \"undefined-input\": return;\n\t\t\t\tcase \"repaired-parse\":\n\t\t\t\tcase \"successful-parse\": return result.value === void 0 ? void 0 : { partial: result.value };\n\t\t\t}\n\t\t},\n\t\tcreateElementStreamTransform() {}\n\t};\n};\nvar inputSchemaInputSymbol = Symbol(\"ai-sdk-tool-call-input-schema-input\");\nfunction setToolCallInputSchemaInput(toolCall, inputSchemaInput) {\n\tObject.defineProperty(toolCall, inputSchemaInputSymbol, { value: inputSchemaInput });\n\treturn toolCall;\n}\nfunction getToolCallInputSchemaInput(toolCall) {\n\treturn inputSchemaInputSymbol in toolCall ? { value: toolCall[inputSchemaInputSymbol] } : void 0;\n}\nasync function parseToolCall({ toolCall, tools, repairToolCall, system, messages }) {\n\ttry {\n\t\tif (tools == null) {\n\t\t\tif (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall);\n\t\t\tthrow new NoSuchToolError({ toolName: toolCall.toolName });\n\t\t}\n\t\ttry {\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (repairToolCall == null || !(NoSuchToolError.isInstance(error) || InvalidToolInputError.isInstance(error))) throw error;\n\t\t\tlet repairedToolCall = null;\n\t\t\ttry {\n\t\t\t\trepairedToolCall = await repairToolCall({\n\t\t\t\t\ttoolCall,\n\t\t\t\t\ttools,\n\t\t\t\t\tinputSchema: async ({ toolName }) => {\n\t\t\t\t\t\tconst { inputSchema } = tools[toolName];\n\t\t\t\t\t\treturn await asSchema(inputSchema).jsonSchema;\n\t\t\t\t\t},\n\t\t\t\t\tsystem,\n\t\t\t\t\tmessages,\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t} catch (repairError) {\n\t\t\t\tthrow new ToolCallRepairError({\n\t\t\t\t\tcause: repairError,\n\t\t\t\t\toriginalError: error\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (repairedToolCall == null) throw error;\n\t\t\treturn await doParseToolCall({\n\t\t\t\ttoolCall: repairedToolCall,\n\t\t\t\ttools\n\t\t\t});\n\t\t}\n\t} catch (error) {\n\t\tconst parsedInput = await safeParseJSON({ text: toolCall.input });\n\t\tconst input = parsedInput.success ? parsedInput.value : toolCall.input;\n\t\tconst tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n\t\treturn {\n\t\t\ttype: \"tool-call\",\n\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tinput,\n\t\t\tdynamic: true,\n\t\t\tinvalid: true,\n\t\t\terror,\n\t\t\ttitle: tool2 == null ? void 0 : tool2.title,\n\t\t\tproviderExecuted: toolCall.providerExecuted,\n\t\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t\t...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n\t\t};\n\t}\n}\nasync function parseProviderExecutedDynamicToolCall(toolCall) {\n\tconst parseResult = toolCall.input.trim() === \"\" ? {\n\t\tsuccess: true,\n\t\tvalue: {}\n\t} : await safeParseJSON({ text: toolCall.input });\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName: toolCall.toolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: true,\n\t\tdynamic: true,\n\t\tproviderMetadata: toolCall.providerMetadata\n\t};\n}\nasync function doParseToolCall({ toolCall, tools }) {\n\tconst toolName = toolCall.toolName;\n\tconst tool2 = tools[toolName];\n\tif (tool2 == null) {\n\t\tif (toolCall.providerExecuted && toolCall.dynamic) return await parseProviderExecutedDynamicToolCall(toolCall);\n\t\tthrow new NoSuchToolError({\n\t\t\ttoolName: toolCall.toolName,\n\t\t\tavailableTools: Object.keys(tools)\n\t\t});\n\t}\n\tconst schema = asSchema(tool2.inputSchema);\n\tconst parseResult = toolCall.input.trim() === \"\" ? await safeValidateTypes({\n\t\tvalue: {},\n\t\tschema\n\t}) : await safeParseJSON({\n\t\ttext: toolCall.input,\n\t\tschema\n\t});\n\tif (parseResult.success === false) throw new InvalidToolInputError({\n\t\ttoolName,\n\t\ttoolInput: toolCall.input,\n\t\tcause: parseResult.error\n\t});\n\treturn setToolCallInputSchemaInput(tool2.type === \"dynamic\" ? {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {},\n\t\tdynamic: true,\n\t\ttitle: tool2.title\n\t} : {\n\t\ttype: \"tool-call\",\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName,\n\t\tinput: parseResult.value,\n\t\tproviderExecuted: toolCall.providerExecuted,\n\t\tproviderMetadata: toolCall.providerMetadata,\n\t\t...tool2.metadata != null ? { toolMetadata: tool2.metadata } : {},\n\t\ttitle: tool2.title\n\t}, parseResult.rawValue);\n}\nfunction prepareStepCallSettings({ callSettings, stepSettings }) {\n\tvar _a23, _b, _c, _d, _e, _f, _g, _h;\n\treturn prepareCallSettings({\n\t\tmaxOutputTokens: (_a23 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a23 : callSettings.maxOutputTokens,\n\t\ttemperature: (_b = stepSettings == null ? void 0 : stepSettings.temperature) != null ? _b : callSettings.temperature,\n\t\ttopP: (_c = stepSettings == null ? void 0 : stepSettings.topP) != null ? _c : callSettings.topP,\n\t\ttopK: (_d = stepSettings == null ? void 0 : stepSettings.topK) != null ? _d : callSettings.topK,\n\t\tpresencePenalty: (_e = stepSettings == null ? void 0 : stepSettings.presencePenalty) != null ? _e : callSettings.presencePenalty,\n\t\tfrequencyPenalty: (_f = stepSettings == null ? void 0 : stepSettings.frequencyPenalty) != null ? _f : callSettings.frequencyPenalty,\n\t\tstopSequences: (_g = stepSettings == null ? void 0 : stepSettings.stopSequences) != null ? _g : callSettings.stopSequences,\n\t\tseed: (_h = stepSettings == null ? void 0 : stepSettings.seed) != null ? _h : callSettings.seed\n\t});\n}\nvar DefaultStepResult = class {\n\tconstructor({ stepNumber, model, functionId, metadata, experimental_context, content, finishReason, rawFinishReason, usage, warnings, request, response, providerMetadata }) {\n\t\tthis.stepNumber = stepNumber;\n\t\tthis.model = model;\n\t\tthis.functionId = functionId;\n\t\tthis.metadata = metadata;\n\t\tthis.experimental_context = experimental_context;\n\t\tthis.content = content;\n\t\tthis.finishReason = finishReason;\n\t\tthis.rawFinishReason = rawFinishReason;\n\t\tthis.usage = usage;\n\t\tthis.warnings = warnings;\n\t\tthis.request = request;\n\t\tthis.response = response;\n\t\tthis.providerMetadata = providerMetadata;\n\t}\n\tget text() {\n\t\treturn this.content.filter((part) => part.type === \"text\").map((part) => part.text).join(\"\");\n\t}\n\tget reasoning() {\n\t\treturn this.content.filter((part) => part.type === \"reasoning\");\n\t}\n\tget reasoningText() {\n\t\treturn this.reasoning.length === 0 ? void 0 : this.reasoning.map((part) => part.text).join(\"\");\n\t}\n\tget files() {\n\t\treturn this.content.filter((part) => part.type === \"file\").map((part) => part.file);\n\t}\n\tget sources() {\n\t\treturn this.content.filter((part) => part.type === \"source\");\n\t}\n\tget toolCalls() {\n\t\treturn this.content.filter((part) => part.type === \"tool-call\");\n\t}\n\tget staticToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic !== true);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.toolCalls.filter((toolCall) => toolCall.dynamic === true);\n\t}\n\tget toolResults() {\n\t\treturn this.content.filter((part) => part.type === \"tool-result\");\n\t}\n\tget staticToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic !== true);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.toolResults.filter((toolResult) => toolResult.dynamic === true);\n\t}\n};\nfunction stepCountIs(stepCount) {\n\treturn ({ steps }) => steps.length === stepCount;\n}\nfunction isLoopFinished() {\n\treturn () => false;\n}\nfunction hasToolCall(toolName) {\n\treturn ({ steps }) => {\n\t\tvar _a23, _b, _c;\n\t\treturn (_c = (_b = (_a23 = steps[steps.length - 1]) == null ? void 0 : _a23.toolCalls) == null ? void 0 : _b.some((toolCall) => toolCall.toolName === toolName)) != null ? _c : false;\n\t};\n}\nasync function isStopConditionMet({ stopConditions, steps }) {\n\treturn (await Promise.all(stopConditions.map((condition) => condition({ steps })))).some((result) => result);\n}\nasync function toResponseMessages({ content: inputContent, tools }) {\n\tconst responseMessages = [];\n\tconst toolCallOrder = /* @__PURE__ */ new Map();\n\tconst content = [];\n\tfor (const part of inputContent) {\n\t\tif (part.type === \"source\") continue;\n\t\tif ((part.type === \"tool-result\" || part.type === \"tool-error\") && !part.providerExecuted) continue;\n\t\tif (part.type === \"text\" && part.text.length === 0) continue;\n\t\tswitch (part.type) {\n\t\t\tcase \"text\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: part.text,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"reasoning\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: part.text,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"file\":\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tdata: part.file.base64,\n\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool-call\":\n\t\t\t\tif (!toolCallOrder.has(part.toolCallId)) toolCallOrder.set(part.toolCallId, toolCallOrder.size);\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: part.invalid && typeof part.input !== \"object\" ? {} : part.input,\n\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"tool-result\": {\n\t\t\t\tconst output = await createToolModelOutput({\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.output,\n\t\t\t\t\terrorMode: \"none\"\n\t\t\t\t});\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\toutput,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-error\": {\n\t\t\t\tconst output = await createToolModelOutput({\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\tinput: part.input,\n\t\t\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\t\t\toutput: part.error,\n\t\t\t\t\terrorMode: \"json\"\n\t\t\t\t});\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\toutput,\n\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"tool-approval-request\":\n\t\t\t\tconst inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);\n\t\t\t\tcontent.push({\n\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\t\ttoolCallId: part.toolCall.toolCallId,\n\t\t\t\t\t...part.signature != null ? { signature: part.signature } : {},\n\t\t\t\t\t...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {}\n\t\t\t\t});\n\t\t}\n\t}\n\tif (content.length > 0) responseMessages.push({\n\t\trole: \"assistant\",\n\t\tcontent\n\t});\n\tconst toolResultContent = [];\n\tfor (const part of inputContent) {\n\t\tif (!(part.type === \"tool-result\" || part.type === \"tool-error\") || part.providerExecuted) continue;\n\t\tconst output = await createToolModelOutput({\n\t\t\ttoolCallId: part.toolCallId,\n\t\t\tinput: part.input,\n\t\t\ttool: tools == null ? void 0 : tools[part.toolName],\n\t\t\toutput: part.type === \"tool-result\" ? part.output : part.error,\n\t\t\terrorMode: part.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t});\n\t\ttoolResultContent.push({\n\t\t\ttype: \"tool-result\",\n\t\t\ttoolCallId: part.toolCallId,\n\t\t\ttoolName: part.toolName,\n\t\t\toutput,\n\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t});\n\t}\n\tif (toolResultContent.length > 0) responseMessages.push({\n\t\trole: \"tool\",\n\t\tcontent: sortToolResultContentByToolCallOrder({\n\t\t\ttoolResultContent,\n\t\t\ttoolCallOrder\n\t\t})\n\t});\n\treturn responseMessages;\n}\nfunction sortToolResultContentByToolCallOrder({ toolResultContent, toolCallOrder }) {\n\tconst sortedToolResults = toolResultContent.filter((part) => part.type === \"tool-result\").map((part, index) => ({\n\t\tpart,\n\t\tindex\n\t})).sort((a, b) => {\n\t\tconst aOrder = toolCallOrder.get(a.part.toolCallId);\n\t\tconst bOrder = toolCallOrder.get(b.part.toolCallId);\n\t\tif (aOrder == null && bOrder == null) return a.index - b.index;\n\t\tif (aOrder == null) return 1;\n\t\tif (bOrder == null) return -1;\n\t\treturn aOrder - bOrder || a.index - b.index;\n\t}).map(({ part }) => part);\n\tlet toolResultIndex = 0;\n\treturn toolResultContent.map((part) => part.type === \"tool-result\" ? sortedToolResults[toolResultIndex++] : part);\n}\nfunction mergeAbortSignals(...signals) {\n\tconst validSignals = signals.filter((signal) => signal != null);\n\tif (validSignals.length === 0) return;\n\tif (validSignals.length === 1) return validSignals[0];\n\tconst controller = new AbortController();\n\tfor (const signal of validSignals) {\n\t\tif (signal.aborted) {\n\t\t\tcontroller.abort(signal.reason);\n\t\t\treturn controller.signal;\n\t\t}\n\t\tsignal.addEventListener(\"abort\", () => {\n\t\t\tcontroller.abort(signal.reason);\n\t\t}, { once: true });\n\t}\n\treturn controller.signal;\n}\nvar originalGenerateId = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nasync function generateText({ model: modelArg, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen = stepCountIs(1), experimental_output, output = experimental_output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_prepareStep, prepareStep = experimental_prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download2, experimental_context, experimental_toolApprovalSecret, experimental_include: include, _internal: { generateId: generateId2 = originalGenerateId } = {}, experimental_onStart: onStart, experimental_onStepStart: onStepStart, experimental_onToolCallStart: onToolCallStart, experimental_onToolCallFinish: onToolCallFinish, onStepFinish, onFinish, ...settings }) {\n\tconst model = resolveLanguageModel(modelArg);\n\tconst createGlobalTelemetry = getGlobalTelemetryIntegration();\n\tconst stopConditions = asArray(stopWhen);\n\tconst totalTimeoutMs = getTotalTimeoutMs(timeout);\n\tconst stepTimeoutMs = getStepTimeoutMs(timeout);\n\tconst stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n\tconst mergedAbortSignal = mergeAbortSignals(abortSignal, totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : void 0, stepAbortController == null ? void 0 : stepAbortController.signal);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal: mergedAbortSignal\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst modelInfo = {\n\t\tprovider: model.provider,\n\t\tmodelId: model.modelId\n\t};\n\tconst initialPrompt = await standardizePrompt({\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages\n\t});\n\tconst globalTelemetry = createGlobalTelemetry(telemetry == null ? void 0 : telemetry.integrations);\n\tawait notify({\n\t\tevent: {\n\t\t\tmodel: modelInfo,\n\t\t\tsystem,\n\t\t\tprompt,\n\t\t\tmessages,\n\t\t\ttools,\n\t\t\ttoolChoice,\n\t\t\tactiveTools,\n\t\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\t\ttemperature: callSettings.temperature,\n\t\t\ttopP: callSettings.topP,\n\t\t\ttopK: callSettings.topK,\n\t\t\tpresencePenalty: callSettings.presencePenalty,\n\t\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\t\tstopSequences: callSettings.stopSequences,\n\t\t\tseed: callSettings.seed,\n\t\t\tmaxRetries,\n\t\t\ttimeout,\n\t\t\theaders,\n\t\t\tproviderOptions,\n\t\t\tstopWhen,\n\t\t\toutput,\n\t\t\tabortSignal,\n\t\t\tinclude,\n\t\t\tfunctionId: telemetry == null ? void 0 : telemetry.functionId,\n\t\t\tmetadata: telemetry == null ? void 0 : telemetry.metadata,\n\t\t\texperimental_context\n\t\t},\n\t\tcallbacks: [onStart, globalTelemetry.onStart]\n\t});\n\tconst tracer = getTracer(telemetry);\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.model.provider\": model.provider,\n\t\t\t\t\t\"ai.model.id\": model.modelId,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a23, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;\n\t\t\t\tconst initialMessages = initialPrompt.messages;\n\t\t\t\tconst responseMessages = [];\n\t\t\t\tconst { approvedToolApprovals, deniedToolApprovals: collectedDeniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n\t\t\t\tconst { approvedToolApprovals: localApprovedToolApprovals, deniedToolApprovals: revalidationDeniedToolApprovals, invalidToolApprovals } = await validateApprovedToolApprovals({\n\t\t\t\t\tapprovedToolApprovals: approvedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted),\n\t\t\t\t\ttools,\n\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\texperimental_context,\n\t\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret\n\t\t\t\t});\n\t\t\t\tconst deniedToolApprovals = [...collectedDeniedToolApprovals, ...revalidationDeniedToolApprovals];\n\t\t\t\tif (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0 || invalidToolApprovals.length > 0) {\n\t\t\t\t\tconst toolOutputs = await executeTools({\n\t\t\t\t\t\ttoolCalls: localApprovedToolApprovals.map((toolApproval) => toolApproval.toolCall),\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\tstepNumber: 0,\n\t\t\t\t\t\tmodel: modelInfo,\n\t\t\t\t\t\tonToolCallStart: [onToolCallStart, globalTelemetry.onToolCallStart],\n\t\t\t\t\t\tonToolCallFinish: [onToolCallFinish, globalTelemetry.onToolCallFinish]\n\t\t\t\t\t});\n\t\t\t\t\tconst toolContent = [];\n\t\t\t\t\tfor (const output2 of toolOutputs) {\n\t\t\t\t\t\tconst modelOutput = await createToolModelOutput({\n\t\t\t\t\t\t\ttoolCallId: output2.toolCallId,\n\t\t\t\t\t\t\tinput: output2.input,\n\t\t\t\t\t\t\ttool: tools == null ? void 0 : tools[output2.toolName],\n\t\t\t\t\t\t\toutput: output2.type === \"tool-result\" ? output2.output : output2.error,\n\t\t\t\t\t\t\terrorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t});\n\t\t\t\t\t\ttoolContent.push({\n\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\ttoolCallId: output2.toolCallId,\n\t\t\t\t\t\t\ttoolName: output2.toolName,\n\t\t\t\t\t\t\toutput: modelOutput\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tfor (const toolApproval of invalidToolApprovals) toolContent.push({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\t\ttool: tools == null ? void 0 : tools[toolApproval.toolCall.toolName],\n\t\t\t\t\t\t\toutput: toolApproval.error,\n\t\t\t\t\t\t\terrorMode: \"text\"\n\t\t\t\t\t\t})\n\t\t\t\t\t});\n\t\t\t\t\tfor (const toolApproval of deniedToolApprovals) toolContent.push({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\t\t\treason: toolApproval.approvalResponse.reason,\n\t\t\t\t\t\t\t...toolApproval.toolCall.providerExecuted && { providerOptions: { openai: { approvalId: toolApproval.approvalResponse.approvalId } } }\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tresponseMessages.push({\n\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\tcontent: toolContent\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tconst callSettings2 = prepareCallSettings(settings);\n\t\t\t\tlet currentModelResponse;\n\t\t\t\tlet clientToolCalls = [];\n\t\t\t\tlet clientToolOutputs = [];\n\t\t\t\tconst steps = [];\n\t\t\t\tconst pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n\t\t\t\tdo {\n\t\t\t\t\tif (steps.length > 0) mergedAbortSignal?.throwIfAborted();\n\t\t\t\t\tconst stepTimeoutId = setAbortTimeout({\n\t\t\t\t\t\tabortController: stepAbortController,\n\t\t\t\t\t\tlabel: \"Step\",\n\t\t\t\t\t\ttimeoutMs: stepTimeoutMs\n\t\t\t\t\t});\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst stepInputMessages = [...initialMessages, ...responseMessages];\n\t\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tsteps,\n\t\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst stepModel = resolveLanguageModel((_a23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a23 : model);\n\t\t\t\t\t\tconst stepModelInfo = {\n\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\tmodelId: stepModel.modelId\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\t\tdownload: download2,\n\t\t\t\t\t\t\tabortSignal: mergedAbortSignal\n\t\t\t\t\t\t});\n\t\t\t\t\t\texperimental_context = (_d = prepareStepResult == null ? void 0 : prepareStepResult.experimental_context) != null ? _d : experimental_context;\n\t\t\t\t\t\tconst stepActiveTools = (_e = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _e : activeTools;\n\t\t\t\t\t\tconst stepToolSet = filterActiveTools({\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = await prepareToolsAndToolChoice({\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\ttoolChoice: (_f = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _f : toolChoice,\n\t\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst stepMessages = (_g = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _g : stepInputMessages;\n\t\t\t\t\t\tconst stepSystem = (_h = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _h : initialPrompt.system;\n\t\t\t\t\t\tconst stepProviderOptions = mergeObjects(providerOptions, prepareStepResult == null ? void 0 : prepareStepResult.providerOptions);\n\t\t\t\t\t\tconst stepCallSettings = prepareStepCallSettings({\n\t\t\t\t\t\t\tcallSettings: callSettings2,\n\t\t\t\t\t\t\tstepSettings: prepareStepResult\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\t\t\tmodel: stepModelInfo,\n\t\t\t\t\t\t\t\tsystem: stepSystem,\n\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\tactiveTools: stepActiveTools,\n\t\t\t\t\t\t\t\tsteps: [...steps],\n\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tstopWhen,\n\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\tinclude,\n\t\t\t\t\t\t\t\tfunctionId: telemetry == null ? void 0 : telemetry.functionId,\n\t\t\t\t\t\t\t\tmetadata: telemetry == null ? void 0 : telemetry.metadata,\n\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [onStepStart, globalTelemetry.onStepStart]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcurrentModelResponse = await retry(() => recordSpan({\n\t\t\t\t\t\t\tname: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.generateText.doGenerate\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": stepCallSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": stepCallSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": stepCallSettings.presencePenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": stepCallSettings.stopSequences,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": stepCallSettings.temperature,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": stepCallSettings.topK,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": stepCallSettings.topP\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\t\t\tvar _a24, _b2, _c2, _d2, _e2, _f2, _g2, _h2;\n\t\t\t\t\t\t\t\tconst result = await stepModel.doGenerate({\n\t\t\t\t\t\t\t\t\t...stepCallSettings,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: await (output == null ? void 0 : output.responseFormat),\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\t\t\tid: (_b2 = (_a24 = result.response) == null ? void 0 : _a24.id) != null ? _b2 : generateId2(),\n\t\t\t\t\t\t\t\t\ttimestamp: (_d2 = (_c2 = result.response) == null ? void 0 : _c2.timestamp) != null ? _d2 : /* @__PURE__ */ new Date(),\n\t\t\t\t\t\t\t\t\tmodelId: (_f2 = (_e2 = result.response) == null ? void 0 : _e2.modelId) != null ? _f2 : stepModel.modelId,\n\t\t\t\t\t\t\t\t\theaders: (_g2 = result.response) == null ? void 0 : _g2.headers,\n\t\t\t\t\t\t\t\t\tbody: (_h2 = result.response) == null ? void 0 : _h2.body\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tconst usage = asLanguageModelUsage(result.usage);\n\t\t\t\t\t\t\t\tspan2.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result.finishReason.unified,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(result.content) },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.reasoning\": { output: () => extractReasoningContent(result.content) },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\t\t\t\tconst toolCalls = asToolCalls(result.content);\n\t\t\t\t\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result.providerMetadata),\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": result.usage.inputTokens.total,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.noCacheTokens\": result.usage.inputTokens.noCache,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheReadTokens\": result.usage.inputTokens.cacheRead,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheWriteTokens\": result.usage.inputTokens.cacheWrite,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": result.usage.outputTokens.total,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.textTokens\": result.usage.outputTokens.text,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.reasoningTokens\": result.usage.outputTokens.reasoning,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": usage.totalTokens,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": result.usage.outputTokens.reasoning,\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": result.usage.inputTokens.cacheRead,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result.finishReason.unified],\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result.usage.inputTokens.total,\n\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result.usage.outputTokens.total\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\t...result,\n\t\t\t\t\t\t\t\t\tresponse: responseData\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst stepToolCalls = await Promise.all(currentModelResponse.content.filter((part) => part.type === \"tool-call\").map((toolCall) => parseToolCall({\n\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\t\trepairToolCall: (stepToolChoice == null ? void 0 : stepToolChoice.type) === \"none\" ? void 0 : repairToolCall,\n\t\t\t\t\t\t\tsystem,\n\t\t\t\t\t\t\tmessages: stepInputMessages\n\t\t\t\t\t\t})));\n\t\t\t\t\t\tconst enforcedToolChoice = (stepToolChoice == null ? void 0 : stepToolChoice.type) === \"auto\" ? void 0 : stepToolChoice;\n\t\t\t\t\t\tif (enforcedToolChoice != null && (enforcedToolChoice.type === \"none\" ? stepToolCalls.length > 0 : !stepToolCalls.some((toolCall) => enforcedToolChoice.type === \"required\" || toolCall.toolName === enforcedToolChoice.toolName))) throw new ToolChoiceViolationError({\n\t\t\t\t\t\t\ttoolChoice: enforcedToolChoice,\n\t\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\tmodelId: stepModel.modelId,\n\t\t\t\t\t\t\tcontent: currentModelResponse.content\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst toolApprovalRequests = {};\n\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\tif (toolCall.invalid) continue;\n\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[toolCall.toolName];\n\t\t\t\t\t\t\tif (tool2 == null) continue;\n\t\t\t\t\t\t\tif (tool2.onInputStart != null) await tool2.onInputStart({\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (tool2.onInputAvailable != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (await isApprovalNeeded({\n\t\t\t\t\t\t\t\ttool: tool2,\n\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\t\tconst approvalId = generateId2();\n\t\t\t\t\t\t\t\tconst signature = await maybeSignApproval({\n\t\t\t\t\t\t\t\t\tsecret: experimental_toolApprovalSecret,\n\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\t\tinput: toolCall.input\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\ttoolApprovalRequests[toolCall.toolCallId] = {\n\t\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst invalidToolCalls = stepToolCalls.filter((toolCall) => toolCall.invalid && toolCall.dynamic && !toolCall.providerExecuted);\n\t\t\t\t\t\tclientToolOutputs = [];\n\t\t\t\t\t\tfor (const toolCall of invalidToolCalls) clientToolOutputs.push({\n\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\t\tdynamic: true\n\t\t\t\t\t\t});\n\t\t\t\t\t\tclientToolCalls = stepToolCalls.filter((toolCall) => !toolCall.providerExecuted);\n\t\t\t\t\t\tif (stepToolSet != null && isToolExecutionAllowedFinishReason(currentModelResponse.finishReason.unified)) clientToolOutputs.push(...await executeTools({\n\t\t\t\t\t\t\ttoolCalls: clientToolCalls.filter((toolCall) => !toolCall.invalid && toolApprovalRequests[toolCall.toolCallId] == null),\n\t\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\tabortSignal: mergedAbortSignal,\n\t\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\t\tstepNumber: steps.length,\n\t\t\t\t\t\t\tmodel: stepModelInfo,\n\t\t\t\t\t\t\tonToolCallStart: [onToolCallStart, globalTelemetry.onToolCallStart],\n\t\t\t\t\t\t\tonToolCallFinish: [onToolCallFinish, globalTelemetry.onToolCallFinish]\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\tif (!toolCall.providerExecuted) continue;\n\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[toolCall.toolName];\n\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n\t\t\t\t\t\t\t\tif (!currentModelResponse.content.some((part) => part.type === \"tool-result\" && part.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor (const part of currentModelResponse.content) if (part.type === \"tool-result\") pendingDeferredToolCalls.delete(part.toolCallId);\n\t\t\t\t\t\tconst stepContent = asContent({\n\t\t\t\t\t\t\tcontent: currentModelResponse.content,\n\t\t\t\t\t\t\ttoolCalls: stepToolCalls,\n\t\t\t\t\t\t\ttoolOutputs: clientToolOutputs,\n\t\t\t\t\t\t\ttoolApprovalRequests: Object.values(toolApprovalRequests),\n\t\t\t\t\t\t\ttools: stepToolSet\n\t\t\t\t\t\t});\n\t\t\t\t\t\tresponseMessages.push(...await toResponseMessages({\n\t\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\t\ttools: stepToolSet\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? (_j = currentModelResponse.request) != null ? _j : {} : {\n\t\t\t\t\t\t\t...currentModelResponse.request,\n\t\t\t\t\t\t\tbody: void 0\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stepResponse = {\n\t\t\t\t\t\t\t...currentModelResponse.response,\n\t\t\t\t\t\t\tmessages: structuredClone(responseMessages),\n\t\t\t\t\t\t\tbody: ((_k = include == null ? void 0 : include.responseBody) != null ? _k : true) ? (_l = currentModelResponse.response) == null ? void 0 : _l.body : void 0\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stepNumber = steps.length;\n\t\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\t\tstepNumber,\n\t\t\t\t\t\t\tmodel: stepModelInfo,\n\t\t\t\t\t\t\tfunctionId: telemetry == null ? void 0 : telemetry.functionId,\n\t\t\t\t\t\t\tmetadata: telemetry == null ? void 0 : telemetry.metadata,\n\t\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\t\tcontent: stepContent,\n\t\t\t\t\t\t\tfinishReason: currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\trawFinishReason: currentModelResponse.finishReason.raw,\n\t\t\t\t\t\t\tusage: asLanguageModelUsage(currentModelResponse.usage),\n\t\t\t\t\t\t\twarnings: currentModelResponse.warnings,\n\t\t\t\t\t\t\tproviderMetadata: currentModelResponse.providerMetadata,\n\t\t\t\t\t\t\trequest: stepRequest,\n\t\t\t\t\t\t\tresponse: stepResponse\n\t\t\t\t\t\t});\n\t\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\t\twarnings: (_m = currentModelResponse.warnings) != null ? _m : [],\n\t\t\t\t\t\t\tprovider: stepModelInfo.provider,\n\t\t\t\t\t\t\tmodel: stepModelInfo.modelId\n\t\t\t\t\t\t});\n\t\t\t\t\t\tsteps.push(currentStepResult);\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: currentStepResult,\n\t\t\t\t\t\t\tcallbacks: [onStepFinish, globalTelemetry.onStepFinish]\n\t\t\t\t\t\t});\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (stepTimeoutId != null) clearTimeout(stepTimeoutId);\n\t\t\t\t\t}\n\t\t\t\t} while ((clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && !await isStopConditionMet({\n\t\t\t\t\tstopConditions,\n\t\t\t\t\tsteps\n\t\t\t\t}));\n\t\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": currentModelResponse.finishReason.unified,\n\t\t\t\t\t\t\"ai.response.text\": { output: () => extractTextContent(currentModelResponse.content) },\n\t\t\t\t\t\t\"ai.response.reasoning\": { output: () => extractReasoningContent(currentModelResponse.content) },\n\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\tconst toolCalls = asToolCalls(currentModelResponse.content);\n\t\t\t\t\t\t\treturn toolCalls == null ? void 0 : JSON.stringify(toolCalls);\n\t\t\t\t\t\t} },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(currentModelResponse.providerMetadata)\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tconst lastStep = steps[steps.length - 1];\n\t\t\t\tconst totalUsage = steps.reduce((totalUsage2, step) => {\n\t\t\t\t\treturn addLanguageModelUsage(totalUsage2, step.usage);\n\t\t\t\t}, {\n\t\t\t\t\tinputTokens: void 0,\n\t\t\t\t\toutputTokens: void 0,\n\t\t\t\t\ttotalTokens: void 0,\n\t\t\t\t\treasoningTokens: void 0,\n\t\t\t\t\tcachedInputTokens: void 0\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.usage.inputTokens\": totalUsage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.inputTokenDetails.noCacheTokens\": (_n = totalUsage.inputTokenDetails) == null ? void 0 : _n.noCacheTokens,\n\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheReadTokens\": (_o = totalUsage.inputTokenDetails) == null ? void 0 : _o.cacheReadTokens,\n\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheWriteTokens\": (_p = totalUsage.inputTokenDetails) == null ? void 0 : _p.cacheWriteTokens,\n\t\t\t\t\t\t\"ai.usage.outputTokens\": totalUsage.outputTokens,\n\t\t\t\t\t\t\"ai.usage.outputTokenDetails.textTokens\": (_q = totalUsage.outputTokenDetails) == null ? void 0 : _q.textTokens,\n\t\t\t\t\t\t\"ai.usage.outputTokenDetails.reasoningTokens\": (_r = totalUsage.outputTokenDetails) == null ? void 0 : _r.reasoningTokens,\n\t\t\t\t\t\t\"ai.usage.totalTokens\": totalUsage.totalTokens,\n\t\t\t\t\t\t\"ai.usage.reasoningTokens\": (_s = totalUsage.outputTokenDetails) == null ? void 0 : _s.reasoningTokens,\n\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": (_t = totalUsage.inputTokenDetails) == null ? void 0 : _t.cacheReadTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tstepNumber: lastStep.stepNumber,\n\t\t\t\t\t\tmodel: lastStep.model,\n\t\t\t\t\t\tfunctionId: lastStep.functionId,\n\t\t\t\t\t\tmetadata: lastStep.metadata,\n\t\t\t\t\t\texperimental_context: lastStep.experimental_context,\n\t\t\t\t\t\tfinishReason: lastStep.finishReason,\n\t\t\t\t\t\trawFinishReason: lastStep.rawFinishReason,\n\t\t\t\t\t\tusage: lastStep.usage,\n\t\t\t\t\t\tcontent: lastStep.content,\n\t\t\t\t\t\ttext: lastStep.text,\n\t\t\t\t\t\treasoningText: lastStep.reasoningText,\n\t\t\t\t\t\treasoning: lastStep.reasoning,\n\t\t\t\t\t\tfiles: lastStep.files,\n\t\t\t\t\t\tsources: lastStep.sources,\n\t\t\t\t\t\ttoolCalls: lastStep.toolCalls,\n\t\t\t\t\t\tstaticToolCalls: lastStep.staticToolCalls,\n\t\t\t\t\t\tdynamicToolCalls: lastStep.dynamicToolCalls,\n\t\t\t\t\t\ttoolResults: lastStep.toolResults,\n\t\t\t\t\t\tstaticToolResults: lastStep.staticToolResults,\n\t\t\t\t\t\tdynamicToolResults: lastStep.dynamicToolResults,\n\t\t\t\t\t\trequest: lastStep.request,\n\t\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\t\twarnings: lastStep.warnings,\n\t\t\t\t\t\tproviderMetadata: lastStep.providerMetadata,\n\t\t\t\t\t\tsteps,\n\t\t\t\t\t\ttotalUsage\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [onFinish, globalTelemetry.onFinish]\n\t\t\t\t});\n\t\t\t\tlet resolvedOutput;\n\t\t\t\tif (lastStep.finishReason === \"stop\" || lastStep.finishReason !== \"tool-calls\" && lastStep.text.length > 0) resolvedOutput = await (output != null ? output : text()).parseCompleteOutput({ text: lastStep.text }, {\n\t\t\t\t\tresponse: lastStep.response,\n\t\t\t\t\tusage: lastStep.usage,\n\t\t\t\t\tfinishReason: lastStep.finishReason\n\t\t\t\t});\n\t\t\t\treturn new DefaultGenerateTextResult({\n\t\t\t\t\tsteps,\n\t\t\t\t\ttotalUsage,\n\t\t\t\t\toutput: resolvedOutput\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nasync function executeTools({ toolCalls, tools, tracer, telemetry, messages, abortSignal, experimental_context, stepNumber, model, onToolCallStart, onToolCallFinish }) {\n\treturn (await Promise.all(toolCalls.map(async (toolCall) => executeToolCall({\n\t\ttoolCall,\n\t\ttools,\n\t\ttracer,\n\t\ttelemetry,\n\t\tmessages,\n\t\tabortSignal,\n\t\texperimental_context,\n\t\tstepNumber,\n\t\tmodel,\n\t\tonToolCallStart,\n\t\tonToolCallFinish\n\t})))).filter((output) => output != null);\n}\nvar DefaultGenerateTextResult = class {\n\tconstructor(options) {\n\t\tthis.steps = options.steps;\n\t\tthis._output = options.output;\n\t\tthis.totalUsage = options.totalUsage;\n\t}\n\tget finalStep() {\n\t\treturn this.steps[this.steps.length - 1];\n\t}\n\tget content() {\n\t\treturn this.finalStep.content;\n\t}\n\tget text() {\n\t\treturn this.finalStep.text;\n\t}\n\tget files() {\n\t\treturn this.finalStep.files;\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.reasoningText;\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.reasoning;\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.toolCalls;\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.staticToolCalls;\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.dynamicToolCalls;\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.toolResults;\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.staticToolResults;\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.dynamicToolResults;\n\t}\n\tget sources() {\n\t\treturn this.finalStep.sources;\n\t}\n\tget finishReason() {\n\t\treturn this.finalStep.finishReason;\n\t}\n\tget rawFinishReason() {\n\t\treturn this.finalStep.rawFinishReason;\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.warnings;\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.providerMetadata;\n\t}\n\tget response() {\n\t\treturn this.finalStep.response;\n\t}\n\tget request() {\n\t\treturn this.finalStep.request;\n\t}\n\tget usage() {\n\t\treturn this.finalStep.usage;\n\t}\n\tget experimental_output() {\n\t\treturn this.output;\n\t}\n\tget output() {\n\t\tif (this._output == null) throw new NoOutputGeneratedError();\n\t\treturn this._output;\n\t}\n};\nfunction asToolCalls(content) {\n\tconst parts = content.filter((part) => part.type === \"tool-call\");\n\tif (parts.length === 0) return;\n\treturn parts.map((toolCall) => ({\n\t\ttoolCallId: toolCall.toolCallId,\n\t\ttoolName: toolCall.toolName,\n\t\tinput: toolCall.input\n\t}));\n}\nfunction asContent({ content, toolCalls, toolOutputs, toolApprovalRequests, tools }) {\n\tconst contentParts = [];\n\tfor (const part of content) switch (part.type) {\n\t\tcase \"text\":\n\t\tcase \"reasoning\":\n\t\tcase \"source\":\n\t\t\tcontentParts.push(part);\n\t\t\tbreak;\n\t\tcase \"file\":\n\t\t\tcontentParts.push({\n\t\t\t\ttype: \"file\",\n\t\t\t\tfile: new DefaultGeneratedFile(part),\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"tool-call\":\n\t\t\tcontentParts.push(toolCalls.find((toolCall) => toolCall.toolCallId === part.toolCallId));\n\t\t\tbreak;\n\t\tcase \"tool-result\": {\n\t\t\tconst toolCall = toolCalls.find((toolCall2) => toolCall2.toolCallId === part.toolCallId);\n\t\t\tif (toolCall == null) {\n\t\t\t\tconst tool2 = tools == null ? void 0 : tools[part.toolName];\n\t\t\t\tif (!((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults)) throw new Error(`Tool call ${part.toolCallId} not found.`);\n\t\t\t\tif (part.isError) contentParts.push({\n\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: void 0,\n\t\t\t\t\terror: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: part.dynamic,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n\t\t\t\t});\n\t\t\t\telse contentParts.push({\n\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\tinput: void 0,\n\t\t\t\t\toutput: part.result,\n\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\tdynamic: part.dynamic,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t...(tool2 == null ? void 0 : tool2.metadata) != null ? { toolMetadata: tool2.metadata } : {}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tif (part.isError) contentParts.push({\n\t\t\t\ttype: \"tool-error\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: toolCall.input,\n\t\t\t\terror: part.result,\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tdynamic: toolCall.dynamic,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t});\n\t\t\telse contentParts.push({\n\t\t\t\ttype: \"tool-result\",\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\ttoolName: part.toolName,\n\t\t\t\tinput: toolCall.input,\n\t\t\t\toutput: part.result,\n\t\t\t\tproviderExecuted: true,\n\t\t\t\tdynamic: toolCall.dynamic,\n\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"tool-approval-request\": {\n\t\t\tconst toolCall = toolCalls.find((toolCall2) => toolCall2.toolCallId === part.toolCallId);\n\t\t\tif (toolCall == null) throw new ToolCallNotFoundForApprovalError({\n\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\tapprovalId: part.approvalId\n\t\t\t});\n\t\t\tcontentParts.push({\n\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\ttoolCall\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t}\n\treturn [\n\t\t...contentParts,\n\t\t...toolOutputs,\n\t\t...toolApprovalRequests\n\t];\n}\nfunction prepareHeaders(headers, defaultHeaders) {\n\tconst responseHeaders = new Headers(headers != null ? headers : {});\n\tfor (const [key, value] of Object.entries(defaultHeaders)) if (!responseHeaders.has(key)) responseHeaders.set(key, value);\n\treturn responseHeaders;\n}\nfunction createTextStreamResponse({ status, statusText, headers, textStream }) {\n\treturn new Response(textStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus: status != null ? status : 200,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" })\n\t});\n}\nfunction writeToServerResponse({ response, status, statusText, headers, stream }) {\n\tconst statusCode = status != null ? status : 200;\n\tif (statusText !== void 0) response.writeHead(statusCode, statusText, headers);\n\telse response.writeHead(statusCode, headers);\n\tconst reader = stream.getReader();\n\tlet clientDisconnected = false;\n\tlet onDisconnect;\n\tconst handleClose = () => {\n\t\tif (response.writableFinished) return;\n\t\tclientDisconnected = true;\n\t\tonDisconnect?.();\n\t\treader.cancel(/* @__PURE__ */ new Error(\"Client disconnected.\")).catch(() => {});\n\t};\n\tresponse.once(\"close\", handleClose);\n\tif (response.destroyed) handleClose();\n\tconst read = async () => {\n\t\ttry {\n\t\t\twhile (true) {\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done || clientDisconnected || response.destroyed) break;\n\t\t\t\tif (!response.write(value)) {\n\t\t\t\t\tawait new Promise((resolve3) => {\n\t\t\t\t\t\tonDisconnect = resolve3;\n\t\t\t\t\t\tresponse.once(\"drain\", resolve3);\n\t\t\t\t\t});\n\t\t\t\t\tonDisconnect = void 0;\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tresponse.off(\"close\", handleClose);\n\t\t\tif (clientDisconnected || response.destroyed) reader.cancel().catch(() => {});\n\t\t\telse response.end();\n\t\t}\n\t};\n\treturn read();\n}\nfunction pipeTextStreamToResponse({ response, status, statusText, headers, textStream }) {\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, { \"content-type\": \"text/plain; charset=utf-8\" }).entries()),\n\t\tstream: textStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nvar STREAM_OPEN_COMMENT = \": stream-open\\n\\n\";\nvar KEEP_ALIVE_COMMENT = \": keep-alive\\n\\n\";\nfunction createSseStreamWithKeepAlive({ stream, keepAliveMs }) {\n\tif (keepAliveMs == null) return stream;\n\tif (!Number.isFinite(keepAliveMs) || keepAliveMs <= 0 || keepAliveMs > 2147483647) throw new Error(\"keepAliveMs must be a positive finite timer duration no greater than 2147483647\");\n\tconst reader = stream.getReader();\n\tlet keepAliveTimeout;\n\tlet isCancelled = false;\n\tconst clearKeepAliveTimeout = () => {\n\t\tclearTimeout(keepAliveTimeout);\n\t\tkeepAliveTimeout = void 0;\n\t};\n\tconst scheduleKeepAlive = (controller) => {\n\t\tclearKeepAliveTimeout();\n\t\tkeepAliveTimeout = setTimeout(() => {\n\t\t\tif (isCancelled) return;\n\t\t\tif (controller.desiredSize != null && controller.desiredSize > 0) controller.enqueue(KEEP_ALIVE_COMMENT);\n\t\t\tscheduleKeepAlive(controller);\n\t\t}, keepAliveMs);\n\t};\n\treturn new ReadableStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue(STREAM_OPEN_COMMENT);\n\t\t\tscheduleKeepAlive(controller);\n\t\t},\n\t\tpull(controller) {\n\t\t\treturn reader.read().then((result) => {\n\t\t\t\tclearKeepAliveTimeout();\n\t\t\t\tif (isCancelled) return;\n\t\t\t\tif (result.done) controller.close();\n\t\t\t\telse {\n\t\t\t\t\tcontroller.enqueue(result.value);\n\t\t\t\t\tscheduleKeepAlive(controller);\n\t\t\t\t}\n\t\t\t}, (error) => {\n\t\t\t\tclearKeepAliveTimeout();\n\t\t\t\tif (!isCancelled) throw error;\n\t\t\t});\n\t\t},\n\t\tasync cancel(reason) {\n\t\t\tisCancelled = true;\n\t\t\tclearKeepAliveTimeout();\n\t\t\tawait reader.cancel(reason);\n\t\t}\n\t});\n}\nvar JsonToSseTransformStream = class extends TransformStream {\n\tconstructor() {\n\t\tsuper({\n\t\t\ttransform(part, controller) {\n\t\t\t\tcontroller.enqueue(`data: ${JSON.stringify(part)}\n\n`);\n\t\t\t},\n\t\t\tflush(controller) {\n\t\t\t\tcontroller.enqueue(\"data: [DONE]\\n\\n\");\n\t\t\t}\n\t\t});\n\t}\n};\nvar UI_MESSAGE_STREAM_HEADERS = {\n\t\"content-type\": \"text/event-stream\",\n\t\"cache-control\": \"no-cache\",\n\tconnection: \"keep-alive\",\n\t\"x-vercel-ai-ui-message-stream\": \"v1\",\n\t\"x-accel-buffering\": \"no\"\n};\nfunction createUIMessageStreamResponse({ status, statusText, headers, stream, keepAliveMs, consumeSseStream }) {\n\tlet sseStream = createSseStreamWithKeepAlive({\n\t\tstream: stream.pipeThrough(new JsonToSseTransformStream()),\n\t\tkeepAliveMs\n\t});\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn new Response(sseStream.pipeThrough(new TextEncoderStream()), {\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)\n\t});\n}\nfunction getResponseUIMessageId({ originalMessages, responseMessageId }) {\n\tif (originalMessages == null) return;\n\tconst lastMessage = originalMessages[originalMessages.length - 1];\n\treturn (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage.id : typeof responseMessageId === \"function\" ? responseMessageId() : responseMessageId;\n}\nvar toolMetadataSchema = z.record(z.string(), jsonValueSchema.optional());\nvar uiMessageChunkSchema = lazySchema(() => zodSchema(z.union([\n\tz.looseObject({\n\t\ttype: z.literal(\"text-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"text-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"error\"),\n\t\terrorText: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-start\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinputEncoding: z.enum([\"json\", \"text\"]).optional(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-delta\"),\n\t\ttoolCallId: z.string(),\n\t\tinputTextDelta: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-available\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-input-error\"),\n\t\ttoolCallId: z.string(),\n\t\ttoolName: z.string(),\n\t\tinput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\terrorText: z.string(),\n\t\ttitle: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-approval-request\"),\n\t\tapprovalId: z.string(),\n\t\ttoolCallId: z.string(),\n\t\tapprovalDescriptor: z.unknown().optional(),\n\t\tinputSchemaInput: z.unknown().optional(),\n\t\tsignature: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-available\"),\n\t\ttoolCallId: z.string(),\n\t\toutput: z.unknown(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional(),\n\t\tpreliminary: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-error\"),\n\t\ttoolCallId: z.string(),\n\t\terrorText: z.string(),\n\t\tproviderExecuted: z.boolean().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional(),\n\t\ttoolMetadata: toolMetadataSchema.optional(),\n\t\tdynamic: z.boolean().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"tool-output-denied\"),\n\t\ttoolCallId: z.string()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-start\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-delta\"),\n\t\tid: z.string(),\n\t\tdelta: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"reasoning-end\"),\n\t\tid: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-url\"),\n\t\tsourceId: z.string(),\n\t\turl: z.string(),\n\t\ttitle: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"source-document\"),\n\t\tsourceId: z.string(),\n\t\tmediaType: z.string(),\n\t\ttitle: z.string(),\n\t\tfilename: z.string().optional(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"file\"),\n\t\turl: z.string(),\n\t\tmediaType: z.string(),\n\t\tproviderMetadata: providerMetadataSchema.optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.custom((value) => typeof value === \"string\" && value.startsWith(\"data-\"), { message: \"Type must start with \\\"data-\\\"\" }),\n\t\tid: z.string().optional(),\n\t\tdata: z.unknown(),\n\t\ttransient: z.boolean().optional()\n\t}),\n\tz.looseObject({ type: z.literal(\"start-step\") }),\n\tz.looseObject({ type: z.literal(\"finish-step\") }),\n\tz.looseObject({\n\t\ttype: z.literal(\"start\"),\n\t\tmessageId: z.string().optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"finish\"),\n\t\tfinishReason: z.enum([\n\t\t\t\"stop\",\n\t\t\t\"length\",\n\t\t\t\"content-filter\",\n\t\t\t\"tool-calls\",\n\t\t\t\"error\",\n\t\t\t\"other\"\n\t\t]).optional(),\n\t\tmessageMetadata: z.unknown().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"abort\"),\n\t\treason: z.string().optional()\n\t}),\n\tz.looseObject({\n\t\ttype: z.literal(\"message-metadata\"),\n\t\tmessageMetadata: z.unknown()\n\t})\n])));\nfunction isDataUIMessageChunk(chunk) {\n\treturn chunk.type.startsWith(\"data-\");\n}\nfunction createIdMap() {\n\treturn /* @__PURE__ */ Object.create(null);\n}\nfunction isDataUIPart(part) {\n\treturn part.type.startsWith(\"data-\");\n}\nfunction isTextUIPart(part) {\n\treturn part.type === \"text\";\n}\nfunction isFileUIPart(part) {\n\treturn part.type === \"file\";\n}\nfunction isReasoningUIPart(part) {\n\treturn part.type === \"reasoning\";\n}\nfunction isStaticToolUIPart(part) {\n\treturn part.type.startsWith(\"tool-\");\n}\nfunction isDynamicToolUIPart(part) {\n\treturn part.type === \"dynamic-tool\";\n}\nfunction isToolUIPart(part) {\n\treturn isStaticToolUIPart(part) || isDynamicToolUIPart(part);\n}\nvar isToolOrDynamicToolUIPart = isToolUIPart;\nfunction getStaticToolName(part) {\n\treturn part.type.split(\"-\").slice(1).join(\"-\");\n}\nfunction getToolName(part) {\n\treturn isDynamicToolUIPart(part) ? part.toolName : getStaticToolName(part);\n}\nvar getToolOrDynamicToolName = getToolName;\nfunction createStreamingUIMessageState({ lastMessage, messageId }) {\n\tvar _a23;\n\tconst message = (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n\t\tid: messageId,\n\t\tmetadata: void 0,\n\t\trole: \"assistant\",\n\t\tparts: []\n\t};\n\tconst partialToolCalls = createIdMap();\n\tconst lastStepStartIndex = message.parts.findLastIndex((part) => part.type === \"step-start\");\n\tlet staticToolIndex = 0;\n\tfor (const part of message.parts.slice(lastStepStartIndex + 1)) {\n\t\tif (!isToolUIPart(part)) continue;\n\t\tconst index = staticToolIndex;\n\t\tif (isStaticToolUIPart(part)) staticToolIndex++;\n\t\tif (part.state !== \"input-streaming\") continue;\n\t\tpartialToolCalls[part.toolCallId] = {\n\t\t\ttext: (_a23 = part.rawInput) != null ? _a23 : \"\",\n\t\t\tinputEncoding: part.inputEncoding,\n\t\t\tindex,\n\t\t\ttoolName: part.type === \"dynamic-tool\" ? part.toolName : getStaticToolName(part),\n\t\t\tdynamic: part.type === \"dynamic-tool\",\n\t\t\ttitle: part.title,\n\t\t\ttoolMetadata: part.toolMetadata\n\t\t};\n\t}\n\treturn {\n\t\tmessage,\n\t\tactiveTextParts: createIdMap(),\n\t\tactiveReasoningParts: createIdMap(),\n\t\tpartialToolCalls\n\t};\n}\nfunction processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData, resetStateOnMessageIdChange = false, resetStateOnFirstMessageStart = false }) {\n\tlet isFirstMessageStart = true;\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tawait runUpdateMessageJob(async ({ state, write }) => {\n\t\t\tvar _a23, _b, _c, _d, _e, _f, _g, _h, _i;\n\t\t\tfunction getCurrentStepParts() {\n\t\t\t\tconst parts = state.message.parts;\n\t\t\t\tlet currentStepStartIndex = parts.length - 1;\n\t\t\t\twhile (currentStepStartIndex >= 0 && parts[currentStepStartIndex].type !== \"step-start\") currentStepStartIndex--;\n\t\t\t\treturn parts.slice(currentStepStartIndex + 1);\n\t\t\t}\n\t\t\tfunction getCurrentStepToolInvocations() {\n\t\t\t\treturn getCurrentStepParts().filter(isToolUIPart);\n\t\t\t}\n\t\t\tfunction getToolInvocation(toolCallId) {\n\t\t\t\tlet toolInvocation = getCurrentStepToolInvocations().find((invocation) => invocation.toolCallId === toolCallId);\n\t\t\t\tif (toolInvocation == null) {\n\t\t\t\t\tconst parts = state.message.parts;\n\t\t\t\t\tfor (let i = parts.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst part = parts[i];\n\t\t\t\t\t\tif (isToolUIPart(part) && part.toolCallId === toolCallId) {\n\t\t\t\t\t\t\ttoolInvocation = part;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolInvocation == null) throw new UIMessageStreamError({\n\t\t\t\t\tchunkType: \"tool-invocation\",\n\t\t\t\t\tchunkId: toolCallId,\n\t\t\t\t\tmessage: `No tool invocation found for tool call ID \"${toolCallId}\".`\n\t\t\t\t});\n\t\t\t\treturn toolInvocation;\n\t\t\t}\n\t\t\tfunction updateToolPart(options, existingPart) {\n\t\t\t\tvar _a24;\n\t\t\t\tconst part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => isStaticToolUIPart(part2) && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.type = `tool-${options.toolName}`;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tif (anyOptions.inputEncoding != null) anyPart.inputEncoding = anyOptions.inputEncoding;\n\t\t\t\t\telse delete anyPart.inputEncoding;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tif (options.title !== void 0) anyPart.title = options.title;\n\t\t\t\t\tif (options.toolMetadata !== void 0) anyPart.toolMetadata = options.toolMetadata;\n\t\t\t\t\tanyPart.providerExecuted = (_a24 = anyOptions.providerExecuted) != null ? _a24 : part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) {\n\t\t\t\t\t\tif (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\n\t\t\t\t\t}\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: `tool-${options.toolName}`,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\ttitle: options.title,\n\t\t\t\t\t...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\t...anyOptions.inputEncoding != null ? { inputEncoding: anyOptions.inputEncoding } : {},\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\trawInput: anyOptions.rawInput,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\t...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tfunction updateDynamicToolPart(options, existingPart) {\n\t\t\t\tvar _a24;\n\t\t\t\tconst part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => part2.type === \"dynamic-tool\" && part2.toolCallId === options.toolCallId);\n\t\t\t\tconst anyOptions = options;\n\t\t\t\tconst anyPart = part;\n\t\t\t\tif (part != null) {\n\t\t\t\t\tpart.state = options.state;\n\t\t\t\t\tanyPart.toolName = options.toolName;\n\t\t\t\t\tanyPart.input = anyOptions.input;\n\t\t\t\t\tanyPart.output = anyOptions.output;\n\t\t\t\t\tanyPart.errorText = anyOptions.errorText;\n\t\t\t\t\tanyPart.rawInput = anyOptions.rawInput;\n\t\t\t\t\tif (anyOptions.inputEncoding != null) anyPart.inputEncoding = anyOptions.inputEncoding;\n\t\t\t\t\telse delete anyPart.inputEncoding;\n\t\t\t\t\tanyPart.preliminary = anyOptions.preliminary;\n\t\t\t\t\tif (options.title !== void 0) anyPart.title = options.title;\n\t\t\t\t\tif (options.toolMetadata !== void 0) anyPart.toolMetadata = options.toolMetadata;\n\t\t\t\t\tanyPart.providerExecuted = (_a24 = anyOptions.providerExecuted) != null ? _a24 : part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) {\n\t\t\t\t\t\tif (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\n\t\t\t\t\t}\n\t\t\t\t} else state.message.parts.push({\n\t\t\t\t\ttype: \"dynamic-tool\",\n\t\t\t\t\ttoolName: options.toolName,\n\t\t\t\t\ttoolCallId: options.toolCallId,\n\t\t\t\t\tstate: options.state,\n\t\t\t\t\tinput: anyOptions.input,\n\t\t\t\t\t...anyOptions.inputEncoding != null ? { inputEncoding: anyOptions.inputEncoding } : {},\n\t\t\t\t\toutput: anyOptions.output,\n\t\t\t\t\terrorText: anyOptions.errorText,\n\t\t\t\t\tpreliminary: anyOptions.preliminary,\n\t\t\t\t\tproviderExecuted: anyOptions.providerExecuted,\n\t\t\t\t\ttitle: options.title,\n\t\t\t\t\t...options.toolMetadata !== void 0 ? { toolMetadata: options.toolMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && (options.state === \"output-available\" || options.state === \"output-error\") ? { resultProviderMetadata: anyOptions.providerMetadata } : {},\n\t\t\t\t\t...anyOptions.providerMetadata != null && !(options.state === \"output-available\" || options.state === \"output-error\") ? { callProviderMetadata: anyOptions.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t}\n\t\t\tasync function updateMessageMetadata(metadata) {\n\t\t\t\tif (metadata != null) {\n\t\t\t\t\tconst mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;\n\t\t\t\t\tif (messageMetadataSchema != null) await validateTypes({\n\t\t\t\t\t\tvalue: mergedMetadata,\n\t\t\t\t\t\tschema: messageMetadataSchema,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: \"message.metadata\",\n\t\t\t\t\t\t\tentityId: state.message.id\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tstate.message.metadata = mergedMetadata;\n\t\t\t\t}\n\t\t\t}\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-start\": {\n\t\t\t\t\tconst textPart = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeTextParts[chunk.id] = textPart;\n\t\t\t\t\tstate.message.parts.push(textPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-delta\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\tif (textPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"text-delta\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received text-delta for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\ttextPart.text += chunk.delta;\n\t\t\t\t\ttextPart.providerMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"text-end\": {\n\t\t\t\t\tconst textPart = state.activeTextParts[chunk.id];\n\t\t\t\t\tif (textPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"text-end\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received text-end for missing text part with ID \"${chunk.id}\". Ensure a \"text-start\" chunk is sent before any \"text-end\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\ttextPart.state = \"done\";\n\t\t\t\t\ttextPart.providerMetadata = (_b = chunk.providerMetadata) != null ? _b : textPart.providerMetadata;\n\t\t\t\t\tdelete state.activeTextParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\tconst reasoningPart = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\tstate: \"streaming\"\n\t\t\t\t\t};\n\t\t\t\t\tstate.activeReasoningParts[chunk.id] = reasoningPart;\n\t\t\t\t\tstate.message.parts.push(reasoningPart);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-delta\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\tif (reasoningPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"reasoning-delta\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received reasoning-delta for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\treasoningPart.text += chunk.delta;\n\t\t\t\t\treasoningPart.providerMetadata = (_c = chunk.providerMetadata) != null ? _c : reasoningPart.providerMetadata;\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"reasoning-end\": {\n\t\t\t\t\tconst reasoningPart = state.activeReasoningParts[chunk.id];\n\t\t\t\t\tif (reasoningPart == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"reasoning-end\",\n\t\t\t\t\t\tchunkId: chunk.id,\n\t\t\t\t\t\tmessage: `Received reasoning-end for missing reasoning part with ID \"${chunk.id}\". Ensure a \"reasoning-start\" chunk is sent before any \"reasoning-end\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\treasoningPart.providerMetadata = (_d = chunk.providerMetadata) != null ? _d : reasoningPart.providerMetadata;\n\t\t\t\t\treasoningPart.state = \"done\";\n\t\t\t\t\tdelete state.activeReasoningParts[chunk.id];\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"file\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-url\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\turl: chunk.url,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"source-document\":\n\t\t\t\t\tstate.message.parts.push({\n\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\tsourceId: chunk.sourceId,\n\t\t\t\t\t\tmediaType: chunk.mediaType,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\tfilename: chunk.filename,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\tconst toolInvocations = getCurrentStepParts().filter(isStaticToolUIPart);\n\t\t\t\t\tstate.partialToolCalls[chunk.toolCallId] = {\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tinputEncoding: chunk.inputEncoding,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tindex: toolInvocations.length,\n\t\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t};\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinputEncoding: chunk.inputEncoding,\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinputEncoding: chunk.inputEncoding,\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\tconst partialToolCall = state.partialToolCalls[chunk.toolCallId];\n\t\t\t\t\tif (partialToolCall == null) throw new UIMessageStreamError({\n\t\t\t\t\t\tchunkType: \"tool-input-delta\",\n\t\t\t\t\t\tchunkId: chunk.toolCallId,\n\t\t\t\t\t\tmessage: `Received tool-input-delta for missing tool call with ID \"${chunk.toolCallId}\". Ensure a \"tool-input-start\" chunk is sent before any \"tool-input-delta\" chunks.`\n\t\t\t\t\t});\n\t\t\t\t\tpartialToolCall.text += chunk.inputTextDelta;\n\t\t\t\t\tconst partialArgs = partialToolCall.inputEncoding === \"text\" ? partialToolCall.text : (await parsePartialJson(partialToolCall.text)).value;\n\t\t\t\t\tif (partialToolCall.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinputEncoding: partialToolCall.inputEncoding,\n\t\t\t\t\t\tinput: partialArgs,\n\t\t\t\t\t\trawInput: partialToolCall.text,\n\t\t\t\t\t\ttitle: partialToolCall.title,\n\t\t\t\t\t\ttoolMetadata: partialToolCall.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: partialToolCall.toolName,\n\t\t\t\t\t\tstate: \"input-streaming\",\n\t\t\t\t\t\tinputEncoding: partialToolCall.inputEncoding,\n\t\t\t\t\t\tinput: partialArgs,\n\t\t\t\t\t\trawInput: partialToolCall.text,\n\t\t\t\t\t\ttitle: partialToolCall.title,\n\t\t\t\t\t\ttoolMetadata: partialToolCall.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-available\":\n\t\t\t\t\tif (chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"input-available\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: chunk.title,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tif (onToolCall && !chunk.providerExecuted) await onToolCall({ toolCall: chunk });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-error\": {\n\t\t\t\t\tconst existingPart = getCurrentStepParts().filter(isToolUIPart).find((p) => p.toolCallId === chunk.toolCallId);\n\t\t\t\t\tif (existingPart != null ? existingPart.type === \"dynamic-tool\" : !!chunk.dynamic) updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: chunk.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: void 0,\n\t\t\t\t\t\trawInput: chunk.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttoolMetadata: chunk.toolMetadata\n\t\t\t\t\t});\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-approval-request\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\ttoolInvocation.state = \"approval-requested\";\n\t\t\t\t\ttoolInvocation.approval = {\n\t\t\t\t\t\tid: chunk.approvalId,\n\t\t\t\t\t\t...chunk.approvalDescriptor != null ? { descriptor: chunk.approvalDescriptor } : {},\n\t\t\t\t\t\t...Object.prototype.hasOwnProperty.call(chunk, \"inputSchemaInput\") ? { inputSchemaInput: chunk.inputSchemaInput } : {},\n\t\t\t\t\t\t...chunk.signature != null ? { signature: chunk.signature } : {}\n\t\t\t\t\t};\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-denied\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\ttoolInvocation.state = \"output-denied\";\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-available\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\tif (toolInvocation.type === \"dynamic-tool\") updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\tpreliminary: chunk.preliminary,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: (_e = chunk.toolMetadata) != null ? _e : toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: getStaticToolName(toolInvocation),\n\t\t\t\t\t\tstate: \"output-available\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\toutput: chunk.output,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tpreliminary: chunk.preliminary,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: (_f = chunk.toolMetadata) != null ? _f : toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-output-error\": {\n\t\t\t\t\tconst toolInvocation = getToolInvocation(chunk.toolCallId);\n\t\t\t\t\tif (toolInvocation.type === \"dynamic-tool\") updateDynamicToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: toolInvocation.toolName,\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: (_g = chunk.toolMetadata) != null ? _g : toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\telse updateToolPart({\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName: getStaticToolName(toolInvocation),\n\t\t\t\t\t\tstate: \"output-error\",\n\t\t\t\t\t\tinput: toolInvocation.input,\n\t\t\t\t\t\trawInput: toolInvocation.rawInput,\n\t\t\t\t\t\terrorText: chunk.errorText,\n\t\t\t\t\t\tproviderExecuted: chunk.providerExecuted,\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata,\n\t\t\t\t\t\ttitle: toolInvocation.title,\n\t\t\t\t\t\ttoolMetadata: (_h = chunk.toolMetadata) != null ? _h : toolInvocation.toolMetadata\n\t\t\t\t\t}, toolInvocation);\n\t\t\t\t\twrite();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"start-step\":\n\t\t\t\t\tstate.message.parts.push({ type: \"step-start\" });\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish-step\":\n\t\t\t\t\tstate.activeTextParts = createIdMap();\n\t\t\t\t\tstate.activeReasoningParts = createIdMap();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"start\": {\n\t\t\t\t\tconst shouldReset = resetStateOnFirstMessageStart && isFirstMessageStart || resetStateOnMessageIdChange && chunk.messageId != null && chunk.messageId !== state.message.id;\n\t\t\t\t\tisFirstMessageStart = false;\n\t\t\t\t\tif (shouldReset) Object.assign(state, createStreamingUIMessageState({\n\t\t\t\t\t\tlastMessage: void 0,\n\t\t\t\t\t\tmessageId: (_i = chunk.messageId) != null ? _i : state.message.id\n\t\t\t\t\t}), { finishReason: void 0 });\n\t\t\t\t\tif (chunk.messageId != null) state.message.id = chunk.messageId;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (shouldReset || chunk.messageId != null || chunk.messageMetadata != null) write({ updateStatus: false });\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"finish\":\n\t\t\t\t\tif (chunk.finishReason != null) state.finishReason = chunk.finishReason;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"message-metadata\":\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"error\":\n\t\t\t\t\tonError?.(new Error(chunk.errorText));\n\t\t\t\t\tbreak;\n\t\t\t\tdefault: if (isDataUIMessageChunk(chunk)) {\n\t\t\t\t\tif ((dataPartSchemas == null ? void 0 : dataPartSchemas[chunk.type]) != null) {\n\t\t\t\t\t\tconst partIdx = state.message.parts.findIndex((p) => \"id\" in p && \"data\" in p && p.id === chunk.id && p.type === chunk.type);\n\t\t\t\t\t\tconst actualPartIdx = partIdx >= 0 ? partIdx : state.message.parts.length;\n\t\t\t\t\t\tawait validateTypes({\n\t\t\t\t\t\t\tvalue: chunk.data,\n\t\t\t\t\t\t\tschema: dataPartSchemas[chunk.type],\n\t\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\t\tfield: `message.parts[${actualPartIdx}].data`,\n\t\t\t\t\t\t\t\tentityName: chunk.type,\n\t\t\t\t\t\t\t\tentityId: chunk.id\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tconst dataChunk = chunk;\n\t\t\t\t\tif (dataChunk.transient) {\n\t\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst existingUIPart = dataChunk.id != null ? state.message.parts.find((chunkArg) => dataChunk.type === chunkArg.type && dataChunk.id === chunkArg.id) : void 0;\n\t\t\t\t\tif (existingUIPart != null) existingUIPart.data = dataChunk.data;\n\t\t\t\t\telse state.message.parts.push(dataChunk);\n\t\t\t\t\tonData?.(dataChunk);\n\t\t\t\t\twrite();\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontroller.enqueue(chunk);\n\t\t});\n\t} }));\n}\nfunction handleUIMessageStreamFinish({ messageId, originalMessages = [], onStepFinish, onFinish, onError, stream, getOutcome }) {\n\tlet lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];\n\tif ((lastMessage == null ? void 0 : lastMessage.role) !== \"assistant\") lastMessage = void 0;\n\telse messageId = lastMessage.id;\n\tlet isAborted = false;\n\tlet hasProcessingFailure = false;\n\tlet processingError;\n\tconst recordProcessingFailure = (error) => {\n\t\thasProcessingFailure = true;\n\t\tprocessingError = error;\n\t};\n\tconst idInjectedStream = stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\ttry {\n\t\t\tlet outputChunk = chunk;\n\t\t\tif (chunk.type === \"start\") {\n\t\t\t\tconst startChunk = chunk;\n\t\t\t\tif (startChunk.messageId == null && messageId != null) outputChunk = {\n\t\t\t\t\t...startChunk,\n\t\t\t\t\tmessageId\n\t\t\t\t};\n\t\t\t}\n\t\t\tif (chunk.type === \"abort\") isAborted = true;\n\t\t\tcontroller.enqueue(outputChunk);\n\t\t} catch (error) {\n\t\t\trecordProcessingFailure(error);\n\t\t\tthrow error;\n\t\t}\n\t} }));\n\tif (onFinish == null && onStepFinish == null) return idInjectedStream;\n\tconst state = createStreamingUIMessageState({\n\t\tlastMessage: lastMessage ? structuredClone(lastMessage) : void 0,\n\t\tmessageId: messageId != null ? messageId : \"\"\n\t});\n\tconst runUpdateMessageJob = async (job) => {\n\t\ttry {\n\t\t\tawait job({\n\t\t\t\tstate,\n\t\t\t\twrite: () => {}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\trecordProcessingFailure(error);\n\t\t\tthrow error;\n\t\t}\n\t};\n\tlet finishCalled = false;\n\tconst callOnFinish = async () => {\n\t\tvar _a23;\n\t\tif (finishCalled || !onFinish) return;\n\t\tfinishCalled = true;\n\t\tconst isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n\t\tconst declaredOutcome = (_a23 = getOutcome == null ? void 0 : getOutcome()) != null ? _a23 : { status: \"unknown\" };\n\t\tconst outcome = hasProcessingFailure ? {\n\t\t\tstatus: \"failed\",\n\t\t\terror: processingError\n\t\t} : declaredOutcome.status === \"unknown\" && isAborted ? { status: \"aborted\" } : declaredOutcome;\n\t\tawait onFinish({\n\t\t\tisAborted: isAborted || outcome.status === \"aborted\",\n\t\t\tisContinuation,\n\t\t\toutcome,\n\t\t\tresponseMessage: state.message,\n\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, state.message],\n\t\t\tfinishReason: state.finishReason\n\t\t});\n\t};\n\tconst callOnStepFinish = async () => {\n\t\tif (!onStepFinish) return;\n\t\tconst isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);\n\t\ttry {\n\t\t\tawait onStepFinish({\n\t\t\t\tisContinuation,\n\t\t\t\tresponseMessage: structuredClone(state.message),\n\t\t\t\tmessages: [...isContinuation ? originalMessages.slice(0, -1) : originalMessages, structuredClone(state.message)]\n\t\t\t});\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tonError(error);\n\t\t\t} catch (onErrorError) {\n\t\t\t\trecordProcessingFailure(onErrorError);\n\t\t\t\tawait callOnFinish();\n\t\t\t\tthrow onErrorError;\n\t\t\t}\n\t\t}\n\t};\n\treturn processUIMessageStream({\n\t\tstream: idInjectedStream,\n\t\trunUpdateMessageJob,\n\t\tonError\n\t}).pipeThrough(new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tif (chunk.type === \"finish-step\") await callOnStepFinish();\n\t\t\tcontroller.enqueue(chunk);\n\t\t},\n\t\tasync cancel() {\n\t\t\tawait callOnFinish();\n\t\t},\n\t\tasync flush() {\n\t\t\tawait callOnFinish();\n\t\t}\n\t}));\n}\nfunction pipeUIMessageStreamToResponse({ response, status, statusText, headers, stream, keepAliveMs, consumeSseStream }) {\n\tlet sseStream = createSseStreamWithKeepAlive({\n\t\tstream: stream.pipeThrough(new JsonToSseTransformStream()),\n\t\tkeepAliveMs\n\t});\n\tif (consumeSseStream) {\n\t\tconst [stream1, stream2] = sseStream.tee();\n\t\tsseStream = stream1;\n\t\tconsumeSseStream({ stream: stream2 });\n\t}\n\treturn writeToServerResponse({\n\t\tresponse,\n\t\tstatus,\n\t\tstatusText,\n\t\theaders: Object.fromEntries(prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS).entries()),\n\t\tstream: sseStream.pipeThrough(new TextEncoderStream())\n\t});\n}\nfunction createAsyncIterableStream(source) {\n\tconst stream = source.pipeThrough(new TransformStream());\n\tstream[Symbol.asyncIterator] = function() {\n\t\tconst reader = this.getReader();\n\t\tlet finished = false;\n\t\tasync function cleanup(cancelStream) {\n\t\t\tvar _a23;\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\ttry {\n\t\t\t\tif (cancelStream) await ((_a23 = reader.cancel) == null ? void 0 : _a23.call(reader));\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t} catch (e) {}\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\t/**\n\t\t\t* Reads the next chunk from the stream.\n\t\t\t* @returns A promise resolving to the next IteratorResult.\n\t\t\t*/\n\t\t\tasync next() {\n\t\t\t\tif (finished) return {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\tif (done) {\n\t\t\t\t\tawait cleanup(true);\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: true,\n\t\t\t\t\t\tvalue: void 0\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\treturn {\n\t\t\t\t\tdone: false,\n\t\t\t\t\tvalue\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* May be called on early exit (e.g., break from for-await) or after completion.\n\t\t\t* Ensures the stream is cancelled and resources are released.\n\t\t\t* @returns A promise resolving to a completed IteratorResult.\n\t\t\t*/\n\t\t\tasync return() {\n\t\t\t\tawait cleanup(true);\n\t\t\t\treturn {\n\t\t\t\t\tdone: true,\n\t\t\t\t\tvalue: void 0\n\t\t\t\t};\n\t\t\t},\n\t\t\t/**\n\t\t\t* Called on early exit with error.\n\t\t\t* Ensures the stream is cancelled and resources are released, then rethrows the error.\n\t\t\t* @param err The error to throw.\n\t\t\t* @returns A promise that rejects with the provided error.\n\t\t\t*/\n\t\t\tasync throw(err) {\n\t\t\t\tawait cleanup(true);\n\t\t\t\tthrow err;\n\t\t\t}\n\t\t};\n\t};\n\treturn stream;\n}\nasync function consumeStream({ stream, onError, abortSignal }) {\n\tconst reader = stream.getReader();\n\tconst cancelOnAbort = () => {\n\t\treader.cancel().catch(() => {});\n\t};\n\tif (abortSignal == null ? void 0 : abortSignal.aborted) cancelOnAbort();\n\telse abortSignal?.addEventListener(\"abort\", cancelOnAbort, { once: true });\n\ttry {\n\t\twhile (true) {\n\t\t\tconst { done } = await reader.read();\n\t\t\tif (done) break;\n\t\t}\n\t} catch (error) {\n\t\tonError?.(error);\n\t} finally {\n\t\tabortSignal?.removeEventListener(\"abort\", cancelOnAbort);\n\t\treader.releaseLock();\n\t}\n}\nfunction createResolvablePromise() {\n\tlet resolve3;\n\tlet reject;\n\treturn {\n\t\tpromise: new Promise((res, rej) => {\n\t\t\tresolve3 = res;\n\t\t\treject = rej;\n\t\t}),\n\t\tresolve: resolve3,\n\t\treject\n\t};\n}\nfunction createStitchableStream() {\n\tlet innerStreams = [];\n\tlet controller = null;\n\tlet isClosed = false;\n\tlet isCancelled = false;\n\tlet waitForNewStream = createResolvablePromise();\n\tconst terminate = () => {\n\t\tif (isCancelled) return;\n\t\tisClosed = true;\n\t\twaitForNewStream.resolve();\n\t\tinnerStreams.forEach(({ reader, onCancel }) => {\n\t\t\tonCancel?.();\n\t\t\treader.cancel();\n\t\t});\n\t\tinnerStreams = [];\n\t\tcontroller?.close();\n\t};\n\tconst processPull = async () => {\n\t\tvar _a23;\n\t\tif (isCancelled) return;\n\t\tif (isClosed && innerStreams.length === 0) {\n\t\t\tcontroller?.close();\n\t\t\treturn;\n\t\t}\n\t\tif (innerStreams.length === 0) {\n\t\t\twaitForNewStream = createResolvablePromise();\n\t\t\tawait waitForNewStream.promise;\n\t\t\treturn processPull();\n\t\t}\n\t\tconst currentStream = innerStreams[0];\n\t\ttry {\n\t\t\tconst { value, done } = await currentStream.reader.read();\n\t\t\tif (isCancelled) return;\n\t\t\tif (done) {\n\t\t\t\tinnerStreams.shift();\n\t\t\t\tif (innerStreams.length === 0 && isClosed) controller?.close();\n\t\t\t\telse await processPull();\n\t\t\t} else controller?.enqueue(value);\n\t\t} catch (error) {\n\t\t\tif (isCancelled) return;\n\t\t\t(_a23 = currentStream.onError) == null || _a23.call(currentStream, error);\n\t\t\tcontroller?.error(error);\n\t\t\tinnerStreams.shift();\n\t\t\tterminate();\n\t\t}\n\t};\n\treturn {\n\t\tstream: new ReadableStream({\n\t\t\tstart(controllerParam) {\n\t\t\t\tcontroller = controllerParam;\n\t\t\t},\n\t\t\tpull: processPull,\n\t\t\tasync cancel() {\n\t\t\t\tisCancelled = true;\n\t\t\t\tisClosed = true;\n\t\t\t\twaitForNewStream.resolve();\n\t\t\t\tfor (const { reader, onCancel } of innerStreams) {\n\t\t\t\t\tonCancel?.();\n\t\t\t\t\tawait reader.cancel();\n\t\t\t\t}\n\t\t\t\tinnerStreams = [];\n\t\t\t}\n\t\t}),\n\t\taddStream: (innerStream, callbacks) => {\n\t\t\tvar _a23;\n\t\t\tif (isCancelled) {\n\t\t\t\t(_a23 = callbacks == null ? void 0 : callbacks.onCancel) == null || _a23.call(callbacks);\n\t\t\t\tinnerStream.cancel().catch(() => {});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (isClosed) throw new Error(\"Cannot add inner stream: outer stream is closed\");\n\t\t\tinnerStreams.push({\n\t\t\t\treader: innerStream.getReader(),\n\t\t\t\t...callbacks\n\t\t\t});\n\t\t\twaitForNewStream.resolve();\n\t\t},\n\t\t/**\n\t\t* Gracefully close the outer stream. This will let the inner streams\n\t\t* finish processing and then close the outer stream.\n\t\t*/\n\t\tclose: () => {\n\t\t\tif (isCancelled) return;\n\t\t\tisClosed = true;\n\t\t\twaitForNewStream.resolve();\n\t\t\tif (innerStreams.length === 0) controller?.close();\n\t\t},\n\t\t/**\n\t\t* Immediately close the outer stream. This will cancel all inner streams\n\t\t* and close the outer stream.\n\t\t*/\n\t\tterminate\n\t};\n}\nfunction runToolsTransformation({ tools, toolChoice, generatorStream, tracer, telemetry, system, messages, abortSignal, repairToolCall, experimental_context, toolApprovalSecret, generateId: generateId2, stepNumber, model, onToolCallStart, onToolCallFinish }) {\n\tlet toolResultsStreamController = null;\n\tlet toolResultsStreamClosed = false;\n\tconst toolResultsStream = new ReadableStream({\n\t\tstart(controller) {\n\t\t\ttoolResultsStreamController = controller;\n\t\t},\n\t\tcancel() {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t});\n\tfunction enqueueToolResult(chunk) {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttry {\n\t\t\ttoolResultsStreamController.enqueue(chunk);\n\t\t} catch (e) {\n\t\t\ttoolResultsStreamClosed = true;\n\t\t}\n\t}\n\tfunction closeToolResultsStream() {\n\t\tif (toolResultsStreamClosed) return;\n\t\ttoolResultsStreamClosed = true;\n\t\ttry {\n\t\t\ttoolResultsStreamController.close();\n\t\t} catch (e) {}\n\t}\n\tconst outstandingToolResults = /* @__PURE__ */ new Set();\n\tconst toolCallsToExecute = [];\n\tconst toolCallsByToolCallId = /* @__PURE__ */ new Map();\n\tlet canClose = false;\n\tlet finishChunk = void 0;\n\tfunction attemptClose() {\n\t\tif (canClose && outstandingToolResults.size === 0) {\n\t\t\tif (finishChunk != null) enqueueToolResult(finishChunk);\n\t\t\tcloseToolResultsStream();\n\t\t}\n\t}\n\tfunction executeToolCallAfterFinish(toolCall) {\n\t\tconst toolExecutionId = generateId2();\n\t\toutstandingToolResults.add(toolExecutionId);\n\t\texecuteToolCall({\n\t\t\ttoolCall,\n\t\t\ttools,\n\t\t\ttracer,\n\t\t\ttelemetry,\n\t\t\tmessages,\n\t\t\tabortSignal,\n\t\t\texperimental_context,\n\t\t\tstepNumber,\n\t\t\tmodel,\n\t\t\tonToolCallStart,\n\t\t\tonToolCallFinish,\n\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\tenqueueToolResult(result);\n\t\t\t}\n\t\t}).then((result) => {\n\t\t\tenqueueToolResult(result);\n\t\t}).catch((error) => {\n\t\t\tenqueueToolResult({\n\t\t\t\ttype: \"error\",\n\t\t\t\terror\n\t\t\t});\n\t\t}).finally(() => {\n\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\tattemptClose();\n\t\t});\n\t}\n\tconst activeToolCallToolNames = /* @__PURE__ */ new Map();\n\tconst withholdToolParts = (toolChoice == null ? void 0 : toolChoice.type) === \"none\";\n\tconst withheldToolContent = [];\n\tconst forwardStream = new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tvar _a23, _b, _c, _d, _e, _f;\n\t\t\tconst chunkType = chunk.type;\n\t\t\tif (withholdToolParts && (chunkType === \"tool-input-start\" || chunkType === \"tool-input-delta\" || chunkType === \"tool-input-end\" || chunkType === \"tool-approval-request\")) return;\n\t\t\tif (withholdToolParts && (chunkType === \"tool-call\" || chunkType === \"tool-result\")) {\n\t\t\t\twithheldToolContent.push(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tswitch (chunkType) {\n\t\t\t\tcase \"stream-start\":\n\t\t\t\tcase \"text-start\":\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"text-end\":\n\t\t\t\tcase \"reasoning-start\":\n\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\tcase \"reasoning-end\":\n\t\t\t\tcase \"source\":\n\t\t\t\tcase \"response-metadata\":\n\t\t\t\tcase \"error\":\n\t\t\t\tcase \"raw\":\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-start\":\n\t\t\t\t\tactiveToolCallToolNames.set(chunk.id, chunk.toolName);\n\t\t\t\t\tawait ((_b = (_a23 = tools == null ? void 0 : tools[chunk.toolName]) == null ? void 0 : _a23.onInputStart) == null ? void 0 : _b.call(_a23, {\n\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t}));\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-input-delta\": {\n\t\t\t\t\tconst toolName = activeToolCallToolNames.get(chunk.id);\n\t\t\t\t\tif (toolName != null) await ((_d = (_c = tools == null ? void 0 : tools[toolName]) == null ? void 0 : _c.onInputDelta) == null ? void 0 : _d.call(_c, {\n\t\t\t\t\t\tinputTextDelta: chunk.delta,\n\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t}));\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-input-end\":\n\t\t\t\t\tactiveToolCallToolNames.delete(chunk.id);\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"file\":\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tfile: new DefaultGeneratedFileWithType({\n\t\t\t\t\t\t\tdata: chunk.data,\n\t\t\t\t\t\t\tmediaType: chunk.mediaType\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"finish\": {\n\t\t\t\t\tconst toolChoiceViolationError = withholdToolParts && withheldToolContent.some((part) => part.type === \"tool-call\") ? new ToolChoiceViolationError({\n\t\t\t\t\t\ttoolChoice: { type: \"none\" },\n\t\t\t\t\t\tfinishReason: chunk.finishReason.unified,\n\t\t\t\t\t\tprovider: (_e = model == null ? void 0 : model.provider) != null ? _e : \"unknown\",\n\t\t\t\t\t\tmodelId: (_f = model == null ? void 0 : model.modelId) != null ? _f : \"unknown\",\n\t\t\t\t\t\tcontent: withheldToolContent\n\t\t\t\t\t}) : void 0;\n\t\t\t\t\tfinishChunk = {\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: toolChoiceViolationError == null ? chunk.finishReason.unified : \"error\",\n\t\t\t\t\t\trawFinishReason: chunk.finishReason.raw,\n\t\t\t\t\t\tusage: asLanguageModelUsage(chunk.usage),\n\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\tif (toolChoiceViolationError != null) controller.enqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terror: toolChoiceViolationError\n\t\t\t\t\t});\n\t\t\t\t\tif (isToolExecutionAllowedFinishReason(chunk.finishReason.unified)) for (const toolCall of toolCallsToExecute.splice(0)) executeToolCallAfterFinish(toolCall);\n\t\t\t\t\telse toolCallsToExecute.length = 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-approval-request\": {\n\t\t\t\t\tconst toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\t\t\t\t\tif (toolCall == null) {\n\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror: new ToolCallNotFoundForApprovalError({\n\t\t\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\t\t\tapprovalId: chunk.approvalId\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\tapprovalId: chunk.approvalId,\n\t\t\t\t\t\ttoolCall\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcase \"tool-call\":\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst toolCall = await parseToolCall({\n\t\t\t\t\t\t\ttoolCall: chunk,\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\t\tsystem,\n\t\t\t\t\t\t\tmessages\n\t\t\t\t\t\t});\n\t\t\t\t\t\ttoolCallsByToolCallId.set(toolCall.toolCallId, toolCall);\n\t\t\t\t\t\tcontroller.enqueue({ ...toolCall });\n\t\t\t\t\t\tif (toolCall.invalid) {\n\t\t\t\t\t\t\tif (!toolCall.providerExecuted) enqueueToolResult({\n\t\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\t\terror: getErrorMessage$1(toolCall.error),\n\t\t\t\t\t\t\t\tdynamic: true,\n\t\t\t\t\t\t\t\ttitle: toolCall.title,\n\t\t\t\t\t\t\t\t...toolCall.toolMetadata != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tconst tool2 = tools == null ? void 0 : tools[toolCall.toolName];\n\t\t\t\t\t\tif (tool2 == null) break;\n\t\t\t\t\t\tif (tool2.onInputAvailable != null) await tool2.onInputAvailable({\n\t\t\t\t\t\t\tinput: toolCall.input,\n\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (await isApprovalNeeded({\n\t\t\t\t\t\t\ttool: tool2,\n\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\tmessages,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\tconst approvalId = generateId2();\n\t\t\t\t\t\t\tconst signature = await maybeSignApproval({\n\t\t\t\t\t\t\t\tsecret: toolApprovalSecret,\n\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\ttoolCallId: toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\t\t\t\t\tinput: toolCall.input\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\tapprovalId,\n\t\t\t\t\t\t\t\ttoolCall,\n\t\t\t\t\t\t\t\t...signature != null ? { signature } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (tool2.execute != null && toolCall.providerExecuted !== true) toolCallsToExecute.push(toolCall);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terror\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\tconst toolName = chunk.toolName;\n\t\t\t\t\tconst toolCall = toolCallsByToolCallId.get(chunk.toolCallId);\n\t\t\t\t\tif (chunk.isError) enqueueToolResult({\n\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolCall == null ? void 0 : toolCall.input,\n\t\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\t\terror: chunk.result,\n\t\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n\t\t\t\t\t\t...(toolCall == null ? void 0 : toolCall.toolMetadata) != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\ttoolCallId: chunk.toolCallId,\n\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\tinput: toolCall == null ? void 0 : toolCall.input,\n\t\t\t\t\t\toutput: chunk.result,\n\t\t\t\t\t\tproviderExecuted: true,\n\t\t\t\t\t\tdynamic: chunk.dynamic,\n\t\t\t\t\t\t...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {},\n\t\t\t\t\t\t...(toolCall == null ? void 0 : toolCall.toolMetadata) != null ? { toolMetadata: toolCall.toolMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdefault: throw new Error(`Unhandled chunk type: ${chunkType}`);\n\t\t\t}\n\t\t},\n\t\tflush() {\n\t\t\tcanClose = true;\n\t\t\tattemptClose();\n\t\t}\n\t});\n\treturn new ReadableStream({ async start(controller) {\n\t\treturn Promise.all([generatorStream.pipeThrough(forwardStream).pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {}\n\t\t})), toolResultsStream.pipeTo(new WritableStream({\n\t\t\twrite(chunk) {\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t},\n\t\t\tclose() {\n\t\t\t\tcontroller.close();\n\t\t\t}\n\t\t}))]);\n\t} });\n}\nvar originalGenerateId2 = createIdGenerator({\n\tprefix: \"aitxt\",\n\tsize: 24\n});\nvar isOutputChunkType = {\n\tfile: true,\n\tsource: true,\n\t\"text-start\": true,\n\t\"text-end\": true,\n\t\"text-delta\": true,\n\t\"reasoning-start\": true,\n\t\"reasoning-end\": true,\n\t\"reasoning-delta\": true,\n\t\"tool-input-start\": true,\n\t\"tool-input-end\": true,\n\t\"tool-input-delta\": true,\n\t\"tool-approval-request\": true,\n\t\"tool-call\": true,\n\t\"tool-result\": true,\n\t\"tool-error\": true,\n\t\"stream-start\": false,\n\t\"response-metadata\": false,\n\tfinish: false,\n\terror: false,\n\traw: false\n};\nfunction streamText({ model, tools, toolChoice, system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, timeout, headers, stopWhen = stepCountIs(1), experimental_output, output = experimental_output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools = experimental_activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download2, includeRawChunks = false, onChunk, onError = ({ error }) => {\n\tconsole.error(error);\n}, onFinish, onAbort, onStepFinish, experimental_onStart: onStart, experimental_onStepStart: onStepStart, experimental_onToolCallStart: onToolCallStart, experimental_onToolCallFinish: onToolCallFinish, experimental_context, experimental_toolApprovalSecret, experimental_include: include, _internal: { now: now2 = now, generateId: generateId2 = originalGenerateId2 } = {}, ...settings }) {\n\tconst totalTimeoutMs = getTotalTimeoutMs(timeout);\n\tconst stepTimeoutMs = getStepTimeoutMs(timeout);\n\tconst chunkTimeoutMs = getChunkTimeoutMs(timeout);\n\tconst stepAbortController = stepTimeoutMs != null ? new AbortController() : void 0;\n\tconst chunkAbortController = chunkTimeoutMs != null ? new AbortController() : void 0;\n\treturn new DefaultStreamTextResult({\n\t\tmodel: resolveLanguageModel(model),\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal: mergeAbortSignals(abortSignal, totalTimeoutMs != null ? AbortSignal.timeout(totalTimeoutMs) : void 0, stepAbortController == null ? void 0 : stepAbortController.signal, chunkAbortController == null ? void 0 : chunkAbortController.signal),\n\t\tstepTimeoutMs,\n\t\tstepAbortController,\n\t\tchunkTimeoutMs,\n\t\tchunkAbortController,\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\ttools,\n\t\ttoolChoice,\n\t\ttransforms: asArray(transform),\n\t\tactiveTools,\n\t\trepairToolCall,\n\t\tstopConditions: asArray(stopWhen),\n\t\toutput,\n\t\tproviderOptions,\n\t\tprepareStep,\n\t\tincludeRawChunks,\n\t\ttimeout,\n\t\tstopWhen,\n\t\toriginalAbortSignal: abortSignal,\n\t\tonChunk,\n\t\tonError,\n\t\tonFinish,\n\t\tonAbort,\n\t\tonStepFinish,\n\t\tonStart,\n\t\tonStepStart,\n\t\tonToolCallStart,\n\t\tonToolCallFinish,\n\t\tnow: now2,\n\t\tgenerateId: generateId2,\n\t\texperimental_context,\n\t\texperimental_toolApprovalSecret,\n\t\tdownload: download2,\n\t\tinclude\n\t});\n}\nfunction createOutputTransformStream(output) {\n\tlet firstTextChunkId = void 0;\n\tlet text2 = \"\";\n\tlet textChunk = \"\";\n\tlet textProviderMetadata = void 0;\n\tlet lastPublishedValue = void 0;\n\tlet hasPublishedValue = false;\n\tfunction resetOutputState() {\n\t\tfirstTextChunkId = void 0;\n\t\ttext2 = \"\";\n\t\ttextChunk = \"\";\n\t\ttextProviderMetadata = void 0;\n\t\tlastPublishedValue = \"\";\n\t}\n\tfunction publishTextChunk({ controller, partialOutput = void 0 }) {\n\t\tcontroller.enqueue({\n\t\t\tpart: {\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: firstTextChunkId,\n\t\t\t\ttext: textChunk,\n\t\t\t\tproviderMetadata: textProviderMetadata\n\t\t\t},\n\t\t\tpartialOutput\n\t\t});\n\t\ttextChunk = \"\";\n\t}\n\treturn new TransformStream({ async transform(chunk, controller) {\n\t\tvar _a23;\n\t\tif (chunk.type === \"start-step\") resetOutputState();\n\t\tif (chunk.type === \"finish-step\" && textChunk.length > 0) publishTextChunk({ controller });\n\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"text-start\" && chunk.type !== \"text-end\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (firstTextChunkId == null) firstTextChunkId = chunk.id;\n\t\telse if (chunk.id !== firstTextChunkId) {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-start\") {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tif (chunk.type === \"text-end\") {\n\t\t\tif (textChunk.length > 0) publishTextChunk({ controller });\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\ttext2 += chunk.text;\n\t\ttextChunk += chunk.text;\n\t\ttextProviderMetadata = (_a23 = chunk.providerMetadata) != null ? _a23 : textProviderMetadata;\n\t\tif (chunk.text.length === 0 && chunk.providerMetadata != null) {\n\t\t\tcontroller.enqueue({\n\t\t\t\tpart: chunk,\n\t\t\t\tpartialOutput: void 0\n\t\t\t});\n\t\t\treturn;\n\t\t}\n\t\tconst result = await output.parsePartialOutput({ text: text2 });\n\t\tif (result !== void 0) {\n\t\t\tconst currentValue = typeof result.partial === \"string\" ? result.partial : JSON.stringify(result.partial);\n\t\t\tif (!hasPublishedValue || currentValue !== lastPublishedValue) {\n\t\t\t\tpublishTextChunk({\n\t\t\t\t\tcontroller,\n\t\t\t\t\tpartialOutput: result.partial\n\t\t\t\t});\n\t\t\t\tlastPublishedValue = currentValue;\n\t\t\t\thasPublishedValue = true;\n\t\t\t}\n\t\t}\n\t} });\n}\nvar DefaultStreamTextResult = class {\n\tconstructor({ model, telemetry, headers, settings, maxRetries: maxRetriesArg, abortSignal, stepTimeoutMs, stepAbortController, chunkTimeoutMs, chunkAbortController, system, prompt, messages, allowSystemInMessages, tools, toolChoice, transforms, activeTools, repairToolCall, stopConditions, output, providerOptions, prepareStep, includeRawChunks, now: now2, generateId: generateId2, timeout, stopWhen, originalAbortSignal, onChunk, onError, onFinish, onAbort, onStepFinish, onStart, onStepStart, onToolCallStart, onToolCallFinish, experimental_context, experimental_toolApprovalSecret, download: download2, include }) {\n\t\tthis._totalUsage = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tthis._rawFinishReason = new DelayedPromise();\n\t\tthis._steps = new DelayedPromise();\n\t\tthis.outputSpecification = output;\n\t\tthis.includeRawChunks = includeRawChunks;\n\t\tthis.tools = tools;\n\t\tconst globalTelemetry = getGlobalTelemetryIntegration()(telemetry == null ? void 0 : telemetry.integrations);\n\t\tlet stepFinish;\n\t\tlet recordedContent = [];\n\t\tconst recordedResponseMessages = [];\n\t\tlet recordedFinishReason = void 0;\n\t\tlet recordedRawFinishReason = void 0;\n\t\tlet recordedTotalUsage = void 0;\n\t\tlet recordedRequest = {};\n\t\tlet recordedWarnings = [];\n\t\tconst recordedSteps = [];\n\t\tlet recordedNoOutputError;\n\t\tlet currentStepToolSet = tools;\n\t\tlet currentStepModel = model;\n\t\tconst createPartIdReserver = () => {\n\t\t\tconst usedIds = /* @__PURE__ */ new Set();\n\t\t\treturn (id) => {\n\t\t\t\tif (!usedIds.has(id)) {\n\t\t\t\t\tusedIds.add(id);\n\t\t\t\t\treturn id;\n\t\t\t\t}\n\t\t\t\tconst generatedId = generateId2();\n\t\t\t\tlet uniqueId = generatedId;\n\t\t\t\tlet suffix = 0;\n\t\t\t\twhile (usedIds.has(uniqueId)) uniqueId = `${generatedId}-${++suffix}`;\n\t\t\t\tusedIds.add(uniqueId);\n\t\t\t\treturn uniqueId;\n\t\t\t};\n\t\t};\n\t\tconst reserveTextPartId = createPartIdReserver();\n\t\tconst reserveReasoningPartId = createPartIdReserver();\n\t\tconst pendingDeferredToolCalls = /* @__PURE__ */ new Map();\n\t\tlet rootSpan;\n\t\tlet activeTextContent = createIdMap();\n\t\tlet activeReasoningContent = createIdMap();\n\t\tconst eventProcessor = new TransformStream({\n\t\t\tasync transform(chunk, controller) {\n\t\t\t\tvar _a23, _b, _c, _d;\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tconst { part } = chunk;\n\t\t\t\tif (part.type === \"text-delta\" || part.type === \"reasoning-delta\" || part.type === \"source\" || part.type === \"tool-call\" || part.type === \"tool-result\" || part.type === \"tool-input-start\" || part.type === \"tool-input-delta\" || part.type === \"raw\") await notify({\n\t\t\t\t\tevent: { chunk: part },\n\t\t\t\t\tcallbacks: onChunk\n\t\t\t\t});\n\t\t\t\tif (part.type === \"error\") {\n\t\t\t\t\tconst error = wrapGatewayError(part.error);\n\t\t\t\t\tif (NoOutputGeneratedError.isInstance(error)) recordedNoOutputError = error;\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: { error },\n\t\t\t\t\t\tcallbacks: onError\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-start\") {\n\t\t\t\t\tactiveTextContent[part.id] = {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeTextContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-delta\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.text += part.text;\n\t\t\t\t\tactiveText.providerMetadata = (_a23 = part.providerMetadata) != null ? _a23 : activeText.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"text-end\") {\n\t\t\t\t\tconst activeText = activeTextContent[part.id];\n\t\t\t\t\tif (activeText == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `text part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveText.providerMetadata = (_b = part.providerMetadata) != null ? _b : activeText.providerMetadata;\n\t\t\t\t\tdelete activeTextContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-start\") {\n\t\t\t\t\tactiveReasoningContent[part.id] = {\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: \"\",\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t};\n\t\t\t\t\trecordedContent.push(activeReasoningContent[part.id]);\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-delta\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.text += part.text;\n\t\t\t\t\tactiveReasoning.providerMetadata = (_c = part.providerMetadata) != null ? _c : activeReasoning.providerMetadata;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"reasoning-end\") {\n\t\t\t\t\tconst activeReasoning = activeReasoningContent[part.id];\n\t\t\t\t\tif (activeReasoning == null) {\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\tpart: {\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: `reasoning part ${part.id} not found`\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tpartialOutput: void 0\n\t\t\t\t\t\t});\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tactiveReasoning.providerMetadata = (_d = part.providerMetadata) != null ? _d : activeReasoning.providerMetadata;\n\t\t\t\t\tdelete activeReasoningContent[part.id];\n\t\t\t\t}\n\t\t\t\tif (part.type === \"file\") recordedContent.push({\n\t\t\t\t\ttype: \"file\",\n\t\t\t\t\tfile: part.file,\n\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tif (part.type === \"source\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-call\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-result\" && !part.preliminary) recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-approval-request\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"tool-error\") recordedContent.push(part);\n\t\t\t\tif (part.type === \"start-step\") {\n\t\t\t\t\trecordedContent = [];\n\t\t\t\t\tactiveReasoningContent = createIdMap();\n\t\t\t\t\tactiveTextContent = createIdMap();\n\t\t\t\t\trecordedRequest = part.request;\n\t\t\t\t\trecordedWarnings = part.warnings;\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish-step\") {\n\t\t\t\t\tconst stepMessages = await toResponseMessages({\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\ttools: currentStepToolSet\n\t\t\t\t\t});\n\t\t\t\t\tconst currentStepResult = new DefaultStepResult({\n\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\tmodel: {\n\t\t\t\t\t\t\tprovider: currentStepModel.provider,\n\t\t\t\t\t\t\tmodelId: currentStepModel.modelId\n\t\t\t\t\t\t},\n\t\t\t\t\t\t...callbackTelemetryProps,\n\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\tcontent: recordedContent,\n\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\trawFinishReason: part.rawFinishReason,\n\t\t\t\t\t\tusage: part.usage,\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\trequest: recordedRequest,\n\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t...part.response,\n\t\t\t\t\t\t\tmessages: [...recordedResponseMessages, ...stepMessages]\n\t\t\t\t\t\t},\n\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tawait notify({\n\t\t\t\t\t\tevent: currentStepResult,\n\t\t\t\t\t\tcallbacks: [onStepFinish, globalTelemetry.onStepFinish]\n\t\t\t\t\t});\n\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\twarnings: recordedWarnings,\n\t\t\t\t\t\tprovider: currentStepModel.provider,\n\t\t\t\t\t\tmodel: currentStepModel.modelId\n\t\t\t\t\t});\n\t\t\t\t\trecordedSteps.push(currentStepResult);\n\t\t\t\t\trecordedResponseMessages.push(...stepMessages);\n\t\t\t\t\tstepFinish.resolve();\n\t\t\t\t}\n\t\t\t\tif (part.type === \"finish\") {\n\t\t\t\t\trecordedTotalUsage = part.totalUsage;\n\t\t\t\t\trecordedFinishReason = part.finishReason;\n\t\t\t\t\trecordedRawFinishReason = part.rawFinishReason;\n\t\t\t\t}\n\t\t\t},\n\t\t\tasync flush(controller) {\n\t\t\t\tvar _a23, _b, _c, _d, _e, _f, _g;\n\t\t\t\ttry {\n\t\t\t\t\tif (recordedSteps.length === 0 || recordedNoOutputError != null) {\n\t\t\t\t\t\tconst error = (abortSignal == null ? void 0 : abortSignal.aborted) ? abortSignal.reason : recordedNoOutputError != null ? recordedNoOutputError : new NoOutputGeneratedError({ message: \"No output generated. Check the stream for errors.\" });\n\t\t\t\t\t\tself._finishReason.reject(error);\n\t\t\t\t\t\tself._rawFinishReason.reject(error);\n\t\t\t\t\t\tself._totalUsage.reject(error);\n\t\t\t\t\t\tself._steps.reject(error);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tconst finishReason = recordedFinishReason != null ? recordedFinishReason : \"other\";\n\t\t\t\t\tconst totalUsage = recordedTotalUsage != null ? recordedTotalUsage : createNullLanguageModelUsage();\n\t\t\t\t\tself._finishReason.resolve(finishReason);\n\t\t\t\t\tself._rawFinishReason.resolve(recordedRawFinishReason);\n\t\t\t\t\tself._totalUsage.resolve(totalUsage);\n\t\t\t\t\tself._steps.resolve(recordedSteps);\n\t\t\t\t\tconst finalStep = recordedSteps[recordedSteps.length - 1];\n\t\t\t\t\tconst onFinishEvent = {\n\t\t\t\t\t\tstepNumber: finalStep.stepNumber,\n\t\t\t\t\t\tmodel: finalStep.model,\n\t\t\t\t\t\tfunctionId: finalStep.functionId,\n\t\t\t\t\t\tmetadata: finalStep.metadata,\n\t\t\t\t\t\texperimental_context: finalStep.experimental_context,\n\t\t\t\t\t\tfinishReason: finalStep.finishReason,\n\t\t\t\t\t\trawFinishReason: finalStep.rawFinishReason,\n\t\t\t\t\t\ttotalUsage,\n\t\t\t\t\t\tusage: finalStep.usage,\n\t\t\t\t\t\tcontent: finalStep.content,\n\t\t\t\t\t\ttext: finalStep.text,\n\t\t\t\t\t\treasoningText: finalStep.reasoningText,\n\t\t\t\t\t\treasoning: finalStep.reasoning,\n\t\t\t\t\t\tfiles: finalStep.files,\n\t\t\t\t\t\tsources: finalStep.sources,\n\t\t\t\t\t\ttoolCalls: finalStep.toolCalls,\n\t\t\t\t\t\tstaticToolCalls: finalStep.staticToolCalls,\n\t\t\t\t\t\tdynamicToolCalls: finalStep.dynamicToolCalls,\n\t\t\t\t\t\ttoolResults: finalStep.toolResults,\n\t\t\t\t\t\tstaticToolResults: finalStep.staticToolResults,\n\t\t\t\t\t\tdynamicToolResults: finalStep.dynamicToolResults,\n\t\t\t\t\t\trequest: finalStep.request,\n\t\t\t\t\t\tresponse: finalStep.response,\n\t\t\t\t\t\twarnings: finalStep.warnings,\n\t\t\t\t\t\tproviderMetadata: finalStep.providerMetadata,\n\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t};\n\t\t\t\t\tconst onFinishWithOutput = onFinish == null ? void 0 : async (event) => {\n\t\t\t\t\t\tconst parsedOutput = output == null ? void 0 : await self.getOutputPromise().catch(() => void 0);\n\t\t\t\t\t\tawait onFinish({\n\t\t\t\t\t\t\t...event,\n\t\t\t\t\t\t\t...output != null ? { output: parsedOutput } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t};\n\t\t\t\t\tawait Promise.all([notify({\n\t\t\t\t\t\tevent: onFinishEvent,\n\t\t\t\t\t\tcallbacks: onFinishWithOutput\n\t\t\t\t\t}), notify({\n\t\t\t\t\t\tevent: onFinishEvent,\n\t\t\t\t\t\tcallbacks: globalTelemetry.onFinish\n\t\t\t\t\t})]);\n\t\t\t\t\trootSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\"ai.response.text\": { output: () => finalStep.text },\n\t\t\t\t\t\t\t\"ai.response.reasoning\": { output: () => finalStep.reasoningText },\n\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => {\n\t\t\t\t\t\t\t\tvar _a24;\n\t\t\t\t\t\t\t\treturn ((_a24 = finalStep.toolCalls) == null ? void 0 : _a24.length) ? JSON.stringify(finalStep.toolCalls) : void 0;\n\t\t\t\t\t\t\t} },\n\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(finalStep.providerMetadata),\n\t\t\t\t\t\t\t\"ai.usage.inputTokens\": totalUsage.inputTokens,\n\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.noCacheTokens\": (_a23 = totalUsage.inputTokenDetails) == null ? void 0 : _a23.noCacheTokens,\n\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheReadTokens\": (_b = totalUsage.inputTokenDetails) == null ? void 0 : _b.cacheReadTokens,\n\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheWriteTokens\": (_c = totalUsage.inputTokenDetails) == null ? void 0 : _c.cacheWriteTokens,\n\t\t\t\t\t\t\t\"ai.usage.outputTokens\": totalUsage.outputTokens,\n\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.textTokens\": (_d = totalUsage.outputTokenDetails) == null ? void 0 : _d.textTokens,\n\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.reasoningTokens\": (_e = totalUsage.outputTokenDetails) == null ? void 0 : _e.reasoningTokens,\n\t\t\t\t\t\t\t\"ai.usage.totalTokens\": totalUsage.totalTokens,\n\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": (_f = totalUsage.outputTokenDetails) == null ? void 0 : _f.reasoningTokens,\n\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": (_g = totalUsage.inputTokenDetails) == null ? void 0 : _g.cacheReadTokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcontroller.error(error);\n\t\t\t\t} finally {\n\t\t\t\t\trootSpan.end();\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t\tconst stitchableStream = createStitchableStream();\n\t\tthis.addStream = stitchableStream.addStream;\n\t\tthis.closeStream = stitchableStream.close;\n\t\tconst reader = stitchableStream.stream.getReader();\n\t\tlet stream = new ReadableStream({\n\t\t\tasync start(controller) {\n\t\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\t},\n\t\t\tasync pull(controller) {\n\t\t\t\tfunction abort() {\n\t\t\t\t\tonAbort?.({ steps: recordedSteps });\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"abort\",\n\t\t\t\t\t\t...(abortSignal == null ? void 0 : abortSignal.reason) !== void 0 ? { reason: getErrorMessage(abortSignal.reason) } : {}\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\tif (done) {\n\t\t\t\t\t\tcontroller.close();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (abortSignal == null ? void 0 : abortSignal.aborted) {\n\t\t\t\t\t\tabort();\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(value);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tif (isAbortError(error) && (abortSignal == null ? void 0 : abortSignal.aborted)) abort();\n\t\t\t\t\telse controller.error(error);\n\t\t\t\t}\n\t\t\t},\n\t\t\tcancel(reason) {\n\t\t\t\treturn stitchableStream.stream.cancel(reason);\n\t\t\t}\n\t\t});\n\t\tlet isRunning = true;\n\t\tstream = stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (isRunning) controller.enqueue(chunk);\n\t\t} }));\n\t\tfor (const transform of transforms) stream = stream.pipeThrough(transform({\n\t\t\ttools,\n\t\t\tstopStream() {\n\t\t\t\tstitchableStream.terminate();\n\t\t\t\tisRunning = false;\n\t\t\t}\n\t\t}));\n\t\tthis.baseStream = stream.pipeThrough(createOutputTransformStream(output != null ? output : text())).pipeThrough(eventProcessor);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst self = this;\n\t\tconst modelInfo = {\n\t\t\tprovider: model.provider,\n\t\t\tmodelId: model.modelId\n\t\t};\n\t\tconst callbackTelemetryProps = {\n\t\t\tfunctionId: telemetry == null ? void 0 : telemetry.functionId,\n\t\t\tmetadata: telemetry == null ? void 0 : telemetry.metadata\n\t\t};\n\t\trecordSpan({\n\t\t\tname: \"ai.streamText\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamText\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) }\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tfn: async (rootSpanArg) => {\n\t\t\t\trootSpan = rootSpanArg;\n\t\t\t\tconst initialPrompt = await standardizePrompt({\n\t\t\t\t\tsystem,\n\t\t\t\t\tprompt,\n\t\t\t\t\tmessages,\n\t\t\t\t\tallowSystemInMessages\n\t\t\t\t});\n\t\t\t\tawait notify({\n\t\t\t\t\tevent: {\n\t\t\t\t\t\tmodel: modelInfo,\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\ttoolChoice,\n\t\t\t\t\t\tactiveTools,\n\t\t\t\t\t\tmaxOutputTokens: callSettings.maxOutputTokens,\n\t\t\t\t\t\ttemperature: callSettings.temperature,\n\t\t\t\t\t\ttopP: callSettings.topP,\n\t\t\t\t\t\ttopK: callSettings.topK,\n\t\t\t\t\t\tpresencePenalty: callSettings.presencePenalty,\n\t\t\t\t\t\tfrequencyPenalty: callSettings.frequencyPenalty,\n\t\t\t\t\t\tstopSequences: callSettings.stopSequences,\n\t\t\t\t\t\tseed: callSettings.seed,\n\t\t\t\t\t\tmaxRetries,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\theaders,\n\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\tstopWhen,\n\t\t\t\t\t\toutput,\n\t\t\t\t\t\tabortSignal: originalAbortSignal,\n\t\t\t\t\t\tinclude,\n\t\t\t\t\t\t...callbackTelemetryProps,\n\t\t\t\t\t\texperimental_context\n\t\t\t\t\t},\n\t\t\t\t\tcallbacks: [onStart, globalTelemetry.onStart]\n\t\t\t\t});\n\t\t\t\tconst initialMessages = initialPrompt.messages;\n\t\t\t\tconst initialResponseMessages = [];\n\t\t\t\tconst { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });\n\t\t\t\tif (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {\n\t\t\t\t\tconst { approvedToolApprovals: localApprovedToolApprovals, deniedToolApprovals: revalidationDeniedToolApprovals, invalidToolApprovals } = await validateApprovedToolApprovals({\n\t\t\t\t\t\tapprovedToolApprovals: approvedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted),\n\t\t\t\t\t\ttools,\n\t\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret\n\t\t\t\t\t});\n\t\t\t\t\tconst localDeniedToolApprovals = [...deniedToolApprovals.filter((toolApproval) => !toolApproval.toolCall.providerExecuted), ...revalidationDeniedToolApprovals];\n\t\t\t\t\tconst deniedProviderExecutedToolApprovals = deniedToolApprovals.filter((toolApproval) => toolApproval.toolCall.providerExecuted);\n\t\t\t\t\tlet toolExecutionStepStreamController;\n\t\t\t\t\tconst toolExecutionStepStream = new ReadableStream({ start(controller) {\n\t\t\t\t\t\ttoolExecutionStepStreamController = controller;\n\t\t\t\t\t} });\n\t\t\t\t\tself.addStream(toolExecutionStepStream);\n\t\t\t\t\ttry {\n\t\t\t\t\t\tfor (const toolApproval of [...localDeniedToolApprovals, ...deniedProviderExecutedToolApprovals]) toolExecutionStepStreamController?.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-denied\",\n\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName\n\t\t\t\t\t\t});\n\t\t\t\t\t\tfor (const toolApproval of invalidToolApprovals) toolExecutionStepStreamController?.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-error\",\n\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\t\terror: getErrorMessage(toolApproval.error),\n\t\t\t\t\t\t\ttitle: toolApproval.toolCall.title,\n\t\t\t\t\t\t\t...toolApproval.toolCall.dynamic === true ? { dynamic: true } : {},\n\t\t\t\t\t\t\t...toolApproval.toolCall.toolMetadata != null ? { toolMetadata: toolApproval.toolCall.toolMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst toolOutputs = [];\n\t\t\t\t\t\tawait Promise.all(localApprovedToolApprovals.map(async (toolApproval) => {\n\t\t\t\t\t\t\tconst result = await executeToolCall({\n\t\t\t\t\t\t\t\ttoolCall: toolApproval.toolCall,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tmessages: initialMessages,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\t\t\tmodel: modelInfo,\n\t\t\t\t\t\t\t\tonToolCallStart: [onToolCallStart, globalTelemetry.onToolCallStart],\n\t\t\t\t\t\t\t\tonToolCallFinish: [onToolCallFinish, globalTelemetry.onToolCallFinish],\n\t\t\t\t\t\t\t\tonPreliminaryToolResult: (result2) => {\n\t\t\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result2);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (result != null) {\n\t\t\t\t\t\t\t\ttoolExecutionStepStreamController?.enqueue(result);\n\t\t\t\t\t\t\t\ttoolOutputs.push(result);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tif (toolOutputs.length > 0 || localDeniedToolApprovals.length > 0 || invalidToolApprovals.length > 0) {\n\t\t\t\t\t\t\tconst localToolContent = [];\n\t\t\t\t\t\t\tfor (const output2 of toolOutputs) localToolContent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: output2.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: output2.toolName,\n\t\t\t\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\t\t\t\ttoolCallId: output2.toolCallId,\n\t\t\t\t\t\t\t\t\tinput: output2.input,\n\t\t\t\t\t\t\t\t\ttool: tools == null ? void 0 : tools[output2.toolName],\n\t\t\t\t\t\t\t\t\toutput: output2.type === \"tool-result\" ? output2.output : output2.error,\n\t\t\t\t\t\t\t\t\terrorMode: output2.type === \"tool-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tfor (const toolApproval of invalidToolApprovals) localToolContent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\t\t\toutput: await createToolModelOutput({\n\t\t\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\t\t\tinput: toolApproval.toolCall.input,\n\t\t\t\t\t\t\t\t\ttool: tools == null ? void 0 : tools[toolApproval.toolCall.toolName],\n\t\t\t\t\t\t\t\t\toutput: toolApproval.error,\n\t\t\t\t\t\t\t\t\terrorMode: \"text\"\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tfor (const toolApproval of localDeniedToolApprovals) localToolContent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\ttoolCallId: toolApproval.toolCall.toolCallId,\n\t\t\t\t\t\t\t\ttoolName: toolApproval.toolCall.toolName,\n\t\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t\ttype: \"execution-denied\",\n\t\t\t\t\t\t\t\t\treason: toolApproval.approvalResponse.reason\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tinitialResponseMessages.push({\n\t\t\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\t\t\tcontent: localToolContent\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} finally {\n\t\t\t\t\t\ttoolExecutionStepStreamController?.close();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\trecordedResponseMessages.push(...initialResponseMessages);\n\t\t\t\tasync function streamStep({ currentStep, responseMessages, usage }) {\n\t\t\t\t\tvar _a23, _b, _c, _d, _e, _f, _g, _h, _i;\n\t\t\t\t\tconst includeRawChunks2 = self.includeRawChunks;\n\t\t\t\t\tconst stepTimeoutId = setAbortTimeout({\n\t\t\t\t\t\tabortController: stepAbortController,\n\t\t\t\t\t\tlabel: \"Step\",\n\t\t\t\t\t\ttimeoutMs: stepTimeoutMs\n\t\t\t\t\t});\n\t\t\t\t\tlet chunkTimeoutId = void 0;\n\t\t\t\t\tfunction resetChunkTimeout() {\n\t\t\t\t\t\tif (chunkTimeoutId != null) clearTimeout(chunkTimeoutId);\n\t\t\t\t\t\tchunkTimeoutId = setAbortTimeout({\n\t\t\t\t\t\t\tabortController: chunkAbortController,\n\t\t\t\t\t\t\tlabel: \"Chunk\",\n\t\t\t\t\t\t\ttimeoutMs: chunkTimeoutMs\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tfunction clearChunkTimeout() {\n\t\t\t\t\t\tif (chunkTimeoutId != null) {\n\t\t\t\t\t\t\tclearTimeout(chunkTimeoutId);\n\t\t\t\t\t\t\tchunkTimeoutId = void 0;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tfunction clearStepTimeout() {\n\t\t\t\t\t\tif (stepTimeoutId != null) clearTimeout(stepTimeoutId);\n\t\t\t\t\t}\n\t\t\t\t\tfunction clearStepTimeouts() {\n\t\t\t\t\t\tclearStepTimeout();\n\t\t\t\t\t\tclearChunkTimeout();\n\t\t\t\t\t}\n\t\t\t\t\tfunction cleanupStepTimeouts() {\n\t\t\t\t\t\tabortSignal?.removeEventListener(\"abort\", cleanupStepTimeouts);\n\t\t\t\t\t\tclearStepTimeouts();\n\t\t\t\t\t}\n\t\t\t\t\tabortSignal?.addEventListener(\"abort\", cleanupStepTimeouts, { once: true });\n\t\t\t\t\ttry {\n\t\t\t\t\t\tstepFinish = new DelayedPromise();\n\t\t\t\t\t\tconst stepInputMessages = [...initialMessages, ...responseMessages];\n\t\t\t\t\t\tconst prepareStepResult = await (prepareStep == null ? void 0 : prepareStep({\n\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\tsteps: recordedSteps,\n\t\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst stepModel = resolveLanguageModel((_a23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a23 : model);\n\t\t\t\t\t\tcurrentStepModel = stepModel;\n\t\t\t\t\t\tconst stepModelInfo = {\n\t\t\t\t\t\t\tprovider: stepModel.provider,\n\t\t\t\t\t\t\tmodelId: stepModel.modelId\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\t\t\tprompt: {\n\t\t\t\t\t\t\t\tsystem: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,\n\t\t\t\t\t\t\t\tmessages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tsupportedUrls: await stepModel.supportedUrls,\n\t\t\t\t\t\t\tdownload: download2,\n\t\t\t\t\t\t\tabortSignal\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst stepActiveTools = (_d = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _d : activeTools;\n\t\t\t\t\t\tconst stepToolSet = filterActiveTools({\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t\t});\n\t\t\t\t\t\tcurrentStepToolSet = stepToolSet;\n\t\t\t\t\t\tconst { toolChoice: stepToolChoice, tools: stepTools } = await prepareToolsAndToolChoice({\n\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\ttoolChoice: (_e = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _e : toolChoice,\n\t\t\t\t\t\t\tactiveTools: stepActiveTools\n\t\t\t\t\t\t});\n\t\t\t\t\t\texperimental_context = (_f = prepareStepResult == null ? void 0 : prepareStepResult.experimental_context) != null ? _f : experimental_context;\n\t\t\t\t\t\tconst stepMessages = (_g = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _g : stepInputMessages;\n\t\t\t\t\t\tconst stepSystem = (_h = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _h : initialPrompt.system;\n\t\t\t\t\t\tconst stepProviderOptions = mergeObjects(providerOptions, prepareStepResult == null ? void 0 : prepareStepResult.providerOptions);\n\t\t\t\t\t\tconst stepCallSettings = prepareStepCallSettings({\n\t\t\t\t\t\t\tcallSettings,\n\t\t\t\t\t\t\tstepSettings: prepareStepResult\n\t\t\t\t\t\t});\n\t\t\t\t\t\tawait notify({\n\t\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\t\t\tmodel: stepModelInfo,\n\t\t\t\t\t\t\t\tsystem: stepSystem,\n\t\t\t\t\t\t\t\tmessages: stepMessages,\n\t\t\t\t\t\t\t\ttools,\n\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\tactiveTools: stepActiveTools,\n\t\t\t\t\t\t\t\tsteps: [...recordedSteps],\n\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\tstopWhen,\n\t\t\t\t\t\t\t\toutput,\n\t\t\t\t\t\t\t\tabortSignal: originalAbortSignal,\n\t\t\t\t\t\t\t\tinclude,\n\t\t\t\t\t\t\t\t...callbackTelemetryProps,\n\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tcallbacks: [onStepStart, globalTelemetry.onStepStart]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst { result: { stream: stream2, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\t\t\tname: \"ai.streamText.doStream\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.streamText.doStream\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.model.provider\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"ai.model.id\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.tools\": { input: () => stepTools == null ? void 0 : stepTools.map((tool2) => JSON.stringify(tool2)) },\n\t\t\t\t\t\t\t\t\t\"ai.prompt.toolChoice\": { input: () => stepToolChoice != null ? JSON.stringify(stepToolChoice) : void 0 },\n\t\t\t\t\t\t\t\t\t\"gen_ai.system\": stepModel.provider,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.model\": stepModel.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": stepCallSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": stepCallSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": stepCallSettings.presencePenalty,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.stop_sequences\": stepCallSettings.stopSequences,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.temperature\": stepCallSettings.temperature,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_k\": stepCallSettings.topK,\n\t\t\t\t\t\t\t\t\t\"gen_ai.request.top_p\": stepCallSettings.topP\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\t\t\tendOnError: true,\n\t\t\t\t\t\t\tfn: async (doStreamSpan2) => ({\n\t\t\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\t\t\tresult: await stepModel.doStream({\n\t\t\t\t\t\t\t\t\t...stepCallSettings,\n\t\t\t\t\t\t\t\t\ttools: stepTools,\n\t\t\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\t\t\tresponseFormat: await (output == null ? void 0 : output.responseFormat),\n\t\t\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\t\t\tproviderOptions: stepProviderOptions,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders,\n\t\t\t\t\t\t\t\t\tincludeRawChunks: includeRawChunks2\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t}));\n\t\t\t\t\t\tconst streamWithToolResults = runToolsTransformation({\n\t\t\t\t\t\t\ttools: stepToolSet,\n\t\t\t\t\t\t\ttoolChoice: stepToolChoice,\n\t\t\t\t\t\t\tgeneratorStream: stream2,\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tsystem,\n\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\trepairToolCall,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\texperimental_context,\n\t\t\t\t\t\t\ttoolApprovalSecret: experimental_toolApprovalSecret,\n\t\t\t\t\t\t\tgenerateId: generateId2,\n\t\t\t\t\t\t\tstepNumber: recordedSteps.length,\n\t\t\t\t\t\t\tmodel: stepModelInfo,\n\t\t\t\t\t\t\tonToolCallStart: [onToolCallStart, globalTelemetry.onToolCallStart],\n\t\t\t\t\t\t\tonToolCallFinish: [onToolCallFinish, globalTelemetry.onToolCallFinish]\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst stepRequest = ((_i = include == null ? void 0 : include.requestBody) != null ? _i : true) ? request != null ? request : {} : {\n\t\t\t\t\t\t\t...request,\n\t\t\t\t\t\t\tbody: void 0\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst stepToolCalls = [];\n\t\t\t\t\t\tconst stepToolOutputs = [];\n\t\t\t\t\t\tlet warnings;\n\t\t\t\t\t\tlet stepFinishReason = \"other\";\n\t\t\t\t\t\tlet stepRawFinishReason = void 0;\n\t\t\t\t\t\tlet hasReceivedTerminalChunk = false;\n\t\t\t\t\t\tlet hasReceivedOutputChunk = false;\n\t\t\t\t\t\tlet stepUsage = createNullLanguageModelUsage();\n\t\t\t\t\t\tlet stepProviderMetadata;\n\t\t\t\t\t\tlet stepFirstChunk = true;\n\t\t\t\t\t\tlet stepResponse = {\n\t\t\t\t\t\t\tid: generateId2(),\n\t\t\t\t\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\t\t\t\t\tmodelId: stepModelInfo.modelId\n\t\t\t\t\t\t};\n\t\t\t\t\t\tlet activeText = \"\";\n\t\t\t\t\t\tconst textPartIds = /* @__PURE__ */ new Map();\n\t\t\t\t\t\tconst reasoningPartIds = /* @__PURE__ */ new Map();\n\t\t\t\t\t\tself.addStream(streamWithToolResults.pipeThrough(new TransformStream({\n\t\t\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\t\t\tvar _a24, _b2, _c2, _d2, _e2, _f2, _g2, _h2, _i2;\n\t\t\t\t\t\t\t\tresetChunkTimeout();\n\t\t\t\t\t\t\t\tif (chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (stepFirstChunk) {\n\t\t\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\t\tstepFirstChunk = false;\n\t\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.response.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"start-step\",\n\t\t\t\t\t\t\t\t\t\trequest: stepRequest,\n\t\t\t\t\t\t\t\t\t\twarnings: warnings != null ? warnings : []\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst chunkType = chunk.type;\n\t\t\t\t\t\t\t\tif (isOutputChunkType[chunkType]) hasReceivedOutputChunk = true;\n\t\t\t\t\t\t\t\tswitch (chunkType) {\n\t\t\t\t\t\t\t\t\tcase \"tool-approval-request\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"text-start\": {\n\t\t\t\t\t\t\t\t\t\tconst id = reserveTextPartId(chunk.id);\n\t\t\t\t\t\t\t\t\t\ttextPartIds.set(chunk.id, id);\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\t\tid: (_a24 = textPartIds.get(chunk.id)) != null ? _a24 : chunk.id\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\ttextPartIds.delete(chunk.id);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\t\t\t\tif (chunk.delta.length > 0 || chunk.providerMetadata != null) controller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\t\tid: (_b2 = textPartIds.get(chunk.id)) != null ? _b2 : chunk.id,\n\t\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tactiveText += chunk.delta;\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"reasoning-start\": {\n\t\t\t\t\t\t\t\t\t\tconst id = reserveReasoningPartId(chunk.id);\n\t\t\t\t\t\t\t\t\t\treasoningPartIds.set(chunk.id, id);\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\t\tid\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\t\tid: (_c2 = reasoningPartIds.get(chunk.id)) != null ? _c2 : chunk.id\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\treasoningPartIds.delete(chunk.id);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\t\t\t\tid: (_d2 = reasoningPartIds.get(chunk.id)) != null ? _d2 : chunk.id,\n\t\t\t\t\t\t\t\t\t\t\ttext: chunk.delta,\n\t\t\t\t\t\t\t\t\t\t\tproviderMetadata: chunk.providerMetadata\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"tool-call\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tstepToolCalls.push(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"tool-result\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tif (!chunk.preliminary) stepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"tool-error\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tstepToolOutputs.push(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\t\t\tstepResponse = {\n\t\t\t\t\t\t\t\t\t\t\tid: (_e2 = chunk.id) != null ? _e2 : stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\ttimestamp: (_f2 = chunk.timestamp) != null ? _f2 : stepResponse.timestamp,\n\t\t\t\t\t\t\t\t\t\t\tmodelId: (_g2 = chunk.modelId) != null ? _g2 : stepResponse.modelId\n\t\t\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"finish\": {\n\t\t\t\t\t\t\t\t\t\thasReceivedTerminalChunk = true;\n\t\t\t\t\t\t\t\t\t\tstepUsage = chunk.usage;\n\t\t\t\t\t\t\t\t\t\tstepFinishReason = chunk.finishReason;\n\t\t\t\t\t\t\t\t\t\tstepRawFinishReason = chunk.rawFinishReason;\n\t\t\t\t\t\t\t\t\t\tstepProviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\t\t\tconst msToFinish = now2() - startTimestampMs;\n\t\t\t\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.finish\");\n\t\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes({\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.msToFinish\": msToFinish,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.avgOutputTokensPerSecond\": 1e3 * ((_h2 = stepUsage.outputTokens) != null ? _h2 : 0) / msToFinish\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[chunk.toolName];\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\t\t\tdynamic: (_i2 = chunk.dynamic) != null ? _i2 : (tool2 == null ? void 0 : tool2.type) === \"dynamic\",\n\t\t\t\t\t\t\t\t\t\t\ttitle: tool2 == null ? void 0 : tool2.title\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\tcase \"tool-input-end\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\t\t\thasReceivedTerminalChunk = true;\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tstepFinishReason = \"error\";\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tcase \"raw\":\n\t\t\t\t\t\t\t\t\t\tif (includeRawChunks2) controller.enqueue(chunk);\n\t\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${chunkType}`);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\t\t\tvar _a24, _b2, _c2, _d2, _e2, _f2, _g2;\n\t\t\t\t\t\t\t\tif (!hasReceivedTerminalChunk && !hasReceivedOutputChunk) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\t\terror: new NoOutputGeneratedError({ message: \"No output generated. The model stream ended without a finish chunk.\" })\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst stepToolCallsJson = stepToolCalls.length > 0 ? JSON.stringify(stepToolCalls) : void 0;\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": stepFinishReason,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.toolCalls\": { output: () => stepToolCallsJson },\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": stepResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.noCacheTokens\": (_a24 = stepUsage.inputTokenDetails) == null ? void 0 : _a24.noCacheTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheReadTokens\": (_b2 = stepUsage.inputTokenDetails) == null ? void 0 : _b2.cacheReadTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokenDetails.cacheWriteTokens\": (_c2 = stepUsage.inputTokenDetails) == null ? void 0 : _c2.cacheWriteTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": stepUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.textTokens\": (_d2 = stepUsage.outputTokenDetails) == null ? void 0 : _d2.textTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokenDetails.reasoningTokens\": (_e2 = stepUsage.outputTokenDetails) == null ? void 0 : _e2.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": stepUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": (_f2 = stepUsage.outputTokenDetails) == null ? void 0 : _f2.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": (_g2 = stepUsage.inputTokenDetails) == null ? void 0 : _g2.cacheReadTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [stepFinishReason],\n\t\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": stepResponse.modelId,\n\t\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": stepUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": stepUsage.outputTokens\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t} catch (error) {}\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"finish-step\",\n\t\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\t\trawFinishReason: stepRawFinishReason,\n\t\t\t\t\t\t\t\t\tusage: stepUsage,\n\t\t\t\t\t\t\t\t\tproviderMetadata: stepProviderMetadata,\n\t\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t\t...stepResponse,\n\t\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst combinedUsage = addLanguageModelUsage(usage, stepUsage);\n\t\t\t\t\t\t\t\tawait stepFinish.promise;\n\t\t\t\t\t\t\t\tconst processedStep = recordedSteps[recordedSteps.length - 1];\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tdoStreamSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.text\": { output: () => processedStep.text },\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.reasoning\": { output: () => processedStep.reasoningText },\n\t\t\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(processedStep.providerMetadata)\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t} catch (error) {} finally {\n\t\t\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tconst clientToolCalls = stepToolCalls.filter((toolCall) => toolCall.providerExecuted !== true);\n\t\t\t\t\t\t\t\tconst clientToolOutputs = stepToolOutputs.filter((toolOutput) => toolOutput.providerExecuted !== true);\n\t\t\t\t\t\t\t\tfor (const toolCall of stepToolCalls) {\n\t\t\t\t\t\t\t\t\tif (toolCall.providerExecuted !== true) continue;\n\t\t\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[toolCall.toolName];\n\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.type) === \"provider\" && tool2.supportsDeferredResults) {\n\t\t\t\t\t\t\t\t\t\tif (!stepToolOutputs.some((output2) => (output2.type === \"tool-result\" || output2.type === \"tool-error\") && output2.toolCallId === toolCall.toolCallId)) pendingDeferredToolCalls.set(toolCall.toolCallId, { toolName: toolCall.toolName });\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tfor (const output2 of stepToolOutputs) if (output2.type === \"tool-result\" || output2.type === \"tool-error\") pendingDeferredToolCalls.delete(output2.toolCallId);\n\t\t\t\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\t\t\t\tif ((clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && !await isStopConditionMet({\n\t\t\t\t\t\t\t\t\tstopConditions,\n\t\t\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t\t\t})) {\n\t\t\t\t\t\t\t\t\tresponseMessages.push(...await toResponseMessages({\n\t\t\t\t\t\t\t\t\t\tcontent: recordedSteps[recordedSteps.length - 1].content,\n\t\t\t\t\t\t\t\t\t\ttools: stepToolSet\n\t\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\t\tawait streamStep({\n\t\t\t\t\t\t\t\t\t\t\tcurrentStep: currentStep + 1,\n\t\t\t\t\t\t\t\t\t\t\tresponseMessages,\n\t\t\t\t\t\t\t\t\t\t\tusage: combinedUsage\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\t\t\t\tfinishReason: stepFinishReason,\n\t\t\t\t\t\t\t\t\t\trawFinishReason: stepRawFinishReason,\n\t\t\t\t\t\t\t\t\t\ttotalUsage: combinedUsage\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself.closeStream();\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t})), {\n\t\t\t\t\t\t\tonError: cleanupStepTimeouts,\n\t\t\t\t\t\t\tonCancel: cleanupStepTimeouts\n\t\t\t\t\t\t});\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tcleanupStepTimeouts();\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tawait streamStep({\n\t\t\t\t\tcurrentStep: 0,\n\t\t\t\t\tresponseMessages: initialResponseMessages,\n\t\t\t\t\tusage: createNullLanguageModelUsage()\n\t\t\t\t});\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tself.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t\tself.closeStream();\n\t\t});\n\t}\n\tget steps() {\n\t\tthis.consumeStream();\n\t\treturn this._steps.promise;\n\t}\n\tget finalStep() {\n\t\treturn this.steps.then((steps) => steps[steps.length - 1]);\n\t}\n\tget content() {\n\t\treturn this.finalStep.then((step) => step.content);\n\t}\n\tget warnings() {\n\t\treturn this.finalStep.then((step) => step.warnings);\n\t}\n\tget providerMetadata() {\n\t\treturn this.finalStep.then((step) => step.providerMetadata);\n\t}\n\tget text() {\n\t\treturn this.finalStep.then((step) => step.text);\n\t}\n\tget reasoningText() {\n\t\treturn this.finalStep.then((step) => step.reasoningText);\n\t}\n\tget reasoning() {\n\t\treturn this.finalStep.then((step) => step.reasoning);\n\t}\n\tget sources() {\n\t\treturn this.finalStep.then((step) => step.sources);\n\t}\n\tget files() {\n\t\treturn this.finalStep.then((step) => step.files);\n\t}\n\tget toolCalls() {\n\t\treturn this.finalStep.then((step) => step.toolCalls);\n\t}\n\tget staticToolCalls() {\n\t\treturn this.finalStep.then((step) => step.staticToolCalls);\n\t}\n\tget dynamicToolCalls() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolCalls);\n\t}\n\tget toolResults() {\n\t\treturn this.finalStep.then((step) => step.toolResults);\n\t}\n\tget staticToolResults() {\n\t\treturn this.finalStep.then((step) => step.staticToolResults);\n\t}\n\tget dynamicToolResults() {\n\t\treturn this.finalStep.then((step) => step.dynamicToolResults);\n\t}\n\tget usage() {\n\t\treturn this.finalStep.then((step) => step.usage);\n\t}\n\tget request() {\n\t\treturn this.finalStep.then((step) => step.request);\n\t}\n\tget response() {\n\t\treturn this.finalStep.then((step) => step.response);\n\t}\n\tget totalUsage() {\n\t\tthis.consumeStream();\n\t\treturn this._totalUsage.promise;\n\t}\n\tget finishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._finishReason.promise;\n\t}\n\tget rawFinishReason() {\n\t\tthis.consumeStream();\n\t\treturn this._rawFinishReason.promise;\n\t}\n\t/**\n\t* Split out a new stream from the original stream.\n\t* The original stream is replaced to allow for further splitting,\n\t* since we do not know how many times the stream will be split.\n\t*\n\t* Note: this leads to buffering the stream content on the server.\n\t* However, the LLM results are expected to be small enough to not cause issues.\n\t*/\n\tteeStream() {\n\t\tconst [stream1, stream2] = this.baseStream.tee();\n\t\tthis.baseStream = stream2;\n\t\treturn stream1;\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tif (part.type === \"text-delta\") controller.enqueue(part.text);\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ part }, controller) {\n\t\t\tcontroller.enqueue(part);\n\t\t} })));\n\t}\n\trejectResultPromises(error) {\n\t\tif (this._finishReason.isPending()) this._finishReason.reject(error);\n\t\tif (this._rawFinishReason.isPending()) this._rawFinishReason.reject(error);\n\t\tif (this._totalUsage.isPending()) this._totalUsage.reject(error);\n\t\tif (this._steps.isPending()) this._steps.reject(error);\n\t}\n\tasync consumeStream(options) {\n\t\tvar _a23;\n\t\ttry {\n\t\t\tawait consumeStream({\n\t\t\t\tstream: this.fullStream,\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tvar _a24;\n\t\t\t\t\tthis.rejectResultPromises(error);\n\t\t\t\t\t(_a24 = options == null ? void 0 : options.onError) == null || _a24.call(options, error);\n\t\t\t\t}\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.rejectResultPromises(error);\n\t\t\t(_a23 = options == null ? void 0 : options.onError) == null || _a23.call(options, error);\n\t\t}\n\t}\n\tget experimental_partialOutputStream() {\n\t\treturn this.partialOutputStream;\n\t}\n\tget partialOutputStream() {\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(new TransformStream({ transform({ partialOutput }, controller) {\n\t\t\tif (partialOutput !== void 0) controller.enqueue(partialOutput);\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\tvar _a23, _b, _c;\n\t\tconst transform = (_a23 = this.outputSpecification) == null ? void 0 : _a23.createElementStreamTransform();\n\t\tif (transform == null) throw new UnsupportedFunctionalityError({ functionality: `element streams in ${(_c = (_b = this.outputSpecification) == null ? void 0 : _b.name) != null ? _c : \"text\"} mode` });\n\t\treturn createAsyncIterableStream(this.teeStream().pipeThrough(transform));\n\t}\n\tgetOutputPromise() {\n\t\tif (this.outputPromise == null) this.outputPromise = this.finalStep.then((step) => {\n\t\t\tvar _a23;\n\t\t\treturn ((_a23 = this.outputSpecification) != null ? _a23 : text()).parseCompleteOutput({ text: step.text }, {\n\t\t\t\tresponse: step.response,\n\t\t\t\tusage: step.usage,\n\t\t\t\tfinishReason: step.finishReason\n\t\t\t});\n\t\t});\n\t\treturn this.outputPromise;\n\t}\n\tget output() {\n\t\treturn this.getOutputPromise();\n\t}\n\ttoUIMessageStream({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\" } = {}) {\n\t\tlet outcome = { status: \"unknown\" };\n\t\tlet hasFatalFailure = false;\n\t\tconst setSourceOutcome = (newOutcome) => {\n\t\t\tif (!hasFatalFailure && outcome.status !== \"completed\" && outcome.status !== \"aborted\" && newOutcome.status !== \"unknown\" && (outcome.status === \"unknown\" || newOutcome.status !== \"failed\")) outcome = newOutcome;\n\t\t};\n\t\tconst failOutcome = (error) => {\n\t\t\thasFatalFailure = true;\n\t\t\toutcome = {\n\t\t\t\tstatus: \"failed\",\n\t\t\t\terror\n\t\t\t};\n\t\t};\n\t\tconst responseMessageId = generateMessageId != null ? getResponseUIMessageId({\n\t\t\toriginalMessages,\n\t\t\tresponseMessageId: generateMessageId\n\t\t}) : void 0;\n\t\tconst isDynamic = (part) => {\n\t\t\tvar _a23;\n\t\t\tconst tool2 = (_a23 = this.tools) == null ? void 0 : _a23[part.toolName];\n\t\t\tif (tool2 == null) return part.dynamic;\n\t\t\treturn (tool2 == null ? void 0 : tool2.type) === \"dynamic\" ? true : void 0;\n\t\t};\n\t\tconst trackFatalFailures = (stream) => {\n\t\t\tconst reader = stream.getReader();\n\t\t\tlet readerReleased = false;\n\t\t\tlet streamCancelled = false;\n\t\t\tconst releaseReader = () => {\n\t\t\t\tif (!readerReleased) {\n\t\t\t\t\treader.releaseLock();\n\t\t\t\t\treaderReleased = true;\n\t\t\t\t}\n\t\t\t};\n\t\t\treturn new ReadableStream({\n\t\t\t\tasync pull(controller) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) {\n\t\t\t\t\t\t\treleaseReader();\n\t\t\t\t\t\t\tif (!streamCancelled) controller.close();\n\t\t\t\t\t\t} else controller.enqueue(value);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\treleaseReader();\n\t\t\t\t\t\tif (!streamCancelled) {\n\t\t\t\t\t\t\tfailOutcome(error);\n\t\t\t\t\t\t\tcontroller.error(error);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\tasync cancel(reason) {\n\t\t\t\t\tstreamCancelled = true;\n\t\t\t\t\tif (readerReleased) return;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tawait reader.cancel(reason);\n\t\t\t\t\t} finally {\n\t\t\t\t\t\treleaseReader();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\t\t};\n\t\treturn createAsyncIterableStream(handleUIMessageStreamFinish({\n\t\t\tstream: trackFatalFailures(trackFatalFailures(this.fullStream).pipeThrough(new TransformStream({ transform: async (part, controller) => {\n\t\t\t\tconst messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });\n\t\t\t\tconst partType = part.type;\n\t\t\t\tswitch (partType) {\n\t\t\t\t\tcase \"text-start\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"text-end\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-start\":\n\t\t\t\t\tcase \"reasoning-end\":\n\t\t\t\t\t\tif (sendReasoning) controller.enqueue({\n\t\t\t\t\t\t\ttype: partType,\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"reasoning-delta\":\n\t\t\t\t\t\tif (sendReasoning) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\tid: part.id,\n\t\t\t\t\t\t\tdelta: part.text,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"file\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\t\tmediaType: part.file.mediaType,\n\t\t\t\t\t\t\turl: `data:${part.file.mediaType};base64,${part.file.base64}`,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"source\":\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"url\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-url\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\turl: part.url,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tif (sendSources && part.sourceType === \"document\") controller.enqueue({\n\t\t\t\t\t\t\ttype: \"source-document\",\n\t\t\t\t\t\t\tsourceId: part.id,\n\t\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\t\ttitle: part.title,\n\t\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-start\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-start\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\t...part.inputEncoding != null ? { inputEncoding: part.inputEncoding } : {},\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-delta\",\n\t\t\t\t\t\t\ttoolCallId: part.id,\n\t\t\t\t\t\t\tinputTextDelta: part.delta\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-call\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part);\n\t\t\t\t\t\tif (part.invalid) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t\t\t\terrorText: onError(part.error),\n\t\t\t\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\telse controller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-input-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\ttoolName: part.toolName,\n\t\t\t\t\t\t\tinput: part.input,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {},\n\t\t\t\t\t\t\t...part.title != null ? { title: part.title } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-approval-request\": {\n\t\t\t\t\t\tconst inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\tapprovalId: part.approvalId,\n\t\t\t\t\t\t\ttoolCallId: part.toolCall.toolCallId,\n\t\t\t\t\t\t\t...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {},\n\t\t\t\t\t\t\t...part.signature != null ? { signature: part.signature } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-result\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-available\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\toutput: part.output === void 0 ? null : part.output,\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t\t\t\t...part.preliminary != null ? { preliminary: part.preliminary } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-error\": {\n\t\t\t\t\t\tconst dynamic = isDynamic(part);\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-error\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\terrorText: part.providerExecuted ? typeof part.error === \"string\" ? part.error : JSON.stringify(part.error) : onError(part.error),\n\t\t\t\t\t\t\t...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},\n\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},\n\t\t\t\t\t\t\t...part.toolMetadata != null ? { toolMetadata: part.toolMetadata } : {},\n\t\t\t\t\t\t\t...dynamic != null ? { dynamic } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"tool-output-denied\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"tool-output-denied\",\n\t\t\t\t\t\t\ttoolCallId: part.toolCallId\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\terrorText: onError(part.error)\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish-step\":\n\t\t\t\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"start\":\n\t\t\t\t\t\tif (sendStart) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"start\",\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},\n\t\t\t\t\t\t\t...responseMessageId != null ? { messageId: responseMessageId } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tif (sendFinish) controller.enqueue({\n\t\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\t\tfinishReason: part.finishReason,\n\t\t\t\t\t\t\t...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}\n\t\t\t\t\t\t});\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"abort\":\n\t\t\t\t\t\tcontroller.enqueue(part);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"tool-input-end\": break;\n\t\t\t\t\tcase \"raw\": break;\n\t\t\t\t\tdefault: throw new Error(`Unknown chunk type: ${partType}`);\n\t\t\t\t}\n\t\t\t\tif (messageMetadataValue != null && partType !== \"start\" && partType !== \"finish\") controller.enqueue({\n\t\t\t\t\ttype: \"message-metadata\",\n\t\t\t\t\tmessageMetadata: messageMetadataValue\n\t\t\t\t});\n\t\t\t\tif (part.type === \"finish\") setSourceOutcome({ status: \"completed\" });\n\t\t\t\telse if (part.type === \"abort\") setSourceOutcome({ status: \"aborted\" });\n\t\t\t\telse if (part.type === \"error\") setSourceOutcome({\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\terror: part.error\n\t\t\t\t});\n\t\t\t} }))),\n\t\t\tmessageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),\n\t\t\toriginalMessages,\n\t\t\tonFinish,\n\t\t\tonError,\n\t\t\tgetOutcome: () => outcome\n\t\t}));\n\t}\n\tpipeUIMessageStreamToResponse(response, { originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn pipeUIMessageStreamToResponse({\n\t\t\tresponse,\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoUIMessageStreamResponse({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning, sendSources, sendFinish, sendStart, onError, ...init } = {}) {\n\t\treturn createUIMessageStreamResponse({\n\t\t\tstream: this.toUIMessageStream({\n\t\t\t\toriginalMessages,\n\t\t\t\tgenerateMessageId,\n\t\t\t\tonFinish,\n\t\t\t\tmessageMetadata,\n\t\t\t\tsendReasoning,\n\t\t\t\tsendSources,\n\t\t\t\tsendFinish,\n\t\t\t\tsendStart,\n\t\t\t\tonError\n\t\t\t}),\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nvar ToolLoopAgent = class {\n\tconstructor(settings) {\n\t\tthis.version = \"agent-v1\";\n\t\tthis.settings = settings;\n\t}\n\t/**\n\t* The id of the agent.\n\t*/\n\tget id() {\n\t\treturn this.settings.id;\n\t}\n\t/**\n\t* The tools that the agent can use.\n\t*/\n\tget tools() {\n\t\treturn this.settings.tools;\n\t}\n\tasync prepareCall(options) {\n\t\tvar _a23, _b, _c, _d;\n\t\tif (this.settings.callOptionsSchema != null && options.options !== void 0) {\n\t\t\tconst validatedOptions = await validateTypes({\n\t\t\t\tvalue: options.options,\n\t\t\t\tschema: this.settings.callOptionsSchema,\n\t\t\t\tcontext: { field: \"options\" }\n\t\t\t});\n\t\t\toptions = {\n\t\t\t\t...options,\n\t\t\t\toptions: validatedOptions\n\t\t\t};\n\t\t}\n\t\tconst { onStepFinish: _settingsOnStepFinish, ...settingsWithoutCallback } = this.settings;\n\t\tconst baseCallArgs = {\n\t\t\t...settingsWithoutCallback,\n\t\t\tstopWhen: (_a23 = this.settings.stopWhen) != null ? _a23 : stepCountIs(20),\n\t\t\t...options\n\t\t};\n\t\tconst { instructions, allowSystemInMessages, messages, prompt, ...callArgs } = (_d = await ((_c = (_b = this.settings).prepareCall) == null ? void 0 : _c.call(_b, baseCallArgs))) != null ? _d : baseCallArgs;\n\t\treturn {\n\t\t\t...callArgs,\n\t\t\tsystem: instructions,\n\t\t\tallowSystemInMessages,\n\t\t\tmessages,\n\t\t\tprompt\n\t\t};\n\t}\n\tmergeOnStepFinishCallbacks(methodCallback) {\n\t\tconst constructorCallback = this.settings.onStepFinish;\n\t\tif (methodCallback && constructorCallback) return async (stepResult) => {\n\t\t\tawait constructorCallback(stepResult);\n\t\t\tawait methodCallback(stepResult);\n\t\t};\n\t\treturn methodCallback != null ? methodCallback : constructorCallback;\n\t}\n\t/**\n\t* Generates an output from the agent (non-streaming).\n\t*/\n\tasync generate({ abortSignal, timeout, onStepFinish, ...options }) {\n\t\tconst preparedCall = await this.prepareCall(options);\n\t\treturn generateText({\n\t\t\t...preparedCall,\n\t\t\tabortSignal,\n\t\t\ttimeout: timeout != null ? timeout : preparedCall.timeout,\n\t\t\tonStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)\n\t\t});\n\t}\n\t/**\n\t* Streams an output from the agent (streaming).\n\t*/\n\tasync stream({ abortSignal, timeout, experimental_transform, onStepFinish, ...options }) {\n\t\tconst preparedCall = await this.prepareCall(options);\n\t\treturn streamText({\n\t\t\t...preparedCall,\n\t\t\tabortSignal,\n\t\t\ttimeout: timeout != null ? timeout : preparedCall.timeout,\n\t\t\texperimental_transform,\n\t\t\tonStepFinish: this.mergeOnStepFinishCallbacks(onStepFinish)\n\t\t});\n\t}\n};\nfunction createUIMessageStream({ execute, onError = () => \"An error occurred.\", originalMessages, onStepFinish, onFinish, generateId: generateId2 = generateId }) {\n\tlet controller;\n\tconst ongoingStreamPromises = [];\n\tlet outcome = { status: \"unknown\" };\n\tconst stream = new ReadableStream({ start(controllerArg) {\n\t\tcontroller = controllerArg;\n\t} });\n\tfunction safeEnqueue(data) {\n\t\ttry {\n\t\t\tcontroller.enqueue(data);\n\t\t} catch (error) {}\n\t}\n\tfunction setOutcome(newOutcome) {\n\t\tif (outcome.status === \"unknown\" && newOutcome.status !== \"unknown\") outcome = newOutcome;\n\t}\n\tfunction failOutcome(error) {\n\t\toutcome = {\n\t\t\tstatus: \"failed\",\n\t\t\terror\n\t\t};\n\t}\n\tfunction safeError(error) {\n\t\ttry {\n\t\t\tcontroller.error(error);\n\t\t} catch (e) {}\n\t}\n\tfunction handleError(error) {\n\t\tfailOutcome(error);\n\t\tlet errorText;\n\t\ttry {\n\t\t\terrorText = onError(error);\n\t\t} catch (onErrorError) {\n\t\t\tfailOutcome(onErrorError);\n\t\t\tsafeError(onErrorError);\n\t\t\treturn;\n\t\t}\n\t\tsafeEnqueue({\n\t\t\ttype: \"error\",\n\t\t\terrorText\n\t\t});\n\t}\n\ttry {\n\t\tconst result = execute({ writer: {\n\t\t\twrite(part) {\n\t\t\t\tsafeEnqueue(part);\n\t\t\t},\n\t\t\tmerge(streamArg) {\n\t\t\t\tongoingStreamPromises.push((async () => {\n\t\t\t\t\tconst reader = streamArg.getReader();\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tconst { done, value } = await reader.read();\n\t\t\t\t\t\tif (done) break;\n\t\t\t\t\t\tsafeEnqueue(value);\n\t\t\t\t\t}\n\t\t\t\t})().catch((error) => {\n\t\t\t\t\thandleError(error);\n\t\t\t\t}));\n\t\t\t},\n\t\t\tsetOutcome,\n\t\t\tonError\n\t\t} });\n\t\tif (result) ongoingStreamPromises.push(result.catch((error) => {\n\t\t\thandleError(error);\n\t\t}));\n\t} catch (error) {\n\t\thandleError(error);\n\t}\n\t(async () => {\n\t\twhile (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();\n\t})().finally(() => {\n\t\ttry {\n\t\t\tcontroller.close();\n\t\t} catch (error) {}\n\t});\n\treturn handleUIMessageStreamFinish({\n\t\tstream,\n\t\tmessageId: generateId2(),\n\t\toriginalMessages,\n\t\tonStepFinish,\n\t\tonFinish,\n\t\tonError,\n\t\tgetOutcome: () => outcome\n\t});\n}\nfunction createUIMessageSnapshot(message) {\n\tconst textByPartIndex = /* @__PURE__ */ new Map();\n\tconst messageWithoutText = {\n\t\t...message,\n\t\tparts: message.parts.map((part, index) => {\n\t\t\tif (part.type === \"text\" || part.type === \"reasoning\") {\n\t\t\t\ttextByPartIndex.set(index, part.text);\n\t\t\t\treturn {\n\t\t\t\t\t...part,\n\t\t\t\t\ttext: \"\"\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn part;\n\t\t})\n\t};\n\tconst snapshot = structuredClone(messageWithoutText);\n\tfor (const [index, text2] of textByPartIndex) {\n\t\tconst part = snapshot.parts[index];\n\t\tif (part.type === \"text\" || part.type === \"reasoning\") part.text = text2;\n\t}\n\treturn snapshot;\n}\nfunction readUIMessageStream({ message, stream, onError, terminateOnError = false }) {\n\tvar _a23;\n\tlet controller;\n\tlet hasErrored = false;\n\tlet isCancelled = false;\n\tconst abortController = new AbortController();\n\tconst outputStream = new ReadableStream({\n\t\tstart(controllerParam) {\n\t\t\tcontroller = controllerParam;\n\t\t},\n\t\tcancel() {\n\t\t\tisCancelled = true;\n\t\t\tabortController.abort();\n\t\t}\n\t});\n\tconst state = createStreamingUIMessageState({\n\t\tmessageId: (_a23 = message == null ? void 0 : message.id) != null ? _a23 : \"\",\n\t\tlastMessage: message\n\t});\n\tconst handleError = (error) => {\n\t\tonError?.(error);\n\t\tif (!hasErrored && terminateOnError) {\n\t\t\thasErrored = true;\n\t\t\tcontroller?.error(error);\n\t\t}\n\t};\n\tconsumeStream({\n\t\tstream: processUIMessageStream({\n\t\t\tstream,\n\t\t\tresetStateOnMessageIdChange: true,\n\t\t\trunUpdateMessageJob(job) {\n\t\t\t\treturn job({\n\t\t\t\t\tstate,\n\t\t\t\t\twrite: () => {\n\t\t\t\t\t\tif (!isCancelled) controller?.enqueue(createUIMessageSnapshot(state.message));\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t},\n\t\t\tonError: handleError\n\t\t}),\n\t\tonError: handleError,\n\t\tabortSignal: abortController.signal\n\t}).finally(() => {\n\t\tif (!hasErrored && !isCancelled) controller?.close();\n\t});\n\treturn createAsyncIterableStream(outputStream);\n}\nfunction getOwn(obj, key) {\n\treturn obj != null && Object.hasOwn(obj, key) ? obj[key] : void 0;\n}\nfunction markToolPartAsUnavailable(part) {\n\tpart.dynamic = false;\n\treturn part;\n}\nfunction isToolPartFromUnavailableTool(part) {\n\treturn part.type === \"dynamic-tool\" && part.dynamic === false;\n}\nasync function convertToModelMessages(messages, options) {\n\tconst modelMessages = [];\n\tif (options == null ? void 0 : options.ignoreIncompleteToolCalls) messages = messages.map((message) => ({\n\t\t...message,\n\t\tparts: message.parts.filter((part) => !isToolUIPart(part) || part.state === \"approval-responded\" || part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\" || part.state === \"output-denied\")\n\t}));\n\tasync function createModelOutput({ toolPart, toolName, output, errorMode }) {\n\t\tconst tool2 = getOwn(options == null ? void 0 : options.tools, toolName);\n\t\tif (errorMode === \"none\" && tool2 == null && isToolPartFromUnavailableTool(toolPart)) return {\n\t\t\ttype: \"text\",\n\t\t\tvalue: \"Tool output omitted because the tool is no longer available.\"\n\t\t};\n\t\treturn createToolModelOutput({\n\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\tinput: toolPart.input,\n\t\t\toutput,\n\t\t\ttool: tool2,\n\t\t\terrorMode\n\t\t});\n\t}\n\tfor (const message of messages) switch (message.role) {\n\t\tcase \"system\": {\n\t\t\tconst textParts = message.parts.filter((part) => part.type === \"text\");\n\t\t\tconst providerMetadata = textParts.reduce((acc, part) => {\n\t\t\t\tif (part.providerMetadata != null) return {\n\t\t\t\t\t...acc,\n\t\t\t\t\t...part.providerMetadata\n\t\t\t\t};\n\t\t\t\treturn acc;\n\t\t\t}, {});\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"system\",\n\t\t\t\tcontent: textParts.map((part) => part.text).join(\"\"),\n\t\t\t\t...Object.keys(providerMetadata).length > 0 ? { providerOptions: providerMetadata } : {}\n\t\t\t});\n\t\t\tbreak;\n\t\t}\n\t\tcase \"user\":\n\t\t\tmodelMessages.push({\n\t\t\t\trole: \"user\",\n\t\t\t\tcontent: message.parts.map((part) => {\n\t\t\t\t\tvar _a23;\n\t\t\t\t\tif (isTextUIPart(part)) return {\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isFileUIPart(part)) return {\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t};\n\t\t\t\t\tif (isDataUIPart(part)) return (_a23 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a23.call(options, part);\n\t\t\t\t}).filter(isNonNullable)\n\t\t\t});\n\t\t\tbreak;\n\t\tcase \"assistant\":\n\t\t\tif (message.parts != null) {\n\t\t\t\tlet block = [];\n\t\t\t\tasync function processBlock() {\n\t\t\t\t\tvar _a23, _b, _c, _d, _e, _f, _g;\n\t\t\t\t\tif (block.length === 0) return;\n\t\t\t\t\tconst content = [];\n\t\t\t\t\tfor (const part of block) if (isTextUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isFileUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"file\",\n\t\t\t\t\t\tmediaType: part.mediaType,\n\t\t\t\t\t\tfilename: part.filename,\n\t\t\t\t\t\tdata: part.url,\n\t\t\t\t\t\t...part.providerMetadata != null ? { providerOptions: part.providerMetadata } : {}\n\t\t\t\t\t});\n\t\t\t\t\telse if (isReasoningUIPart(part)) content.push({\n\t\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\t\ttext: part.text,\n\t\t\t\t\t\tproviderOptions: part.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\telse if (isToolUIPart(part)) {\n\t\t\t\t\t\tconst toolName = getToolName(part);\n\t\t\t\t\t\tif (part.state !== \"input-streaming\") {\n\t\t\t\t\t\t\tconst callProviderMetadata = (_a23 = part.callProviderMetadata) != null ? _a23 : part.state === \"output-error\" ? part.resultProviderMetadata : void 0;\n\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\ttype: \"tool-call\",\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\tinput: part.state === \"output-error\" ? (_b = part.input) != null ? _b : \"rawInput\" in part ? part.rawInput : void 0 : part.input,\n\t\t\t\t\t\t\t\tproviderExecuted: part.providerExecuted,\n\t\t\t\t\t\t\t\t...callProviderMetadata != null ? { providerOptions: callProviderMetadata } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.approval != null) content.push({\n\t\t\t\t\t\t\t\ttype: \"tool-approval-request\",\n\t\t\t\t\t\t\t\tapprovalId: part.approval.id,\n\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\t...Object.prototype.hasOwnProperty.call(part.approval, \"inputSchemaInput\") ? { inputSchemaInput: part.approval.inputSchemaInput } : {},\n\t\t\t\t\t\t\t\t...part.approval.signature != null ? { signature: part.approval.signature } : {}\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (part.providerExecuted === true && part.state !== \"approval-responded\" && (part.state === \"output-available\" || part.state === \"output-error\")) {\n\t\t\t\t\t\t\t\tconst resultProviderMetadata = (_c = part.resultProviderMetadata) != null ? _c : part.callProviderMetadata;\n\t\t\t\t\t\t\t\tcontent.push({\n\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\toutput: await createModelOutput({\n\t\t\t\t\t\t\t\t\t\ttoolPart: part,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: part.state === \"output-error\" ? part.errorText : part.output,\n\t\t\t\t\t\t\t\t\t\terrorMode: part.state === \"output-error\" ? \"json\" : \"none\"\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...resultProviderMetadata != null ? { providerOptions: resultProviderMetadata } : {}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t} else if (isDataUIPart(part)) {\n\t\t\t\t\t\tconst dataPart = (_d = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _d.call(options, part);\n\t\t\t\t\t\tif (dataPart != null) content.push(dataPart);\n\t\t\t\t\t} else throw new Error(`Unsupported part: ${part}`);\n\t\t\t\t\tif (content.length > 0) modelMessages.push({\n\t\t\t\t\t\trole: \"assistant\",\n\t\t\t\t\t\tcontent\n\t\t\t\t\t});\n\t\t\t\t\tconst toolParts = block.filter((part) => {\n\t\t\t\t\t\tvar _a24;\n\t\t\t\t\t\treturn isToolUIPart(part) && (part.providerExecuted !== true || ((_a24 = part.approval) == null ? void 0 : _a24.approved) != null);\n\t\t\t\t\t});\n\t\t\t\t\tif (toolParts.length > 0) {\n\t\t\t\t\t\tconst content2 = [];\n\t\t\t\t\t\tfor (const toolPart of toolParts) {\n\t\t\t\t\t\t\tif (((_e = toolPart.approval) == null ? void 0 : _e.approved) != null) content2.push({\n\t\t\t\t\t\t\t\ttype: \"tool-approval-response\",\n\t\t\t\t\t\t\t\tapprovalId: toolPart.approval.id,\n\t\t\t\t\t\t\t\tapproved: toolPart.approval.approved,\n\t\t\t\t\t\t\t\treason: toolPart.approval.reason,\n\t\t\t\t\t\t\t\tproviderExecuted: toolPart.providerExecuted\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (toolPart.providerExecuted === true) continue;\n\t\t\t\t\t\t\tswitch (toolPart.state) {\n\t\t\t\t\t\t\t\tcase \"output-denied\":\n\t\t\t\t\t\t\t\t\tcontent2.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName: getToolName(toolPart),\n\t\t\t\t\t\t\t\t\t\toutput: {\n\t\t\t\t\t\t\t\t\t\t\ttype: \"error-text\",\n\t\t\t\t\t\t\t\t\t\t\tvalue: (_g = (_f = toolPart.approval) == null ? void 0 : _f.reason) != null ? _g : \"Tool call execution denied.\"\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\tcase \"output-error\":\n\t\t\t\t\t\t\t\tcase \"output-available\": {\n\t\t\t\t\t\t\t\t\tconst toolName = getToolName(toolPart);\n\t\t\t\t\t\t\t\t\tcontent2.push({\n\t\t\t\t\t\t\t\t\t\ttype: \"tool-result\",\n\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\toutput: await createModelOutput({\n\t\t\t\t\t\t\t\t\t\t\ttoolPart,\n\t\t\t\t\t\t\t\t\t\t\ttoolName,\n\t\t\t\t\t\t\t\t\t\t\toutput: toolPart.state === \"output-error\" ? toolPart.errorText : toolPart.output,\n\t\t\t\t\t\t\t\t\t\t\terrorMode: toolPart.state === \"output-error\" ? \"text\" : \"none\"\n\t\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t\t...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (content2.length > 0) modelMessages.push({\n\t\t\t\t\t\t\trole: \"tool\",\n\t\t\t\t\t\t\tcontent: content2\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tblock = [];\n\t\t\t\t}\n\t\t\t\tfor (const part of message.parts) if (isTextUIPart(part) || isReasoningUIPart(part) || isFileUIPart(part) || isToolUIPart(part) || isDataUIPart(part)) block.push(part);\n\t\t\t\telse if (part.type === \"step-start\") await processBlock();\n\t\t\t\tawait processBlock();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault: {\n\t\t\tconst _exhaustiveCheck = message.role;\n\t\t\tthrow new MessageConversionError({\n\t\t\t\toriginalMessage: message,\n\t\t\t\tmessage: `Unsupported role: ${_exhaustiveCheck}`\n\t\t\t});\n\t\t}\n\t}\n\treturn modelMessages;\n}\nvar toolMetadataSchema2 = z.record(z.string(), jsonValueSchema.optional());\nfunction isEmptyObject(value) {\n\treturn value != null && typeof value === \"object\" && !Array.isArray(value) && Object.keys(value).length === 0;\n}\nfunction asDynamicToolPart(toolPart) {\n\tconst { type, ...part } = toolPart;\n\treturn markToolPartAsUnavailable({\n\t\t...part,\n\t\ttype: \"dynamic-tool\",\n\t\ttoolName: type.slice(5)\n\t});\n}\nfunction getToolPartInputSchemaInput(toolPart) {\n\treturn toolPart.approval != null && Object.prototype.hasOwnProperty.call(toolPart.approval, \"inputSchemaInput\") ? { value: toolPart.approval.inputSchemaInput } : void 0;\n}\nvar uiMessagesSchema = lazySchema(() => {\n\tconst approvalRequestedSchema = z.object({\n\t\tid: z.string(),\n\t\tapproved: z.never().optional(),\n\t\tdescriptor: z.unknown().optional(),\n\t\treason: z.never().optional(),\n\t\tsignature: z.string().optional(),\n\t\tinputSchemaInput: z.unknown().optional()\n\t});\n\tconst approvalRespondedSchema = approvalRequestedSchema.extend({\n\t\tapproved: z.boolean(),\n\t\treason: z.string().optional()\n\t});\n\tconst approvalGrantedSchema = approvalRespondedSchema.extend({ approved: z.literal(true) });\n\tconst approvalDeniedSchema = approvalRespondedSchema.extend({ approved: z.literal(false) });\n\treturn zodSchema(z.array(z.object({\n\t\tid: z.string(),\n\t\trole: z.enum([\n\t\t\t\"system\",\n\t\t\t\"user\",\n\t\t\t\"assistant\"\n\t\t]),\n\t\tmetadata: z.unknown().optional(),\n\t\tparts: z.array(z.union([\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"text\"),\n\t\t\t\ttext: z.string(),\n\t\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"reasoning\"),\n\t\t\t\tid: z.string().optional(),\n\t\t\t\ttext: z.string(),\n\t\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"source-url\"),\n\t\t\t\tsourceId: z.string(),\n\t\t\t\turl: z.string(),\n\t\t\t\ttitle: z.string().optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"source-document\"),\n\t\t\t\tsourceId: z.string(),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\ttitle: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"file\"),\n\t\t\t\tmediaType: z.string(),\n\t\t\t\tfilename: z.string().optional(),\n\t\t\t\turl: z.string(),\n\t\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t\t}),\n\t\t\tz.object({ type: z.literal(\"step-start\") }),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"data-\"),\n\t\t\t\tid: z.string().optional(),\n\t\t\t\tdata: z.unknown()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.string().optional(),\n\t\t\t\tinputEncoding: z.enum([\"json\", \"text\"]).optional(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"input-available\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRequestedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRespondedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-available\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.unknown(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tpreliminary: z.boolean().optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-error\"),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.unknown().optional(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.string(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\t\tdynamic: z.literal(false).optional(),\n\t\t\t\ttoolName: z.string(),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalDeniedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.string().optional(),\n\t\t\t\tinputEncoding: z.enum([\"json\", \"text\"]).optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"input-available\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: z.never().optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRequestedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalRespondedSchema\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-available\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.unknown(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tpreliminary: z.boolean().optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-error\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown().optional(),\n\t\t\t\trawInput: z.unknown().optional(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.string(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalGrantedSchema.optional()\n\t\t\t}),\n\t\t\tz.object({\n\t\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\t\ttoolCallId: z.string(),\n\t\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\t\tinput: z.unknown(),\n\t\t\t\toutput: z.never().optional(),\n\t\t\t\terrorText: z.never().optional(),\n\t\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\t\tapproval: approvalDeniedSchema\n\t\t\t})\n\t\t]))\n\t}).superRefine((message, context2) => {\n\t\tif (message.role !== \"assistant\" && message.parts.length === 0) context2.addIssue({\n\t\t\torigin: \"array\",\n\t\t\tcode: \"too_small\",\n\t\t\tminimum: 1,\n\t\t\tinclusive: true,\n\t\t\tinput: message.parts,\n\t\t\tpath: [\"parts\"],\n\t\t\tmessage: \"Message must contain at least one part\"\n\t\t});\n\t})).nonempty(\"Messages array must not be empty\"));\n});\nasync function safeValidateUIMessagesInternal({ messages, metadataSchema, dataSchemas, tools }, { convertMissingTerminalToolsToDynamic }) {\n\ttry {\n\t\tif (messages == null) return {\n\t\t\tsuccess: false,\n\t\t\terror: new InvalidArgumentError({\n\t\t\t\tparameter: \"messages\",\n\t\t\t\tvalue: messages,\n\t\t\t\tmessage: \"messages parameter must be provided\"\n\t\t\t})\n\t\t};\n\t\tconst validatedMessages = await validateTypes({\n\t\t\tvalue: messages,\n\t\t\tschema: uiMessagesSchema\n\t\t});\n\t\tif (metadataSchema) for (const [msgIdx, message] of validatedMessages.entries()) message.metadata = await validateTypes({\n\t\t\tvalue: message.metadata,\n\t\t\tschema: metadataSchema,\n\t\t\tcontext: {\n\t\t\t\tfield: `messages[${msgIdx}].metadata`,\n\t\t\t\tentityId: message.id\n\t\t\t}\n\t\t});\n\t\tconst shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;\n\t\tif (dataSchemas || shouldValidateToolParts) for (const [msgIdx, message] of validatedMessages.entries()) for (const [partIdx, part] of message.parts.entries()) {\n\t\t\tif (dataSchemas && part.type.startsWith(\"data-\")) {\n\t\t\t\tconst dataPart = part;\n\t\t\t\tconst dataName = dataPart.type.slice(5);\n\t\t\t\tconst dataSchema = dataSchemas[dataName];\n\t\t\t\tif (!dataSchema) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\t\tcause: `No data schema found for data part ${dataName}`,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].data`,\n\t\t\t\t\t\t\tentityName: dataName,\n\t\t\t\t\t\t\tentityId: dataPart.id\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tdataPart.data = await validateTypes({\n\t\t\t\t\tvalue: dataPart.data,\n\t\t\t\t\tschema: dataSchema,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].data`,\n\t\t\t\t\t\tentityName: dataName,\n\t\t\t\t\t\tentityId: dataPart.id\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (shouldValidateToolParts && part.type.startsWith(\"tool-\")) {\n\t\t\t\tconst toolPart = part;\n\t\t\t\tconst toolName = toolPart.type.slice(5);\n\t\t\t\tconst tool2 = getOwn(tools, toolName);\n\t\t\t\tconst isTerminal = toolPart.state === \"output-available\" || toolPart.state === \"output-error\" || toolPart.state === \"output-denied\";\n\t\t\t\tif (!tool2 && isTerminal) {\n\t\t\t\t\tif (tools != null || convertMissingTerminalToolsToDynamic) message.parts[partIdx] = asDynamicToolPart(toolPart);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!tool2) return {\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\tcause: `No tool schema found for tool part ${toolName}`,\n\t\t\t\t\t\tcontext: {\n\t\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].input`,\n\t\t\t\t\t\t\tentityName: toolName,\n\t\t\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t\t\t}\n\t\t\t\t\t})\n\t\t\t\t};\n\t\t\t\tconst inputValidationContext = {\n\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].input`,\n\t\t\t\t\tentityName: toolName,\n\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t};\n\t\t\t\tconst inputSchemaInput = getToolPartInputSchemaInput(toolPart);\n\t\t\t\tconst inputToValidate = inputSchemaInput == null ? toolPart.input : inputSchemaInput.value;\n\t\t\t\tlet convertToDynamic = false;\n\t\t\t\tif (toolPart.state !== \"input-streaming\" && (toolPart.state !== \"output-error\" || inputSchemaInput != null || toolPart.input !== void 0)) {\n\t\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\t\tvalue: inputToValidate,\n\t\t\t\t\t\tschema: tool2.inputSchema,\n\t\t\t\t\t\tcontext: inputValidationContext\n\t\t\t\t\t});\n\t\t\t\t\tlet inputError;\n\t\t\t\t\tif (!result.success) inputError = result.error;\n\t\t\t\t\telse if (inputSchemaInput != null) {\n\t\t\t\t\t\tif (!isDeepEqualData(result.value, toolPart.input)) inputError = new TypeValidationError({\n\t\t\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\t\t\tcause: \"Tool input does not match the output reconstructed from inputSchemaInput.\",\n\t\t\t\t\t\t\tcontext: inputValidationContext\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t\tif (inputError != null) {\n\t\t\t\t\t\tif (toolPart.state === \"output-error\" || toolPart.state === \"output-available\" && isEmptyObject(toolPart.input)) convertToDynamic = true;\n\t\t\t\t\t\telse throw inputError;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (toolPart.state === \"output-available\" && tool2.outputSchema) await validateTypes({\n\t\t\t\t\tvalue: toolPart.output,\n\t\t\t\t\tschema: tool2.outputSchema,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].output`,\n\t\t\t\t\t\tentityName: toolName,\n\t\t\t\t\t\tentityId: toolPart.toolCallId\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tif (convertToDynamic) message.parts[partIdx] = asDynamicToolPart(toolPart);\n\t\t\t}\n\t\t}\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tdata: validatedMessages\n\t\t};\n\t} catch (error) {\n\t\treturn {\n\t\t\tsuccess: false,\n\t\t\terror\n\t\t};\n\t}\n}\nasync function safeValidateUIMessages(options) {\n\treturn safeValidateUIMessagesInternal(options, { convertMissingTerminalToolsToDynamic: false });\n}\nasync function validateUIMessages(options) {\n\tconst response = await safeValidateUIMessages(options);\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\nasync function validateUIMessagesForAgent(options) {\n\tconst response = await safeValidateUIMessagesInternal(options, { convertMissingTerminalToolsToDynamic: true });\n\tif (!response.success) throw response.error;\n\treturn response.data;\n}\nasync function createAgentUIStream({ agent, uiMessages, options, abortSignal, timeout, experimental_transform, onStepFinish, ...uiMessageStreamOptions }) {\n\tvar _a23;\n\tconst validatedMessages = await validateUIMessagesForAgent({\n\t\tmessages: uiMessages != null ? uiMessages : uiMessageStreamOptions.originalMessages,\n\t\ttools: agent.tools\n\t});\n\tconst modelMessages = await convertToModelMessages(validatedMessages, { tools: agent.tools });\n\treturn (await agent.stream({\n\t\tprompt: modelMessages,\n\t\toptions,\n\t\tabortSignal,\n\t\ttimeout,\n\t\texperimental_transform,\n\t\tonStepFinish\n\t})).toUIMessageStream({\n\t\t...uiMessageStreamOptions,\n\t\toriginalMessages: (_a23 = uiMessageStreamOptions.originalMessages) != null ? _a23 : validatedMessages\n\t});\n}\nasync function createAgentUIStreamResponse({ headers, status, statusText, keepAliveMs, consumeSseStream, ...options }) {\n\treturn createUIMessageStreamResponse({\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\n\t\tkeepAliveMs,\n\t\tconsumeSseStream,\n\t\tstream: await createAgentUIStream(options)\n\t});\n}\nasync function pipeAgentUIStreamToResponse({ response, headers, status, statusText, keepAliveMs, consumeSseStream, ...options }) {\n\treturn pipeUIMessageStreamToResponse({\n\t\tresponse,\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\n\t\tkeepAliveMs,\n\t\tconsumeSseStream,\n\t\tstream: await createAgentUIStream(options)\n\t});\n}\nasync function embed({ model: modelArg, value, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embed\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embed\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.value\": { input: () => JSON.stringify(value) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tconst { embedding, usage, warnings, response, providerMetadata } = await retry(() => recordSpan({\n\t\t\t\tname: \"ai.embed.doEmbed\",\n\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\toperationId: \"ai.embed.doEmbed\",\n\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\"ai.values\": { input: () => [JSON.stringify(value)] }\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttracer,\n\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\tvar _a23, _b;\n\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\tvalues: [value],\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t});\n\t\t\t\t\tconst embedding2 = modelResponse.embeddings[0];\n\t\t\t\t\tconst usage2 = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };\n\t\t\t\t\tdoEmbedSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => modelResponse.embeddings.map((embedding3) => JSON.stringify(embedding3)) },\n\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\tif (embedding2 == null) throw new InvalidResponseDataError({\n\t\t\t\t\t\tdata: modelResponse.embeddings,\n\t\t\t\t\t\tmessage: \"No embedding generated.\"\n\t\t\t\t\t});\n\t\t\t\t\treturn {\n\t\t\t\t\t\tembedding: embedding2,\n\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\twarnings: (_b = modelResponse.warnings) != null ? _b : [],\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}));\n\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embedding\": { output: () => JSON.stringify(embedding) },\n\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\tlogWarnings({\n\t\t\t\twarnings,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodel: model.modelId\n\t\t\t});\n\t\t\treturn new DefaultEmbedResult({\n\t\t\t\tvalue,\n\t\t\t\tembedding,\n\t\t\t\tusage,\n\t\t\t\twarnings,\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponse\n\t\t\t});\n\t\t}\n\t});\n}\nvar DefaultEmbedResult = class {\n\tconstructor(options) {\n\t\tthis.value = options.value;\n\t\tthis.embedding = options.embedding;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t}\n};\nfunction setOwn(object2, key, value) {\n\tObject.defineProperty(object2, key, {\n\t\tvalue,\n\t\tenumerable: true,\n\t\tconfigurable: true,\n\t\twritable: true\n\t});\n}\nfunction getEmbeddingModelMaxInputBytesPerCall(model) {\n\treturn model[EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL];\n}\nfunction getEmbeddingModelProviderOptionsTransformer(model) {\n\treturn model[EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER];\n}\nfunction splitArray(array2, chunkSize) {\n\tif (chunkSize <= 0) throw new Error(\"chunkSize must be greater than 0\");\n\tconst result = [];\n\tfor (let i = 0; i < array2.length; i += chunkSize) result.push(array2.slice(i, i + chunkSize));\n\treturn result;\n}\nasync function embedMany({ model: modelArg, values, maxParallelCalls = Infinity, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) {\n\tconst model = resolveEmbeddingModel(modelArg);\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.embedMany\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.embedMany\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async (span) => {\n\t\t\tconst [maxEmbeddingsPerCall, maxInputBytesPerCall, supportsParallelCalls] = await Promise.all([\n\t\t\t\tmodel.maxEmbeddingsPerCall,\n\t\t\t\tgetEmbeddingModelMaxInputBytesPerCall(model),\n\t\t\t\tmodel.supportsParallelCalls\n\t\t\t]);\n\t\t\tconst hasEmbeddingLimit = maxEmbeddingsPerCall != null && maxEmbeddingsPerCall !== Infinity;\n\t\t\tconst hasInputByteLimit = maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;\n\t\t\tif (!hasEmbeddingLimit && !hasInputByteLimit) {\n\t\t\t\tconst { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(() => {\n\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\"ai.values\": { input: () => values.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}),\n\t\t\t\t\t\ttracer,\n\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\tvar _a23, _b;\n\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\tvalues,\n\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\tproviderOptions\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tconst embeddings3 = modelResponse.embeddings;\n\t\t\t\t\t\t\tconst usage2 = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };\n\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings3.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage2.tokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\tembeddings: embeddings3,\n\t\t\t\t\t\t\t\tusage: usage2,\n\t\t\t\t\t\t\t\twarnings: (_b = modelResponse.warnings) != null ? _b : [],\n\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings: warnings2,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\t\tvalues,\n\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\tusage,\n\t\t\t\t\twarnings: warnings2,\n\t\t\t\t\tproviderMetadata: providerMetadata2,\n\t\t\t\t\tresponses: [response]\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst valueChunks = splitByEmbeddingLimits({\n\t\t\t\tvalues,\n\t\t\t\tmaxEmbeddingsPerCall: hasEmbeddingLimit ? maxEmbeddingsPerCall : Infinity,\n\t\t\t\tmaxInputBytesPerCall: hasInputByteLimit ? maxInputBytesPerCall : Infinity\n\t\t\t});\n\t\t\tconst providerOptionsTransformer = getEmbeddingModelProviderOptionsTransformer(model);\n\t\t\tconst embeddings = [];\n\t\t\tconst warnings = [];\n\t\t\tconst responses = [];\n\t\t\tlet tokens = 0;\n\t\t\tlet providerMetadata;\n\t\t\tconst parallelChunks = splitArray(valueChunks, supportsParallelCalls ? maxParallelCalls : 1);\n\t\t\tlet nextChunkStartIndex = 0;\n\t\t\tfor (const parallelChunk of parallelChunks) {\n\t\t\t\tconst results = await Promise.all(parallelChunk.map(async (chunk) => {\n\t\t\t\t\tconst startIndex = nextChunkStartIndex;\n\t\t\t\t\tnextChunkStartIndex += chunk.length;\n\t\t\t\t\tconst chunkProviderOptions = providerOptionsTransformer ? await providerOptionsTransformer({\n\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\tvalues,\n\t\t\t\t\t\tstartIndex,\n\t\t\t\t\t\tendIndex: startIndex + chunk.length\n\t\t\t\t\t}) : providerOptions;\n\t\t\t\t\treturn retry(() => {\n\t\t\t\t\t\treturn recordSpan({\n\t\t\t\t\t\t\tname: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\t\t\toperationId: \"ai.embedMany.doEmbed\",\n\t\t\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\t\t\"ai.values\": { input: () => chunk.map((value) => JSON.stringify(value)) }\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\ttracer,\n\t\t\t\t\t\t\tfn: async (doEmbedSpan) => {\n\t\t\t\t\t\t\t\tvar _a23, _b;\n\t\t\t\t\t\t\t\tconst modelResponse = await model.doEmbed({\n\t\t\t\t\t\t\t\t\tvalues: chunk,\n\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\t\t\t\t\tproviderOptions: chunkProviderOptions\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tconst embeddings2 = modelResponse.embeddings;\n\t\t\t\t\t\t\t\tconst usage = (_a23 = modelResponse.usage) != null ? _a23 : { tokens: NaN };\n\t\t\t\t\t\t\t\tdoEmbedSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings2.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\t\t\t\t\t\"ai.usage.tokens\": usage.tokens\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t\t\tembeddings: embeddings2,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\twarnings: (_b = modelResponse.warnings) != null ? _b : [],\n\t\t\t\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\t\t\t\tresponse: modelResponse.response\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t\tfor (const result of results) {\n\t\t\t\t\tembeddings.push(...result.embeddings);\n\t\t\t\t\twarnings.push(...result.warnings);\n\t\t\t\t\tresponses.push(result.response);\n\t\t\t\t\ttokens += result.usage.tokens;\n\t\t\t\t\tif (result.providerMetadata) {\n\t\t\t\t\t\tif (!providerMetadata) providerMetadata = { ...result.providerMetadata };\n\t\t\t\t\t\telse for (const [providerName, metadata] of Object.entries(result.providerMetadata)) setOwn(providerMetadata, providerName, {\n\t\t\t\t\t\t\t...getOwn(providerMetadata, providerName),\n\t\t\t\t\t\t\t...metadata\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t\"ai.embeddings\": { output: () => embeddings.map((embedding) => JSON.stringify(embedding)) },\n\t\t\t\t\t\"ai.usage.tokens\": tokens\n\t\t\t\t}\n\t\t\t}));\n\t\t\tlogWarnings({\n\t\t\t\twarnings,\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodel: model.modelId\n\t\t\t});\n\t\t\treturn new DefaultEmbedManyResult({\n\t\t\t\tvalues,\n\t\t\t\tembeddings,\n\t\t\t\tusage: { tokens },\n\t\t\t\twarnings,\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponses\n\t\t\t});\n\t\t}\n\t});\n}\nvar textEncoder = new TextEncoder();\nfunction splitByEmbeddingLimits({ values, maxEmbeddingsPerCall, maxInputBytesPerCall }) {\n\tif (maxEmbeddingsPerCall <= 0) throw new Error(\"maxEmbeddingsPerCall must be greater than 0\");\n\tif (maxInputBytesPerCall <= 0) throw new Error(\"maxInputBytesPerCall must be greater than 0\");\n\tif (values.length === 0) return [];\n\tconst chunks = [];\n\tlet currentChunk = [];\n\tlet currentInputBytes = 0;\n\tfor (const value of values) {\n\t\tconst inputBytes = textEncoder.encode(value).length;\n\t\tif (currentChunk.length > 0 && (currentChunk.length >= maxEmbeddingsPerCall || currentInputBytes + inputBytes > maxInputBytesPerCall)) {\n\t\t\tchunks.push(currentChunk);\n\t\t\tcurrentChunk = [];\n\t\t\tcurrentInputBytes = 0;\n\t\t}\n\t\tcurrentChunk.push(value);\n\t\tcurrentInputBytes += inputBytes;\n\t}\n\tchunks.push(currentChunk);\n\treturn chunks;\n}\nvar DefaultEmbedManyResult = class {\n\tconstructor(options) {\n\t\tthis.values = options.values;\n\t\tthis.embeddings = options.embeddings;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.responses = options.responses;\n\t}\n};\nvar RetryableNoImageResultError = class extends Error {\n\tconstructor() {\n\t\tsuper(\"No image generated.\");\n\t\tthis.name = \"RetryableNoImageResultError\";\n\t}\n};\nasync function generateImage({ model: modelArg, prompt: promptArg, n = 1, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a23, _b;\n\tconst model = resolveImageModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal,\n\t\tadditionalRetryableError: (error) => error instanceof RetryableNoImageResultError\n\t});\n\tconst maxImagesPerCallWithDefault = (_a23 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a23 : 1;\n\tconst callCount = Math.ceil(n / maxImagesPerCallWithDefault);\n\tconst callImageCounts = Array.from({ length: callCount }, (_, i) => {\n\t\tif (i < callCount - 1) return maxImagesPerCallWithDefault;\n\t\tconst remainder = n % maxImagesPerCallWithDefault;\n\t\treturn remainder === 0 ? maxImagesPerCallWithDefault : remainder;\n\t});\n\tconst results = (await Promise.all(callImageCounts.map(async (callImageCount) => {\n\t\tconst callResults = [];\n\t\ttry {\n\t\t\tawait retry(async () => {\n\t\t\t\tconst { prompt, files, mask } = normalizePrompt(promptArg);\n\t\t\t\tconst result = await model.doGenerate({\n\t\t\t\t\tprompt,\n\t\t\t\t\tfiles,\n\t\t\t\t\tmask,\n\t\t\t\t\tn: callImageCount,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders: headersWithUserAgent,\n\t\t\t\t\tsize,\n\t\t\t\t\taspectRatio,\n\t\t\t\t\tseed,\n\t\t\t\t\tproviderOptions: providerOptions != null ? providerOptions : {}\n\t\t\t\t});\n\t\t\t\tcallResults.push(result);\n\t\t\t\tif (result.images.length === 0 && result.isRetryable !== false) throw new RetryableNoImageResultError();\n\t\t\t\treturn result;\n\t\t\t});\n\t\t\treturn callResults;\n\t\t} catch (error) {\n\t\t\tif ((error instanceof RetryableNoImageResultError ? error : RetryError.isInstance(error) && error.lastError instanceof RetryableNoImageResultError ? error.lastError : void 0) != null) return callResults;\n\t\t\tthrow error;\n\t\t}\n\t}))).flat();\n\tconst images = [];\n\tconst warnings = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tlet totalUsage = {\n\t\tinputTokens: void 0,\n\t\toutputTokens: void 0,\n\t\ttotalTokens: void 0\n\t};\n\tfor (const result of results) {\n\t\timages.push(...result.images.map((image) => {\n\t\t\tvar _a24;\n\t\t\treturn new DefaultGeneratedFile({\n\t\t\t\tdata: image,\n\t\t\t\tmediaType: (_a24 = detectMediaType({\n\t\t\t\t\tdata: image,\n\t\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t\t})) != null ? _a24 : \"image/png\"\n\t\t\t});\n\t\t}));\n\t\twarnings.push(...result.warnings);\n\t\tif (result.usage != null) totalUsage = addImageModelUsage(totalUsage, result.usage);\n\t\tif (result.providerMetadata) for (const [providerName, metadata] of Object.entries(result.providerMetadata)) if (providerName === \"gateway\") {\n\t\t\tconst currentEntry = providerMetadata[providerName];\n\t\t\tif (currentEntry != null && typeof currentEntry === \"object\") providerMetadata[providerName] = {\n\t\t\t\t...currentEntry,\n\t\t\t\t...metadata\n\t\t\t};\n\t\t\telse providerMetadata[providerName] = metadata;\n\t\t\tconst imagesValue = providerMetadata[providerName].images;\n\t\t\tif (Array.isArray(imagesValue) && imagesValue.length === 0) delete providerMetadata[providerName].images;\n\t\t} else {\n\t\t\tconst currentEntry = (_b = getOwn(providerMetadata, providerName)) != null ? _b : { images: [] };\n\t\t\tcurrentEntry.images.push(...result.providerMetadata[providerName].images);\n\t\t\tsetOwn(providerMetadata, providerName, currentEntry);\n\t\t}\n\t\tresponses.push(result.response);\n\t}\n\tlogWarnings({\n\t\twarnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\tif (!images.length) throw new NoImageGeneratedError({ responses });\n\treturn new DefaultGenerateImageResult({\n\t\timages,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata,\n\t\tusage: totalUsage\n\t});\n}\nvar DefaultGenerateImageResult = class {\n\tconstructor(options) {\n\t\tthis.images = options.images;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.usage = options.usage;\n\t}\n\tget image() {\n\t\treturn this.images[0];\n\t}\n};\nasync function invokeModelMaxImagesPerCall(model) {\n\tif (!(model.maxImagesPerCall instanceof Function)) return model.maxImagesPerCall;\n\treturn model.maxImagesPerCall({ modelId: model.modelId });\n}\nfunction normalizePrompt(prompt) {\n\tif (typeof prompt === \"string\") return {\n\t\tprompt,\n\t\tfiles: void 0,\n\t\tmask: void 0\n\t};\n\treturn {\n\t\tprompt: prompt.text,\n\t\tfiles: prompt.images.map(toImageModelV3File),\n\t\tmask: prompt.mask ? toImageModelV3File(prompt.mask) : void 0\n\t};\n}\nfunction toImageModelV3File(dataContent) {\n\tif (typeof dataContent === \"string\" && dataContent.startsWith(\"http\")) return {\n\t\ttype: \"url\",\n\t\turl: dataContent\n\t};\n\tif (typeof dataContent === \"string\" && dataContent.startsWith(\"data:\")) {\n\t\tconst { mediaType: dataUrlMediaType, base64Content } = splitDataUrl(dataContent);\n\t\tif (base64Content != null) {\n\t\t\tconst uint8Data2 = convertBase64ToUint8Array(base64Content);\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tdata: uint8Data2,\n\t\t\t\tmediaType: dataUrlMediaType || detectMediaType({\n\t\t\t\t\tdata: uint8Data2,\n\t\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t\t}) || \"image/png\"\n\t\t\t};\n\t\t}\n\t}\n\tconst uint8Data = convertDataContentToUint8Array(dataContent);\n\treturn {\n\t\ttype: \"file\",\n\t\tdata: uint8Data,\n\t\tmediaType: detectMediaType({\n\t\t\tdata: uint8Data,\n\t\t\tsignatures: imageMediaTypeSignatures\n\t\t}) || \"image/png\"\n\t};\n}\nvar experimental_generateImage = generateImage;\nvar noSchemaOutputStrategy = {\n\ttype: \"no-schema\",\n\tjsonSchema: async () => void 0,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value, context2) {\n\t\treturn value === void 0 ? {\n\t\t\tsuccess: false,\n\t\t\terror: new NoObjectGeneratedError({\n\t\t\t\tmessage: \"No object generated: response did not match schema.\",\n\t\t\t\ttext: context2.text,\n\t\t\t\tresponse: context2.response,\n\t\t\t\tusage: context2.usage,\n\t\t\t\tfinishReason: context2.finishReason\n\t\t\t})\n\t\t} : {\n\t\t\tsuccess: true,\n\t\t\tvalue\n\t\t};\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in no-schema mode\" });\n\t}\n};\nvar objectOutputStrategy = (schema) => ({\n\ttype: \"object\",\n\tjsonSchema: async () => await schema.jsonSchema,\n\tasync validatePartialResult({ value, textDelta }) {\n\t\treturn {\n\t\t\tsuccess: true,\n\t\t\tvalue: {\n\t\t\t\tpartial: value,\n\t\t\t\ttextDelta\n\t\t\t}\n\t\t};\n\t},\n\tasync validateFinalResult(value) {\n\t\treturn safeValidateTypes({\n\t\t\tvalue,\n\t\t\tschema\n\t\t});\n\t},\n\tcreateElementStream() {\n\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in object mode\" });\n\t}\n});\nvar arrayOutputStrategy = (schema) => {\n\treturn {\n\t\ttype: \"array\",\n\t\tjsonSchema: async () => {\n\t\t\tconst { $schema, ...itemSchema } = await schema.jsonSchema;\n\t\t\treturn {\n\t\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\t\ttype: \"object\",\n\t\t\t\tproperties: { elements: {\n\t\t\t\t\ttype: \"array\",\n\t\t\t\t\titems: itemSchema\n\t\t\t\t} },\n\t\t\t\trequired: [\"elements\"],\n\t\t\t\tadditionalProperties: false\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, latestObject, isFirstDelta, isFinalDelta }) {\n\t\t\tvar _a23;\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (let i = 0; i < inputArray.length; i++) {\n\t\t\t\tconst element = inputArray[i];\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (i === inputArray.length - 1 && !isFinalDelta) continue;\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\tconst publishedElementCount = (_a23 = latestObject == null ? void 0 : latestObject.length) != null ? _a23 : 0;\n\t\t\tlet textDelta = \"\";\n\t\t\tif (isFirstDelta) textDelta += \"[\";\n\t\t\tif (publishedElementCount > 0) textDelta += \",\";\n\t\t\ttextDelta += resultArray.slice(publishedElementCount).map((element) => JSON.stringify(element)).join(\",\");\n\t\t\tif (isFinalDelta) textDelta += \"]\";\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: resultArray,\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || !isJSONArray(value.elements)) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains an array of elements\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst inputArray = value.elements;\n\t\t\tconst resultArray = [];\n\t\t\tfor (const element of inputArray) {\n\t\t\t\tconst result = await safeValidateTypes({\n\t\t\t\t\tvalue: element,\n\t\t\t\t\tschema\n\t\t\t\t});\n\t\t\t\tif (!result.success) return result;\n\t\t\t\tresultArray.push(result.value);\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: resultArray\n\t\t\t};\n\t\t},\n\t\tcreateElementStream(originalStream) {\n\t\t\tlet publishedElements = 0;\n\t\t\treturn createAsyncIterableStream(originalStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\tcase \"object\": {\n\t\t\t\t\t\tconst array2 = chunk.object;\n\t\t\t\t\t\tfor (; publishedElements < array2.length; publishedElements++) controller.enqueue(array2[publishedElements]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcase \"finish\":\n\t\t\t\t\tcase \"error\": break;\n\t\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t\t}\n\t\t\t} })));\n\t\t}\n\t};\n};\nvar enumOutputStrategy = (enumValues) => {\n\treturn {\n\t\ttype: \"enum\",\n\t\tjsonSchema: async () => ({\n\t\t\t$schema: \"http://json-schema.org/draft-07/schema#\",\n\t\t\ttype: \"object\",\n\t\t\tproperties: { result: {\n\t\t\t\ttype: \"string\",\n\t\t\t\tenum: enumValues\n\t\t\t} },\n\t\t\trequired: [\"result\"],\n\t\t\tadditionalProperties: false\n\t\t}),\n\t\tasync validateFinalResult(value) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\treturn enumValues.includes(result) ? {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: result\n\t\t\t} : {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t},\n\t\tasync validatePartialResult({ value, textDelta }) {\n\t\t\tif (!isJSONObject(value) || typeof value.result !== \"string\") return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be an object that contains a string in the \\\"result\\\" property.\"\n\t\t\t\t})\n\t\t\t};\n\t\t\tconst result = value.result;\n\t\t\tconst possibleEnumValues = enumValues.filter((enumValue) => enumValue.startsWith(result));\n\t\t\tif (value.result.length === 0 || possibleEnumValues.length === 0) return {\n\t\t\t\tsuccess: false,\n\t\t\t\terror: new TypeValidationError({\n\t\t\t\t\tvalue,\n\t\t\t\t\tcause: \"value must be a string in the enum\"\n\t\t\t\t})\n\t\t\t};\n\t\t\treturn {\n\t\t\t\tsuccess: true,\n\t\t\t\tvalue: {\n\t\t\t\t\tpartial: possibleEnumValues.length > 1 ? result : possibleEnumValues[0],\n\t\t\t\t\ttextDelta\n\t\t\t\t}\n\t\t\t};\n\t\t},\n\t\tcreateElementStream() {\n\t\t\tthrow new UnsupportedFunctionalityError({ functionality: \"element streams in enum mode\" });\n\t\t}\n\t};\n};\nfunction getOutputStrategy({ output, schema, enumValues }) {\n\tswitch (output) {\n\t\tcase \"object\": return objectOutputStrategy(asSchema(schema));\n\t\tcase \"array\": return arrayOutputStrategy(asSchema(schema));\n\t\tcase \"enum\": return enumOutputStrategy(enumValues);\n\t\tcase \"no-schema\": return noSchemaOutputStrategy;\n\t\tdefault: throw new Error(`Unsupported output: ${output}`);\n\t}\n}\nasync function parseAndValidateObjectResult(result, outputStrategy, context2) {\n\tconst parseResult = await safeParseJSON({ text: result });\n\tif (!parseResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: could not parse the response.\",\n\t\tcause: parseResult.error,\n\t\ttext: result,\n\t\tresponse: context2.response,\n\t\tusage: context2.usage,\n\t\tfinishReason: context2.finishReason\n\t});\n\tconst validationResult = await outputStrategy.validateFinalResult(parseResult.value, {\n\t\ttext: result,\n\t\tresponse: context2.response,\n\t\tusage: context2.usage\n\t});\n\tif (!validationResult.success) throw new NoObjectGeneratedError({\n\t\tmessage: \"No object generated: response did not match schema.\",\n\t\tcause: validationResult.error,\n\t\ttext: result,\n\t\tresponse: context2.response,\n\t\tusage: context2.usage,\n\t\tfinishReason: context2.finishReason\n\t});\n\treturn validationResult.value;\n}\nasync function parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, context2) {\n\ttry {\n\t\treturn await parseAndValidateObjectResult(result, outputStrategy, context2);\n\t} catch (error) {\n\t\tif (repairText != null && NoObjectGeneratedError.isInstance(error) && (JSONParseError.isInstance(error.cause) || TypeValidationError.isInstance(error.cause))) {\n\t\t\tconst repairedText = await repairText({\n\t\t\t\ttext: result,\n\t\t\t\terror: error.cause\n\t\t\t});\n\t\t\tif (repairedText === null) throw error;\n\t\t\treturn await parseAndValidateObjectResult(repairedText, outputStrategy, context2);\n\t\t}\n\t\tthrow error;\n\t}\n}\nfunction validateObjectGenerationInput({ output, schema, schemaName, schemaDescription, enumValues }) {\n\tif (output != null && output !== \"object\" && output !== \"array\" && output !== \"enum\" && output !== \"no-schema\") throw new InvalidArgumentError({\n\t\tparameter: \"output\",\n\t\tvalue: output,\n\t\tmessage: \"Invalid output type.\"\n\t});\n\tif (output === \"no-schema\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for no-schema output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for no-schema output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for no-schema output.\"\n\t\t});\n\t}\n\tif (output === \"object\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is required for object output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for object output.\"\n\t\t});\n\t}\n\tif (output === \"array\") {\n\t\tif (schema == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Element schema is required for array output.\"\n\t\t});\n\t\tif (enumValues != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are not supported for array output.\"\n\t\t});\n\t}\n\tif (output === \"enum\") {\n\t\tif (schema != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schema\",\n\t\t\tvalue: schema,\n\t\t\tmessage: \"Schema is not supported for enum output.\"\n\t\t});\n\t\tif (schemaDescription != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaDescription\",\n\t\t\tvalue: schemaDescription,\n\t\t\tmessage: \"Schema description is not supported for enum output.\"\n\t\t});\n\t\tif (schemaName != null) throw new InvalidArgumentError({\n\t\t\tparameter: \"schemaName\",\n\t\t\tvalue: schemaName,\n\t\t\tmessage: \"Schema name is not supported for enum output.\"\n\t\t});\n\t\tif (enumValues == null) throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue: enumValues,\n\t\t\tmessage: \"Enum values are required for enum output.\"\n\t\t});\n\t\tfor (const value of enumValues) if (typeof value !== \"string\") throw new InvalidArgumentError({\n\t\t\tparameter: \"enumValues\",\n\t\t\tvalue,\n\t\t\tmessage: \"Enum values must be strings.\"\n\t\t});\n\t}\n}\nvar originalGenerateId3 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nasync function generateObject(options) {\n\tconst { model: modelArg, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries: maxRetriesArg, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, _internal: { generateId: generateId2 = originalGenerateId3, currentDate = () => /* @__PURE__ */ new Date() } = {}, ...settings } = options;\n\tconst model = resolveLanguageModel(modelArg);\n\tconst enumValues = \"enum\" in options ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst outputStrategy = getOutputStrategy({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tenumValues\n\t});\n\tconst callSettings = prepareCallSettings(settings);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders: headersWithUserAgent,\n\t\tsettings: {\n\t\t\t...callSettings,\n\t\t\tmaxRetries\n\t\t}\n\t});\n\tconst tracer = getTracer(telemetry);\n\tconst jsonSchema2 = await outputStrategy.jsonSchema();\n\ttry {\n\t\treturn await recordSpan({\n\t\t\tname: \"ai.generateObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.generateObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": jsonSchema2 != null ? { input: () => JSON.stringify(jsonSchema2) } : void 0,\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tfn: async (span) => {\n\t\t\t\tvar _a23;\n\t\t\t\tlet result;\n\t\t\t\tlet finishReason;\n\t\t\t\tlet usage;\n\t\t\t\tlet warnings;\n\t\t\t\tlet response;\n\t\t\t\tlet request;\n\t\t\t\tlet resultProviderMetadata;\n\t\t\t\tlet reasoning;\n\t\t\t\tconst promptMessages = await convertToLanguageModelPrompt({\n\t\t\t\t\tprompt: await standardizePrompt({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages,\n\t\t\t\t\t\tallowSystemInMessages\n\t\t\t\t\t}),\n\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\tdownload: download2,\n\t\t\t\t\tabortSignal\n\t\t\t\t});\n\t\t\t\tconst generateResult = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.generateObject.doGenerate\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.generateObject.doGenerate\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(promptMessages) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tfn: async (span2) => {\n\t\t\t\t\t\tvar _a24, _b, _c, _d, _e, _f, _g, _h;\n\t\t\t\t\t\tconst result2 = await model.doGenerate({\n\t\t\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\t\t\tschema: jsonSchema2,\n\t\t\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\t\t\tprompt: promptMessages,\n\t\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\theaders: headersWithUserAgent\n\t\t\t\t\t\t});\n\t\t\t\t\t\tconst responseData = {\n\t\t\t\t\t\t\tid: (_b = (_a24 = result2.response) == null ? void 0 : _a24.id) != null ? _b : generateId2(),\n\t\t\t\t\t\t\ttimestamp: (_d = (_c = result2.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),\n\t\t\t\t\t\t\tmodelId: (_f = (_e = result2.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,\n\t\t\t\t\t\t\theaders: (_g = result2.response) == null ? void 0 : _g.headers,\n\t\t\t\t\t\t\tbody: (_h = result2.response) == null ? void 0 : _h.body\n\t\t\t\t\t\t};\n\t\t\t\t\t\tconst text2 = extractTextContent(result2.content);\n\t\t\t\t\t\tconst reasoning2 = extractReasoningContent(result2.content);\n\t\t\t\t\t\tif (text2 === void 0) throw new NoObjectGeneratedError({\n\t\t\t\t\t\t\tmessage: \"No object generated: the model did not return a response.\",\n\t\t\t\t\t\t\tresponse: responseData,\n\t\t\t\t\t\t\tusage: asLanguageModelUsage(result2.usage),\n\t\t\t\t\t\t\tfinishReason: result2.finishReason.unified\n\t\t\t\t\t\t});\n\t\t\t\t\t\tspan2.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\"ai.response.finishReason\": result2.finishReason.unified,\n\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => text2 },\n\t\t\t\t\t\t\t\t\"ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"ai.response.timestamp\": responseData.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(result2.providerMetadata),\n\t\t\t\t\t\t\t\t\"ai.usage.promptTokens\": result2.usage.inputTokens.total,\n\t\t\t\t\t\t\t\t\"ai.usage.completionTokens\": result2.usage.outputTokens.total,\n\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [result2.finishReason.unified],\n\t\t\t\t\t\t\t\t\"gen_ai.response.id\": responseData.id,\n\t\t\t\t\t\t\t\t\"gen_ai.response.model\": responseData.modelId,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": result2.usage.inputTokens.total,\n\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": result2.usage.outputTokens.total\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}));\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\t...result2,\n\t\t\t\t\t\t\tobjectText: text2,\n\t\t\t\t\t\t\treasoning: reasoning2,\n\t\t\t\t\t\t\tresponseData\n\t\t\t\t\t\t};\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tresult = generateResult.objectText;\n\t\t\t\tfinishReason = generateResult.finishReason.unified;\n\t\t\t\tusage = asLanguageModelUsage(generateResult.usage);\n\t\t\t\twarnings = generateResult.warnings;\n\t\t\t\tresultProviderMetadata = generateResult.providerMetadata;\n\t\t\t\trequest = (_a23 = generateResult.request) != null ? _a23 : {};\n\t\t\t\tresponse = generateResult.responseData;\n\t\t\t\treasoning = generateResult.reasoning;\n\t\t\t\tlogWarnings({\n\t\t\t\t\twarnings,\n\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\tmodel: model.modelId\n\t\t\t\t});\n\t\t\t\tconst object2 = await parseAndValidateObjectResultWithRepair(result, outputStrategy, repairText, {\n\t\t\t\t\tresponse,\n\t\t\t\t\tusage,\n\t\t\t\t\tfinishReason\n\t\t\t\t});\n\t\t\t\tspan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(resultProviderMetadata),\n\t\t\t\t\t\t\"ai.usage.promptTokens\": usage.inputTokens,\n\t\t\t\t\t\t\"ai.usage.completionTokens\": usage.outputTokens\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\treturn new DefaultGenerateObjectResult({\n\t\t\t\t\tobject: object2,\n\t\t\t\t\treasoning,\n\t\t\t\t\tfinishReason,\n\t\t\t\t\tusage,\n\t\t\t\t\twarnings,\n\t\t\t\t\trequest,\n\t\t\t\t\tresponse,\n\t\t\t\t\tproviderMetadata: resultProviderMetadata\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\t} catch (error) {\n\t\tthrow wrapGatewayError(error);\n\t}\n}\nvar DefaultGenerateObjectResult = class {\n\tconstructor(options) {\n\t\tthis.object = options.object;\n\t\tthis.finishReason = options.finishReason;\n\t\tthis.usage = options.usage;\n\t\tthis.warnings = options.warnings;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t\tthis.response = options.response;\n\t\tthis.request = options.request;\n\t\tthis.reasoning = options.reasoning;\n\t}\n\ttoJsonResponse(init) {\n\t\tvar _a23;\n\t\treturn new Response(JSON.stringify(this.object), {\n\t\t\tstatus: (_a23 = init == null ? void 0 : init.status) != null ? _a23 : 200,\n\t\t\theaders: prepareHeaders(init == null ? void 0 : init.headers, { \"content-type\": \"application/json; charset=utf-8\" })\n\t\t});\n\t}\n};\nfunction cosineSimilarity(vector1, vector2) {\n\tif (vector1.length !== vector2.length) throw new InvalidArgumentError({\n\t\tparameter: \"vector1,vector2\",\n\t\tvalue: {\n\t\t\tvector1Length: vector1.length,\n\t\t\tvector2Length: vector2.length\n\t\t},\n\t\tmessage: `Vectors must have the same length`\n\t});\n\tconst n = vector1.length;\n\tif (n === 0) return 0;\n\tlet magnitudeSquared1 = 0;\n\tlet magnitudeSquared2 = 0;\n\tlet dotProduct = 0;\n\tfor (let i = 0; i < n; i++) {\n\t\tconst value1 = vector1[i];\n\t\tconst value2 = vector2[i];\n\t\tmagnitudeSquared1 += value1 * value1;\n\t\tmagnitudeSquared2 += value2 * value2;\n\t\tdotProduct += value1 * value2;\n\t}\n\treturn magnitudeSquared1 === 0 || magnitudeSquared2 === 0 ? 0 : dotProduct / (Math.sqrt(magnitudeSquared1) * Math.sqrt(magnitudeSquared2));\n}\nfunction createDownload(options) {\n\treturn ({ url, abortSignal }) => download({\n\t\turl,\n\t\tmaxBytes: options == null ? void 0 : options.maxBytes,\n\t\tabortSignal\n\t});\n}\nvar { atob } = globalThis;\nfunction getTextFromDataUrl(dataUrl) {\n\tconst [header, base64Content] = dataUrl.split(\",\");\n\tif (header.split(\";\")[0].split(\":\")[1] == null || base64Content == null) throw new Error(\"Invalid data URL format\");\n\ttry {\n\t\treturn atob(base64Content);\n\t} catch (error) {\n\t\tthrow new Error(`Error decoding data URL`);\n\t}\n}\nvar SerialJobExecutor = class {\n\tconstructor() {\n\t\tthis.queue = [];\n\t\tthis.isProcessing = false;\n\t\tthis.idleWaiters = [];\n\t}\n\tasync processQueue() {\n\t\tif (this.isProcessing) return;\n\t\tthis.isProcessing = true;\n\t\ttry {\n\t\t\twhile (this.queue.length > 0) {\n\t\t\t\tawait this.queue[0]();\n\t\t\t\tthis.queue.shift();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.isProcessing = false;\n\t\t\tfor (const resolve3 of this.idleWaiters.splice(0)) resolve3();\n\t\t}\n\t}\n\tasync run(job) {\n\t\treturn new Promise((resolve3, reject) => {\n\t\t\tthis.queue.push(async () => {\n\t\t\t\ttry {\n\t\t\t\t\tawait job();\n\t\t\t\t\tresolve3();\n\t\t\t\t} catch (error) {\n\t\t\t\t\treject(error);\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.processQueue();\n\t\t});\n\t}\n\tasync waitForIdle() {\n\t\tif (!this.isProcessing && this.queue.length === 0) return;\n\t\tawait new Promise((resolve3) => {\n\t\t\tthis.idleWaiters.push(resolve3);\n\t\t});\n\t}\n};\nfunction simulateReadableStream({ chunks, initialDelayInMs = 0, chunkDelayInMs = 0, _internal }) {\n\tvar _a23;\n\tconst delay$1 = (_a23 = _internal == null ? void 0 : _internal.delay) != null ? _a23 : delay;\n\tlet index = 0;\n\treturn new ReadableStream({ async pull(controller) {\n\t\tif (index < chunks.length) {\n\t\t\tawait delay$1(index === 0 ? initialDelayInMs : chunkDelayInMs);\n\t\t\tcontroller.enqueue(chunks[index++]);\n\t\t} else controller.close();\n\t} });\n}\nvar originalGenerateId4 = createIdGenerator({\n\tprefix: \"aiobj\",\n\tsize: 24\n});\nasync function markPromiseAsHandled(promise) {\n\ttry {\n\t\tawait promise;\n\t} catch (e) {}\n}\nfunction streamObject(options) {\n\tconst { model, output = \"object\", system, prompt, messages, allowSystemInMessages, maxRetries, abortSignal, headers, experimental_repairText: repairText, experimental_telemetry: telemetry, experimental_download: download2, providerOptions, onError = ({ error }) => {\n\t\tconsole.error(error);\n\t}, onFinish, _internal: { generateId: generateId2 = originalGenerateId4, currentDate = () => /* @__PURE__ */ new Date(), now: now2 = now } = {}, ...settings } = options;\n\tconst enumValues = \"enum\" in options && options.enum ? options.enum : void 0;\n\tconst { schema: inputSchema, schemaDescription, schemaName } = \"schema\" in options ? options : {};\n\tvalidateObjectGenerationInput({\n\t\toutput,\n\t\tschema: inputSchema,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tenumValues\n\t});\n\treturn new DefaultStreamObjectResult({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings,\n\t\tmaxRetries,\n\t\tabortSignal,\n\t\toutputStrategy: getOutputStrategy({\n\t\t\toutput,\n\t\t\tschema: inputSchema,\n\t\t\tenumValues\n\t\t}),\n\t\tsystem,\n\t\tprompt,\n\t\tmessages,\n\t\tallowSystemInMessages,\n\t\tschemaName,\n\t\tschemaDescription,\n\t\tproviderOptions,\n\t\trepairText,\n\t\tonError,\n\t\tonFinish,\n\t\tdownload: download2,\n\t\tgenerateId: generateId2,\n\t\tcurrentDate,\n\t\tnow: now2\n\t});\n}\nvar DefaultStreamObjectResult = class {\n\tconstructor({ model: modelArg, headers, telemetry, settings, maxRetries: maxRetriesArg, abortSignal, outputStrategy, system, prompt, messages, allowSystemInMessages, schemaName, schemaDescription, providerOptions, repairText, onError, onFinish, download: download2, generateId: generateId2, currentDate, now: now2 }) {\n\t\tthis._object = new DelayedPromise();\n\t\tthis._usage = new DelayedPromise();\n\t\tthis._providerMetadata = new DelayedPromise();\n\t\tthis._warnings = new DelayedPromise();\n\t\tthis._request = new DelayedPromise();\n\t\tthis._response = new DelayedPromise();\n\t\tthis._finishReason = new DelayedPromise();\n\t\tconst model = resolveLanguageModel(modelArg);\n\t\tconst { maxRetries, retry } = prepareRetries({\n\t\t\tmaxRetries: maxRetriesArg,\n\t\t\tabortSignal\n\t\t});\n\t\tconst callSettings = prepareCallSettings(settings);\n\t\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\t\tmodel,\n\t\t\ttelemetry,\n\t\t\theaders,\n\t\t\tsettings: {\n\t\t\t\t...callSettings,\n\t\t\t\tmaxRetries\n\t\t\t}\n\t\t});\n\t\tconst tracer = getTracer(telemetry);\n\t\tconst self = this;\n\t\tconst stitchableStream = createStitchableStream();\n\t\tconst eventProcessor = new TransformStream({ transform(chunk, controller) {\n\t\t\tcontroller.enqueue(chunk);\n\t\t\tif (chunk.type === \"error\") notify({\n\t\t\t\tevent: { error: wrapGatewayError(chunk.error) },\n\t\t\t\tcallbacks: onError\n\t\t\t});\n\t\t} });\n\t\tthis.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);\n\t\trecordSpan({\n\t\t\tname: \"ai.streamObject\",\n\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\ttelemetry,\n\t\t\t\tattributes: {\n\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\toperationId: \"ai.streamObject\",\n\t\t\t\t\t\ttelemetry\n\t\t\t\t\t}),\n\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\"ai.prompt\": { input: () => JSON.stringify({\n\t\t\t\t\t\tsystem,\n\t\t\t\t\t\tprompt,\n\t\t\t\t\t\tmessages\n\t\t\t\t\t}) },\n\t\t\t\t\t\"ai.schema\": { input: async () => JSON.stringify(await outputStrategy.jsonSchema()) },\n\t\t\t\t\t\"ai.schema.name\": schemaName,\n\t\t\t\t\t\"ai.schema.description\": schemaDescription,\n\t\t\t\t\t\"ai.settings.output\": outputStrategy.type\n\t\t\t\t}\n\t\t\t}),\n\t\t\ttracer,\n\t\t\tendWhenDone: false,\n\t\t\tendOnError: true,\n\t\t\tfn: async (rootSpan) => {\n\t\t\t\tconst standardizedPrompt = await standardizePrompt({\n\t\t\t\t\tsystem,\n\t\t\t\t\tprompt,\n\t\t\t\t\tmessages,\n\t\t\t\t\tallowSystemInMessages\n\t\t\t\t});\n\t\t\t\tconst callOptions = {\n\t\t\t\t\tresponseFormat: {\n\t\t\t\t\t\ttype: \"json\",\n\t\t\t\t\t\tschema: await outputStrategy.jsonSchema(),\n\t\t\t\t\t\tname: schemaName,\n\t\t\t\t\t\tdescription: schemaDescription\n\t\t\t\t\t},\n\t\t\t\t\t...prepareCallSettings(settings),\n\t\t\t\t\tprompt: await convertToLanguageModelPrompt({\n\t\t\t\t\t\tprompt: standardizedPrompt,\n\t\t\t\t\t\tsupportedUrls: await model.supportedUrls,\n\t\t\t\t\t\tdownload: download2,\n\t\t\t\t\t\tabortSignal\n\t\t\t\t\t}),\n\t\t\t\t\tproviderOptions,\n\t\t\t\t\tabortSignal,\n\t\t\t\t\theaders,\n\t\t\t\t\tincludeRawChunks: false\n\t\t\t\t};\n\t\t\t\tconst transformer = { transform: (chunk, controller) => {\n\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\tcase \"text-delta\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk.delta);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\tcase \"stream-start\": controller.enqueue(chunk);\n\t\t\t\t\t}\n\t\t\t\t} };\n\t\t\t\tconst { result: { stream, response, request }, doStreamSpan, startTimestampMs } = await retry(() => recordSpan({\n\t\t\t\t\tname: \"ai.streamObject.doStream\",\n\t\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\t\toperationId: \"ai.streamObject.doStream\",\n\t\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\t\"ai.prompt.messages\": { input: () => stringifyForTelemetry(callOptions.prompt) },\n\t\t\t\t\t\t\t\"gen_ai.system\": model.provider,\n\t\t\t\t\t\t\t\"gen_ai.request.model\": model.modelId,\n\t\t\t\t\t\t\t\"gen_ai.request.frequency_penalty\": callSettings.frequencyPenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.max_tokens\": callSettings.maxOutputTokens,\n\t\t\t\t\t\t\t\"gen_ai.request.presence_penalty\": callSettings.presencePenalty,\n\t\t\t\t\t\t\t\"gen_ai.request.temperature\": callSettings.temperature,\n\t\t\t\t\t\t\t\"gen_ai.request.top_k\": callSettings.topK,\n\t\t\t\t\t\t\t\"gen_ai.request.top_p\": callSettings.topP\n\t\t\t\t\t\t}\n\t\t\t\t\t}),\n\t\t\t\t\ttracer,\n\t\t\t\t\tendWhenDone: false,\n\t\t\t\t\tendOnError: true,\n\t\t\t\t\tfn: async (doStreamSpan2) => ({\n\t\t\t\t\t\tstartTimestampMs: now2(),\n\t\t\t\t\t\tdoStreamSpan: doStreamSpan2,\n\t\t\t\t\t\tresult: await model.doStream(callOptions)\n\t\t\t\t\t})\n\t\t\t\t}));\n\t\t\t\tself._request.resolve(request != null ? request : {});\n\t\t\t\tlet warnings;\n\t\t\t\tlet usage = createNullLanguageModelUsage();\n\t\t\t\tlet finishReason;\n\t\t\t\tlet providerMetadata;\n\t\t\t\tlet object2;\n\t\t\t\tlet error;\n\t\t\t\tlet terminalError;\n\t\t\t\tlet accumulatedText = \"\";\n\t\t\t\tlet textDelta = \"\";\n\t\t\t\tlet fullResponse = {\n\t\t\t\t\tid: generateId2(),\n\t\t\t\t\ttimestamp: currentDate(),\n\t\t\t\t\tmodelId: model.modelId\n\t\t\t\t};\n\t\t\t\tlet latestObjectJson = void 0;\n\t\t\t\tlet latestObject = void 0;\n\t\t\t\tlet isFirstChunk = true;\n\t\t\t\tlet isFirstDelta = true;\n\t\t\t\tconst transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(new TransformStream({\n\t\t\t\t\tasync transform(chunk, controller) {\n\t\t\t\t\t\tvar _a23, _b, _c;\n\t\t\t\t\t\tif (typeof chunk === \"object\" && chunk.type === \"stream-start\") {\n\t\t\t\t\t\t\twarnings = chunk.warnings;\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (isFirstChunk) {\n\t\t\t\t\t\t\tconst msToFirstChunk = now2() - startTimestampMs;\n\t\t\t\t\t\t\tisFirstChunk = false;\n\t\t\t\t\t\t\tdoStreamSpan.addEvent(\"ai.stream.firstChunk\", { \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes({ \"ai.stream.msToFirstChunk\": msToFirstChunk });\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (typeof chunk === \"string\") {\n\t\t\t\t\t\t\taccumulatedText += chunk;\n\t\t\t\t\t\t\ttextDelta += chunk;\n\t\t\t\t\t\t\tconst { value: currentObjectJson, state: parseState } = await parsePartialJson(accumulatedText);\n\t\t\t\t\t\t\tif (currentObjectJson !== void 0 && !isDeepEqualData(latestObjectJson, currentObjectJson)) {\n\t\t\t\t\t\t\t\tconst validationResult = await outputStrategy.validatePartialResult({\n\t\t\t\t\t\t\t\t\tvalue: currentObjectJson,\n\t\t\t\t\t\t\t\t\ttextDelta,\n\t\t\t\t\t\t\t\t\tlatestObject,\n\t\t\t\t\t\t\t\t\tisFirstDelta,\n\t\t\t\t\t\t\t\t\tisFinalDelta: parseState === \"successful-parse\"\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (validationResult.success && !isDeepEqualData(latestObject, validationResult.value.partial)) {\n\t\t\t\t\t\t\t\t\tlatestObjectJson = currentObjectJson;\n\t\t\t\t\t\t\t\t\tlatestObject = validationResult.value.partial;\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"object\",\n\t\t\t\t\t\t\t\t\t\tobject: latestObject\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\t\ttextDelta: validationResult.value.textDelta\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\ttextDelta = \"\";\n\t\t\t\t\t\t\t\t\tisFirstDelta = false;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tswitch (chunk.type) {\n\t\t\t\t\t\t\tcase \"response-metadata\":\n\t\t\t\t\t\t\t\tfullResponse = {\n\t\t\t\t\t\t\t\t\tid: (_a23 = chunk.id) != null ? _a23 : fullResponse.id,\n\t\t\t\t\t\t\t\t\ttimestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,\n\t\t\t\t\t\t\t\t\tmodelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId\n\t\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"error\":\n\t\t\t\t\t\t\t\tif (terminalError === void 0) {\n\t\t\t\t\t\t\t\t\tconst wrappedError = wrapGatewayError(chunk.error);\n\t\t\t\t\t\t\t\t\tterminalError = { error: wrappedError };\n\t\t\t\t\t\t\t\t\terror = wrappedError;\n\t\t\t\t\t\t\t\t\tfinishReason = \"error\";\n\t\t\t\t\t\t\t\t\tself.rejectResultPromises(wrappedError);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"finish\":\n\t\t\t\t\t\t\t\tif (textDelta !== \"\") controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\ttextDelta\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tfinishReason = terminalError === void 0 ? chunk.finishReason.unified : \"error\";\n\t\t\t\t\t\t\t\tusage = asLanguageModelUsage(chunk.usage);\n\t\t\t\t\t\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\t...chunk,\n\t\t\t\t\t\t\t\t\tfinishReason,\n\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\tresponse: fullResponse\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tlogWarnings({\n\t\t\t\t\t\t\t\t\twarnings: warnings != null ? warnings : [],\n\t\t\t\t\t\t\t\t\tprovider: model.provider,\n\t\t\t\t\t\t\t\t\tmodel: model.modelId\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tif (terminalError !== void 0) break;\n\t\t\t\t\t\t\t\tself._usage.resolve(usage);\n\t\t\t\t\t\t\t\tself._providerMetadata.resolve(providerMetadata);\n\t\t\t\t\t\t\t\tself._warnings.resolve(warnings);\n\t\t\t\t\t\t\t\tself._response.resolve({\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tself._finishReason.resolve(finishReason != null ? finishReason : \"other\");\n\t\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t\tobject2 = await parseAndValidateObjectResultWithRepair(accumulatedText, outputStrategy, repairText, {\n\t\t\t\t\t\t\t\t\t\tresponse: fullResponse,\n\t\t\t\t\t\t\t\t\t\tusage,\n\t\t\t\t\t\t\t\t\t\tfinishReason\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\t\tself._object.resolve(object2);\n\t\t\t\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\t\t\t\terror = e;\n\t\t\t\t\t\t\t\t\tself._object.reject(e);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tdefault: controller.enqueue(chunk);\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\tasync flush(controller) {\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tconst finalUsage = usage != null ? usage : {\n\t\t\t\t\t\t\t\tpromptTokens: NaN,\n\t\t\t\t\t\t\t\tcompletionTokens: NaN,\n\t\t\t\t\t\t\t\ttotalTokens: NaN\n\t\t\t\t\t\t\t};\n\t\t\t\t\t\t\tdoStreamSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.response.finishReason\": finishReason,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"ai.response.timestamp\": fullResponse.timestamp.toISOString(),\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata),\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.finish_reasons\": [finishReason],\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.id\": fullResponse.id,\n\t\t\t\t\t\t\t\t\t\"gen_ai.response.model\": fullResponse.modelId,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.input_tokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"gen_ai.usage.output_tokens\": finalUsage.outputTokens\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tdoStreamSpan.end();\n\t\t\t\t\t\t\trootSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\t\t\"ai.usage.inputTokens\": finalUsage.inputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.outputTokens\": finalUsage.outputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.totalTokens\": finalUsage.totalTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.reasoningTokens\": finalUsage.reasoningTokens,\n\t\t\t\t\t\t\t\t\t\"ai.usage.cachedInputTokens\": finalUsage.cachedInputTokens,\n\t\t\t\t\t\t\t\t\t\"ai.response.object\": { output: () => JSON.stringify(object2) },\n\t\t\t\t\t\t\t\t\t\"ai.response.providerMetadata\": JSON.stringify(providerMetadata)\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t\tawait (onFinish == null ? void 0 : onFinish({\n\t\t\t\t\t\t\t\tusage: finalUsage,\n\t\t\t\t\t\t\t\tobject: object2,\n\t\t\t\t\t\t\t\terror,\n\t\t\t\t\t\t\t\tresponse: {\n\t\t\t\t\t\t\t\t\t...fullResponse,\n\t\t\t\t\t\t\t\t\theaders: response == null ? void 0 : response.headers\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\twarnings,\n\t\t\t\t\t\t\t\tproviderMetadata\n\t\t\t\t\t\t\t}));\n\t\t\t\t\t\t} catch (error2) {\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\terror: error2\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t} finally {\n\t\t\t\t\t\t\trootSpan.end();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}));\n\t\t\t\tstitchableStream.addStream(transformedStream, { onError(error2) {\n\t\t\t\t\tconst wrappedError = wrapGatewayError(error2);\n\t\t\t\t\tself.rejectResultPromises(wrappedError);\n\t\t\t\t\tnotify({\n\t\t\t\t\t\tevent: { error: wrappedError },\n\t\t\t\t\t\tcallbacks: onError\n\t\t\t\t\t});\n\t\t\t\t} });\n\t\t\t}\n\t\t}).catch((error) => {\n\t\t\tself.rejectResultPromises(error);\n\t\t\tstitchableStream.addStream(new ReadableStream({ start(controller) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype: \"error\",\n\t\t\t\t\terror\n\t\t\t\t});\n\t\t\t\tcontroller.close();\n\t\t\t} }));\n\t\t}).finally(() => {\n\t\t\tstitchableStream.close();\n\t\t});\n\t\tthis.outputStrategy = outputStrategy;\n\t}\n\trejectResultPromises(error) {\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._object,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._usage,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._providerMetadata,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._warnings,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._request,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._response,\n\t\t\terror\n\t\t});\n\t\tthis.rejectResultPromise({\n\t\t\tdelayedPromise: this._finishReason,\n\t\t\terror\n\t\t});\n\t}\n\trejectResultPromise({ delayedPromise, error }) {\n\t\tif (delayedPromise.isPending()) {\n\t\t\tdelayedPromise.reject(error);\n\t\t\tmarkPromiseAsHandled(delayedPromise.promise);\n\t\t}\n\t}\n\tget object() {\n\t\treturn this._object.promise;\n\t}\n\tget usage() {\n\t\treturn this._usage.promise;\n\t}\n\tget providerMetadata() {\n\t\treturn this._providerMetadata.promise;\n\t}\n\tget warnings() {\n\t\treturn this._warnings.promise;\n\t}\n\tget request() {\n\t\treturn this._request.promise;\n\t}\n\tget response() {\n\t\treturn this._response.promise;\n\t}\n\tget finishReason() {\n\t\treturn this._finishReason.promise;\n\t}\n\tget partialObjectStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"object\":\n\t\t\t\t\tcontroller.enqueue(chunk.object);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"text-delta\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\treturn this.outputStrategy.createElementStream(this.baseStream);\n\t}\n\tget textStream() {\n\t\treturn createAsyncIterableStream(this.baseStream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\t\tswitch (chunk.type) {\n\t\t\t\tcase \"text-delta\":\n\t\t\t\t\tcontroller.enqueue(chunk.textDelta);\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"object\":\n\t\t\t\tcase \"finish\":\n\t\t\t\tcase \"error\": break;\n\t\t\t\tdefault: throw new Error(`Unsupported chunk type: ${chunk}`);\n\t\t\t}\n\t\t} })));\n\t}\n\tget fullStream() {\n\t\treturn createAsyncIterableStream(this.baseStream);\n\t}\n\tpipeTextStreamToResponse(response, init) {\n\t\treturn pipeTextStreamToResponse({\n\t\t\tresponse,\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n\ttoTextStreamResponse(init) {\n\t\treturn createTextStreamResponse({\n\t\t\ttextStream: this.textStream,\n\t\t\t...init\n\t\t});\n\t}\n};\nvar DefaultGeneratedAudioFile = class extends DefaultGeneratedFile {\n\tconstructor({ data, mediaType }) {\n\t\tsuper({\n\t\t\tdata,\n\t\t\tmediaType\n\t\t});\n\t\tlet format = \"mp3\";\n\t\tif (mediaType) {\n\t\t\tconst mediaTypeParts = mediaType.split(\"/\");\n\t\t\tif (mediaTypeParts.length === 2) {\n\t\t\t\tif (mediaType !== \"audio/mpeg\") format = mediaTypeParts[1];\n\t\t\t}\n\t\t}\n\t\tif (!format) throw new Error(\"Audio format must be provided or determinable from media type\");\n\t\tthis.format = format;\n\t}\n};\nasync function generateSpeech({ model, text: text2, voice, outputFormat, instructions, speed, language, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a23;\n\tconst resolvedModel = resolveSpeechModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst result = await retry(() => resolvedModel.doGenerate({\n\t\ttext: text2,\n\t\tvoice,\n\t\toutputFormat,\n\t\tinstructions,\n\t\tspeed,\n\t\tlanguage,\n\t\tabortSignal,\n\t\theaders: headersWithUserAgent,\n\t\tproviderOptions\n\t}));\n\tif (!result.audio || result.audio.length === 0) throw new NoSpeechGeneratedError({ responses: [result.response] });\n\tlogWarnings({\n\t\twarnings: result.warnings,\n\t\tprovider: resolvedModel.provider,\n\t\tmodel: resolvedModel.modelId\n\t});\n\treturn new DefaultSpeechResult({\n\t\taudio: new DefaultGeneratedAudioFile({\n\t\t\tdata: result.audio,\n\t\t\tmediaType: (_a23 = detectMediaType({\n\t\t\t\tdata: result.audio,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a23 : \"audio/mp3\"\n\t\t}),\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultSpeechResult = class {\n\tconstructor(options) {\n\t\tvar _a23;\n\t\tthis.audio = options.audio;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};\n\t}\n};\nfunction pruneMessages({ messages, reasoning = \"none\", toolCalls = [], emptyMessages = \"remove\" }) {\n\tif (reasoning === \"all\" || reasoning === \"before-last-message\") messages = messages.map((message, messageIndex) => {\n\t\tif (message.role !== \"assistant\" || typeof message.content === \"string\" || reasoning === \"before-last-message\" && messageIndex === messages.length - 1) return message;\n\t\treturn {\n\t\t\t...message,\n\t\t\tcontent: message.content.filter((part) => part.type !== \"reasoning\")\n\t\t};\n\t});\n\tif (toolCalls === \"none\") toolCalls = [];\n\telse if (toolCalls === \"all\") toolCalls = [{ type: \"all\" }];\n\telse if (toolCalls === \"before-last-message\") toolCalls = [{ type: \"before-last-message\" }];\n\telse if (typeof toolCalls === \"string\") toolCalls = [{ type: toolCalls }];\n\tfor (const toolCall of toolCalls) {\n\t\tconst keepLastMessagesCount = toolCall.type === \"all\" ? void 0 : toolCall.type === \"before-last-message\" ? 1 : Number(toolCall.type.slice(12).slice(0, -9));\n\t\tconst keptToolCallIds = /* @__PURE__ */ new Set();\n\t\tconst keptApprovalIds = /* @__PURE__ */ new Set();\n\t\tif (keepLastMessagesCount != null) {\n\t\t\tfor (const message of messages.slice(-keepLastMessagesCount)) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") keptToolCallIds.add(part.toolCallId);\n\t\t\t\telse if (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") keptApprovalIds.add(part.approvalId);\n\t\t\t}\n\t\t}\n\t\tconst toolCallIdToToolName = /* @__PURE__ */ new Map();\n\t\tfor (const message of messages) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\tfor (const part of message.content) if (part.type === \"tool-call\" || part.type === \"tool-result\") toolCallIdToToolName.set(part.toolCallId, part.toolName);\n\t\t}\n\t\tconst approvalIdToToolCallId = /* @__PURE__ */ new Map();\n\t\tconst approvalIdToToolName = /* @__PURE__ */ new Map();\n\t\tfor (const message of messages) if ((message.role === \"assistant\" || message.role === \"tool\") && typeof message.content !== \"string\") {\n\t\t\tfor (const part of message.content) if (part.type === \"tool-approval-request\") {\n\t\t\t\tapprovalIdToToolCallId.set(part.approvalId, part.toolCallId);\n\t\t\t\tconst toolName = toolCallIdToToolName.get(part.toolCallId);\n\t\t\t\tif (toolName != null) approvalIdToToolName.set(part.approvalId, toolName);\n\t\t\t}\n\t\t}\n\t\tfor (const approvalId of keptApprovalIds) {\n\t\t\tconst toolCallId = approvalIdToToolCallId.get(approvalId);\n\t\t\tif (toolCallId != null) keptToolCallIds.add(toolCallId);\n\t\t}\n\t\tmessages = messages.map((message, messageIndex) => {\n\t\t\tif (message.role !== \"assistant\" && message.role !== \"tool\" || typeof message.content === \"string\" || keepLastMessagesCount && messageIndex >= messages.length - keepLastMessagesCount) return message;\n\t\t\tconst keepParts = message.content.map((part) => {\n\t\t\t\tif (part.type !== \"tool-call\" && part.type !== \"tool-result\" && part.type !== \"tool-approval-request\" && part.type !== \"tool-approval-response\") return true;\n\t\t\t\tif ((part.type === \"tool-call\" || part.type === \"tool-result\") && keptToolCallIds.has(part.toolCallId) || (part.type === \"tool-approval-request\" || part.type === \"tool-approval-response\") && keptApprovalIds.has(part.approvalId)) return true;\n\t\t\t\tconst partToolName = part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName.get(part.approvalId);\n\t\t\t\treturn toolCall.tools != null && partToolName != null && !toolCall.tools.includes(partToolName);\n\t\t\t});\n\t\t\tif (message.role === \"assistant\") for (let reasoningIndex = 0; reasoningIndex < message.content.length; reasoningIndex++) {\n\t\t\t\tif (message.content[reasoningIndex].type !== \"reasoning\") continue;\n\t\t\t\tlet reasoningEndIndex = reasoningIndex + 1;\n\t\t\t\twhile (reasoningEndIndex < message.content.length) {\n\t\t\t\t\tif (message.content[reasoningEndIndex].type !== \"reasoning\") break;\n\t\t\t\t\treasoningEndIndex++;\n\t\t\t\t}\n\t\t\t\tlet followingPartIndex = reasoningEndIndex;\n\t\t\t\tlet hasFollowingPart = false;\n\t\t\t\tlet hasKeptFollowingPart = false;\n\t\t\t\twhile (followingPartIndex < message.content.length) {\n\t\t\t\t\tif (message.content[followingPartIndex].type === \"reasoning\") break;\n\t\t\t\t\thasFollowingPart = true;\n\t\t\t\t\thasKeptFollowingPart || (hasKeptFollowingPart = keepParts[followingPartIndex]);\n\t\t\t\t\tfollowingPartIndex++;\n\t\t\t\t}\n\t\t\t\tif (hasFollowingPart && !hasKeptFollowingPart) for (let index = reasoningIndex; index < reasoningEndIndex; index++) keepParts[index] = false;\n\t\t\t\treasoningIndex = followingPartIndex - 1;\n\t\t\t}\n\t\t\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((_, index) => keepParts[index])\n\t\t\t};\n\t\t});\n\t}\n\tif (emptyMessages === \"remove\") messages = messages.filter((message) => message.content.length > 0);\n\treturn messages;\n}\nvar CHUNKING_REGEXPS = {\n\tword: /\\S+\\s+/m,\n\tline: /\\n+/m\n};\nfunction isDocumentHidden() {\n\treturn typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n}\nfunction smoothStream({ delayInMs = 10, chunking = \"word\", _internal: { delay: delay$2 = delay } = {} } = {}) {\n\tlet detectChunk;\n\tif (chunking != null && typeof chunking === \"object\" && \"segment\" in chunking && typeof chunking.segment === \"function\") {\n\t\tconst segmenter = chunking;\n\t\tdetectChunk = (buffer) => {\n\t\t\tif (buffer.length === 0) return null;\n\t\t\tconst first = segmenter.segment(buffer)[Symbol.iterator]().next().value;\n\t\t\treturn (first == null ? void 0 : first.segment) || null;\n\t\t};\n\t} else if (typeof chunking === \"function\") detectChunk = (buffer) => {\n\t\tconst match = chunking(buffer);\n\t\tif (match == null) return null;\n\t\tif (!match.length) throw new Error(`Chunking function must return a non-empty string.`);\n\t\tif (!buffer.startsWith(match)) throw new Error(`Chunking function must return a match that is a prefix of the buffer. Received: \"${match}\" expected to start with \"${buffer}\"`);\n\t\treturn match;\n\t};\n\telse {\n\t\tconst chunkingRegex = typeof chunking === \"string\" ? CHUNKING_REGEXPS[chunking] : chunking instanceof RegExp ? chunking : void 0;\n\t\tif (chunkingRegex == null) throw new InvalidArgumentError$1({\n\t\t\targument: \"chunking\",\n\t\t\tmessage: `Chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a ChunkDetector function. Received: ${chunking}`\n\t\t});\n\t\tdetectChunk = (buffer) => {\n\t\t\tconst match = chunkingRegex.exec(buffer);\n\t\t\tif (!match) return null;\n\t\t\treturn buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);\n\t\t};\n\t}\n\treturn () => {\n\t\tlet buffer = \"\";\n\t\tlet id = \"\";\n\t\tlet type = void 0;\n\t\tlet providerMetadata = void 0;\n\t\tfunction flushBuffer(controller) {\n\t\t\tif (type !== void 0 && (buffer.length > 0 || providerMetadata != null)) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype,\n\t\t\t\t\ttext: buffer,\n\t\t\t\t\tid,\n\t\t\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tbuffer = \"\";\n\t\t\t\tproviderMetadata = void 0;\n\t\t\t}\n\t\t}\n\t\treturn new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (chunk.type !== \"text-delta\" && chunk.type !== \"reasoning-delta\") {\n\t\t\t\tflushBuffer(controller);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (chunk.text.length === 0 && chunk.providerMetadata != null) {\n\t\t\t\tflushBuffer(controller);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (buffer.length > 0 && (chunk.type !== type || chunk.id !== id || providerMetadata != null || chunk.providerMetadata != null)) flushBuffer(controller);\n\t\t\tbuffer += chunk.text;\n\t\t\tid = chunk.id;\n\t\t\ttype = chunk.type;\n\t\t\tproviderMetadata = chunk.providerMetadata;\n\t\t\tlet match;\n\t\t\twhile ((match = detectChunk(buffer)) != null) {\n\t\t\t\tcontroller.enqueue({\n\t\t\t\t\ttype,\n\t\t\t\t\ttext: match,\n\t\t\t\t\tid,\n\t\t\t\t\t...providerMetadata != null ? { providerMetadata } : {}\n\t\t\t\t});\n\t\t\t\tbuffer = buffer.slice(match.length);\n\t\t\t\tawait delay$2(isDocumentHidden() ? null : delayInMs);\n\t\t\t}\n\t\t\tif (buffer.length === 0) providerMetadata = void 0;\n\t\t} });\n\t};\n}\nvar defaultDownload = createDownload();\nasync function experimental_generateVideo({ model: modelArg, prompt: promptArg, n = 1, maxVideosPerCall, aspectRatio, resolution, duration, fps, seed, frameImages, inputReferences, generateAudio, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload }) {\n\tvar _a23, _b;\n\tconst model = resolveVideoModel(modelArg);\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst { prompt, image } = normalizePrompt2(promptArg);\n\tconst normalizedFrameImages = frameImages == null ? void 0 : frameImages.flatMap((frame) => {\n\t\tconst normalizedImage = normalizeImageData(frame.image);\n\t\treturn normalizedImage != null ? [{\n\t\t\timage: normalizedImage,\n\t\t\tframeType: frame.frameType\n\t\t}] : [];\n\t});\n\tconst normalizedInputReferences = inputReferences == null ? void 0 : inputReferences.flatMap((reference) => {\n\t\tconst normalized = normalizeReferenceData(reference);\n\t\treturn normalized != null ? [normalized] : [];\n\t});\n\tconst effectiveInputReferences = normalizedFrameImages != null && normalizedFrameImages.length > 0 ? void 0 : normalizedInputReferences;\n\tconst warnings = [];\n\tif (normalizedFrameImages != null && normalizedFrameImages.length > 0 && normalizedInputReferences != null && normalizedInputReferences.length > 0) warnings.push({\n\t\ttype: \"other\",\n\t\tmessage: \"inputReferences were ignored because frameImages were provided; frameImages and inputReferences cannot be combined.\"\n\t});\n\tconst firstFrameImage = (_a23 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find((frame) => frame.frameType === \"first_frame\")) == null ? void 0 : _a23.image;\n\tif (image != null && firstFrameImage != null) warnings.push({\n\t\ttype: \"other\",\n\t\tmessage: \"prompt.image was ignored because a first_frame frameImage was provided; the first_frame frameImage takes precedence as the start image.\"\n\t});\n\tconst resolvedImage = firstFrameImage != null ? firstFrameImage : image;\n\tconst maxVideosPerCallWithDefault = (_b = maxVideosPerCall != null ? maxVideosPerCall : await invokeModelMaxVideosPerCall(model)) != null ? _b : 1;\n\tconst callCount = Math.ceil(n / maxVideosPerCallWithDefault);\n\tconst callVideoCounts = Array.from({ length: callCount }, (_, index) => {\n\t\tconst remaining = n - index * maxVideosPerCallWithDefault;\n\t\treturn Math.min(remaining, maxVideosPerCallWithDefault);\n\t});\n\tconst results = await Promise.all(callVideoCounts.map(async (callVideoCount) => await retry(() => model.doGenerate({\n\t\tprompt,\n\t\tn: callVideoCount,\n\t\taspectRatio,\n\t\tresolution,\n\t\tduration,\n\t\tfps,\n\t\tseed,\n\t\timage: resolvedImage,\n\t\tframeImages: normalizedFrameImages,\n\t\tinputReferences: effectiveInputReferences,\n\t\tgenerateAudio,\n\t\tproviderOptions: providerOptions != null ? providerOptions : {},\n\t\theaders: headersWithUserAgent,\n\t\tabortSignal\n\t}))));\n\tconst videos = [];\n\tconst responses = [];\n\tconst providerMetadata = {};\n\tfor (const result of results) {\n\t\tfor (const videoData of result.videos) switch (videoData.type) {\n\t\t\tcase \"url\": {\n\t\t\t\tconst { data, mediaType: downloadedMediaType } = await downloadFn({\n\t\t\t\t\turl: new URL(videoData.url),\n\t\t\t\t\tabortSignal\n\t\t\t\t});\n\t\t\t\tconst isUsableMediaType = (type) => !!type && type !== \"application/octet-stream\";\n\t\t\t\tconst mediaType = isUsableMediaType(videoData.mediaType) && videoData.mediaType || isUsableMediaType(downloadedMediaType) && downloadedMediaType || detectMediaType({\n\t\t\t\t\tdata,\n\t\t\t\t\tsignatures: videoMediaTypeSignatures\n\t\t\t\t}) || \"video/mp4\";\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata,\n\t\t\t\t\tmediaType\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"base64\":\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\tmediaType: videoData.mediaType || \"video/mp4\"\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\tcase \"binary\": {\n\t\t\t\tconst mediaType = videoData.mediaType || detectMediaType({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\tsignatures: videoMediaTypeSignatures\n\t\t\t\t}) || \"video/mp4\";\n\t\t\t\tvideos.push(new DefaultGeneratedFile({\n\t\t\t\t\tdata: videoData.data,\n\t\t\t\t\tmediaType\n\t\t\t\t}));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\twarnings.push(...result.warnings);\n\t\tresponses.push({\n\t\t\ttimestamp: result.response.timestamp,\n\t\t\tmodelId: result.response.modelId,\n\t\t\theaders: result.response.headers,\n\t\t\tproviderMetadata: result.providerMetadata\n\t\t});\n\t\tif (result.providerMetadata != null) for (const [providerName, metadata] of Object.entries(result.providerMetadata)) {\n\t\t\tconst existingMetadata = getOwn(providerMetadata, providerName);\n\t\t\tif (existingMetadata != null && typeof existingMetadata === \"object\") {\n\t\t\t\tsetOwn(providerMetadata, providerName, {\n\t\t\t\t\t...existingMetadata,\n\t\t\t\t\t...metadata\n\t\t\t\t});\n\t\t\t\tif (\"videos\" in existingMetadata && Array.isArray(existingMetadata.videos) && \"videos\" in metadata && Array.isArray(metadata.videos)) providerMetadata[providerName].videos = [...existingMetadata.videos, ...metadata.videos];\n\t\t\t} else setOwn(providerMetadata, providerName, metadata);\n\t\t}\n\t}\n\tif (videos.length === 0) throw new NoVideoGeneratedError({ responses });\n\tif (warnings.length > 0) logWarnings({\n\t\twarnings,\n\t\tprovider: model.provider,\n\t\tmodel: model.modelId\n\t});\n\treturn {\n\t\tvideo: videos[0],\n\t\tvideos,\n\t\twarnings,\n\t\tresponses,\n\t\tproviderMetadata\n\t};\n}\nfunction normalizePrompt2(promptArg) {\n\tif (typeof promptArg === \"string\") return {\n\t\tprompt: promptArg,\n\t\timage: void 0\n\t};\n\treturn {\n\t\tprompt: promptArg.text,\n\t\timage: promptArg.image != null ? normalizeImageData(promptArg.image) : void 0\n\t};\n}\nfunction detectFileMediaType(data, restrictToImages) {\n\tvar _a23;\n\tconst detected = restrictToImages ? detectMediaType({\n\t\tdata,\n\t\tsignatures: imageMediaTypeSignatures\n\t}) : (_a23 = detectMediaType({\n\t\tdata,\n\t\tsignatures: imageMediaTypeSignatures\n\t})) != null ? _a23 : detectMediaType({\n\t\tdata,\n\t\tsignatures: videoMediaTypeSignatures\n\t});\n\treturn detected != null ? detected : \"image/png\";\n}\nfunction normalizeImageData(dataContent, { restrictToImages = true } = {}) {\n\tif (typeof dataContent === \"string\") {\n\t\tif (dataContent.startsWith(\"http://\") || dataContent.startsWith(\"https://\")) return {\n\t\t\ttype: \"url\",\n\t\t\turl: dataContent\n\t\t};\n\t\tif (dataContent.startsWith(\"data:\")) {\n\t\t\tconst { mediaType, base64Content } = splitDataUrl(dataContent);\n\t\t\tconst data = convertBase64ToUint8Array(base64Content != null ? base64Content : \"\");\n\t\t\treturn {\n\t\t\t\ttype: \"file\",\n\t\t\t\tmediaType: mediaType != null ? mediaType : detectFileMediaType(data, restrictToImages),\n\t\t\t\tdata\n\t\t\t};\n\t\t}\n\t\tconst bytes = convertBase64ToUint8Array(dataContent);\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: detectFileMediaType(bytes, restrictToImages),\n\t\t\tdata: bytes\n\t\t};\n\t}\n\tif (dataContent instanceof Uint8Array || dataContent instanceof ArrayBuffer) {\n\t\tconst bytes = dataContent instanceof Uint8Array ? dataContent : new Uint8Array(dataContent);\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: detectFileMediaType(bytes, restrictToImages),\n\t\t\tdata: bytes\n\t\t};\n\t}\n}\nfunction normalizeReferenceData(reference) {\n\tif (!(typeof reference === \"object\" && reference != null && !(reference instanceof Uint8Array) && !(reference instanceof ArrayBuffer) && \"data\" in reference)) return normalizeImageData(reference, { restrictToImages: false });\n\tconst normalized = normalizeImageData(reference.data, { restrictToImages: false });\n\tif (normalized == null) return normalized;\n\treturn {\n\t\t...normalized,\n\t\t...reference.mediaType != null ? { mediaType: reference.mediaType } : {}\n\t};\n}\nasync function invokeModelMaxVideosPerCall(model) {\n\tif (typeof model.maxVideosPerCall === \"function\") return await model.maxVideosPerCall({ modelId: model.modelId });\n\treturn model.maxVideosPerCall;\n}\nfunction defaultEmbeddingSettingsMiddleware({ settings }) {\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\nfunction defaultSettingsMiddleware({ settings }) {\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\treturn mergeObjects(settings, params);\n\t\t}\n\t};\n}\nfunction defaultTransform(text2) {\n\treturn text2.replace(/^```(?:json)?\\s*\\n?/, \"\").replace(/\\n?```\\s*$/, \"\").trim();\n}\nfunction stripMarkdownCodeFenceSuffix(text2) {\n\treturn text2.replace(/\\n?```\\s*$/, \"\").trimEnd();\n}\nfunction extractJsonMiddleware(options) {\n\tvar _a23;\n\tconst transform = (_a23 = options == null ? void 0 : options.transform) != null ? _a23 : defaultTransform;\n\tconst hasCustomTransform = (options == null ? void 0 : options.transform) !== void 0;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\t...part,\n\t\t\t\t\ttext: transform(part.text)\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst textBlocks = createIdMap();\n\t\t\tconst SUFFIX_BUFFER_SIZE = 12;\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\ttextBlocks[chunk.id] = {\n\t\t\t\t\t\t\tstartEvent: chunk,\n\t\t\t\t\t\t\tphase: hasCustomTransform ? \"buffering\" : \"prefix\",\n\t\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\t\tprefixStripped: false\n\t\t\t\t\t\t};\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-delta\") {\n\t\t\t\t\t\tconst block = textBlocks[chunk.id];\n\t\t\t\t\t\tif (!block) {\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tblock.buffer += chunk.delta;\n\t\t\t\t\t\tif (block.phase === \"buffering\") return;\n\t\t\t\t\t\tif (block.phase === \"prefix\") {\n\t\t\t\t\t\t\tif (block.buffer.length > 0 && !block.buffer.startsWith(\"`\")) {\n\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t} else if (block.buffer.startsWith(\"```\")) {\n\t\t\t\t\t\t\t\tif (block.buffer.includes(\"\\n\")) {\n\t\t\t\t\t\t\t\t\tconst prefixMatch = block.buffer.match(/^```(?:json)?\\s*\\n/);\n\t\t\t\t\t\t\t\t\tif (prefixMatch) {\n\t\t\t\t\t\t\t\t\t\tblock.buffer = block.buffer.slice(prefixMatch[0].length);\n\t\t\t\t\t\t\t\t\t\tblock.prefixStripped = true;\n\t\t\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else if (block.buffer.length >= 3 && !block.buffer.startsWith(\"```\")) {\n\t\t\t\t\t\t\t\tblock.phase = \"streaming\";\n\t\t\t\t\t\t\t\tcontroller.enqueue(block.startEvent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (block.phase === \"streaming\" && block.buffer.length > SUFFIX_BUFFER_SIZE) {\n\t\t\t\t\t\t\tconst toStream = block.buffer.slice(0, -12);\n\t\t\t\t\t\t\tblock.buffer = block.buffer.slice(-12);\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\tdelta: toStream\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\") {\n\t\t\t\t\t\tconst block = textBlocks[chunk.id];\n\t\t\t\t\t\tif (block) {\n\t\t\t\t\t\t\tif (block.phase === \"prefix\" || block.phase === \"buffering\") controller.enqueue(block.startEvent);\n\t\t\t\t\t\t\tlet remaining = block.buffer;\n\t\t\t\t\t\t\tif (block.phase === \"buffering\") remaining = transform(remaining);\n\t\t\t\t\t\t\telse if (block.prefixStripped) remaining = stripMarkdownCodeFenceSuffix(remaining);\n\t\t\t\t\t\t\telse if (block.phase === \"prefix\") remaining = transform(remaining);\n\t\t\t\t\t\t\telse remaining = stripMarkdownCodeFenceSuffix(remaining);\n\t\t\t\t\t\t\tif (remaining.length > 0) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\tid: chunk.id,\n\t\t\t\t\t\t\t\tdelta: remaining\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tdelete textBlocks[chunk.id];\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\nfunction getPotentialStartIndex(text2, searchedText) {\n\tif (searchedText.length === 0) return null;\n\tconst directIndex = text2.indexOf(searchedText);\n\tif (directIndex !== -1) return directIndex;\n\tfor (let i = text2.length - 1; i >= 0; i--) {\n\t\tconst suffix = text2.substring(i);\n\t\tif (searchedText.startsWith(suffix)) return i;\n\t}\n\treturn null;\n}\nfunction extractReasoningMiddleware({ tagName, separator = \"\\n\", startWithReasoning = false }) {\n\tconst openingTag = `<${tagName}>`;\n\tconst closingTag = `</${tagName}>`;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\twrapGenerate: async ({ doGenerate }) => {\n\t\t\tconst { content, ...rest } = await doGenerate();\n\t\t\tconst transformedContent = [];\n\t\t\tfor (const part of content) {\n\t\t\t\tif (part.type !== \"text\") {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst text2 = startWithReasoning ? openingTag + part.text : part.text;\n\t\t\t\tconst regexp = new RegExp(`${openingTag}(.*?)${closingTag}`, \"gs\");\n\t\t\t\tconst matches = Array.from(text2.matchAll(regexp));\n\t\t\t\tif (!matches.length) {\n\t\t\t\t\ttransformedContent.push(part);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst reasoningText = matches.map((match) => match[1]).join(separator);\n\t\t\t\tlet textWithoutReasoning = text2;\n\t\t\t\tfor (let i = matches.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst match = matches[i];\n\t\t\t\t\tconst beforeMatch = textWithoutReasoning.slice(0, match.index);\n\t\t\t\t\tconst afterMatch = textWithoutReasoning.slice(match.index + match[0].length);\n\t\t\t\t\ttextWithoutReasoning = beforeMatch + (beforeMatch.length > 0 && afterMatch.length > 0 ? separator : \"\") + afterMatch;\n\t\t\t\t}\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"reasoning\",\n\t\t\t\t\ttext: reasoningText\n\t\t\t\t});\n\t\t\t\ttransformedContent.push({\n\t\t\t\t\ttype: \"text\",\n\t\t\t\t\ttext: textWithoutReasoning\n\t\t\t\t});\n\t\t\t}\n\t\t\treturn {\n\t\t\t\tcontent: transformedContent,\n\t\t\t\t...rest\n\t\t\t};\n\t\t},\n\t\twrapStream: async ({ doStream }) => {\n\t\t\tconst { stream, ...rest } = await doStream();\n\t\t\tconst reasoningExtractions = createIdMap();\n\t\t\tlet delayedTextStart;\n\t\t\treturn {\n\t\t\t\tstream: stream.pipeThrough(new TransformStream({ transform: (chunk, controller) => {\n\t\t\t\t\tif (chunk.type === \"text-start\") {\n\t\t\t\t\t\tdelayedTextStart = chunk;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type === \"text-end\" && delayedTextStart) {\n\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t}\n\t\t\t\t\tif (chunk.type !== \"text-delta\") {\n\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (reasoningExtractions[chunk.id] == null) reasoningExtractions[chunk.id] = {\n\t\t\t\t\t\tisFirstReasoning: true,\n\t\t\t\t\t\tisFirstText: true,\n\t\t\t\t\t\tafterSwitch: false,\n\t\t\t\t\t\tisReasoning: startWithReasoning,\n\t\t\t\t\t\tbuffer: \"\",\n\t\t\t\t\t\tidCounter: 0,\n\t\t\t\t\t\ttextId: chunk.id\n\t\t\t\t\t};\n\t\t\t\t\tconst activeExtraction = reasoningExtractions[chunk.id];\n\t\t\t\t\tactiveExtraction.buffer += chunk.delta;\n\t\t\t\t\tfunction publish(text2) {\n\t\t\t\t\t\tif (text2.length > 0) {\n\t\t\t\t\t\t\tconst prefix = activeExtraction.afterSwitch && (activeExtraction.isReasoning ? !activeExtraction.isFirstReasoning : !activeExtraction.isFirstText) ? separator : \"\";\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning && (activeExtraction.afterSwitch || activeExtraction.isFirstReasoning)) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\tif (delayedTextStart) {\n\t\t\t\t\t\t\t\t\tcontroller.enqueue(delayedTextStart);\n\t\t\t\t\t\t\t\t\tdelayedTextStart = void 0;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tdelta: prefix + text2,\n\t\t\t\t\t\t\t\t\tid: activeExtraction.textId\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = false;\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) activeExtraction.isFirstReasoning = false;\n\t\t\t\t\t\t\telse activeExtraction.isFirstText = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tdo {\n\t\t\t\t\t\tconst nextTag = activeExtraction.isReasoning ? closingTag : openingTag;\n\t\t\t\t\t\tconst startIndex = getPotentialStartIndex(activeExtraction.buffer, nextTag);\n\t\t\t\t\t\tif (startIndex == null) {\n\t\t\t\t\t\t\tpublish(activeExtraction.buffer);\n\t\t\t\t\t\t\tactiveExtraction.buffer = \"\";\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tpublish(activeExtraction.buffer.slice(0, startIndex));\n\t\t\t\t\t\tif (startIndex + nextTag.length <= activeExtraction.buffer.length) {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex + nextTag.length);\n\t\t\t\t\t\t\tif (activeExtraction.isReasoning) {\n\t\t\t\t\t\t\t\tif (activeExtraction.isFirstReasoning) controller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter}`\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\t\tid: `reasoning-${activeExtraction.idCounter++}`\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tactiveExtraction.isReasoning = !activeExtraction.isReasoning;\n\t\t\t\t\t\t\tactiveExtraction.afterSwitch = true;\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tactiveExtraction.buffer = activeExtraction.buffer.slice(startIndex);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t} while (true);\n\t\t\t\t} })),\n\t\t\t\t...rest\n\t\t\t};\n\t\t}\n\t};\n}\nfunction simulateStreamingMiddleware() {\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\twrapStream: async ({ doGenerate }) => {\n\t\t\tconst result = await doGenerate();\n\t\t\tlet id = 0;\n\t\t\treturn {\n\t\t\t\tstream: new ReadableStream({ start(controller) {\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"stream-start\",\n\t\t\t\t\t\twarnings: result.warnings\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"response-metadata\",\n\t\t\t\t\t\t...result.response\n\t\t\t\t\t});\n\t\t\t\t\tfor (const part of result.content) switch (part.type) {\n\t\t\t\t\t\tcase \"text\":\n\t\t\t\t\t\t\tif (part.text.length > 0) {\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-start\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\t...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-delta\",\n\t\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\t\ttype: \"text-end\",\n\t\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"reasoning\":\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-start\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tproviderMetadata: part.providerMetadata\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-delta\",\n\t\t\t\t\t\t\t\tid: String(id),\n\t\t\t\t\t\t\t\tdelta: part.text\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\t\t\ttype: \"reasoning-end\",\n\t\t\t\t\t\t\t\tid: String(id)\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\tid++;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tdefault: controller.enqueue(part);\n\t\t\t\t\t}\n\t\t\t\t\tcontroller.enqueue({\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: result.finishReason,\n\t\t\t\t\t\tusage: result.usage,\n\t\t\t\t\t\tproviderMetadata: result.providerMetadata\n\t\t\t\t\t});\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} }),\n\t\t\t\trequest: result.request,\n\t\t\t\tresponse: result.response\n\t\t\t};\n\t\t}\n\t};\n}\nfunction defaultFormatExample(example) {\n\treturn JSON.stringify(example.input);\n}\nfunction addToolInputExamplesMiddleware({ prefix = \"Input Examples:\", format = defaultFormatExample, remove = true } = {}) {\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\ttransformParams: async ({ params }) => {\n\t\t\tvar _a23;\n\t\t\tif (!((_a23 = params.tools) == null ? void 0 : _a23.length)) return params;\n\t\t\tconst transformedTools = params.tools.map((tool2) => {\n\t\t\t\tvar _a24;\n\t\t\t\tif (tool2.type !== \"function\" || !((_a24 = tool2.inputExamples) == null ? void 0 : _a24.length)) return tool2;\n\t\t\t\tconst examplesSection = `${prefix}\n${tool2.inputExamples.map((example, index) => format(example, index)).join(\"\\n\")}`;\n\t\t\t\tconst toolDescription = tool2.description ? `${tool2.description}\n\n${examplesSection}` : examplesSection;\n\t\t\t\treturn {\n\t\t\t\t\t...tool2,\n\t\t\t\t\tdescription: toolDescription,\n\t\t\t\t\tinputExamples: remove ? void 0 : tool2.inputExamples\n\t\t\t\t};\n\t\t\t});\n\t\t\treturn {\n\t\t\t\t...params,\n\t\t\t\ttools: transformedTools\n\t\t\t};\n\t\t}\n\t};\n}\nvar wrapLanguageModel = ({ model, middleware: middlewareArg, modelId, providerId }) => {\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nvar doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream, overrideProvider, overrideModelId, overrideSupportedUrls }, modelId, providerId }) => {\n\tvar _a23, _b, _c;\n\tasync function doTransform({ params, type }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\ttype,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tprovider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,\n\t\tmodelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n\t\tsupportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"generate\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapGenerate ? wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doGenerate();\n\t\t},\n\t\tasync doStream(params) {\n\t\t\tconst transformedParams = await doTransform({\n\t\t\t\tparams,\n\t\t\t\ttype: \"stream\"\n\t\t\t});\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\tconst doStream = async () => model.doStream(transformedParams);\n\t\t\treturn wrapStream ? wrapStream({\n\t\t\t\tdoGenerate,\n\t\t\t\tdoStream,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doStream();\n\t\t}\n\t};\n};\nvar wrapEmbeddingModel = ({ model, middleware: middlewareArg, modelId, providerId }) => {\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap2({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nvar doWrap2 = ({ model, middleware: { transformParams, wrapEmbed, overrideProvider, overrideModelId, overrideMaxEmbeddingsPerCall, overrideSupportsParallelCalls }, modelId, providerId }) => {\n\tvar _a23, _b, _c, _d;\n\tasync function doTransform({ params }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tprovider: (_a23 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a23 : model.provider,\n\t\tmodelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,\n\t\tmaxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,\n\t\t[EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL]: getEmbeddingModelMaxInputBytesPerCall(model),\n\t\t[EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER]: getEmbeddingModelProviderOptionsTransformer(model),\n\t\tsupportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,\n\t\tasync doEmbed(params) {\n\t\t\tconst transformedParams = await doTransform({ params });\n\t\t\tconst doEmbed = async () => model.doEmbed(transformedParams);\n\t\t\treturn wrapEmbed ? wrapEmbed({\n\t\t\t\tdoEmbed,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doEmbed();\n\t\t}\n\t};\n};\nvar wrapImageModel = ({ model, middleware: middlewareArg, modelId, providerId }) => {\n\treturn [...asArray(middlewareArg)].reverse().reduce((wrappedModel, middleware) => {\n\t\treturn doWrap3({\n\t\t\tmodel: wrappedModel,\n\t\t\tmiddleware,\n\t\t\tmodelId,\n\t\t\tproviderId\n\t\t});\n\t}, model);\n};\nvar doWrap3 = ({ model, middleware: { transformParams, wrapGenerate, overrideProvider, overrideModelId, overrideMaxImagesPerCall }, modelId, providerId }) => {\n\tvar _a23, _b, _c;\n\tasync function doTransform({ params }) {\n\t\treturn transformParams ? await transformParams({\n\t\t\tparams,\n\t\t\tmodel\n\t\t}) : params;\n\t}\n\tconst maxImagesPerCallRaw = (_a23 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a23 : model.maxImagesPerCall;\n\tconst maxImagesPerCall = maxImagesPerCallRaw instanceof Function ? maxImagesPerCallRaw.bind(model) : maxImagesPerCallRaw;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tprovider: (_b = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _b : model.provider,\n\t\tmodelId: (_c = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _c : model.modelId,\n\t\tmaxImagesPerCall,\n\t\tasync doGenerate(params) {\n\t\t\tconst transformedParams = await doTransform({ params });\n\t\t\tconst doGenerate = async () => model.doGenerate(transformedParams);\n\t\t\treturn wrapGenerate ? wrapGenerate({\n\t\t\t\tdoGenerate,\n\t\t\t\tparams: transformedParams,\n\t\t\t\tmodel\n\t\t\t}) : doGenerate();\n\t\t}\n\t};\n};\nfunction asProviderV3(provider) {\n\tif (\"specificationVersion\" in provider && provider.specificationVersion === \"v3\") return provider;\n\tconst v2Provider = provider;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tlanguageModel: (modelId) => asLanguageModelV3(v2Provider.languageModel(modelId)),\n\t\tembeddingModel: (modelId) => asEmbeddingModelV3(v2Provider.textEmbeddingModel(modelId)),\n\t\timageModel: (modelId) => asImageModelV3(v2Provider.imageModel(modelId)),\n\t\ttranscriptionModel: v2Provider.transcriptionModel ? (modelId) => asTranscriptionModelV3(v2Provider.transcriptionModel(modelId)) : void 0,\n\t\tspeechModel: v2Provider.speechModel ? (modelId) => asSpeechModelV3(v2Provider.speechModel(modelId)) : void 0,\n\t\trerankingModel: void 0\n\t};\n}\nfunction wrapProvider({ provider, languageModelMiddleware, imageModelMiddleware }) {\n\tconst providerV3 = asProviderV3(provider);\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tlanguageModel: (modelId) => wrapLanguageModel({\n\t\t\tmodel: providerV3.languageModel(modelId),\n\t\t\tmiddleware: languageModelMiddleware\n\t\t}),\n\t\tembeddingModel: providerV3.embeddingModel,\n\t\timageModel: (modelId) => {\n\t\t\tlet model = providerV3.imageModel(modelId);\n\t\t\tif (imageModelMiddleware != null) model = wrapImageModel({\n\t\t\t\tmodel,\n\t\t\t\tmiddleware: imageModelMiddleware\n\t\t\t});\n\t\t\treturn model;\n\t\t},\n\t\ttranscriptionModel: providerV3.transcriptionModel,\n\t\tspeechModel: providerV3.speechModel,\n\t\trerankingModel: providerV3.rerankingModel\n\t};\n}\nfunction customProvider({ languageModels, embeddingModels, imageModels, transcriptionModels, speechModels, rerankingModels, videoModels, fallbackProvider: fallbackProviderArg }) {\n\tconst fallbackProvider = fallbackProviderArg ? asProviderV3(fallbackProviderArg) : void 0;\n\treturn {\n\t\tspecificationVersion: \"v3\",\n\t\tlanguageModel(modelId) {\n\t\t\tif (languageModels != null && modelId in languageModels) return languageModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.languageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"languageModel\"\n\t\t\t});\n\t\t},\n\t\tembeddingModel(modelId) {\n\t\t\tif (embeddingModels != null && modelId in embeddingModels) return embeddingModels[modelId];\n\t\t\tif (fallbackProvider) return fallbackProvider.embeddingModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"embeddingModel\"\n\t\t\t});\n\t\t},\n\t\timageModel(modelId) {\n\t\t\tif (imageModels != null && modelId in imageModels) return imageModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.imageModel) return fallbackProvider.imageModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"imageModel\"\n\t\t\t});\n\t\t},\n\t\ttranscriptionModel(modelId) {\n\t\t\tif (transcriptionModels != null && modelId in transcriptionModels) return transcriptionModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.transcriptionModel) return fallbackProvider.transcriptionModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"transcriptionModel\"\n\t\t\t});\n\t\t},\n\t\tspeechModel(modelId) {\n\t\t\tif (speechModels != null && modelId in speechModels) return speechModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.speechModel) return fallbackProvider.speechModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"speechModel\"\n\t\t\t});\n\t\t},\n\t\trerankingModel(modelId) {\n\t\t\tif (rerankingModels != null && modelId in rerankingModels) return rerankingModels[modelId];\n\t\t\tif (fallbackProvider == null ? void 0 : fallbackProvider.rerankingModel) return fallbackProvider.rerankingModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"rerankingModel\"\n\t\t\t});\n\t\t},\n\t\tvideoModel(modelId) {\n\t\t\tif (videoModels != null && modelId in videoModels) return videoModels[modelId];\n\t\t\tconst videoModel = fallbackProvider == null ? void 0 : fallbackProvider.videoModel;\n\t\t\tif (videoModel) return videoModel(modelId);\n\t\t\tthrow new NoSuchModelError({\n\t\t\t\tmodelId,\n\t\t\t\tmodelType: \"videoModel\"\n\t\t\t});\n\t\t}\n\t};\n}\nvar experimental_customProvider = customProvider;\nvar name22 = \"AI_NoSuchProviderError\";\nvar marker22 = `vercel.ai.error.${name22}`;\nvar symbol22 = Symbol.for(marker22);\nvar _a22;\nvar NoSuchProviderError = class extends NoSuchModelError {\n\tconstructor({ modelId, modelType, providerId, availableProviders, message = `No such provider: ${providerId} (available providers: ${availableProviders.join()})` }) {\n\t\tsuper({\n\t\t\terrorName: name22,\n\t\t\tmodelId,\n\t\t\tmodelType,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a22] = true;\n\t\tthis.providerId = providerId;\n\t\tthis.availableProviders = availableProviders;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker22);\n\t}\n};\n_a22 = symbol22;\nfunction createProviderRegistry(providers, { separator = \":\", languageModelMiddleware, imageModelMiddleware } = {}) {\n\tconst registry = new DefaultProviderRegistry({\n\t\tseparator,\n\t\tlanguageModelMiddleware,\n\t\timageModelMiddleware\n\t});\n\tfor (const [id, provider] of Object.entries(providers)) registry.registerProvider({\n\t\tid,\n\t\tprovider\n\t});\n\treturn registry;\n}\nvar experimental_createProviderRegistry = createProviderRegistry;\nvar DefaultProviderRegistry = class {\n\tconstructor({ separator, languageModelMiddleware, imageModelMiddleware }) {\n\t\tthis.providers = /* @__PURE__ */ Object.create(null);\n\t\tthis.separator = separator;\n\t\tthis.languageModelMiddleware = languageModelMiddleware;\n\t\tthis.imageModelMiddleware = imageModelMiddleware;\n\t}\n\tregisterProvider({ id, provider }) {\n\t\tthis.providers[id] = provider;\n\t}\n\tgetProvider(id, modelType) {\n\t\tconst provider = this.providers[id];\n\t\tif (provider == null) throw new NoSuchProviderError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tproviderId: id,\n\t\t\tavailableProviders: Object.keys(this.providers)\n\t\t});\n\t\treturn provider;\n\t}\n\tsplitId(id, modelType) {\n\t\tconst index = id.indexOf(this.separator);\n\t\tif (index === -1) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType,\n\t\t\tmessage: `Invalid ${modelType} id for registry: ${id} (must be in the format \"providerId${this.separator}modelId\")`\n\t\t});\n\t\treturn [id.slice(0, index), id.slice(index + this.separator.length)];\n\t}\n\tlanguageModel(id) {\n\t\tvar _a23, _b;\n\t\tconst [providerId, modelId] = this.splitId(id, \"languageModel\");\n\t\tlet model = (_b = (_a23 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(_a23, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"languageModel\"\n\t\t});\n\t\tif (this.languageModelMiddleware != null) model = wrapLanguageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.languageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\tembeddingModel(id) {\n\t\tvar _a23;\n\t\tconst [providerId, modelId] = this.splitId(id, \"embeddingModel\");\n\t\tconst provider = this.getProvider(providerId, \"embeddingModel\");\n\t\tconst model = (_a23 = provider.embeddingModel) == null ? void 0 : _a23.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"embeddingModel\"\n\t\t});\n\t\treturn model;\n\t}\n\timageModel(id) {\n\t\tvar _a23;\n\t\tconst [providerId, modelId] = this.splitId(id, \"imageModel\");\n\t\tconst provider = this.getProvider(providerId, \"imageModel\");\n\t\tlet model = (_a23 = provider.imageModel) == null ? void 0 : _a23.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"imageModel\"\n\t\t});\n\t\tif (this.imageModelMiddleware != null) model = wrapImageModel({\n\t\t\tmodel,\n\t\t\tmiddleware: this.imageModelMiddleware\n\t\t});\n\t\treturn model;\n\t}\n\ttranscriptionModel(id) {\n\t\tvar _a23;\n\t\tconst [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n\t\tconst provider = this.getProvider(providerId, \"transcriptionModel\");\n\t\tconst model = (_a23 = provider.transcriptionModel) == null ? void 0 : _a23.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"transcriptionModel\"\n\t\t});\n\t\treturn model;\n\t}\n\tspeechModel(id) {\n\t\tvar _a23;\n\t\tconst [providerId, modelId] = this.splitId(id, \"speechModel\");\n\t\tconst provider = this.getProvider(providerId, \"speechModel\");\n\t\tconst model = (_a23 = provider.speechModel) == null ? void 0 : _a23.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"speechModel\"\n\t\t});\n\t\treturn model;\n\t}\n\trerankingModel(id) {\n\t\tvar _a23;\n\t\tconst [providerId, modelId] = this.splitId(id, \"rerankingModel\");\n\t\tconst provider = this.getProvider(providerId, \"rerankingModel\");\n\t\tconst model = (_a23 = provider.rerankingModel) == null ? void 0 : _a23.call(provider, modelId);\n\t\tif (model == null) throw new NoSuchModelError({\n\t\t\tmodelId: id,\n\t\t\tmodelType: \"rerankingModel\"\n\t\t});\n\t\treturn model;\n\t}\n};\nasync function rerank({ model: modelArg, documents, query, topN, maxRetries: maxRetriesArg, abortSignal, headers, providerOptions, experimental_telemetry: telemetry }) {\n\tconst model = resolveRerankingModel(modelArg);\n\tif (documents.length === 0) return new DefaultRerankResult({\n\t\toriginalDocuments: [],\n\t\tranking: [],\n\t\tproviderMetadata: void 0,\n\t\tresponse: {\n\t\t\ttimestamp: /* @__PURE__ */ new Date(),\n\t\t\tmodelId: model.modelId\n\t\t}\n\t});\n\tconst { maxRetries, retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst documentsToSend = typeof documents[0] === \"string\" ? {\n\t\ttype: \"text\",\n\t\tvalues: documents\n\t} : {\n\t\ttype: \"object\",\n\t\tvalues: documents\n\t};\n\tconst baseTelemetryAttributes = getBaseTelemetryAttributes({\n\t\tmodel,\n\t\ttelemetry,\n\t\theaders,\n\t\tsettings: { maxRetries }\n\t});\n\tconst tracer = getTracer(telemetry);\n\treturn recordSpan({\n\t\tname: \"ai.rerank\",\n\t\tattributes: selectTelemetryAttributes({\n\t\t\ttelemetry,\n\t\t\tattributes: {\n\t\t\t\t...assembleOperationName({\n\t\t\t\t\toperationId: \"ai.rerank\",\n\t\t\t\t\ttelemetry\n\t\t\t\t}),\n\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\"ai.documents\": { input: () => documents.map((document2) => JSON.stringify(document2)) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async () => {\n\t\t\tvar _a23, _b;\n\t\t\tconst { ranking, response, providerMetadata, warnings } = await retry(() => recordSpan({\n\t\t\t\tname: \"ai.rerank.doRerank\",\n\t\t\t\tattributes: selectTelemetryAttributes({\n\t\t\t\t\ttelemetry,\n\t\t\t\t\tattributes: {\n\t\t\t\t\t\t...assembleOperationName({\n\t\t\t\t\t\t\toperationId: \"ai.rerank.doRerank\",\n\t\t\t\t\t\t\ttelemetry\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t...baseTelemetryAttributes,\n\t\t\t\t\t\t\"ai.documents\": { input: () => documents.map((document2) => JSON.stringify(document2)) }\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\ttracer,\n\t\t\t\tfn: async (doRerankSpan) => {\n\t\t\t\t\tconst modelResponse = await model.doRerank({\n\t\t\t\t\t\tdocuments: documentsToSend,\n\t\t\t\t\t\tquery,\n\t\t\t\t\t\ttopN,\n\t\t\t\t\t\tproviderOptions,\n\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\theaders\n\t\t\t\t\t});\n\t\t\t\t\tconst ranking2 = modelResponse.ranking;\n\t\t\t\t\tdoRerankSpan.setAttributes(await selectTelemetryAttributes({\n\t\t\t\t\t\ttelemetry,\n\t\t\t\t\t\tattributes: {\n\t\t\t\t\t\t\t\"ai.ranking.type\": documentsToSend.type,\n\t\t\t\t\t\t\t\"ai.ranking\": { output: () => ranking2.map((ranking3) => JSON.stringify(ranking3)) }\n\t\t\t\t\t\t}\n\t\t\t\t\t}));\n\t\t\t\t\treturn {\n\t\t\t\t\t\tranking: ranking2,\n\t\t\t\t\t\tproviderMetadata: modelResponse.providerMetadata,\n\t\t\t\t\t\tresponse: modelResponse.response,\n\t\t\t\t\t\twarnings: modelResponse.warnings\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}));\n\t\t\tvalidateRankingIndices({\n\t\t\t\tranking,\n\t\t\t\tdocuments\n\t\t\t});\n\t\t\tlogWarnings({\n\t\t\t\twarnings: warnings != null ? warnings : [],\n\t\t\t\tprovider: model.provider,\n\t\t\t\tmodel: model.modelId\n\t\t\t});\n\t\t\treturn new DefaultRerankResult({\n\t\t\t\toriginalDocuments: documents,\n\t\t\t\tranking: ranking.map((ranking2) => ({\n\t\t\t\t\toriginalIndex: ranking2.index,\n\t\t\t\t\tscore: ranking2.relevanceScore,\n\t\t\t\t\tdocument: documents[ranking2.index]\n\t\t\t\t})),\n\t\t\t\tproviderMetadata,\n\t\t\t\tresponse: {\n\t\t\t\t\tid: response == null ? void 0 : response.id,\n\t\t\t\t\ttimestamp: (_a23 = response == null ? void 0 : response.timestamp) != null ? _a23 : /* @__PURE__ */ new Date(),\n\t\t\t\t\tmodelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,\n\t\t\t\t\theaders: response == null ? void 0 : response.headers,\n\t\t\t\t\tbody: response == null ? void 0 : response.body\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t});\n}\nfunction validateRankingIndices({ ranking, documents }) {\n\tfor (const { index } of ranking) if (!Number.isInteger(index) || index < 0 || index >= documents.length) throw new InvalidResponseDataError({\n\t\tdata: ranking,\n\t\tmessage: `Invalid ranking index ${index}. Expected an integer between 0 and ${documents.length - 1}.`\n\t});\n}\nvar DefaultRerankResult = class {\n\tconstructor(options) {\n\t\tthis.originalDocuments = options.originalDocuments;\n\t\tthis.ranking = options.ranking;\n\t\tthis.response = options.response;\n\t\tthis.providerMetadata = options.providerMetadata;\n\t}\n\tget rerankedDocuments() {\n\t\treturn this.ranking.map((ranking) => ranking.document);\n\t}\n};\nvar defaultDownload2 = createDownload();\nasync function transcribe({ model, audio, providerOptions = {}, maxRetries: maxRetriesArg, abortSignal, headers, download: downloadFn = defaultDownload2 }) {\n\tconst resolvedModel = resolveTranscriptionModel(model);\n\tif (!resolvedModel) throw new Error(\"Model could not be resolved\");\n\tconst { retry } = prepareRetries({\n\t\tmaxRetries: maxRetriesArg,\n\t\tabortSignal\n\t});\n\tconst headersWithUserAgent = withUserAgentSuffix(headers != null ? headers : {}, `ai/${VERSION}`);\n\tconst audioData = audio instanceof URL ? (await downloadFn({\n\t\turl: audio,\n\t\tabortSignal\n\t})).data : convertDataContentToUint8Array(audio);\n\tconst result = await retry(() => {\n\t\tvar _a23;\n\t\treturn resolvedModel.doGenerate({\n\t\t\taudio: audioData,\n\t\t\tabortSignal,\n\t\t\theaders: headersWithUserAgent,\n\t\t\tproviderOptions,\n\t\t\tmediaType: (_a23 = detectMediaType({\n\t\t\t\tdata: audioData,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a23 : \"audio/wav\"\n\t\t});\n\t});\n\tlogWarnings({\n\t\twarnings: result.warnings,\n\t\tprovider: resolvedModel.provider,\n\t\tmodel: resolvedModel.modelId\n\t});\n\tif (!result.text) throw new NoTranscriptGeneratedError({ responses: [result.response] });\n\treturn new DefaultTranscriptionResult({\n\t\ttext: result.text,\n\t\tsegments: result.segments,\n\t\tlanguage: result.language,\n\t\tdurationInSeconds: result.durationInSeconds,\n\t\twarnings: result.warnings,\n\t\tresponses: [result.response],\n\t\tproviderMetadata: result.providerMetadata\n\t});\n}\nvar DefaultTranscriptionResult = class {\n\tconstructor(options) {\n\t\tvar _a23;\n\t\tthis.text = options.text;\n\t\tthis.segments = options.segments;\n\t\tthis.language = options.language;\n\t\tthis.durationInSeconds = options.durationInSeconds;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a23 = options.providerMetadata) != null ? _a23 : {};\n\t}\n};\nasync function processTextStream({ stream, onTextPart }) {\n\tconst reader = stream.pipeThrough(new TextDecoderStream()).getReader();\n\twhile (true) {\n\t\tconst { done, value } = await reader.read();\n\t\tif (done) break;\n\t\tawait onTextPart(value);\n\t}\n}\nvar getOriginalFetch = () => fetch;\nasync function callCompletionApi({ api, prompt, credentials, headers, body, streamProtocol = \"data\", setCompletion, setLoading, setError, setAbortController, onFinish, onError, fetch: fetch2 = getOriginalFetch() }) {\n\tvar _a23;\n\ttry {\n\t\tsetLoading(true);\n\t\tsetError(void 0);\n\t\tconst abortController = new AbortController();\n\t\tsetAbortController(abortController);\n\t\tsetCompletion(\"\");\n\t\tconst response = await fetch2(api, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tprompt,\n\t\t\t\t...body\n\t\t\t}),\n\t\t\tcredentials,\n\t\t\theaders: withUserAgentSuffix({\n\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\n\t\t\tsignal: abortController.signal\n\t\t}).catch((err) => {\n\t\t\tthrow err;\n\t\t});\n\t\tif (!response.ok) throw new Error((_a23 = await response.text()) != null ? _a23 : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\tlet result = \"\";\n\t\tswitch (streamProtocol) {\n\t\t\tcase \"text\":\n\t\t\t\tawait processTextStream({\n\t\t\t\t\tstream: response.body,\n\t\t\t\t\tonTextPart: (chunk) => {\n\t\t\t\t\t\tresult += chunk;\n\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tcase \"data\":\n\t\t\t\tawait consumeStream({\n\t\t\t\t\tstream: parseJsonEventStream({\n\t\t\t\t\t\tstream: response.body,\n\t\t\t\t\t\tschema: uiMessageChunkSchema\n\t\t\t\t\t}).pipeThrough(new TransformStream({ async transform(part) {\n\t\t\t\t\t\tif (!part.success) throw part.error;\n\t\t\t\t\t\tconst streamPart = part.value;\n\t\t\t\t\t\tif (streamPart.type === \"text-delta\") {\n\t\t\t\t\t\t\tresult += streamPart.delta;\n\t\t\t\t\t\t\tsetCompletion(result);\n\t\t\t\t\t\t} else if (streamPart.type === \"error\") throw new Error(streamPart.errorText);\n\t\t\t\t\t} })),\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\tdefault: throw new Error(`Unknown stream protocol: ${streamProtocol}`);\n\t\t}\n\t\tif (onFinish) onFinish(prompt, result);\n\t\tsetAbortController(null);\n\t\treturn result;\n\t} catch (err) {\n\t\tif (err.name === \"AbortError\") {\n\t\t\tsetAbortController(null);\n\t\t\treturn null;\n\t\t}\n\t\tif (err instanceof Error) {\n\t\t\tif (onError) onError(err);\n\t\t}\n\t\tsetError(err);\n\t} finally {\n\t\tsetLoading(false);\n\t}\n}\nasync function convertFileListToFileUIParts(files) {\n\tif (files == null) return [];\n\tif (!globalThis.FileList || !(files instanceof globalThis.FileList)) throw new Error(\"FileList is not supported in the current environment\");\n\treturn Promise.all(Array.from(files).map(async (file) => {\n\t\tconst { name: name23, type } = file;\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: type,\n\t\t\tfilename: name23,\n\t\t\turl: await new Promise((resolve3, reject) => {\n\t\t\t\tconst reader = new FileReader();\n\t\t\t\treader.onload = (readerEvent) => {\n\t\t\t\t\tvar _a23;\n\t\t\t\t\tresolve3((_a23 = readerEvent.target) == null ? void 0 : _a23.result);\n\t\t\t\t};\n\t\t\t\treader.onerror = (error) => reject(error);\n\t\t\t\treader.readAsDataURL(file);\n\t\t\t})\n\t\t};\n\t}));\n}\nfunction appendPathToUrl(url, path) {\n\tconst queryOrFragmentStart = url.search(/[?#]/);\n\tconst urlPath = queryOrFragmentStart === -1 ? url : url.slice(0, queryOrFragmentStart);\n\tconst suffix = queryOrFragmentStart === -1 ? \"\" : url.slice(queryOrFragmentStart);\n\treturn `${urlPath.endsWith(\"/\") && path.startsWith(\"/\") ? urlPath.slice(0, -1) : urlPath}${path}${suffix}`;\n}\nvar HttpChatTransport = class {\n\tconstructor({ api = \"/api/chat\", credentials, headers, body, fetch: fetch2, prepareSendMessagesRequest, prepareReconnectToStreamRequest }) {\n\t\tthis.api = api;\n\t\tthis.credentials = credentials;\n\t\tthis.headers = headers;\n\t\tthis.body = body;\n\t\tthis.fetch = fetch2;\n\t\tthis.prepareSendMessagesRequest = prepareSendMessagesRequest;\n\t\tthis.prepareReconnectToStreamRequest = prepareReconnectToStreamRequest;\n\t}\n\tasync sendMessages({ abortSignal, ...options }) {\n\t\tvar _a23, _b, _c, _d, _e;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a23 = this.prepareSendMessagesRequest) == null ? void 0 : _a23.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t}));\n\t\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : this.api;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst body = (preparedRequest == null ? void 0 : preparedRequest.body) !== void 0 ? preparedRequest.body : {\n\t\t\t...resolvedBody,\n\t\t\t...options.body,\n\t\t\tid: options.chatId,\n\t\t\tmessages: options.messages,\n\t\t\ttrigger: options.trigger,\n\t\t\tmessageId: options.messageId\n\t\t};\n\t\tconst credentials = (_c = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _c : resolvedCredentials;\n\t\tconst response = await ((_d = this.fetch) != null ? _d : globalThis.fetch)(api, {\n\t\t\tmethod: \"POST\",\n\t\t\theaders: {\n\t\t\t\t\"content-type\": \"application/json\",\n\t\t\t\t...headers\n\t\t\t},\n\t\t\tbody: JSON.stringify(body),\n\t\t\tcredentials,\n\t\t\tsignal: abortSignal\n\t\t});\n\t\tif (!response.ok) throw new Error((_e = await response.text()) != null ? _e : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n\tasync reconnectToStream(options) {\n\t\tvar _a23, _b, _c, _d;\n\t\tconst resolvedBody = await resolve(this.body);\n\t\tconst resolvedHeaders = await resolve(this.headers);\n\t\tconst resolvedCredentials = await resolve(this.credentials);\n\t\tconst baseHeaders = {\n\t\t\t...normalizeHeaders(resolvedHeaders),\n\t\t\t...normalizeHeaders(options.headers)\n\t\t};\n\t\tconst preparedRequest = await ((_a23 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a23.call(this, {\n\t\t\tapi: this.api,\n\t\t\tid: options.chatId,\n\t\t\tbody: {\n\t\t\t\t...resolvedBody,\n\t\t\t\t...options.body\n\t\t\t},\n\t\t\theaders: baseHeaders,\n\t\t\tcredentials: resolvedCredentials,\n\t\t\trequestMetadata: options.metadata\n\t\t}));\n\t\tlet api = preparedRequest == null ? void 0 : preparedRequest.api;\n\t\tif (api == null) {\n\t\t\tif (options.chatId === \".\" || options.chatId === \"..\") throw new InvalidArgumentError({\n\t\t\t\tparameter: \"chatId\",\n\t\t\t\tvalue: options.chatId,\n\t\t\t\tmessage: \"Chat IDs must not be \\\".\\\" or \\\"..\\\" when using the default reconnect URL.\"\n\t\t\t});\n\t\t\tapi = appendPathToUrl(this.api, `/${encodeURIComponent(options.chatId)}/stream`);\n\t\t}\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\n\t\tconst credentials = (_b = preparedRequest == null ? void 0 : preparedRequest.credentials) != null ? _b : resolvedCredentials;\n\t\tconst response = await ((_c = this.fetch) != null ? _c : globalThis.fetch)(api, {\n\t\t\tmethod: \"GET\",\n\t\t\theaders,\n\t\t\tcredentials,\n\t\t\tsignal: options.abortSignal\n\t\t});\n\t\tif (response.status === 204) return null;\n\t\tif (!response.ok) throw new Error((_d = await response.text()) != null ? _d : \"Failed to fetch the chat response.\");\n\t\tif (!response.body) throw new Error(\"The response body is empty.\");\n\t\treturn this.processResponseStream(response.body);\n\t}\n};\nvar DefaultChatTransport = class extends HttpChatTransport {\n\tconstructor({ resumeStreamIsReplay = true, ...options } = {}) {\n\t\tsuper(options);\n\t\tthis.resumeStreamIsReplay = resumeStreamIsReplay;\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn parseJsonEventStream({\n\t\t\tstream,\n\t\t\tschema: uiMessageChunkSchema\n\t\t}).pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\t\tif (!chunk.success) throw chunk.error;\n\t\t\tcontroller.enqueue(chunk.value);\n\t\t} }));\n\t}\n};\nvar AbstractChat = class {\n\tconstructor({ generateId: generateId2 = generateId, id = generateId2(), transport = new DefaultChatTransport(), messageMetadataSchema, dataPartSchemas, state, onError, onToolCall, onFinish, onData, sendAutomaticallyWhen }) {\n\t\tthis.activeResponse = void 0;\n\t\tthis.activeResumeRequest = void 0;\n\t\tthis.resumableStreamState = void 0;\n\t\tthis.jobExecutor = new SerialJobExecutor();\n\t\tthis.activeStopCount = 0;\n\t\tthis.stopGeneration = 0;\n\t\t/**\n\t\t* Appends or replaces a user message to the chat list. This triggers the API call to fetch\n\t\t* the assistant's response.\n\t\t*\n\t\t* If a messageId is provided, the message will be replaced.\n\t\t*/\n\t\tthis.sendMessage = async (message, options) => {\n\t\t\tvar _a23, _b, _c, _d;\n\t\t\tif (message == null) {\n\t\t\t\tlet messageId = this.pendingApprovalMessageId;\n\t\t\t\tif (messageId == null) {\n\t\t\t\t\tmessageId = (_a23 = this.lastMessage) == null ? void 0 : _a23.id;\n\t\t\t\t\tfor (let i = this.state.messages.length - 1; i >= 0; i--) {\n\t\t\t\t\t\tconst candidate = this.state.messages[i];\n\t\t\t\t\t\tif (candidate.role === \"assistant\" && candidate.parts.some((part) => isToolUIPart(part) && part.state === \"approval-responded\")) {\n\t\t\t\t\t\t\tmessageId = candidate.id;\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tconst pendingApprovalMessageIndex = messageId != null && messageId === this.pendingApprovalMessageId ? this.state.messages.findIndex((message2) => message2.id === messageId) : -1;\n\t\t\t\tawait this.makeRequestForToolApproval({\n\t\t\t\t\tmessageId,\n\t\t\t\t\tmessageIndex: pendingApprovalMessageIndex,\n\t\t\t\t\t...options\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tlet uiMessage;\n\t\t\tif (\"text\" in message || \"files\" in message) uiMessage = { parts: [...Array.isArray(message.files) ? message.files : await convertFileListToFileUIParts(message.files), ...\"text\" in message && message.text != null ? [{\n\t\t\t\ttype: \"text\",\n\t\t\t\ttext: message.text\n\t\t\t}] : []] };\n\t\t\telse uiMessage = message;\n\t\t\tif (message.messageId != null) {\n\t\t\t\tconst messageIndex = this.state.messages.findIndex((m) => m.id === message.messageId);\n\t\t\t\tif (messageIndex === -1) throw new Error(`message with id ${message.messageId} not found`);\n\t\t\t\tif (this.state.messages[messageIndex].role !== \"user\") throw new Error(`message with id ${message.messageId} is not a user message`);\n\t\t\t\tthis.state.messages = this.state.messages.slice(0, messageIndex + 1);\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...uiMessage,\n\t\t\t\t\tid: message.messageId,\n\t\t\t\t\trole: (_b = uiMessage.role) != null ? _b : \"user\",\n\t\t\t\t\tmetadata: message.metadata\n\t\t\t\t});\n\t\t\t} else this.state.pushMessage({\n\t\t\t\t...uiMessage,\n\t\t\t\tid: (_c = uiMessage.id) != null ? _c : this.generateId(),\n\t\t\t\trole: (_d = uiMessage.role) != null ? _d : \"user\",\n\t\t\t\tmetadata: message.metadata\n\t\t\t});\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: message.messageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Regenerate the assistant message with the provided message id.\n\t\t* If no message id is provided, the last assistant message will be regenerated.\n\t\t*/\n\t\tthis.regenerate = async ({ messageId, ...options } = {}) => {\n\t\t\tconst messageIndex = messageId == null ? this.state.messages.length - 1 : this.state.messages.findIndex((message) => message.id === messageId);\n\t\t\tif (messageIndex === -1) throw new Error(`message ${messageId} not found`);\n\t\t\tthis.state.messages = this.state.messages.slice(0, this.messages[messageIndex].role === \"assistant\" ? messageIndex : messageIndex + 1);\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"regenerate-message\",\n\t\t\t\tmessageId,\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Attempt to resume an ongoing streaming response.\n\t\t*/\n\t\tthis.resumeStream = async (options = {}) => {\n\t\t\tawait this.makeRequest({\n\t\t\t\ttrigger: \"resume-stream\",\n\t\t\t\t...options\n\t\t\t});\n\t\t};\n\t\t/**\n\t\t* Resume the stream if the latest response ended with a resumable network\n\t\t* disconnect. If a response is still active, wait for it to settle first so\n\t\t* disconnects reported shortly after the caller's trigger are handled.\n\t\t*\n\t\t* @internal\n\t\t*/\n\t\tthis[\"~resumeStreamIfDisconnected\"] = async ({ shouldResume = () => true } = {}) => {\n\t\t\tconst activeResponse = this.activeResponse;\n\t\t\tif (this.resumableStreamState == null && activeResponse != null) {\n\t\t\t\tawait activeResponse.completionPromise;\n\t\t\t\tif (this.resumableStreamState !== activeResponse.state) return;\n\t\t\t}\n\t\t\tif (this.resumableStreamState != null && shouldResume()) await this.resumeStream();\n\t\t};\n\t\t/**\n\t\t* Clear the error state and set the status to ready if the chat is in an error state.\n\t\t*/\n\t\tthis.clearError = () => {\n\t\t\tif (this.status === \"error\") {\n\t\t\t\tthis.state.error = void 0;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t}\n\t\t};\n\t\tthis.addToolApprovalResponse = async ({ id, approved, reason, options }) => this.jobExecutor.run(async () => {\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst updatePart = (part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id ? {\n\t\t\t\t...part,\n\t\t\t\tstate: \"approval-responded\",\n\t\t\t\tapproval: {\n\t\t\t\t\t...part.approval,\n\t\t\t\t\tid,\n\t\t\t\t\tapproved,\n\t\t\t\t\treason\n\t\t\t\t}\n\t\t\t} : part;\n\t\t\tconst messageIndex = messages.findIndex((message) => message.parts.some((part) => isToolUIPart(part) && part.state === \"approval-requested\" && part.approval.id === id));\n\t\t\tif (messageIndex !== -1) {\n\t\t\t\tconst message = messages[messageIndex];\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: message.parts.map(updatePart)\n\t\t\t\t});\n\t\t\t\tthis.pendingApprovalMessageId = message.id;\n\t\t\t}\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n\t\t\t\tconst shouldSend = await this.shouldSendAutomatically();\n\t\t\t\tif (shouldSend) this.runAutomaticRequest(() => {\n\t\t\t\t\tvar _a23;\n\t\t\t\t\tconst messageId = messageIndex === -1 ? (_a23 = this.lastMessage) == null ? void 0 : _a23.id : messages[messageIndex].id;\n\t\t\t\t\treturn this.makeRequestForToolApproval({\n\t\t\t\t\t\tmessageId,\n\t\t\t\t\t\tmessageIndex,\n\t\t\t\t\t\t...options\n\t\t\t\t\t});\n\t\t\t\t}, shouldSend);\n\t\t\t}\n\t\t});\n\t\tthis.addToolOutput = async ({ state = \"output-available\", toolCallId, output, errorText, options }) => this.jobExecutor.run(async () => {\n\t\t\tconst messages = this.state.messages;\n\t\t\tconst updatePart = (part) => isToolUIPart(part) && part.toolCallId === toolCallId ? {\n\t\t\t\t...part,\n\t\t\t\tstate,\n\t\t\t\toutput,\n\t\t\t\terrorText\n\t\t\t} : part;\n\t\t\tconst messageIndex = messages.findIndex((message) => message.parts.some((part) => isToolUIPart(part) && part.toolCallId === toolCallId));\n\t\t\tif (messageIndex !== -1) {\n\t\t\t\tconst message = messages[messageIndex];\n\t\t\t\tthis.state.replaceMessage(messageIndex, {\n\t\t\t\t\t...message,\n\t\t\t\t\tparts: message.parts.map(updatePart)\n\t\t\t\t});\n\t\t\t}\n\t\t\tif (this.activeResponse) this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);\n\t\t\tif (messageIndex !== -1 && this.status !== \"streaming\" && this.status !== \"submitted\" && this.sendAutomaticallyWhen) {\n\t\t\t\tconst shouldSend = await this.shouldSendAutomatically();\n\t\t\t\tif (shouldSend) this.runAutomaticRequest(() => this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: messages[messageIndex].id,\n\t\t\t\t\t...options\n\t\t\t\t}), shouldSend);\n\t\t\t}\n\t\t});\n\t\t/** @deprecated Use addToolOutput */\n\t\tthis.addToolResult = this.addToolOutput;\n\t\t/**\n\t\t* Abort the current request, keep the generated tokens if any, and wait for\n\t\t* the request pipeline to finish.\n\t\t*/\n\t\tthis.stop = async () => {\n\t\t\tthis.activeStopCount++;\n\t\t\tthis.stopGeneration++;\n\t\t\ttry {\n\t\t\t\tconst activeResumeRequest = this.activeResumeRequest;\n\t\t\t\tconst activeResponse = this.activeResponse;\n\t\t\t\tactiveResumeRequest?.abortController.abort();\n\t\t\t\tactiveResponse?.abortController.abort();\n\t\t\t\tawait Promise.all([activeResumeRequest == null ? void 0 : activeResumeRequest.completionPromise, activeResponse == null ? void 0 : activeResponse.completionPromise]);\n\t\t\t\tawait this.jobExecutor.waitForIdle();\n\t\t\t} finally {\n\t\t\t\tthis.activeStopCount--;\n\t\t\t}\n\t\t};\n\t\tthis.id = id;\n\t\tthis.transport = transport;\n\t\tthis.generateId = generateId2;\n\t\tthis.messageMetadataSchema = messageMetadataSchema;\n\t\tthis.dataPartSchemas = dataPartSchemas;\n\t\tthis.state = state;\n\t\tthis.onError = onError;\n\t\tthis.onToolCall = onToolCall;\n\t\tthis.onFinish = onFinish;\n\t\tthis.onData = onData;\n\t\tthis.sendAutomaticallyWhen = sendAutomaticallyWhen;\n\t}\n\t/**\n\t* Hook status:\n\t*\n\t* - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.\n\t* - `streaming`: The response is actively streaming in from the API, receiving chunks of data.\n\t* - `ready`: The full response has been received and processed; a new user message can be submitted.\n\t* - `error`: An error occurred during the API request, preventing successful completion.\n\t*/\n\tget status() {\n\t\treturn this.state.status;\n\t}\n\tsetStatus({ status, error }) {\n\t\tif (this.status === status) {\n\t\t\tif (this.error !== error) this.state.error = error;\n\t\t\treturn;\n\t\t}\n\t\tthis.state.status = status;\n\t\tthis.state.error = error;\n\t}\n\tget error() {\n\t\treturn this.state.error;\n\t}\n\tget messages() {\n\t\treturn this.state.messages;\n\t}\n\tget lastMessage() {\n\t\treturn this.state.messages[this.state.messages.length - 1];\n\t}\n\tset messages(messages) {\n\t\tthis.state.messages = messages;\n\t}\n\tasync shouldSendAutomatically() {\n\t\tif (!this.sendAutomaticallyWhen) return false;\n\t\tconst result = this.sendAutomaticallyWhen({ messages: this.state.messages });\n\t\tif (result && typeof result === \"object\" && \"then\" in result) return await result;\n\t\treturn result;\n\t}\n\tasync runAutomaticRequest(request, shouldSend) {\n\t\tconst stopGeneration = this.stopGeneration;\n\t\tconst startedWhileStopping = this.activeStopCount > 0;\n\t\tif (!(shouldSend != null ? shouldSend : await this.shouldSendAutomatically())) return;\n\t\tif (startedWhileStopping || stopGeneration !== this.stopGeneration || this.activeStopCount > 0) return;\n\t\tawait request();\n\t}\n\tasync makeRequestForToolApproval({ messageId, messageIndex, ...options }) {\n\t\tvar _a23, _b;\n\t\tconst consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;\n\t\tif (consumesPendingApproval) this.pendingApprovalMessageId = void 0;\n\t\tawait this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId,\n\t\t\t...options\n\t\t});\n\t\tif (consumesPendingApproval && this.status === \"error\" && this.pendingApprovalMessageId == null) this.pendingApprovalMessageId = (_b = (_a23 = this.state.messages[messageIndex]) == null ? void 0 : _a23.id) != null ? _b : messageId;\n\t}\n\tasync makeRequest(options) {\n\t\tconst completion = createResolvablePromise();\n\t\ttry {\n\t\t\tawait this.makeRequestImpl({\n\t\t\t\t...options,\n\t\t\t\tcompletionPromise: completion.promise\n\t\t\t});\n\t\t} finally {\n\t\t\tcompletion.resolve();\n\t\t}\n\t}\n\tasync makeRequestImpl({ trigger, metadata, headers, body, messageId, completionPromise }) {\n\t\tvar _a23, _b;\n\t\tif (trigger !== \"resume-stream\") this.resumableStreamState = void 0;\n\t\tconst abortController = new AbortController();\n\t\tconst activeResumeRequest = trigger === \"resume-stream\" ? {\n\t\t\tabortController,\n\t\t\tcompletionPromise\n\t\t} : void 0;\n\t\tif (activeResumeRequest) {\n\t\t\t(_a23 = this.activeResumeRequest) == null || _a23.abortController.abort();\n\t\t\tthis.activeResumeRequest = activeResumeRequest;\n\t\t}\n\t\tconst isCurrentRequest = () => activeResumeRequest == null || this.activeResumeRequest === activeResumeRequest;\n\t\tconst clearActiveResumeRequest = () => {\n\t\t\tif (this.activeResumeRequest === activeResumeRequest) this.activeResumeRequest = void 0;\n\t\t};\n\t\tlet resumeStream;\n\t\tif (trigger === \"resume-stream\") try {\n\t\t\tconst reconnect = await this.transport.reconnectToStream({\n\t\t\t\tchatId: this.id,\n\t\t\t\tabortSignal: abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody\n\t\t\t});\n\t\t\tif (abortController.signal.aborted || !isCurrentRequest()) {\n\t\t\t\tawait (reconnect == null ? void 0 : reconnect.cancel().catch(() => {}));\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (reconnect == null) {\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tresumeStream = reconnect;\n\t\t} catch (err) {\n\t\t\tif (abortController.signal.aborted || err.name === \"AbortError\") {\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tthis.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!isCurrentRequest()) return;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t\tclearActiveResumeRequest();\n\t\t\treturn;\n\t\t}\n\t\tthis.setStatus({\n\t\t\tstatus: \"submitted\",\n\t\t\terror: void 0\n\t\t});\n\t\tconst lastMessage = this.lastMessage;\n\t\tconst responseMessageIndex = trigger === \"submit-message\" && messageId != null ? this.state.messages.findIndex((message) => message.id === messageId) : this.state.messages.length - 1;\n\t\tconst responseMessage = responseMessageIndex === -1 ? lastMessage : this.state.messages[responseMessageIndex];\n\t\tconst originalResponseMessageId = responseMessage == null ? void 0 : responseMessage.id;\n\t\tconst resumableResponseMessage = trigger === \"resume-stream\" && (responseMessage == null ? void 0 : responseMessage.role) === \"assistant\" && responseMessage.parts.some((part) => isToolUIPart(part) && part.state === \"input-streaming\") ? this.state.snapshot(responseMessage) : void 0;\n\t\tconst usesEarlierAssistantMessage = responseMessageIndex !== -1 && responseMessageIndex < this.state.messages.length - 1 && (responseMessage == null ? void 0 : responseMessage.role) === \"assistant\";\n\t\tlet isAbort = false;\n\t\tlet isDisconnect = false;\n\t\tlet isError = false;\n\t\tlet activeResponse;\n\t\ttry {\n\t\t\tconst response = {\n\t\t\t\tstate: trigger === \"resume-stream\" && this.resumableStreamState != null ? this.resumableStreamState : createStreamingUIMessageState({\n\t\t\t\t\tlastMessage: trigger === \"resume-stream\" ? resumableResponseMessage : trigger === \"regenerate-message\" ? void 0 : this.state.snapshot(responseMessage),\n\t\t\t\t\tmessageId: this.generateId()\n\t\t\t\t}),\n\t\t\t\tabortController,\n\t\t\t\tcompletionPromise\n\t\t\t};\n\t\t\tactiveResponse = response;\n\t\t\tresponse.abortController.signal.addEventListener(\"abort\", () => {\n\t\t\t\tisAbort = true;\n\t\t\t});\n\t\t\tthis.activeResponse = response;\n\t\t\tlet stream;\n\t\t\tif (trigger === \"resume-stream\") stream = resumeStream;\n\t\t\telse stream = await this.transport.sendMessages({\n\t\t\t\tchatId: this.id,\n\t\t\t\tmessages: this.state.messages,\n\t\t\t\tabortSignal: response.abortController.signal,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody,\n\t\t\t\ttrigger,\n\t\t\t\tmessageId\n\t\t\t});\n\t\t\tconst runUpdateMessageJob = (job) => this.jobExecutor.run(() => {\n\t\t\t\tif (response.abortController.signal.aborted) return Promise.resolve();\n\t\t\t\treturn job({\n\t\t\t\t\tstate: response.state,\n\t\t\t\t\twrite: ({ updateStatus = true } = {}) => {\n\t\t\t\t\t\tif (response.abortController.signal.aborted) return;\n\t\t\t\t\t\tif (updateStatus) this.setStatus({ status: \"streaming\" });\n\t\t\t\t\t\tconst existingMessageIndex = this.state.messages.findLastIndex((message) => message.id === response.state.message.id);\n\t\t\t\t\t\tif (existingMessageIndex !== -1) this.state.replaceMessage(existingMessageIndex, response.state.message);\n\t\t\t\t\t\telse if (usesEarlierAssistantMessage) {\n\t\t\t\t\t\t\tconst originalMessageIndex = this.state.messages.findLastIndex((message) => message.id === originalResponseMessageId);\n\t\t\t\t\t\t\tif (originalMessageIndex !== -1) this.state.replaceMessage(originalMessageIndex, response.state.message);\n\t\t\t\t\t\t\telse this.state.pushMessage(response.state.message);\n\t\t\t\t\t\t} else this.state.pushMessage(response.state.message);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t});\n\t\t\tawait consumeStream({\n\t\t\t\tstream: processUIMessageStream({\n\t\t\t\t\tstream,\n\t\t\t\t\tresetStateOnMessageIdChange: trigger === \"resume-stream\",\n\t\t\t\t\tresetStateOnFirstMessageStart: trigger === \"resume-stream\" && this.transport.resumeStreamIsReplay,\n\t\t\t\t\tonToolCall: this.onToolCall,\n\t\t\t\t\tonData: this.onData,\n\t\t\t\t\tmessageMetadataSchema: this.messageMetadataSchema,\n\t\t\t\t\tdataPartSchemas: this.dataPartSchemas,\n\t\t\t\t\trunUpdateMessageJob,\n\t\t\t\t\tonError: (error) => {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t\tabortSignal: response.abortController.signal,\n\t\t\t\tonError: (error) => {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\tif (isAbort) {\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tif (this.resumableStreamState === response.state) this.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (isCurrentRequest()) {\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\tif (this.resumableStreamState === response.state) this.resumableStreamState = void 0;\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (isAbort || err.name === \"AbortError\") {\n\t\t\t\tisAbort = true;\n\t\t\t\tif (isCurrentRequest()) {\n\t\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\t\tif (this.resumableStreamState === (activeResponse == null ? void 0 : activeResponse.state)) this.resumableStreamState = void 0;\n\t\t\t\t}\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\tif (!isCurrentRequest()) return null;\n\t\t\tisError = true;\n\t\t\tif (err instanceof TypeError && (err.message.toLowerCase().includes(\"fetch\") || err.message.toLowerCase().includes(\"network\"))) isDisconnect = true;\n\t\t\tif (isDisconnect) this.resumableStreamState = activeResponse == null ? void 0 : activeResponse.state;\n\t\t\telse if (this.resumableStreamState === (activeResponse == null ? void 0 : activeResponse.state)) this.resumableStreamState = void 0;\n\t\t\tif (this.onError && err instanceof Error) this.onError(err);\n\t\t\tthis.setStatus({\n\t\t\t\tstatus: \"error\",\n\t\t\t\terror: err\n\t\t\t});\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tif (activeResponse) (_b = this.onFinish) == null || _b.call(this, {\n\t\t\t\t\tmessage: activeResponse.state.message,\n\t\t\t\t\tmessages: this.state.messages,\n\t\t\t\t\tisAbort,\n\t\t\t\t\tisDisconnect,\n\t\t\t\t\tisError,\n\t\t\t\t\tfinishReason: activeResponse.state.finishReason\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tif (this.activeResponse === activeResponse) this.activeResponse = void 0;\n\t\t\t\tclearActiveResumeRequest();\n\t\t\t}\n\t\t}\n\t\tif (!isAbort && !isError) await this.runAutomaticRequest(() => {\n\t\t\tvar _a24;\n\t\t\treturn this.makeRequest({\n\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\tmessageId: (_a24 = this.lastMessage) == null ? void 0 : _a24.id,\n\t\t\t\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody\n\t\t\t});\n\t\t});\n\t}\n};\nvar DirectChatTransport = class {\n\tconstructor({ agent, options, ...uiMessageStreamOptions }) {\n\t\tthis.agent = agent;\n\t\tthis.agentOptions = options;\n\t\tthis.uiMessageStreamOptions = uiMessageStreamOptions;\n\t}\n\tasync sendMessages({ messages, abortSignal }) {\n\t\tconst modelMessages = await convertToModelMessages(await validateUIMessagesForAgent({\n\t\t\tmessages,\n\t\t\ttools: this.agent.tools\n\t\t}), { tools: this.agent.tools });\n\t\treturn (await this.agent.stream({\n\t\t\tprompt: modelMessages,\n\t\t\tabortSignal,\n\t\t\t...this.agentOptions !== void 0 ? { options: this.agentOptions } : {}\n\t\t})).toUIMessageStream(this.uiMessageStreamOptions);\n\t}\n\t/**\n\t* Direct transport does not support reconnection since there is no\n\t* persistent server-side stream to reconnect to.\n\t*\n\t* @returns Always returns `null`\n\t*/\n\tasync reconnectToStream(_options) {\n\t\treturn null;\n\t}\n};\nfunction lastAssistantMessageIsCompleteWithApprovalResponses({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart);\n\treturn lastStepToolInvocations.filter((part) => part.state === \"approval-responded\").length > 0 && lastStepToolInvocations.every((part) => part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\" || part.state === \"output-denied\" || part.state === \"approval-responded\");\n}\nfunction lastAssistantMessageIsCompleteWithToolCalls({ messages }) {\n\tconst message = messages[messages.length - 1];\n\tif (!message) return false;\n\tif (message.role !== \"assistant\") return false;\n\tconst lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {\n\t\treturn part.type === \"step-start\" ? index : lastIndex;\n\t}, -1);\n\tconst lastStepParts = message.parts.slice(lastStepStartIndex + 1);\n\tconst lastStepToolInvocations = lastStepParts.filter(isToolUIPart).filter((part) => !part.providerExecuted);\n\tconst lastToolInvocationIndex = lastStepParts.reduce((lastIndex, part, index) => isToolUIPart(part) && !part.providerExecuted ? index : lastIndex, -1);\n\treturn lastStepToolInvocations.length > 0 && !lastStepParts.slice(lastToolInvocationIndex + 1).some((part) => part.type === \"text\" && part.state !== \"done\") && lastStepToolInvocations.every((part) => part.state === \"output-available\" && part.preliminary !== true || part.state === \"output-error\");\n}\nfunction transformTextToUiMessageStream({ stream }) {\n\treturn stream.pipeThrough(new TransformStream({\n\t\tstart(controller) {\n\t\t\tcontroller.enqueue({ type: \"start\" });\n\t\t\tcontroller.enqueue({ type: \"start-step\" });\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-start\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t},\n\t\tasync transform(part, controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-delta\",\n\t\t\t\tid: \"text-1\",\n\t\t\t\tdelta: part\n\t\t\t});\n\t\t},\n\t\tasync flush(controller) {\n\t\t\tcontroller.enqueue({\n\t\t\t\ttype: \"text-end\",\n\t\t\t\tid: \"text-1\"\n\t\t\t});\n\t\t\tcontroller.enqueue({ type: \"finish-step\" });\n\t\t\tcontroller.enqueue({ type: \"finish\" });\n\t\t}\n\t}));\n}\nvar TextStreamChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\n\t}\n\tprocessResponseStream(stream) {\n\t\treturn transformTextToUiMessageStream({ stream: stream.pipeThrough(new TextDecoderStream()) });\n\t}\n};\nexport { AISDKError, APICallError, AbstractChat, DefaultChatTransport, DefaultGeneratedFile, DirectChatTransport, DownloadError, EmptyResponseBodyError, ToolLoopAgent as Experimental_Agent, ToolLoopAgent, HttpChatTransport, InvalidArgumentError, InvalidDataContentError, InvalidMessageRoleError, InvalidPromptError, InvalidResponseDataError, InvalidStreamPartError, InvalidToolApprovalError, InvalidToolApprovalSignatureError, InvalidToolInputError, JSONParseError, JsonToSseTransformStream, LoadAPIKeyError, LoadSettingError, MessageConversionError, MissingToolResultsError, NoContentGeneratedError, NoImageGeneratedError, NoObjectGeneratedError, NoOutputGeneratedError, NoSpeechGeneratedError, NoSuchModelError, NoSuchProviderError, NoSuchToolError, NoTranscriptGeneratedError, NoVideoGeneratedError, output_exports as Output, RetryError, SerialJobExecutor, TextStreamChatTransport, TooManyEmbeddingValuesForCallError, ToolCallNotFoundForApprovalError, ToolCallRepairError, ToolChoiceViolationError, TypeValidationError, UIMessageStreamError, UI_MESSAGE_STREAM_HEADERS, UnsupportedFunctionalityError, UnsupportedModelVersionError, addToolInputExamplesMiddleware, asSchema, assistantModelMessageSchema, bindTelemetryIntegration, callCompletionApi, consumeStream, convertFileListToFileUIParts, convertToModelMessages, cosineSimilarity, createAgentUIStream, createAgentUIStreamResponse, createDownload, createGatewayProvider as createGateway, createIdGenerator, createProviderRegistry, createTextStreamResponse, createUIMessageStream, createUIMessageStreamResponse, customProvider, defaultEmbeddingSettingsMiddleware, defaultSettingsMiddleware, dynamicTool, embed, embedMany, experimental_createProviderRegistry, experimental_customProvider, experimental_generateImage, generateSpeech as experimental_generateSpeech, experimental_generateVideo, transcribe as experimental_transcribe, extractJsonMiddleware, extractReasoningMiddleware, gateway, generateId, generateImage, generateObject, generateText, getStaticToolName, getTextFromDataUrl, getToolName, getToolOrDynamicToolName, hasToolCall, isDataUIPart, isDeepEqualData, isDynamicToolUIPart, isFileUIPart, isLoopFinished, isReasoningUIPart, isStaticToolUIPart, isTextUIPart, isToolOrDynamicToolUIPart, isToolUIPart, jsonSchema, lastAssistantMessageIsCompleteWithApprovalResponses, lastAssistantMessageIsCompleteWithToolCalls, modelMessageSchema, parseJsonEventStream, parsePartialJson, pipeAgentUIStreamToResponse, pipeTextStreamToResponse, pipeUIMessageStreamToResponse, pruneMessages, readUIMessageStream, registerTelemetryIntegration, rerank, safeValidateUIMessages, simulateReadableStream, simulateStreamingMiddleware, smoothStream, stepCountIs, streamObject, streamText, systemModelMessageSchema, tool, toolModelMessageSchema, uiMessageChunkSchema, userModelMessageSchema, validateUIMessages, wrapEmbeddingModel, wrapImageModel, wrapLanguageModel, wrapProvider, zodSchema };\n\n//# sourceMappingURL=index.js.map","import * as AIV5 from '@internal/ai-sdk-v5';\n\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../../error';\nimport { getTransformedToolPayload, hasTransformedToolPayload } from '../../../tools/payload-transform';\nimport type { ImageContent } from '../prompt/image-utils';\nimport {\n categorizeFileData,\n createDataUri,\n imageContentToString,\n isAbsoluteUrl,\n isBase64DataUri,\n isBase64Like,\n parseDataUri,\n resolveFilePartMediaTypeAndData,\n toBase64DataUri,\n} from '../prompt/image-utils';\nimport type {\n MastraDBMessage,\n MastraMessageContentV2,\n MastraMessagePart,\n MastraToolInvocationPart,\n MessageSource,\n} from '../state/types';\nimport type { AIV5Type } from '../types';\nimport { findToolCallArgs } from '../utils/provider-compat';\nimport { preserveResponseItemIdsOnMerge } from '../utils/response-item-metadata';\nimport { sanitizeToolName } from '../utils/tool-name';\nimport { normalizeToolOutput, unwrapLegacyToolOutput } from '../utils/unwrap-legacy-tool-output';\n\n/**\n * Compact malformed entries and filter out empty text parts from message parts arrays.\n * Empty text blocks are not allowed by Anthropic's API and cause request failures.\n * This can happen during streaming when text-start/text-end events occur without actual content.\n * However, if the only part is an empty text part, it is preserved as a legitimate placeholder\n * (e.g. empty assistant messages between tool results and user messages).\n */\nfunction compactMessageParts(parts: unknown): MastraMessagePart[] {\n if (!Array.isArray(parts)) return [];\n return parts.filter((part): part is MastraMessagePart => part !== null && typeof part === 'object');\n}\n\nfunction filterEmptyTextParts(parts: unknown): MastraMessagePart[] {\n const compactedParts = compactMessageParts(parts);\n const hasNonEmptyParts = compactedParts.some(part => !(part.type === 'text' && part.text === ''));\n if (!hasNonEmptyParts) return compactedParts;\n return compactedParts.filter(part => {\n if (part.type === 'text') {\n return part.text !== '';\n }\n return true;\n });\n}\n\nfunction getSignalType(message: MastraDBMessage): string | undefined {\n const signal = message.content.metadata?.signal;\n if (signal && typeof signal === 'object' && !Array.isArray(signal)) {\n const type = (signal as Record<string, unknown>).type;\n return typeof type === 'string' ? type : message.type;\n }\n\n return message.type;\n}\n\nfunction getSignalTagName(message: MastraDBMessage): string | undefined {\n const signal = message.content.metadata?.signal;\n if (signal && typeof signal === 'object' && !Array.isArray(signal)) {\n const tagName = (signal as Record<string, unknown>).tagName;\n if (typeof tagName === 'string') return tagName;\n }\n\n const type = getSignalType(message);\n if (type === 'user') return 'user';\n if (type === 'reactive') return message.type;\n return type;\n}\n\nfunction isUserSignalType(type: string | undefined): boolean {\n return type === 'user' || type === 'user-message';\n}\n\nfunction getTextContent(message: MastraDBMessage): string {\n return typeof message.content.content === 'string'\n ? message.content.content\n : (compactMessageParts(message.content.parts).find(part => part.type === 'text')?.text ?? '');\n}\n\nfunction toSignalDataPart(message: MastraDBMessage): AIV5Type.DataUIPart<AIV5.UIDataTypes> {\n const signal =\n message.content.metadata?.signal && typeof message.content.metadata.signal === 'object'\n ? (message.content.metadata.signal as Record<string, unknown>)\n : {};\n const metadata =\n signal.metadata && typeof signal.metadata === 'object' && !Array.isArray(signal.metadata)\n ? (signal.metadata as Record<string, unknown>)\n : {};\n const attributes =\n signal.attributes && typeof signal.attributes === 'object' && !Array.isArray(signal.attributes)\n ? (signal.attributes as Record<string, unknown>)\n : {};\n\n const type = getSignalType(message) ?? 'signal';\n const tagName = getSignalTagName(message) ?? type;\n return {\n type: type === 'user' ? 'data-user-message' : 'data-signal',\n data: {\n id: typeof signal.id === 'string' ? signal.id : message.id,\n type,\n tagName,\n contents: 'contents' in signal ? signal.contents : getTextContent(message),\n createdAt: typeof signal.createdAt === 'string' ? signal.createdAt : message.createdAt.toISOString(),\n ...(typeof signal.acceptedAt === 'string' ? { acceptedAt: signal.acceptedAt } : {}),\n ...(Object.keys(attributes).length ? { attributes } : {}),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n },\n } as AIV5Type.DataUIPart<AIV5.UIDataTypes>;\n}\n\n/**\n * Extract tool name from AI SDK v5 tool type string\n *\n * V5 format: \"tool-${toolName}\" or \"dynamic-tool\"\n * V4 format: \"tool-invocation\"\n *\n * @param type - The tool type string from AI SDK v5\n * @returns The tool name or 'dynamic-tool' if it's a dynamic tool\n */\nfunction getToolName(type: string | { type: string }): string {\n // Handle objects with type property\n if (typeof type === 'object' && type && 'type' in type) {\n type = type.type;\n }\n\n // Ensure type is a string\n if (typeof type !== 'string') {\n return sanitizeToolName(type);\n }\n\n if (type === 'dynamic-tool') {\n return 'dynamic-tool';\n }\n\n // Extract tool name from \"tool-${toolName}\" format\n if (type.startsWith('tool-')) {\n return sanitizeToolName(type.slice('tool-'.length)); // Remove \"tool-\" prefix\n }\n\n // Fallback for unexpected formats\n return sanitizeToolName(type);\n}\n\nfunction mergeMastraCreatedAt(metadata: AIV5Type.ProviderMetadata | undefined, createdAt?: number) {\n if (createdAt == null) {\n return metadata;\n }\n\n return {\n ...(metadata || {}),\n mastra: {\n ...(((metadata || {}).mastra as Record<string, unknown> | undefined) || {}),\n createdAt,\n },\n } satisfies AIV5Type.ProviderMetadata;\n}\n\nfunction getMastraCreatedAt(providerMetadata?: AIV5Type.ProviderMetadata): number | undefined {\n const value = providerMetadata?.mastra;\n if (!value || typeof value !== 'object') {\n return undefined;\n }\n\n const createdAt = (value as Record<string, unknown>).createdAt;\n return typeof createdAt === 'number' ? createdAt : undefined;\n}\n\nfunction getDisplayTransform(\n providerMetadata: unknown,\n phase: 'input-available' | 'output-available' | 'error' | 'approval' | 'suspend',\n fallback: unknown,\n enabled = true,\n) {\n if (!enabled) {\n return fallback;\n }\n const transform = getTransformedToolPayload(providerMetadata, 'display', phase);\n return hasTransformedToolPayload(transform) ? transform.transformed : fallback;\n}\n\nfunction transformToolStateDataForDisplay(data: unknown, phase: 'approval' | 'suspend', enabled = true): unknown {\n if (!enabled) {\n return data;\n }\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const stateData = data as Record<string, unknown>;\n const metadata = stateData.metadata ?? stateData.providerMetadata;\n const argsTransform = getTransformedToolPayload(metadata, 'display', phase);\n const inputTransform = getTransformedToolPayload(metadata, 'display', 'input-available');\n const transformedArgs =\n phase === 'approval'\n ? hasTransformedToolPayload(argsTransform)\n ? argsTransform.transformed\n : hasTransformedToolPayload(inputTransform)\n ? inputTransform.transformed\n : undefined\n : hasTransformedToolPayload(inputTransform)\n ? inputTransform.transformed\n : hasTransformedToolPayload(argsTransform)\n ? argsTransform.transformed\n : undefined;\n const transformedSuspendPayload =\n phase === 'suspend' && hasTransformedToolPayload(argsTransform) ? argsTransform.transformed : undefined;\n\n return {\n ...stateData,\n ...(transformedArgs !== undefined ? { args: transformedArgs } : {}),\n ...(transformedSuspendPayload !== undefined ? { suspendPayload: transformedSuspendPayload } : {}),\n };\n}\n\nexport interface AIV5AdapterContext {\n memoryInfo: { threadId?: string; resourceId?: string } | null;\n newMessageId?(): string;\n generateCreatedAt?(messageSource: MessageSource, start?: unknown): Date;\n}\n\n/**\n * AIV5Adapter - Handles conversions between MastraDBMessage and AI SDK V5 formats\n *\n * This adapter centralizes all AI SDK V5 (UIMessage and ModelMessage) conversion logic.\n */\nexport class AIV5Adapter {\n /**\n * Direct conversion from MastraDBMessage to AIV5 UIMessage\n */\n static toUIMessage(dbMsg: MastraDBMessage, options?: { transformToolPayloads?: boolean }): AIV5Type.UIMessage {\n const signalType = dbMsg.role === 'signal' ? getSignalType(dbMsg) : undefined;\n const isUserMessageSignal = isUserSignalType(signalType);\n const transformToolPayloads = options?.transformToolPayloads ?? true;\n const parts: AIV5Type.UIMessage['parts'] = [];\n const metadata: Record<string, unknown> = { ...(dbMsg.content.metadata || {}) };\n\n if (dbMsg.role === 'signal' && !isUserMessageSignal) {\n parts.push(toSignalDataPart(dbMsg));\n }\n\n // Add Mastra-specific metadata\n if (dbMsg.createdAt) metadata.createdAt = dbMsg.createdAt;\n if (dbMsg.threadId) metadata.threadId = dbMsg.threadId;\n if (dbMsg.resourceId) metadata.resourceId = dbMsg.resourceId;\n\n // Preserve message-level providerMetadata in metadata so it survives UI → Model conversion\n if (dbMsg.content.providerMetadata) {\n metadata.providerMetadata = dbMsg.content.providerMetadata;\n }\n\n if (dbMsg.role === 'signal' && !isUserMessageSignal) {\n return {\n id: dbMsg.id,\n role: 'system',\n metadata,\n parts,\n };\n }\n\n const contentParts = compactMessageParts(dbMsg.content.parts);\n\n // 1. Handle tool invocations (only if not already in parts array)\n const hasToolInvocationParts = contentParts.some(p => p.type === 'tool-invocation');\n if (dbMsg.content.toolInvocations && !hasToolInvocationParts) {\n for (const invocation of dbMsg.content.toolInvocations) {\n if (invocation.state === 'result') {\n parts.push({\n type: `tool-${invocation.toolName}`,\n toolCallId: invocation.toolCallId,\n state: 'output-available',\n input: invocation.args,\n output: invocation.result,\n });\n } else {\n parts.push({\n type: `tool-${invocation.toolName}`,\n toolCallId: invocation.toolCallId,\n state: invocation.state === 'call' ? 'input-available' : 'input-streaming',\n input: invocation.args,\n });\n }\n }\n }\n\n // 2. Check if we have parts with providerMetadata first\n const hasReasoningInParts = contentParts.some(p => p.type === 'reasoning');\n const hasFileInParts = contentParts.some(p => p.type === 'file');\n\n // 3. Handle reasoning (AIV4 reasoning is a string) - only if not in parts\n if (dbMsg.content.reasoning && !hasReasoningInParts) {\n parts.push({\n type: 'reasoning',\n text: dbMsg.content.reasoning,\n });\n }\n\n // 4. Handle files (experimental_attachments) - only if not in parts\n const attachmentUrls = new Set<string>();\n if (dbMsg.content.experimental_attachments && !hasFileInParts) {\n for (const attachment of dbMsg.content.experimental_attachments) {\n attachmentUrls.add(attachment.url);\n parts.push({\n type: 'file',\n url: attachment.url,\n mediaType: attachment.contentType || 'unknown',\n });\n }\n }\n\n // 5. Handle parts directly (if present in V2)\n let hasNonToolReasoningParts = false;\n if (contentParts.length > 0) {\n for (const part of contentParts) {\n // Handle tool-invocation parts\n if (part.type === 'tool-invocation' && part.toolInvocation) {\n const inv = part.toolInvocation;\n\n if (inv.state === 'result') {\n parts.push({\n type: `tool-${inv.toolName}`,\n toolCallId: inv.toolCallId,\n input: getDisplayTransform(part.providerMetadata, 'input-available', inv.args, transformToolPayloads),\n output: getDisplayTransform(\n part.providerMetadata,\n 'output-available',\n getDisplayTransform(part.providerMetadata, 'error', inv.result, transformToolPayloads),\n transformToolPayloads,\n ),\n state: 'output-available',\n callProviderMetadata: mergeMastraCreatedAt(part.providerMetadata, part.createdAt),\n providerExecuted: (part as { providerExecuted?: boolean }).providerExecuted,\n } satisfies AIV5Type.ToolUIPart);\n } else if (inv.state === 'output-error') {\n parts.push({\n type: `tool-${inv.toolName}`,\n toolCallId: inv.toolCallId,\n input: getDisplayTransform(part.providerMetadata, 'input-available', inv.args, transformToolPayloads),\n errorText: getDisplayTransform(\n part.providerMetadata,\n 'error',\n inv.errorText || '',\n transformToolPayloads,\n ) as string,\n state: 'output-error',\n callProviderMetadata: mergeMastraCreatedAt(part.providerMetadata, part.createdAt),\n providerExecuted: (part as { providerExecuted?: boolean }).providerExecuted,\n } satisfies AIV5Type.ToolUIPart);\n } else if (inv.state === 'output-denied') {\n // v5 has no denied state. Downgrade to a single output-available part whose output is\n // the denial reason, so v5 UI consumers — and the next LLM turn's prompt, which is\n // built through this adapter — see a tool result instead of a dangling tool call.\n parts.push({\n type: `tool-${inv.toolName}`,\n toolCallId: inv.toolCallId,\n input: getDisplayTransform(part.providerMetadata, 'input-available', inv.args, transformToolPayloads),\n output: inv.approval?.reason ?? 'Tool call was not approved by the user',\n state: 'output-available',\n callProviderMetadata: mergeMastraCreatedAt(part.providerMetadata, part.createdAt),\n providerExecuted: (part as { providerExecuted?: boolean }).providerExecuted,\n } satisfies AIV5Type.ToolUIPart);\n } else {\n parts.push({\n type: `tool-${inv.toolName}`,\n toolCallId: inv.toolCallId,\n input: getDisplayTransform(part.providerMetadata, 'input-available', inv.args, transformToolPayloads),\n state: 'input-available',\n callProviderMetadata: mergeMastraCreatedAt(part.providerMetadata, part.createdAt),\n providerExecuted: (part as { providerExecuted?: boolean }).providerExecuted,\n } satisfies AIV5Type.ToolUIPart);\n }\n continue;\n }\n\n // Handle reasoning parts\n if (part.type === 'reasoning') {\n const text =\n part.reasoning ||\n (part.details?.reduce((p: string, c) => {\n if (c.type === `text` && c.text) return p + c.text;\n return p;\n }, '') ??\n '');\n if (text || part.details?.length) {\n const v5UIPart: AIV5Type.ReasoningUIPart = {\n type: 'reasoning' as const,\n text: text || '',\n state: 'done' as const,\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n parts.push(v5UIPart);\n }\n continue;\n }\n\n // Skip tool-invocation parts without toolInvocation object and other tool- parts\n if (part.type === 'tool-invocation' || part.type.startsWith('tool-')) {\n continue;\n }\n\n // Convert file parts from V2 format (data) to AIV5 format (url)\n if (part.type === 'file') {\n // v5-shaped file parts (`mediaType`/`url`) can reach this v2→v5 path; resolve both\n // shapes so the media type survives (instead of the image/png default) and the\n // payload is read from `url` when v5-shaped. Mirrors #17366.\n const { mediaType: fileMimeType, data: fileData } = resolveFilePartMediaTypeAndData(part);\n const filename = (part as { filename?: string }).filename;\n\n // Skip file parts that came from experimental_attachments to avoid duplicates\n if (typeof fileData === 'string' && attachmentUrls.has(fileData)) {\n continue;\n }\n\n const categorized =\n typeof fileData === 'string'\n ? categorizeFileData(fileData, fileMimeType)\n : { type: 'raw' as const, mimeType: fileMimeType, data: fileData };\n\n // Provider file IDs (e.g. OpenAI \"file-...\") ride the url branch untouched so\n // @ai-sdk/openai can forward them as { file_id: \"file-...\" } to the API. So do raw\n // strings that aren't base64 (relative paths), instead of becoming undecodable data URLs.\n if (\n typeof fileData === 'string' &&\n (categorized.type === 'url' ||\n categorized.type === 'providerFileId' ||\n (categorized.type === 'raw' && !isBase64Like(fileData)))\n ) {\n const v5UIPart: AIV5Type.FileUIPart = {\n type: 'file' as const,\n url: fileData,\n mediaType: categorized.mimeType || 'image/png',\n ...(filename ? { filename } : {}),\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n parts.push(v5UIPart);\n } else {\n let filePartData: string;\n let extractedMimeType = fileMimeType;\n\n if (typeof fileData === 'string') {\n const parsed = parseDataUri(fileData);\n\n if (parsed.isDataUri && !isBase64DataUri(fileData)) {\n // Percent-encoded data URLs (`data:image/svg+xml,%3Csvg...`) are converted to\n // base64 rather than having their payload re-wrapped as if it already were.\n filePartData = toBase64DataUri(fileData) ?? fileData;\n } else if (parsed.isDataUri) {\n filePartData = parsed.base64Content;\n if (parsed.mimeType) {\n extractedMimeType = extractedMimeType || parsed.mimeType;\n }\n } else {\n filePartData = fileData;\n }\n } else {\n // Non-string payload (defensive: stored file parts carry string data/url):\n // coerce so `filePartData` stays typed `string`.\n filePartData = imageContentToString(fileData as ImageContent, extractedMimeType);\n }\n\n const finalMimeType = extractedMimeType || 'image/png';\n\n let dataUri: string;\n if (typeof filePartData === 'string' && filePartData.startsWith('data:')) {\n dataUri = filePartData;\n } else {\n dataUri = createDataUri(filePartData, finalMimeType);\n }\n\n const v5UIPart: AIV5Type.FileUIPart = {\n type: 'file' as const,\n url: dataUri,\n mediaType: finalMimeType,\n ...(filename ? { filename } : {}),\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n parts.push(v5UIPart);\n }\n } else if (part.type === 'source') {\n const v5UIPart: AIV5Type.SourceUrlUIPart = {\n type: 'source-url' as const,\n url: part.source.url,\n sourceId: part.source.id,\n title: part.source.title,\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n\n parts.push(v5UIPart);\n } else if (part.type === 'source-document') {\n const v5UIPart: AIV5Type.SourceDocumentUIPart = {\n type: 'source-document' as const,\n sourceId: part.sourceId,\n mediaType: part.mediaType,\n title: part.title,\n ...(part.filename ? { filename: part.filename } : {}),\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n parts.push(v5UIPart);\n } else if (part.type === 'text') {\n const v5UIPart: AIV5Type.TextUIPart = {\n type: 'text' as const,\n text: part.text,\n };\n v5UIPart.providerMetadata = mergeMastraCreatedAt(part.providerMetadata, part.createdAt);\n parts.push(v5UIPart);\n hasNonToolReasoningParts = true;\n } else if (part.type === 'data-tool-call-suspended' || part.type === 'data-tool-call-approval') {\n parts.push({\n ...part,\n data: transformToolStateDataForDisplay(\n part.data,\n part.type === 'data-tool-call-suspended' ? 'suspend' : 'approval',\n transformToolPayloads,\n ),\n });\n } else if (part.type === 'error') {\n // Mastra-only record of a terminal failure. Preserved for DB/UI history\n // (see sanitizeV5UIMessages, which strips it from provider prompts).\n parts.push(part as unknown as AIV5Type.UIMessage['parts'][number]);\n hasNonToolReasoningParts = true;\n } else {\n // Other parts (step-start, etc.) can be pushed as-is\n parts.push(part);\n hasNonToolReasoningParts = true;\n }\n }\n }\n\n // 6. Handle text content (fallback if no parts)\n if (dbMsg.content.content && !hasNonToolReasoningParts) {\n parts.push({ type: 'text', text: dbMsg.content.content });\n }\n\n const existingToolStateDataPartIds = new Set(\n parts\n .filter(\n (part): part is AIV5Type.DataUIPart<AIV5.UIDataTypes> =>\n part.type === 'data-tool-call-suspended' || part.type === 'data-tool-call-approval',\n )\n .map(part => {\n const data = part.data as Record<string, unknown> | undefined;\n return typeof data?.toolCallId === 'string' ? data.toolCallId : undefined;\n })\n .filter((toolCallId): toolCallId is string => typeof toolCallId === 'string'),\n );\n\n const insertToolStateDataPart = (toolCallId: string, toolStateDataPart: AIV5Type.DataUIPart<AIV5.UIDataTypes>) => {\n const toolPartIndex = parts.findIndex(\n part => part.type.startsWith('tool-') && (part as { toolCallId?: unknown }).toolCallId === toolCallId,\n );\n\n if (toolPartIndex === -1) {\n parts.push(toolStateDataPart);\n return;\n }\n\n parts.splice(toolPartIndex + 1, 0, toolStateDataPart);\n };\n\n const suspendedTools = metadata.suspendedTools;\n if (suspendedTools && typeof suspendedTools === 'object') {\n for (const suspendedTool of Object.values(suspendedTools)) {\n if (!suspendedTool || typeof suspendedTool !== 'object') {\n continue;\n }\n\n const toolCallId = 'toolCallId' in suspendedTool ? suspendedTool.toolCallId : undefined;\n if (typeof toolCallId !== 'string' || existingToolStateDataPartIds.has(toolCallId)) {\n continue;\n }\n\n insertToolStateDataPart(toolCallId, {\n type: 'data-tool-call-suspended',\n data: transformToolStateDataForDisplay(suspendedTool, 'suspend', transformToolPayloads),\n } as AIV5Type.DataUIPart<AIV5.UIDataTypes>);\n existingToolStateDataPartIds.add(toolCallId);\n }\n }\n\n const pendingToolApprovals = metadata.pendingToolApprovals;\n if (pendingToolApprovals && typeof pendingToolApprovals === 'object') {\n for (const pendingToolApproval of Object.values(pendingToolApprovals)) {\n if (!pendingToolApproval || typeof pendingToolApproval !== 'object') {\n continue;\n }\n\n const toolCallId = 'toolCallId' in pendingToolApproval ? pendingToolApproval.toolCallId : undefined;\n if (typeof toolCallId !== 'string' || existingToolStateDataPartIds.has(toolCallId)) {\n continue;\n }\n\n insertToolStateDataPart(toolCallId, {\n type: 'data-tool-call-approval',\n data: transformToolStateDataForDisplay(pendingToolApproval, 'approval', transformToolPayloads),\n } as AIV5Type.DataUIPart<AIV5.UIDataTypes>);\n existingToolStateDataPartIds.add(toolCallId);\n }\n }\n\n return {\n id: dbMsg.id,\n role: dbMsg.role === 'signal' ? (isUserMessageSignal ? 'user' : 'system') : dbMsg.role,\n metadata,\n parts,\n };\n }\n\n /**\n * Direct conversion from AIV5 UIMessage to MastraDBMessage\n */\n static fromUIMessage(uiMsg: AIV5Type.UIMessage): MastraDBMessage {\n const { parts, metadata: rawMetadata } = uiMsg;\n const metadata = (rawMetadata || {}) as Record<string, unknown>;\n\n // Extract Mastra-specific metadata\n const createdAtValue = metadata.createdAt;\n const createdAt = createdAtValue\n ? typeof createdAtValue === 'string'\n ? new Date(createdAtValue)\n : createdAtValue instanceof Date\n ? createdAtValue\n : new Date()\n : new Date();\n const threadId = metadata.threadId as string | undefined;\n const resourceId = metadata.resourceId as string | undefined;\n\n // Remove Mastra-specific metadata from the metadata object\n const cleanMetadata = { ...metadata };\n delete cleanMetadata.createdAt;\n delete cleanMetadata.threadId;\n delete cleanMetadata.resourceId;\n\n // Process parts to build V2 content\n const toolInvocationParts = parts.filter(p => AIV5.isToolUIPart(p));\n const reasoningParts = parts.filter(p => p.type === 'reasoning');\n const fileParts = parts.filter(p => p.type === 'file');\n const textParts = parts.filter(p => p.type === 'text');\n\n // Build tool invocations array\n let toolInvocations: MastraDBMessage['content']['toolInvocations'] = undefined;\n if (toolInvocationParts.length > 0) {\n toolInvocations = toolInvocationParts.map(p => {\n const toolName = getToolName(p);\n if (p.state === 'output-available') {\n return {\n args: p.input,\n result: unwrapLegacyToolOutput(p.output),\n toolCallId: p.toolCallId,\n toolName,\n state: 'result',\n } satisfies NonNullable<MastraDBMessage['content']['toolInvocations']>[0];\n }\n return {\n args: p.input,\n toolCallId: p.toolCallId,\n toolName,\n state: 'call',\n } satisfies NonNullable<MastraDBMessage['content']['toolInvocations']>[0];\n });\n }\n\n // Build reasoning string (AIV4 reasoning is a string, not an array)\n let reasoning: MastraDBMessage['content']['reasoning'] = undefined;\n if (reasoningParts.length > 0) {\n reasoning = reasoningParts.map(p => p.text).join('\\n');\n }\n\n // Build experimental_attachments from file parts\n let experimental_attachments: MastraDBMessage['content']['experimental_attachments'] = undefined;\n if (fileParts.length > 0) {\n experimental_attachments = fileParts.map(p => ({\n url: p.url || '',\n contentType: p.mediaType,\n }));\n }\n\n // Build content from text parts (AIV4 content is a string)\n let content: MastraDBMessage['content']['content'] = undefined;\n if (textParts.length > 0) {\n content = textParts.map(p => p.text).join('');\n }\n // Build V2-compatible parts array\n const v2Parts = parts\n .map(p => {\n // Convert AIV5 UI parts to V2 parts\n if (AIV5.isToolUIPart(p)) {\n const toolName = getToolName(p);\n const callProviderMetadata = 'callProviderMetadata' in p ? p.callProviderMetadata : undefined;\n // Preserve provider-executed so a hosted tool (e.g. OpenAI tool_search)\n // stays inline in the assistant message on replay, matching fromModelMessage.\n const toolProviderExecuted = (p as { providerExecuted?: boolean }).providerExecuted;\n if (p.state === 'output-available') {\n const toolInvocationPart: MastraToolInvocationPart = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: p.toolCallId,\n toolName,\n args: p.input,\n result: unwrapLegacyToolOutput(p.output),\n state: 'result' as const,\n },\n providerMetadata: callProviderMetadata,\n createdAt: getMastraCreatedAt(callProviderMetadata),\n };\n if (toolProviderExecuted !== undefined) {\n (toolInvocationPart as { providerExecuted?: boolean }).providerExecuted = toolProviderExecuted;\n }\n return toolInvocationPart;\n }\n if (p.state === 'output-error') {\n const toolInvocationPart: MastraToolInvocationPart = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: p.toolCallId,\n toolName,\n args: p.input,\n state: 'output-error' as const,\n errorText: p.errorText,\n ...('rawInput' in p && p.rawInput !== undefined ? { rawInput: p.rawInput } : {}),\n },\n providerMetadata: callProviderMetadata,\n createdAt: getMastraCreatedAt(callProviderMetadata),\n };\n if (toolProviderExecuted !== undefined) {\n (toolInvocationPart as { providerExecuted?: boolean }).providerExecuted = toolProviderExecuted;\n }\n return toolInvocationPart;\n }\n const toolInvocationPart: MastraToolInvocationPart = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: p.toolCallId,\n toolName,\n args: p.input,\n state: 'call' as const,\n },\n providerMetadata: callProviderMetadata,\n createdAt: getMastraCreatedAt(callProviderMetadata),\n };\n if (toolProviderExecuted !== undefined) {\n (toolInvocationPart as { providerExecuted?: boolean }).providerExecuted = toolProviderExecuted;\n }\n return toolInvocationPart;\n }\n\n if (p.type === 'reasoning') {\n return {\n type: 'reasoning' as const,\n reasoning: p.text,\n details: [\n {\n type: 'text' as const,\n text: p.text,\n },\n ],\n providerMetadata: p.providerMetadata,\n createdAt: getMastraCreatedAt(p.providerMetadata),\n };\n }\n\n if (p.type === 'file') {\n return {\n type: 'file' as const,\n mimeType: p.mediaType,\n data: p.url || '',\n providerMetadata: p.providerMetadata,\n createdAt: getMastraCreatedAt(p.providerMetadata),\n ...((p as { filename?: string }).filename ? { filename: (p as { filename?: string }).filename } : {}),\n };\n }\n\n if (p.type === 'source-url') {\n return {\n type: 'source' as const,\n source: {\n url: p.url,\n sourceType: 'url',\n id: p.sourceId ?? p.url,\n ...(p.title ? { title: p.title } : {}),\n providerMetadata: p.providerMetadata,\n },\n providerMetadata: p.providerMetadata,\n createdAt: getMastraCreatedAt(p.providerMetadata),\n };\n }\n\n if (p.type === 'source-document') {\n return {\n type: 'source-document' as const,\n sourceId: p.sourceId,\n mediaType: p.mediaType,\n title: p.title,\n ...(p.filename ? { filename: p.filename } : {}),\n providerMetadata: p.providerMetadata,\n createdAt: getMastraCreatedAt(p.providerMetadata),\n };\n }\n\n if (p.type === 'text') {\n type V2TextPart = {\n type: 'text';\n text: string;\n providerMetadata?: AIV5Type.ProviderMetadata;\n createdAt?: number;\n };\n return {\n type: 'text' as const,\n text: p.text,\n providerMetadata: p.providerMetadata,\n createdAt: getMastraCreatedAt(p.providerMetadata),\n } satisfies V2TextPart;\n }\n\n if (p.type === 'step-start') {\n return p;\n }\n\n // Mastra-only record of a terminal failure. Round-trips through UI\n // history unchanged; sanitizeV5UIMessages strips it from provider\n // prompts. AIV6Adapter.fromUIMessage pairs its output with the incoming\n // parts by index, so dropping it here would misalign every later part.\n if ((p as { type: string }).type === 'error') {\n return p as unknown as MastraMessagePart;\n }\n\n // Handle data-* parts (custom parts emitted by tools via writer.custom())\n if (typeof p.type === 'string' && p.type.startsWith('data-')) {\n return {\n type: p.type,\n data: 'data' in p ? (p as any).data : undefined,\n };\n }\n\n return null;\n })\n .filter((p): p is NonNullable<typeof p> => p !== null);\n\n // Filter out empty text parts to prevent Anthropic API errors\n const filteredV2Parts = filterEmptyTextParts(v2Parts as MastraMessagePart[]);\n\n return {\n id: uiMsg.id,\n role: uiMsg.role,\n createdAt,\n threadId,\n resourceId,\n content: {\n format: 2,\n parts: filteredV2Parts as MastraMessageContentV2['parts'],\n toolInvocations,\n reasoning,\n experimental_attachments,\n content,\n metadata: Object.keys(cleanMetadata).length > 0 ? cleanMetadata : undefined,\n },\n };\n }\n\n /**\n * Convert image or file to data URI or URL for V2 file part\n */\n private static getDataStringFromAIV5DataPart(part: AIV5Type.ImagePart | AIV5Type.FilePart): string {\n let mimeType: string;\n let data: AIV5.FilePart['data'] | AIV5.ImagePart['image'];\n if ('data' in part) {\n mimeType = part.mediaType || 'application/octet-stream';\n data = part.data;\n } else if ('image' in part) {\n mimeType = part.mediaType || 'image/jpeg';\n data = part.image;\n } else if ('url' in part && typeof (part as any).url === 'string') {\n return (part as any).url;\n } else {\n throw new MastraError({\n id: 'MASTRA_AIV5_DATA_PART_INVALID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: 'Invalid AIV5 data part in getDataStringFromAIV5DataPart',\n details: {\n part,\n },\n });\n }\n\n if (\n data &&\n typeof data === 'object' &&\n !(data instanceof URL) &&\n !(data instanceof Uint8Array) &&\n !(data instanceof ArrayBuffer) &&\n typeof (data as { type?: unknown }).type === 'string'\n ) {\n // AI SDK v7 tagged FileData: { type: 'url' | 'data' | 'text' | 'reference', ... }\n const tagged = data as { type: string; url?: unknown; data?: unknown; text?: unknown };\n if (tagged.type === 'url' && (typeof tagged.url === 'string' || tagged.url instanceof URL)) {\n data = tagged.url;\n } else if (tagged.type === 'data' && tagged.data != null) {\n data = tagged.data as typeof data;\n } else if (tagged.type === 'text' && typeof tagged.text === 'string') {\n return `data:${mimeType};base64,${Buffer.from(tagged.text, 'utf8').toString('base64')}`;\n } else {\n throw new MastraError({\n id: 'MASTRA_AIV5_DATA_PART_INVALID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text:\n tagged.type === 'reference'\n ? 'Provider file references are not supported as message input.'\n : `Invalid \"${tagged.type}\" file data in message part.`,\n details: { type: tagged.type },\n });\n }\n }\n\n if (data instanceof URL) {\n return data.toString();\n } else if (data instanceof Buffer) {\n const base64 = data.toString('base64');\n return `data:${mimeType};base64,${base64}`;\n } else if (typeof data === 'string') {\n // Absolute URLs of any scheme (https:, gs:, s3:, ...) pass through. So do OpenAI\n // Files API file IDs (e.g. \"file-abc123\"), which @ai-sdk/openai forwards as\n // { file_id: \"file-...\" }. Only base64 is wrapped as a data URL; anything else\n // (e.g. a relative path) is kept as-is, and the prompt build treats it as an\n // attachment that can't be downloaded.\n if (data.startsWith('data:') || data.startsWith('file-') || isAbsoluteUrl(data) || !isBase64Like(data)) {\n return data;\n }\n return `data:${mimeType};base64,${data}`;\n } else if (data instanceof Uint8Array) {\n const base64 = Buffer.from(data).toString('base64');\n return `data:${mimeType};base64,${base64}`;\n } else if (data instanceof ArrayBuffer) {\n const base64 = Buffer.from(data).toString('base64');\n return `data:${mimeType};base64,${base64}`;\n }\n throw new MastraError({\n id: 'MASTRA_AIV5_DATA_PART_INVALID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: 'Unrecognized file data in message part',\n details: { dataType: typeof data },\n });\n }\n\n /**\n * Direct conversion from AIV5 ModelMessage to MastraDBMessage\n */\n static fromModelMessage(\n modelMsg: AIV5Type.ModelMessage,\n _messageSource?: MessageSource,\n context: { dbMessages?: MastraDBMessage[] } = {},\n ): MastraDBMessage {\n const content = Array.isArray(modelMsg.content)\n ? modelMsg.content.filter(part => part !== null && typeof part === 'object')\n : typeof modelMsg.content === 'string'\n ? [{ type: 'text', text: modelMsg.content } satisfies AIV5.TextPart]\n : [];\n\n const mastraDBParts: MastraMessageContentV2['parts'] = [];\n const toolInvocations: NonNullable<MastraDBMessage['content']['toolInvocations']> = [];\n const reasoningParts: string[] = [];\n const experimental_attachments: NonNullable<MastraDBMessage['content']['experimental_attachments']> = [];\n\n for (const part of content) {\n if (part.type === 'text') {\n const textPart: MastraDBMessage['content']['parts'][number] = {\n type: 'text' as const,\n text: part.text,\n };\n if (part.providerOptions) {\n textPart.providerMetadata = part.providerOptions;\n textPart.createdAt = getMastraCreatedAt(part.providerOptions);\n }\n mastraDBParts.push(textPart);\n } else if (part.type === 'tool-call') {\n const toolCallPart = part as AIV5Type.ToolCallPart;\n const toolInvocationPart: MastraDBMessage['content']['parts'][number] = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: toolCallPart.toolCallId,\n toolName: sanitizeToolName(toolCallPart.toolName),\n args: toolCallPart.input,\n state: 'call',\n },\n };\n if (part.providerOptions) {\n toolInvocationPart.providerMetadata = part.providerOptions;\n toolInvocationPart.createdAt = getMastraCreatedAt(part.providerOptions);\n }\n // Preserve provider-executed so the replayed part stays inline in the\n // assistant message. Without it, convertToModelMessages moves the result\n // into a `tool` role message, where @ai-sdk/openai re-serializes a hosted\n // tool_search as a client-mode tool_search_output (\"No tool call found\").\n const toolCallProviderExecuted = (part as { providerExecuted?: boolean }).providerExecuted;\n if (toolCallProviderExecuted !== undefined) {\n (toolInvocationPart as { providerExecuted?: boolean }).providerExecuted = toolCallProviderExecuted;\n }\n mastraDBParts.push(toolInvocationPart);\n toolInvocations.push({\n toolCallId: toolCallPart.toolCallId,\n toolName: sanitizeToolName(toolCallPart.toolName),\n args: toolCallPart.input,\n state: 'call',\n });\n } else if (part.type === 'tool-result') {\n const toolResultPart = part;\n const matchingCall = toolInvocations.find(inv => inv.toolCallId === toolResultPart.toolCallId);\n\n const matchingV2Part = mastraDBParts.find(\n (p): p is Extract<MastraDBMessage['content']['parts'][number], { type: 'tool-invocation' }> =>\n p.type === 'tool-invocation' &&\n 'toolInvocation' in p &&\n p.toolInvocation.toolCallId === toolResultPart.toolCallId,\n );\n\n const updateMatchingCallInvocationResult = (toolResultPart: AIV5Type.ToolResultPart, matchingCall: any) => {\n const normalized = normalizeToolOutput(toolResultPart.output);\n matchingCall.state = normalized.isError ? 'output-error' : 'result';\n matchingCall.result = normalized.output;\n if (normalized.isError) {\n matchingCall.errorText =\n typeof normalized.output === 'string' ? normalized.output : JSON.stringify(normalized.output);\n }\n };\n\n // When the matching tool-call isn't in this same model message (e.g. the\n // server resume path or an AG-UI host replaying a tool-result on its own),\n // recover the original args from prior persisted messages before falling\n // back to the tool-result's own `input` field, then finally to `{}`.\n // Persisting `args: {}` poisons the LLM via in-context learning (issue #16017).\n const recoveredArgs = context.dbMessages\n ? findToolCallArgs(context.dbMessages, toolResultPart.toolCallId)\n : undefined;\n const fallbackArgs =\n recoveredArgs && Object.keys(recoveredArgs).length > 0\n ? recoveredArgs\n : ((toolResultPart as AIV5Type.ToolResultPart & { input?: Record<string, unknown> }).input ?? {});\n\n if (matchingCall) {\n updateMatchingCallInvocationResult(toolResultPart, matchingCall);\n } else {\n const call: any = {\n state: 'call',\n toolCallId: toolResultPart.toolCallId,\n toolName: sanitizeToolName(toolResultPart.toolName),\n args: fallbackArgs,\n };\n updateMatchingCallInvocationResult(toolResultPart, call);\n toolInvocations.push(call);\n }\n\n const resultProviderExecuted = (toolResultPart as { providerExecuted?: boolean }).providerExecuted;\n\n if (matchingV2Part && matchingV2Part.type === 'tool-invocation') {\n updateMatchingCallInvocationResult(toolResultPart, matchingV2Part.toolInvocation);\n if (resultProviderExecuted !== undefined) {\n (matchingV2Part as { providerExecuted?: boolean }).providerExecuted = resultProviderExecuted;\n }\n if (toolResultPart.providerOptions) {\n // When the call and result carry different Responses item ids\n // (e.g. OpenAI hosted tool_search: tsc_… call / tso_… output),\n // keep both so next-turn replay can reference each item.\n matchingV2Part.providerMetadata = preserveResponseItemIdsOnMerge(\n matchingV2Part.providerMetadata as Record<string, unknown> | undefined,\n toolResultPart.providerOptions as Record<string, unknown> | undefined,\n toolResultPart.providerOptions as Record<string, unknown>,\n ) as AIV5Type.ProviderMetadata;\n matchingV2Part.createdAt = getMastraCreatedAt(toolResultPart.providerOptions) ?? matchingV2Part.createdAt;\n }\n } else {\n const toolInvocationPart: MastraDBMessage['content']['parts'][number] = {\n type: 'tool-invocation' as const,\n toolInvocation: {\n toolCallId: toolResultPart.toolCallId,\n toolName: sanitizeToolName(toolResultPart.toolName),\n args: fallbackArgs,\n state: 'call',\n },\n };\n updateMatchingCallInvocationResult(toolResultPart, toolInvocationPart.toolInvocation);\n if (resultProviderExecuted !== undefined) {\n (toolInvocationPart as { providerExecuted?: boolean }).providerExecuted = resultProviderExecuted;\n }\n if (toolResultPart.providerOptions) {\n toolInvocationPart.providerMetadata = toolResultPart.providerOptions;\n toolInvocationPart.createdAt = getMastraCreatedAt(toolResultPart.providerOptions);\n }\n mastraDBParts.push(toolInvocationPart);\n }\n } else if (part.type === 'reasoning') {\n const v2ReasoningPart: MastraDBMessage['content']['parts'][number] = {\n type: 'reasoning',\n reasoning: part.text,\n details: [{ type: 'text', text: part.text }],\n };\n if (part.providerOptions) {\n v2ReasoningPart.providerMetadata = part.providerOptions;\n v2ReasoningPart.createdAt = getMastraCreatedAt(part.providerOptions);\n }\n mastraDBParts.push(v2ReasoningPart);\n reasoningParts.push(part.text);\n } else if (part.type === 'image') {\n const imagePart = part;\n const mimeType = imagePart.mediaType || 'image/jpeg';\n const imageData = this.getDataStringFromAIV5DataPart(imagePart);\n\n const imageFilePart: MastraDBMessage['content']['parts'][number] = {\n type: 'file',\n data: imageData,\n mimeType,\n };\n if (part.providerOptions) {\n imageFilePart.providerMetadata = part.providerOptions;\n imageFilePart.createdAt = getMastraCreatedAt(part.providerOptions);\n }\n mastraDBParts.push(imageFilePart);\n experimental_attachments.push({\n url: imageData,\n contentType: mimeType,\n });\n } else if (part.type === 'file') {\n const filePart = part;\n const mimeType = filePart.mediaType || 'application/octet-stream';\n const fileData = this.getDataStringFromAIV5DataPart(filePart);\n\n const v2FilePart: MastraDBMessage['content']['parts'][number] = {\n type: 'file',\n data: fileData,\n mimeType,\n };\n if (part.providerOptions) {\n v2FilePart.providerMetadata = part.providerOptions;\n v2FilePart.createdAt = getMastraCreatedAt(part.providerOptions);\n }\n if ((filePart as { filename?: string }).filename) {\n (v2FilePart as Record<string, unknown>).filename = (filePart as { filename?: string }).filename;\n }\n mastraDBParts.push(v2FilePart);\n experimental_attachments.push({\n url: fileData,\n contentType: mimeType,\n });\n }\n }\n\n // Filter out empty text parts to prevent Anthropic API errors\n const filteredMastraDBParts = filterEmptyTextParts(mastraDBParts);\n\n // Build V2 content string\n const contentString = filteredMastraDBParts\n .filter(p => p.type === 'text')\n .map(p => p.text)\n .join('\\n');\n\n // Preserve metadata from the input message if present\n const metadata: Record<string, unknown> =\n 'metadata' in modelMsg && modelMsg.metadata !== null && modelMsg.metadata !== undefined\n ? (modelMsg.metadata as Record<string, unknown>)\n : {};\n\n // Generate ID from modelMsg if available, otherwise create a new one\n const id =\n `id` in modelMsg && typeof modelMsg.id === `string`\n ? modelMsg.id\n : `msg-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n const message: MastraDBMessage = {\n id,\n role: modelMsg.role === 'tool' ? 'assistant' : modelMsg.role,\n createdAt: new Date(),\n content: {\n format: 2,\n parts: filteredMastraDBParts,\n toolInvocations: toolInvocations.length > 0 ? toolInvocations : undefined,\n reasoning: reasoningParts.length > 0 ? reasoningParts.join('\\n') : undefined,\n experimental_attachments: experimental_attachments.length > 0 ? experimental_attachments : undefined,\n content: contentString || undefined,\n metadata: Object.keys(metadata).length > 0 ? metadata : undefined,\n },\n };\n // Add message-level providerOptions if present\n if (modelMsg.providerOptions) {\n message.content.providerMetadata = modelMsg.providerOptions;\n }\n\n return message;\n }\n}\n","import * as AIV5 from '@internal/ai-sdk-v5';\nimport * as AIV6 from '@internal/ai-v6';\n\nimport { getTransformedToolPayload, hasTransformedToolPayload } from '../../../tools/payload-transform';\nimport type {\n MastraDBMessage,\n MastraMessagePart,\n MastraProviderMetadata,\n MastraToolApproval,\n MastraToolInvocation,\n MastraToolInvocationPart,\n} from '../state/types';\nimport type { AIV5Type, AIV6Type, MessageSource } from '../types';\nimport {\n getResponseResultProviderMetadata,\n omitResponseResultItemIds,\n preserveResponseItemIdsOnMerge,\n} from '../utils/response-item-metadata';\nimport { sanitizeToolName } from '../utils/tool-name';\nimport { unwrapLegacyToolOutput } from '../utils/unwrap-legacy-tool-output';\nimport { AIV5Adapter } from './AIV5Adapter';\n\ntype AIV6AdapterContext = {\n dbMessages?: MastraDBMessage[];\n};\n\nfunction withOptionalFields<T extends Record<string, unknown>, U extends Record<string, unknown>>(\n target: T,\n fields: U,\n): T & Partial<U> {\n for (const [key, value] of Object.entries(fields)) {\n if (value !== undefined) {\n (target as Record<string, unknown>)[key] = value;\n }\n }\n return target as T & Partial<U>;\n}\n\nfunction getDisplayTransform(\n providerMetadata: unknown,\n phase: 'input-available' | 'output-available' | 'error',\n fallback: unknown,\n) {\n const transform = getTransformedToolPayload(providerMetadata, 'display', phase);\n return hasTransformedToolPayload(transform) ? transform.transformed : fallback;\n}\n\nfunction getToolNameFromType(type: string): string {\n return type.startsWith('tool-') ? sanitizeToolName(type.slice('tool-'.length)) : sanitizeToolName(type);\n}\n\nfunction normalizeToolArgs(input: unknown): Record<string, unknown> {\n return typeof input === 'object' && input !== null && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n}\n\nfunction isV6OnlyToolState(\n state: string,\n): state is Extract<MastraToolInvocation['state'], 'approval-requested' | 'approval-responded' | 'output-denied'> {\n return state === 'approval-requested' || state === 'approval-responded' || state === 'output-denied';\n}\n\nfunction toMastraApproval(\n approval: AIV6Type.UIToolInvocation<AIV6Type.UITool>['approval'],\n): MastraToolApproval | undefined {\n if (!approval) return undefined;\n\n return {\n id: approval.id,\n approved: 'approved' in approval ? approval.approved : undefined,\n reason: 'reason' in approval ? approval.reason : undefined,\n };\n}\n\nfunction toMastraProviderMetadata(\n providerMetadata: AIV6Type.ProviderMetadata | undefined,\n): MastraProviderMetadata | undefined {\n return providerMetadata as MastraProviderMetadata | undefined;\n}\n\nfunction getToolNameFromUIPart(part: AIV6Type.ToolUIPart | AIV6Type.DynamicToolUIPart): string {\n return part.type === 'dynamic-tool' ? sanitizeToolName(part.toolName) : getToolNameFromType(part.type);\n}\n\n/**\n * v6 splits tool provider metadata across `callProviderMetadata` and\n * `resultProviderMetadata`, but a Mastra part has one slot. Reading only the call half\n * dropped the `toModelOutput` projection prompt building looks for (issue #22012).\n * The result half wins on conflict, being the later of the two — except for Responses\n * item ids: a hosted tool (e.g. OpenAI `tool_search`) gives its call and output distinct\n * ids and replay needs both, so the call's stays as `itemId` and the result's is kept\n * beside it as `resultItemId`.\n */\nfunction mergeToolUIPartProviderMetadata(\n part: AIV6Type.ToolUIPart | AIV6Type.DynamicToolUIPart,\n): MastraProviderMetadata | undefined {\n const callMetadata = 'callProviderMetadata' in part ? part.callProviderMetadata : undefined;\n const resultMetadata = 'resultProviderMetadata' in part ? part.resultProviderMetadata : undefined;\n\n if (!resultMetadata) return toMastraProviderMetadata(callMetadata);\n if (!callMetadata) return toMastraProviderMetadata(resultMetadata);\n\n // Merge per provider namespace so a result that only sets `mastra.modelOutput` keeps\n // the call-time keys sitting beside it.\n const merged: AIV6Type.ProviderMetadata = { ...callMetadata };\n for (const [providerKey, resultValue] of Object.entries(resultMetadata)) {\n const callValue = merged[providerKey];\n merged[providerKey] = callValue ? { ...callValue, ...resultValue } : resultValue;\n }\n\n return toMastraProviderMetadata(\n preserveResponseItemIdsOnMerge(\n callMetadata as Record<string, unknown>,\n resultMetadata as Record<string, unknown>,\n merged as Record<string, unknown>,\n ) as AIV6Type.ProviderMetadata,\n );\n}\n\nfunction createToolInvocationPartFromUIPart(part: AIV6Type.ToolUIPart | AIV6Type.DynamicToolUIPart) {\n const base = {\n toolCallId: part.toolCallId,\n toolName: getToolNameFromUIPart(part),\n args: normalizeToolArgs(part.input),\n approval: 'approval' in part ? toMastraApproval(part.approval) : undefined,\n providerMetadata: mergeToolUIPartProviderMetadata(part),\n providerExecuted: part.providerExecuted,\n title: part.title,\n preliminary: 'preliminary' in part ? part.preliminary : undefined,\n };\n\n switch (part.state) {\n case 'input-streaming':\n return createToolInvocationPart({\n ...base,\n state: 'partial-call',\n });\n\n case 'input-available':\n return createToolInvocationPart({\n ...base,\n state: 'call',\n });\n\n case 'output-available':\n return createToolInvocationPart({\n ...base,\n state: 'result',\n result: unwrapLegacyToolOutput(part.output),\n });\n\n case 'output-error':\n return createToolInvocationPart({\n ...base,\n state: 'output-error',\n errorText: part.errorText,\n rawInput: 'rawInput' in part ? part.rawInput : undefined,\n });\n\n case 'approval-requested':\n case 'approval-responded':\n case 'output-denied':\n return createToolInvocationPart({\n ...base,\n state: part.state,\n });\n }\n}\n\nfunction normalizeV6PartForV5Bridge(part: AIV6Type.UIMessage['parts'][number]): AIV5Type.UIMessage['parts'][number] {\n if (part.type === 'dynamic-tool' && !isV6OnlyToolState(part.state)) {\n return {\n ...part,\n type: `tool-${sanitizeToolName(part.toolName)}`,\n } as unknown as AIV5Type.UIMessage['parts'][number];\n }\n\n return part as unknown as AIV5Type.UIMessage['parts'][number];\n}\n\n/** Part types `fromUIMessage` maps: its own tool and source-document handling plus what the v5 bridge keeps. */\nfunction isMappedV6UIPart(part: { type: string }): boolean {\n return (\n AIV6.isToolUIPart(part as AIV6Type.UIMessage['parts'][number]) ||\n part.type.startsWith('data-') ||\n ['text', 'reasoning', 'file', 'source-url', 'source-document', 'step-start', 'error'].includes(part.type)\n );\n}\n\nfunction getSuspendedToolCallId(part: { type: string }): string | undefined {\n if (part.type !== 'data-tool-call-suspended' || !('data' in part)) return undefined;\n const data = part.data;\n if (!data || typeof data !== 'object' || !('toolCallId' in data)) return undefined;\n return typeof data.toolCallId === 'string' ? data.toolCallId : undefined;\n}\n\nfunction createToolInvocationPart({\n toolCallId,\n toolName,\n args,\n state,\n approval,\n result,\n errorText,\n rawInput,\n providerMetadata,\n providerExecuted,\n title,\n preliminary,\n}: {\n toolCallId: string;\n toolName: string;\n args: Record<string, unknown>;\n state: MastraToolInvocation['state'];\n approval?: MastraToolApproval;\n result?: unknown;\n errorText?: string;\n rawInput?: unknown;\n providerMetadata?: MastraToolInvocationPart['providerMetadata'];\n providerExecuted?: boolean;\n title?: string;\n preliminary?: boolean;\n}): MastraToolInvocationPart {\n return withOptionalFields(\n {\n type: 'tool-invocation',\n toolInvocation: withOptionalFields(\n {\n toolCallId,\n toolName,\n args,\n state,\n },\n {\n approval,\n result,\n errorText,\n rawInput,\n },\n ),\n } satisfies MastraToolInvocationPart,\n {\n providerMetadata,\n providerExecuted,\n title,\n preliminary,\n },\n );\n}\n\nfunction findToolInvocationPart(parts: MastraMessagePart[], toolCallId: string): MastraToolInvocationPart | undefined {\n for (const part of parts) {\n if (part.type === 'tool-invocation' && part.toolInvocation.toolCallId === toolCallId) {\n return part;\n }\n }\n\n return undefined;\n}\n\nfunction findApprovalRequest(\n dbMessages: MastraDBMessage[] | undefined,\n approvalId: string,\n): MastraToolInvocationPart | undefined {\n if (!dbMessages) return undefined;\n\n for (const message of [...dbMessages].reverse()) {\n for (const part of [...(message.content.parts || [])].reverse()) {\n if (\n part.type === 'tool-invocation' &&\n part.toolInvocation.approval?.id === approvalId &&\n part.toolInvocation.state === 'approval-requested'\n ) {\n return part;\n }\n }\n\n const pendingToolApprovals = message.content.metadata?.pendingToolApprovals;\n if (!pendingToolApprovals || typeof pendingToolApprovals !== 'object') {\n continue;\n }\n\n for (const pendingToolApproval of Object.values(pendingToolApprovals)) {\n if (!pendingToolApproval || typeof pendingToolApproval !== 'object') {\n continue;\n }\n\n const toolCallId = 'toolCallId' in pendingToolApproval ? pendingToolApproval.toolCallId : undefined;\n if (typeof toolCallId !== 'string') {\n continue;\n }\n\n const runId = 'runId' in pendingToolApproval ? pendingToolApproval.runId : undefined;\n const pendingApprovalId = typeof runId === 'string' ? `${runId}::${toolCallId}` : toolCallId;\n if (pendingApprovalId !== approvalId) {\n continue;\n }\n\n const existingPart = findToolInvocationPart(message.content.parts || [], toolCallId);\n if (!existingPart) {\n continue;\n }\n\n return createToolInvocationPart({\n toolCallId: existingPart.toolInvocation.toolCallId,\n toolName: existingPart.toolInvocation.toolName,\n args: existingPart.toolInvocation.args,\n state: 'approval-requested',\n approval: { id: pendingApprovalId },\n providerMetadata: existingPart.providerMetadata,\n providerExecuted: existingPart.providerExecuted,\n title: existingPart.title,\n preliminary: existingPart.preliminary,\n });\n }\n }\n\n return undefined;\n}\n\nfunction rehydratePendingToolApprovals(parts: AIV6Type.UIMessage['parts'], metadata: Record<string, unknown>) {\n const pendingToolApprovals = metadata.pendingToolApprovals;\n if (!pendingToolApprovals || typeof pendingToolApprovals !== 'object') {\n return;\n }\n\n for (const pendingToolApproval of Object.values(pendingToolApprovals)) {\n if (!pendingToolApproval || typeof pendingToolApproval !== 'object') {\n continue;\n }\n\n const toolCallId = 'toolCallId' in pendingToolApproval ? pendingToolApproval.toolCallId : undefined;\n if (typeof toolCallId !== 'string') {\n continue;\n }\n\n const runId = 'runId' in pendingToolApproval ? pendingToolApproval.runId : undefined;\n const approvalId = typeof runId === 'string' ? `${runId}::${toolCallId}` : toolCallId;\n\n const toolPartIndex = parts.findIndex(\n part => AIV6.isToolUIPart(part) && part.toolCallId === toolCallId && part.state === 'input-available',\n );\n if (toolPartIndex === -1) {\n continue;\n }\n\n const toolPart = parts[toolPartIndex];\n if (!toolPart || !AIV6.isToolUIPart(toolPart) || toolPart.state !== 'input-available') {\n continue;\n }\n\n parts[toolPartIndex] = {\n ...toolPart,\n state: 'approval-requested',\n approval: { id: approvalId },\n } as AIV6Type.UIMessage['parts'][number];\n }\n}\n\nfunction createLegacyToolInvocations(\n parts: MastraMessagePart[],\n): MastraDBMessage['content']['toolInvocations'] | undefined {\n const toolInvocations: NonNullable<MastraDBMessage['content']['toolInvocations']> = [];\n\n for (const part of parts) {\n if (part.type !== 'tool-invocation') continue;\n\n const invocation = part.toolInvocation;\n\n if (invocation.state === 'result') {\n toolInvocations.push({\n args: invocation.args,\n result: invocation.result,\n toolCallId: invocation.toolCallId,\n toolName: invocation.toolName,\n state: 'result',\n });\n continue;\n }\n\n if (invocation.state === 'call' || invocation.state === 'partial-call') {\n toolInvocations.push({\n args: invocation.args,\n toolCallId: invocation.toolCallId,\n toolName: invocation.toolName,\n state: invocation.state,\n });\n }\n }\n\n return toolInvocations.length > 0 ? toolInvocations : undefined;\n}\n\n/**\n * AIV6Adapter - Handles conversions between MastraDBMessage and AI SDK v6 formats.\n */\nexport class AIV6Adapter {\n static toUIMessage(dbMsg: MastraDBMessage): AIV6Type.UIMessage {\n const v5Message = AIV5Adapter.toUIMessage(dbMsg);\n const metadata = (v5Message.metadata || {}) as Record<string, unknown>;\n const parts: AIV6Type.UIMessage['parts'] = [];\n\n if (dbMsg.role === 'signal' && v5Message.role !== 'user') {\n return {\n id: dbMsg.id,\n role: 'system',\n metadata: Object.keys(metadata).length > 0 ? metadata : undefined,\n parts: v5Message.parts.map(part => AIV6Adapter.toUIPartFromV5(part)),\n };\n }\n\n const dbParts = dbMsg.content.parts || [];\n const hasToolInvocationParts = dbParts.some(part => part.type === 'tool-invocation');\n const hasReasoningParts = dbParts.some(part => part.type === 'reasoning');\n const hasFileParts = dbParts.some(part => part.type === 'file');\n const hasTextParts = dbParts.some(part => part.type === 'text');\n\n for (const part of dbParts) {\n const uiPart = AIV6Adapter.toUIPart(part);\n if (uiPart) parts.push(uiPart);\n }\n\n if (!hasToolInvocationParts || !hasReasoningParts || !hasFileParts || !hasTextParts) {\n for (const part of v5Message.parts) {\n if (AIV5.isToolUIPart(part)) {\n if (!hasToolInvocationParts) {\n parts.push(AIV6Adapter.toUIPartFromV5(part));\n }\n continue;\n }\n\n if (part.type === 'reasoning') {\n if (!hasReasoningParts) {\n parts.push(AIV6Adapter.toUIPartFromV5(part));\n }\n continue;\n }\n\n if (part.type === 'file') {\n if (!hasFileParts) {\n parts.push(AIV6Adapter.toUIPartFromV5(part));\n }\n continue;\n }\n\n if (part.type === 'text' && !hasTextParts) {\n parts.push(AIV6Adapter.toUIPartFromV5(part));\n }\n }\n }\n\n AIV6Adapter.rehydrateSuspendedToolParts(parts, v5Message.parts);\n rehydratePendingToolApprovals(parts, metadata);\n\n return {\n id: dbMsg.id,\n role: dbMsg.role === 'signal' ? v5Message.role : dbMsg.role,\n metadata: Object.keys(metadata).length > 0 ? metadata : undefined,\n parts,\n };\n }\n\n static fromUIMessage(uiMsg: AIV6Type.UIMessage): MastraDBMessage {\n // Parts are paired with the v5 bridge output by index below, so drop the ones the bridge would drop\n // first: part types it doesn't map (e.g. `steering-message` from a newer `ai`, #29575) and, like its\n // filterEmptyTextParts, empty text unless nothing else is left. Otherwise every later part shifts.\n const isBridgePart = (part: AIV6Type.UIMessage['parts'][number]) =>\n part.type !== 'source-document' && !AIV6.isToolUIPart(part);\n const isEmptyText = (part: AIV6Type.UIMessage['parts'][number]) => part.type === 'text' && part.text === '';\n const mappedParts = uiMsg.parts.filter(isMappedV6UIPart);\n const dropEmptyText = mappedParts.some(part => isBridgePart(part) && !isEmptyText(part));\n uiMsg = { ...uiMsg, parts: dropEmptyText ? mappedParts.filter(part => !isEmptyText(part)) : mappedParts };\n\n const compatibleParts = uiMsg.parts.filter(isBridgePart);\n\n const baseDb = AIV5Adapter.fromUIMessage({\n ...uiMsg,\n parts: compatibleParts.map(part => normalizeV6PartForV5Bridge(part)) as AIV5Type.UIMessage['parts'],\n } as AIV5Type.UIMessage);\n\n const baseParts = baseDb.content.parts || [];\n const parts: MastraMessagePart[] = [];\n let basePartIndex = 0;\n\n for (const part of uiMsg.parts) {\n if (part.type === 'source-document') {\n parts.push(\n withOptionalFields(\n {\n type: 'source-document',\n sourceId: part.sourceId,\n mediaType: part.mediaType,\n title: part.title,\n },\n {\n filename: part.filename,\n providerMetadata: toMastraProviderMetadata(part.providerMetadata),\n },\n ) as MastraMessagePart,\n );\n continue;\n }\n\n if (!AIV6.isToolUIPart(part)) {\n const basePart = baseParts[basePartIndex++];\n if (basePart) {\n parts.push(basePart);\n }\n continue;\n }\n\n parts.push(createToolInvocationPartFromUIPart(part));\n }\n\n return {\n ...baseDb,\n content: {\n ...baseDb.content,\n parts,\n toolInvocations: createLegacyToolInvocations(parts) || baseDb.content.toolInvocations,\n },\n };\n }\n\n static fromModelMessage(\n modelMsg: AIV6Type.ModelMessage,\n _messageSource?: MessageSource,\n context: AIV6AdapterContext = {},\n ): MastraDBMessage {\n const content = Array.isArray(modelMsg.content)\n ? modelMsg.content\n : [{ type: 'text', text: modelMsg.content } satisfies AIV6Type.TextPart];\n\n const compatibleContent = content.filter(\n part => part.type !== 'tool-approval-request' && part.type !== 'tool-approval-response',\n );\n\n const baseDb = AIV5Adapter.fromModelMessage(\n {\n ...modelMsg,\n content: compatibleContent as unknown as AIV5Type.ModelMessage['content'],\n } as AIV5Type.ModelMessage,\n _messageSource,\n context,\n );\n\n const parts = [...baseDb.content.parts];\n\n if (modelMsg.role === 'assistant') {\n const toolCalls = new Map<\n string,\n {\n toolName: string;\n args: Record<string, unknown>;\n }\n >();\n\n for (const part of content) {\n if (part.type === 'tool-call') {\n toolCalls.set(part.toolCallId, {\n toolName: sanitizeToolName(part.toolName),\n args: normalizeToolArgs(part.input),\n });\n continue;\n }\n\n if (part.type !== 'tool-approval-request') {\n continue;\n }\n\n const call = toolCalls.get(part.toolCallId);\n const existingPart = findToolInvocationPart(parts, part.toolCallId);\n\n if (existingPart) {\n existingPart.toolInvocation.state = 'approval-requested';\n existingPart.toolInvocation.approval = { id: part.approvalId };\n continue;\n }\n\n parts.push(\n createToolInvocationPart({\n toolCallId: part.toolCallId,\n toolName: call?.toolName || 'unknown',\n args: call?.args || {},\n state: 'approval-requested',\n approval: { id: part.approvalId },\n }),\n );\n }\n } else if (modelMsg.role === 'tool') {\n for (const part of content) {\n if (part.type !== 'tool-approval-response') {\n continue;\n }\n\n const request = findApprovalRequest(context.dbMessages, part.approvalId);\n if (!request) {\n continue;\n }\n\n parts.push(\n createToolInvocationPart({\n toolCallId: request.toolInvocation.toolCallId,\n toolName: request.toolInvocation.toolName,\n args: request.toolInvocation.args,\n state: 'approval-responded',\n approval: {\n id: part.approvalId,\n approved: part.approved,\n reason: part.reason,\n },\n providerMetadata: request.providerMetadata,\n providerExecuted: request.providerExecuted,\n title: request.title,\n }),\n );\n }\n }\n\n return {\n ...baseDb,\n content: {\n ...baseDb.content,\n parts,\n },\n };\n }\n\n private static toUIPart(part: MastraMessagePart): AIV6Type.UIMessage['parts'][number] | undefined {\n if (part.type === 'tool-invocation') {\n const base = withOptionalFields(\n {\n type: `tool-${sanitizeToolName(part.toolInvocation.toolName)}`,\n toolCallId: part.toolInvocation.toolCallId,\n providerExecuted: part.providerExecuted,\n },\n {\n // `resultItemId` is how a single-slot Mastra part carries the result's\n // Responses item id. v6 has a real slot for it (`resultProviderMetadata`\n // below), so the internal key must not ride along on the public call\n // metadata — v6's own convertToModelMessages would forward it to the\n // provider as `providerOptions.openai.resultItemId`.\n callProviderMetadata: omitResponseResultItemIds(\n part.providerMetadata as Record<string, unknown> | undefined,\n ) as typeof part.providerMetadata,\n title: part.title,\n },\n );\n\n switch (part.toolInvocation.state) {\n case 'partial-call':\n return {\n ...base,\n state: 'input-streaming',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n } as AIV6Type.UIMessage['parts'][number];\n\n case 'call':\n return {\n ...base,\n state: 'input-available',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n } as AIV6Type.UIMessage['parts'][number];\n\n case 'approval-requested':\n return {\n ...base,\n state: 'approval-requested',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n approval: {\n id: part.toolInvocation.approval?.id || part.toolInvocation.toolCallId,\n },\n } as AIV6Type.UIMessage['parts'][number];\n\n case 'approval-responded':\n return {\n ...base,\n state: 'approval-responded',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n approval: {\n id: part.toolInvocation.approval?.id || part.toolInvocation.toolCallId,\n approved: part.toolInvocation.approval?.approved ?? false,\n reason: part.toolInvocation.approval?.reason,\n },\n } as AIV6Type.UIMessage['parts'][number];\n\n case 'output-error':\n return withOptionalFields(\n {\n ...base,\n state: 'output-error',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n errorText: getDisplayTransform(\n part.providerMetadata,\n 'error',\n part.toolInvocation.errorText || '',\n ) as string,\n },\n {\n rawInput: part.toolInvocation.rawInput,\n // A failed hosted call replays by item reference like a successful\n // one, so its result id needs the same dedicated slot (see the\n // `result` case below).\n resultProviderMetadata: getResponseResultProviderMetadata(\n part.providerMetadata as Record<string, unknown> | undefined,\n ),\n approval:\n part.toolInvocation.approval?.approved === true\n ? {\n id: part.toolInvocation.approval.id,\n approved: true,\n reason: part.toolInvocation.approval.reason,\n }\n : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'output-denied':\n return {\n ...base,\n state: 'output-denied',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n approval: {\n id: part.toolInvocation.approval?.id || part.toolInvocation.toolCallId,\n approved: false,\n reason: part.toolInvocation.approval?.reason,\n },\n } as AIV6Type.UIMessage['parts'][number];\n\n case 'result':\n return withOptionalFields(\n {\n ...base,\n state: 'output-available',\n input: getDisplayTransform(part.providerMetadata, 'input-available', part.toolInvocation.args),\n output: getDisplayTransform(\n part.providerMetadata,\n 'output-available',\n getDisplayTransform(part.providerMetadata, 'error', part.toolInvocation.result),\n ),\n },\n {\n preliminary: part.preliminary,\n // v6 has a dedicated slot for result-side metadata. Surface the result's\n // Responses item id there when it differs from the call's, so a\n // toUIMessage → fromUIMessage round trip keeps both ids.\n resultProviderMetadata: getResponseResultProviderMetadata(\n part.providerMetadata as Record<string, unknown> | undefined,\n ),\n approval:\n part.toolInvocation.approval?.approved === true\n ? {\n id: part.toolInvocation.approval.id,\n approved: true,\n reason: part.toolInvocation.approval.reason,\n }\n : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n default:\n throw new Error(`Unhandled toolInvocation.state: ${String(part.toolInvocation.state)}`);\n }\n }\n\n if (part.type === 'source-document') {\n return withOptionalFields(\n {\n type: 'source-document',\n sourceId: part.sourceId,\n mediaType: part.mediaType,\n title: part.title,\n },\n {\n filename: part.filename,\n providerMetadata: part.providerMetadata,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n }\n\n const v5Part = AIV5Adapter.toUIMessage({\n id: 'tmp',\n role: 'assistant',\n createdAt: new Date(),\n content: {\n format: 2,\n parts: [part],\n },\n }).parts[0];\n\n // The v5 bridge legitimately omits some parts (e.g. reasoning with no text and no\n // details, which streaming emits before the first reasoning delta arrives).\n // Signal \"no part\" instead of dereferencing undefined.\n return v5Part ? AIV6Adapter.toUIPartFromV5(v5Part) : undefined;\n }\n\n // AIV5Adapter synthesizes data-tool-call-suspended parts from metadata.suspendedTools;\n // carry them into the v6 message so suspension state survives history reloads.\n private static rehydrateSuspendedToolParts(\n parts: AIV6Type.UIMessage['parts'],\n v5Parts: AIV5Type.UIMessage['parts'],\n ): void {\n const existingIds = new Set(parts.map(getSuspendedToolCallId).filter(id => id !== undefined));\n\n for (const v5Part of v5Parts) {\n const toolCallId = getSuspendedToolCallId(v5Part);\n if (!toolCallId || existingIds.has(toolCallId)) continue;\n\n const toolPartIndex = parts.findIndex(part => AIV6.isToolUIPart(part) && part.toolCallId === toolCallId);\n const dataPart = AIV6Adapter.toUIPartFromV5(v5Part);\n if (toolPartIndex === -1) {\n parts.push(dataPart);\n } else {\n parts.splice(toolPartIndex + 1, 0, dataPart);\n }\n existingIds.add(toolCallId);\n }\n }\n\n private static toUIPartFromV5(part: AIV5Type.UIMessage['parts'][number]): AIV6Type.UIMessage['parts'][number] {\n if (AIV5.isToolUIPart(part)) {\n const base = {\n type: part.type,\n toolCallId: part.toolCallId,\n providerExecuted: part.providerExecuted,\n };\n\n switch (part.state) {\n case 'input-streaming':\n return withOptionalFields(\n {\n ...base,\n state: 'input-streaming',\n input: part.input,\n },\n {\n callProviderMetadata: 'callProviderMetadata' in part ? part.callProviderMetadata : undefined,\n title: 'title' in part ? part.title : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'input-available':\n return withOptionalFields(\n {\n ...base,\n state: 'input-available',\n input: part.input,\n },\n {\n callProviderMetadata: 'callProviderMetadata' in part ? part.callProviderMetadata : undefined,\n title: 'title' in part ? part.title : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'output-available':\n return withOptionalFields(\n {\n ...base,\n state: 'output-available',\n input: part.input,\n output: part.output,\n },\n {\n callProviderMetadata: 'callProviderMetadata' in part ? part.callProviderMetadata : undefined,\n preliminary: 'preliminary' in part ? part.preliminary : undefined,\n title: 'title' in part ? part.title : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'output-error':\n return withOptionalFields(\n {\n ...base,\n state: 'output-error',\n input: part.input,\n errorText: part.errorText,\n },\n {\n rawInput: 'rawInput' in part ? part.rawInput : undefined,\n callProviderMetadata: 'callProviderMetadata' in part ? part.callProviderMetadata : undefined,\n title: 'title' in part ? part.title : undefined,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n }\n }\n\n switch (part.type) {\n case 'text':\n return withOptionalFields(\n { type: 'text', text: part.text },\n { providerMetadata: part.providerMetadata },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'reasoning':\n return withOptionalFields(\n {\n type: 'reasoning',\n text: part.text,\n state: part.state,\n },\n { providerMetadata: part.providerMetadata },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'file':\n return withOptionalFields(\n {\n type: 'file',\n url: part.url,\n mediaType: part.mediaType,\n },\n {\n filename: 'filename' in part ? part.filename : undefined,\n providerMetadata: part.providerMetadata,\n },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'source-url':\n return withOptionalFields(\n {\n type: 'source-url',\n sourceId: part.sourceId,\n url: part.url,\n },\n { title: part.title, providerMetadata: part.providerMetadata },\n ) as AIV6Type.UIMessage['parts'][number];\n\n case 'step-start':\n return { type: 'step-start' };\n\n default:\n if (typeof part.type === 'string' && part.type.startsWith('data-')) {\n return {\n type: part.type,\n data: 'data' in part ? part.data : undefined,\n } as AIV6Type.UIMessage['parts'][number];\n }\n\n return part as unknown as AIV6Type.UIMessage['parts'][number];\n }\n }\n}\n","/**\n * Provider-agnostic reasoning identity for cache keys.\n *\n * Several providers return reasoning blocks whose text can be empty while their identity\n * lives in provider metadata (e.g. `openai.itemId`, `anthropic.signature`,\n * `anthropic.redactedData`, `google.thoughtSignature`). Without that identity, distinct\n * empty-text reasoning parts collapse onto one cache key and are deduped during merge.\n *\n * Only identity-like fields are used (not the whole namespace) so that non-identity metadata\n * drift such as `cacheControl` or usage does not split otherwise identical parts.\n */\nconst IDENTITY_KEY =\n /^(itemId|signature|redactedData|encryptedContent|reasoningEncryptedContent|\\w*Signature|\\w*Digest)$/;\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** cyrb53: fast, deterministic, runtime-agnostic 53-bit string hash. */\nexport function hashIdentityValue(value: string): string {\n let h1 = 0xdeadbeef;\n let h2 = 0x41c6ce57;\n for (let i = 0; i < value.length; i++) {\n const ch = value.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);\n}\n\n/**\n * Collect `field:hash` identity entries from provider metadata/options objects.\n * The namespace is deliberately omitted so the same identity mirrored under several\n * namespaces (e.g. `azure.itemId` and `openai.itemId`) yields one entry.\n * Output is sorted and de-duplicated so it is independent of key order and source order.\n */\nexport function getReasoningIdentityKeys(...sources: unknown[]): string[] {\n const keys = new Set<string>();\n for (const source of sources) {\n if (!isPlainObject(source)) continue;\n for (const block of Object.values(source)) {\n if (!isPlainObject(block)) continue;\n for (const [field, value] of Object.entries(block)) {\n if (typeof value !== 'string' || value.length === 0 || !IDENTITY_KEY.test(field)) continue;\n keys.add(`${field}:${hashIdentityValue(value)}`);\n }\n }\n }\n return [...keys].sort();\n}\n\nexport function appendReasoningIdentityKeys(cacheKey: string, ...sources: unknown[]): string {\n for (const identityKey of getReasoningIdentityKeys(...sources)) {\n cacheKey += `|${identityKey}`;\n }\n return cacheKey;\n}\n","/**\n * `JSON.stringify` with deterministic key ordering at every level.\n *\n * Required because object key order is preserved by `JSON.stringify`, and we\n * don't want `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` to hash to different keys.\n *\n * This is critical for cache key generation when comparing messages restored\n * from different storage backends: jsonb columns (e.g. mastra_workflow_snapshot\n * in PostgreSQL) normalize key order, while text columns (mastra_messages)\n * preserve insertion order. Without stable stringification, functionally-equal\n * data-* parts produce different cache keys, causing false dedup misses.\n */\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(value, (_key, val) => {\n if (val && typeof val === 'object' && !Array.isArray(val)) {\n // Use a null-prototype object so an own `__proto__` key is written as a\n // real own property instead of triggering the inherited Object.prototype\n // setter (which would silently drop it and collapse distinct values onto\n // one cache key).\n const sorted: Record<string, unknown> = Object.create(null);\n for (const k of Object.keys(val as Record<string, unknown>).sort()) {\n sorted[k] = (val as Record<string, unknown>)[k];\n }\n return sorted;\n }\n return val;\n });\n}\n","import type { UIMessage as UIMessageV4 } from '@internal/ai-sdk-v4';\nimport * as AIV5 from '@internal/ai-sdk-v5';\n\nimport { getImageCacheKey, resolveFilePartMediaTypeAndData } from '../prompt/image-utils';\nimport type { AIV5Type, CoreMessageV4 } from '../types';\nimport { getResponseProviderItemKeys } from '../utils/response-item-metadata';\nimport { appendReasoningIdentityKeys, hashIdentityValue } from './reasoning-identity';\nimport { stableStringify } from './stable-stringify';\nimport type { MastraMessagePart, UIMessageV4Part } from './types';\n\nfunction appendResponseProviderItemKeys(cacheKey: string, ...providerSources: unknown[]): string {\n const itemKeys = new Set(\n providerSources.flatMap(source => getResponseProviderItemKeys(source as Record<string, unknown> | undefined)),\n );\n\n for (const itemKey of itemKeys) {\n cacheKey += `|${itemKey}`;\n }\n\n return cacheKey;\n}\n\n/**\n * CacheKeyGenerator - Centralized cache key generation for message equality checks\n *\n * This class provides consistent cache key generation across all message formats,\n * which is critical for:\n * - Deduplication of messages\n * - Detecting when messages have been updated\n * - Comparing messages across different formats\n *\n * Cache key invariants:\n * - Same message content should always produce the same key\n * - Different content should produce different keys\n * - Provider metadata (e.g., OpenAI/Azure OpenAI text, reasoning, and tool itemId) must be included for proper distinction\n * - Reasoning identity held in any provider namespace (signatures, redacted data, item ids) is included,\n * so empty-text reasoning blocks from different steps stay distinct without provider-specific helpers\n */\nexport class CacheKeyGenerator {\n /**\n * Generate cache key from AIV4 UIMessage parts\n */\n static fromAIV4Parts(parts: UIMessageV4['parts']): string {\n let key = '';\n for (const part of parts) {\n key += part.type;\n key += CacheKeyGenerator.fromAIV4Part(part);\n }\n return key;\n }\n\n /**\n * Generate cache key from a single AIV4 UIMessage part\n */\n static fromAIV4Part(part: UIMessageV4['parts'][number]): string {\n let cacheKey = '';\n if (part.type === 'text') {\n cacheKey += part.text;\n cacheKey = appendResponseProviderItemKeys(cacheKey, (part as any).providerMetadata);\n }\n if (part.type === 'tool-invocation') {\n if (!part.toolInvocation) return cacheKey;\n cacheKey += part.toolInvocation.toolCallId;\n cacheKey += part.toolInvocation.state;\n }\n if (part.type === 'reasoning') {\n cacheKey += part.reasoning;\n cacheKey += (part.details ?? []).reduce((prev, current) => {\n if (current.type === 'text') {\n return prev + (current.text?.length ?? 0) + (current.signature?.length || 0);\n }\n return prev;\n }, 0);\n\n // OpenAI-compatible Responses providers send reasoning items (rs_...) inside\n // provider metadata itemId fields such as openai.itemId or azure.itemId.\n // When the reasoning text is empty, the default cache key logic produces \"reasoning0\"\n // for *all* reasoning parts. This makes distinct rs_ entries appear identical, so the\n // message-merging logic drops the latest reasoning item. The result is that subsequent\n // OpenAI-compatible calls fail with:\n //\n // \"Item 'fc_...' was provided without its required 'reasoning' item\"\n //\n // To fix this, we incorporate the provider itemId into the cache key so each\n // rs_ entry is treated as distinct.\n //\n // Note: We cast `part` to `any` here because the AI SDK's ReasoningUIPart V4 type does\n // NOT declare `providerMetadata` (even though Mastra attaches it at runtime). This\n // access is safe in JavaScript, but TypeScript cannot type it without augmentation,\n // so we intentionally narrow to `any` only for this metadata lookup.\n\n const partAny = part as any;\n\n if (partAny && Object.hasOwn(partAny, 'providerMetadata')) {\n cacheKey = appendResponseProviderItemKeys(cacheKey, partAny.providerMetadata);\n }\n\n // Other providers (Anthropic, Bedrock, Gemini, ...) carry reasoning identity such as\n // signatures or redacted data in metadata or in reasoning details. Fold it in generically.\n cacheKey = appendReasoningIdentityKeys(cacheKey, partAny?.providerMetadata);\n for (const detail of part.details ?? []) {\n const identity = detail.type === 'text' ? detail.signature : detail.data;\n if (identity) cacheKey += `|${detail.type}:${hashIdentityValue(identity)}`;\n }\n }\n if (part.type === 'file') {\n // Stored parts can be v5-shaped (`mediaType`/`url`) even though this union only\n // describes v4 (`mimeType`/`data`); both fields read as `undefined` otherwise,\n // collapsing distinct v5 file parts onto the same cache key. Mirrors #17366.\n const { mediaType, data } = resolveFilePartMediaTypeAndData(part);\n cacheKey += data;\n cacheKey += mediaType;\n }\n\n return cacheKey;\n }\n\n /**\n * Generate cache key from MastraDB message parts\n */\n static fromDBParts(parts: MastraMessagePart[]): string {\n let key = '';\n for (const part of parts) {\n key += part.type;\n if (part.type.startsWith('data-')) {\n // Stringify data for proper cache key comparison since data can be any type\n const data = (part as AIV5Type.DataUIPart<AIV5.UIDataTypes>).data;\n key += stableStringify(data); // order-independent: jsonb vs text storage may reorder keys\n } else {\n // Cast to UIMessageV4Part since we've already handled data-* parts above\n key += CacheKeyGenerator.fromAIV4Part(part as UIMessageV4Part);\n }\n }\n return key;\n }\n\n /**\n * Generate cache key from AIV4 CoreMessage content\n */\n static fromAIV4CoreMessageContent(content: CoreMessageV4['content']): string {\n if (typeof content === 'string') return content;\n let key = '';\n for (const part of content) {\n key += part.type;\n if (part.type === 'text') {\n key += part.text.length;\n const partAny = part as any;\n key = appendResponseProviderItemKeys(key, partAny.providerMetadata, partAny.providerOptions);\n }\n if (part.type === 'reasoning') {\n key += part.text.length;\n const partAny = part as any;\n key = appendResponseProviderItemKeys(key, partAny.providerMetadata, partAny.providerOptions);\n key = appendReasoningIdentityKeys(key, partAny.providerMetadata, partAny.providerOptions);\n if (part.signature) key += `|signature:${hashIdentityValue(part.signature)}`;\n }\n if (part.type === 'tool-call') {\n key += part.toolCallId;\n key += part.toolName;\n }\n if (part.type === 'tool-result') {\n key += part.toolCallId;\n key += part.toolName;\n }\n if (part.type === 'file') {\n key += part.filename;\n key += part.mimeType;\n }\n if (part.type === 'image') {\n key += getImageCacheKey(part.image);\n key += part.mimeType;\n }\n if (part.type === 'redacted-reasoning') {\n key += part.data.length;\n key += `|${hashIdentityValue(part.data)}`;\n }\n }\n return key;\n }\n\n /**\n * Generate cache key from AIV5 UIMessage parts\n */\n static fromAIV5Parts(parts: AIV5Type.UIMessage['parts']): string {\n let key = '';\n for (const part of parts) {\n key += part.type;\n if (part.type === 'text') {\n key += part.text;\n key = appendResponseProviderItemKeys(key, (part as any).providerMetadata);\n }\n if (AIV5.isToolUIPart(part) || part.type === 'dynamic-tool') {\n key += part.toolCallId;\n key += part.state;\n }\n if (part.type === 'reasoning') {\n key += part.text;\n key = appendResponseProviderItemKeys(key, (part as any).providerMetadata);\n key = appendReasoningIdentityKeys(key, (part as any).providerMetadata);\n }\n if (part.type === 'file') {\n key += part.url.length;\n key += part.mediaType;\n key += part.filename || '';\n }\n }\n return key;\n }\n\n /**\n * Generate cache key from AIV5 ModelMessage content\n */\n static fromAIV5ModelMessageContent(content: AIV5Type.ModelMessage['content']): string {\n if (typeof content === 'string') return content;\n let key = '';\n for (const part of content) {\n key += part.type;\n if (part.type === 'text') {\n key += part.text.length;\n key = appendResponseProviderItemKeys(key, (part as any).providerOptions);\n }\n if (part.type === 'reasoning') {\n key += part.text.length;\n key = appendResponseProviderItemKeys(key, (part as any).providerOptions);\n key = appendReasoningIdentityKeys(key, (part as any).providerOptions);\n }\n if (part.type === 'tool-call') {\n key += part.toolCallId;\n key += part.toolName;\n }\n if (part.type === 'tool-result') {\n key += part.toolCallId;\n key += part.toolName;\n }\n if (part.type === 'file') {\n key += part.filename;\n key += part.mediaType;\n }\n if (part.type === 'image') {\n key += getImageCacheKey(part.image);\n key += part.mediaType;\n }\n }\n return key;\n }\n}\n","import type { MastraMessageContentV2, MastraMessagePart } from '../agent/message-list/state/types';\n\nexport const WORKING_MEMORY_START_TAG = '<working_memory>';\nexport const WORKING_MEMORY_END_TAG = '</working_memory>';\n\nexport const SYSTEM_REMINDER_START_TAG = '<system-reminder>';\nexport const SYSTEM_REMINDER_END_TAG = '</system-reminder>';\n\n/**\n * Tool name used when working memory is delivered via the legacy system-message path.\n * This is the registry key in `Memory.listTools()` and therefore the `toolName` on the\n * wire when the LLM calls the tool.\n */\nexport const UPDATE_WORKING_MEMORY_TOOL_NAME = 'updateWorkingMemory';\n\n/**\n * Tool name used when working memory is delivered via state signals\n * (`workingMemory.useStateSignals: true`). The rename keeps legacy strip filters\n * — which look for `updateWorkingMemory` — from incidentally stripping the new\n * path's tool-call parts, so they persist as a normal audit trail.\n */\nexport const SET_WORKING_MEMORY_TOOL_NAME = 'setWorkingMemory';\n\n/**\n * All known working-memory tool names. Use this when you want to recognize the\n * tool regardless of delivery mode (e.g. to skip scoring on WM-only iterations\n * or detect that working memory was updated). Strip-style filters should NOT\n * use this — they should keep matching only `UPDATE_WORKING_MEMORY_TOOL_NAME`.\n */\nexport const WORKING_MEMORY_TOOL_NAMES = [UPDATE_WORKING_MEMORY_TOOL_NAME, SET_WORKING_MEMORY_TOOL_NAME] as const;\n\nexport function isWorkingMemoryToolName(name: string | undefined | null): boolean {\n return name === UPDATE_WORKING_MEMORY_TOOL_NAME || name === SET_WORKING_MEMORY_TOOL_NAME;\n}\n\n/*\n * Compatibility note: @mastra/memory intentionally copies the exported helpers\n * in this file into packages/memory/src/index.ts instead of importing them.\n * Its peer range permits older core versions that do not export these newer\n * names, and importing them can crash published memory builds during ESM\n * instantiation. Until v2 can tighten that peer contract, keep both sides\n * manually in sync.\n */\n\n/**\n * Extracts all working memory tag contents from text using indexOf-based parsing.\n * This avoids ReDoS vulnerability that exists with regex-based approaches.\n * @returns Array of full matches (including tags) or null if no matches\n */\nexport function extractWorkingMemoryTags(text: string): string[] | null {\n const results: string[] = [];\n let pos = 0;\n\n while (pos < text.length) {\n const start = text.indexOf(WORKING_MEMORY_START_TAG, pos);\n if (start === -1) break;\n\n const end = text.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);\n if (end === -1) break;\n\n results.push(text.substring(start, end + WORKING_MEMORY_END_TAG.length));\n pos = end + WORKING_MEMORY_END_TAG.length;\n }\n\n return results.length > 0 ? results : null;\n}\n\n/**\n * Removes all working memory tags and their contents from text.\n * Uses indexOf-based parsing to avoid ReDoS vulnerability.\n */\nexport function removeWorkingMemoryTags(text: string): string {\n let result = '';\n let pos = 0;\n\n while (pos < text.length) {\n const start = text.indexOf(WORKING_MEMORY_START_TAG, pos);\n if (start === -1) {\n result += text.substring(pos);\n break;\n }\n\n result += text.substring(pos, start);\n\n const end = text.indexOf(WORKING_MEMORY_END_TAG, start + WORKING_MEMORY_START_TAG.length);\n if (end === -1) {\n // No closing tag found, keep the rest as-is\n result += text.substring(start);\n break;\n }\n\n pos = end + WORKING_MEMORY_END_TAG.length;\n }\n\n return result;\n}\n\n/**\n * Extracts the content of the first working memory tag (without the tags themselves).\n * Uses indexOf-based parsing to avoid ReDoS vulnerability.\n * @returns The content between the tags, or null if no valid tag pair found\n */\nexport function extractWorkingMemoryContent(text: string): string | null {\n const start = text.indexOf(WORKING_MEMORY_START_TAG);\n if (start === -1) return null;\n\n const contentStart = start + WORKING_MEMORY_START_TAG.length;\n const end = text.indexOf(WORKING_MEMORY_END_TAG, contentStart);\n if (end === -1) return null;\n\n return text.substring(contentStart, end);\n}\n\n// Google's documented dummy signature for Gemini function calls without a real one.\nconst SKIP_THOUGHT_SIGNATURE_VALIDATOR = 'skip_thought_signature_validator';\n\n/**\n * Removes `updateWorkingMemory` tool invocations from stored message parts, one step\n * at a time. A step starts at a `step-start` part, or where a tool part is followed by\n * a non-tool part (the same boundary prompt conversion uses when markers are missing).\n * A step whose tool calls were all working-memory calls loses its tool-call/tool-result\n * boundary once they are removed. If only reasoning is left, the whole step is dropped:\n * replaying that signed reasoning merges it into the next step's assistant message,\n * which providers such as Anthropic reject (see #22798).\n */\nexport function removeWorkingMemoryToolInvocationParts(parts: MastraMessagePart[]): MastraMessagePart[] {\n const isWorkingMemoryCall = (part: MastraMessagePart) =>\n part?.type === 'tool-invocation' && part.toolInvocation?.toolName === UPDATE_WORKING_MEMORY_TOOL_NAME;\n\n if (!parts.some(isWorkingMemoryCall)) return parts;\n\n const steps: MastraMessagePart[][] = [];\n parts.forEach((part, i) => {\n const previous = parts[i - 1];\n const startsStep =\n part?.type === 'step-start' || (previous?.type === 'tool-invocation' && part?.type !== 'tool-invocation');\n if (startsStep || steps.length === 0) steps.push([]);\n steps[steps.length - 1]!.push(part);\n });\n\n return steps.flatMap(step => {\n if (!step.some(isWorkingMemoryCall)) return step;\n const remaining = step.filter(part => !isWorkingMemoryCall(part));\n // Gemini signs only the first call of a parallel step and rejects a replayed step\n // whose first call is unsigned. When the signed call was the working-memory call,\n // mark the first surviving call with Google's documented skip-validator signature\n // (#27231). The real signature is bound to the removed call, so it is not moved.\n // A signature already on the surviving call wins.\n const targetIndex = remaining.findIndex(part => part?.type === 'tool-invocation');\n const target = remaining[targetIndex];\n if (target?.type === 'tool-invocation') {\n let providerMetadata = target.providerMetadata;\n for (const removed of step) {\n if (!isWorkingMemoryCall(removed)) continue;\n for (const [provider, metadata] of Object.entries(removed.providerMetadata ?? {})) {\n if (metadata?.thoughtSignature === undefined) continue;\n if (providerMetadata?.[provider]?.thoughtSignature !== undefined) continue;\n providerMetadata = {\n ...providerMetadata,\n [provider]: { ...providerMetadata?.[provider], thoughtSignature: SKIP_THOUGHT_SIGNATURE_VALIDATOR },\n };\n }\n }\n if (providerMetadata !== target.providerMetadata) remaining[targetIndex] = { ...target, providerMetadata };\n }\n const onlyReasoningLeft = remaining.every(\n part =>\n part?.type === 'step-start' ||\n part?.type === 'reasoning' ||\n (part?.type === 'text' && !removeWorkingMemoryTags(part.text ?? '').trim()),\n );\n return onlyReasoningLeft ? [] : remaining;\n });\n}\n\n/**\n * Removes `updateWorkingMemory` entries from the legacy `toolInvocations` array so\n * prompt conversion cannot re-add a stripped working-memory call.\n */\nexport function removeWorkingMemoryToolInvocations(\n toolInvocations: MastraMessageContentV2['toolInvocations'],\n): MastraMessageContentV2['toolInvocations'] {\n if (!toolInvocations?.some(invocation => invocation.toolName === UPDATE_WORKING_MEMORY_TOOL_NAME)) {\n return toolInvocations;\n }\n const remaining = toolInvocations.filter(invocation => invocation.toolName !== UPDATE_WORKING_MEMORY_TOOL_NAME);\n return remaining.length > 0 ? remaining : undefined;\n}\n\n/**\n * Removes all system-reminder tags and their contents from text.\n * Uses indexOf-based parsing to avoid ReDoS vulnerability.\n *\n * Note: system-reminder tags can have attributes like `<system-reminder type=\"...\">`,\n * so we match from `<system-reminder` to the closing `>` for the start tag.\n */\nexport function removeSystemReminderTags(text: string): string {\n let result = '';\n let pos = 0;\n\n while (pos < text.length) {\n // Find start of tag (may have attributes)\n const startTagBegin = text.indexOf('<system-reminder', pos);\n if (startTagBegin === -1) {\n result += text.substring(pos);\n break;\n }\n\n result += text.substring(pos, startTagBegin);\n\n // Find end of opening tag (the closing >)\n const startTagEnd = text.indexOf('>', startTagBegin);\n if (startTagEnd === -1) {\n // Malformed tag, keep rest as-is\n result += text.substring(startTagBegin);\n break;\n }\n\n // Find closing tag\n const end = text.indexOf(SYSTEM_REMINDER_END_TAG, startTagEnd + 1);\n if (end === -1) {\n // No closing tag found, keep the rest as-is\n result += text.substring(startTagBegin);\n break;\n }\n\n pos = end + SYSTEM_REMINDER_END_TAG.length;\n }\n\n return result;\n}\n","import {\n removeWorkingMemoryTags,\n removeWorkingMemoryToolInvocationParts,\n removeWorkingMemoryToolInvocations,\n} from '../memory/working-memory-utils';\nimport { isTransientSignalMessage } from './signals';\nimport type { MastraDBMessage } from './types';\n\n/**\n * Filters messages before persisting to storage:\n * 1. Removes system messages - these are runtime instructions and should never be stored\n * 2. Removes transient signals (`transient: true`) - delivery-only, must never be retained\n * 3. Removes streaming tool calls (state === 'partial-call') - these are intermediate states\n * 4. Removes updateWorkingMemory tool invocations (hide args from message history)\n * 5. Strips <working_memory> tags from text content\n *\n * Note: We preserve 'call' state tool invocations because:\n * - For server-side tools, 'call' should have been converted to 'result' by the time OUTPUT is processed\n * - For client-side tools (no execute function), 'call' is the final state from the server's perspective\n */\nexport function filterMessagesForPersistence(messages: MastraDBMessage[]): MastraDBMessage[] {\n return messages\n .filter(m => m.role !== 'system' && !isTransientSignalMessage(m))\n .map(m => {\n const newMessage = { ...m };\n // Only spread content if it's a proper V2 object\n if (m.content && typeof m.content === 'object' && !Array.isArray(m.content)) {\n newMessage.content = { ...m.content };\n }\n\n // Strip working memory tags from string content\n if (typeof newMessage.content?.content === 'string' && newMessage.content.content.length > 0) {\n const cleanedContent = removeWorkingMemoryTags(newMessage.content.content);\n newMessage.content.content =\n cleanedContent !== newMessage.content.content ? cleanedContent.trim() : newMessage.content.content;\n }\n\n if (Array.isArray(newMessage.content?.parts)) {\n if (Array.isArray(newMessage.content.toolInvocations)) {\n newMessage.content.toolInvocations = removeWorkingMemoryToolInvocations(newMessage.content.toolInvocations);\n }\n // Filter out updateWorkingMemory tool invocations (hide args from message history)\n newMessage.content.parts = removeWorkingMemoryToolInvocationParts(newMessage.content.parts)\n .map(p => {\n // Filter out streaming tool calls (partial-call is an intermediate state during streaming)\n if (p.type === `tool-invocation` && p.toolInvocation.state === `partial-call`) {\n return null;\n }\n // Strip working memory tags from text parts\n if (p.type === `text`) {\n const text = typeof p.text === 'string' ? p.text : '';\n const cleaned = removeWorkingMemoryTags(text);\n return {\n ...p,\n text: cleaned !== text ? cleaned.trim() : text,\n };\n }\n return p;\n })\n .filter((p): p is NonNullable<typeof p> => Boolean(p));\n\n // If all parts were filtered out, skip the whole message\n if (newMessage.content.parts.length === 0) {\n return null;\n }\n }\n\n return newMessage;\n })\n .filter((m): m is NonNullable<typeof m> => Boolean(m));\n}\n","import type { CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\n\nimport { removeWorkingMemoryTags, removeWorkingMemoryToolInvocationParts } from '../../../memory/working-memory-utils';\nimport { filterMessagesForPersistence } from '../../filter-messages-for-persistence';\nimport { CacheKeyGenerator } from '../cache/CacheKeyGenerator';\nimport { TypeDetector } from '../detection/TypeDetector';\nimport type { MastraDBMessage, MastraMessagePart } from '../state/types';\nimport type { MessageInput } from '../types';\n\n/**\n * Convert CoreMessage content to a plain string.\n * Extracts text from text parts and concatenates them.\n */\nexport function coreContentToString(content: CoreMessageV4['content']): string {\n if (typeof content === `string`) return content;\n\n return content.reduce((p, c) => {\n if (c.type === `text`) {\n p += c.text;\n }\n return p;\n }, '');\n}\n\n/**\n * Compare two messages for equality based on their content.\n * Uses cache keys for efficient comparison across different message formats.\n */\nexport function messagesAreEqual(one: MessageInput, two: MessageInput): boolean {\n const oneUIV4 = TypeDetector.isAIV4UIMessage(one) && one;\n const twoUIV4 = TypeDetector.isAIV4UIMessage(two) && two;\n if (oneUIV4 && !twoUIV4) return false;\n if (oneUIV4 && twoUIV4) {\n return CacheKeyGenerator.fromAIV4Parts(one.parts) === CacheKeyGenerator.fromAIV4Parts(two.parts);\n }\n\n const oneCMV4 = TypeDetector.isAIV4CoreMessage(one) && one;\n const twoCMV4 = TypeDetector.isAIV4CoreMessage(two) && two;\n if (oneCMV4 && !twoCMV4) return false;\n if (oneCMV4 && twoCMV4) {\n return (\n CacheKeyGenerator.fromAIV4CoreMessageContent(oneCMV4.content) ===\n CacheKeyGenerator.fromAIV4CoreMessageContent(twoCMV4.content)\n );\n }\n\n const oneMM1 = TypeDetector.isMastraMessageV1(one) && one;\n const twoMM1 = TypeDetector.isMastraMessageV1(two) && two;\n if (oneMM1 && !twoMM1) return false;\n if (oneMM1 && twoMM1) {\n return (\n oneMM1.id === twoMM1.id &&\n CacheKeyGenerator.fromAIV4CoreMessageContent(oneMM1.content) ===\n CacheKeyGenerator.fromAIV4CoreMessageContent(twoMM1.content)\n );\n }\n\n const oneMM2 = TypeDetector.isMastraDBMessage(one) && one;\n const twoMM2 = TypeDetector.isMastraDBMessage(two) && two;\n if (oneMM2 && !twoMM2) return false;\n if (oneMM2 && twoMM2) {\n return (\n oneMM2.id === twoMM2.id &&\n CacheKeyGenerator.fromDBParts(oneMM2.content.parts) === CacheKeyGenerator.fromDBParts(twoMM2.content.parts)\n );\n }\n\n const oneUIV5 = TypeDetector.isAIV5UIMessage(one) && one;\n const twoUIV5 = TypeDetector.isAIV5UIMessage(two) && two;\n if (oneUIV5 && !twoUIV5) return false;\n if (oneUIV5 && twoUIV5) {\n return CacheKeyGenerator.fromAIV5Parts(one.parts) === CacheKeyGenerator.fromAIV5Parts(two.parts);\n }\n\n const oneCMV5 = TypeDetector.isAIV5CoreMessage(one) && one;\n const twoCMV5 = TypeDetector.isAIV5CoreMessage(two) && two;\n if (oneCMV5 && !twoCMV5) return false;\n if (oneCMV5 && twoCMV5) {\n return (\n CacheKeyGenerator.fromAIV5ModelMessageContent(oneCMV5.content) ===\n CacheKeyGenerator.fromAIV5ModelMessageContent(twoCMV5.content)\n );\n }\n\n // default to it did change. we'll likely never reach this codepath\n return true;\n}\n\n/**\n * The parts as memory persists them: `updateWorkingMemory` tool steps removed, and\n * `<working_memory>` tags and surrounding whitespace stripped from text.\n */\nfunction projectPartsForPersistence(parts: MastraMessagePart[]): MastraMessagePart[] {\n return removeWorkingMemoryToolInvocationParts(parts).map(part =>\n part.type === 'text'\n ? { ...part, text: removeWorkingMemoryTags(typeof part.text === 'string' ? part.text : '').trim() }\n : part,\n );\n}\n\n/**\n * Whether `stored` is the persisted copy of `live`: the same id, and the same parts once\n * both go through the cleanup memory applies when it saves a message. That cleanup makes\n * `messagesAreEqual` treat a stored copy as a different message, for example when the live\n * text ends in a newline.\n *\n * Saves through `MessageHistory` (observational memory's buffering) and the agent's save\n * queue first run `filterMessagesForPersistence`, which also drops streaming `partial-call`\n * tool parts, so the live message is matched with and without that filter.\n */\nexport function isPersistedCopy(live: MastraDBMessage, stored: MastraDBMessage): boolean {\n if (live.id !== stored.id) return false;\n const storedKey = CacheKeyGenerator.fromDBParts(projectPartsForPersistence(stored.content.parts));\n const [filteredLive] = filterMessagesForPersistence([live]);\n return [live, filteredLive].some(\n candidate =>\n candidate !== undefined &&\n CacheKeyGenerator.fromDBParts(projectPartsForPersistence(candidate.content.parts)) === storedKey,\n );\n}\n","import type { MastraDBMessage, MastraMessagePart, MessageSource } from '../state/types';\n\nexport function stampPart<T extends MastraMessagePart>(part: T): T {\n if (part.createdAt == null) part.createdAt = Date.now();\n return part;\n}\n\nexport function stampMessageParts<T extends MastraDBMessage>(message: T, source: MessageSource): T {\n if (source === 'memory' || !Array.isArray(message.content.parts)) {\n return message;\n }\n\n message.content.parts = message.content.parts.map(part => stampPart(part));\n return message;\n}\n\ntype ToolInvocationPart = Extract<MastraMessagePart, { type: 'tool-invocation' }>;\n\n/**\n * Stamps `updatedAt` on a tool part whose invocation changed. A merge that\n * repeats the same state keeps its stamp, so replay dedupe doesn't drop newer parts.\n */\nexport function stampToolPartUpdate(\n part: ToolInvocationPart,\n before: ToolInvocationPart['toolInvocation'],\n incomingUpdatedAt?: number,\n): void {\n if (incomingUpdatedAt !== undefined) {\n part.updatedAt = incomingUpdatedAt;\n return;\n }\n if (part.updatedAt !== undefined && JSON.stringify(before) === JSON.stringify(part.toolInvocation)) return;\n part.updatedAt = Date.now();\n}\n","import type { CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\n\nimport { AIV4Adapter, AIV5Adapter, AIV6Adapter } from '../adapters';\nimport { TypeDetector } from '../detection/TypeDetector';\nimport type { MastraDBMessage, MastraMessageV1, MessageSource, MemoryInfo } from '../state/types';\nimport type { MessageInput } from '../types';\nimport { stampMessageParts } from '../utils/stamp-part';\n\n/**\n * Context required for input conversion functions.\n * This is passed from MessageList to provide access to instance-specific utilities.\n */\nexport interface InputConversionContext {\n memoryInfo: MemoryInfo | null;\n newMessageId: () => string;\n generateCreatedAt: (messageSource: MessageSource, start?: unknown) => Date;\n /** Messages array for looking up tool call args */\n dbMessages: MastraDBMessage[];\n}\n\n/**\n * Convert any supported message input format to MastraDBMessage.\n * Routes to the appropriate converter based on message type detection.\n */\nexport function inputToMastraDBMessage(\n message: MessageInput,\n messageSource: MessageSource,\n context: InputConversionContext,\n): MastraDBMessage {\n // Validate threadId matches (except for memory messages which can come from other threads)\n if (\n messageSource !== `memory` &&\n `threadId` in message &&\n message.threadId &&\n context.memoryInfo &&\n message.threadId !== context.memoryInfo.threadId\n ) {\n throw new Error(\n `Received input message with wrong threadId. Input ${message.threadId}, expected ${context.memoryInfo.threadId}`,\n );\n }\n\n // Validate resourceId matches (except for memory messages, which can carry a\n // system resourceId — e.g. observational-memory continuation messages)\n if (\n messageSource !== `memory` &&\n `resourceId` in message &&\n message.resourceId &&\n context.memoryInfo?.resourceId &&\n message.resourceId !== context.memoryInfo.resourceId\n ) {\n throw new Error(\n `Received input message with wrong resourceId. Input ${message.resourceId}, expected ${context.memoryInfo.resourceId}`,\n );\n }\n\n if (TypeDetector.isMastraMessageV1(message)) {\n return stampMessageParts(mastraMessageV1ToMastraDBMessage(message, messageSource, context), messageSource);\n }\n if (TypeDetector.isMastraDBMessage(message)) {\n return stampMessageParts(hydrateMastraDBMessageFields(message, context, messageSource), messageSource);\n }\n if (TypeDetector.isAIV4CoreMessage(message)) {\n return stampMessageParts(AIV4Adapter.fromCoreMessage(message, context, messageSource), messageSource);\n }\n if (TypeDetector.isAIV4UIMessage(message)) {\n return stampMessageParts(AIV4Adapter.fromUIMessage(message, context, messageSource), messageSource);\n }\n\n // Use custom ID generator if message doesn't have an ID, otherwise keep the original\n const hasOriginalId = 'id' in message && typeof message.id === 'string';\n const id = hasOriginalId ? message.id : context.newMessageId();\n\n if (TypeDetector.isAIV6CoreMessage(message)) {\n const dbMsg = AIV6Adapter.fromModelMessage(message, messageSource, context);\n const rawCreatedAt =\n 'metadata' in message &&\n message.metadata &&\n typeof message.metadata === 'object' &&\n 'createdAt' in message.metadata\n ? message.metadata.createdAt\n : undefined;\n return {\n ...dbMsg,\n id,\n createdAt: context.generateCreatedAt(messageSource, rawCreatedAt),\n threadId: context.memoryInfo?.threadId,\n resourceId: context.memoryInfo?.resourceId,\n };\n }\n if (TypeDetector.isAIV6UIMessage(message)) {\n const dbMsg = AIV6Adapter.fromUIMessage(message);\n const rawCreatedAt = 'createdAt' in message ? message.createdAt : undefined;\n return {\n ...dbMsg,\n id,\n createdAt: context.generateCreatedAt(messageSource, rawCreatedAt),\n threadId: context.memoryInfo?.threadId,\n resourceId: context.memoryInfo?.resourceId,\n };\n }\n\n if (TypeDetector.isAIV5CoreMessage(message)) {\n const dbMsg = AIV5Adapter.fromModelMessage(message, messageSource, context);\n // Only use the original createdAt from input message metadata, not the generated one from the static method\n // This fixes issue #10683 where messages without createdAt would get shuffled\n const rawCreatedAt =\n 'metadata' in message &&\n message.metadata &&\n typeof message.metadata === 'object' &&\n 'createdAt' in message.metadata\n ? message.metadata.createdAt\n : undefined;\n return stampMessageParts(\n {\n ...dbMsg,\n id,\n createdAt: context.generateCreatedAt(messageSource, rawCreatedAt),\n threadId: context.memoryInfo?.threadId,\n resourceId: context.memoryInfo?.resourceId,\n },\n messageSource,\n );\n }\n if (TypeDetector.isAIV5UIMessage(message)) {\n const dbMsg = AIV5Adapter.fromUIMessage(message);\n // Only use the original createdAt from input message, not the generated one from the static method\n // This fixes issue #10683 where messages without createdAt would get shuffled\n const rawCreatedAt = 'createdAt' in message ? message.createdAt : undefined;\n return stampMessageParts(\n {\n ...dbMsg,\n id,\n createdAt: context.generateCreatedAt(messageSource, rawCreatedAt),\n threadId: context.memoryInfo?.threadId,\n resourceId: context.memoryInfo?.resourceId,\n },\n messageSource,\n );\n }\n\n throw new Error(`Found unhandled message ${JSON.stringify(message)}`);\n}\n\n/**\n * Convert MastraMessageV1 format to MastraDBMessage.\n */\nexport function mastraMessageV1ToMastraDBMessage(\n message: MastraMessageV1,\n messageSource: MessageSource,\n context: InputConversionContext,\n): MastraDBMessage {\n const coreV2 = AIV4Adapter.fromCoreMessage(\n {\n content: message.content,\n role: message.role,\n } as CoreMessageV4,\n context,\n messageSource,\n );\n\n return {\n id: message.id,\n role: coreV2.role,\n createdAt: context.generateCreatedAt(messageSource, message.createdAt),\n threadId: message.threadId,\n resourceId: message.resourceId,\n content: coreV2.content,\n };\n}\n\n/**\n * Hydrate a MastraDBMessage with missing fields (id, createdAt, threadId, resourceId).\n * Also fixes toolInvocations with empty args by looking in the parts array.\n */\nexport function hydrateMastraDBMessageFields(\n message: MastraDBMessage,\n context: InputConversionContext,\n messageSource: MessageSource,\n): MastraDBMessage {\n message.content.parts = Array.isArray(message.content.parts)\n ? message.content.parts.filter(part => part !== null && typeof part === 'object')\n : [];\n\n // Generate ID if missing\n if (!message.id) {\n message.id = context.newMessageId();\n }\n\n if (message.createdAt === undefined || message.createdAt === null) {\n message.createdAt = context.generateCreatedAt(messageSource);\n } else if (!(message.createdAt instanceof Date)) {\n message.createdAt = new Date(message.createdAt);\n }\n\n // Fix toolInvocations with empty args by looking in the parts array\n // This handles messages restored from database where toolInvocations might have lost their args\n if (message.content.toolInvocations && message.content.parts) {\n message.content.toolInvocations = message.content.toolInvocations.map(ti => {\n if (!ti.args || Object.keys(ti.args).length === 0) {\n // Find the corresponding tool-invocation part with args\n const partWithArgs = message.content.parts.find(\n part =>\n part.type === 'tool-invocation' &&\n part.toolInvocation &&\n part.toolInvocation.toolCallId === ti.toolCallId &&\n part.toolInvocation.args &&\n Object.keys(part.toolInvocation.args).length > 0,\n );\n if (partWithArgs && partWithArgs.type === 'tool-invocation') {\n return { ...ti, args: partWithArgs.toolInvocation.args };\n }\n }\n return ti;\n });\n }\n\n if (!message.threadId && context.memoryInfo?.threadId) {\n message.threadId = context.memoryInfo.threadId;\n }\n\n if (!message.resourceId && context.memoryInfo?.resourceId) {\n message.resourceId = context.memoryInfo.resourceId;\n }\n\n return message;\n}\n","import { convertToCoreMessages as convertToCoreMessagesV4 } from '@internal/ai-sdk-v4';\nimport type { CoreMessage as CoreMessageV4, UIMessage as UIMessageV4 } from '@internal/ai-sdk-v4';\nimport * as AIV5 from '@internal/ai-sdk-v5';\n\nimport { deepEqual } from '../../../utils/deep-equal';\nimport { AIV4Adapter, AIV5Adapter, AIV6Adapter } from '../adapters';\nimport type { AdapterContext } from '../adapters';\nimport { TypeDetector } from '../detection/TypeDetector';\nimport { categorizeFileData } from '../prompt/image-utils';\nimport type { MastraDBMessage, MessageSource } from '../state/types';\nimport type { AIV5Type, AIV6Type } from '../types';\nimport {\n ensureAnthropicCompatibleMessages,\n pairOrphanedToolCalls,\n sanitizeOrphanedToolPairs,\n} from '../utils/provider-compat';\nimport {\n getResponseProviderItemId,\n getResponseProviderItemKey,\n getResponseResultItemId,\n RESPONSE_ITEM_ID_PROVIDERS,\n RESPONSE_RESULT_ITEM_ID_KEY,\n} from '../utils/response-item-metadata';\nimport { normalizeToolOutput } from '../utils/unwrap-legacy-tool-output';\n\n/**\n * Merges text parts that share the same OpenAI-compatible itemId.\n *\n * When OpenAI streams a response with web search, it interleaves `source` chunks\n * with text-deltas. If the streaming pipeline flushes text on these source chunks,\n * it creates multiple text parts all sharing the same `providerMetadata.openai.itemId`.\n *\n * When these parts are later converted to model messages, each part with an itemId\n * becomes an `item_reference` pointing to the same ID, causing OpenAI to reject\n * the request with: \"Duplicate item found with id msg_*\"\n *\n * This function merges consecutive text parts with the same itemId into a single part,\n * allowing source annotations between those text flushes, concatenating their text\n * content, and keeping the metadata from the first part.\n */\nfunction isTextMergePassThroughPart(part: { type: string }): boolean {\n // Only source annotations are transparent for text-item merging. Tool,\n // reasoning, file, and step parts are merge boundaries.\n return part.type.startsWith('source-');\n}\n\nfunction mergeTextPartsWithDuplicateItemIds<T extends { type: string }>(parts: T[]): T[] {\n const result: T[] = [];\n\n for (const part of parts) {\n // Only process text parts with OpenAI-compatible itemId\n if (part.type !== 'text') {\n result.push(part);\n continue;\n }\n\n const textPart = part as T & { text: string; providerMetadata?: Record<string, unknown> };\n const itemId = getResponseProviderItemKey(textPart.providerMetadata);\n if (!itemId) {\n result.push(part);\n continue;\n }\n\n let merged = false;\n for (let index = result.length - 1; index >= 0; index--) {\n const previous = result[index]!;\n if (previous.type === 'text') {\n const previousTextPart = previous as T & { text: string; providerMetadata?: Record<string, unknown> };\n const previousItemId = getResponseProviderItemKey(previousTextPart.providerMetadata);\n\n if (previousItemId === itemId) {\n result[index] = {\n ...previousTextPart,\n text: previousTextPart.text + textPart.text,\n };\n merged = true;\n }\n\n break;\n }\n\n if (!isTextMergePassThroughPart(previous)) {\n break;\n }\n }\n\n if (merged) {\n continue;\n }\n\n result.push(part);\n }\n\n return result;\n}\n\n/**\n * Detects a hosted OpenAI `tool_search` part that can no longer be replayed.\n *\n * A hosted (provider-executed) `tool_search` call only replays as a pair of\n * `item_reference`s built from its Responses item ids. When those ids are\n * gone (e.g. a UI round-trip stripped providerMetadata), the provider instead\n * rebuilds a full `tool_search_call` without its required `arguments` and an\n * orphaned `function_call_output` — both rejected by the API. Such parts are\n * dropped from prompts; the model re-discovers tools on the next turn.\n *\n * A COMPLETED hosted search needs both ids — the call's and the output's. History\n * persisted before the two were kept apart carries only one (whichever half wrote\n * last), which conversion then copies onto both model parts, producing the same\n * `item_reference` twice (\"Duplicate item found\"). One id is therefore as\n * unreplayable as none. An in-flight call has no output yet, so its call id alone\n * is complete.\n *\n * Client-executed `tool_search` (non-null `call_id` in the input) replays as\n * a plain function call and is never dropped here.\n */\nfunction isUnreplayableHostedToolSearchPart(part: AIV5Type.ToolUIPart): boolean {\n if (AIV5.getToolName(part) !== 'tool_search') return false;\n\n // Only a provider-executed search replays by item reference. A user-defined tool\n // that happens to be named `tool_search` is an ordinary client function call on\n // every provider, so it must survive even though it carries no item ids.\n if (!part.providerExecuted) return false;\n\n const callProviderMetadata =\n 'callProviderMetadata' in part ? (part.callProviderMetadata as Record<string, unknown> | undefined) : undefined;\n const callItem = getResponseProviderItemId(callProviderMetadata);\n if (callItem) {\n // Both completed states emit a tool-call AND a tool-result, each carrying the\n // part's call metadata, so a lone id lands on both. An in-flight call emits no\n // result part, so its call id alone is complete.\n const isCompleted = part.state === 'output-available' || part.state === 'output-error';\n // Read the result id from the same namespace the call id came from -\n // getResponseProviderItemId picks one namespace, and a pair stored under a\n // DIFFERENT namespace does not make this id replayable.\n if (!isCompleted || getResponseResultItemId(callProviderMetadata, callItem.provider)) return false;\n }\n\n const input = part.input;\n if (input && typeof input === 'object' && typeof (input as Record<string, unknown>).call_id === 'string') {\n return false;\n }\n\n return true;\n}\n\n/**\n * Splits merged Responses item ids back onto their own tool parts.\n *\n * A stored tool part holds the result's item id under `resultItemId` when it\n * differs from the call's (see {@link RESPONSE_RESULT_ITEM_ID_KEY}), and UI →\n * model conversion copies the same metadata onto both the tool-call and the\n * tool-result part. Rewrite each side to carry only its own id — call keeps\n * `itemId`, result gets `resultItemId` as its `itemId` — so the provider emits\n * two distinct `item_reference`s instead of the same one twice (\"Duplicate\n * item found\").\n */\nfunction splitResponsesToolItemReferences(modelMessages: AIV5Type.ModelMessage[]): AIV5Type.ModelMessage[] {\n return modelMessages.map(msg => {\n if (typeof msg.content === 'string') return msg;\n\n let modified = false;\n const content = msg.content.map(part => {\n if (part.type !== 'tool-call' && part.type !== 'tool-result') return part;\n const providerOptions = (part as { providerOptions?: Record<string, Record<string, unknown>> }).providerOptions;\n if (!providerOptions) return part;\n\n let rewritten: Record<string, Record<string, unknown>> | undefined;\n const split = new Set<string>();\n for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n const namespace = providerOptions[provider];\n if (!namespace) continue;\n const resultItemId = namespace[RESPONSE_RESULT_ITEM_ID_KEY];\n if (typeof resultItemId !== 'string') continue;\n\n const { [RESPONSE_RESULT_ITEM_ID_KEY]: _removed, ...rest } = namespace;\n split.add(provider);\n rewritten = {\n ...(rewritten ?? providerOptions),\n [provider]: part.type === 'tool-result' ? { ...rest, itemId: resultItemId } : rest,\n };\n }\n if (!rewritten) return part;\n\n // A namespace with no `resultItemId` has one id for both halves of the\n // pair. On the call part that is correct; on the result part it is the\n // call's id a second time (\"Duplicate item found\"), so drop it and let\n // the split namespace carry the reference.\n if (part.type === 'tool-result') {\n for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n if (split.has(provider)) continue;\n const leftover: Record<string, unknown> | undefined = rewritten[provider];\n if (typeof leftover?.itemId !== 'string') continue;\n const { itemId: _duplicate, ...withoutItemId } = leftover;\n rewritten = { ...rewritten, [provider]: withoutItemId };\n }\n }\n\n modified = true;\n return { ...part, providerOptions: rewritten } as typeof part;\n });\n\n return modified ? ({ ...msg, content } as AIV5Type.ModelMessage) : msg;\n });\n}\n\n/**\n * Sanitizes AIV4 UI messages by filtering out incomplete tool calls.\n * Removes messages with empty parts arrays after sanitization.\n */\nexport function sanitizeAIV4UIMessages(messages: UIMessageV4[]): UIMessageV4[] {\n const msgs = messages\n .map(m => {\n if (m.parts.length === 0) return false;\n const safeParts = m.parts.filter(p => {\n // Mastra-only record of a terminal failure. It exists for DB/UI history\n // and must never reach a provider. Cast because the v4 UI part union has\n // no `error` member even though the adapter passes the part through.\n if ((p as { type: string }).type === 'error') return false;\n\n return (\n p.type !== `tool-invocation` ||\n // calls and partial-calls should be updated to be results at this point\n // if they haven't we can't send them back to the llm and need to remove them.\n (p.toolInvocation.state !== `call` && p.toolInvocation.state !== `partial-call`)\n );\n });\n\n // fully remove this message if it has an empty parts array after stripping out incomplete tool calls.\n if (!safeParts.length) return false;\n\n const sanitized = {\n ...m,\n parts: safeParts,\n };\n\n // ensure toolInvocations are also updated to only show results\n if (`toolInvocations` in m && m.toolInvocations) {\n sanitized.toolInvocations = m.toolInvocations.filter(t => t.state === `result`);\n }\n\n return sanitized;\n })\n .filter((m): m is UIMessageV4 => Boolean(m));\n return msgs;\n}\n\n/**\n * Sanitizes AIV5 UI messages by filtering out streaming states, data-* parts, empty text parts, and optionally incomplete tool calls.\n * Handles legacy data by filtering empty text parts that may exist in pre-existing DB records.\n */\nexport function sanitizeV5UIMessages(\n messages: AIV5Type.UIMessage[],\n mode: ToolCallConversionMode = 'response',\n): AIV5Type.UIMessage[] {\n // Precompute the index of the last user message. A deferred provider-executed\n // tool call (e.g. Anthropic non-deterministically defers web_search across\n // steps N→N+1 within the same run) may legitimately carry `input-available`\n // state ONLY on the most recent surviving assistant message, AND only if no\n // user turn has followed it. On any earlier assistant turn (or after a later\n // user message) an unresolved provider-executed call is an orphan — provider\n // dropped the result chunk (#15668), run aborted mid-stream (#14148), or a\n // stale call from an earlier step (#14192) — and must be dropped to keep the\n // tool-call/tool-result invariant.\n let lastUserIdx = -1;\n for (let i = messages.length - 1; i >= 0; i--) {\n if (messages[i]!.role === 'user') {\n lastUserIdx = i;\n break;\n }\n }\n\n const getSafeParts = (m: AIV5Type.UIMessage, assistantTurnStillOpen: boolean) =>\n m.parts.filter(p => {\n // Filter out data-* parts (custom streaming data from writer.custom())\n // These are Mastra extensions not supported by LLM providers.\n // If not filtered, convertToModelMessages produces empty content arrays\n // which causes some models to fail with \"must include at least one parts field\"\n if (typeof p.type === 'string' && p.type.startsWith('data-')) {\n return false;\n }\n\n // Filter out Mastra-only `error` parts (persisted terminal-failure records).\n // Like data-* parts they are not provider content: an error-only assistant\n // message therefore drops out below instead of reaching the model as an\n // empty turn. Cast because the v5 UI part union has no `error` member even\n // though the adapter passes the part through.\n if ((p as { type: string }).type === 'error') {\n return false;\n }\n\n // Filter out empty text parts to handle legacy data from before this filtering was implemented.\n // For assistant messages, preserve empty text parts if they are the only parts (placeholder messages).\n // For user messages, always filter them out — Anthropic rejects empty user text content blocks.\n if (p.type === 'text' && (!('text' in p) || p.text === '' || p.text?.trim() === '')) {\n // Always filter empty text parts from user messages\n if (m.role === 'user') return false;\n\n // For non-user messages, only filter if there are other non-empty parts\n const hasNonEmptyParts = m.parts.some(\n part => !(part.type === 'text' && (!('text' in part) || part.text === '' || part.text?.trim() === '')),\n );\n if (hasNonEmptyParts) return false;\n }\n\n if (!AIV5.isToolUIPart(p)) return true;\n\n // When sending messages TO the LLM: keep completed tool calls and provider-executed tools.\n // Filter out incomplete client-side tool calls (input-available without providerExecuted)\n // and input-streaming states.\n if (mode !== 'response') {\n // Hosted tool_search parts whose Responses item ids were lost cannot be\n // replayed in any state — drop them before the state-based checks below.\n if (isUnreplayableHostedToolSearchPart(p)) return false;\n\n // Completed tools (client or provider) — keep them\n if (p.state === 'output-available' || p.state === 'output-error') return true;\n if (p.state === 'input-available') {\n // Provider-executed tools may be deferred by the provider (e.g. Anthropic non-deterministically\n // defers web_search when mixed with client tool calls). Keep these so the provider API sees\n // the server_tool_use block on the next request — but ONLY on the most recent surviving\n // assistant message. On any earlier assistant turn an unresolved provider-executed call is\n // an orphan (provider dropped the result chunk, or the run aborted mid-stream) and must be\n // dropped to keep the tool-call/tool-result invariant required by provider APIs. See #15668, #14148.\n // This holds whichever way the caller configured suspended tool calls — the provider decides\n // when it resumes its own call, not the caller.\n if (p.providerExecuted) return assistantTurnStillOpen;\n // Client-side suspended calls are kept only when the caller asked to see them. They are\n // paired with a pending result downstream so the prompt stays valid.\n return mode === 'prompt-with-suspended';\n }\n return false;\n }\n\n // When processing response messages FROM the LLM: keep input-available states\n // (tool calls waiting for client-side execution) but filter out input-streaming\n return p.state !== 'input-streaming';\n });\n\n let lastSurvivingAssistantIdx = -1;\n if (lastUserIdx !== messages.length - 1) {\n for (let i = messages.length - 1; i > lastUserIdx; i--) {\n const message = messages[i]!;\n if (message.role !== 'assistant' || message.parts.length === 0) continue;\n if (getSafeParts(message, true).length > 0) {\n lastSurvivingAssistantIdx = i;\n break;\n }\n }\n }\n\n const msgs = messages\n .map((m, idx) => {\n if (m.parts.length === 0) return false;\n\n // Deferred-provider-tool behavior is ONLY valid on the most recent surviving\n // assistant message AND only when no user turn has followed it.\n const assistantTurnStillOpen = m.role === 'assistant' && idx === lastSurvivingAssistantIdx;\n\n // Filter out streaming states and optionally input-available (which aren't supported by convertToModelMessages)\n const safeParts = getSafeParts(m, assistantTurnStillOpen);\n\n if (!safeParts.length) return false;\n\n // Merge text parts with duplicate OpenAI-compatible itemIds to prevent \"Duplicate item found\" errors.\n // This can happen when streaming flushes text multiple times for the same response\n // (e.g., when source citations are interleaved with text-deltas).\n const mergedParts = mergeTextPartsWithDuplicateItemIds(safeParts);\n\n const sanitized = {\n ...m,\n parts: mergedParts.map(part => {\n if (AIV5.isToolUIPart(part) && part.state === 'output-available') {\n return {\n ...part,\n // Preserve the AI SDK's native multimodal content wrapper here.\n // convertToModelMessages stringifies the raw array if it is unwrapped.\n // See: https://github.com/mastra-ai/mastra/issues/17876\n output: normalizeToolOutput(part.output, { unwrapContent: false }).output,\n };\n }\n return part;\n }),\n };\n\n return sanitized;\n })\n .filter((m): m is AIV5Type.UIMessage => Boolean(m));\n return msgs;\n}\n\n/**\n * Adds step-start parts between tool parts and non-tool parts for proper AIV5 message conversion.\n * This ensures AIV5.convertToModelMessages produces the correct message order.\n */\nexport function addStartStepPartsForAIV5(messages: AIV5Type.UIMessage[]): AIV5Type.UIMessage[] {\n for (const message of messages) {\n if (message.role !== `assistant`) continue;\n for (const [index, part] of message.parts.entries()) {\n if (!AIV5.isToolUIPart(part)) continue;\n const nextPart = message.parts.at(index + 1);\n // If we don't insert step-start between tools and other parts, AIV5.convertToModelMessages will incorrectly add extra tool parts in the wrong order\n // ex: ui message with parts: [tool-result, text] becomes [assistant-message-with-both-parts, tool-result-message], when it should become [tool-call-message, tool-result-message, text-message]\n // However, we should NOT add step-start between consecutive tool parts (parallel tool calls)\n if (nextPart && nextPart.type !== `step-start` && !AIV5.isToolUIPart(nextPart)) {\n message.parts.splice(index + 1, 0, { type: 'step-start' });\n }\n\n // Split client tools from completed provider-executed tools.\n // Anthropic requires tool_result to immediately follow tool_use. When a client tool_use and\n // a server_tool_use (with inline result) are in the same block, convertToModelMessages produces:\n // assistant: [tool_use(client), server_tool_use(provider), tool_result(provider)]\n // user: [tool_result(client)]\n // Anthropic rejects this because tool_result(client) doesn't immediately follow tool_use(client).\n // Splitting them into separate blocks fixes the ordering.\n if (\n nextPart &&\n AIV5.isToolUIPart(nextPart) &&\n !part.providerExecuted &&\n nextPart.providerExecuted &&\n (nextPart.state === 'output-available' || nextPart.state === 'output-error')\n ) {\n message.parts.splice(index + 1, 0, { type: 'step-start' });\n }\n }\n }\n return messages;\n}\n\n/**\n * Converts AIV4 UI messages to AIV4 Core messages.\n *\n * Provider file IDs (e.g. OpenAI Files API \"file-...\") stored in\n * `experimental_attachments` would make AI SDK v4's internal `attachmentsToParts`\n * throw `Invalid URL: file-...` inside `convertToCoreMessages`. Strip them before\n * conversion and re-append them as file parts on the resulting user core message\n * so the IDs survive untouched.\n */\nexport function aiV4UIMessagesToAIV4CoreMessages(messages: UIMessageV4[]): CoreMessageV4[] {\n const sanitized = sanitizeAIV4UIMessages(messages);\n\n type AttachmentV4 = NonNullable<UIMessageV4['experimental_attachments']>[number];\n // Keyed by the user message's position among user messages: each user UI message\n // converts to exactly one user core message, in order.\n const fileIdAttachmentsByUserIndex = new Map<number, AttachmentV4[]>();\n let userIndex = 0;\n\n const prepared = sanitized.map(m => {\n if (m.role !== 'user') return m;\n const currentUserIndex = userIndex++;\n\n if (!m.experimental_attachments?.length) return m;\n\n const fileIdAttachments = m.experimental_attachments.filter(\n a => categorizeFileData(a.url, a.contentType).type === 'providerFileId',\n );\n if (!fileIdAttachments.length) return m;\n\n fileIdAttachmentsByUserIndex.set(currentUserIndex, fileIdAttachments);\n const remaining = m.experimental_attachments.filter(a => !fileIdAttachments.includes(a));\n return {\n ...m,\n experimental_attachments: remaining.length ? remaining : undefined,\n };\n });\n\n const coreMessages = convertToCoreMessagesV4(prepared);\n if (!fileIdAttachmentsByUserIndex.size) return coreMessages;\n\n let coreUserIndex = 0;\n return coreMessages.map(coreMessage => {\n if (coreMessage.role !== 'user') return coreMessage;\n const fileIdAttachments = fileIdAttachmentsByUserIndex.get(coreUserIndex++);\n if (!fileIdAttachments) return coreMessage;\n\n const fileParts = fileIdAttachments.map(a => ({\n type: 'file' as const,\n data: a.url,\n mimeType: a.contentType || 'application/octet-stream',\n }));\n const existingContent =\n typeof coreMessage.content === 'string'\n ? [{ type: 'text' as const, text: coreMessage.content }]\n : coreMessage.content;\n\n return {\n ...coreMessage,\n content: [...existingContent, ...fileParts],\n };\n });\n}\n\n/**\n * Converts MCP-style tool results (`{ content: [...] }`) to model-native\n * multimodal tool result output without persisting a duplicate modelOutput copy.\n * Media is emitted in the V2-authored `media` shape; the spec-boundary prompt\n * converters translate it for V3/V4 models.\n */\nfunction convertMcpContentToolResultOutput(output: unknown): unknown {\n if (!output || typeof output !== 'object') return undefined;\n\n const content = (output as Record<string, unknown>).content;\n if (!Array.isArray(content)) return undefined;\n\n const hasValidMultimodal = content.some(part => {\n if (!part || typeof part !== 'object') return false;\n const typedPart = part as Record<string, unknown>;\n return (typedPart.type === 'image' || typedPart.type === 'audio') && typeof typedPart.data === 'string';\n });\n if (!hasValidMultimodal) return undefined;\n\n const value = content\n .map(part => {\n if (!part || typeof part !== 'object') return null;\n const typedPart = part as Record<string, unknown>;\n switch (typedPart.type) {\n case 'text':\n return { type: 'text', text: String(typedPart.text ?? '') };\n case 'image':\n return typeof typedPart.data === 'string'\n ? { type: 'media', data: typedPart.data, mediaType: String(typedPart.mimeType ?? 'image/png') }\n : { type: 'text', text: JSON.stringify(typedPart) };\n case 'audio':\n return typeof typedPart.data === 'string'\n ? { type: 'media', data: typedPart.data, mediaType: String(typedPart.mimeType ?? 'audio/wav') }\n : { type: 'text', text: JSON.stringify(typedPart) };\n default:\n return { type: 'text', text: JSON.stringify(typedPart) };\n }\n })\n .filter(Boolean);\n\n return value.length > 0 ? { type: 'content', value } : undefined;\n}\n\nfunction collectRawToolResultOutputs(dbMessages: MastraDBMessage[]): Map<string, unknown> {\n const outputs = new Map<string, unknown>();\n for (const message of dbMessages) {\n if (message.content?.format !== 2 || !message.content.parts) continue;\n\n for (const part of message.content.parts) {\n if (part.type !== 'tool-invocation' || part.toolInvocation?.state !== 'result') continue;\n const mastraMetadata = part.providerMetadata?.mastra;\n if (mastraMetadata && typeof mastraMetadata === 'object' && 'modelOutput' in mastraMetadata) continue;\n outputs.set(part.toolInvocation.toolCallId, part.toolInvocation.result);\n }\n }\n return outputs;\n}\n\nfunction isDefaultToolResultOutput(output: unknown, rawOutput: unknown): boolean {\n if (!output || typeof output !== 'object') return false;\n const typedOutput = output as Record<string, unknown>;\n if (typedOutput.type !== 'json') return false;\n return typedOutput.value === rawOutput || deepEqual(typedOutput.value, rawOutput);\n}\n\nfunction applyMcpContentToolResultOutputs(\n modelMessages: AIV5Type.ModelMessage[],\n dbMessages: MastraDBMessage[],\n): AIV5Type.ModelMessage[] {\n const rawOutputs = collectRawToolResultOutputs(dbMessages);\n if (rawOutputs.size === 0) return modelMessages;\n\n return modelMessages.map(message => {\n if (message.role !== 'tool' || !Array.isArray(message.content)) return message;\n\n let modified = false;\n const content = message.content.map(part => {\n if (part.type !== 'tool-result' || !rawOutputs.has(part.toolCallId)) return part;\n if (part.output?.type !== 'json') return part;\n const rawOutput = rawOutputs.get(part.toolCallId);\n let converted: ReturnType<typeof convertMcpContentToolResultOutput>;\n try {\n converted = convertMcpContentToolResultOutput(rawOutput);\n if (!converted) return part;\n if (!isDefaultToolResultOutput(part.output, rawOutput)) return part;\n } catch {\n // MCP content may contain values that cannot be serialized or structurally compared.\n // Preserve the original JSON output when the optional conversion cannot complete.\n return part;\n }\n modified = true;\n return { ...part, output: converted } as typeof part;\n });\n\n return modified ? ({ ...message, content } as AIV5Type.ModelMessage) : message;\n });\n}\n\nfunction collectProviderToolErrorResults(dbMessage: MastraDBMessage | undefined): Map<string, unknown> {\n const errors = new Map<string, unknown>();\n if (dbMessage?.content?.format !== 2 || !dbMessage.content.parts) return errors;\n\n for (const part of dbMessage.content.parts) {\n if (part.type !== 'tool-invocation' || part.toolInvocation?.state !== 'output-error') continue;\n if (!part.providerExecuted || part.toolInvocation.result === undefined) continue;\n errors.set(part.toolInvocation.toolCallId, part.toolInvocation.result);\n }\n return errors;\n}\n\n/**\n * The vendored AI SDK v5 `convertToModelMessages` builds a provider-executed\n * tool error's `error-json` value from the `errorText` string. Providers expect\n * the original structured error (e.g. Anthropic `tool_search_tool_result_error`),\n * so restore the object stored in the tool invocation's `result`. Results are\n * read from the UI message's own source message so a toolCallId reused in\n * another turn cannot overwrite this turn's error.\n */\nfunction applyProviderToolErrorOutputs(\n modelMessages: AIV5Type.ModelMessage[],\n dbMessage: MastraDBMessage | undefined,\n): AIV5Type.ModelMessage[] {\n const errorResults = collectProviderToolErrorResults(dbMessage);\n if (errorResults.size === 0) return modelMessages;\n\n return modelMessages.map(message => {\n if (message.role !== 'assistant' || !Array.isArray(message.content)) return message;\n\n let modified = false;\n const content = message.content.map(part => {\n if (part.type !== 'tool-result' || part.output?.type !== 'error-json') return part;\n if (!errorResults.has(part.toolCallId)) return part;\n const value = errorResults.get(part.toolCallId);\n if (typeof value === 'string') return part;\n modified = true;\n return { ...part, output: { type: 'error-json', value: value ?? null } } as typeof part;\n });\n\n return modified ? ({ ...message, content } as AIV5Type.ModelMessage) : message;\n });\n}\n\n/**\n * Restores `providerOptions` on assistant file parts after `convertToModelMessages`.\n *\n * The vendored AI SDK v5 `convertToModelMessages` drops `providerMetadata` from\n * assistant file parts (fixed in v6 but not backported). This causes providers\n * like Google Gemini to reject round-tripped responses that require metadata\n * (e.g. `thoughtSignature` on generated images).\n *\n * We collect all `providerMetadata` values from assistant `file` UI parts in\n * order, then walk the model messages and assign them to assistant `file` parts\n * in the same order. The ordering is guaranteed to be preserved.\n */\nfunction restoreAssistantFileProviderMetadata(\n modelMessages: AIV5Type.ModelMessage[],\n uiMessages: AIV5Type.UIMessage[],\n): AIV5Type.ModelMessage[] {\n // Collect providerMetadata from ALL assistant file UI parts in order,\n // using undefined as a placeholder for parts without metadata so that\n // the indices stay aligned with the model-side file parts.\n const fileMetadata: (AIV5Type.ProviderMetadata | undefined)[] = [];\n for (const msg of uiMessages) {\n if (msg.role !== 'assistant') continue;\n for (const part of msg.parts) {\n if (part.type === 'file') {\n fileMetadata.push(part.providerMetadata ?? undefined);\n }\n }\n }\n\n if (fileMetadata.length === 0 || fileMetadata.every(m => m == null)) return modelMessages;\n\n // Walk model messages and restore providerOptions on assistant file parts\n let metadataIndex = 0;\n return modelMessages.map(msg => {\n if (msg.role !== 'assistant' || typeof msg.content === 'string') return msg;\n\n let modified = false;\n const content = msg.content.map(part => {\n if (part.type !== 'file' || metadataIndex >= fileMetadata.length) return part;\n const metadata = fileMetadata[metadataIndex++];\n if (part.providerOptions || !metadata) return part;\n modified = true;\n return { ...part, providerOptions: metadata };\n });\n\n return modified ? { ...msg, content } : msg;\n });\n}\n\n/**\n * How suspended (result-less) tool calls are handled when converting to model messages.\n *\n * - `response`: messages coming FROM the LLM. Suspended calls are kept so they stay in\n * message history, and no pairing is enforced — nothing here is sent to a provider.\n * - `prompt`: messages going TO the LLM. Suspended calls are dropped.\n * - `prompt-with-suspended`: messages going TO the LLM with suspended calls kept visible to\n * the agent. Each is paired with a pending result so the prompt stays valid.\n *\n * The last two both submit to a provider, so both enforce tool-call/tool-result pairing.\n * That requirement belongs to the provider protocol, not to the caller's preference.\n */\nexport type ToolCallConversionMode = 'response' | 'prompt' | 'prompt-with-suspended';\n\n/**\n * A step that dies after the model starts thinking but before the reasoning\n * signature arrives leaves a step block holding only unsigned reasoning.\n * Providers that require signed thinking (Anthropic, Bedrock) drop such parts,\n * sending `content: []` and failing every later turn with a 400 (#24558).\n */\nconst REPLAYABLE_REASONING_KEYS = [\n 'signature',\n 'redactedData',\n 'itemId',\n 'reasoningEncryptedContent',\n 'thoughtSignature',\n];\n\nfunction hasReplayableReasoningMetadata(providerOptions: AIV5Type.ProviderMetadata | undefined): boolean {\n return Object.values(providerOptions ?? {}).some(\n value => !!value && typeof value === 'object' && REPLAYABLE_REASONING_KEYS.some(key => key in value),\n );\n}\n\nfunction isUnforwardableReasoningOnlyMessage(message: AIV5Type.ModelMessage): boolean {\n if (message.role !== 'assistant' || !Array.isArray(message.content) || message.content.length === 0) return false;\n return message.content.every(\n part => part.type === 'reasoning' && !hasReplayableReasoningMetadata(part.providerOptions),\n );\n}\n\n/**\n * Converts AIV5 UI messages to AIV5 Model messages.\n * Handles sanitization, step-start insertion, provider options restoration, and Anthropic compatibility.\n *\n * @param messages - AIV5 UI messages to convert\n * @param dbMessages - MastraDB messages used to look up tool call args for Anthropic compatibility\n * @param mode - How to handle suspended tool calls\n */\nexport function aiV5UIMessagesToAIV5ModelMessages(\n messages: AIV5Type.UIMessage[],\n dbMessages: MastraDBMessage[],\n mode: ToolCallConversionMode = 'response',\n): AIV5Type.ModelMessage[] {\n const sanitized = sanitizeV5UIMessages(messages, mode);\n const preprocessed = addStartStepPartsForAIV5(sanitized);\n\n // Convert per UI message: an assistant turn with a tool call splits into\n // [assistant, tool] model messages, so a batch convert + index-based attach\n // would misplace message-level providerOptions onto the tool message.\n const converted: AIV5Type.ModelMessage[] = [];\n const dbMessagesById = new Map(dbMessages.map(message => [message.id, message]));\n for (const uiMsg of preprocessed) {\n const produced = applyProviderToolErrorOutputs(AIV5.convertToModelMessages([uiMsg]), dbMessagesById.get(uiMsg.id));\n if (produced.length === 0) continue;\n\n const providerMetadata =\n uiMsg.metadata && typeof uiMsg.metadata === 'object' && 'providerMetadata' in uiMsg.metadata\n ? (uiMsg.metadata as { providerMetadata?: AIV5Type.ProviderMetadata }).providerMetadata\n : undefined;\n\n if (providerMetadata) {\n let target = -1;\n for (let index = produced.length - 1; index >= 0; index--) {\n if (produced[index]?.role === uiMsg.role) {\n target = index;\n break;\n }\n }\n if (target !== -1) {\n produced[target] = { ...produced[target], providerOptions: providerMetadata } as AIV5Type.ModelMessage;\n }\n }\n\n for (const message of produced) {\n if (mode !== 'response' && isUnforwardableReasoningOnlyMessage(message)) continue;\n converted.push(message);\n }\n }\n\n const withSplitItemReferences = splitResponsesToolItemReferences(converted);\n const withFileMetadata = restoreAssistantFileProviderMetadata(withSplitItemReferences, preprocessed);\n const withMcpContentOutputs = applyMcpContentToolResultOutputs(withFileMetadata, dbMessages);\n\n // Add input field to tool-result parts for Anthropic API compatibility (fixes issue #11376)\n const anthropicCompat = ensureAnthropicCompatibleMessages(withMcpContentOutputs, dbMessages);\n\n switch (mode) {\n case 'prompt':\n return sanitizeOrphanedToolPairs(anthropicCompat);\n case 'prompt-with-suspended':\n return pairOrphanedToolCalls(anthropicCompat);\n default:\n return anthropicCompat;\n }\n}\n\n/**\n * Converts AIV4 Core messages to AIV5 Model messages.\n */\nexport function aiV4CoreMessagesToAIV5ModelMessages(\n messages: CoreMessageV4[],\n source: MessageSource,\n adapterContext: AdapterContext,\n dbMessages: MastraDBMessage[],\n): AIV5Type.ModelMessage[] {\n return aiV5UIMessagesToAIV5ModelMessages(\n messages.map(m => AIV4Adapter.fromCoreMessage(m, adapterContext, source)).map(m => AIV5Adapter.toUIMessage(m)),\n dbMessages,\n );\n}\n\n/**\n * Converts various message formats to AIV4 CoreMessage format for system messages.\n * Supports string, MastraDBMessage, or AI SDK message types.\n */\nexport function systemMessageToAIV4Core(\n message: CoreMessageV4 | AIV5Type.ModelMessage | AIV6Type.ModelMessage | MastraDBMessage | string,\n): CoreMessageV4 {\n if (typeof message === `string`) {\n return { role: 'system', content: message };\n }\n\n if (TypeDetector.isAIV6CoreMessage(message)) {\n const dbMsg = AIV6Adapter.fromModelMessage(message as AIV6Type.ModelMessage, 'system');\n return AIV4Adapter.systemToV4Core(dbMsg);\n }\n\n if (TypeDetector.isAIV5CoreMessage(message)) {\n const dbMsg = AIV5Adapter.fromModelMessage(message as AIV5Type.ModelMessage, 'system');\n return AIV4Adapter.systemToV4Core(dbMsg);\n }\n\n if (TypeDetector.isMastraDBMessage(message)) {\n return AIV4Adapter.systemToV4Core(message);\n }\n\n return message;\n}\n","import * as AIV5 from '@internal/ai-sdk-v5';\n\nimport { DefaultGeneratedFileWithType } from '../../../stream/aisdk/v5/file';\nimport { convertDataContentToBase64String } from '../prompt/data-content';\nimport { parseDataUri } from '../prompt/image-utils';\nimport type { MastraDBMessage } from '../state/types';\nimport type { AIV5Type } from '../types';\nimport { findToolCallArgs } from '../utils/provider-compat';\nimport { sanitizeV5UIMessages } from './output-converter';\n\n/**\n * StepContentExtractor - Handles extraction of step content from response messages\n *\n * This class encapsulates the complex logic for:\n * - Finding step boundaries by looking for step-start markers\n * - Handling special cases like -1 (last step) and tool-only steps\n * - Converting UI messages to model messages and extracting content\n */\nexport class StepContentExtractor {\n /**\n * Extract content for a specific step number from UI messages\n *\n * @param uiMessages - Array of AI SDK V5 UI messages\n * @param stepNumber - Step number to extract (1-indexed, or -1 for last step)\n * @param stepContentFn - Function to convert model messages to step content\n * @returns Step content array\n */\n static extractStepContent(\n uiMessages: AIV5Type.UIMessage[],\n stepNumber: number,\n stepContentFn: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content'],\n stepToolCallIds?: string[],\n ): AIV5Type.StepResult<any>['content'] {\n const uiMessagesParts = uiMessages.flatMap(item => item.parts);\n\n // Find step boundaries by looking for step-start markers\n const stepBoundaries: number[] = [];\n uiMessagesParts.forEach((part, index) => {\n if (part.type === 'step-start') {\n stepBoundaries.push(index);\n }\n });\n\n // Handle -1 to get the last step (the current/most recent step)\n if (stepNumber === -1) {\n return StepContentExtractor.extractLastStep(uiMessagesParts, stepBoundaries, stepContentFn, stepToolCallIds);\n }\n\n // Step 1 is everything before the first step-start\n if (stepNumber === 1) {\n return StepContentExtractor.extractFirstStep(uiMessagesParts, stepBoundaries, stepContentFn);\n }\n\n // For steps 2+, content is between (stepNumber-1)th and stepNumber-th step-start markers\n return StepContentExtractor.extractMiddleStep(uiMessagesParts, stepBoundaries, stepNumber, stepContentFn);\n }\n\n /**\n * Extract the last step content (stepNumber === -1)\n */\n private static extractLastStep(\n uiMessagesParts: AIV5Type.UIMessage['parts'],\n stepBoundaries: number[],\n stepContentFn: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content'],\n stepToolCallIds?: string[],\n ): AIV5Type.StepResult<any>['content'] {\n // For tool-only steps without step-start markers, we need different logic\n const toolParts = uiMessagesParts.filter(p => p.type?.startsWith('tool-'));\n const hasStepStart = stepBoundaries.length > 0;\n\n if (!hasStepStart && toolParts.length > 0) {\n // Without markers the parts alone cannot tell one step with several calls\n // from several one-call steps. When the caller knows the step's calls, the\n // step starts at its first call; otherwise assume one call per step.\n const lastToolPart = toolParts[toolParts.length - 1];\n if (!lastToolPart) {\n return [];\n }\n const lastToolIndex = uiMessagesParts.indexOf(lastToolPart);\n const stepCallIds = new Set(stepToolCallIds ?? []);\n const firstStepToolIndex = stepCallIds.size\n ? toolParts.findIndex(p => stepCallIds.has((p as { toolCallId?: string }).toolCallId ?? ''))\n : -1;\n const firstToolIndex = firstStepToolIndex === -1 ? toolParts.length - 1 : firstStepToolIndex;\n const previousToolPart = toolParts[firstToolIndex - 1];\n const previousToolIndex = previousToolPart ? uiMessagesParts.indexOf(previousToolPart) : -1;\n\n const startIndex = previousToolIndex + 1;\n const stepParts = uiMessagesParts.slice(startIndex, lastToolIndex + 1);\n\n return StepContentExtractor.convertPartsToContent(stepParts, 'last-step', stepContentFn);\n }\n\n // Count total steps (1 + number of step-start markers)\n const totalSteps = stepBoundaries.length + 1;\n\n // Get the content for the last step using the regular step logic\n if (totalSteps === 1 && !hasStepStart) {\n // Only one step, return all content\n return StepContentExtractor.convertPartsToContent(uiMessagesParts, 'last-step', stepContentFn);\n }\n\n // Multiple steps - get content after the last step-start marker\n const lastStepStart = stepBoundaries[stepBoundaries.length - 1];\n if (lastStepStart === undefined) {\n return [];\n }\n const stepParts = uiMessagesParts.slice(lastStepStart + 1);\n\n if (stepParts.length === 0) {\n return [];\n }\n\n return StepContentExtractor.convertPartsToContent(stepParts, 'last-step', stepContentFn);\n }\n\n /**\n * Extract the first step content (stepNumber === 1)\n */\n private static extractFirstStep(\n uiMessagesParts: AIV5Type.UIMessage['parts'],\n stepBoundaries: number[],\n stepContentFn: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content'],\n ): AIV5Type.StepResult<any>['content'] {\n const firstStepStart = stepBoundaries[0] ?? uiMessagesParts.length;\n if (firstStepStart === 0) {\n // No content before first step-start\n return [];\n }\n\n const stepParts = uiMessagesParts.slice(0, firstStepStart);\n return StepContentExtractor.convertPartsToContent(stepParts, 'step-1', stepContentFn);\n }\n\n /**\n * Extract content for steps 2+ (between step-start markers)\n */\n private static extractMiddleStep(\n uiMessagesParts: AIV5Type.UIMessage['parts'],\n stepBoundaries: number[],\n stepNumber: number,\n stepContentFn: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content'],\n ): AIV5Type.StepResult<any>['content'] {\n const stepIndex = stepNumber - 2; // -2 because step 2 is at index 0 in boundaries\n if (stepIndex < 0 || stepIndex >= stepBoundaries.length) {\n return [];\n }\n\n const startIndex = (stepBoundaries[stepIndex] ?? 0) + 1; // Start after the step-start marker\n const endIndex = stepBoundaries[stepIndex + 1] ?? uiMessagesParts.length;\n\n if (startIndex >= endIndex) {\n return [];\n }\n\n const stepParts = uiMessagesParts.slice(startIndex, endIndex);\n return StepContentExtractor.convertPartsToContent(stepParts, `step-${stepNumber}`, stepContentFn);\n }\n\n /**\n * Convert UI message parts to step content\n */\n private static convertPartsToContent(\n parts: AIV5Type.UIMessage['parts'],\n stepId: string,\n stepContentFn: (message?: AIV5Type.ModelMessage) => AIV5Type.StepResult<any>['content'],\n ): AIV5Type.StepResult<any>['content'] {\n const stepUiMessages: AIV5Type.UIMessage[] = [\n {\n id: stepId,\n role: 'assistant',\n parts,\n },\n ];\n\n const modelMessages = AIV5.convertToModelMessages(sanitizeV5UIMessages(stepUiMessages));\n return modelMessages.flatMap(stepContentFn);\n }\n\n /**\n * Convert a single model message content to step result content\n *\n * This handles:\n * - Tool results: adding input field from DB messages\n * - Files: converting to GeneratedFile format\n * - Images: converting to file format with proper media type\n * - Other content: passed through as-is\n *\n * @param message - Model message to convert (or undefined to use latest)\n * @param dbMessages - Database messages for looking up tool call args\n * @param getLatestMessage - Function to get the latest model message if not provided\n */\n static convertToStepContent(\n message: AIV5Type.ModelMessage | undefined,\n dbMessages: MastraDBMessage[],\n getLatestMessage: () => AIV5Type.ModelMessage | undefined,\n ): AIV5Type.StepResult<any>['content'] {\n const latest = message ? message : getLatestMessage();\n if (!latest) return [];\n\n if (typeof latest.content === 'string') {\n return [{ type: 'text', text: latest.content }];\n }\n\n return latest.content.map(c => {\n if (c.type === 'tool-result') {\n return {\n type: 'tool-result',\n input: findToolCallArgs(dbMessages, c.toolCallId),\n output: c.output,\n toolCallId: c.toolCallId,\n toolName: c.toolName,\n } satisfies AIV5Type.StaticToolResult<any>;\n }\n\n if (c.type === 'file') {\n return {\n type: 'file',\n file: new DefaultGeneratedFileWithType({\n data:\n typeof c.data === 'string'\n ? parseDataUri(c.data).base64Content // Strip data URI prefix if present\n : c.data instanceof URL\n ? c.data.toString()\n : convertDataContentToBase64String(c.data),\n mediaType: c.mediaType,\n }),\n } satisfies Extract<AIV5Type.StepResult<any>['content'][number], { type: 'file' }>;\n }\n\n if (c.type === 'image') {\n return {\n type: 'file',\n file: new DefaultGeneratedFileWithType({\n data:\n typeof c.image === 'string'\n ? parseDataUri(c.image).base64Content // Strip data URI prefix if present\n : c.image instanceof URL\n ? c.image.toString()\n : convertDataContentToBase64String(c.image),\n mediaType: c.mediaType || 'unknown',\n }),\n };\n }\n\n return { ...c };\n });\n }\n}\n","import { CacheKeyGenerator } from '../cache/CacheKeyGenerator';\nimport type { MastraDBMessage, MastraMessageContentV2 } from '../state/types';\nimport { stampPart, stampToolPartUpdate } from '../utils/stamp-part';\n\ntype MessagePart = MastraMessageContentV2['parts'][number];\n\n/**\n * Per-merge index over both messages' parts. Every part is keyed once and the per-key counts\n * are updated as parts are inserted, so inserting a part costs O(1) key work instead of\n * re-keying every part of both messages (which made merging quadratic in the part count).\n */\ntype MergeIndex = {\n keyOf: (part: MessagePart) => string;\n latestCounts: Map<string, number>;\n incomingCounts: Map<string, number>;\n /** First index of each part object in the incoming message (same result as `indexOf`). */\n incomingIndex: Map<MessagePart, number>;\n /** Index of the first incoming part that is not a step-start. */\n firstIncomingNonStepStart: number;\n};\n\n/**\n * MessageMerger - Handles complex logic for merging assistant messages\n *\n * When streaming responses from LLMs, we often receive multiple messages that need to be\n * merged together:\n * - Tool calls that need to be updated with their results\n * - Text parts that need to be appended\n * - Step-start markers that need to be inserted\n *\n * This class encapsulates all the complex merging logic that was previously spread\n * throughout the MessageList.addOne method.\n */\nexport class MessageMerger {\n /**\n * Check if a message is sealed (should not be merged into).\n * Messages are sealed after observation to preserve observation markers.\n */\n static isSealed(message: MastraDBMessage): boolean {\n const metadata = message.content?.metadata as { mastra?: { sealed?: boolean } } | undefined;\n return metadata?.mastra?.sealed === true;\n }\n\n /**\n * Check if we should merge an incoming message with the latest message\n *\n * @param latestMessage - The most recent message in the list\n * @param incomingMessage - The message being added\n * @param messageSource - The source of the incoming message ('memory', 'input', 'response', 'context')\n * @param isLatestFromMemory - Whether the latest message is from memory\n * @param agentNetworkAppend - Whether agent network append mode is enabled\n */\n\n static shouldMerge(\n latestMessage: MastraDBMessage | undefined,\n incomingMessage: MastraDBMessage,\n messageSource: string,\n isLatestFromMemory: boolean,\n agentNetworkAppend: boolean = false,\n ): boolean {\n if (!latestMessage) return false;\n\n // Don't merge into sealed messages (e.g., messages that have been observed)\n if (MessageMerger.isSealed(latestMessage)) return false;\n\n // A boundary keeps the next response out of this message. Parts that still\n // carry this message's own id (a tool that was running when the boundary\n // landed, reporting its data parts and result) belong to it and must merge;\n // otherwise the add falls through to replace-by-id and drops its tool call.\n if (\n latestMessage.id !== incomingMessage.id &&\n (latestMessage.content?.metadata as { mastra?: { responseBoundary?: boolean } } | undefined)?.mastra\n ?.responseBoundary\n ) {\n return false;\n }\n\n // Don't merge completion result message (network uses completionResult, supervisor uses isTaskCompleteResult)\n if (\n incomingMessage.content.metadata?.completionResult ||\n latestMessage.content.metadata?.completionResult ||\n incomingMessage.content.metadata?.isTaskCompleteResult ||\n latestMessage.content.metadata?.isTaskCompleteResult\n ) {\n return false;\n }\n\n const latestParts = latestMessage.content?.parts ?? [];\n const latestOnlyHasDataParts = latestParts.length > 0 && latestParts.every(part => part.type.startsWith('data-'));\n if (latestOnlyHasDataParts && latestMessage.id !== incomingMessage.id) {\n return false;\n }\n\n // Basic merge conditions: both messages must be assistant messages from the same thread\n const shouldAppendToLastAssistantMessage =\n latestMessage.role === 'assistant' &&\n incomingMessage.role === 'assistant' &&\n latestMessage.threadId === incomingMessage.threadId &&\n // If the message is from memory, don't append to the last assistant message\n messageSource !== 'memory';\n\n // Agent network append flag handling\n // When enabled, only merge if the latest message is NOT from memory\n const appendNetworkMessage = agentNetworkAppend ? !isLatestFromMemory : true;\n\n return shouldAppendToLastAssistantMessage && appendNetworkMessage;\n }\n\n /**\n * Merge an incoming assistant message into the latest assistant message.\n *\n * This preserves the existing message-level createdAt. OM uses that timestamp\n * as its observation boundary, so moving it forward can make an already\n * observed message look unobserved and eligible for reprocessing.\n *\n * This handles:\n * - Updating tool invocations with their results\n * - Adding new parts in the correct order using anchor maps\n * - Inserting step-start markers where needed\n * - Updating content strings\n */\n static merge(latestMessage: MastraDBMessage, incomingMessage: MastraDBMessage): void {\n if (incomingMessage.content.metadata) {\n latestMessage.content.metadata = {\n ...(latestMessage.content.metadata ?? {}),\n ...incomingMessage.content.metadata,\n };\n }\n\n // Used for mapping indexes for incomingMessage parts to corresponding indexes in latestMessage\n const toolResultAnchorMap = new Map<number, number>();\n const partsToAdd = new Map<number, MastraMessageContentV2['parts'][number]>();\n\n for (const [index, part] of incomingMessage.content.parts.entries()) {\n // If the incoming part is a tool-invocation result, find the corresponding call in the latest message\n if (part.type === 'tool-invocation') {\n if (!part.toolInvocation) continue;\n const existingCallPart = [...latestMessage.content.parts]\n .reverse()\n .find(p => p.type === 'tool-invocation' && p.toolInvocation?.toolCallId === part.toolInvocation.toolCallId);\n\n const existingCallToolInvocation = !!existingCallPart && existingCallPart.type === 'tool-invocation';\n\n if (existingCallToolInvocation) {\n const before = existingCallPart.toolInvocation;\n if (part.toolInvocation.state === 'result') {\n // Update the existing tool-call part with the result\n existingCallPart.toolInvocation = {\n ...existingCallPart.toolInvocation,\n step: part.toolInvocation.step,\n state: 'result',\n result: part.toolInvocation.result,\n args: {\n ...existingCallPart.toolInvocation.args,\n ...part.toolInvocation.args,\n },\n };\n stampToolPartUpdate(existingCallPart, before, part.updatedAt);\n // Preserve providerMetadata from the result part (e.g. toModelOutput stored at mastra.modelOutput)\n if (part.providerMetadata) {\n existingCallPart.providerMetadata = {\n ...existingCallPart.providerMetadata,\n ...part.providerMetadata,\n };\n }\n if (!latestMessage.content.toolInvocations) {\n latestMessage.content.toolInvocations = [];\n }\n const toolInvocationIndex = latestMessage.content.toolInvocations.findIndex(\n t => t.toolCallId === existingCallPart.toolInvocation.toolCallId,\n );\n if (toolInvocationIndex === -1) {\n latestMessage.content.toolInvocations.push(\n existingCallPart.toolInvocation as NonNullable<MastraDBMessage['content']['toolInvocations']>[number],\n );\n } else {\n latestMessage.content.toolInvocations[toolInvocationIndex] =\n existingCallPart.toolInvocation as NonNullable<MastraDBMessage['content']['toolInvocations']>[number];\n }\n } else if (\n part.toolInvocation.state === 'approval-requested' ||\n part.toolInvocation.state === 'approval-responded' ||\n part.toolInvocation.state === 'output-denied' ||\n part.toolInvocation.state === 'output-error'\n ) {\n existingCallPart.toolInvocation = {\n ...existingCallPart.toolInvocation,\n state: part.toolInvocation.state,\n approval: part.toolInvocation.approval,\n errorText: part.toolInvocation.errorText,\n ...(part.toolInvocation.state === 'output-error' && part.toolInvocation.result !== undefined\n ? { result: part.toolInvocation.result }\n : {}),\n rawInput: part.toolInvocation.rawInput,\n args: {\n ...existingCallPart.toolInvocation.args,\n ...part.toolInvocation.args,\n },\n };\n stampToolPartUpdate(existingCallPart, before, part.updatedAt);\n\n if (part.providerMetadata) {\n existingCallPart.providerMetadata = {\n ...existingCallPart.providerMetadata,\n ...part.providerMetadata,\n };\n }\n\n if ('providerExecuted' in part && part.providerExecuted !== undefined) {\n existingCallPart.providerExecuted = part.providerExecuted;\n }\n\n if ('title' in part && part.title !== undefined) {\n existingCallPart.title = part.title;\n }\n\n if ('preliminary' in part && part.preliminary !== undefined) {\n existingCallPart.preliminary = part.preliminary;\n }\n }\n // Map the index of the tool call in incomingMessage to the index of the tool call in latestMessage\n const existingIndex = latestMessage.content.parts.findIndex(p => p === existingCallPart);\n toolResultAnchorMap.set(index, existingIndex);\n // Otherwise we do nothing, as we're not updating the tool call\n } else {\n partsToAdd.set(index, part);\n }\n } else {\n partsToAdd.set(index, part);\n }\n }\n\n MessageMerger.addPartsToMessage({\n latestMessage,\n incomingMessage,\n anchorMap: toolResultAnchorMap,\n partsToAdd,\n });\n\n if (!latestMessage.content.content && incomingMessage.content.content) {\n latestMessage.content.content = incomingMessage.content.content;\n }\n if (\n latestMessage.content.content &&\n incomingMessage.content.content &&\n latestMessage.content.content !== incomingMessage.content.content\n ) {\n // Match what AI SDK does - content string is always the latest text part.\n latestMessage.content.content = incomingMessage.content.content;\n }\n }\n\n /**\n * Add parts from the incoming message to the latest message using anchor positions\n */\n private static addPartsToMessage({\n latestMessage,\n incomingMessage,\n anchorMap,\n partsToAdd,\n }: {\n latestMessage: MastraDBMessage;\n incomingMessage: MastraDBMessage;\n anchorMap: Map<number, number>;\n partsToAdd: Map<number, MastraMessageContentV2['parts'][number]>;\n }): void {\n let previousLeftAnchor = -1;\n let insertionDrift = 0;\n const index = MessageMerger.createMergeIndex(latestMessage, incomingMessage);\n let window: { leftAnchor: number; parts: MessagePart[]; start: number; counts: Map<string, number> } | undefined;\n\n // Walk through incomingMessage, inserting any part not present at the canonical position\n for (let i = 0; i < incomingMessage.content.parts.length; ++i) {\n const part = incomingMessage.content.parts[i];\n if (!part) continue;\n const key = index.keyOf(part);\n const partToAdd = partsToAdd.get(i);\n if (!key || !partToAdd) continue;\n if (anchorMap.size > 0) {\n if (anchorMap.has(i)) continue; // skip anchors\n // Find left anchor in incomingMessage\n const leftAnchorV2 = [...anchorMap.keys()].filter(idx => idx < i).pop() ?? -1;\n // Find right anchor in incomingMessage\n const rightAnchorV2 = [...anchorMap.keys()].find(idx => idx > i) ?? -1;\n\n // Map to latestMessage\n const leftAnchorLatest = leftAnchorV2 !== -1 ? anchorMap.get(leftAnchorV2)! : 0;\n\n // Compute offset from anchor\n const offset = leftAnchorV2 === -1 ? i : i - leftAnchorV2;\n\n // Shifted anchors already include insertions from earlier intervals.\n if (leftAnchorV2 !== previousLeftAnchor) {\n insertionDrift = 0;\n previousLeftAnchor = leftAnchorV2;\n }\n\n // Insert at proportional position, accounting for synthetic step-starts.\n const insertAt = leftAnchorLatest + offset + insertionDrift;\n\n const rightAnchorLatest =\n rightAnchorV2 !== -1 ? anchorMap.get(rightAnchorV2)! : latestMessage.content.parts.length;\n\n if (insertAt < 0 || insertAt > rightAnchorLatest) continue;\n\n // insertAt only moves forward within an interval and inserted parts always land before the\n // next insertAt, so [insertAt, rightAnchorLatest) is always a suffix of the parts the interval\n // held when first visited. Count that suffix once and trim it from the front instead of\n // rescanning the slice for every incoming part.\n if (!window || window.leftAnchor !== leftAnchorV2) {\n const parts = latestMessage.content.parts.slice(insertAt, rightAnchorLatest);\n const counts = new Map<string, number>();\n for (const p of parts) {\n const k = index.keyOf(p);\n counts.set(k, (counts.get(k) ?? 0) + 1);\n }\n window = { leftAnchor: leftAnchorV2, parts, start: 0, counts };\n }\n while (window.parts.length - window.start > rightAnchorLatest - insertAt) {\n const k = index.keyOf(window.parts[window.start++]!);\n window.counts.set(k, window.counts.get(k)! - 1);\n }\n\n if (!window.counts.get(key)) {\n const insertedCount = MessageMerger.pushNewPart({\n latestMessage,\n newMessage: incomingMessage,\n part,\n insertAt,\n index,\n });\n if (insertedCount === 0) continue;\n insertionDrift += insertedCount - 1;\n for (const [v2Idx, latestIdx] of anchorMap.entries()) {\n if (latestIdx >= insertAt) {\n anchorMap.set(v2Idx, latestIdx + insertedCount);\n }\n }\n }\n } else {\n MessageMerger.pushNewPart({\n latestMessage,\n newMessage: incomingMessage,\n part,\n index,\n });\n }\n }\n }\n\n private static createMergeIndex(latestMessage: MastraDBMessage, incomingMessage: MastraDBMessage): MergeIndex {\n const keys = new Map<MessagePart, string>();\n const baseKeyOf = (part: MessagePart) => CacheKeyGenerator.fromDBParts([part]);\n const dataPartId = (part: MessagePart) =>\n part.type.startsWith('data-') && 'id' in part && typeof part.id === 'string' ? part.id : undefined;\n // Data part ids only distinguish parts when both sides carry ids. A stored part without an id\n // (legacy rows, regular-agent persistence) still matches one incoming copy that has an id the\n // other side lacks; every other id keeps its own key. The id-less part matches the last such\n // copy, so suppressing it doesn't shift where the earlier ones are inserted.\n const keyParts = (parts: MessagePart[], otherParts: MessagePart[]) => {\n const otherIds = new Set<string>();\n const otherIdless = new Map<string, number>();\n for (const part of otherParts) {\n if (!part.type.startsWith('data-')) continue;\n const baseKey = baseKeyOf(part);\n const id = dataPartId(part);\n if (id !== undefined) otherIds.add(`${baseKey}|id:${JSON.stringify(id)}`);\n else otherIdless.set(baseKey, (otherIdless.get(baseKey) ?? 0) + 1);\n }\n for (const part of [...parts].reverse()) {\n if (keys.has(part)) continue;\n const baseKey = baseKeyOf(part);\n const id = dataPartId(part);\n const unmatched = otherIdless.get(baseKey) ?? 0;\n const idKey = id !== undefined ? `${baseKey}|id:${JSON.stringify(id)}` : undefined;\n if (idKey !== undefined && !otherIds.has(idKey) && unmatched > 0) {\n otherIdless.set(baseKey, unmatched - 1);\n keys.set(part, baseKey);\n } else {\n keys.set(part, idKey ?? baseKey);\n }\n }\n };\n keyParts(latestMessage.content.parts, incomingMessage.content.parts);\n keyParts(incomingMessage.content.parts, latestMessage.content.parts);\n const keyOf = (part: MessagePart) => {\n let key = keys.get(part);\n if (key === undefined) {\n key = baseKeyOf(part);\n keys.set(part, key);\n }\n return key;\n };\n const countKeys = (parts: MessagePart[]) => {\n const counts = new Map<string, number>();\n for (const part of parts) {\n const key = keyOf(part);\n counts.set(key, (counts.get(key) ?? 0) + 1);\n }\n return counts;\n };\n\n const incomingParts = incomingMessage.content.parts;\n const incomingIndex = new Map<MessagePart, number>();\n incomingParts.forEach((part, i) => {\n if (!incomingIndex.has(part)) incomingIndex.set(part, i);\n });\n const firstNonStepStart = incomingParts.findIndex(p => p.type !== 'step-start');\n\n return {\n keyOf,\n latestCounts: countKeys(latestMessage.content.parts),\n incomingCounts: countKeys(incomingParts),\n incomingIndex,\n firstIncomingNonStepStart: firstNonStepStart === -1 ? incomingParts.length : firstNonStepStart,\n };\n }\n\n /**\n * Push a new message part to the latest message\n */\n private static pushNewPart({\n latestMessage,\n newMessage,\n part,\n insertAt,\n index,\n }: {\n latestMessage: MastraDBMessage;\n newMessage: MastraDBMessage;\n part: MastraMessageContentV2['parts'][number];\n insertAt?: number;\n index: MergeIndex;\n }): number {\n const partKey = index.keyOf(part);\n const latestPartCount = index.latestCounts.get(partKey) ?? 0;\n const newPartCount = index.incomingCounts.get(partKey) ?? 0;\n // If the number of parts in the latest message is less than the number of parts in the new message, insert the part\n if (latestPartCount < newPartCount) {\n // Check if we need to add a step-start when merging assistant messages: before text parts the\n // incoming message doesn't already precede with a step-start, and before a tool call that opens\n // the incoming step. Only add after tool invocations. Later tool calls in the same incoming\n // message are parallel calls of that step and stay together.\n const partIndex = index.incomingIndex.get(part) ?? -1;\n const hasStepStartBefore = partIndex > 0 && newMessage.content.parts[partIndex - 1]?.type === 'step-start';\n // An incoming step-start can be deduplicated against one already stored, so a tool call\n // preceded only by step-starts still opens a new step.\n const opensStep = partIndex <= index.firstIncomingNonStepStart;\n\n const needsStepStart =\n latestMessage.role === 'assistant' &&\n ((part.type === 'text' && !hasStepStartBefore) || (part.type === 'tool-invocation' && opensStep)) &&\n latestMessage.content.parts.length > 0 &&\n latestMessage.content.parts.at(-1)?.type === 'tool-invocation';\n\n let stepStartPart: MessagePart | undefined;\n if (needsStepStart) {\n const previousStepStart = latestMessage.content.parts.findLast(p => p.type === 'step-start');\n stepStartPart = previousStepStart?.model\n ? stampPart({\n type: 'step-start' as const,\n model: previousStepStart.model,\n })\n : ({ type: 'step-start' as const } as MessagePart);\n const stepStartKey = index.keyOf(stepStartPart);\n index.latestCounts.set(stepStartKey, (index.latestCounts.get(stepStartKey) ?? 0) + 1);\n }\n index.latestCounts.set(partKey, latestPartCount + 1);\n\n if (typeof insertAt === 'number') {\n if (stepStartPart) {\n latestMessage.content.parts.splice(insertAt, 0, stepStartPart);\n latestMessage.content.parts.splice(insertAt + 1, 0, part);\n } else {\n latestMessage.content.parts.splice(insertAt, 0, part);\n }\n } else {\n if (stepStartPart) {\n latestMessage.content.parts.push(stepStartPart);\n }\n latestMessage.content.parts.push(part);\n }\n return stepStartPart ? 2 : 1;\n }\n return 0;\n }\n}\n","import type { LanguageModelV2FilePart, LanguageModelV2TextPart } from '@ai-sdk/provider-v5';\nimport type { DataContent, ImagePart, FilePart } from '@internal/ai-sdk-v5';\nimport { convertToDataContent, detectMediaType, imageMediaTypeSignatures } from '../../../stream/aisdk/v5/compat';\n\nexport function convertImageFilePart(\n part: ImagePart | FilePart,\n downloadedAssets?: Record<string, { mediaType: string | undefined; data: Uint8Array }>,\n): LanguageModelV2TextPart | LanguageModelV2FilePart {\n let originalData: DataContent | URL;\n const type = part.type;\n switch (type) {\n case 'image':\n originalData = part.image;\n break;\n case 'file':\n originalData = part.data;\n\n break;\n default:\n throw new Error(`Unsupported part type: ${type}`);\n }\n\n const { data: convertedData, mediaType: convertedMediaType } = convertToDataContent(originalData);\n\n let mediaType: string | undefined = convertedMediaType ?? part.mediaType;\n let data: Uint8Array | string | URL = convertedData; // binary | base64 | url\n\n // If the content is a URL, we check if it was downloaded:\n if (data instanceof URL && downloadedAssets) {\n const downloadedFile = downloadedAssets[data.toString()];\n if (downloadedFile) {\n data = downloadedFile.data;\n mediaType ??= downloadedFile.mediaType;\n }\n }\n\n // Now that we have the normalized data either as a URL or a Uint8Array,\n // we can create the LanguageModelV2Part.\n switch (type) {\n case 'image': {\n // When possible, try to detect the media type automatically\n // to deal with incorrect media type inputs.\n // When detection fails, use provided media type.\n if (data instanceof Uint8Array || typeof data === 'string') {\n mediaType = detectMediaType({ data, signatures: imageMediaTypeSignatures }) ?? mediaType;\n }\n\n return {\n type: 'file',\n mediaType: mediaType ?? 'image/*', // any image\n filename: undefined,\n data,\n providerOptions: part.providerOptions,\n };\n }\n\n case 'file': {\n // We must have a mediaType for files, if not, throw an error.\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 }\n}\n","import type { FilePart, ImagePart, TextPart, UIMessage } from '@internal/ai-sdk-v4';\nimport { categorizeFileData, createDataUri } from './image-utils';\n\ntype ContentPart = TextPart | ImagePart | FilePart;\nexport type Attachment = NonNullable<UIMessage['experimental_attachments']>[number];\n\n/**\n * Converts a list of attachments to a list of content parts\n * for consumption by `ai/core` functions.\n * Currently only supports images and text attachments.\n */\nexport function attachmentsToParts(attachments: Attachment[]): ContentPart[] {\n const parts: ContentPart[] = [];\n\n for (const attachment of attachments) {\n // Categorize the attachment URL to determine if it's a URL, data URI, raw base64,\n // or a provider file ID (e.g. OpenAI \"file-...\")\n const categorized = categorizeFileData(attachment.url, attachment.contentType);\n\n // Provider file IDs are not parseable URLs — pass them through as file parts\n // untouched so providers can forward them by reference (e.g. { file_id: \"file-...\" }).\n if (categorized.type === 'providerFileId') {\n parts.push({\n type: 'file',\n data: attachment.url,\n mimeType: attachment.contentType || 'application/octet-stream',\n });\n continue;\n }\n\n // If it's raw data (base64), convert it to a data URI\n let urlString = attachment.url;\n if (categorized.type === 'raw') {\n urlString = createDataUri(attachment.url, attachment.contentType || 'application/octet-stream');\n }\n\n let url;\n try {\n url = new URL(urlString);\n } catch {\n throw new Error(`Invalid URL: ${attachment.url}`);\n }\n\n switch (url.protocol) {\n case 'http:':\n case 'https:':\n // Cloud storage protocols supported by AI providers (e.g., Vertex AI for gs://, Bedrock for s3://)\n case 'gs:':\n case 's3:': {\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({ type: 'image', image: url.toString(), mimeType: attachment.contentType });\n } else {\n if (!attachment.contentType) {\n throw new Error('If the attachment is not an image, it must specify a content type');\n }\n\n parts.push({\n type: 'file',\n data: url.toString(),\n mimeType: attachment.contentType,\n });\n }\n break;\n }\n\n case 'data:': {\n if (attachment.contentType?.startsWith('image/')) {\n parts.push({\n type: 'image',\n image: urlString,\n mimeType: attachment.contentType,\n });\n } else if (attachment.contentType?.startsWith('text/')) {\n parts.push({\n type: 'file',\n data: urlString,\n mimeType: attachment.contentType,\n });\n } else {\n if (!attachment.contentType) {\n throw new Error('If the attachment is not an image or text, it must specify a content type');\n }\n\n parts.push({\n type: 'file',\n data: urlString,\n mimeType: attachment.contentType,\n });\n }\n\n break;\n }\n\n default: {\n throw new Error(`Unsupported URL protocol: ${url.protocol}`);\n }\n }\n }\n\n return parts;\n}\n","/**\n * This file is an adaptation of https://github.com/vercel/ai/blob/e14c066bf4d02c5ee2180c56a01fa0e5216bc582/packages/ai/core/prompt/convert-to-core-messages.ts\n * But has been modified to work with Mastra storage adapter messages (MastraMessageV1)\n */\nimport type { AssistantContent, ToolResultPart } from '@internal/ai-sdk-v4';\nimport type { MastraMessageV1 } from '../../../memory/types';\nimport type { MastraMessageContentV2, MastraDBMessage } from '../../message-list';\nimport { attachmentsToParts } from './attachments-to-parts';\nimport { resolveFilePartMediaTypeAndData } from './image-utils';\n\nconst makePushOrCombine = (v1Messages: MastraMessageV1[]) => {\n // Track how many times each ID has been used to create unique IDs for split messages\n const idUsageCount = new Map<string, number>();\n\n // Pattern to detect if an ID already has our split suffix\n const SPLIT_SUFFIX_PATTERN = /__split-\\d+$/;\n\n return (msg: MastraMessageV1) => {\n const previousMessage = v1Messages.at(-1);\n if (\n msg.role === previousMessage?.role &&\n Array.isArray(previousMessage.content) &&\n Array.isArray(msg.content) &&\n // we were creating new messages for tool calls before and not appending to the assistant message\n // so don't append here so everything works as before\n (msg.role !== `assistant` || (msg.role === `assistant` && msg.content.at(-1)?.type !== `tool-call`))\n ) {\n for (const part of msg.content) {\n // @ts-expect-error needs type gymnastics? msg.content and previousMessage.content are the same type here since both are arrays\n previousMessage.content.push(part);\n }\n } else {\n // When pushing a new message, check if we need to deduplicate the ID\n let baseId = msg.id;\n\n // Check if this ID already has a split suffix and extract the base ID\n const hasSplitSuffix = SPLIT_SUFFIX_PATTERN.test(baseId);\n if (hasSplitSuffix) {\n // This ID already has a split suffix, don't add another one\n v1Messages.push(msg);\n return;\n }\n\n const currentCount = idUsageCount.get(baseId) || 0;\n\n // If we've seen this ID before, append our unique split suffix\n if (currentCount > 0) {\n msg.id = `${baseId}__split-${currentCount}`;\n }\n\n // Increment the usage count for this base ID\n idUsageCount.set(baseId, currentCount + 1);\n\n v1Messages.push(msg);\n }\n };\n};\nexport function convertToV1Messages(messages: Array<MastraDBMessage>) {\n const v1Messages: MastraMessageV1[] = [];\n const pushOrCombine = makePushOrCombine(v1Messages);\n\n for (let i = 0; i < messages.length; i++) {\n const message = messages[i];\n const isLastMessage = i === messages.length - 1;\n if (!message?.content) continue;\n const { content, experimental_attachments: inputAttachments = [], parts: inputParts } = message.content;\n const { role } = message;\n\n const fields = {\n id: message.id,\n createdAt: message.createdAt,\n resourceId: message.resourceId!,\n threadId: message.threadId!,\n };\n\n const experimental_attachments = [...inputAttachments];\n const parts: typeof inputParts = [];\n for (const part of inputParts) {\n if (part.type === 'file') {\n // Persisted parts use the AI SDK v4 shape (`mimeType`/`data`), but parts that\n // originate from agent output or user uploads can arrive in the v5 shape\n // (`mediaType`/`url`). The stored union only describes v4, so read both — a v5\n // file part would otherwise persist with `contentType: undefined`, which makes\n // `attachmentsToParts` throw. Mirrors #17366.\n const { mediaType, data } = resolveFilePartMediaTypeAndData(part);\n experimental_attachments.push({\n url: data as string,\n contentType: mediaType ?? 'application/octet-stream',\n });\n } else {\n parts.push(part);\n }\n }\n\n switch (role) {\n case 'user': {\n if (parts == null) {\n const userContent = experimental_attachments\n ? [{ type: 'text', text: content || '' }, ...attachmentsToParts(experimental_attachments)]\n : { type: 'text', text: content || '' };\n pushOrCombine({\n role: 'user',\n ...fields,\n type: 'text',\n // @ts-expect-error - content type mismatch in conversion\n content: userContent,\n });\n } else {\n const textParts = message.content.parts\n .filter(part => part.type === 'text')\n .map(part => ({\n type: 'text' as const,\n text: part.text,\n }));\n\n const userContent = experimental_attachments\n ? [...textParts, ...attachmentsToParts(experimental_attachments)]\n : textParts;\n pushOrCombine({\n role: 'user',\n ...fields,\n type: 'text',\n content:\n Array.isArray(userContent) &&\n userContent.length === 1 &&\n userContent[0]?.type === `text` &&\n typeof content !== `undefined`\n ? content\n : userContent,\n });\n }\n break;\n }\n\n case 'assistant': {\n if (message.content.parts != null) {\n let currentStep = 0;\n let blockHasToolInvocations = false;\n let block: MastraMessageContentV2['parts'] = [];\n\n function processBlock() {\n const content: AssistantContent = [];\n\n for (const part of block) {\n switch (part.type) {\n case 'file':\n case 'text': {\n content.push(part);\n break;\n }\n case 'reasoning': {\n for (const detail of part.details) {\n switch (detail.type) {\n case 'text':\n content.push({\n type: 'reasoning' as const,\n text: detail.text,\n signature: detail.signature,\n });\n break;\n case 'redacted':\n content.push({\n type: 'redacted-reasoning' as const,\n data: detail.data,\n });\n break;\n }\n }\n break;\n }\n case 'tool-invocation':\n // Skip updateWorkingMemory tool calls as they should not be visible in history\n if (part.toolInvocation.toolName !== 'updateWorkingMemory') {\n content.push({\n type: 'tool-call' as const,\n toolCallId: part.toolInvocation.toolCallId,\n toolName: part.toolInvocation.toolName,\n args: part.toolInvocation.args,\n });\n }\n break;\n }\n }\n\n pushOrCombine({\n role: 'assistant',\n ...fields,\n type: content.some(c => c.type === `tool-call`) ? 'tool-call' : 'text',\n content:\n typeof content !== `string` &&\n Array.isArray(content) &&\n content.length === 1 &&\n content[0]?.type === `text`\n ? content[0].text\n : content,\n });\n\n // check if there are tool invocations with results in the block\n const stepInvocations = block\n .filter(part => `type` in part && part.type === 'tool-invocation')\n .map(part => part.toolInvocation)\n .filter(ti => ti.toolName !== 'updateWorkingMemory');\n\n // Only create tool-result message if there are actual results\n const invocationsWithResults = stepInvocations.filter(ti => ti.state === 'result' && 'result' in ti);\n\n if (invocationsWithResults.length > 0) {\n pushOrCombine({\n role: 'tool',\n ...fields,\n type: 'tool-result',\n content: invocationsWithResults.map((toolInvocation): ToolResultPart => {\n const { toolCallId, toolName, result } = toolInvocation;\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n }),\n });\n }\n\n // updates for next block\n block = [];\n blockHasToolInvocations = false;\n currentStep++;\n }\n\n for (const part of message.content.parts) {\n switch (part.type) {\n case 'text': {\n if (blockHasToolInvocations) {\n processBlock(); // text must come after tool invocations\n }\n block.push(part);\n break;\n }\n case 'file':\n case 'reasoning': {\n block.push(part);\n break;\n }\n case 'tool-invocation': {\n // If we have non-tool content (text/file/reasoning) in the block, process it first\n const hasNonToolContent = block.some(\n p => p.type === 'text' || p.type === 'file' || p.type === 'reasoning',\n );\n if (hasNonToolContent || (part.toolInvocation.step ?? 0) !== currentStep) {\n processBlock();\n }\n block.push(part);\n blockHasToolInvocations = true;\n break;\n }\n }\n }\n\n processBlock();\n\n // Check if there are toolInvocations that weren't processed from parts\n const toolInvocations = message.content.toolInvocations;\n if (toolInvocations && toolInvocations.length > 0) {\n // Find tool invocations that weren't already processed from parts\n const processedToolCallIds = new Set<string>();\n for (const part of message.content.parts) {\n if (part.type === 'tool-invocation' && part.toolInvocation.toolCallId) {\n processedToolCallIds.add(part.toolInvocation.toolCallId);\n }\n }\n\n const unprocessedToolInvocations = toolInvocations.filter(\n ti => !processedToolCallIds.has(ti.toolCallId) && ti.toolName !== 'updateWorkingMemory',\n );\n\n if (unprocessedToolInvocations.length > 0) {\n // Group by step, handling undefined steps\n const invocationsByStep = new Map<number, typeof unprocessedToolInvocations>();\n\n for (const inv of unprocessedToolInvocations) {\n const step = inv.step ?? 0;\n if (!invocationsByStep.has(step)) {\n invocationsByStep.set(step, []);\n }\n invocationsByStep.get(step)!.push(inv);\n }\n\n // Process each step\n const sortedSteps = Array.from(invocationsByStep.keys()).sort((a, b) => a - b);\n\n for (const step of sortedSteps) {\n const stepInvocations = invocationsByStep.get(step)!;\n\n // Create tool-call message for all invocations (calls and results)\n pushOrCombine({\n role: 'assistant',\n ...fields,\n type: 'tool-call',\n content: [\n ...stepInvocations.map(({ toolCallId, toolName, args }) => ({\n type: 'tool-call' as const,\n toolCallId,\n toolName,\n args,\n })),\n ],\n });\n\n // Only create tool-result message if there are actual results\n const invocationsWithResults = stepInvocations.filter(ti => ti.state === 'result' && 'result' in ti);\n\n if (invocationsWithResults.length > 0) {\n pushOrCombine({\n role: 'tool',\n ...fields,\n type: 'tool-result',\n content: invocationsWithResults.map((toolInvocation): ToolResultPart => {\n const { toolCallId, toolName, result } = toolInvocation;\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n }),\n });\n }\n }\n }\n }\n\n break;\n }\n\n const toolInvocations = message.content.toolInvocations;\n\n if (toolInvocations == null || toolInvocations.length === 0) {\n pushOrCombine({ role: 'assistant', ...fields, content: content || '', type: 'text' });\n break;\n }\n\n const maxStep = toolInvocations.reduce((max, toolInvocation) => {\n return Math.max(max, toolInvocation.step ?? 0);\n }, 0);\n\n for (let i = 0; i <= maxStep; i++) {\n const stepInvocations = toolInvocations.filter(\n toolInvocation => (toolInvocation.step ?? 0) === i && toolInvocation.toolName !== 'updateWorkingMemory',\n );\n\n if (stepInvocations.length === 0) {\n continue;\n }\n\n // assistant message with tool calls\n pushOrCombine({\n role: 'assistant',\n ...fields,\n type: 'tool-call',\n content: [\n ...(isLastMessage && content && i === 0 ? [{ type: 'text' as const, text: content }] : []),\n ...stepInvocations.map(({ toolCallId, toolName, args }) => ({\n type: 'tool-call' as const,\n toolCallId,\n toolName,\n args,\n })),\n ],\n });\n\n // Only create tool-result message if there are actual results\n const invocationsWithResults = stepInvocations.filter(ti => ti.state === 'result' && 'result' in ti);\n\n if (invocationsWithResults.length > 0) {\n pushOrCombine({\n role: 'tool',\n ...fields,\n type: 'tool-result',\n content: invocationsWithResults.map((toolInvocation): ToolResultPart => {\n const { toolCallId, toolName, result } = toolInvocation;\n return {\n type: 'tool-result',\n toolCallId,\n toolName,\n result,\n };\n }),\n });\n }\n }\n\n if (content && !isLastMessage) {\n pushOrCombine({ role: 'assistant', ...fields, type: 'text', content: content || '' });\n }\n\n break;\n }\n }\n }\n\n return v1Messages;\n}\n","import { isUrlSupported } from '@ai-sdk/provider-utils-v6';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../../error';\nimport { fetchWithRetry } from '../../../utils/fetchWithRetry';\nimport type { AIV5Type } from '../types';\n\n/**\n * Strip query string and fragment from a URL for inclusion in human-readable\n * error text. Signed-URL query params (e.g. AWS pre-signed `X-Amz-Signature`,\n * WhatsApp media tokens, GCS `X-Goog-Signature`) carry secrets that should not\n * land in logs — but the scheme, host, and path are still useful for diagnosis.\n *\n * The full, unredacted URL is preserved on `error.details.url` for callers that\n * need to react programmatically (e.g. matching a failing URL back to the\n * specific message part for recovery). Mirrors the project convention of\n * redacting at the human-facing log boundary while keeping structured fields\n * raw (see `SENSITIVE_KEYS` in `tools/validation.ts` and `redactHeaders` in\n * server config).\n */\nfunction redactUrlForLog(url: URL): string {\n if (url.protocol === 'data:') {\n // `origin` is \"null\" for data URLs and the pathname is the whole (possibly huge) payload.\n const commaIndex = url.pathname.indexOf(',');\n const header = commaIndex === -1 ? url.pathname : url.pathname.slice(0, commaIndex);\n const payloadLength = commaIndex === -1 ? 0 : url.pathname.length - commaIndex - 1;\n return `data:${header},<${payloadLength} chars>`;\n }\n return `${url.origin}${url.pathname}`;\n}\n\nexport const downloadFromUrl = async ({ url, downloadRetries }: { url: URL; downloadRetries: number }) => {\n const urlText = url.toString();\n const safeUrl = redactUrlForLog(url);\n\n try {\n const response = await fetchWithRetry(\n urlText,\n {\n method: 'GET',\n },\n // Decoding a data URL is deterministic, so retrying a failure only adds delay.\n url.protocol === 'data:' ? 1 : downloadRetries,\n {\n shouldRetryResponse: response => response.status >= 500,\n },\n );\n\n if (!response.ok) {\n throw new MastraError({\n id: 'DOWNLOAD_ASSETS_FAILED',\n text: `Failed to download asset: ${safeUrl}`,\n domain: ErrorDomain.LLM,\n category: ErrorCategory.USER,\n details: { url: urlText },\n });\n }\n return {\n data: new Uint8Array(await response.arrayBuffer()),\n mediaType: response.headers.get('content-type') ?? undefined,\n };\n } catch (error) {\n throw new MastraError(\n {\n id: 'DOWNLOAD_ASSETS_FAILED',\n text: `Failed to download asset: ${safeUrl}`,\n domain: ErrorDomain.LLM,\n category: ErrorCategory.USER,\n details: { url: urlText },\n },\n error,\n );\n }\n};\n\nfunction toAssetUrl(part: AIV5Type.ImagePart | AIV5Type.FilePart) {\n const data = part.type === 'image' ? part.image : part.data;\n if (typeof data !== 'string') return data;\n try {\n return new URL(data);\n } catch {\n return data;\n }\n}\n\n/** The key a part's download result is stored under, or `undefined` when the part is not a URL. */\nexport function getAssetUrl(part: AIV5Type.ImagePart | AIV5Type.FilePart): string | undefined {\n const data = toAssetUrl(part);\n return data instanceof URL ? data.toString() : undefined;\n}\n\n/**\n * Successful downloads keyed by URL, shared across the prompt builds of one run so\n * each attachment is downloaded at most once per run. Failures are not kept, so a\n * retry requested by an error processor fetches again.\n */\nexport type AssetDownloadCache = Map<string, ReturnType<typeof downloadFromUrl>>;\n\nexport function isDownloadAssetsError(error: unknown): error is MastraError {\n return error instanceof MastraError && error.id === 'DOWNLOAD_ASSETS_FAILED';\n}\n\nexport async function downloadAssetsFromMessages({\n messages,\n downloadConcurrency = 10,\n downloadRetries = 3,\n supportedUrls,\n cache,\n isUnavailable,\n onUnavailable,\n}: {\n messages: AIV5Type.ModelMessage[];\n downloadConcurrency?: number;\n downloadRetries?: number;\n supportedUrls?: Record<string, RegExp[]>;\n cache?: AssetDownloadCache;\n /** Returns true for URLs already known to be unavailable. They are not fetched. */\n isUnavailable?: (url: string) => boolean;\n /** When set, a failed download is reported here instead of failing the whole prompt. */\n onUnavailable?: (url: string, error: MastraError) => void;\n}) {\n const pMap = (await import('p-map')).default;\n\n const filesToDownload = messages\n .filter(message => message.role === 'user')\n .map(message => message.content)\n .filter(content => Array.isArray(content))\n .flat()\n .filter(part => part.type === 'image' || part.type === 'file')\n .map(part => {\n const mediaType = part.mediaType ?? (part.type === 'image' ? 'image/*' : undefined);\n\n return { mediaType, data: toAssetUrl(part) };\n })\n\n .filter((part): part is { mediaType: string | undefined; data: URL } => part.data instanceof URL)\n .map(part => {\n return {\n url: part.data,\n isUrlSupportedByModel:\n part.mediaType != null &&\n isUrlSupported({\n url: part.data.toString(),\n mediaType: part.mediaType,\n supportedUrls: supportedUrls ?? {},\n }),\n };\n });\n\n const downloadedFiles = await pMap(\n filesToDownload,\n async fileItem => {\n const url = fileItem.url.toString();\n if (fileItem.isUrlSupportedByModel || isUnavailable?.(url)) {\n return null;\n }\n let download = cache?.get(url);\n if (!download) {\n download = downloadFromUrl({ url: fileItem.url, downloadRetries });\n if (cache) {\n const cached = download;\n cache.set(url, cached);\n cached.catch(() => {\n if (cache.get(url) === cached) cache.delete(url);\n });\n }\n }\n try {\n return { url, ...(await download) };\n } catch (error) {\n if (!onUnavailable || !isDownloadAssetsError(error)) throw error;\n onUnavailable(url, error);\n return null;\n }\n },\n {\n concurrency: downloadConcurrency,\n },\n );\n\n const downloadFileList = downloadedFiles\n .filter(\n (\n downloadedFile,\n ): downloadedFile is {\n url: string;\n mediaType: string | undefined;\n data: Uint8Array<ArrayBuffer>;\n } => downloadedFile?.data != null,\n )\n .map(({ url, data, mediaType }) => [url, { data, mediaType }]);\n\n return Object.fromEntries(downloadFileList);\n}\n","import type { MastraDBMessage } from '../state/types';\nimport { resolveFilePartMediaTypeAndData } from './image-utils';\n\n/**\n * Attachment URLs that could not be downloaded are recorded on their user message under\n * `content.metadata.mastra.unavailableAttachments`, so later turns render the same\n * placeholder without fetching them again. What a thread's history produces then stays\n * stable instead of changing with each URL's availability. Data URLs are not recorded:\n * decoding one is local and deterministic, so a bad one is detected again at no cost.\n */\nconst METADATA_KEY = 'unavailableAttachments';\n\nexport function getUnavailableAttachmentUrls(message: MastraDBMessage): string[] {\n const mastra = message.content.metadata?.mastra;\n if (!mastra || typeof mastra !== 'object') return [];\n const urls = (mastra as Record<string, unknown>)[METADATA_KEY];\n return Array.isArray(urls) ? urls.filter((url): url is string => typeof url === 'string') : [];\n}\n\nexport function withUnavailableAttachmentUrls(\n metadata: Record<string, unknown> | undefined,\n urls: Iterable<string>,\n): Record<string, unknown> {\n const mastra = (metadata?.mastra as Record<string, unknown> | undefined) ?? {};\n const existing = Array.isArray(mastra[METADATA_KEY]) ? (mastra[METADATA_KEY] as string[]) : [];\n return {\n ...metadata,\n mastra: { ...mastra, [METADATA_KEY]: [...new Set([...existing, ...urls])] },\n };\n}\n\nfunction toUrlString(data: unknown): string | undefined {\n if (data instanceof URL) return data.toString();\n // Data URLs are never recorded; skip parsing (and copying) their payloads.\n if (typeof data !== 'string' || data.startsWith('data:')) return undefined;\n try {\n return new URL(data).toString();\n } catch {\n return undefined;\n }\n}\n\nexport function unavailableAttachmentPlaceholder(name: string): string {\n return `[Attachment unavailable: ${name}]`;\n}\n\n/**\n * Returns a copy of a user message with the attachments it recorded as unavailable\n * replaced by a placeholder text part, so they are neither fetched nor sent. The record\n * is per message: another message carrying the same URL is downloaded as usual.\n */\nexport function withUnavailableAttachmentPlaceholders(message: MastraDBMessage): MastraDBMessage {\n const recorded = new Set(getUnavailableAttachmentUrls(message));\n if (message.role !== 'user' || recorded.size === 0) return message;\n const isRecorded = (data: unknown) => {\n const url = toUrlString(data);\n return url !== undefined && recorded.has(url);\n };\n const placeholder = (name: string) => ({ type: 'text' as const, text: unavailableAttachmentPlaceholder(name) });\n\n const parts = message.content.parts ?? [];\n const attachments = message.content.experimental_attachments ?? [];\n const replacedUrls = new Set<string>();\n const replacedParts = parts.map(part => {\n if (part.type !== 'file') return part;\n const { mediaType, data } = resolveFilePartMediaTypeAndData(part);\n const url = toUrlString(data);\n if (url === undefined || !recorded.has(url)) return part;\n replacedUrls.add(url);\n return placeholder((part as { filename?: string }).filename || mediaType || 'file');\n });\n // The adapter turns attachments into prompt parts when no file parts are left, so a recorded\n // one has to go as well or it would be fetched from the attachment list instead. An attachment\n // that only repeats a file part's URL is already covered by that part's placeholder.\n const recordedAttachments = attachments.filter(attachment => {\n const url = toUrlString(attachment.url);\n return url !== undefined && recorded.has(url) && !replacedUrls.has(url);\n });\n const droppedAttachments = attachments.filter(attachment => isRecorded(attachment.url));\n if (replacedUrls.size === 0 && droppedAttachments.length === 0) return message;\n\n // Once parts hold text, the adapter no longer reads `content.content`; keep it.\n const text = message.content.content;\n const contentText =\n typeof text === 'string' && text && !replacedParts.some(part => part.type === 'text')\n ? [{ type: 'text' as const, text }]\n : [];\n return {\n ...message,\n content: {\n ...message.content,\n parts: [\n ...recordedAttachments.map(attachment => placeholder(attachment.name || attachment.contentType || 'unknown')),\n ...contentText,\n ...replacedParts,\n ],\n ...(droppedAttachments.length > 0\n ? { experimental_attachments: attachments.filter(attachment => !isRecorded(attachment.url)) }\n : {}),\n },\n };\n}\n\n/**\n * Recordable (non-data) URLs of a stored message's file parts and attachments,\n * normalized like the prompt's asset URLs.\n */\nexport function getMessageAttachmentUrls(message: MastraDBMessage): string[] {\n const urls: string[] = [];\n for (const part of message.content.parts ?? []) {\n if (part.type !== 'file') continue;\n const url = toUrlString(resolveFilePartMediaTypeAndData(part).data);\n if (url) urls.push(url);\n }\n for (const attachment of message.content.experimental_attachments ?? []) {\n const url = toUrlString(attachment.url);\n if (url) urls.push(url);\n }\n return urls;\n}\n","import type { MastraDBMessage } from './types';\n\n/**\n * Serialized form of a MastraDBMessage where Date is converted to string\n */\nexport type SerializedMessage = Omit<MastraDBMessage, 'createdAt'> & {\n createdAt: string;\n};\n\n/**\n * Serialize a message by converting Date to string\n */\nexport function serializeMessage(message: MastraDBMessage): SerializedMessage {\n return {\n ...message,\n createdAt: message.createdAt.toISOString(),\n };\n}\n\n/**\n * Deserialize a message by converting string back to Date\n */\nexport function deserializeMessage(message: SerializedMessage): MastraDBMessage {\n return {\n ...message,\n createdAt: new Date(message.createdAt),\n } as MastraDBMessage;\n}\n\n/**\n * Serialize an array of messages\n */\nexport function serializeMessages(messages: MastraDBMessage[]): SerializedMessage[] {\n return messages.map(serializeMessage);\n}\n\n/**\n * Deserialize an array of messages\n */\nexport function deserializeMessages(messages: SerializedMessage[]): MastraDBMessage[] {\n return messages.map(deserializeMessage);\n}\n","import type { CoreSystemMessage } from '@internal/ai-sdk-v4';\n\nimport { serializeMessages, deserializeMessages } from './serialization';\nimport type { SerializedMessage } from './serialization';\nimport type { MastraDBMessage, MessageSource, MemoryInfo } from './types';\n\n// Re-export for backward compatibility\nexport type { MessageSource };\n\n/**\n * MessageStateManager - Manages the state of messages in a MessageList\n *\n * Handles:\n * - Tracking messages by their source (memory, input, response, context)\n * - Tracking which messages have been persisted\n * - Providing efficient lookups for message categorization\n *\n * This replaces the 8 Sets in the original MessageList with a more manageable interface.\n */\nexport class MessageStateManager {\n // Messages tracked by source\n private memoryMessages = new Set<MastraDBMessage>();\n private newUserMessages = new Set<MastraDBMessage>();\n private newResponseMessages = new Set<MastraDBMessage>();\n private userContextMessages = new Set<MastraDBMessage>();\n\n // Persisted message tracking\n private memoryMessagesPersisted = new Set<MastraDBMessage>();\n private newUserMessagesPersisted = new Set<MastraDBMessage>();\n private newResponseMessagesPersisted = new Set<MastraDBMessage>();\n private userContextMessagesPersisted = new Set<MastraDBMessage>();\n\n /**\n * Add a message to the appropriate source set and persisted set\n */\n addToSource(message: MastraDBMessage, source: MessageSource): void {\n switch (source) {\n case 'memory':\n this.memoryMessages.add(message);\n this.memoryMessagesPersisted.add(message);\n break;\n case 'response':\n // Promoting from memory (e.g. OM step prepare → merge step-2 text): keep a single\n // canonical source so clear.response.db() cannot drop merged content while the\n // message remains only in memoryMessages.\n if (this.memoryMessages.has(message)) {\n this.memoryMessages.delete(message);\n }\n this.newResponseMessages.add(message);\n this.newResponseMessagesPersisted.add(message);\n // Handle case where a client-side tool response was added as user input\n if (this.newUserMessages.has(message)) {\n this.newUserMessages.delete(message);\n }\n break;\n case 'input':\n case 'user': // deprecated alias for input\n this.newUserMessages.add(message);\n this.newUserMessagesPersisted.add(message);\n break;\n case 'context':\n this.userContextMessages.add(message);\n this.userContextMessagesPersisted.add(message);\n break;\n default:\n throw new Error(`Missing message source for message ${message}`);\n }\n }\n\n /**\n * Check if a message belongs to the memory source\n */\n isMemoryMessage(message: MastraDBMessage): boolean {\n return this.memoryMessages.has(message);\n }\n\n /**\n * Check if a message belongs to the input source\n */\n isUserMessage(message: MastraDBMessage): boolean {\n return this.newUserMessages.has(message);\n }\n\n /**\n * Check if a message belongs to the response source\n */\n isResponseMessage(message: MastraDBMessage): boolean {\n return this.newResponseMessages.has(message);\n }\n\n /**\n * Check if a message belongs to the context source\n */\n isContextMessage(message: MastraDBMessage): boolean {\n return this.userContextMessages.has(message);\n }\n\n /**\n * Get all memory messages\n */\n getMemoryMessages(): Set<MastraDBMessage> {\n return this.memoryMessages;\n }\n\n /**\n * Get all user/input messages\n */\n getUserMessages(): Set<MastraDBMessage> {\n return this.newUserMessages;\n }\n\n /**\n * Get all response messages\n */\n getResponseMessages(): Set<MastraDBMessage> {\n return this.newResponseMessages;\n }\n\n /**\n * Get all context messages\n */\n getContextMessages(): Set<MastraDBMessage> {\n return this.userContextMessages;\n }\n\n /**\n * Get persisted memory messages\n */\n getMemoryMessagesPersisted(): Set<MastraDBMessage> {\n return this.memoryMessagesPersisted;\n }\n\n /**\n * Get persisted user/input messages\n */\n getUserMessagesPersisted(): Set<MastraDBMessage> {\n return this.newUserMessagesPersisted;\n }\n\n /**\n * Get persisted response messages\n */\n getResponseMessagesPersisted(): Set<MastraDBMessage> {\n return this.newResponseMessagesPersisted;\n }\n\n /**\n * Get persisted context messages\n */\n getContextMessagesPersisted(): Set<MastraDBMessage> {\n return this.userContextMessagesPersisted;\n }\n\n /**\n * Remove a message from all source sets\n */\n removeMessage(message: MastraDBMessage): void {\n this.memoryMessages.delete(message);\n this.newUserMessages.delete(message);\n this.newResponseMessages.delete(message);\n this.userContextMessages.delete(message);\n }\n\n /**\n * Clear all user messages\n */\n clearUserMessages(): void {\n this.newUserMessages.clear();\n }\n\n /**\n * Clear all response messages\n */\n clearResponseMessages(): void {\n this.newResponseMessages.clear();\n }\n\n /**\n * Clear all context messages\n */\n clearContextMessages(): void {\n this.userContextMessages.clear();\n }\n\n /**\n * Clear all messages from all sources (but not persisted tracking)\n */\n clearAll(): void {\n this.newUserMessages.clear();\n this.newResponseMessages.clear();\n this.userContextMessages.clear();\n }\n\n /**\n * Create a lookup function to determine message source\n */\n createSourceChecker(): {\n memory: Set<string>;\n input: Set<string>;\n output: Set<string>;\n context: Set<string>;\n getSource: (message: MastraDBMessage) => MessageSource | null;\n } {\n const sources = {\n memory: new Set(Array.from(this.memoryMessages.values()).map(m => m.id)),\n output: new Set(Array.from(this.newResponseMessages.values()).map(m => m.id)),\n input: new Set(Array.from(this.newUserMessages.values()).map(m => m.id)),\n context: new Set(Array.from(this.userContextMessages.values()).map(m => m.id)),\n };\n\n return {\n ...sources,\n getSource: (msg: MastraDBMessage): MessageSource | null => {\n if (sources.memory.has(msg.id)) return 'memory';\n if (sources.input.has(msg.id)) return 'input';\n if (sources.output.has(msg.id)) return 'response';\n if (sources.context.has(msg.id)) return 'context';\n return null;\n },\n };\n }\n\n /**\n * Check if a message is a new (unsaved) user or response message by ID\n */\n isNewMessage(messageOrId: MastraDBMessage | string): boolean {\n const id = typeof messageOrId === 'string' ? messageOrId : messageOrId.id;\n\n // Check by object reference first (fast path)\n if (typeof messageOrId !== 'string') {\n if (this.newUserMessages.has(messageOrId) || this.newResponseMessages.has(messageOrId)) {\n return true;\n }\n }\n\n // Check by ID (handles copies)\n return (\n Array.from(this.newUserMessages).some(m => m.id === id) ||\n Array.from(this.newResponseMessages).some(m => m.id === id)\n );\n }\n\n /**\n * Serialize source tracking state (message IDs only)\n */\n private serializeSourceTracking(): {\n memoryMessages: string[];\n newUserMessages: string[];\n newResponseMessages: string[];\n userContextMessages: string[];\n memoryMessagesPersisted: string[];\n newUserMessagesPersisted: string[];\n newResponseMessagesPersisted: string[];\n userContextMessagesPersisted: string[];\n } {\n const serializeSet = (set: Set<MastraDBMessage>) => Array.from(set).map(value => value.id);\n\n return {\n memoryMessages: serializeSet(this.memoryMessages),\n newUserMessages: serializeSet(this.newUserMessages),\n newResponseMessages: serializeSet(this.newResponseMessages),\n userContextMessages: serializeSet(this.userContextMessages),\n memoryMessagesPersisted: serializeSet(this.memoryMessagesPersisted),\n newUserMessagesPersisted: serializeSet(this.newUserMessagesPersisted),\n newResponseMessagesPersisted: serializeSet(this.newResponseMessagesPersisted),\n userContextMessagesPersisted: serializeSet(this.userContextMessagesPersisted),\n };\n }\n\n /**\n * Deserialize source tracking state from message IDs\n */\n private deserializeSourceTracking(\n state: ReturnType<typeof this.serializeSourceTracking>,\n messages: MastraDBMessage[],\n ): void {\n const deserializeSet = (ids: string[]) =>\n new Set(ids.map(id => messages.find(m => m.id === id)).filter(Boolean) as MastraDBMessage[]);\n\n this.memoryMessages = deserializeSet(state.memoryMessages);\n this.newUserMessages = deserializeSet(state.newUserMessages);\n this.newResponseMessages = deserializeSet(state.newResponseMessages);\n this.userContextMessages = deserializeSet(state.userContextMessages);\n this.memoryMessagesPersisted = deserializeSet(state.memoryMessagesPersisted);\n this.newUserMessagesPersisted = deserializeSet(state.newUserMessagesPersisted);\n this.newResponseMessagesPersisted = deserializeSet(state.newResponseMessagesPersisted);\n this.userContextMessagesPersisted = deserializeSet(state.userContextMessagesPersisted);\n }\n\n /**\n * Serialize all MessageList state for workflow suspend/resume\n */\n serializeAll(data: {\n messages: MastraDBMessage[];\n systemMessages: CoreSystemMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n memoryInfo: MemoryInfo | null;\n agentNetworkAppend: boolean;\n }): SerializedMessageListState {\n return {\n messages: serializeMessages(data.messages),\n systemMessages: data.systemMessages,\n taggedSystemMessages: data.taggedSystemMessages,\n memoryInfo: data.memoryInfo,\n _agentNetworkAppend: data.agentNetworkAppend,\n ...this.serializeSourceTracking(),\n };\n }\n\n /**\n * Deserialize all MessageList state from workflow suspend/resume\n */\n deserializeAll(state: SerializedMessageListState): {\n messages: MastraDBMessage[];\n systemMessages: CoreSystemMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n memoryInfo: MemoryInfo | null;\n agentNetworkAppend: boolean;\n } {\n const messages = deserializeMessages(state.messages);\n\n this.deserializeSourceTracking(\n {\n memoryMessages: state.memoryMessages,\n newUserMessages: state.newUserMessages,\n newResponseMessages: state.newResponseMessages,\n userContextMessages: state.userContextMessages,\n memoryMessagesPersisted: state.memoryMessagesPersisted,\n newUserMessagesPersisted: state.newUserMessagesPersisted,\n newResponseMessagesPersisted: state.newResponseMessagesPersisted,\n userContextMessagesPersisted: state.userContextMessagesPersisted,\n },\n messages,\n );\n\n return {\n messages,\n systemMessages: state.systemMessages,\n taggedSystemMessages: state.taggedSystemMessages,\n memoryInfo: state.memoryInfo,\n agentNetworkAppend: state._agentNetworkAppend,\n };\n }\n}\n\n/**\n * Serialized form of the complete MessageList state\n */\nexport interface SerializedMessageListState {\n messages: SerializedMessage[];\n systemMessages: CoreSystemMessage[];\n taggedSystemMessages: Record<string, CoreSystemMessage[]>;\n memoryInfo: MemoryInfo | null;\n _agentNetworkAppend: boolean;\n memoryMessages: string[];\n newUserMessages: string[];\n newResponseMessages: string[];\n userContextMessages: string[];\n memoryMessagesPersisted: string[];\n newUserMessagesPersisted: string[];\n newResponseMessagesPersisted: string[];\n userContextMessagesPersisted: string[];\n /**\n * Ids of the run's response messages that were pruned from `messages` (e.g. after observational\n * memory observed and saved them). Only ids, so suspend state does not grow with pruning; the\n * messages are loaded from memory when the whole run is needed (see getRunResponseMessages).\n */\n prunedResponseMessageIds?: string[];\n /** Where the latest loop-iteration boundary sits, so a restored list scopes final-step text the same way. */\n lastStepBoundary?: { messageId: string; partIndex: number };\n /**\n * Messages this run already wrote to the semantic recall index, as message id -> hash of the\n * embedded text. Absent when nothing was embedded, and in snapshots written before it existed.\n */\n embeddedMessages?: Record<string, string>;\n}\n","import type { MastraToolInvocation } from '../state/types';\n\ntype ToolInvocationState = MastraToolInvocation['state'];\n\n// How far a tool invocation has progressed. A tool part may only be moved forward by a later copy\n// of the same call; a copy at the same or an earlier stage never overwrites what is stored.\nconst TOOL_INVOCATION_STATE_RANK: Record<ToolInvocationState, number> = {\n 'partial-call': 0,\n call: 1,\n 'approval-requested': 2,\n // Still pending: the approval was answered, but the tool has not produced its outcome yet.\n 'approval-responded': 3,\n result: 4,\n 'output-error': 4,\n 'output-denied': 4,\n};\n\nexport function isTerminalToolInvocationState(state: ToolInvocationState): boolean {\n return TOOL_INVOCATION_STATE_RANK[state] === TOOL_INVOCATION_STATE_RANK.result;\n}\n\n/** States a client can contribute for a call the server left pending: an approval answer or an outcome. */\nexport function isClientToolInvocationUpdate(state: ToolInvocationState): boolean {\n return state === 'approval-responded' || isTerminalToolInvocationState(state);\n}\n\n/** Whether `incoming` moves a stored tool invocation in state `stored` forward. */\nexport function advancesToolInvocationState(stored: ToolInvocationState, incoming: ToolInvocationState): boolean {\n return (\n !isTerminalToolInvocationState(stored) && TOOL_INVOCATION_STATE_RANK[incoming] > TOOL_INVOCATION_STATE_RANK[stored]\n );\n}\n","import type { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport type { LanguageModelV1Prompt, CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\nimport type * as AIV4Type from '@internal/ai-sdk-v4';\nimport { v4 as randomUUID } from '@lukeed/uuid';\n\nimport { MastraError, ErrorDomain, ErrorCategory } from '../../error';\nimport type { IMastraLogger } from '../../logger';\nimport type { AnySpan } from '../../observability/types';\nimport { resolveCurrentSpan } from '../../observability/utils';\nimport { getTransformedToolPayload, hasTransformedToolPayload } from '../../tools/payload-transform';\nimport type { IdGeneratorContext } from '../../types';\nimport { safeStringify } from '../../utils/safe-stringify';\nimport { createSignal, isCreatedAgentSignal, isTransientSignalMessage, mastraDBMessageToSignal } from '../signals';\nimport type { CreatedAgentSignal } from '../signals';\nimport { AIV4Adapter, AIV5Adapter, AIV6Adapter } from './adapters';\nimport { CacheKeyGenerator } from './cache/CacheKeyGenerator';\nimport {\n aiV4CoreMessageToV1PromptMessage,\n aiV5ModelMessageToV2PromptMessage,\n aiV5PromptToAIV6Prompt,\n aiV5PromptToAIV7Prompt,\n coreContentToString,\n messagesAreEqual,\n inputToMastraDBMessage as convertInputToMastraDBMessage,\n aiV4UIMessagesToAIV4CoreMessages,\n aiV5UIMessagesToAIV5ModelMessages as convertAIV5UIToModelMessages,\n aiV4CoreMessagesToAIV5ModelMessages as convertAIV4CoreToAIV5ModelMessages,\n systemMessageToAIV4Core,\n StepContentExtractor,\n} from './conversion';\nimport type { ToolCallConversionMode } from './conversion';\nimport { isPersistedCopy } from './conversion/utils';\nimport { TypeDetector } from './detection/TypeDetector';\nimport type { StoredMessageLoader } from './memory-message-refs';\nimport { MessageMerger } from './merge';\nimport { convertImageFilePart } from './prompt/convert-file';\nimport { convertToV1Messages } from './prompt/convert-to-mastra-v1';\nimport { downloadAssetsFromMessages, getAssetUrl } from './prompt/download-assets';\nimport type { AssetDownloadCache } from './prompt/download-assets';\nimport { isSendableFileData } from './prompt/image-utils';\nimport {\n getMessageAttachmentUrls,\n getUnavailableAttachmentUrls,\n unavailableAttachmentPlaceholder,\n withUnavailableAttachmentPlaceholders,\n withUnavailableAttachmentUrls,\n} from './prompt/unavailable-attachments';\nimport { MessageStateManager } from './state';\nimport type {\n MastraDBMessage,\n MastraMessagePart,\n MastraStepStartPart,\n MastraMessageV1,\n MessageSource,\n MemoryInfo,\n UIMessageWithMetadata,\n SerializedMessageListState,\n} from './state';\nimport type { MastraToolInvocation, MastraToolInvocationPart } from './state/types';\nimport type { AIV5Type, AIV5ResponseMessage, AIV6Type, MessageInput, MessageListInput } from './types';\nimport { dropCrossProviderExecutedParts } from './utils/provider-compat';\nimport { preserveResponseItemIdsOnMerge } from './utils/response-item-metadata';\nimport { stampPart, stampToolPartUpdate } from './utils/stamp-part';\nimport {\n advancesToolInvocationState,\n isClientToolInvocationUpdate,\n isTerminalToolInvocationState,\n} from './utils/tool-invocation-state';\n\nfunction isSignalDataMessage<T extends { role: string; parts: Array<{ type: string }> }>(message: T): boolean {\n return message.role === 'system' && message.parts.length > 0 && message.parts.every(p => p.type.startsWith('data-'));\n}\n\n/**\n * Post-processes converted UI messages to merge non-user signal data parts into an\n * immediate neighbor assistant message, matching active-streaming behavior.\n *\n * Only checks immediate neighbors: append to preceding assistant, or prepend to\n * following assistant. If neither neighbor is assistant, convert the signal in-place\n * to an assistant message with just its data parts.\n */\nfunction mergeSignalDataParts<T extends { role: string; parts: Array<{ type: string }> }>(messages: T[]): T[] {\n const result: T[] = [];\n for (let idx = 0; idx < messages.length; idx++) {\n const message = messages[idx]!;\n if (!isSignalDataMessage(message)) {\n result.push(message);\n continue;\n }\n\n const prev = result[result.length - 1];\n const next = messages[idx + 1];\n\n if (prev && prev.role === 'assistant') {\n result[result.length - 1] = { ...prev, parts: [...prev.parts, ...message.parts] };\n } else if (next && next.role === 'assistant') {\n messages[idx + 1] = { ...next, parts: [...message.parts, ...next.parts] } as T;\n } else {\n result.push({ ...message, role: 'assistant' } as T);\n }\n }\n return result;\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction mergeBackgroundTasks(\n existingBgTasks?: Record<string, unknown>,\n incomingBgTasks?: Record<string, unknown>,\n): Record<string, unknown> | undefined {\n if (!existingBgTasks && !incomingBgTasks) {\n return undefined;\n }\n\n const merged: Record<string, unknown> = { ...(existingBgTasks ?? {}) };\n for (const [toolCallId, incomingTask] of Object.entries(incomingBgTasks ?? {})) {\n const existingTask = merged[toolCallId];\n merged[toolCallId] =\n isPlainRecord(existingTask) && isPlainRecord(incomingTask) ? { ...existingTask, ...incomingTask } : incomingTask;\n }\n return merged;\n}\n\n/**\n * Returns `live` with every tool part that would not move its stored counterpart forward turned\n * into a bare call. The merger then uses it only to anchor surrounding parts: a stored outcome\n * stays canonical, and a stale or edited echo can't overwrite it. Live state may fill in a\n * pending call or advance a background result from running to completed or failed.\n */\nfunction withoutStaleToolStates(stored: MastraDBMessage, live: MastraDBMessage): MastraDBMessage {\n const storedParts = new Map<string, MastraToolInvocationPart>();\n for (const part of stored.content.parts) {\n if (part.type === 'tool-invocation') storedParts.set(part.toolInvocation.toolCallId, part);\n }\n if (storedParts.size === 0) return live;\n\n let changed = false;\n const parts = live.content.parts.map(part => {\n if (part.type !== 'tool-invocation') return part;\n const storedPart = storedParts.get(part.toolInvocation.toolCallId);\n if (!storedPart || advancesToolInvocationState(storedPart.toolInvocation.state, part.toolInvocation.state))\n return part;\n const storedTask = storedPart.providerMetadata?.mastra?.backgroundTask as { status?: string } | undefined;\n const liveTask = part.providerMetadata?.mastra?.backgroundTask as { status?: string } | undefined;\n if (storedTask?.status === 'running' && (liveTask?.status === 'completed' || liveTask?.status === 'failed')) {\n return part;\n }\n changed = true;\n const { toolCallId, toolName, args } = part.toolInvocation;\n return { type: 'tool-invocation' as const, toolInvocation: { state: 'call' as const, toolCallId, toolName, args } };\n });\n return changed ? { ...live, content: { ...live.content, parts } } : live;\n}\n\n/**\n * Returns only the tool parts of a client-sent assistant message that move a stored call\n * forward with a state a client produces (an approval answer or an outcome). The client's text,\n * reasoning, and metadata are its own rendering of the stored message, which can differ from\n * what was saved (an output processor may rewrite text before it is persisted), so none of it is\n * layered onto the stored copy. Only the new state and its outcome fields are taken; the call's\n * arguments and metadata stay as stored. A provider-executed call can only take an approval\n * answer, since the provider, not the client, produces its outcome.\n */\nfunction clientToolOutcomes(stored: MastraDBMessage, live: MastraDBMessage): MastraDBMessage {\n const storedCalls = new Map<string, MastraToolInvocationPart>();\n for (const part of stored.content.parts) {\n if (part.type === 'tool-invocation') storedCalls.set(part.toolInvocation.toolCallId, part);\n }\n const parts = live.content.parts.flatMap(part => {\n if (part.type !== 'tool-invocation') return [];\n const { state, toolCallId, result, errorText, approval } = part.toolInvocation;\n const storedCall = storedCalls.get(toolCallId);\n if (\n !storedCall ||\n !isClientToolInvocationUpdate(state) ||\n !advancesToolInvocationState(storedCall.toolInvocation.state, state) ||\n (storedCall.providerExecuted && state !== 'approval-responded')\n ) {\n return [];\n }\n const toolInvocation = {\n ...storedCall.toolInvocation,\n state,\n result,\n errorText,\n approval: approval ?? storedCall.toolInvocation.approval,\n };\n return [{ type: 'tool-invocation' as const, toolInvocation }];\n });\n return { ...live, content: { format: 2, parts } };\n}\n\ntype MessageListAddOptions = {\n merge?: boolean;\n};\n\n/**\n * Locate the step boundary a loop iteration opened, for `rollbackToStepBoundary`.\n *\n * In order: the held reference, wherever it sits in the parts being rolled back; else the marker\n * carrying the boundary's `createdAt`, if exactly one does, provided the boundary was opened in\n * this message and the same parts still stand in front of it. Anything else is -1 and the caller\n * removes the message whole. The reference needs no such corroboration — a part physically\n * present in this message's array is the boundary, and nothing else can be.\n *\n * Reference first because it is exact. It is lost when a processor returns an array rather than\n * mutating the list: the runner re-adds each returned message with `{ merge: false }`\n * (`processors/runner.ts`), so a processor that maps or clones its messages hands back parts this\n * list has never seen. `stampPart` puts a `createdAt` on every marker and cloning carries it, so\n * the timestamp can find the anchor again.\n *\n * The rest of the conditions exist because a wrong match is worse than no match: too early\n * over-splices accepted content, too late strands the rejected step, which is the bug this\n * anchoring exists to prevent. The same processors that can clone parts can also drop them, and a\n * dropped boundary leaves a same-millisecond marker as the sole timestamp match, sitting further\n * down the message with the rejected step in front of it. So the checkpoint pins what preceded\n * the boundary — by identifying content, since types alone line up by coincidence once a\n * processor trims accepted parts — and which message it preceded it in.\n */\nfunction findBoundaryIndex(\n parts: MastraMessagePart[],\n boundary: MastraStepStartPart,\n messageId: string,\n checkpoint: BoundaryCheckpoint | undefined,\n): number {\n const byReference = parts.indexOf(boundary);\n if (byReference !== -1) return byReference;\n\n const stampedAt = boundary.createdAt;\n if (stampedAt == null || checkpoint === undefined || checkpoint.messageId !== messageId) return -1;\n\n const matches = parts.flatMap((part, index) =>\n // Unary + so a Date, or a string from some storage round trip, compares as a number or not at all.\n part.type === 'step-start' && part.createdAt != null && +part.createdAt === +stampedAt ? [index] : [],\n );\n if (matches.length !== 1) return -1;\n\n const index = matches[0]!;\n const prefix = prefixFingerprint(parts, index);\n const held = checkpoint.prefix;\n const same =\n prefix.length === held.length && prefix.every((token, i) => token[0] === held[i]![0] && token[1] === held[i]![1]);\n return same ? index : -1;\n}\n\n/** A preceding part, named by its type and by whatever identifies it within that type. */\ntype BoundaryToken = [type: string, identity: string | undefined];\n\n/** Where a boundary was opened, and what stood in front of it there. */\ntype BoundaryCheckpoint = { messageId: string; prefix: BoundaryToken[] };\n\n/**\n * Identify the parts preceding an index — what a splice at that index is actually a statement\n * about. A tool call is named by its id, text and reasoning by their own string, anything else by\n * its type alone. Each token holds that string as-is rather than building one out of it, so the\n * capture every iteration allocates a pair per preceding part and copies no content; the\n * comparing happens only on a rejection.\n */\nfunction prefixFingerprint(parts: MastraMessagePart[], index: number): BoundaryToken[] {\n const tokens: BoundaryToken[] = [];\n for (let i = 0; i < index; i++) {\n const part = parts[i]!;\n if (part.type === 'text') tokens.push([part.type, part.text]);\n else if (part.type === 'tool-invocation') tokens.push([part.type, part.toolInvocation?.toolCallId]);\n else if (part.type === 'reasoning') tokens.push([part.type, part.reasoning]);\n else tokens.push([part.type, undefined]);\n }\n return tokens;\n}\n\nexport class MessageList {\n private messages: MastraDBMessage[] = [];\n // Derived lookup state for `this.messages` so adding a message doesn't scan the whole list.\n // Trusted only while `messages` is still the same array at the same length; anything else\n // (reassignment, splice, external pushes) makes getMessageIndex() rebuild it.\n private messageIndex?: {\n messages: MastraDBMessage[];\n length: number;\n byId: Map<string, MastraDBMessage[]>;\n sorted: boolean;\n };\n\n // passed in by dev in input or context\n private systemMessages: AIV4Type.CoreSystemMessage[] = [];\n // passed in by us for a specific purpose, eg memory system message\n private taggedSystemMessages: Record<string, AIV4Type.CoreSystemMessage[]> = {};\n\n private memoryInfo: null | MemoryInfo = null;\n\n // Centralized state management for message tracking\n private stateManager = new MessageStateManager();\n\n // Response messages this run produced that were later pruned from the live context (e.g. by\n // observational memory after observing them). They no longer belong in the prompt, but they\n // are still part of the run's response — see getRunResponseMessages(). Keyed by id in pruning\n // order; the message is only held when pruned by this instance; a restored list has ids only.\n #prunedResponseMessages = new Map<string, MastraDBMessage | undefined>();\n\n // Message id -> hash of the text this run already wrote to the semantic recall index. Both\n // writers (the SemanticRecall output processor and Memory.saveMessages through the save queue)\n // read and update it, so whichever runs second skips what the first one embedded.\n #embeddedMessages = new Map<string, string>();\n\n // Legacy getters for backward compatibility - delegate to stateManager\n private get memoryMessages() {\n return this.stateManager.getMemoryMessages();\n }\n private get newUserMessages() {\n return this.stateManager.getUserMessages();\n }\n private get newResponseMessages() {\n return this.stateManager.getResponseMessages();\n }\n private get userContextMessages() {\n return this.stateManager.getContextMessages();\n }\n private get memoryMessagesPersisted() {\n return this.stateManager.getMemoryMessagesPersisted();\n }\n private get newUserMessagesPersisted() {\n return this.stateManager.getUserMessagesPersisted();\n }\n private get newResponseMessagesPersisted() {\n return this.stateManager.getResponseMessagesPersisted();\n }\n private get userContextMessagesPersisted() {\n return this.stateManager.getContextMessagesPersisted();\n }\n\n // Each attachment is downloaded at most once per MessageList (i.e. per run).\n private assetDownloads: AssetDownloadCache = new Map();\n // Attachment URLs newly found unavailable, by message id, awaiting persistence.\n private unavailableAttachmentUpdates = new Map<string, Set<string>>();\n\n private generateMessageId?: (context?: IdGeneratorContext) => string;\n private _agentNetworkAppend = false;\n private filterIncompleteToolCalls: boolean;\n private logger?: IMastraLogger;\n private responseMessageSplits = new Map<string, string>();\n\n private toAIV5UIMessages(messages: MastraDBMessage[], options?: { transformToolPayloads?: boolean }) {\n return mergeSignalDataParts(messages.map(message => AIV5Adapter.toUIMessage(message, options)));\n }\n\n private toAIV4UIMessages(messages: MastraDBMessage[], options?: { transformToolPayloads?: boolean }) {\n return mergeSignalDataParts(messages.map(message => AIV4Adapter.toUIMessage(message, options)));\n }\n\n private toAIV6UIMessages(messages: MastraDBMessage[]) {\n return mergeSignalDataParts(messages.map(AIV6Adapter.toUIMessage));\n }\n\n // Event recording for observability\n private isRecording = false;\n private spanRecordings = new Map<AnySpan, ReturnType<MessageList['getRecordedEvents']>>();\n private recordedEvents: Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: MessageSource;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: CoreMessageV4;\n }> = [];\n\n constructor({\n threadId,\n resourceId,\n generateMessageId,\n logger,\n filterIncompleteToolCalls,\n // @ts-expect-error Flag for agent network messages\n _agentNetworkAppend,\n }: {\n threadId?: string;\n resourceId?: string;\n generateMessageId?: (context?: IdGeneratorContext) => string;\n logger?: IMastraLogger;\n filterIncompleteToolCalls?: boolean;\n } = {}) {\n if (threadId) {\n this.memoryInfo = { threadId, resourceId };\n }\n this.generateMessageId = generateMessageId;\n this.logger = logger;\n this.filterIncompleteToolCalls = filterIncompleteToolCalls ?? true;\n this._agentNetworkAppend = _agentNetworkAppend || false;\n }\n\n /**\n * Start recording mutations to the MessageList for observability/tracing.\n * A span scopes recording to that async context, allowing parallel processors.\n */\n public startRecording(span?: AnySpan): void {\n if (span) {\n this.spanRecordings.set(span, []);\n return;\n }\n this.isRecording = true;\n this.recordedEvents = [];\n }\n\n public hasRecordedEvents(): boolean {\n return this.recordedEvents.length > 0;\n }\n\n public getRecordedEvents(): Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: MessageSource;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: CoreMessageV4;\n }> {\n const events = [...this.recordedEvents];\n return events;\n }\n\n /**\n * Stop recording and return the list of recorded events\n */\n public stopRecording(span?: AnySpan): Array<{\n type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n source?: MessageSource;\n count?: number;\n ids?: string[];\n text?: string;\n tag?: string;\n message?: CoreMessageV4;\n }> {\n if (span) {\n const events = this.spanRecordings.get(span) ?? [];\n this.spanRecordings.delete(span);\n return events;\n }\n this.isRecording = false;\n const events = this.getRecordedEvents();\n this.recordedEvents = [];\n return events;\n }\n\n private recordMutation(event: ReturnType<MessageList['getRecordedEvents']>[number]): void {\n // Child operations belong to the nearest processor recording. Parallel\n // processors share the list, but have separate async span contexts.\n if (this.spanRecordings.size > 0) {\n let span = resolveCurrentSpan();\n while (span) {\n const events = this.spanRecordings.get(span);\n if (events) {\n events.push(event);\n return;\n }\n span = span.parent;\n }\n }\n if (this.isRecording) this.recordedEvents.push(event);\n }\n\n public addSignal(signal: CreatedAgentSignal, options?: { source?: MessageSource }): CreatedAgentSignal {\n const source = options?.source ?? 'input';\n // A signal that names the message it precedes (e.g. memory's temporal-gap reminder)\n // sorts just before that message instead of being stamped at arrival time.\n const precedesMessageId = signal.metadata?.precedesMessageId;\n const precededMessage = typeof precedesMessageId === 'string' ? this.getMessageById(precedesMessageId) : undefined;\n const createdAt = precededMessage\n ? new Date(precededMessage.createdAt.getTime() - 1)\n : this.generateCreatedAt(source, new Date());\n const acceptedAt = signal.acceptedAt ?? signal.createdAt;\n const signalInput = {\n id: signal.id,\n tagName: signal.tagName,\n contents: signal.contents,\n attributes: signal.attributes,\n metadata: signal.metadata,\n author: signal.author,\n providerOptions: signal.providerOptions,\n createdAt,\n acceptedAt,\n };\n const signalForTranscript =\n signal.type === 'state'\n ? createSignal({ ...signalInput, type: signal.type })\n : createSignal({ ...signalInput, type: signal.type, transient: signal.transient });\n\n const dbMessage = signalForTranscript.toDBMessage(this.memoryInfo ?? undefined);\n // Transient signals are delivery-only: when the same logical signal is re-sent within a\n // turn (e.g. from processInputStep, which runs once per model call), drop the previous\n // in-memory copy so the prompt keeps a single fresh copy near the latest message instead\n // of accumulating one copy per step. Matching is by signal id, or — for the documented\n // no-id pattern where each re-send mints a fresh UUID — by (type, tagName, contents).\n if (signalForTranscript.type !== 'state' && signalForTranscript.transient) {\n this.removeMatchingTransientSignals(dbMessage);\n }\n this.addOne(dbMessage, source);\n return signalForTranscript;\n }\n\n private removeMatchingTransientSignals(incoming: MastraDBMessage): void {\n const incomingMeta = incoming.content.metadata?.signal as\n | { id?: string; type?: string; tagName?: string }\n | undefined;\n // The stored copy's parts gain bookkeeping fields (e.g. a per-part `createdAt` stamp)\n // during conversion, so compare contents with those stripped.\n const serializeParts = (parts: MastraDBMessage['content']['parts']) =>\n JSON.stringify(parts.map(part => ({ ...part, createdAt: undefined })));\n const incomingParts = serializeParts(incoming.content.parts);\n\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const existing = this.messages[i]!;\n if (!isTransientSignalMessage(existing)) continue;\n\n const existingMeta = existing.content.metadata?.signal as\n | { id?: string; type?: string; tagName?: string }\n | undefined;\n\n const sameId = existing.id === incoming.id;\n const sameLogicalSignal =\n !!incomingMeta &&\n !!existingMeta &&\n existingMeta.type === incomingMeta.type &&\n existingMeta.tagName === incomingMeta.tagName &&\n serializeParts(existing.content.parts) === incomingParts;\n\n if (sameId || sameLogicalSignal) {\n this.messages.splice(i, 1);\n this.stateManager.removeMessage(existing);\n }\n }\n }\n\n public add(messages: MessageListInput, messageSource: MessageSource, options: MessageListAddOptions = {}) {\n if (messageSource === `user`) messageSource = `input`;\n\n if (!messages) return this;\n const messageArray = Array.isArray(messages) ? messages : [messages];\n\n // Record event if recording is enabled\n this.recordMutation({\n type: 'add',\n source: messageSource,\n count: messageArray.length,\n });\n\n for (const message of messageArray) {\n if (isCreatedAgentSignal(message) && messageSource === 'input') {\n this.addSignal(message, { source: messageSource });\n continue;\n }\n\n const messageInput = isCreatedAgentSignal(message)\n ? message.toDBMessage(this.memoryInfo ?? undefined)\n : typeof message === `string`\n ? {\n role: 'user' as const,\n content: message,\n }\n : message;\n\n if (Array.isArray(messageInput)) {\n for (const nestedMessage of messageInput) {\n this.addOne(\n typeof nestedMessage === `string`\n ? {\n role: 'user',\n content: nestedMessage,\n }\n : nestedMessage,\n messageSource,\n options,\n );\n }\n continue;\n }\n\n this.addOne(\n typeof messageInput === `string`\n ? {\n role: 'user',\n content: messageInput,\n }\n : messageInput,\n messageSource,\n options,\n );\n }\n this.moveLiveMessagesPastStoredTies();\n return this;\n }\n\n public serialize(): SerializedMessageListState {\n const state = this.stateManager.serializeAll({\n messages: this.messages,\n systemMessages: this.systemMessages,\n taggedSystemMessages: this.taggedSystemMessages,\n memoryInfo: this.memoryInfo,\n agentNetworkAppend: this._agentNetworkAppend,\n });\n const lastStepBoundary = this.#locateLastStepBoundary();\n const prunedResponseMessageIds = this.#getPrunedResponseMessageIds();\n return {\n ...state,\n ...(lastStepBoundary ? { lastStepBoundary } : {}),\n ...(prunedResponseMessageIds.length > 0 ? { prunedResponseMessageIds } : {}),\n ...(this.#embeddedMessages.size > 0 ? { embeddedMessages: Object.fromEntries(this.#embeddedMessages) } : {}),\n };\n }\n\n /**\n * The run's record of messages already written to the semantic recall index, as\n * message id -> hash of the embedded text. Returned live: embedding writers add to it after a\n * successful write and skip messages recorded with the same text.\n *\n * @internal\n */\n public getEmbeddedMessages(): Map<string, string> {\n return this.#embeddedMessages;\n }\n\n /**\n * Custom serialization for tracing/observability spans.\n * Returns a clean representation with just the essential data,\n * excluding internal state tracking, methods, and implementation details.\n *\n * This is automatically called by the span serialization system when\n * a MessageList instance appears in span input/output/attributes.\n */\n public serializeForSpan(): {\n messages: Array<{ role: string; content: unknown }>;\n systemMessages: Array<{ role: string; content: unknown; tag?: string }>;\n } {\n const coreMessages = this.all.aiV4.core();\n\n return {\n messages: coreMessages.map(msg => ({\n role: msg.role,\n content: msg.content,\n })),\n systemMessages: [\n // Untagged first (base instructions)\n ...this.systemMessages.map(m => ({ role: m.role, content: m.content })),\n // Tagged after (contextual additions)\n ...Object.entries(this.taggedSystemMessages).flatMap(([tag, msgs]) =>\n msgs.map(m => ({ role: m.role, content: m.content, tag })),\n ),\n ],\n };\n }\n\n public deserialize(state: SerializedMessageListState) {\n const data = this.stateManager.deserializeAll(state);\n this.messages = data.messages;\n this.systemMessages = data.systemMessages;\n this.taggedSystemMessages = data.taggedSystemMessages;\n this.memoryInfo = data.memoryInfo;\n this._agentNetworkAppend = data.agentNetworkAppend;\n this.responseMessageSplits.clear();\n for (const message of this.messages) {\n this.updateLastCreatedAt(message);\n }\n this.#prunedResponseMessages = new Map((state.prunedResponseMessageIds ?? []).map(id => [id, undefined]));\n // Merged instead of replaced: durable runs restore older snapshots onto the live list at\n // finalize, and the live list can hold entries the snapshot lacks (the input save writes\n // them before the workflow starts). An entry only skips a message whose text still matches\n // its hash, so keeping an older entry can at most cause one extra embedding.\n for (const [messageId, textHash] of Object.entries(state.embeddedMessages ?? {})) {\n this.#embeddedMessages.set(messageId, textHash);\n }\n this.#lastStepBoundary = undefined;\n if (state.lastStepBoundary) {\n const { messageId, partIndex } = state.lastStepBoundary;\n const parts = this.messages.find(m => m.id === messageId)?.content.parts;\n const part = parts?.[partIndex];\n if (parts && part?.type === 'step-start') {\n this.#rememberBoundaryFingerprint(messageId, parts, part);\n this.#lastStepBoundary = part;\n }\n }\n return this;\n }\n\n /** @internal */\n public clone(): MessageList {\n return new MessageList({\n generateMessageId: this.generateMessageId,\n logger: this.logger,\n filterIncompleteToolCalls: this.filterIncompleteToolCalls,\n }).deserialize(this.serialize());\n }\n\n /**\n * Return the transcript view that persistence-oriented output processors should store.\n * During final output processing, the current loop iteration may temporarily be exposed as a separate response\n * message so processors can transform it independently. This method coalesces that temporary split while preserving\n * the original response identity and order.\n */\n public cloneForPersistence(): MessageList {\n if (this.responseMessageSplits.size === 0) return this;\n\n const clone = this.clone();\n for (const [currentMessageId, earlierMessageId] of this.responseMessageSplits) {\n clone.coalesceSplitResponseMessages(earlierMessageId, currentMessageId);\n }\n return clone;\n }\n\n /**\n * Suspended tool calls are dropped from the prompt by default. When the caller opts out\n * they stay visible, but they are still paired with a pending result — providers reject a\n * tool call that has no result regardless of what the caller prefers.\n */\n private get promptConversionMode(): ToolCallConversionMode {\n return this.filterIncompleteToolCalls ? 'prompt' : 'prompt-with-suspended';\n }\n\n /**\n * Whether tool calls without a result are dropped from the prompt (the default) rather than\n * paired with a pending placeholder result. Lets prompt-shape-aware processors reason about\n * what a trailing assistant message will look like once converted.\n */\n get dropsIncompleteToolCalls(): boolean {\n return this.filterIncompleteToolCalls;\n }\n\n private getMessagesForModelPrompt(): MastraDBMessage[] {\n return this.messages.flatMap(message => {\n if ((message.role as string) !== 'signal') {\n return [message];\n }\n\n return this.convertSignalForModelPrompt(message);\n });\n }\n\n private convertSignalForModelPrompt(message: MastraDBMessage): MastraDBMessage[] {\n // Model providers only understand normal prompt messages, so project the signal into\n // its LLM-facing UserModelMessage. Preserve the original id/createdAt so MessageList's\n // timestamp/ordering bookkeeping stays anchored to the persisted signal row.\n const signalMessage = mastraDBMessageToSignal(message).toLLMMessage();\n const createdAt = message.createdAt;\n const promptMessage = {\n ...signalMessage,\n id: message.id,\n metadata: { createdAt },\n };\n\n return [\n convertInputToMastraDBMessage(promptMessage as MessageInput, 'input', {\n memoryInfo: this.memoryInfo,\n newMessageId: () => message.id,\n generateCreatedAt: (_messageSource, start) => {\n if (start instanceof Date) return start;\n if (typeof start === 'string' || typeof start === 'number') return new Date(start);\n return createdAt;\n },\n dbMessages: this.messages,\n }),\n ];\n }\n\n public makeMessageSourceChecker(): {\n memory: Set<string>;\n input: Set<string>;\n output: Set<string>;\n context: Set<string>;\n getSource: (message: MastraDBMessage) => MessageSource | null;\n } {\n return this.stateManager.createSourceChecker();\n }\n\n /**\n * Ids of every message that entered this list from memory or as input, including messages\n * later promoted to the response or replaced by a copy with the same id.\n */\n public getRememberedAndInputMessageIds(): Set<string> {\n return new Set([...this.memoryMessagesPersisted, ...this.newUserMessagesPersisted].map(message => message.id));\n }\n\n public getLatestUserContent(): string | null {\n const currentUserMessages = this.all.core().filter(m => m.role === 'user');\n const content = currentUserMessages.at(-1)?.content;\n if (!content) return null;\n return coreContentToString(content);\n }\n\n public get get() {\n return {\n all: this.all,\n remembered: this.remembered,\n input: this.input,\n response: this.response,\n };\n }\n public get getPersisted() {\n return {\n remembered: this.rememberedPersisted,\n input: this.inputPersisted,\n taggedSystemMessages: this.taggedSystemMessages,\n response: this.responsePersisted,\n };\n }\n\n public get clear() {\n return {\n all: {\n db: (): MastraDBMessage[] => {\n const allMessages = [...this.messages];\n this.messages = [];\n this.stateManager.clearAll();\n if (allMessages.length > 0) {\n this.recordMutation({\n type: 'clear',\n count: allMessages.length,\n });\n }\n return allMessages;\n },\n },\n input: {\n db: (): MastraDBMessage[] => {\n const userMessages = Array.from(this.stateManager.getUserMessages());\n this.messages = this.messages.filter(m => !this.stateManager.isUserMessage(m));\n this.stateManager.clearUserMessages();\n if (userMessages.length > 0) {\n this.recordMutation({\n type: 'clear',\n source: 'input',\n count: userMessages.length,\n });\n }\n return userMessages;\n },\n },\n response: {\n db: () => {\n const responseMessages = Array.from(this.stateManager.getResponseMessages());\n this.messages = this.messages.filter(m => !this.stateManager.isResponseMessage(m));\n this.stateManager.clearResponseMessages();\n if (responseMessages.length > 0) {\n this.recordMutation({\n type: 'clear',\n source: 'response',\n count: responseMessages.length,\n });\n }\n return responseMessages;\n },\n },\n };\n }\n\n /**\n * Remove messages by ID\n * @param ids - Array of message IDs to remove\n * @param options.pruned - The messages are only being dropped from the live context (e.g. after\n * observational memory has observed them). Response messages removed this way stay part of the\n * run's response reported by getRunResponseMessages().\n * @returns Array of removed messages\n */\n public removeByIds(ids: string[], options?: { pruned?: boolean }): MastraDBMessage[] {\n const idsSet = new Set(ids);\n const removed: MastraDBMessage[] = [];\n const persistedResponse = this.newResponseMessagesPersisted;\n this.messages = this.messages.filter(m => {\n if (idsSet.has(m.id)) {\n removed.push(m);\n if (options?.pruned && persistedResponse.has(m)) {\n this.#prunedResponseMessages.set(m.id, m);\n } else if (!options?.pruned) {\n this.#prunedResponseMessages.delete(m.id);\n }\n this.stateManager.removeMessage(m);\n return false;\n }\n return true;\n });\n if (removed.length > 0) {\n this.recordMutation({\n type: 'removeByIds',\n ids,\n count: removed.length,\n });\n }\n return removed;\n }\n\n /**\n * Split an accumulated response message so result processors can transform the current loop iteration independently.\n * The original id stays with the earlier, potentially persisted parts so storage and client updates keep resolving\n * the same row while processors work with the current iteration under a temporary id.\n * @internal\n */\n public splitResponseMessageAtPartOffset(\n messageId: string,\n partOffset: number,\n ): { earlierMessageId: string; currentMessageId: string } | undefined {\n const messageIndex = this.messages.findIndex(message => message.id === messageId);\n const message = this.messages[messageIndex];\n const parts = message?.content.parts;\n if (\n !message ||\n !this.stateManager.isResponseMessage(message) ||\n !parts ||\n partOffset <= 0 ||\n partOffset >= parts.length\n ) {\n return undefined;\n }\n\n const contentForParts = (selectedParts: MastraMessagePart[]): MastraDBMessage['content'] => {\n const content = { ...message.content, parts: selectedParts };\n if (typeof content.content === 'string') {\n content.content = selectedParts.reduce((text, part) => (part.type === 'text' ? part.text : text), '');\n }\n if (Array.isArray(content.toolInvocations)) {\n const toolCallIds = new Set(\n selectedParts.flatMap(part =>\n part.type === 'tool-invocation' && part.toolInvocation ? [part.toolInvocation.toolCallId] : [],\n ),\n );\n content.toolInvocations = content.toolInvocations.filter(invocation => toolCallIds.has(invocation.toolCallId));\n }\n return content;\n };\n\n const earlierMessageId = messageId;\n const currentMessageId = this.newMessageId(message.role);\n const currentMessage: MastraDBMessage = {\n ...message,\n id: currentMessageId,\n content: contentForParts(parts.slice(partOffset)),\n };\n message.content = contentForParts(parts.slice(0, partOffset));\n this.messages.splice(messageIndex, 1, message, currentMessage);\n\n const prunedResponseMessages = this.#prunedResponseMessages;\n const state = this.serialize();\n for (const key of ['newResponseMessages', 'newResponseMessagesPersisted'] as const) {\n state[key] = state[key].flatMap(id => (id === messageId ? [earlierMessageId, currentMessageId] : [id]));\n }\n this.deserialize(state);\n for (const [id, message] of this.#prunedResponseMessages) {\n if (message === undefined) this.#prunedResponseMessages.set(id, prunedResponseMessages.get(id));\n }\n this.responseMessageSplits.set(currentMessageId, earlierMessageId);\n\n return { earlierMessageId, currentMessageId };\n }\n\n /**\n * Restore a split processor view to the accumulated response shape used for persistence.\n * The original response id belongs to the earlier iteration and remains stable unless the\n * processor removes that half, in which case the current survivor inherits it.\n * @internal\n */\n public coalesceSplitResponseMessages(earlierMessageId: string, currentMessageId: string): void {\n this.responseMessageSplits.delete(currentMessageId);\n const earlierIndex = this.messages.findIndex(message => message.id === earlierMessageId);\n const currentIndex = this.messages.findIndex(message => message.id === currentMessageId);\n const earlierMessage = this.messages[earlierIndex];\n const currentMessage = this.messages[currentIndex];\n\n if (!earlierMessage) {\n if (currentMessage) currentMessage.id = earlierMessageId;\n return;\n }\n\n if (!currentMessage) return;\n\n const parts = [...(earlierMessage.content.parts ?? []), ...(currentMessage.content.parts ?? [])];\n const content = {\n ...earlierMessage.content,\n ...currentMessage.content,\n parts,\n };\n if (typeof earlierMessage.content.content === 'string' || typeof currentMessage.content.content === 'string') {\n content.content = parts.reduce((text, part) => (part.type === 'text' ? part.text : text), '');\n }\n if (\n Array.isArray(earlierMessage.content.toolInvocations) ||\n Array.isArray(currentMessage.content.toolInvocations)\n ) {\n const invocations = [\n ...(earlierMessage.content.toolInvocations ?? []),\n ...(currentMessage.content.toolInvocations ?? []),\n ];\n const toolCallIds = new Set(\n parts.flatMap(part =>\n part.type === 'tool-invocation' && part.toolInvocation ? [part.toolInvocation.toolCallId] : [],\n ),\n );\n content.toolInvocations = invocations.filter(\n (invocation, index) =>\n toolCallIds.has(invocation.toolCallId) &&\n invocations.findIndex(candidate => candidate.toolCallId === invocation.toolCallId) === index,\n );\n }\n\n earlierMessage.content = content;\n this.messages.splice(Math.max(earlierIndex, currentIndex), 1);\n this.messages.splice(Math.min(earlierIndex, currentIndex), 1, earlierMessage);\n this.stateManager.removeMessage(currentMessage);\n }\n\n /**\n * Roll a response message back to the boundary the caller's loop iteration opened, discarding\n * the parts produced by that step while keeping every earlier, completed step intact.\n *\n * Used by the processor-retry path: the rejected attempt must not survive into the next\n * prompt (PR #12799), but the accepted steps before it must. Removing the whole message\n * instead — as that path used to do — also destroyed the reasoning (`rs_…`) and\n * tool-invocation (`fc_…`) parts of accepted steps, leaving a persisted assistant message\n * with an OpenAI text `itemId` and no reasoning item to pair with it, which OpenAI rejects\n * with a non-retryable 400 on replay (issue #22291).\n *\n * The boundary must be the marker handed back by `openStepBoundary()`, not \"the last\n * `step-start` in the message\". Markers are also synthesized *within* a single response\n * whenever a tool call is followed by text, and nothing stored on the part says which writer\n * produced it, so the last marker is routinely an intra-response one. Anchoring on it splices\n * below the rejected step and leaves part of the rejected attempt behind — on a first\n * iteration, which opens no boundary at all, that is the whole bug: a rejected tool call\n * survives, unexecuted and still carrying its `fc_…` item id.\n *\n * Where no boundary can be located — a first iteration, which opens none; a sealed message; or\n * a marker `findBoundaryIndex` cannot resolve — the message is removed whole. That is not a\n * claim that no accepted step exists, only that this cannot tell where one ends, and it is the\n * pre-#12799 behaviour, so the fallback is never worse than the path it replaced.\n *\n * Mirrors: `content.content` and `content.toolInvocations` are re-derived below, because\n * `MessageMerger` keeps both in step with the parts as a turn streams. `content.reasoning`\n * and `content.experimental_attachments` are deliberately *not* touched: the merger never\n * writes them (they are set once when a DB message is built from model messages), so they\n * describe the first chunk of the message — which a rollback that keeps any parts has by\n * definition kept. `AIV5Adapter` only re-synthesizes a part from either field when no such\n * part survives, so there is nothing to resurrect today. If the merger is ever changed to\n * update them per step, as it does `content.content`, they will need the same treatment here.\n * `content.metadata.structuredOutput` is invalidated for the same reason `content.content` is\n * re-derived: it is written per step and a retry that emits no object never overwrites it.\n *\n * @param messageId - ID of the message to roll back\n * @param boundary - the marker returned by `openStepBoundary()` for the step being discarded\n * @returns true if a message was found and rolled back or removed\n */\n public rollbackToStepBoundary(messageId: string, boundary?: MastraStepStartPart): boolean {\n const message = this.messages.find(m => m.id === messageId);\n if (!message) return false;\n\n const parts = message.content?.parts;\n if (!parts) {\n this.removeByIds([messageId]);\n return true;\n }\n\n // Reference, then timestamp, then give up — see findBoundaryIndex.\n const boundaryIndex = boundary\n ? findBoundaryIndex(parts, boundary, messageId, this.#boundaryFingerprints.get(boundary))\n : -1;\n\n // Nowhere to splice: discard the message rather than guess which parts were accepted.\n if (boundaryIndex === -1) {\n this.removeByIds([messageId]);\n return true;\n }\n\n // Drop the marker itself along with the step it opened, so the next iteration's\n // openStepBoundary() writes a fresh marker for the retry rather than reusing the rejected one.\n this.#truncateParts(message, boundaryIndex);\n return true;\n }\n\n /**\n * Cut a message back to its first `length` parts, removing it when none remain, and keep the\n * mirrors `MessageMerger` maintains beside the parts in step with what survived.\n */\n #truncateParts(message: MastraDBMessage, length: number): void {\n const parts = message.content.parts;\n parts.splice(length);\n\n if (parts.length === 0) {\n this.removeByIds([message.id]);\n return;\n }\n\n // `content.toolInvocations` is the legacy AIV4 mirror of the tool-invocation parts, also\n // maintained by MessageMerger. convert-to-mastra-v1 treats any entry that is in the mirror\n // but not in `parts` as an *unprocessed* invocation and pushes it back into the prompt, so\n // leaving the rejected step's calls behind would resurrect exactly what the rollback dropped.\n if (Array.isArray(message.content.toolInvocations)) {\n const survivingCallIds = new Set(\n parts.flatMap(part =>\n part.type === 'tool-invocation' && part.toolInvocation ? [part.toolInvocation.toolCallId] : [],\n ),\n );\n message.content.toolInvocations = message.content.toolInvocations.filter(invocation =>\n survivingCallIds.has(invocation.toolCallId),\n );\n }\n\n // `content.content` mirrors the latest text part (see MessageMerger), and readers such as\n // AIV4Adapter prefer it over `parts` when it is non-empty. Re-derive it from what survived,\n // otherwise the rejected attempt's text outlives the rollback whenever the retry emits no\n // text of its own to overwrite it.\n if (typeof message.content.content === 'string') {\n let lastText = '';\n for (const part of parts) {\n if (part.type === 'text') lastText = part.text;\n }\n message.content.content = lastText;\n }\n\n // `content.metadata.structuredOutput` is written straight onto the merged message by the\n // execution step, before output processors get a chance to reject the step, and nothing\n // clears it when a retry emits no object of its own — so the rejected attempt's object would\n // otherwise outlive the rollback, still readable on the message. Invalidate rather than\n // restore: the write is in place, so an earlier accepted object is already overwritten\n // whenever the rejected step produced one of its own, and there is nothing to roll back to\n // when it did not. Other metadata is left alone; the keys\n // that are step-derived, such as the model identity, are rewritten by the retry itself.\n if (message.content.metadata) {\n delete message.content.metadata.structuredOutput;\n }\n\n // Ensure the mutated message is persisted.\n if (!this.stateManager.isResponseMessage(message)) {\n this.stateManager.removeMessage(message);\n this.stateManager.addToSource(message, 'response');\n }\n }\n\n /** Response parts per message as of the last completed step; undefined until a step completes. */\n #completedStepParts: Map<string, number> | undefined;\n /** Structured output per message as of the last completed step. */\n #completedStepStructuredOutput: Map<string, unknown> | undefined;\n\n /**\n * Record the response as it stands now as the end of a completed step. Called by the loop when a\n * step finishes, before the next one can add to the response.\n * @internal\n */\n public markStepCompleted(): void {\n this.#completedStepParts = new Map(\n this.get.response.db().map(message => [message.id, message.content.parts?.length ?? 0]),\n );\n this.#completedStepStructuredOutput = new Map(\n this.get.response\n .db()\n .flatMap(message =>\n message.content.metadata?.structuredOutput !== undefined\n ? [[message.id, message.content.metadata.structuredOutput] as const]\n : [],\n ),\n );\n }\n\n /**\n * A copy of this list holding the input and only the response of completed steps: the parts and\n * messages a step still in flight added since the last {@link markStepCompleted} are left out.\n * A step whose tool calls all have results (an aborted call records a notice) counts as completed\n * even though the loop never reached its step-finish, and is kept whole. When the step is cut,\n * or kept whole without the text it already streamed, `inFlightText` is added as its own assistant message,\n * returned as `inFlightMessageId` so the caller can run it through the step processors it never reached.\n * @internal\n */\n public cloneWithCompletedSteps(inFlightText = ''): { turn: MessageList; inFlightMessageId?: string } {\n const clone = this.clone();\n const addInFlightText = () => {\n clone.add({ role: 'assistant', content: [{ type: 'text', text: inFlightText }] }, 'response', { merge: false });\n return clone.get.response.db().at(-1)!.id;\n };\n const completed = this.#completedStepParts;\n const pending = clone.get.response\n .db()\n .flatMap(message => (message.content.parts ?? []).slice(completed?.get(message.id) ?? 0));\n const toolCalls = pending.filter(part => part.type === 'tool-invocation');\n if (toolCalls.length > 0 && toolCalls.every(part => isTerminalToolInvocationState(part.toolInvocation.state))) {\n // Recovered eager work commits only the tool call and its result; the text streamed since is not in the list yet.\n const keptText = pending.flatMap(part => (part.type === 'text' ? [part.text] : [])).join('');\n if (inFlightText.trim().length > 0 && !keptText.includes(inFlightText.trim())) {\n return { turn: clone, inFlightMessageId: addInFlightText() };\n }\n return { turn: clone };\n }\n for (const message of clone.get.response.db()) {\n const length = completed?.get(message.id);\n if (length === undefined) clone.removeByIds([message.id]);\n else if ((message.content.parts?.length ?? 0) > length) {\n // clone() shares content with this list; truncating it in place would cut the live step too.\n message.content = {\n ...message.content,\n parts: [...message.content.parts],\n ...(message.content.metadata ? { metadata: { ...message.content.metadata } } : {}),\n };\n clone.#truncateParts(message, length);\n // #truncateParts drops structuredOutput for rollback; a completed step keeps the object it produced.\n const structuredOutput = this.#completedStepStructuredOutput?.get(message.id);\n if (structuredOutput !== undefined) {\n message.content.metadata = { ...message.content.metadata, structuredOutput };\n }\n }\n }\n if (inFlightText.trim().length > 0) return { turn: clone, inFlightMessageId: addInFlightText() };\n return { turn: clone };\n }\n\n private all = {\n db: (): MastraDBMessage[] => this.messages,\n v1: (): MastraMessageV1[] => convertToV1Messages(this.all.db()),\n\n aiV5: {\n model: (): AIV5Type.ModelMessage[] => {\n const promptMessages = this.getMessagesForModelPrompt();\n return convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(promptMessages, { transformToolPayloads: false }),\n promptMessages,\n );\n },\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.all.db()),\n\n // Used when calling AI SDK streamText/generateText\n prompt: (): AIV5Type.ModelMessage[] => {\n const systemMessages = convertAIV4CoreToAIV5ModelMessages(\n [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat()],\n `system`,\n this.createAdapterContext(),\n this.messages,\n );\n const promptMessages = this.getMessagesForModelPrompt();\n const modelMessages = convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(promptMessages, { transformToolPayloads: false }),\n promptMessages,\n this.promptConversionMode,\n );\n\n return [...systemMessages, ...modelMessages];\n },\n\n // Used for creating LLM prompt messages without AI SDK streamText/generateText\n llmPrompt: async (\n options: {\n downloadConcurrency?: number;\n downloadRetries?: number;\n supportedUrls?: Record<string, RegExp[]>;\n /**\n * Provider this prompt is being sent to. Lets conversion drop stored\n * provider-executed tool results a different provider produced.\n * @see https://github.com/mastra-ai/mastra/issues/23082\n */\n targetProvider?: string;\n /**\n * Replace user attachments that fail to download with a text placeholder\n * instead of failing the whole prompt, and record them as unavailable.\n */\n skipUnavailableAttachments?: boolean;\n } = {\n downloadConcurrency: 10,\n downloadRetries: 3,\n },\n ): Promise<LanguageModelV2Prompt> => {\n const promptMessages = this.getMessagesForModelPrompt().map(withUnavailableAttachmentPlaceholders);\n const modelMessages = convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(promptMessages, { transformToolPayloads: false }),\n promptMessages,\n this.promptConversionMode,\n );\n\n const storedModelOutputs = new Map<string, unknown>();\n for (const dbMsg of this.messages) {\n if (dbMsg.content?.format !== 2 || !dbMsg.content.parts) continue;\n\n for (const part of dbMsg.content.parts) {\n if (\n part.type === 'tool-invocation' &&\n part.toolInvocation?.state === 'result' &&\n part.providerMetadata?.mastra &&\n typeof part.providerMetadata.mastra === 'object' &&\n Object.hasOwn(part.providerMetadata.mastra, 'modelOutput') &&\n // A nullish `modelOutput` means the tool's toModelOutput opted out of mapping,\n // so the raw result must be kept.\n (part.providerMetadata.mastra as Record<string, unknown>).modelOutput != null\n ) {\n storedModelOutputs.set(\n part.toolInvocation.toolCallId,\n (part.providerMetadata.mastra as Record<string, unknown>).modelOutput,\n );\n }\n }\n }\n\n if (storedModelOutputs.size > 0) {\n for (const modelMsg of modelMessages) {\n if (modelMsg.role !== 'tool' || !Array.isArray(modelMsg.content)) continue;\n\n for (let i = 0; i < modelMsg.content.length; i++) {\n const part = modelMsg.content[i]!;\n if (part.type === 'tool-result' && storedModelOutputs.has(part.toolCallId)) {\n // The stored modelOutput is substituted into `output` here. The\n // internal `mastra.modelOutput` marker stays on the part: input\n // processors read it to tell a toModelOutput-mapped result apart\n // from a raw fallback (see ToolCallFilter).\n modelMsg.content[i] = {\n ...part,\n output: storedModelOutputs.get(part.toolCallId) as any,\n };\n }\n }\n }\n }\n const systemMessages = convertAIV4CoreToAIV5ModelMessages(\n [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat()],\n `system`,\n this.createAdapterContext(),\n this.messages,\n );\n\n // Attachments that failed to download while building this prompt.\n const unavailableUrls = new Set<string>();\n const downloadedAssets = await downloadAssetsFromMessages({\n messages: modelMessages,\n downloadConcurrency: options?.downloadConcurrency,\n downloadRetries: options?.downloadRetries,\n supportedUrls: options?.supportedUrls,\n cache: this.assetDownloads,\n // Invalid inline content gets the placeholder below; don't try to decode it first.\n isUnavailable: url => url.startsWith('data:') && !isSendableFileData(url),\n onUnavailable: (url, error) => {\n const isDataUrl = url.startsWith('data:');\n // A network download failure goes to error processors and fallback models first.\n if (!isDataUrl && !options?.skipUnavailableAttachments) throw error;\n unavailableUrls.add(url);\n if (!isDataUrl) this.recordUnavailableAttachment(url);\n this.logger?.warn(`Skipping an attachment that could not be downloaded: ${error.message}`);\n },\n });\n\n let messages = [...systemMessages, ...modelMessages];\n\n // Check if any messages have image/file content that needs processing\n const hasImageOrFileContent = modelMessages.some(\n message =>\n (message.role === 'user' || message.role === 'assistant') &&\n typeof message.content !== 'string' &&\n message.content.some(part => part.type === 'image' || part.type === 'file'),\n );\n\n if (hasImageOrFileContent) {\n messages = messages.map(message => {\n if (message.role === 'user') {\n if (typeof message.content === 'string') {\n return {\n role: 'user' as const,\n content: [{ type: 'text' as const, text: message.content }],\n providerOptions: message.providerOptions,\n } as AIV5Type.ModelMessage;\n }\n\n const convertedContent = message.content\n .map(part => {\n if (part.type === 'image' || part.type === 'file') {\n const assetUrl = getAssetUrl(part);\n const data = part.type === 'image' ? part.image : part.data;\n const unsendable = typeof data === 'string' && !isSendableFileData(data, part.mediaType);\n if (unsendable) {\n const shown = data.startsWith('data:')\n ? `${data.slice(0, data.indexOf(',') + 1)}<${data.length} chars>`\n : `${part.mediaType ?? part.type} <${data.length} chars>`;\n this.logger?.warn(`Skipping an attachment that is not a URL or valid file content: ${shown}`);\n }\n if (unsendable || (assetUrl && unavailableUrls.has(assetUrl))) {\n const name = (part.type === 'file' && part.filename) || part.mediaType || part.type;\n return { type: 'text' as const, text: unavailableAttachmentPlaceholder(name) };\n }\n return convertImageFilePart(part, downloadedAssets);\n }\n return part;\n })\n .filter(part => part.type !== 'text' || part.text !== '');\n\n return {\n role: 'user' as const,\n content: convertedContent,\n providerOptions: message.providerOptions,\n } as AIV5Type.ModelMessage;\n }\n\n if (message.role === 'assistant' && typeof message.content !== 'string') {\n const convertedContent = message.content.map(part => {\n if (part.type === 'file') {\n return convertImageFilePart(part, downloadedAssets);\n }\n return part;\n });\n\n return {\n ...message,\n content: convertedContent,\n };\n }\n\n return message;\n });\n }\n\n messages = dropCrossProviderExecutedParts(messages, this.messages, options.targetProvider, this.logger);\n\n return messages\n .filter(message => message != null)\n .map(aiV5ModelMessageToV2PromptMessage)\n .filter(\n message => message.role === 'system' || typeof message.content === 'string' || message.content.length > 0,\n );\n },\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.all.db()),\n\n // Builds the v5 prompt, then converts it to the shape AI SDK v6 (spec 'v3')\n // providers require (tool-result `media` -> `image-data`/`file-data`).\n llmPrompt: async (options?: {\n downloadConcurrency?: number;\n downloadRetries?: number;\n supportedUrls?: Record<string, RegExp[]>;\n targetProvider?: string;\n skipUnavailableAttachments?: boolean;\n }): Promise<LanguageModelV2Prompt> => aiV5PromptToAIV6Prompt(await this.all.aiV5.llmPrompt(options)),\n },\n aiV7: {\n ui: () => this.toAIV6UIMessages(this.all.db()),\n\n // Builds the v5 prompt, then converts tool-result `media` parts to the\n // file content shape AI SDK v7 (spec 'v4') providers require.\n llmPrompt: async (options?: {\n downloadConcurrency?: number;\n downloadRetries?: number;\n supportedUrls?: Record<string, RegExp[]>;\n targetProvider?: string;\n skipUnavailableAttachments?: boolean;\n }): Promise<LanguageModelV2Prompt> => aiV5PromptToAIV7Prompt(await this.all.aiV5.llmPrompt(options)),\n },\n\n /* @deprecated use list.get.all.aiV4.prompt() instead */\n prompt: () => this.all.aiV4.prompt(),\n /* @deprecated use list.get.all.aiV4.ui() */\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.all.db()),\n /* @deprecated use list.get.all.aiV4.core() */\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.all.db(), { transformToolPayloads: false })),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.all.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.getMessagesForModelPrompt(), { transformToolPayloads: false }),\n ),\n\n // Used when calling AI SDK streamText/generateText\n prompt: () => {\n const coreMessages = this.all.aiV4.core();\n return [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat(), ...coreMessages];\n },\n\n // Used for creating LLM prompt messages without AI SDK streamText/generateText\n llmPrompt: (): LanguageModelV1Prompt => {\n const coreMessages = this.all.aiV4.core();\n\n const systemMessages = [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat()];\n return [...systemMessages, ...coreMessages].map(aiV4CoreMessageToV1PromptMessage);\n },\n },\n };\n\n private remembered = {\n db: () => this.messages.filter(m => this.memoryMessages.has(m)),\n v1: () => convertToV1Messages(this.remembered.db()),\n\n aiV5: {\n model: () =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.remembered.db(), { transformToolPayloads: false }),\n this.messages,\n ),\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.remembered.db()),\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.remembered.db()),\n },\n\n /* @deprecated use list.get.remembered.aiV4.ui() */\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.remembered.db()),\n /* @deprecated use list.get.remembered.aiV4.core() */\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.remembered.db(), { transformToolPayloads: false })),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.remembered.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.remembered.db(), { transformToolPayloads: false })),\n },\n };\n private rememberedPersisted = {\n db: () => this.all.db().filter(m => this.memoryMessagesPersisted.has(m)),\n v1: () => convertToV1Messages(this.rememberedPersisted.db()),\n\n aiV5: {\n model: () =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.rememberedPersisted.db(), { transformToolPayloads: false }),\n this.messages,\n ),\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.rememberedPersisted.db()),\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.rememberedPersisted.db()),\n },\n\n /* @deprecated use list.getPersisted.remembered.aiV4.ui() */\n ui: () => this.toAIV4UIMessages(this.rememberedPersisted.db()),\n /* @deprecated use list.getPersisted.remembered.aiV4.core() */\n core: () =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.rememberedPersisted.db(), { transformToolPayloads: false }),\n ),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.rememberedPersisted.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.rememberedPersisted.db(), { transformToolPayloads: false }),\n ),\n },\n };\n\n private input = {\n db: () => this.messages.filter(m => this.newUserMessages.has(m)),\n v1: () => convertToV1Messages(this.input.db()),\n\n aiV5: {\n model: () =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.input.db(), { transformToolPayloads: false }),\n this.messages,\n ),\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.input.db()),\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.input.db()),\n },\n\n /* @deprecated use list.get.input.aiV4.ui() instead */\n ui: () => this.toAIV4UIMessages(this.input.db()),\n /* @deprecated use list.get.core.aiV4.ui() instead */\n core: () =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.input.db(), { transformToolPayloads: false })),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.input.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.input.db(), { transformToolPayloads: false })),\n },\n };\n private inputPersisted = {\n db: (): MastraDBMessage[] => this.messages.filter(m => this.newUserMessagesPersisted.has(m)),\n v1: (): MastraMessageV1[] => convertToV1Messages(this.inputPersisted.db()),\n\n aiV5: {\n model: () =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.inputPersisted.db(), { transformToolPayloads: false }),\n this.messages,\n ),\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.inputPersisted.db()),\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.inputPersisted.db()),\n },\n\n /* @deprecated use list.getPersisted.input.aiV4.ui() */\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.inputPersisted.db()),\n /* @deprecated use list.getPersisted.input.aiV4.core() */\n core: () =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.inputPersisted.db(), { transformToolPayloads: false }),\n ),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.inputPersisted.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.inputPersisted.db(), { transformToolPayloads: false }),\n ),\n },\n };\n\n private response = {\n db: (): MastraDBMessage[] => this.messages.filter(m => this.newResponseMessages.has(m)),\n v1: (): MastraMessageV1[] => convertToV1Messages(this.response.db()),\n\n aiV5: {\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.response.db()),\n model: (): AIV5ResponseMessage[] =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.response.db(), { transformToolPayloads: false }),\n this.messages,\n ).filter(m => m.role === `tool` || m.role === `assistant`),\n modelContent: (stepNumber?: number, stepToolCallIds?: string[]): AIV5Type.StepResult<any>['content'] => {\n if (typeof stepNumber === 'number') {\n // Delegate to StepContentExtractor for step-specific content extraction\n return StepContentExtractor.extractStepContent(\n this.response.aiV5.ui(),\n stepNumber,\n this.response.aiV5.stepContent,\n stepToolCallIds,\n );\n }\n\n return this.response.aiV5.model().map(this.response.aiV5.stepContent).flat();\n },\n stepContent: (message?: AIV5Type.ModelMessage): AIV5Type.StepResult<any>['content'] => {\n // Delegate to StepContentExtractor for content conversion\n return StepContentExtractor.convertToStepContent(message, this.messages, () =>\n this.response.aiV5.model().at(-1),\n );\n },\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.response.db()),\n },\n\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.response.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(this.toAIV4UIMessages(this.response.db(), { transformToolPayloads: false })),\n },\n };\n /** Ids of pruned response messages that are not (again) tracked as response messages in the live list. */\n #getPrunedResponseMessageIds(): string[] {\n if (this.#prunedResponseMessages.size === 0) return [];\n const liveResponseIds = new Set(this.responsePersisted.db().map(message => message.id));\n return Array.from(this.#prunedResponseMessages.keys()).filter(id => !liveResponseIds.has(id));\n }\n\n /**\n * Every response message this run produced, in order, including messages that were later pruned\n * from the live context (see removeByIds' `pruned` option). Use this to evaluate the whole run,\n * e.g. for scoring; use getPersisted.response for what is still in the list.\n *\n * A list restored from serialized state only knows pruned messages by id; `loadStoredMessages`\n * loads them from memory, where they were saved before being pruned. Pruned messages it cannot\n * load are left out.\n */\n public async getRunResponseMessages(loadStoredMessages?: StoredMessageLoader): Promise<MastraDBMessage[]> {\n const live = this.responsePersisted.db();\n const prunedIds = this.#getPrunedResponseMessageIds();\n if (prunedIds.length === 0) return live;\n\n const pruned: MastraDBMessage[] = [];\n const missingIds: string[] = [];\n for (const id of prunedIds) {\n const message = this.#prunedResponseMessages.get(id);\n if (message) pruned.push(message);\n else missingIds.push(id);\n }\n if (missingIds.length > 0 && loadStoredMessages) {\n const missing = new Set(missingIds);\n const stored = (await loadStoredMessages(missingIds)) ?? [];\n pruned.push(...stored.filter(message => missing.has(message.id)));\n }\n return [...pruned, ...live].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());\n }\n\n private responsePersisted = {\n db: (): MastraDBMessage[] => this.messages.filter(m => this.newResponseMessagesPersisted.has(m)),\n\n aiV5: {\n model: () =>\n convertAIV5UIToModelMessages(\n this.toAIV5UIMessages(this.responsePersisted.db(), { transformToolPayloads: false }),\n this.messages,\n ),\n ui: (): AIV5Type.UIMessage[] => this.toAIV5UIMessages(this.responsePersisted.db()),\n },\n aiV6: {\n ui: () => this.toAIV6UIMessages(this.responsePersisted.db()),\n },\n\n /* @deprecated use list.getPersisted.response.aiV4.ui() */\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.responsePersisted.db()),\n aiV4: {\n ui: (): UIMessageWithMetadata[] => this.toAIV4UIMessages(this.responsePersisted.db()),\n core: (): CoreMessageV4[] =>\n aiV4UIMessagesToAIV4CoreMessages(\n this.toAIV4UIMessages(this.responsePersisted.db(), { transformToolPayloads: false }),\n ),\n },\n };\n\n private recordUnavailableAttachment(url: string) {\n for (const message of this.messages) {\n if (\n message.role !== 'user' ||\n getUnavailableAttachmentUrls(message).includes(url) ||\n !getMessageAttachmentUrls(message).includes(url)\n ) {\n continue;\n }\n message.content.metadata = withUnavailableAttachmentUrls(message.content.metadata, [url]);\n const urls = this.unavailableAttachmentUpdates.get(message.id) ?? new Set<string>();\n urls.add(url);\n this.unavailableAttachmentUpdates.set(message.id, urls);\n }\n }\n\n /**\n * Returns and clears the attachments newly recorded as unavailable while building\n * prompts. The in-memory messages already carry the record; callers persist it for\n * messages that were loaded from storage.\n */\n public drainUnavailableAttachmentUpdates(): { messageId: string; urls: string[] }[] {\n const updates = [...this.unavailableAttachmentUpdates].map(([messageId, urls]) => ({\n messageId,\n urls: [...urls],\n }));\n this.unavailableAttachmentUpdates.clear();\n return updates;\n }\n\n public drainUnsavedMessages(): MastraDBMessage[] {\n return this.drainUnsavedMessagesForSave().messages;\n }\n\n /**\n * Same as {@link drainUnsavedMessages}, plus `restore`, which marks the drained\n * messages unsaved again so a later save writes them after this one failed.\n */\n public drainUnsavedMessagesForSave(): { messages: MastraDBMessage[]; restore: () => void } {\n const userMessages = [...this.newUserMessages];\n const responseMessages = [...this.newResponseMessages];\n const messages = this.messages.filter(m => this.newUserMessages.has(m) || this.newResponseMessages.has(m));\n this.newUserMessages.clear();\n this.newResponseMessages.clear();\n return {\n messages: messages.map(message => this.transformMessageForTranscript(message)),\n restore: () => {\n for (const message of userMessages) {\n if (this.messages.includes(message)) this.newUserMessages.add(message);\n }\n for (const message of responseMessages) {\n if (this.messages.includes(message)) this.newResponseMessages.add(message);\n }\n },\n };\n }\n\n /**\n * Apply transcript payload transforms to messages without draining them.\n *\n * Persistence paths that read messages directly instead of draining (e.g.\n * the MessageHistory output processor persisting `get.response.db()`) must\n * apply the same transcript redaction as {@link drainUnsavedMessages}.\n * Otherwise the two writers race last-writer-wins on the same message id: a\n * background tool result committed via {@link updateToolInvocation} holds\n * the raw payload plus its transcript transform in providerMetadata, and a\n * direct save landing after the redacting save-queue flush would persist\n * the raw payload. The transform is idempotent — re-applying it to an\n * already-transformed message writes the same values.\n */\n public transformMessagesForTranscript(messages: MastraDBMessage[]): MastraDBMessage[] {\n return messages.map(message => this.transformMessageForTranscript(message));\n }\n\n private transformToolStateDataForTranscript(data: unknown, phase: 'approval' | 'suspend'): unknown {\n if (!data || typeof data !== 'object') {\n return data;\n }\n\n const stateData = data as Record<string, unknown>;\n const metadata = stateData.metadata ?? stateData.providerMetadata;\n const phaseTransform = getTransformedToolPayload(metadata, 'transcript', phase);\n const inputTransform = getTransformedToolPayload(metadata, 'transcript', 'input-available');\n const transformedArgs =\n phase === 'approval'\n ? hasTransformedToolPayload(phaseTransform)\n ? phaseTransform.transformed\n : hasTransformedToolPayload(inputTransform)\n ? inputTransform.transformed\n : undefined\n : hasTransformedToolPayload(inputTransform)\n ? inputTransform.transformed\n : hasTransformedToolPayload(phaseTransform)\n ? phaseTransform.transformed\n : undefined;\n const transformedSuspendPayload =\n phase === 'suspend' && hasTransformedToolPayload(phaseTransform) ? phaseTransform.transformed : undefined;\n\n return {\n ...stateData,\n ...(transformedArgs !== undefined ? { args: transformedArgs } : {}),\n ...(transformedSuspendPayload !== undefined ? { suspendPayload: transformedSuspendPayload } : {}),\n };\n }\n\n private transformMessageForTranscript(message: MastraDBMessage): MastraDBMessage {\n if (message.content?.format !== 2 || !message.content.parts) {\n return message;\n }\n\n let changed = false;\n const transformedByToolCallId = new Map<string, { args?: unknown; result?: unknown; errorText?: string }>();\n\n const parts = message.content.parts.map(part => {\n if (part.type === 'tool-invocation' && part.toolInvocation) {\n const inputTransform = getTransformedToolPayload(part.providerMetadata, 'transcript', 'input-available');\n // A provider-flagged error (`output-error` with a structured `result`) comes from a tool-result\n // chunk, so its transcript transform is stored under the output-available phase.\n const isProviderErrorResult =\n part.toolInvocation.state === 'output-error' &&\n part.toolInvocation.result !== undefined &&\n part.providerExecuted === true;\n const outputTransform =\n part.toolInvocation.state === 'result' || isProviderErrorResult\n ? (getTransformedToolPayload(part.providerMetadata, 'transcript', 'output-available') ??\n getTransformedToolPayload(part.providerMetadata, 'transcript', 'error'))\n : part.toolInvocation.state === 'output-error'\n ? getTransformedToolPayload(part.providerMetadata, 'transcript', 'error')\n : undefined;\n\n if (!inputTransform && !outputTransform) {\n return part;\n }\n\n changed = true;\n const transformedArgs = hasTransformedToolPayload(inputTransform)\n ? inputTransform.transformed\n : part.toolInvocation.args;\n const transformedResult =\n part.toolInvocation.state === 'result'\n ? hasTransformedToolPayload(outputTransform)\n ? outputTransform.transformed\n : part.toolInvocation.result\n : undefined;\n const transformedErrorResult = isProviderErrorResult\n ? hasTransformedToolPayload(outputTransform)\n ? outputTransform.transformed\n : part.toolInvocation.result\n : undefined;\n const transformedErrorText =\n part.toolInvocation.state === 'output-error'\n ? isProviderErrorResult && hasTransformedToolPayload(outputTransform)\n ? typeof transformedErrorResult === 'string'\n ? transformedErrorResult\n : safeStringify(transformedErrorResult)\n : hasTransformedToolPayload(outputTransform)\n ? (outputTransform.transformed as string)\n : part.toolInvocation.errorText\n : undefined;\n transformedByToolCallId.set(part.toolInvocation.toolCallId, {\n args: transformedArgs,\n ...(part.toolInvocation.state === 'result' ? { result: transformedResult } : {}),\n ...(part.toolInvocation.state === 'output-error'\n ? {\n errorText: transformedErrorText,\n ...(isProviderErrorResult ? { result: transformedErrorResult } : {}),\n }\n : {}),\n });\n\n return {\n ...part,\n toolInvocation: {\n ...part.toolInvocation,\n args: transformedArgs,\n ...(part.toolInvocation.state === 'result' ? { result: transformedResult } : {}),\n ...(part.toolInvocation.state === 'output-error'\n ? {\n errorText: transformedErrorText,\n ...(isProviderErrorResult ? { result: transformedErrorResult } : {}),\n }\n : {}),\n },\n };\n }\n\n if (part.type === 'data-tool-call-suspended' || part.type === 'data-tool-call-approval') {\n changed = true;\n return {\n ...part,\n data: this.transformToolStateDataForTranscript(\n part.data,\n part.type === 'data-tool-call-suspended' ? 'suspend' : 'approval',\n ),\n };\n }\n\n return part;\n });\n\n const toolInvocations = message.content.toolInvocations?.map(invocation => {\n const transformed = transformedByToolCallId.get(invocation.toolCallId);\n if (!transformed) {\n return invocation;\n }\n\n const invocationState = invocation.state as string;\n changed = true;\n return {\n ...invocation,\n ...(transformed.args !== undefined ? { args: transformed.args } : {}),\n ...((invocation.state === 'result' || invocationState === 'output-error') && 'result' in transformed\n ? { result: transformed.result }\n : {}),\n ...(invocationState === 'output-error' && transformed.errorText !== undefined\n ? { errorText: transformed.errorText }\n : {}),\n };\n });\n\n const metadata =\n message.content.metadata && typeof message.content.metadata === 'object'\n ? { ...(message.content.metadata as Record<string, unknown>) }\n : message.content.metadata;\n if (metadata && typeof metadata === 'object') {\n for (const [key, phase] of [\n ['suspendedTools', 'suspend'],\n ['pendingToolApprovals', 'approval'],\n ] as const) {\n const toolStates = metadata[key];\n if (!toolStates || typeof toolStates !== 'object') {\n continue;\n }\n changed = true;\n metadata[key] = Object.fromEntries(\n Object.entries(toolStates as Record<string, unknown>).map(([toolName, state]) => [\n toolName,\n this.transformToolStateDataForTranscript(state, phase),\n ]),\n );\n }\n }\n\n if (!changed) {\n return message;\n }\n\n return {\n ...message,\n content: {\n ...message.content,\n parts,\n ...(toolInvocations ? { toolInvocations } : {}),\n ...(metadata ? { metadata } : {}),\n },\n };\n }\n\n public getEarliestUnsavedMessageTimestamp(): number | undefined {\n const unsavedMessages = this.messages.filter(m => this.newUserMessages.has(m) || this.newResponseMessages.has(m));\n if (unsavedMessages.length === 0) return undefined;\n // Find the earliest createdAt among unsaved messages\n return Math.min(...unsavedMessages.map(m => new Date(m.createdAt).getTime()));\n }\n\n /**\n * Check if a message is a new user or response message that should be saved.\n * Checks by message ID to handle cases where the message object may be a copy.\n */\n public isNewMessage(messageOrId: MastraDBMessage | string): boolean {\n return this.stateManager.isNewMessage(messageOrId);\n }\n\n /**\n * Replace a tool-invocation part matching the given toolCallId with the\n * provided result part. Walks backwards through messages to find the match.\n * If the message was already persisted (e.g. as a memory message), it is\n * moved to the response source so it will be re-saved.\n *\n * @returns true if the tool call was found and updated, false otherwise.\n */\n public updateToolInvocation(\n inputPart: Extract<MastraMessagePart, { type: 'tool-invocation' }>,\n metadata?: Record<string, unknown>,\n ): boolean {\n if (!inputPart.toolInvocation?.toolCallId) {\n return false;\n }\n const toolCallId = inputPart.toolInvocation.toolCallId;\n\n // Pass 1: exact toolCallId match. Covers client tools and well-behaved\n // providers where the call and result share an id.\n for (let m = this.messages.length - 1; m >= 0; m--) {\n const msg = this.messages[m]!;\n if (msg.role !== 'assistant' || !msg.content?.parts) continue;\n\n for (let i = 0; i < msg.content.parts.length; i++) {\n const part = msg.content.parts[i];\n if (part?.type === 'tool-invocation' && part.toolInvocation?.toolCallId === toolCallId) {\n this.mergeToolResultIntoPart(msg, i, inputPart, metadata);\n return true;\n }\n }\n }\n\n // Pass 2 (fallback): some providers (e.g. @ai-sdk/google `file_search`\n // running alongside a client tool) assign the tool-result a DIFFERENT\n // toolCallId than the tool-call. Match a still-pending provider-executed\n // call by toolName and overwrite its id with the incoming one so the\n // next-turn replay sends a consistent id. The providerExecuted + state:'call'\n // guard leaves client tools (stable ids) untouched, and the legitimate\n // same-stream case (no state:'call' part exists yet) still returns false.\n const inputToolName = inputPart.toolInvocation.toolName;\n for (let m = this.messages.length - 1; m >= 0; m--) {\n const msg = this.messages[m]!;\n if (msg.role !== 'assistant' || !msg.content?.parts) continue;\n\n for (let i = 0; i < msg.content.parts.length; i++) {\n const part = msg.content.parts[i];\n if (part?.type !== 'tool-invocation') continue;\n // Cast to access providerExecuted which exists at runtime but isn't in the base type\n const candidate = part as typeof part & { providerExecuted?: boolean };\n if (\n candidate.providerExecuted === true &&\n candidate.toolInvocation?.state === 'call' &&\n candidate.toolInvocation.toolName === inputToolName\n ) {\n // Reconcile the stored id so downstream replay uses the result's id.\n // Pass the prior id so the legacy `toolInvocations` array can be\n // resynced from its old key (it still holds the original id).\n const previousToolCallId = candidate.toolInvocation.toolCallId;\n candidate.toolInvocation.toolCallId = toolCallId;\n this.mergeToolResultIntoPart(msg, i, inputPart, metadata, previousToolCallId);\n return true;\n }\n }\n }\n\n this.logger?.warn(`updateToolInvocation: no matching tool call found for toolCallId=${toolCallId}`);\n return false;\n }\n\n public updateMessageMetadataByToolCallId(toolCallId: string, metadata: Record<string, unknown>): boolean {\n if (!toolCallId) {\n return false;\n }\n\n for (let m = this.messages.length - 1; m >= 0; m--) {\n const msg = this.messages[m]!;\n if (msg.role !== 'assistant' || !msg.content?.parts) continue;\n\n const hasToolCall = msg.content.parts.some(\n part => part?.type === 'tool-invocation' && part.toolInvocation?.toolCallId === toolCallId,\n );\n if (!hasToolCall) continue;\n\n const existingMeta = (msg.content.metadata ?? {}) as Record<string, unknown>;\n const incomingMeta = (metadata ?? {}) as Record<string, unknown>;\n const existingBgTasks = existingMeta.backgroundTasks as Record<string, unknown> | undefined;\n const incomingBgTasks = incomingMeta.backgroundTasks as Record<string, unknown> | undefined;\n const backgroundTasks = mergeBackgroundTasks(existingBgTasks, incomingBgTasks);\n\n msg.content.metadata = {\n ...existingMeta,\n ...incomingMeta,\n ...(backgroundTasks ? { backgroundTasks } : {}),\n };\n\n // Update ordering and queue the edited metadata for persistence.\n this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, Date.now());\n this.updateLastCreatedAt(msg);\n if (!this.stateManager.isResponseMessage(msg)) {\n this.stateManager.removeMessage(msg);\n this.stateManager.addToSource(msg, 'response');\n }\n\n return true;\n }\n\n this.logger?.warn(`updateMessageMetadataByToolCallId: no matching tool call found for toolCallId=${toolCallId}`);\n return false;\n }\n\n /**\n * Fail explicitly selected provider calls still in `call` or `partial-call` state.\n * Explicit IDs prevent masking unrelated missing-result bugs. Preserves args and\n * metadata, syncs legacy AIV4 invocations, and queues the message for persistence.\n * Returns whether any call changed.\n */\n public addOutputErrorsToProviderToolCalls(messageId: string, toolCallIds: string[], errorText?: string): boolean {\n if (!messageId || !toolCallIds?.length) {\n return false;\n }\n\n const targetIds = new Set(toolCallIds);\n const resolvedErrorText =\n errorText ?? 'Provider tool call did not complete: the model stream terminated with an error.';\n\n const msg = this.messages.find(m => m.id === messageId && m.role === 'assistant');\n if (!msg?.content?.parts) {\n return false;\n }\n\n let changed = false;\n const erroredToolCallIds: string[] = [];\n\n for (let i = 0; i < msg.content.parts.length; i++) {\n const part = msg.content.parts[i];\n if (part?.type !== 'tool-invocation') continue;\n // Cast to access providerExecuted which exists at runtime but isn't in the base type\n const candidate = part as typeof part & { providerExecuted?: boolean };\n const state = candidate.toolInvocation?.state;\n if (\n candidate.providerExecuted !== true ||\n !targetIds.has(candidate.toolInvocation?.toolCallId) ||\n (state !== 'call' && state !== 'partial-call')\n ) {\n continue;\n }\n\n candidate.toolInvocation = {\n ...candidate.toolInvocation,\n state: 'output-error',\n errorText: resolvedErrorText,\n };\n erroredToolCallIds.push(candidate.toolInvocation.toolCallId);\n changed = true;\n }\n\n if (!changed) {\n return false;\n }\n\n // The legacy AIV4 `content.toolInvocations` array has no `output-error`\n // state (its union is partial-call | call | result), so drop the abandoned\n // entries instead of leaving them as a dangling `call` in AIV4 transcripts.\n if (Array.isArray(msg.content.toolInvocations)) {\n msg.content.toolInvocations = msg.content.toolInvocations.filter(\n invocation => !erroredToolCallIds.includes(invocation.toolCallId),\n );\n }\n\n // Update ordering and queue the failed calls for persistence.\n this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, Date.now());\n this.updateLastCreatedAt(msg);\n if (!this.stateManager.isResponseMessage(msg)) {\n this.stateManager.removeMessage(msg);\n this.stateManager.addToSource(msg, 'response');\n }\n\n return true;\n }\n\n /**\n * Merge a tool-result `inputPart` into the stored tool-invocation part at\n * `msg.content.parts[i]`: preserves the original call args, merges\n * providerExecuted/providerMetadata, merges per-toolCallId `backgroundTasks`\n * metadata, and moves the message to the response source so it is re-saved.\n * Shared by both the exact-toolCallId and provider-executed-toolName passes\n * of {@link updateToolInvocation}.\n */\n private mergeToolResultIntoPart(\n msg: MastraDBMessage,\n i: number,\n inputPart: Extract<MastraMessagePart, { type: 'tool-invocation' }>,\n metadata?: Record<string, unknown>,\n previousToolCallId?: string,\n ): void {\n const part = msg.content.parts![i] as Extract<MastraMessagePart, { type: 'tool-invocation' }>;\n // The legacy `content.toolInvocations` array (AIV4) is keyed by the id the\n // part had BEFORE any reconciliation; default to the part's current id.\n const priorToolCallId = previousToolCallId ?? part.toolInvocation.toolCallId;\n // Cast to access providerExecuted/providerMetadata which exist at runtime but aren't in the base type\n const originalPart = part as typeof part & { providerExecuted?: boolean; providerMetadata?: unknown };\n const inputPartWithMeta = inputPart as typeof inputPart & {\n providerExecuted?: boolean;\n providerMetadata?: unknown;\n };\n\n // `providerMetadata` is a two-level map — provider namespace -> key -> value —\n // so merging it must also be two levels deep. A one-level merge let a caller\n // either keep a whole namespace or clobber it, never replace a single key\n // inside it. That stranded stale keys: a completing background task passes\n // fresh `mastra.modelOutput`, and under a shallow merge either the dispatch's\n // placeholder survived or the rest of the `mastra` namespace was dropped.\n // Merging per-namespace preserves untouched sibling keys (the point of the\n // original shallow merge) while letting the incoming part replace the keys it\n // actually sets.\n const mergedProviderMetadata =\n originalPart.providerMetadata !== undefined || inputPartWithMeta.providerMetadata !== undefined\n ? (() => {\n const original = (originalPart.providerMetadata ?? {}) as Record<\n string,\n Record<string, AIV5Type.JSONValue>\n >;\n const incoming = (inputPartWithMeta.providerMetadata ?? {}) as Record<\n string,\n Record<string, AIV5Type.JSONValue>\n >;\n const merged: Record<string, Record<string, AIV5Type.JSONValue>> = { ...original };\n for (const [namespace, values] of Object.entries(incoming)) {\n const existing = merged[namespace];\n // Only merge when both sides are plain objects; a namespace set to a\n // non-object (or absent) is replaced wholesale, as before.\n merged[namespace] =\n existing &&\n typeof existing === 'object' &&\n !Array.isArray(existing) &&\n values &&\n typeof values === 'object' &&\n !Array.isArray(values)\n ? { ...existing, ...values }\n : values;\n }\n // Some hosted tools (e.g. OpenAI `tool_search`) give the call and its\n // output DIFFERENT Responses item ids (tsc_… / tso_…). The namespace\n // merge above keeps only one `itemId`, so replay would reference the\n // same item twice (\"Duplicate item found\"). Retain the call's id and\n // stash the result's beside it; prompt conversion splits them back\n // onto their own tool parts.\n return preserveResponseItemIdsOnMerge(original, incoming, merged) as AIV5Type.ProviderMetadata;\n })()\n : undefined;\n\n const mergedPart: Extract<MastraMessagePart, { type: 'tool-invocation' }> = {\n ...inputPart,\n toolInvocation: {\n ...inputPart.toolInvocation,\n args: part.toolInvocation.args,\n },\n // Preserve providerExecuted from original call if not in result\n ...(originalPart.providerExecuted !== undefined && inputPartWithMeta.providerExecuted === undefined\n ? { providerExecuted: originalPart.providerExecuted }\n : {}),\n ...(part.title !== undefined && inputPart.title === undefined ? { title: part.title } : {}),\n ...(mergedProviderMetadata !== undefined ? { providerMetadata: mergedProviderMetadata } : {}),\n };\n if (part.updatedAt !== undefined && mergedPart.updatedAt === undefined) mergedPart.updatedAt = part.updatedAt;\n stampToolPartUpdate(mergedPart, part.toolInvocation, inputPart.updatedAt);\n msg.content.parts![i] = mergedPart;\n\n // `backgroundTasks` is a per-toolCallId record — merge instead of\n // overwrite so multiple concurrent background dispatches on the\n // same assistant message don't clobber each other's metadata.\n const existingMeta = (msg.content.metadata ?? {}) as Record<string, unknown>;\n const incomingMeta = (metadata ?? {}) as Record<string, unknown>;\n const existingBgTasks = existingMeta.backgroundTasks as Record<string, unknown> | undefined;\n const incomingBgTasks = incomingMeta.backgroundTasks as Record<string, unknown> | undefined;\n const backgroundTasks = mergeBackgroundTasks(existingBgTasks, incomingBgTasks);\n\n msg.content.metadata = {\n ...existingMeta,\n ...incomingMeta,\n ...(backgroundTasks ? { backgroundTasks } : {}),\n };\n\n // Keep the legacy AIV4 `content.toolInvocations` array in sync so a later\n // transformMessageForTranscript() can still map this part back: carry over\n // the result and the (possibly reconciled) toolCallId, matching the entry by\n // the id it held before reconciliation. Spread the legacy entry first to\n // preserve its type, then override only the fields that change here.\n // A provider-executed error (`output-error`) is mirrored as a result: v4 has no error state.\n // Client-tool errors stay out of the mirror so v4 never reads them as successes.\n if (\n Array.isArray(msg.content.toolInvocations) &&\n (inputPart.toolInvocation.state === 'result' ||\n (inputPart.toolInvocation.state === 'output-error' &&\n (inputPartWithMeta.providerExecuted ?? originalPart.providerExecuted) === true))\n ) {\n const resultInvocation = inputPart.toolInvocation;\n msg.content.toolInvocations = msg.content.toolInvocations.map(invocation =>\n invocation.toolCallId === priorToolCallId\n ? {\n ...invocation,\n toolCallId: resultInvocation.toolCallId,\n state: 'result' as const,\n args: part.toolInvocation.args,\n result: resultInvocation.result,\n }\n : invocation,\n );\n }\n\n // Update ordering and queue the merged result for persistence.\n this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, Date.now());\n this.updateLastCreatedAt(msg);\n if (!this.stateManager.isResponseMessage(msg)) {\n this.stateManager.removeMessage(msg);\n this.stateManager.addToSource(msg, 'response');\n }\n }\n\n /**\n * Append a `step-start` boundary to the last assistant message.\n * This marks the beginning of a new loop iteration so that\n * `convertToModelMessages` splits sequential tool-call turns into\n * separate message blocks instead of collapsing them into one.\n *\n * Respects sealed messages (post-observation) — if the last assistant\n * message is sealed, the step-start is not added.\n *\n * If the message was loaded from memory it is moved to the response\n * source so the updated content is re-saved.\n */\n public stepStart(): boolean {\n return this.openStepBoundary().appended;\n }\n\n /**\n * Open the boundary for a new loop iteration and hand back the marker that delimits it.\n *\n * This is `stepStart()` with the marker returned instead of discarded, for callers that\n * need to name *their own* boundary later — `rollbackToStepBoundary` is the only one today.\n * The distinction matters because `step-start` has several writers and they are\n * indistinguishable once stored: besides this loop boundary, a marker is synthesized inside a\n * single model response whenever a tool call is followed by text\n * (`build-messages-from-chunks.ts`, `MessageMerger.pushNewPart`, `addStartStepPartsForAIV5`).\n * Nothing on the part records which writer produced it — `model` in particular does not, since\n * `MessageMerger` deliberately copies it from the preceding marker onto the synthetic one.\n * So \"the last `step-start`\" is not \"the boundary this iteration opened\", and only the caller\n * that opened one can tell them apart. The reference is the primary handle; a checkpoint is\n * recorded alongside it so `findBoundaryIndex` can still recognise the marker if a processor\n * hands the list a cloned copy of the parts. Nothing new is written to the part itself.\n *\n * When the last part is already a `step-start` the iteration begins at *that* marker — nothing\n * has been appended after it — so it is returned rather than duplicated.\n *\n * @returns the marker beginning this iteration, and whether it had to be appended\n */\n public openStepBoundary(): { boundary?: MastraStepStartPart; appended: boolean } {\n const lastMsg = this.messages[this.messages.length - 1];\n if (!lastMsg || lastMsg.role !== 'assistant' || !lastMsg.content?.parts) {\n return { appended: false };\n }\n\n if (MessageMerger.isSealed(lastMsg)) {\n return { appended: false };\n }\n\n // Don't add a duplicate step-start\n const lastPart = lastMsg.content.parts[lastMsg.content.parts.length - 1];\n const appended = lastPart?.type !== 'step-start';\n\n // A reused marker can be unstamped — `MessageMerger` leaves one so when the marker before it\n // carries no `model` — which would cost this iteration its recovery in `findBoundaryIndex`.\n // `stampPart` is a no-op on a marker that already has a `createdAt`.\n const boundary = appended ? stampPart({ type: 'step-start' as const }) : stampPart(lastPart);\n if (appended) lastMsg.content.parts.push(boundary);\n this.#rememberBoundaryFingerprint(lastMsg.id, lastMsg.content.parts, boundary);\n this.#lastStepBoundary = boundary;\n\n // Ensure the mutated message is persisted. The reused branch stamps too, so it needs this as\n // much as the appended one does. When the reused marker was already stamped there is nothing\n // to write, and re-sourcing then costs one redundant write of a message this run produced.\n if (!this.stateManager.isResponseMessage(lastMsg)) {\n this.stateManager.removeMessage(lastMsg);\n this.stateManager.addToSource(lastMsg, 'response');\n }\n\n return { boundary, appended };\n }\n\n /**\n * What preceded a boundary when it was opened, and in which message, kept beside the part\n * rather than on it so nothing new has to survive serialization. `findBoundaryIndex` needs it\n * to tell a recovered boundary from a same-millisecond marker that merely took its place.\n */\n #boundaryFingerprints = new WeakMap<MastraStepStartPart, BoundaryCheckpoint>();\n\n #lastStepBoundary: MastraStepStartPart | undefined;\n\n /**\n * The parts of `message` written by the current loop iteration: those after the boundary the\n * latest `openStepBoundary()` opened, or all of them when that boundary is not in `message`\n * (a first iteration opens none, and a later one may have started a new message).\n * Intra-response `step-start` markers are not boundaries, so this never splits a single response.\n */\n public partsSinceStepBoundary(message: MastraDBMessage): MastraMessagePart[] {\n const parts = message.content.parts ?? [];\n const boundary = this.#lastStepBoundary;\n if (!boundary) return parts;\n const index = findBoundaryIndex(parts, boundary, message.id, this.#boundaryFingerprints.get(boundary));\n return index === -1 ? parts : parts.slice(index + 1);\n }\n\n #locateLastStepBoundary(): { messageId: string; partIndex: number } | undefined {\n const boundary = this.#lastStepBoundary;\n if (!boundary) return undefined;\n const checkpoint = this.#boundaryFingerprints.get(boundary);\n for (const message of this.messages) {\n const partIndex = findBoundaryIndex(message.content.parts ?? [], boundary, message.id, checkpoint);\n if (partIndex !== -1) return { messageId: message.id, partIndex };\n }\n return undefined;\n }\n\n #rememberBoundaryFingerprint(messageId: string, parts: MastraMessagePart[], boundary: MastraStepStartPart) {\n const index = parts.indexOf(boundary);\n if (index !== -1) this.#boundaryFingerprints.set(boundary, { messageId, prefix: prefixFingerprint(parts, index) });\n }\n\n /** Sealing is not optional: a moved id whose boundary is missing folds the next response into the previous row. */\n public rotateResponseMessageId(sealMessageId?: string): string {\n if (!this.markResponseMessageBoundary(sealMessageId)) this.markResponseMessageBoundary();\n return this.newMessageId('assistant');\n }\n\n public markResponseMessageBoundary(messageId?: string): boolean {\n const message = messageId\n ? this.messages.find(message => message.id === messageId)\n : [...this.messages].reverse().find(message => message.role === 'assistant');\n\n if (!message || message.role !== 'assistant') {\n return false;\n }\n\n message.content.metadata = {\n ...(message.content.metadata ?? {}),\n mastra: {\n ...((message.content.metadata?.mastra as Record<string, unknown> | undefined) ?? {}),\n responseBoundary: true,\n },\n };\n\n if (!this.stateManager.isResponseMessage(message)) {\n this.stateManager.removeMessage(message);\n this.stateManager.addToSource(message, 'response');\n }\n\n return true;\n }\n\n public enrichLastStepStart(model: string): boolean {\n const lastMsg = this.messages[this.messages.length - 1];\n if (!lastMsg || lastMsg.role !== 'assistant' || !lastMsg.content?.parts) {\n return false;\n }\n\n if (MessageMerger.isSealed(lastMsg)) {\n return false;\n }\n\n for (let i = lastMsg.content.parts.length - 1; i >= 0; i--) {\n const part = lastMsg.content.parts[i];\n if (part?.type !== 'step-start') {\n continue;\n }\n\n // Only stamp step-starts that haven't already been attributed. A prior\n // iteration (or a re-used message loaded from memory) may have already\n // stamped its model, and overwriting it would mis-attribute history.\n if (part.model) {\n return false;\n }\n\n part.model = model;\n\n if (!this.stateManager.isResponseMessage(lastMsg)) {\n this.stateManager.removeMessage(lastMsg);\n this.stateManager.addToSource(lastMsg, 'response');\n }\n\n return true;\n }\n\n return false;\n }\n\n public getSystemMessages(tag?: string): CoreMessageV4[] {\n if (tag) {\n return this.taggedSystemMessages[tag] || [];\n }\n return this.systemMessages;\n }\n\n /**\n * Get all system messages (both tagged and untagged)\n * @returns Array of all system messages\n */\n public getAllSystemMessages(): CoreMessageV4[] {\n return [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat()];\n }\n\n /**\n * Clear system messages, optionally for a specific tag\n * @param tag - If provided, only clears messages with this tag. Otherwise clears untagged messages.\n */\n public clearSystemMessages(tag?: string): this {\n if (tag) {\n delete this.taggedSystemMessages[tag];\n } else {\n this.systemMessages = [];\n }\n return this;\n }\n\n /**\n * Replace the untagged system message bucket with the provided array while\n * leaving tagged system message buckets (owned by other processors) intact.\n * @param messages - Array of system messages to set as untagged\n */\n public replaceAllSystemMessages(messages: CoreMessageV4[]): this {\n this.systemMessages = [];\n\n for (const message of messages) {\n if (message.role !== 'system') continue;\n this.systemMessages.push(message);\n }\n\n return this;\n }\n\n public addSystem(\n messages:\n | CoreMessageV4\n | CoreMessageV4[]\n | AIV6Type.ModelMessage\n | AIV6Type.ModelMessage[]\n | AIV5Type.ModelMessage\n | AIV5Type.ModelMessage[]\n | MastraDBMessage\n | MastraDBMessage[]\n | string\n | string[]\n | null,\n tag?: string,\n ) {\n if (!messages) return this;\n for (const message of Array.isArray(messages) ? messages : [messages]) {\n this.addOneSystem(message, tag);\n }\n return this;\n }\n\n private addOneSystem(\n message: CoreMessageV4 | AIV6Type.ModelMessage | AIV5Type.ModelMessage | MastraDBMessage | string,\n tag?: string,\n ) {\n const coreMessage = systemMessageToAIV4Core(message);\n\n if (coreMessage.role !== `system`) {\n throw new Error(\n `Expected role \"system\" but saw ${coreMessage.role} for message ${JSON.stringify(coreMessage, null, 2)}`,\n );\n }\n\n if (tag && !this.isDuplicateSystem(coreMessage, tag)) {\n this.taggedSystemMessages[tag] ||= [];\n this.taggedSystemMessages[tag].push(coreMessage);\n this.recordMutation({\n type: 'addSystem',\n tag,\n message: coreMessage,\n });\n } else if (!tag && !this.isDuplicateSystem(coreMessage)) {\n this.systemMessages.push(coreMessage);\n this.recordMutation({\n type: 'addSystem',\n message: coreMessage,\n });\n }\n }\n\n private isDuplicateSystem(message: CoreMessageV4, tag?: string) {\n if (tag) {\n if (!this.taggedSystemMessages[tag]) return false;\n return this.taggedSystemMessages[tag].some(\n m =>\n CacheKeyGenerator.fromAIV4CoreMessageContent(m.content) ===\n CacheKeyGenerator.fromAIV4CoreMessageContent(message.content),\n );\n }\n return this.systemMessages.some(\n m =>\n CacheKeyGenerator.fromAIV4CoreMessageContent(m.content) ===\n CacheKeyGenerator.fromAIV4CoreMessageContent(message.content),\n );\n }\n\n private getMessageIndex() {\n const index = this.messageIndex;\n if (index && index.messages === this.messages && index.length === this.messages.length) return index;\n\n const byId = new Map<string, MastraDBMessage[]>();\n for (const message of this.messages) {\n const withId = byId.get(message.id);\n if (withId) withId.push(message);\n else byId.set(message.id, [message]);\n }\n this.messageIndex = { messages: this.messages, length: this.messages.length, byId, sorted: false };\n return this.messageIndex;\n }\n\n private getMessagesWithId(id: string): readonly MastraDBMessage[] {\n return this.getMessageIndex().byId.get(id) ?? [];\n }\n\n private getMessageById(id: string) {\n return this.getMessagesWithId(id)[0];\n }\n\n private appendMessage(message: MastraDBMessage) {\n const index = this.getMessageIndex();\n const previous = this.messages.at(-1);\n this.messages.push(message);\n index.length = this.messages.length;\n index.sorted &&= !previous || previous.createdAt.getTime() <= message.createdAt.getTime();\n const withId = index.byId.get(message.id);\n if (withId) withId.push(message);\n else index.byId.set(message.id, [message]);\n }\n\n private replaceMessageAt(position: number, message: MastraDBMessage) {\n const index = this.getMessageIndex();\n const previous = this.messages[position]!;\n this.messages[position] = message;\n index.sorted = false;\n\n const previousWithId = index.byId.get(previous.id)?.filter(m => m !== previous) ?? [];\n if (previousWithId.length) index.byId.set(previous.id, previousWithId);\n else index.byId.delete(previous.id);\n const withId = index.byId.get(message.id);\n if (withId) withId.push(message);\n else index.byId.set(message.id, [message]);\n }\n\n // make sure messages are always stored in order of when they were created!\n private sortMessages() {\n this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n this.getMessageIndex().sorted = true;\n }\n\n private shouldReplaceMessage(message: MastraDBMessage): { exists: boolean; shouldReplace?: boolean; id?: string } {\n if (!this.messages.length) return { exists: false };\n\n if (!(`id` in message) || !message?.id) {\n return { exists: false };\n }\n\n const existingMessage = this.getMessageById(message.id);\n if (!existingMessage) return { exists: false };\n\n return {\n exists: true,\n shouldReplace: !messagesAreEqual(existingMessage, message),\n id: existingMessage.id,\n };\n }\n\n private addOne(message: MessageInput, messageSource: MessageSource, options: MessageListAddOptions = {}) {\n if (\n (!(`content` in message) ||\n (!message.content &&\n // allow empty strings\n typeof message.content !== 'string')) &&\n (!(`parts` in message) || !message.parts)\n ) {\n throw new MastraError({\n id: 'INVALID_MESSAGE_CONTENT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `Message with role \"${message.role}\" must have either a 'content' property (string or array) or a 'parts' property (array) that is not empty, null, or undefined. Received message: ${JSON.stringify(message, null, 2)}`,\n details: {\n role: message.role as string,\n messageSource,\n hasContent: 'content' in message,\n hasParts: 'parts' in message,\n },\n });\n }\n\n if (message.role === `system`) {\n // In the past system messages were accidentally stored in the db. these should be ignored because memory is not supposed to store system messages.\n if (messageSource === `memory`) return null;\n\n // Check if the message is in a supported format for system messages\n const isSupportedSystemFormat =\n TypeDetector.isAIV4CoreMessage(message) ||\n TypeDetector.isAIV6CoreMessage(message) ||\n TypeDetector.isAIV5CoreMessage(message) ||\n TypeDetector.isMastraDBMessage(message);\n\n if (isSupportedSystemFormat) {\n return this.addSystem(message);\n }\n\n // if we didn't add the message and we didn't ignore this intentionally, then it's a problem!\n throw new MastraError({\n id: 'INVALID_SYSTEM_MESSAGE_FORMAT',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n text: `Invalid system message format. System messages must be CoreMessage format with 'role' and 'content' properties. The content should be a string or valid content array.`,\n details: {\n messageSource,\n receivedMessage: JSON.stringify(message, null, 2),\n },\n });\n }\n\n const messageV2 = convertInputToMastraDBMessage(message, messageSource, this.createAdapterContext());\n const signalMetadata =\n messageV2.role === 'signal'\n ? (messageV2.content.metadata?.signal as { acceptedAt?: string; createdAt?: string } | undefined)\n : undefined;\n if (messageSource === 'input' && messageV2.role === 'signal' && !signalMetadata?.acceptedAt) {\n const acceptedAt = signalMetadata?.createdAt ?? messageV2.createdAt.toISOString();\n messageV2.createdAt = this.generateCreatedAt(messageSource, messageV2.createdAt);\n messageV2.content.metadata = {\n ...messageV2.content.metadata,\n signal: {\n ...signalMetadata,\n createdAt: messageV2.createdAt.toISOString(),\n acceptedAt,\n },\n };\n }\n\n const { exists, shouldReplace, id } = this.shouldReplaceMessage(messageV2);\n\n const latestMessage = this.messages.at(-1);\n const latestMessageIsAfterSealedBoundary = !latestMessage || !MessageMerger.isSealed(latestMessage);\n\n const replacementTarget = exists && id ? this.getMessageById(id) : undefined;\n\n // Stored history loads as the base layer, underneath whatever this run already holds.\n // When a stored row shares an id with a live message (client input, or a response part\n // such as a tool result), the stored copy must not replace it wholesale - that would drop\n // the client-supplied content from the prompt. Fold the stored copy into the live one and\n // keep the live message's source so it stays visible to output processing. A client-sent\n // assistant message contributes only tool outcomes for calls the stored copy has pending.\n const replacementTargetSource: MessageSource | undefined = !replacementTarget\n ? undefined\n : this.stateManager.isUserMessage(replacementTarget)\n ? 'input'\n : this.stateManager.isResponseMessage(replacementTarget)\n ? 'response'\n : this.stateManager.isContextMessage(replacementTarget)\n ? 'context'\n : undefined;\n\n if (\n messageSource === 'memory' &&\n replacementTarget &&\n replacementTargetSource &&\n !MessageMerger.isSealed(messageV2)\n ) {\n const replacementIndex = this.messages.indexOf(replacementTarget);\n if (replacementTargetSource === 'input') {\n MessageMerger.merge(messageV2, clientToolOutcomes(messageV2, replacementTarget));\n } else if (messageV2.role === 'user' && replacementTarget.role === 'user') {\n messageV2.content = {\n ...messageV2.content,\n ...replacementTarget.content,\n metadata: {\n ...(messageV2.content.metadata ?? {}),\n ...(replacementTarget.content.metadata ?? {}),\n },\n };\n } else {\n for (const incomingPart of replacementTarget.content.parts) {\n if (incomingPart.type !== 'text') continue;\n const storedPart = messageV2.content.parts.find(\n part => part.type === 'text' && part.text.trim() === incomingPart.text.trim(),\n );\n if (storedPart?.type === 'text') storedPart.text = incomingPart.text;\n }\n MessageMerger.merge(messageV2, withoutStaleToolStates(messageV2, replacementTarget));\n }\n this.stateManager.removeMessage(replacementTarget);\n this.replaceMessageAt(replacementIndex, messageV2);\n this.pushMessageToSource(messageV2, 'memory');\n this.pushMessageToSource(messageV2, replacementTargetSource);\n this.updateLastCreatedAt(messageV2);\n this.sortMessages();\n return this;\n }\n\n if (messageSource === `memory`) {\n // messagesAreEqual only matches stored messages that share the incoming id\n for (const existingMessage of this.getMessagesWithId(messageV2.id)) {\n // don't double store any messages. Memory cleans messages when it saves them\n // (trimmed text, working memory removed), so a stored copy can differ from the live\n // message only by that cleanup. Treating it as new content would re-add a sealed\n // message under a new id with the same provider item ids (#29380).\n if (messagesAreEqual(existingMessage, messageV2) || isPersistedCopy(existingMessage, messageV2)) {\n return;\n }\n }\n }\n\n const hasSealedReplacementTarget = !!replacementTarget && MessageMerger.isSealed(replacementTarget);\n\n // Keep this replacement-target guard here instead of MessageMerger.shouldMerge().\n // shouldMerge() only decides whether to append to the latest assistant message,\n // but replace-by-id can target an older sealed message elsewhere in the list.\n // An incoming message whose id belongs to an earlier message must update that message\n // in place; merging it into the latest one would re-save earlier turns' parts.\n const replacesEarlierMessage = !!replacementTarget && replacementTarget !== latestMessage;\n const isLatestFromMemory = latestMessage ? this.memoryMessages.has(latestMessage) : false;\n const shouldMerge =\n options.merge !== false &&\n latestMessageIsAfterSealedBoundary &&\n !hasSealedReplacementTarget &&\n !replacesEarlierMessage &&\n MessageMerger.shouldMerge(latestMessage, messageV2, messageSource, isLatestFromMemory, this._agentNetworkAppend);\n\n if (shouldMerge && latestMessage) {\n // Delegate merge logic to MessageMerger\n MessageMerger.merge(latestMessage, messageV2);\n this.updateLastCreatedAt(latestMessage);\n\n // If latest message gets appended to, it should be added to the proper source\n this.pushMessageToSource(latestMessage, messageSource);\n }\n // Else the last message and this message are not both assistant messages OR an existing message has been updated and should be replaced. add a new message to the array or update an existing one.\n else {\n let existingIndex = -1;\n if (shouldReplace) {\n existingIndex = this.messages.findIndex(m => m.id === id);\n }\n const existingMessage = existingIndex !== -1 && this.messages[existingIndex];\n\n if (shouldReplace && existingMessage) {\n // Scan on demand rather than caching: observational memory seals messages in place.\n const latestSealedIndex = this.messages.findLastIndex(message => MessageMerger.isSealed(message));\n const existingIsAtOrBeforeSealedBoundary = latestSealedIndex !== -1 && existingIndex <= latestSealedIndex;\n\n // If the existing message is sealed (e.g., after observation), don't replace it.\n // Instead, generate a new ID for the incoming message and add it as a new message.\n if (MessageMerger.isSealed(existingMessage)) {\n // Find the last part with sealedAt metadata in the EXISTING message.\n // The existing message has the seal boundary marker from insertObservationMarker.\n const existingParts = existingMessage.content?.parts || [];\n let sealedPartCount = 0;\n\n for (let i = existingParts.length - 1; i >= 0; i--) {\n const part = existingParts[i] as { metadata?: { mastra?: { sealedAt?: number } } };\n if (part?.metadata?.mastra?.sealedAt) {\n // The seal is at index i, so sealed content is parts 0 through i (inclusive)\n sealedPartCount = i + 1;\n break;\n }\n }\n\n // If no sealedAt found, use the entire existing message length as the boundary\n if (sealedPartCount === 0) {\n sealedPartCount = existingParts.length;\n }\n\n // Get parts from incoming message that are beyond the sealed boundary\n const incomingParts = messageV2.content.parts;\n\n let newParts: typeof incomingParts;\n\n if (incomingParts.length <= sealedPartCount) {\n // Incoming message has fewer or equal parts than the sealed boundary.\n // Check if these are truly stale (same content as the sealed message) or\n // new content flushed independently (e.g., text deltas flushed with the\n // same messageId but only containing a text part).\n if (messagesAreEqual(existingMessage, messageV2)) {\n // Stale message, ignore - don't replace, don't create new\n return this;\n }\n // Not stale — these are fresh parts (e.g., a text flush). Treat all as new.\n newParts = incomingParts;\n } else {\n newParts = incomingParts.slice(sealedPartCount);\n }\n\n // Only create a new message if there are actually new parts\n if (newParts.length > 0) {\n // Generate a new ID for the incoming message\n messageV2.id = this.generateMessageId?.({ idType: 'message', source: 'memory' }) ?? randomUUID();\n // Replace the parts with only the new ones\n messageV2.content.parts = newParts;\n // Ensure the new message has a timestamp after the sealed message\n if (messageV2.createdAt <= existingMessage.createdAt) {\n messageV2.createdAt = new Date(existingMessage.createdAt.getTime() + 1);\n }\n this.appendMessage(messageV2);\n }\n // If no new parts, don't add anything (the sealed message already has all the content)\n } else if (existingIsAtOrBeforeSealedBoundary) {\n messageV2.id = this.generateMessageId?.({ idType: 'message', source: 'memory' }) ?? randomUUID();\n if (messageV2.createdAt <= existingMessage.createdAt) {\n messageV2.createdAt = new Date(existingMessage.createdAt.getTime() + 1);\n }\n this.appendMessage(messageV2);\n } else {\n const isExistingFromMemory = this.memoryMessages.has(existingMessage);\n const shouldMergeIntoExisting =\n options.merge !== false &&\n MessageMerger.shouldMerge(\n existingMessage,\n messageV2,\n messageSource,\n isExistingFromMemory,\n this._agentNetworkAppend,\n );\n if (shouldMergeIntoExisting) {\n MessageMerger.merge(existingMessage, messageV2);\n this.updateLastCreatedAt(existingMessage);\n this.pushMessageToSource(existingMessage, messageSource);\n // Sort messages and return early — existingMessage stays in messages[] and its Sets\n this.sortMessages();\n return this;\n }\n // The replaced object must not linger in its old source set, otherwise a\n // client-echoed input message replaced by its stored copy would be re-persisted.\n this.stateManager.removeMessage(existingMessage);\n this.replaceMessageAt(existingIndex, messageV2);\n }\n } else if (!exists) {\n this.appendMessage(messageV2);\n }\n\n this.pushMessageToSource(messageV2, messageSource);\n }\n\n // Appending in createdAt order keeps the list sorted, and then the newest message is last,\n // so there's no need to walk and re-sort the whole list after every add.\n if (this.getMessageIndex().sorted) {\n const newestMessage = this.messages.at(-1);\n if (newestMessage) this.updateLastCreatedAt(newestMessage);\n return this;\n }\n\n for (const storedMessage of this.messages) {\n this.updateLastCreatedAt(storedMessage);\n }\n\n this.sortMessages();\n\n return this;\n }\n\n private pushMessageToSource(messageV2: MastraDBMessage, messageSource: MessageSource) {\n this.stateManager.addToSource(messageV2, messageSource);\n }\n\n private lastCreatedAt?: number;\n\n // A run's input can be stamped in the same millisecond as the stored message it follows\n // (the previous turn's answer, saved just before this turn was queued). Sorting on equal\n // timestamps would then put the stored answer last, and this turn's response would merge\n // into it. Stored history sits underneath the live turn, so a live message tied with a stored\n // one moves just past it. Every pass places the live messages again from their own timestamps,\n // in the order those timestamps and their arrival give, so a later history load cannot\n // reorder the turn: each keeps its own time unless that ties a stored message or would no\n // longer follow the live message before it, which was moved. A message that was loaded from\n // memory stays stored even if it is added again under another source, and a signal anchored\n // before a message (precedesMessageId) keeps its place.\n private seenAsStored = new WeakSet<MastraDBMessage>();\n private livePlacement = new WeakMap<MastraDBMessage, { own: number; placed: number; arrival: number }>();\n private liveArrivals = 0;\n\n private moveLiveMessagesPastStoredTies(): void {\n const memory = this.memoryMessages;\n if (!memory.size) return;\n for (const message of memory) this.seenAsStored.add(message);\n const live = this.messages.filter(message => !this.seenAsStored.has(message) && !this.isAnchoredSignal(message));\n if (!live.length) return;\n\n const storedTimes = new Set<number>();\n for (const message of memory) storedTimes.add(message.createdAt.getTime());\n\n const placements = live.map(message => {\n const time = message.createdAt.getTime();\n let placement = this.livePlacement.get(message);\n // A timestamp someone else set since the last pass is the message's own again.\n if (!placement || placement.placed !== time) {\n placement = { own: time, placed: time, arrival: placement?.arrival ?? this.liveArrivals++ };\n this.livePlacement.set(message, placement);\n }\n return { message, placement };\n });\n placements.sort((a, b) => a.placement.own - b.placement.own || a.placement.arrival - b.placement.arrival);\n\n let moved = false;\n let previous: { time: number; moved: boolean } | undefined;\n for (const { message, placement } of placements) {\n let time = placement.own;\n if (previous?.moved && time <= previous.time) time = previous.time + 1;\n while (storedTimes.has(time)) time++;\n previous = { time, moved: time !== placement.own };\n placement.placed = time;\n if (time === message.createdAt.getTime()) continue;\n\n const before = message.createdAt.toISOString();\n message.createdAt = new Date(time);\n const signal = message.content.metadata?.signal as { createdAt?: string } | undefined;\n if (signal?.createdAt === before) signal.createdAt = message.createdAt.toISOString();\n this.updateLastCreatedAt(message);\n // A message already saved under its old time must be saved again under the new one.\n if (this.newResponseMessagesPersisted.has(message)) this.newResponseMessages.add(message);\n else if (this.newUserMessagesPersisted.has(message)) this.newUserMessages.add(message);\n moved = true;\n }\n if (moved) this.sortMessages();\n }\n\n // A signal placed just before the message it names (addSignal's precedesMessageId) keeps that place.\n private isAnchoredSignal(message: MastraDBMessage): boolean {\n const signal = message.content.metadata?.signal as { metadata?: { precedesMessageId?: unknown } } | undefined;\n const precedes = signal?.metadata?.precedesMessageId;\n return typeof precedes === 'string' && this.getMessageById(precedes) !== undefined;\n }\n\n private updateLastCreatedAt(message: MastraDBMessage): void {\n // Message-level createdAt controls transcript ordering and OM observation boundaries.\n // Part timestamps are event metadata within a message and must not advance the\n // ordering watermark used to timestamp later messages/signals.\n this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, message.createdAt.getTime());\n }\n\n // this makes sure messages added in order will always have a date atleast 1ms apart.\n private generateCreatedAt(messageSource: MessageSource, start?: unknown): Date {\n // Normalize timestamp\n const startDate: Date | undefined =\n start instanceof Date\n ? start\n : typeof start === 'string' || typeof start === 'number'\n ? new Date(start)\n : undefined;\n\n if (startDate && !this.lastCreatedAt) {\n this.lastCreatedAt = startDate.getTime();\n return startDate;\n }\n\n if (startDate && messageSource === `memory`) {\n // Preserve user-provided timestamps for memory messages to avoid re-ordering\n // Messages without timestamps will fall through to get generated incrementing timestamps\n return startDate;\n }\n\n const now = new Date();\n const nowTime = startDate?.getTime() || now.getTime();\n const lastTime = this.lastCreatedAt || 0;\n\n // make sure our new message is created later than the latest known ordering timestamp\n // it's expected that messages are added to the list in order if they don't have a createdAt date on them\n if (nowTime <= lastTime) {\n const newDate = new Date(lastTime + 1);\n this.lastCreatedAt = newDate.getTime();\n return newDate;\n }\n\n this.lastCreatedAt = nowTime;\n return startDate ?? now;\n }\n\n private newMessageId(role?: string): string {\n if (this.generateMessageId) {\n return this.generateMessageId({\n idType: 'message',\n source: 'agent',\n threadId: this.memoryInfo?.threadId,\n resourceId: this.memoryInfo?.resourceId,\n role,\n });\n }\n return randomUUID();\n }\n\n private createAdapterContext() {\n return {\n memoryInfo: this.memoryInfo,\n newMessageId: () => this.newMessageId(),\n generateCreatedAt: (messageSource: MessageSource, start?: unknown) =>\n this.generateCreatedAt(messageSource, start),\n dbMessages: this.messages,\n };\n }\n}\n","import type * as AIV4 from '@internal/ai-sdk-v4';\nimport type * as AIV5 from '@internal/ai-sdk-v5';\nimport type * as AIV6 from '@internal/ai-v6';\n\nimport type { MastraDBMessage, UIMessageWithMetadata, MessageListInput } from '../index';\n\nimport { MessageList } from '../index';\n\n/**\n * Available output formats for message conversion.\n *\n * @remarks\n * - `Mastra.V2` - Current database storage format, compatible with AI SDK v4\n * - `AIV4.UI` - AI SDK v4 UIMessage format (for frontend components)\n * - `AIV4.Core` - AI SDK v4 CoreMessage format (for LLM API calls)\n * - `AIV5.UI` - AI SDK v5 UIMessage format (for frontend components)\n * - `AIV5.Model` - AI SDK v5 ModelMessage format (for LLM API calls)\n * - `AIV6.UI` - AI SDK v6 UIMessage format (for frontend components)\n */\nexport type OutputFormat = 'Mastra.V2' | 'AIV4.UI' | 'AIV4.Core' | 'AIV5.UI' | 'AIV5.Model' | 'AIV6.UI';\n\nclass MessageConverter {\n private messageList: MessageList;\n\n constructor(messages: MessageListInput) {\n this.messageList = new MessageList();\n // Use 'memory' source to preserve messages exactly as provided\n // without any transformations or combinations\n this.messageList.add(messages, 'memory');\n }\n\n /**\n * Convert messages to Mastra V2 format (current database format).\n * @param format - The format 'Mastra.V2'\n * @returns Array of messages in Mastra V2 format, used for database storage\n */\n to(format: 'Mastra.V2'): MastraDBMessage[];\n /**\n * Convert messages to AI SDK v4 UIMessage format.\n * @param format - The format 'AIV4.UI'\n * @returns Array of UIMessages for use with AI SDK v4 frontend components\n */\n to(format: 'AIV4.UI'): UIMessageWithMetadata[] | AIV4.UIMessage[];\n /**\n * Convert messages to AI SDK v4 CoreMessage format.\n * @param format - The format 'AIV4.Core'\n * @returns Array of CoreMessages for AI SDK v4 LLM API calls\n */\n to(format: 'AIV4.Core'): AIV4.CoreMessage[];\n /**\n * Convert messages to AI SDK v5 UIMessage format.\n * @param format - The format 'AIV5.UI'\n * @returns Array of UIMessages for use with AI SDK v5 frontend components\n */\n to(format: 'AIV5.UI'): AIV5.UIMessage[];\n /**\n * Convert messages to AI SDK v5 ModelMessage format.\n * @param format - The format 'AIV5.Model'\n * @returns Array of ModelMessages for AI SDK v5 LLM API calls\n */\n to(format: 'AIV5.Model'): AIV5.ModelMessage[];\n /**\n * Convert messages to AI SDK v6 UIMessage format.\n * @param format - The format 'AIV6.UI'\n * @returns Array of UIMessages for use with AI SDK v6 frontend components\n */\n to(format: 'AIV6.UI'): AIV6.UIMessage[];\n to(format: OutputFormat): unknown[] {\n switch (format) {\n // Old format keys (backward compatibility)\n case 'Mastra.V2':\n return this.messageList.get.all.db();\n case 'AIV4.UI':\n return this.messageList.get.all.aiV4.ui();\n case 'AIV4.Core':\n return this.messageList.get.all.aiV4.core();\n case 'AIV5.UI':\n return this.messageList.get.all.aiV5.ui();\n case 'AIV5.Model':\n return this.messageList.get.all.aiV5.model();\n case 'AIV6.UI':\n return this.messageList.get.all.aiV6.ui();\n default:\n throw new Error(`Unsupported output format: ${format}`);\n }\n }\n}\n\n/**\n * Convert messages from any supported format to another format.\n *\n * @param messages - Input messages in any supported format. Accepts:\n * - AI SDK v4 formats: UIMessage, CoreMessage, Message\n * - AI SDK v5 formats: UIMessage, ModelMessage\n * - Mastra formats: MastraMessageV1 (input only), MastraDBMessage\n * - Simple strings (will be converted to user messages)\n * - Arrays of any of the above\n *\n * @returns A converter object with a `.to()` method to specify the output format\n *\n * @example\n * ```typescript\n * import { convertMessages } from '@mastra/core/agent';\n *\n * // Convert AI SDK v5 UI messages to v4 Core messages\n * const v4CoreMessages = convertMessages(v5UIMessages).to('AIV4.Core');\n *\n * // Convert database messages (Mastra V2) to AI SDK v5 UI messages for frontend\n * const v5UIMessages = convertMessages(dbMessages).to('AIV5.UI');\n *\n * // Convert any format to Mastra's V2 format for database storage\n * const mastraV2Messages = convertMessages(anyMessages).to('Mastra.V2');\n *\n * // Convert simple strings to formatted messages\n * const messages = convertMessages(['Hello', 'How are you?']).to('AIV5.UI');\n *\n * // Convert v4 UI messages to v5 Model messages for LLM calls\n * const modelMessages = convertMessages(v4UIMessages).to('AIV5.Model');\n * ```\n *\n * @remarks\n * This utility handles all message format conversions internally, including:\n * - Tool invocations and results\n * - File attachments\n * - Multi-part messages\n * - System messages\n * - Metadata preservation where possible\n */\nexport function convertMessages(messages: MessageListInput): MessageConverter {\n return new MessageConverter(messages);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA,MAAM,2CAA2B,IAAI,IAAI;CAAC;CAAQ;CAAQ;CAAc;CAAc;AAAS,CAAC;;AAGhG,SAAgB,uBAAuB,QAA0B;CAC/D,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU,OAAO;CAE1D,MAAM,OAAO,OAAO,KAAK,MAAM;CAC/B,OAAO,KAAK,WAAW,KAAK,KAAK,OAAO,UAAW,OAA8B,QAAQ;AAC3F;;AAGA,SAAgB,oBACd,QACA,EAAE,gBAAgB,SAAsC,CAAC,GAClB;CACvC,IAAI,WAAW,QAAQ,OAAO,WAAW,UAAU,OAAO;EAAE,SAAS;EAAO;CAAO;CAEnF,MAAM,SAAS;CACf,MAAM,OAAO,OAAO,KAAK,MAAM;CAC/B,IACE,KAAK,WAAW,KAChB,KAAK,SAAS,MAAM,KACpB,KAAK,SAAS,OAAO,KACrB,OAAO,OAAO,SAAS,YACvB,yBAAyB,IAAI,OAAO,IAAI,GAExC,OAAO;EACL,SAAS,OAAO,SAAS,gBAAgB,OAAO,SAAS;EACzD,QAAQ,OAAO,SAAS,aAAa,CAAC,gBAAgB,SAAS,OAAO;CACxE;CAGF,OAAO;EAAE,SAAS;EAAO,QAAQ,uBAAuB,MAAM;CAAE;AAClE;;;;;;;;;;;;;ACAA,IAAa,eAAb,MAAa,aAAa;;;;CAIxB,OAAO,kBAAkB,KAA2C;EAClE,OAAO,QACL,aAAa,OACb,IAAI,WACJ,CAAC,MAAM,QAAQ,IAAI,OAAO,KAC1B,OAAO,IAAI,YAAY,YACvB,YAAY,IAAI,WAChB,IAAI,QAAQ,WAAW,CACzB;CACF;;;;CAKA,OAAO,kBAAkB,KAA2C;EAClE,OAAO,CAAC,aAAa,kBAAkB,GAAG,MAAM,cAAc,OAAO,gBAAgB;CACvF;;;;CAKA,OAAO,gBAAgB,KAA6D;EAClF,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GAC/B,MAAM,UAAU,IAAI,YAAY,KAAK,eAAe;GACpD,QAAQ,gBAAgB,IAAI,KAAK,KAAK;GACtC,OAAO;EACR;EACA,KAAK,eAAe,QAAQ;GAC3B,MAAM,UAAU,IAAI,YAAY,KAAK,eAAe;GACpD,QAAQ,gBAAgB,OAAO,GAAG;GAClC,OAAO;EACR;CACD;AACD,EAAE;;;;AAIF,MAAM,uBAAuB;CAC5B,SAAS;CACT,QAAQ;CACR,YAAY;AACb;;;;;;AAOA,IAAI,mBAAmB,MAAM;CAC5B,YAAY,cAAc,sBAAsB;EAC/C,KAAK,eAAe;CACrB;CACA,cAAc;EACb,OAAO,KAAK;CACb;CACA,aAAa,MAAM,QAAQ;EAC1B,OAAO;CACR;CACA,cAAc,aAAa;EAC1B,OAAO;CACR;CACA,SAAS,OAAO,aAAa;EAC5B,OAAO;CACR;CACA,QAAQ,OAAO;EACd,OAAO;CACR;CACA,SAAS,QAAQ;EAChB,OAAO;CACR;CACA,UAAU,SAAS;EAClB,OAAO;CACR;CACA,WAAW,OAAO;EACjB,OAAO;CACR;CACA,IAAI,UAAU,CAAC;CACf,cAAc;EACb,OAAO;CACR;CACA,gBAAgB,YAAY,OAAO,CAAC;AACrC;AAEA,MAAM,QAAQ,IAAI,WAAW;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA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