{"version":3,"file":"message-list-BM7m-E-v.cjs","names":["convertDataContentToBase64String","partAny","getDisplayTransform","getTransformedToolPayload","hasTransformedToolPayload","filterEmptyTextParts","getSignalType","getSignalTagName","isUserSignalType","toSignalDataPart","MastraError","ErrorDomain","ErrorCategory","convertDataContentToBase64String","AISDKError","getErrorMessage","gateway","imageMediaTypeSignatures","convertBase64ToUint8Array","stripID3","detectMediaType","fetchWithValidatedRedirects","withUserAgentSuffix","getRuntimeEnvironmentUserAgent","cancelResponseBody","DownloadError","readResponseWithSizeLimit","DEFAULT_MAX_DOWNLOAD_SIZE","z","convertUint8ArrayToBase64","isUrlSupported","asSchema","InvalidPromptError","safeValidateTypes","GatewayAuthenticationError","APICallError","retryWithExponentialBackoff","GatewayError","executeTool","safeParseJSON","resolve","TypeValidationError","createIdGenerator","getErrorMessage$1","lazySchema","zodSchema","validateTypes","DelayedPromise","isAbortError","UnsupportedFunctionalityError","getDisplayTransform","getTransformedToolPayload","hasTransformedToolPayload","MastraError","ErrorDomain","ErrorCategory","getTransformedToolPayload","hasTransformedToolPayload","AIV6.isToolUIPart","convertDataContentToBase64String","convertToCoreMessagesV4","deepEqual","DefaultGeneratedFileWithType","convertDataContentToBase64String","convertToDataContent","fetchWithRetry","MastraError","ErrorDomain","ErrorCategory","createSignal","isCreatedAgentSignal","mastraDBMessageToSignal","convertInputToMastraDBMessage","convertAIV5UIToModelMessages","convertAIV4CoreToAIV5ModelMessages","getTransformedToolPayload","hasTransformedToolPayload","MastraError","ErrorDomain","ErrorCategory"],"sources":["../src/agent/message-list/detection/TypeDetector.ts","../src/agent/message-list/prompt/image-utils.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/utils/tool-name.ts","../src/agent/message-list/adapters/AIV5Adapter.ts","../src/agent/message-list/adapters/AIV6Adapter.ts","../src/agent/message-list/cache/stable-stringify.ts","../src/agent/message-list/cache/CacheKeyGenerator.ts","../src/agent/message-list/conversion/to-prompt.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/stream/aisdk/v5/compat/media.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/state/serialization.ts","../src/agent/message-list/state/MessageStateManager.ts","../src/agent/message-list/message-list.ts","../src/agent/message-list/utils/convert-messages.ts"],"sourcesContent":["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, CoreMessageV4 } from '../types';\n\n/**\n * Type representing all possible message input formats\n */\nexport type MessageInput =\n  | AIV7Type.UIMessage\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 or tool states.\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(\n        msg as CoreMessageV4 | AIV5Type.ModelMessage | AIV6Type.ModelMessage | AIV7Type.ModelMessage | AIV4Message,\n      )\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: AIV7Type.UIMessage | AIV6Type.UIMessage | AIV5Type.UIMessage | UIMessageV4 | 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      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: AIV7Type.UIMessage | AIV6Type.UIMessage | AIV5Type.UIMessage | UIMessageV4 | 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 || typeof msg.content === 'string') return false;\n\n    return msg.content.some(part => part.type === 'tool-approval-request' || part.type === 'tool-approval-response');\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 content is identical in v4/v5/v6, so treat it as v5-compatible.\n    if (typeof msg.content === 'string') return true;\n\n    for (const part of msg.content) {\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","import { convertDataContentToBase64String } from './data-content';\n\n/**\n * Image content can be a string (URL or data URI), a URL object, or binary data\n */\nexport type ImageContent = string | URL | Uint8Array | ArrayBuffer | Buffer;\n\n/**\n * Represents the parsed components of a data URI\n */\nexport interface DataUriParts {\n  mimeType?: string;\n  base64Content: string;\n  isDataUri: boolean;\n}\n\n/**\n * Parses a data URI string into its components.\n * Format: data:[<mediatype>][;base64],<data>\n *\n * @param dataUri - The data URI string to parse\n * @returns Parsed components including MIME type and base64 content\n */\nexport function parseDataUri(dataUri: string): DataUriParts {\n  if (!dataUri.startsWith('data:')) {\n    return {\n      isDataUri: false,\n      base64Content: dataUri,\n    };\n  }\n\n  const base64Index = dataUri.indexOf(',');\n  if (base64Index === -1) {\n    // Malformed data URI, return as-is\n    return {\n      isDataUri: true,\n      base64Content: dataUri,\n    };\n  }\n\n  const header = dataUri.substring(5, base64Index); // Skip 'data:' prefix\n  const base64Content = dataUri.substring(base64Index + 1);\n\n  // Extract MIME type from header (before ';base64' or ';')\n  const semicolonIndex = header.indexOf(';');\n  const mimeType = semicolonIndex !== -1 ? header.substring(0, semicolonIndex) : header;\n\n  return {\n    isDataUri: true,\n    mimeType: mimeType || undefined,\n    base64Content,\n  };\n}\n\n/**\n * Creates a data URI from base64 content and MIME type.\n *\n * @param base64Content - The base64 encoded content\n * @param mimeType - The MIME type (defaults to 'application/octet-stream')\n * @returns A properly formatted data URI\n */\nexport function createDataUri(base64Content: string, mimeType: string = 'application/octet-stream'): string {\n  // If it's already a data URI, return as-is\n  if (base64Content.startsWith('data:')) {\n    return base64Content;\n  }\n  return `data:${mimeType};base64,${base64Content}`;\n}\n\n/**\n * Converts various image data formats to a string representation.\n * - Strings are returned as-is (could be URLs or data URIs)\n * - URL objects are converted to strings\n * - Binary data (Uint8Array, ArrayBuffer, Buffer) is converted to base64\n *\n * @param image - The image data in various formats\n * @param fallbackMimeType - MIME type to use when creating data URIs from binary data\n * @returns String representation of the image (URL, data URI, or base64)\n */\nexport function imageContentToString(image: ImageContent, fallbackMimeType?: string): string {\n  if (typeof image === 'string') {\n    return image;\n  }\n\n  if (image instanceof URL) {\n    return image.toString();\n  }\n\n  if (image instanceof Uint8Array || image instanceof ArrayBuffer || (globalThis.Buffer && Buffer.isBuffer(image))) {\n    // Convert binary data to base64\n    const base64 = convertDataContentToBase64String(image);\n    // If it's not already a data URI, create one\n    if (fallbackMimeType && !base64.startsWith('data:')) {\n      return `data:${fallbackMimeType};base64,${base64}`;\n    }\n    return base64;\n  }\n\n  // Fallback for unknown types - try to convert to string\n  return String(image);\n}\n\n/**\n * Converts various image data formats to a data URI string.\n *\n * @param image - The image data in various formats\n * @param mimeType - MIME type for the data URI (defaults to 'image/png')\n * @returns Data URI string\n */\nexport function imageContentToDataUri(image: ImageContent, mimeType: string = 'image/png'): string {\n  const imageStr = imageContentToString(image, mimeType);\n\n  // If it's already a data URI, return as-is\n  if (imageStr.startsWith('data:')) {\n    return imageStr;\n  }\n\n  // If it's an HTTP(S) URL, return as-is (can't convert to data URI)\n  if (imageStr.startsWith('http://') || imageStr.startsWith('https://')) {\n    return imageStr;\n  }\n\n  // Otherwise, assume it's base64 and create a data URI\n  return `data:${mimeType};base64,${imageStr}`;\n}\n\n/**\n * Gets a stable cache key component for image content.\n * Used for generating hash keys for caching purposes.\n *\n * @param image - The image data in various formats\n * @returns A string or number suitable for cache key generation\n */\nexport function getImageCacheKey(image: ImageContent): string | number {\n  if (image instanceof URL) {\n    return image.toString();\n  }\n\n  if (typeof image === 'string') {\n    return image.length;\n  }\n\n  if (image instanceof Uint8Array) {\n    return image.byteLength;\n  }\n\n  if (image instanceof ArrayBuffer) {\n    return image.byteLength;\n  }\n\n  return image;\n}\n\n/**\n * Checks if a string is a valid URL (including protocol-relative URLs).\n *\n * @param str - The string to check\n * @returns true if the string is a valid URL\n */\nexport function isValidUrl(str: string): boolean {\n  try {\n    new URL(str);\n    return true;\n  } catch {\n    // Try as protocol-relative URL\n    if (str.startsWith('//')) {\n      try {\n        new URL(`https:${str}`);\n        return true;\n      } catch {\n        return false;\n      }\n    }\n    return false;\n  }\n}\n\n/**\n * Categorizes a string as a URL, data URI, or raw data (base64/other).\n * Also extracts MIME type from data URIs when present.\n *\n * @param data - The string data to categorize\n * @param fallbackMimeType - Optional fallback MIME type\n * @returns Categorized data with type and extracted MIME type\n */\nexport function categorizeFileData(\n  data: string,\n  fallbackMimeType?: string,\n): {\n  type: 'url' | 'dataUri' | 'raw' | 'providerFileId';\n  mimeType?: string;\n  data: string;\n} {\n  // Parse as data URI first to extract MIME type\n  const parsed = parseDataUri(data);\n  const mimeType = parsed.isDataUri && parsed.mimeType ? parsed.mimeType : fallbackMimeType;\n\n  // Check if it's a data URI\n  if (parsed.isDataUri) {\n    return {\n      type: 'dataUri',\n      mimeType,\n      data,\n    };\n  }\n\n  // Check if it's an OpenAI Files API file ID — pass through as-is so\n  // @ai-sdk/openai can forward it as { file_id: \"file-...\" } to the API.\n  // Distinct from 'url': the value is NOT parseable by `new URL()`, so call\n  // sites that construct URLs must handle it explicitly. Collision risk with\n  // raw base64 is negligible (standard base64 has no '-').\n  if (data.startsWith('file-')) {\n    return {\n      type: 'providerFileId',\n      mimeType,\n      data,\n    };\n  }\n\n  // Check if it's a URL\n  if (isValidUrl(data)) {\n    return {\n      type: 'url',\n      mimeType,\n      data,\n    };\n  }\n\n  // Otherwise it's raw data (likely base64 or other string data)\n  return {\n    type: 'raw',\n    mimeType,\n    data,\n  };\n}\n\n/**\n * Resolve a stored file part's media type and payload across the AI SDK v4 and v5 shapes.\n *\n * Stored \"v2\" file parts are typed as the AI SDK v4 UI shape (`mimeType`/`data`), but\n * v5-shaped file parts (`mediaType`/`url`, renamed in the v5 Media Type Standardization)\n * reach the same read sites. Reading only the v4 fields leaves a v5 part with both values\n * `undefined`, which downstream becomes `contentType: undefined` (making `attachmentsToParts`\n * throw) or collapses distinct parts onto a single cache key. Read whichever shape is present.\n *\n * Returns the RAW resolved values (undefined-preserving); call sites that build a\n * `contentType` should apply their own `'application/octet-stream'` fallback. Mirrors #17366.\n */\nexport function resolveFilePartMediaTypeAndData(part: unknown): { mediaType: string | undefined; data: unknown } {\n  // Narrow the boundary: the stored union only describes v4, so widen it here to read\n  // either shape without an `as any` cast.\n  const filePart = part as { mimeType?: string; data?: unknown; mediaType?: string; url?: unknown };\n  return {\n    mediaType: filePart.mimeType ?? filePart.mediaType,\n    data: filePart.data ?? filePart.url,\n  };\n}\n\n/**\n * Classifies a string as a URL, data URI, or raw data.\n *\n * @param data - The string to classify\n * @returns Object with classification and extracted metadata\n */\nexport function classifyFileData(data: string): {\n  type: 'url' | 'dataUri' | 'base64' | 'other';\n  mimeType?: string;\n} {\n  // Check if it's a data URI\n  const parsed = parseDataUri(data);\n  if (parsed.isDataUri) {\n    return {\n      type: 'dataUri',\n      mimeType: parsed.mimeType,\n    };\n  }\n\n  // Check if it's a URL\n  if (isValidUrl(data)) {\n    return { type: 'url' };\n  }\n\n  // Check if it looks like base64 (simple heuristic)\n  if (/^[A-Za-z0-9+/\\-_]+=*$/.test(data) && data.length > 20) {\n    return { type: 'base64' };\n  }\n\n  return { type: 'other' };\n}\n","const RESPONSE_ITEM_ID_PROVIDERS = ['openai', 'azure'] as const;\n\nexport type ResponseItemIdProvider = (typeof RESPONSE_ITEM_ID_PROVIDERS)[number];\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\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 { CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\nimport 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// Gemini Compatibility\n// ============================================================================\n\n/**\n * Ensures message array is compatible with Gemini API requirements.\n *\n * Gemini API requires:\n * 1. The first non-system message must be from the user role\n * 2. Cannot have only system messages - at least one user/assistant is required\n *\n * @param messages - Array of model messages to validate and fix\n * @param logger - Optional logger for warnings\n * @returns Modified messages array that satisfies Gemini requirements\n *\n * @see https://github.com/mastra-ai/mastra/issues/7287 - Tool call ordering\n * @see https://github.com/mastra-ai/mastra/issues/8053 - Single turn validation\n * @see https://github.com/mastra-ai/mastra/issues/13045 - Empty thread support\n */\nexport function ensureGeminiCompatibleMessages<T extends ModelMessage | CoreMessageV4>(\n  messages: T[],\n  logger?: IMastraLogger,\n): T[] {\n  const result = [...messages];\n\n  // Ensure first non-system message is user\n  const firstNonSystemIndex = result.findIndex(m => m.role !== 'system');\n\n  if (firstNonSystemIndex === -1) {\n    // Only system messages or empty — warn and pass through unchanged.\n    // Providers that support system-only prompts (Anthropic, OpenAI) will work natively.\n    // Providers that don't (Gemini) will return their own error.\n    if (result.length > 0) {\n      logger?.warn(\n        'No user or assistant messages in the request. Some providers (e.g. Gemini) require at least one user message to generate a response.',\n      );\n    }\n  } else if (result[firstNonSystemIndex]?.role === 'assistant') {\n    // First non-system is assistant, insert user message before it\n    result.splice(firstNonSystemIndex, 0, {\n      role: 'user',\n      content: '.',\n    } as T);\n  }\n\n  return result;\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 toolInvocation = {\n            ...part.toolInvocation,\n            // v4 has no denied state and AI SDK v4's convertToCoreMessages requires every\n            // tool invocation to carry a result. Downgrade a declined approval to a normal\n            // result whose value is the decline reason so the conversion accepts it.\n            ...(isDeniedApproval ? { state: 'result' as const } : {}),\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                : {}),\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 { $ as NoSuchModelError, A as parseJsonEventStream, B as withUserAgentSuffix, C as isAbortError, D as lazySchema, E as jsonSchema, F as safeParseJSON, G as EmptyResponseBodyError, H as zodSchema, I as safeValidateTypes, J as InvalidResponseDataError, K as InvalidArgumentError$1, M as readResponseWithSizeLimit, N as resolve, P as retryWithExponentialBackoff, Q as NoContentGeneratedError, R as tool, S as getRuntimeEnvironmentUserAgent, T as isUrlSupported, U as AISDKError, W as APICallError, X as LoadAPIKeyError, Y as JSONParseError, Z as LoadSettingError, _ as executeTool, a as cancelResponseBody, at as isJSONObject, b as getErrorMessage$1, c as convertBase64ToUint8Array, d as createIdGenerator, et as TooManyEmbeddingValuesForCallError, g as dynamicTool, h as delay, i as asSchema, it as isJSONArray, k as normalizeHeaders, l as convertUint8ArrayToBase64, n as DelayedPromise, nt as UnsupportedFunctionalityError, q as InvalidPromptError, r as DownloadError, rt as getErrorMessage, t as DEFAULT_MAX_DOWNLOAD_SIZE, tt as TypeValidationError, v as fetchWithValidatedRedirects, w as isNonNullable, y as generateId, z as validateTypes } from \"./dist-BTWHzT8H.js\";\nimport { i as gateway, n as GatewayError, r as createGatewayProvider, t as GatewayAuthenticationError } from \"./dist-3jq9sPhA.js\";\nimport { z } from \"zod/v4\";\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/version.js\nconst VERSION$1 = \"1.9.1\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/internal/semver.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/internal/global-utils.js\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 registerGlobal(type, instance, diag, allowOverride = false) {\n\tvar _a;\n\tconst api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 };\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.9.1\") {\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}\nfunction getGlobal(type) {\n\tvar _a, _b;\n\tconst globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;\n\tif (!globalVersion || !isCompatible(globalVersion)) return;\n\treturn (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/diag/ComponentLogger.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/diag/types.js\n/**\n* Defines the available internal logging levels for the diagnostic logger, the numeric values\n* of the levels are defined to match the original values from the initial LogLevel to avoid\n* compatibility/migration issues for any implementation that assume the numeric ordering.\n*/\nvar DiagLogLevel;\n(function(DiagLogLevel) {\n\t/** Diagnostic Logging level setting to disable all logging (except and forced logs) */\n\tDiagLogLevel[DiagLogLevel[\"NONE\"] = 0] = \"NONE\";\n\t/** Identifies an error scenario */\n\tDiagLogLevel[DiagLogLevel[\"ERROR\"] = 30] = \"ERROR\";\n\t/** Identifies a warning scenario */\n\tDiagLogLevel[DiagLogLevel[\"WARN\"] = 50] = \"WARN\";\n\t/** General informational log message */\n\tDiagLogLevel[DiagLogLevel[\"INFO\"] = 60] = \"INFO\";\n\t/** General debug log message */\n\tDiagLogLevel[DiagLogLevel[\"DEBUG\"] = 70] = \"DEBUG\";\n\t/**\n\t* Detailed trace level logging should only be used for development, should only be set\n\t* in a development environment.\n\t*/\n\tDiagLogLevel[DiagLogLevel[\"VERBOSE\"] = 80] = \"VERBOSE\";\n\t/** Used to set the logging level to include all logging */\n\tDiagLogLevel[DiagLogLevel[\"ALL\"] = 9999] = \"ALL\";\n})(DiagLogLevel || (DiagLogLevel = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/diag/internal/logLevelLogger.js\nfunction createLogLevelDiagLogger(maxLevel, logger) {\n\tif (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;\n\telse if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;\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\", DiagLogLevel.ERROR),\n\t\twarn: _filterFunc(\"warn\", DiagLogLevel.WARN),\n\t\tinfo: _filterFunc(\"info\", DiagLogLevel.INFO),\n\t\tdebug: _filterFunc(\"debug\", DiagLogLevel.DEBUG),\n\t\tverbose: _filterFunc(\"verbose\", DiagLogLevel.VERBOSE)\n\t};\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/api/diag.js\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: DiagLogLevel.INFO }) => {\n\t\t\tvar _a, _b, _c;\n\t\t\tif (logger === self) {\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((_a = err.stack) !== null && _a !== void 0 ? _a : 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((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);\n\t\t\tif (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {\n\t\t\t\tconst stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : \"<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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/context/context.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/context/NoopContextManager.js\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};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/api/context.js\nconst API_NAME$1 = \"context\";\nconst NOOP_CONTEXT_MANAGER = new NoopContextManager();\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/** 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_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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/trace_flags.js\n/**\n* @since 1.0.0\n*/\nvar TraceFlags;\n(function(TraceFlags) {\n\t/** Represents no flag set. */\n\tTraceFlags[TraceFlags[\"NONE\"] = 0] = \"NONE\";\n\t/** Bit to represent whether trace is sampled in trace flags. */\n\tTraceFlags[TraceFlags[\"SAMPLED\"] = 1] = \"SAMPLED\";\n})(TraceFlags || (TraceFlags = {}));\n/**\n* @since 1.0.0\n*/\nconst INVALID_SPAN_CONTEXT = {\n\ttraceId: \"00000000000000000000000000000000\",\n\tspanId: \"0000000000000000\",\n\ttraceFlags: TraceFlags.NONE\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/NonRecordingSpan.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/context-utils.js\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 _a;\n\treturn (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();\n}\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/spancontext-utils.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/NoopTracer.js\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\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 !== 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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracer.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/NoopTracerProvider.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/ProxyTracerProvider.js\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 _a;\n\t\treturn (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);\n\t}\n\tgetDelegate() {\n\t\tvar _a;\n\t\treturn (_a = this._delegate) !== null && _a !== void 0 ? _a : 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 _a;\n\t\treturn (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);\n\t}\n};\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace/status.js\n/**\n* An enumeration of status codes.\n*\n* @since 1.0.0\n*/\nvar SpanStatusCode;\n(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})(SpanStatusCode || (SpanStatusCode = {}));\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/context-api.js\n/**\n* Entrypoint for context API\n* @since 1.0.0\n*/\nconst context = ContextAPI.getInstance();\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/api/trace.js\nconst API_NAME = \"trace\";\n//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@opentelemetry/api/1.9.1/e2e640b4ddcaaa36008bb5e619de6b2e106b2a2441a690dc97bbd19967c1093c/node_modules/@opentelemetry/api/build/esm/trace-api.js\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//#endregion\n//#region ../../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ai/6.0.241/bfbf6151287fdec0e9dd1f301e12f8a983af71105bc958ebbde51541f06e3c61/node_modules/ai/dist/index.mjs\nvar __defProp = Object.defineProperty;\nvar __export = (target, all) => {\n\tfor (var name22 in all) __defProp(target, name22, {\n\t\tget: all[name22],\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_ToolCallRepairError\";\nvar marker15 = `vercel.ai.error.${name15}`;\nvar symbol15 = Symbol.for(marker15);\nvar _a15;\nvar ToolCallRepairError = class extends AISDKError {\n\tconstructor({ cause, originalError, message = `Error repairing tool call: ${getErrorMessage(cause)}` }) {\n\t\tsuper({\n\t\t\tname: name15,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a15] = true;\n\t\tthis.originalError = originalError;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker15);\n\t}\n};\n_a15 = symbol15;\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 name16 = \"AI_UIMessageStreamError\";\nvar marker16 = `vercel.ai.error.${name16}`;\nvar symbol16 = Symbol.for(marker16);\nvar _a16;\nvar UIMessageStreamError = class extends AISDKError {\n\tconstructor({ chunkType, chunkId, message }) {\n\t\tsuper({\n\t\t\tname: name16,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a16] = true;\n\t\tthis.chunkType = chunkType;\n\t\tthis.chunkId = chunkId;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker16);\n\t}\n};\n_a16 = symbol16;\nvar name17 = \"AI_InvalidDataContentError\";\nvar marker17 = `vercel.ai.error.${name17}`;\nvar symbol17 = Symbol.for(marker17);\nvar _a17;\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: name17,\n\t\t\tmessage,\n\t\t\tcause\n\t\t});\n\t\tthis[_a17] = true;\n\t\tthis.content = content;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker17);\n\t}\n};\n_a17 = symbol17;\nvar name18 = \"AI_InvalidMessageRoleError\";\nvar marker18 = `vercel.ai.error.${name18}`;\nvar symbol18 = Symbol.for(marker18);\nvar _a18;\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: name18,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a18] = true;\n\t\tthis.role = role;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker18);\n\t}\n};\n_a18 = symbol18;\nvar name19 = \"AI_MessageConversionError\";\nvar marker19 = `vercel.ai.error.${name19}`;\nvar symbol19 = Symbol.for(marker19);\nvar _a19;\nvar MessageConversionError = class extends AISDKError {\n\tconstructor({ originalMessage, message }) {\n\t\tsuper({\n\t\t\tname: name19,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a19] = true;\n\t\tthis.originalMessage = originalMessage;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker19);\n\t}\n};\n_a19 = symbol19;\nvar name20 = \"AI_RetryError\";\nvar marker20 = `vercel.ai.error.${name20}`;\nvar symbol20 = Symbol.for(marker20);\nvar _a20;\nvar RetryError = class extends AISDKError {\n\tconstructor({ message, reason, errors }) {\n\t\tsuper({\n\t\t\tname: name20,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a20] = 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, marker20);\n\t}\n};\n_a20 = symbol20;\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:\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\tbreak;\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};\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 _a22, _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 = (_a22 = getGlobalProvider()).transcriptionModel) == null ? void 0 : _b.call(_a22, model);\n}\nfunction resolveSpeechModel(model) {\n\tvar _a22, _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 = (_a22 = getGlobalProvider()).speechModel) == null ? void 0 : _b.call(_a22, 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 _a22;\n\treturn (_a22 = globalThis.AI_SDK_DEFAULT_PROVIDER) != null ? _a22 : 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.241\";\nvar download = async ({ url, maxBytes, abortSignal }) => {\n\tvar _a22;\n\tconst urlText = url.toString();\n\ttry {\n\t\tconst response = await fetchWithValidatedRedirects({\n\t\t\turl: urlText,\n\t\t\theaders: withUserAgentSuffix({}, `ai-sdk/${VERSION}`, getRuntimeEnvironmentUserAgent()),\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: (_a22 = response.headers.get(\"content-type\")) != null ? _a22 : 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) => (requestedDownloads) => Promise.all(requestedDownloads.map(async (requestedDownload) => requestedDownload.isUrlSupportedByModel ? null : download2(requestedDownload)));\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.instanceof(Uint8Array),\n\tz.instanceof(ArrayBuffer),\n\tz.custom((value) => {\n\t\tvar _a22, _b;\n\t\treturn (_b = (_a22 = globalThis.Buffer) == null ? void 0 : _a22.isBuffer(value)) != null ? _b : false;\n\t}, { message: \"Must be a Buffer\" })\n]);\nfunction convertToLanguageModelV3DataContent(content) {\n\tif (content instanceof Uint8Array) return {\n\t\tdata: content,\n\t\tmediaType: void 0\n\t};\n\tif (content instanceof ArrayBuffer) return {\n\t\tdata: new Uint8Array(content),\n\t\tmediaType: void 0\n\t};\n\tif (typeof content === \"string\") try {\n\t\tcontent = new URL(content);\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};\n}\nfunction convertDataContentToBase64String(content) {\n\tif (typeof content === \"string\") return content;\n\tif (content instanceof ArrayBuffer) return convertUint8ArrayToBase64(new Uint8Array(content));\n\treturn convertUint8ArrayToBase64(content);\n}\nfunction convertDataContentToUint8Array(content) {\n\tif (content instanceof Uint8Array) return content;\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 (content instanceof ArrayBuffer) return new Uint8Array(content);\n\tthrow new InvalidDataContentError({ content });\n}\nasync function convertToLanguageModelPrompt({ prompt, supportedUrls, download: download2 = createDefaultDownloadFunction() }) {\n\tconst downloadedAssets = await downloadAssets(prompt.messages, download2, supportedUrls);\n\tconst approvalIdToToolCallId = /* @__PURE__ */ new Map();\n\tfor (const message of prompt.messages) if (message.role === \"assistant\" && Array.isArray(message.content)) {\n\t\tfor (const part of message.content) if (part.type === \"tool-approval-request\" && \"approvalId\" in part && \"toolCallId\" in part) approvalIdToToolCallId.set(part.approvalId, part.toolCallId);\n\t}\n\tconst approvedToolCallIds = /* @__PURE__ */ new Set();\n\tfor (const message of prompt.messages) if (message.role === \"tool\") {\n\t\tfor (const part of message.content) if (part.type === \"tool-approval-response\") {\n\t\t\tconst toolCallId = approvalIdToToolCallId.get(part.approvalId);\n\t\t\tif (toolCallId) approvedToolCallIds.add(toolCallId);\n\t\t}\n\t}\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\":\n\t\t\tfor (const id of approvedToolCallIds) toolCallIds.delete(id);\n\t\t\tif (toolCallIds.size > 0) throw new MissingToolResultsError({ toolCallIds: Array.from(toolCallIds) });\n\t\t\tbreak;\n\t}\n\tfor (const id of approvedToolCallIds) toolCallIds.delete(id);\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 _a22;\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: (_a22 = part.mediaType) != null ? _a22 : 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/*\" : void 0\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 _a22;\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 } = 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 = (_a22 = detectMediaType({\n\t\t\t\tdata,\n\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t})) != null ? _a22 : 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\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\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 _a22, _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: (_a22 = downloadedFile.mediaType) != null ? _a22 : \"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(([name22]) => activeTools.includes(name22)) : Object.entries(tools);\n\tconst languageModelTools = [];\n\tfor (const [name22, 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: name22,\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: name22,\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\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});\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 _a22;\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((_a22 = telemetry == null ? void 0 : telemetry.metadata) != null ? _a22 : {}).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(name22, 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: name22, tracer, attributes, fn, endWhenDone = true }) {\n\treturn tracer.startActiveSpan(name22, { 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\tspan.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 _a22;\n\treturn (_a22 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a22 : [];\n}\nfunction bindTelemetryIntegration(integration) {\n\tvar _a22, _b, _c, _d, _e, _f;\n\treturn {\n\t\tonStart: (_a22 = integration.onStart) == null ? void 0 : _a22.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 _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j;\n\treturn {\n\t\tinputTokens: addTokenCounts(usage1.inputTokens, usage2.inputTokens),\n\t\tinputTokenDetails: {\n\t\t\tnoCacheTokens: addTokenCounts((_a22 = usage1.inputTokenDetails) == null ? void 0 : _a22.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};\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 < 60 * 1e3 || ms < exponentialBackoffDelay)) return ms;\n\treturn exponentialBackoffDelay;\n}\nvar retryWithExponentialBackoffRespectingRetryHeaders = ({ maxRetries = 2, initialDelayInMs = 2e3, backoffFactor = 2, abortSignal } = {}) => retryWithExponentialBackoff({\n\tmaxRetries,\n\tinitialDelayInMs,\n\tbackoffFactor,\n\tabortSignal,\n\tshouldRetry: (error) => error instanceof Error && (APICallError.isInstance(error) && error.isRetryable === true || GatewayError.isInstance(error) && error.isRetryable === true),\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 }) {\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})\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 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\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 _a22, _b;\n\treturn (_b = (_a22 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a22.now()) != null ? _b : Date.now();\n}\nasync function executeToolCall({ toolCall, tools, tracer, telemetry, messages, abortSignal, experimental_context, stepNumber, model, onPreliminaryToolResult, onToolCallStart, onToolCallFinish }) {\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\"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(([name22]) => activeTools.includes(name22)));\n}\nvar DefaultGeneratedFile = class {\n\tconstructor({ data, mediaType }) {\n\t\tconst isUint8Array = data instanceof Uint8Array;\n\t\tthis.base64Data = isUint8Array ? void 0 : data;\n\t\tthis.uint8ArrayData = isUint8Array ? data : void 0;\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(options) {\n\t\tsuper(options);\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}\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}\nasync function validateApprovedToolApprovals({ approvedToolApprovals, tools, messages, experimental_context, toolApprovalSecret }) {\n\tvar _a22;\n\tconst approved = [];\n\tconst denied = [];\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 validation = await safeValidateTypes({\n\t\t\t\tvalue: toolCall.input,\n\t\t\t\tschema: asSchema(tool2.inputSchema)\n\t\t\t});\n\t\t\tif (!validation.success) throw new InvalidToolInputError({\n\t\t\t\ttoolName: toolCall.toolName,\n\t\t\t\ttoolInput: JSON.stringify(toolCall.input),\n\t\t\t\tcause: validation.error\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: (_a22 = approval.approvalResponse.reason) != null ? _a22 : `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};\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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\t\tbreak;\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:\n\t\t\t\t\t\tlastValidIndex = i;\n\t\t\t\t\t\tbreak;\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:\n\t\t\t\t\t\tstack.pop();\n\t\t\t\t\t\tbreak;\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: name22, 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...name22 != null && { name: name22 },\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: name22, 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...name22 != null && { name: name22 },\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: name22, 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...name22 != null && { name: name22 },\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: name22, description } = {}) => {\n\treturn {\n\t\tname: \"json\",\n\t\tresponseFormat: Promise.resolve({\n\t\t\ttype: \"json\",\n\t\t\t...name22 != null && { name: name22 },\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};\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 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};\n}\nfunction prepareStepCallSettings({ callSettings, stepSettings }) {\n\tvar _a22, _b, _c, _d, _e, _f, _g, _h;\n\treturn prepareCallSettings({\n\t\tmaxOutputTokens: (_a22 = stepSettings == null ? void 0 : stepSettings.maxOutputTokens) != null ? _a22 : 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 _a22, _b, _c;\n\t\treturn (_c = (_b = (_a22 = steps[steps.length - 1]) == null ? void 0 : _a22.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\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});\n\t\t\t\tbreak;\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 _a22, _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 } = 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) {\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 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((_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : 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});\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 _a23, _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 = (_a23 = result.response) == null ? void 0 : _a23.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,\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 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) 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\") 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\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) break;\n\t\t\t\tif (!response.write(value)) await new Promise((resolve3) => {\n\t\t\t\t\tresponse.once(\"drain\", resolve3);\n\t\t\t\t});\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tresponse.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 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, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\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\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\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\treturn {\n\t\tmessage: (lastMessage == null ? void 0 : lastMessage.role) === \"assistant\" ? lastMessage : {\n\t\t\tid: messageId,\n\t\t\tmetadata: void 0,\n\t\t\trole: \"assistant\",\n\t\t\tparts: []\n\t\t},\n\t\tactiveTextParts: createIdMap(),\n\t\tactiveReasoningParts: createIdMap(),\n\t\tpartialToolCalls: createIdMap()\n\t};\n}\nfunction processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData }) {\n\treturn stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {\n\t\tawait runUpdateMessageJob(async ({ state, write }) => {\n\t\t\tvar _a22, _b, _c, _d;\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 _a23;\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.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\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 = (_a23 = anyOptions.providerExecuted) != null ? _a23 : part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) if (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\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\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 _a23, _b2;\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 = (_a23 = anyOptions.rawInput) != null ? _a23 : anyPart.rawInput;\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 = (_b2 = anyOptions.providerExecuted) != null ? _b2 : part.providerExecuted;\n\t\t\t\t\tconst providerMetadata = anyOptions.providerMetadata;\n\t\t\t\t\tif (providerMetadata != null) if (options.state === \"output-available\" || options.state === \"output-error\") {\n\t\t\t\t\t\tconst resultPart = part;\n\t\t\t\t\t\tresultPart.resultProviderMetadata = providerMetadata;\n\t\t\t\t\t} else part.callProviderMetadata = providerMetadata;\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\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 = (_a22 = chunk.providerMetadata) != null ? _a22 : 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\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\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\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\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 { value: partialArgs } = await parsePartialJson(partialToolCall.text);\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\tinput: partialArgs,\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\tinput: partialArgs,\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.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: 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: 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: 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: 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\tif (chunk.messageId != null) state.message.id = chunk.messageId;\n\t\t\t\t\tawait updateMessageMetadata(chunk.messageMetadata);\n\t\t\t\t\tif (chunk.messageId != null || chunk.messageMetadata != null) write();\n\t\t\t\t\tbreak;\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 }) {\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\tconst idInjectedStream = stream.pipeThrough(new TransformStream({ transform(chunk, controller) {\n\t\tif (chunk.type === \"start\") {\n\t\t\tconst startChunk = chunk;\n\t\t\tif (startChunk.messageId == null && messageId != null) startChunk.messageId = messageId;\n\t\t}\n\t\tif (chunk.type === \"abort\") isAborted = true;\n\t\tcontroller.enqueue(chunk);\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\tawait job({\n\t\t\tstate,\n\t\t\twrite: () => {}\n\t\t});\n\t};\n\tlet finishCalled = false;\n\tconst callOnFinish = async () => {\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\tawait onFinish({\n\t\t\tisAborted,\n\t\t\tisContinuation,\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\tonError(error);\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, consumeSseStream }) {\n\tlet sseStream = stream.pipeThrough(new JsonToSseTransformStream());\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 _a22;\n\t\t\tif (finished) return;\n\t\t\tfinished = true;\n\t\t\ttry {\n\t\t\t\tif (cancelStream) await ((_a22 = reader.cancel) == null ? void 0 : _a22.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 }) {\n\tconst reader = stream.getReader();\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\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 innerStreamReaders = [];\n\tlet controller = null;\n\tlet isClosed = false;\n\tlet waitForNewStream = createResolvablePromise();\n\tconst terminate = () => {\n\t\tisClosed = true;\n\t\twaitForNewStream.resolve();\n\t\tinnerStreamReaders.forEach((reader) => reader.cancel());\n\t\tinnerStreamReaders = [];\n\t\tcontroller?.close();\n\t};\n\tconst processPull = async () => {\n\t\tif (isClosed && innerStreamReaders.length === 0) {\n\t\t\tcontroller?.close();\n\t\t\treturn;\n\t\t}\n\t\tif (innerStreamReaders.length === 0) {\n\t\t\twaitForNewStream = createResolvablePromise();\n\t\t\tawait waitForNewStream.promise;\n\t\t\treturn processPull();\n\t\t}\n\t\ttry {\n\t\t\tconst { value, done } = await innerStreamReaders[0].read();\n\t\t\tif (done) {\n\t\t\t\tinnerStreamReaders.shift();\n\t\t\t\tif (innerStreamReaders.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\tcontroller?.error(error);\n\t\t\tinnerStreamReaders.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\tfor (const reader of innerStreamReaders) await reader.cancel();\n\t\t\t\tinnerStreamReaders = [];\n\t\t\t\tisClosed = true;\n\t\t\t}\n\t\t}),\n\t\taddStream: (innerStream) => {\n\t\t\tif (isClosed) throw new Error(\"Cannot add inner stream: outer stream is closed\");\n\t\t\tinnerStreamReaders.push(innerStream.getReader());\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\tisClosed = true;\n\t\t\twaitForNewStream.resolve();\n\t\t\tif (innerStreamReaders.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, 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 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\tconst forwardStream = new TransformStream({\n\t\tasync transform(chunk, controller) {\n\t\t\tconst chunkType = chunk.type;\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 \"tool-input-start\":\n\t\t\t\tcase \"tool-input-delta\":\n\t\t\t\tcase \"tool-input-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 \"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\tfinishChunk = {\n\t\t\t\t\t\ttype: \"finish\",\n\t\t\t\t\t\tfinishReason: chunk.finishReason.unified,\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\tbreak;\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) {\n\t\t\t\t\t\t\tconst toolExecutionId = generateId2();\n\t\t\t\t\t\t\toutstandingToolResults.add(toolExecutionId);\n\t\t\t\t\t\t\texecuteToolCall({\n\t\t\t\t\t\t\t\ttoolCall,\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,\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,\n\t\t\t\t\t\t\t\tmodel,\n\t\t\t\t\t\t\t\tonToolCallStart,\n\t\t\t\t\t\t\t\tonToolCallFinish,\n\t\t\t\t\t\t\t\tonPreliminaryToolResult: (result) => {\n\t\t\t\t\t\t\t\t\tenqueueToolResult(result);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}).then((result) => {\n\t\t\t\t\t\t\t\tenqueueToolResult(result);\n\t\t\t\t\t\t\t}).catch((error) => {\n\t\t\t\t\t\t\t\tenqueueToolResult({\n\t\t\t\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\t\t\t\terror\n\t\t\t\t\t\t\t\t});\n\t\t\t\t\t\t\t}).finally(() => {\n\t\t\t\t\t\t\t\toutstandingToolResults.delete(toolExecutionId);\n\t\t\t\t\t\t\t\tattemptClose();\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\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 = \"\";\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 _a22;\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 = (_a22 = chunk.providerMetadata) != null ? _a22 : 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 (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}\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\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 _a22, _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 (onChunk == null ? void 0 : onChunk({ chunk: part }));\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 onError({ error });\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 = (_a22 = part.providerMetadata) != null ? _a22 : 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: modelInfo,\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: modelInfo.provider,\n\t\t\t\t\t\tmodel: modelInfo.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 _a22, _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\tawait notify({\n\t\t\t\t\t\tevent: {\n\t\t\t\t\t\t\tstepNumber: finalStep.stepNumber,\n\t\t\t\t\t\t\tmodel: finalStep.model,\n\t\t\t\t\t\t\tfunctionId: finalStep.functionId,\n\t\t\t\t\t\t\tmetadata: finalStep.metadata,\n\t\t\t\t\t\t\texperimental_context: finalStep.experimental_context,\n\t\t\t\t\t\t\tfinishReason: finalStep.finishReason,\n\t\t\t\t\t\t\trawFinishReason: finalStep.rawFinishReason,\n\t\t\t\t\t\t\ttotalUsage,\n\t\t\t\t\t\t\tusage: finalStep.usage,\n\t\t\t\t\t\t\tcontent: finalStep.content,\n\t\t\t\t\t\t\ttext: finalStep.text,\n\t\t\t\t\t\t\treasoningText: finalStep.reasoningText,\n\t\t\t\t\t\t\treasoning: finalStep.reasoning,\n\t\t\t\t\t\t\tfiles: finalStep.files,\n\t\t\t\t\t\t\tsources: finalStep.sources,\n\t\t\t\t\t\t\ttoolCalls: finalStep.toolCalls,\n\t\t\t\t\t\t\tstaticToolCalls: finalStep.staticToolCalls,\n\t\t\t\t\t\t\tdynamicToolCalls: finalStep.dynamicToolCalls,\n\t\t\t\t\t\t\ttoolResults: finalStep.toolResults,\n\t\t\t\t\t\t\tstaticToolResults: finalStep.staticToolResults,\n\t\t\t\t\t\t\tdynamicToolResults: finalStep.dynamicToolResults,\n\t\t\t\t\t\t\trequest: finalStep.request,\n\t\t\t\t\t\t\tresponse: finalStep.response,\n\t\t\t\t\t\t\twarnings: finalStep.warnings,\n\t\t\t\t\t\t\tproviderMetadata: finalStep.providerMetadata,\n\t\t\t\t\t\t\tsteps: recordedSteps\n\t\t\t\t\t\t},\n\t\t\t\t\t\tcallbacks: [onFinish, 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 _a23;\n\t\t\t\t\t\t\t\treturn ((_a23 = finalStep.toolCalls) == null ? void 0 : _a23.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\": (_a22 = totalUsage.inputTokenDetails) == null ? void 0 : _a22.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\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}\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 } = 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\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) {\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 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 _a22, _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\tabortSignal?.addEventListener(\"abort\", clearStepTimeout);\n\t\t\t\t\tabortSignal?.addEventListener(\"abort\", clearChunkTimeout);\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((_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : 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});\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\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\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\tconst activeToolCallToolNames = {};\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: modelInfo.modelId\n\t\t\t\t\t\t};\n\t\t\t\t\t\tlet activeText = \"\";\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 _a23, _b2, _c2, _d2, _e2;\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\tcase \"text-start\":\n\t\t\t\t\t\t\t\t\tcase \"text-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 \"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: 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\tcase \"reasoning-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 \"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: 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: (_a23 = chunk.id) != null ? _a23 : stepResponse.id,\n\t\t\t\t\t\t\t\t\t\t\ttimestamp: (_b2 = chunk.timestamp) != null ? _b2 : stepResponse.timestamp,\n\t\t\t\t\t\t\t\t\t\t\tmodelId: (_c2 = chunk.modelId) != null ? _c2 : 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 * ((_d2 = stepUsage.outputTokens) != null ? _d2 : 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\tactiveToolCallToolNames[chunk.id] = chunk.toolName;\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\tif ((tool2 == null ? void 0 : tool2.onInputStart) != null) await tool2.onInputStart({\n\t\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t\t});\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: (_e2 = chunk.dynamic) != null ? _e2 : (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\tdelete activeToolCallToolNames[chunk.id];\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\tconst toolName = activeToolCallToolNames[chunk.id];\n\t\t\t\t\t\t\t\t\t\tconst tool2 = stepToolSet == null ? void 0 : stepToolSet[toolName];\n\t\t\t\t\t\t\t\t\t\tif ((tool2 == null ? void 0 : tool2.onInputDelta) != null) await tool2.onInputDelta({\n\t\t\t\t\t\t\t\t\t\t\tinputTextDelta: chunk.delta,\n\t\t\t\t\t\t\t\t\t\t\ttoolCallId: chunk.id,\n\t\t\t\t\t\t\t\t\t\t\tmessages: stepInputMessages,\n\t\t\t\t\t\t\t\t\t\t\tabortSignal,\n\t\t\t\t\t\t\t\t\t\t\texperimental_context\n\t\t\t\t\t\t\t\t\t\t});\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\t}\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 _a23, _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\tclearStepTimeout();\n\t\t\t\t\t\t\t\t\tclearChunkTimeout();\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\": (_a23 = stepUsage.inputTokenDetails) == null ? void 0 : _a23.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\tclearStepTimeout();\n\t\t\t\t\t\t\t\tclearChunkTimeout();\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} catch (error) {\n\t\t\t\t\t\tclearStepTimeout();\n\t\t\t\t\t\tclearChunkTimeout();\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 _a22;\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 _a23;\n\t\t\t\t\tthis.rejectResultPromises(error);\n\t\t\t\t\t(_a23 = options == null ? void 0 : options.onError) == null || _a23.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(_a22 = options == null ? void 0 : options.onError) == null || _a22.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 != null) controller.enqueue(partialOutput);\n\t\t} })));\n\t}\n\tget elementStream() {\n\t\tvar _a22, _b, _c;\n\t\tconst transform = (_a22 = this.outputSpecification) == null ? void 0 : _a22.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\tget output() {\n\t\treturn this.finalStep.then((step) => {\n\t\t\tvar _a22;\n\t\t\treturn ((_a22 = this.outputSpecification) != null ? _a22 : 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}\n\ttoUIMessageStream({ originalMessages, generateMessageId, onFinish, messageMetadata, sendReasoning = true, sendSources = false, sendStart = true, sendFinish = true, onError = () => \"An error occurred.\" } = {}) {\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 _a22;\n\t\t\tconst tool2 = (_a22 = this.tools) == null ? void 0 : _a22[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\treturn createAsyncIterableStream(handleUIMessageStreamFinish({\n\t\t\tstream: 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.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\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...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\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} })),\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}));\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 _a22, _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: (_a22 = this.settings.stopWhen) != null ? _a22 : 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\treturn generateText({\n\t\t\t...await this.prepareCall(options),\n\t\t\tabortSignal,\n\t\t\ttimeout,\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\treturn streamText({\n\t\t\t...await this.prepareCall(options),\n\t\t\tabortSignal,\n\t\t\ttimeout,\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\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\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\tsafeEnqueue({\n\t\t\t\t\t\ttype: \"error\",\n\t\t\t\t\t\terrorText: onError(error)\n\t\t\t\t\t});\n\t\t\t\t}));\n\t\t\t},\n\t\t\tonError\n\t\t} });\n\t\tif (result) ongoingStreamPromises.push(result.catch((error) => {\n\t\t\tsafeEnqueue({\n\t\t\t\ttype: \"error\",\n\t\t\t\terrorText: onError(error)\n\t\t\t});\n\t\t}));\n\t} catch (error) {\n\t\tsafeEnqueue({\n\t\t\ttype: \"error\",\n\t\t\terrorText: onError(error)\n\t\t});\n\t}\n\tnew Promise(async (resolve3) => {\n\t\twhile (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();\n\t\tresolve3();\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});\n}\nfunction readUIMessageStream({ message, stream, onError, terminateOnError = false }) {\n\tvar _a22;\n\tlet controller;\n\tlet hasErrored = false;\n\tconst outputStream = new ReadableStream({ start(controllerParam) {\n\t\tcontroller = controllerParam;\n\t} });\n\tconst state = createStreamingUIMessageState({\n\t\tmessageId: (_a22 = message == null ? void 0 : message.id) != null ? _a22 : \"\",\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\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\tcontroller?.enqueue(structuredClone(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}).finally(() => {\n\t\tif (!hasErrored) controller?.close();\n\t});\n\treturn createAsyncIterableStream(outputStream);\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 !== \"input-streaming\" && part.state !== \"input-available\")\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 _a22;\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 (_a22 = options == null ? void 0 : options.convertDataPart) == null ? void 0 : _a22.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 _a22, _b, _c, _d, _e, _f, _g, _h;\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\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\" ? (_a22 = part.input) != null ? _a22 : \"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...part.callProviderMetadata != null ? { providerOptions: part.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...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 = (_b = part.resultProviderMetadata) != null ? _b : 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 createToolModelOutput({\n\t\t\t\t\t\t\t\t\t\ttoolCallId: part.toolCallId,\n\t\t\t\t\t\t\t\t\t\tinput: part.input,\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\ttool: (_c = options == null ? void 0 : options.tools) == null ? void 0 : _c[toolName],\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 _a23;\n\t\t\t\t\t\treturn isToolUIPart(part) && (part.providerExecuted !== true || ((_a23 = part.approval) == null ? void 0 : _a23.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 createToolModelOutput({\n\t\t\t\t\t\t\t\t\t\t\ttoolCallId: toolPart.toolCallId,\n\t\t\t\t\t\t\t\t\t\t\tinput: toolPart.input,\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\ttool: (_h = options == null ? void 0 : options.tools) == null ? void 0 : _h[toolName],\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());\nvar uiMessagesSchema = lazySchema(() => zodSchema(z.array(z.object({\n\tid: z.string(),\n\trole: z.enum([\n\t\t\"system\",\n\t\t\"user\",\n\t\t\"assistant\"\n\t]),\n\tmetadata: z.unknown().optional(),\n\tparts: z.array(z.union([\n\t\tz.object({\n\t\t\ttype: z.literal(\"text\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"reasoning\"),\n\t\t\ttext: z.string(),\n\t\t\tstate: z.enum([\"streaming\", \"done\"]).optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-url\"),\n\t\t\tsourceId: z.string(),\n\t\t\turl: z.string(),\n\t\t\ttitle: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"source-document\"),\n\t\t\tsourceId: z.string(),\n\t\t\tmediaType: z.string(),\n\t\t\ttitle: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"file\"),\n\t\t\tmediaType: z.string(),\n\t\t\tfilename: z.string().optional(),\n\t\t\turl: z.string(),\n\t\t\tproviderMetadata: providerMetadataSchema.optional()\n\t\t}),\n\t\tz.object({ type: z.literal(\"step-start\") }),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"data-\"),\n\t\t\tid: z.string().optional(),\n\t\t\tdata: z.unknown()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tinput: z.unknown().optional(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.never().optional(),\n\t\t\t\treason: z.never().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.boolean(),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tinput: z.unknown().optional(),\n\t\t\trawInput: z.unknown().optional(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.literal(\"dynamic-tool\"),\n\t\t\ttoolName: z.string(),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(false),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"input-streaming\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tinput: z.unknown().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"input-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.never().optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"approval-requested\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.never().optional(),\n\t\t\t\treason: z.never().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"approval-responded\"),\n\t\t\tinput: z.unknown(),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.boolean(),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-available\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.unknown(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tpreliminary: z.boolean().optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-error\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown().optional(),\n\t\t\trawInput: z.unknown().optional(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.string(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tresultProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(true),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t}).optional()\n\t\t}),\n\t\tz.object({\n\t\t\ttype: z.string().startsWith(\"tool-\"),\n\t\t\ttoolCallId: z.string(),\n\t\t\ttoolMetadata: toolMetadataSchema2.optional(),\n\t\t\tstate: z.literal(\"output-denied\"),\n\t\t\tproviderExecuted: z.boolean().optional(),\n\t\t\tinput: z.unknown(),\n\t\t\toutput: z.never().optional(),\n\t\t\terrorText: z.never().optional(),\n\t\t\tcallProviderMetadata: providerMetadataSchema.optional(),\n\t\t\tapproval: z.object({\n\t\t\t\tid: z.string(),\n\t\t\t\tapproved: z.literal(false),\n\t\t\t\treason: z.string().optional(),\n\t\t\t\tsignature: z.string().optional()\n\t\t\t})\n\t\t})\n\t]))\n}).superRefine((message, context2) => {\n\tif (message.role !== \"assistant\" && message.parts.length === 0) context2.addIssue({\n\t\torigin: \"array\",\n\t\tcode: \"too_small\",\n\t\tminimum: 1,\n\t\tinclusive: true,\n\t\tinput: message.parts,\n\t\tpath: [\"parts\"],\n\t\tmessage: \"Message must contain at least one part\"\n\t});\n})).nonempty(\"Messages array must not be empty\")));\nasync function safeValidateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\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()) 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\tif (dataSchemas || tools) 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\tawait 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 (tools && 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 = tools[toolName];\n\t\t\t\tif (!tool2 && (toolPart.state === \"output-available\" || toolPart.state === \"output-error\" || toolPart.state === \"output-denied\")) continue;\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\tif (toolPart.state === \"input-available\" || toolPart.state === \"output-available\") await validateTypes({\n\t\t\t\t\tvalue: toolPart.input,\n\t\t\t\t\tschema: tool2.inputSchema,\n\t\t\t\t\tcontext: {\n\t\t\t\t\t\tfield: `messages[${msgIdx}].parts[${partIdx}].input`,\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 (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}\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 validateUIMessages({ messages, metadataSchema, dataSchemas, tools }) {\n\tconst response = await safeValidateUIMessages({\n\t\tmessages,\n\t\tmetadataSchema,\n\t\tdataSchemas,\n\t\ttools\n\t});\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 _a22;\n\tconst validatedMessages = await validateUIMessages({\n\t\tmessages: uiMessages,\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: (_a22 = uiMessageStreamOptions.originalMessages) != null ? _a22 : validatedMessages\n\t});\n}\nasync function createAgentUIStreamResponse({ headers, status, statusText, consumeSseStream, ...options }) {\n\treturn createUIMessageStreamResponse({\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\n\t\tconsumeSseStream,\n\t\tstream: await createAgentUIStream(options)\n\t});\n}\nasync function pipeAgentUIStreamToResponse({ response, headers, status, statusText, consumeSseStream, ...options }) {\n\treturn pipeUIMessageStreamToResponse({\n\t\tresponse,\n\t\theaders,\n\t\tstatus,\n\t\tstatusText,\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 _a22, _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 = (_a22 = modelResponse.usage) != null ? _a22 : { 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\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 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\tvar _a22;\n\t\t\tconst [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([model.maxEmbeddingsPerCall, model.supportsParallelCalls]);\n\t\t\tif (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {\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 = splitArray(values, maxEmbeddingsPerCall);\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\tfor (const parallelChunk of parallelChunks) {\n\t\t\t\tconst results = await Promise.all(parallelChunk.map((chunk) => {\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\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) if (!providerMetadata) providerMetadata = { ...result.providerMetadata };\n\t\t\t\t\telse for (const [providerName, metadata] of Object.entries(result.providerMetadata)) providerMetadata[providerName] = {\n\t\t\t\t\t\t...(_a22 = providerMetadata[providerName]) != null ? _a22 : {},\n\t\t\t\t\t\t...metadata\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 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};\nasync function generateImage({ model: modelArg, prompt: promptArg, n = 1, maxImagesPerCall, size, aspectRatio, seed, providerOptions, maxRetries: maxRetriesArg, abortSignal, headers }) {\n\tvar _a22;\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});\n\tconst maxImagesPerCallWithDefault = (_a22 = maxImagesPerCall != null ? maxImagesPerCall : await invokeModelMaxImagesPerCall(model)) != null ? _a22 : 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) => retry(() => {\n\t\tconst { prompt, files, mask } = normalizePrompt(promptArg);\n\t\treturn model.doGenerate({\n\t\t\tprompt,\n\t\t\tfiles,\n\t\t\tmask,\n\t\t\tn: callImageCount,\n\t\t\tabortSignal,\n\t\t\theaders: headersWithUserAgent,\n\t\t\tsize,\n\t\t\taspectRatio,\n\t\t\tseed,\n\t\t\tproviderOptions: providerOptions != null ? providerOptions : {}\n\t\t});\n\t})));\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 _a23;\n\t\t\treturn new DefaultGeneratedFile({\n\t\t\t\tdata: image,\n\t\t\t\tmediaType: (_a23 = detectMediaType({\n\t\t\t\t\tdata: image,\n\t\t\t\t\tsignatures: imageMediaTypeSignatures\n\t\t\t\t})) != null ? _a23 : \"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\tproviderMetadata[providerName] ?? (providerMetadata[providerName] = { images: [] });\n\t\t\tproviderMetadata[providerName].images.push(...result.providerMetadata[providerName].images);\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 _a22;\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 = (_a22 = latestObject == null ? void 0 : latestObject.length) != null ? _a22 : 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 _a22;\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});\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 _a23, _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 = (_a23 = result2.response) == null ? void 0 : _a23.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 = (_a22 = generateResult.request) != null ? _a22 : {};\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 _a22;\n\t\treturn new Response(JSON.stringify(this.object), {\n\t\t\tstatus: (_a22 = init == null ? void 0 : init.status) != null ? _a22 : 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}\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 window.atob(base64Content);\n\t} catch (error) {\n\t\tthrow new Error(`Error decoding data URL`);\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}\nvar SerialJobExecutor = class {\n\tconstructor() {\n\t\tthis.queue = [];\n\t\tthis.isProcessing = false;\n\t}\n\tasync processQueue() {\n\t\tif (this.isProcessing) return;\n\t\tthis.isProcessing = true;\n\t\twhile (this.queue.length > 0) {\n\t\t\tawait this.queue[0]();\n\t\t\tthis.queue.shift();\n\t\t}\n\t\tthis.isProcessing = false;\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};\nfunction simulateReadableStream({ chunks, initialDelayInMs = 0, chunkDelayInMs = 0, _internal }) {\n\tvar _a22;\n\tconst delay$1 = (_a22 = _internal == null ? void 0 : _internal.delay) != null ? _a22 : 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});\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\") onError({ error: wrapGatewayError(chunk.error) });\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\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}),\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\":\n\t\t\t\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t\t\t\t\tbreak;\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\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 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 _a22, _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: (_a22 = chunk.id) != null ? _a22 : 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 \"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 = chunk.finishReason.unified;\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: chunk.finishReason.unified,\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\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:\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}\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);\n\t\t\t}\n\t\t}).catch((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\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 _a22;\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: (_a22 = detectMediaType({\n\t\t\t\tdata: result.audio,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a22 : \"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 _a22;\n\t\tthis.audio = options.audio;\n\t\tthis.warnings = options.warnings;\n\t\tthis.responses = options.responses;\n\t\tthis.providerMetadata = (_a22 = options.providerMetadata) != null ? _a22 : {};\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 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\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\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\treturn {\n\t\t\t\t...message,\n\t\t\t\tcontent: message.content.filter((part) => {\n\t\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\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\t\tconst partToolName = part.type === \"tool-call\" || part.type === \"tool-result\" ? part.toolName : approvalIdToToolName.get(part.approvalId);\n\t\t\t\t\treturn toolCall.tools != null && partToolName != null && !toolCall.tools.includes(partToolName);\n\t\t\t\t})\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 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 (buffer.length > 0 && type !== void 0) {\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.type !== type || chunk.id !== id) && buffer.length > 0) flushBuffer(controller);\n\t\t\tbuffer += chunk.text;\n\t\t\tid = chunk.id;\n\t\t\ttype = chunk.type;\n\t\t\tif (chunk.providerMetadata != null) providerMetadata = 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});\n\t\t\t\tbuffer = buffer.slice(match.length);\n\t\t\t\tawait delay$2(delayInMs);\n\t\t\t}\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 _a22, _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 = (_a22 = normalizedFrameImages == null ? void 0 : normalizedFrameImages.find((frame) => frame.frameType === \"first_frame\")) == null ? void 0 : _a22.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 = providerMetadata[providerName];\n\t\t\tif (existingMetadata != null && typeof existingMetadata === \"object\") {\n\t\t\t\tproviderMetadata[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 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 _a22;\n\tconst detected = restrictToImages ? detectMediaType({\n\t\tdata,\n\t\tsignatures: imageMediaTypeSignatures\n\t}) : (_a22 = detectMediaType({\n\t\tdata,\n\t\tsignatures: imageMediaTypeSignatures\n\t})) != null ? _a22 : 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 _a22;\n\tconst transform = (_a22 = options == null ? void 0 : options.transform) != null ? _a22 : 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});\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:\n\t\t\t\t\t\t\tcontroller.enqueue(part);\n\t\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: \"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 _a22;\n\t\t\tif (!((_a22 = params.tools) == null ? void 0 : _a22.length)) return params;\n\t\t\tconst transformedTools = params.tools.map((tool2) => {\n\t\t\t\tvar _a23;\n\t\t\t\tif (tool2.type !== \"function\" || !((_a23 = tool2.inputExamples) == null ? void 0 : _a23.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 _a22, _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: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : 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 _a22, _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: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : 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\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 _a22, _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 = (_a22 = overrideMaxImagesPerCall == null ? void 0 : overrideMaxImagesPerCall({ model })) != null ? _a22 : 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 name21 = \"AI_NoSuchProviderError\";\nvar marker21 = `vercel.ai.error.${name21}`;\nvar symbol21 = Symbol.for(marker21);\nvar _a21;\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: name21,\n\t\t\tmodelId,\n\t\t\tmodelType,\n\t\t\tmessage\n\t\t});\n\t\tthis[_a21] = true;\n\t\tthis.providerId = providerId;\n\t\tthis.availableProviders = availableProviders;\n\t}\n\tstatic isInstance(error) {\n\t\treturn AISDKError.hasMarker(error, marker21);\n\t}\n};\n_a21 = symbol21;\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 = {};\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 _a22, _b;\n\t\tconst [providerId, modelId] = this.splitId(id, \"languageModel\");\n\t\tlet model = (_b = (_a22 = this.getProvider(providerId, \"languageModel\")).languageModel) == null ? void 0 : _b.call(_a22, 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 _a22;\n\t\tconst [providerId, modelId] = this.splitId(id, \"embeddingModel\");\n\t\tconst provider = this.getProvider(providerId, \"embeddingModel\");\n\t\tconst model = (_a22 = provider.embeddingModel) == null ? void 0 : _a22.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 _a22;\n\t\tconst [providerId, modelId] = this.splitId(id, \"imageModel\");\n\t\tconst provider = this.getProvider(providerId, \"imageModel\");\n\t\tlet model = (_a22 = provider.imageModel) == null ? void 0 : _a22.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 _a22;\n\t\tconst [providerId, modelId] = this.splitId(id, \"transcriptionModel\");\n\t\tconst provider = this.getProvider(providerId, \"transcriptionModel\");\n\t\tconst model = (_a22 = provider.transcriptionModel) == null ? void 0 : _a22.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 _a22;\n\t\tconst [providerId, modelId] = this.splitId(id, \"speechModel\");\n\t\tconst provider = this.getProvider(providerId, \"speechModel\");\n\t\tconst model = (_a22 = provider.speechModel) == null ? void 0 : _a22.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 _a22;\n\t\tconst [providerId, modelId] = this.splitId(id, \"rerankingModel\");\n\t\tconst provider = this.getProvider(providerId, \"rerankingModel\");\n\t\tconst model = (_a22 = provider.rerankingModel) == null ? void 0 : _a22.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((document) => JSON.stringify(document)) }\n\t\t\t}\n\t\t}),\n\t\ttracer,\n\t\tfn: async () => {\n\t\t\tvar _a22, _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((document) => JSON.stringify(document)) }\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\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: (_a22 = response == null ? void 0 : response.timestamp) != null ? _a22 : /* @__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}\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 _a22;\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: (_a22 = detectMediaType({\n\t\t\t\tdata: audioData,\n\t\t\t\tsignatures: audioMediaTypeSignatures\n\t\t\t})) != null ? _a22 : \"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 _a22;\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 = (_a22 = options.providerMetadata) != null ? _a22 : {};\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 _a22;\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((_a22 = await response.text()) != null ? _a22 : \"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: name22, type } = file;\n\t\treturn {\n\t\t\ttype: \"file\",\n\t\t\tmediaType: type,\n\t\t\tfilename: name22,\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 _a22;\n\t\t\t\t\tresolve3((_a22 = readerEvent.target) == null ? void 0 : _a22.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}\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 _a22, _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 ((_a22 = this.prepareSendMessagesRequest) == null ? void 0 : _a22.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 _a22, _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 ((_a22 = this.prepareReconnectToStreamRequest) == null ? void 0 : _a22.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\tconst api = (_b = preparedRequest == null ? void 0 : preparedRequest.api) != null ? _b : `${this.api}/${options.chatId}/stream`;\n\t\tconst headers = (preparedRequest == null ? void 0 : preparedRequest.headers) !== void 0 ? normalizeHeaders(preparedRequest.headers) : baseHeaders;\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: \"GET\",\n\t\t\theaders,\n\t\t\tcredentials\n\t\t});\n\t\tif (response.status === 204) return null;\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};\nvar DefaultChatTransport = class extends HttpChatTransport {\n\tconstructor(options = {}) {\n\t\tsuper(options);\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.jobExecutor = new SerialJobExecutor();\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 _a22, _b, _c, _d;\n\t\t\tif (message == null) {\n\t\t\t\tawait this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\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* 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 lastMessage = messages[messages.length - 1];\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\tthis.state.replaceMessage(messages.length - 1, {\n\t\t\t\t...lastMessage,\n\t\t\t\tparts: lastMessage.parts.map(updatePart)\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) this.shouldSendAutomatically().then((shouldSend) => {\n\t\t\t\tvar _a22;\n\t\t\t\tif (shouldSend) this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\n\t\t\t\t\t...options\n\t\t\t\t});\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 lastMessage = messages[messages.length - 1];\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\tthis.state.replaceMessage(messages.length - 1, {\n\t\t\t\t...lastMessage,\n\t\t\t\tparts: lastMessage.parts.map(updatePart)\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) this.shouldSendAutomatically().then((shouldSend) => {\n\t\t\t\tvar _a22;\n\t\t\t\tif (shouldSend) this.makeRequest({\n\t\t\t\t\ttrigger: \"submit-message\",\n\t\t\t\t\tmessageId: (_a22 = this.lastMessage) == null ? void 0 : _a22.id,\n\t\t\t\t\t...options\n\t\t\t\t});\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 immediately, keep the generated tokens if any.\n\t\t*/\n\t\tthis.stop = async () => {\n\t\t\tvar _a22;\n\t\t\tif (this.status !== \"streaming\" && this.status !== \"submitted\") return;\n\t\t\tif ((_a22 = this.activeResponse) == null ? void 0 : _a22.abortController) this.activeResponse.abortController.abort();\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) return;\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 makeRequest({ trigger, metadata, headers, body, messageId }) {\n\t\tvar _a22, _b;\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\tmetadata,\n\t\t\t\theaders,\n\t\t\t\tbody\n\t\t\t});\n\t\t\tif (reconnect == null) return;\n\t\t\tresumeStream = reconnect;\n\t\t} catch (err) {\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\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\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: createStreamingUIMessageState({\n\t\t\t\t\tlastMessage: this.state.snapshot(lastMessage),\n\t\t\t\t\tmessageId: this.generateId()\n\t\t\t\t}),\n\t\t\t\tabortController: new AbortController()\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(() => job({\n\t\t\t\tstate: response.state,\n\t\t\t\twrite: () => {\n\t\t\t\t\tvar _a23;\n\t\t\t\t\tthis.setStatus({ status: \"streaming\" });\n\t\t\t\t\tif (response.state.message.id === ((_a23 = this.lastMessage) == null ? void 0 : _a23.id)) this.state.replaceMessage(this.state.messages.length - 1, response.state.message);\n\t\t\t\t\telse this.state.pushMessage(response.state.message);\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\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\tonError: (error) => {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t} catch (err) {\n\t\t\tif (isAbort || err.name === \"AbortError\") {\n\t\t\t\tisAbort = true;\n\t\t\t\tthis.setStatus({ status: \"ready\" });\n\t\t\t\treturn null;\n\t\t\t}\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 (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) (_a22 = this.onFinish) == null || _a22.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} catch (err) {\n\t\t\t\tconsole.error(err);\n\t\t\t}\n\t\t\tif (this.activeResponse === activeResponse) this.activeResponse = void 0;\n\t\t}\n\t\tif (!isError && await this.shouldSendAutomatically()) await this.makeRequest({\n\t\t\ttrigger: \"submit-message\",\n\t\t\tmessageId: (_b = this.lastMessage) == null ? void 0 : _b.id,\n\t\t\tmetadata,\n\t\t\theaders,\n\t\t\tbody\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 validateUIMessages({\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.state === \"output-error\" || 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 lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter(isToolUIPart).filter((part) => !part.providerExecuted);\n\treturn lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => part.state === \"output-available\" || 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};\n//#endregion\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, 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","const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\nexport const FALLBACK_TOOL_NAME = 'unknown_tool';\n\nexport function sanitizeToolName(toolName: unknown): string {\n  if (typeof toolName !== 'string') {\n    return FALLBACK_TOOL_NAME;\n  }\n\n  return TOOL_NAME_PATTERN.test(toolName) ? toolName : FALLBACK_TOOL_NAME;\n}\n","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  parseDataUri,\n  resolveFilePartMediaTypeAndData,\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 { sanitizeToolName } from '../utils/tool-name';\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 getTextContent(message: MastraDBMessage): string {\n  return typeof message.content.content === 'string'\n    ? message.content.content\n    : (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    // 1. Handle tool invocations (only if not already in parts array)\n    const hasToolInvocationParts = dbMsg.content.parts?.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 = dbMsg.content.parts?.some(p => p.type === 'reasoning');\n    const hasFileInParts = dbMsg.content.parts?.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 (dbMsg.content.parts) {\n      for (const part of dbMsg.content.parts) {\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\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.\n          if ((categorized.type === 'url' || categorized.type === 'providerFileId') && typeof fileData === 'string') {\n            const v5UIPart: AIV5Type.FileUIPart = {\n              type: 'file' as const,\n              url: fileData,\n              mediaType: categorized.mimeType || 'image/png',\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) {\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            };\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          continue;\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 {\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:\n              typeof p.output === 'object' && p.output && 'value' in p.output\n                ? (p.output as { value: unknown }).value\n                : 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          if (p.state === 'output-available') {\n            return {\n              type: 'tool-invocation' as const,\n              toolInvocation: {\n                toolCallId: p.toolCallId,\n                toolName,\n                args: p.input,\n                result:\n                  typeof p.output === 'object' && p.output && 'value' in p.output\n                    ? (p.output as { value: unknown }).value\n                    : p.output,\n                state: 'result' as const,\n              },\n              providerMetadata: callProviderMetadata,\n              createdAt: getMastraCreatedAt(callProviderMetadata),\n            } satisfies MastraToolInvocationPart;\n          }\n          return {\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          } satisfies MastraToolInvocationPart;\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.url,\n              providerMetadata: p.providerMetadata,\n            },\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        // 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 (data instanceof URL) {\n      return data.toString();\n    } else {\n      if (data instanceof Buffer) {\n        const base64 = data.toString('base64');\n        return `data:${mimeType};base64,${base64}`;\n      } else if (typeof data === 'string') {\n        // OpenAI Files API file IDs (e.g. \"file-abc123\") must pass through as-is so\n        // @ai-sdk/openai can forward them as { file_id: \"file-...\" } to the API.\n        return data.startsWith('data:') || data.startsWith('http') || data.startsWith('file-')\n          ? data\n          : `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      } else {\n        return '';\n      }\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\n      : [{ type: 'text', text: modelMsg.content } satisfies AIV5.TextPart];\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        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          matchingCall.state = 'result';\n          matchingCall.result =\n            typeof toolResultPart.output === 'object' && toolResultPart.output && 'value' in toolResultPart.output\n              ? toolResultPart.output.value\n              : toolResultPart.output;\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        if (matchingV2Part && matchingV2Part.type === 'tool-invocation') {\n          updateMatchingCallInvocationResult(toolResultPart, matchingV2Part.toolInvocation);\n          if (toolResultPart.providerOptions) {\n            matchingV2Part.providerMetadata = toolResultPart.providerOptions;\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 (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 { sanitizeToolName } from '../utils/tool-name';\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 normalizeToolResult(output: unknown): unknown {\n  return typeof output === 'object' && output && 'value' in output ? (output as { value: unknown }).value : output;\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\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: 'callProviderMetadata' in part ? toMastraProviderMetadata(part.callProviderMetadata) : undefined,\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: normalizeToolResult(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\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\n  return undefined;\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      parts.push(AIV6Adapter.toUIPart(part));\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    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    const compatibleParts = uiMsg.parts.filter(part => {\n      if (part.type === 'source-document') return false;\n      if (AIV6.isToolUIPart(part)) return false;\n      return true;\n    });\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] {\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          callProviderMetadata: 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              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              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    return AIV6Adapter.toUIPartFromV5(\n      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  }\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 * `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      const sorted: Record<string, unknown> = {};\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 { 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 */\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    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      }\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      }\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      }\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      }\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 { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport type { LanguageModelV1Prompt, CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\n\nimport { convertDataContentToBase64String } from '../prompt/data-content';\nimport { categorizeFileData } from '../prompt/image-utils';\nimport type { AIV5Type } from '../types';\nimport { sanitizeToolName } from '../utils/tool-name';\n\ntype AIV5LanguageModelV2Message = LanguageModelV2Prompt[0];\ntype LanguageModelV1Message = LanguageModelV1Prompt[0];\n\n/**\n * Convert an AI SDK V4 CoreMessage to a V1 LanguageModel prompt message.\n * Used for creating LLM prompt messages without AI SDK streamText/generateText.\n */\nexport function aiV4CoreMessageToV1PromptMessage(coreMessage: CoreMessageV4): LanguageModelV1Message {\n  if (coreMessage.role === `system`) {\n    return coreMessage;\n  }\n\n  if (typeof coreMessage.content === `string` && (coreMessage.role === `assistant` || coreMessage.role === `user`)) {\n    return {\n      ...coreMessage,\n      content: [{ type: 'text', text: coreMessage.content }],\n    };\n  }\n\n  if (typeof coreMessage.content === `string`) {\n    throw new Error(\n      `Saw text content for input CoreMessage, but the role is ${coreMessage.role}. This is only allowed for \"system\", \"assistant\", and \"user\" roles.`,\n    );\n  }\n\n  const roleContent: {\n    user: Exclude<Extract<LanguageModelV1Message, { role: 'user' }>['content'], string>;\n    assistant: Exclude<Extract<LanguageModelV1Message, { role: 'assistant' }>['content'], string>;\n    tool: Exclude<Extract<LanguageModelV1Message, { role: 'tool' }>['content'], string>;\n  } = {\n    user: [],\n    assistant: [],\n    tool: [],\n  };\n\n  const role = coreMessage.role;\n\n  for (const part of coreMessage.content) {\n    const incompatibleMessage = `Saw incompatible message content part type ${part.type} for message role ${role}`;\n\n    switch (part.type) {\n      case 'text': {\n        if (role === `tool`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push(part);\n        break;\n      }\n\n      case 'redacted-reasoning':\n      case 'reasoning': {\n        if (role !== `assistant`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push(part);\n        break;\n      }\n\n      case 'tool-call': {\n        if (role === `tool` || role === `user`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          toolName: sanitizeToolName(part.toolName),\n        });\n        break;\n      }\n\n      case 'tool-result': {\n        if (role === `assistant` || role === `user`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          toolName: sanitizeToolName(part.toolName),\n        });\n        break;\n      }\n\n      case 'image': {\n        if (role === `tool` || role === `assistant`) {\n          throw new Error(incompatibleMessage);\n        }\n\n        let processedImage: URL | Uint8Array;\n\n        if (part.image instanceof URL || part.image instanceof Uint8Array) {\n          processedImage = part.image;\n        } else if (Buffer.isBuffer(part.image) || part.image instanceof ArrayBuffer) {\n          processedImage = new Uint8Array(part.image);\n        } else {\n          // part.image is a string - could be a URL, data URI, raw base64, or a\n          // provider file ID (e.g. OpenAI \"file-...\")\n          const categorized = categorizeFileData(part.image, part.mimeType);\n\n          if (categorized.type === 'raw') {\n            // Raw base64 — keep as Uint8Array so providers receive raw bytes\n            // and don't double-wrap in a data URI (e.g. Gemini inline_data.data)\n            processedImage = new Uint8Array(Buffer.from(part.image, 'base64'));\n          } else if (categorized.type === 'providerFileId') {\n            // Provider file IDs (e.g. OpenAI \"file-...\") are not parseable URLs and\n            // can't be expressed as a V1 image part. Emit a file part instead so the\n            // ID survives untouched and providers can forward it by reference.\n            const { image: _image, type: _type, ...rest } = part;\n            roleContent[role].push({\n              ...rest,\n              type: 'file',\n              data: part.image,\n              mimeType: categorized.mimeType || 'application/octet-stream',\n            });\n            break;\n          } else {\n            processedImage = new URL(part.image);\n          }\n        }\n\n        roleContent[role].push({\n          ...part,\n          image: processedImage,\n        });\n        break;\n      }\n\n      case 'file': {\n        if (role === `tool`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          data:\n            part.data instanceof URL\n              ? part.data\n              : typeof part.data === 'string'\n                ? part.data\n                : convertDataContentToBase64String(part.data),\n        });\n        break;\n      }\n    }\n  }\n\n  if (role === `tool`) {\n    return {\n      ...coreMessage,\n      content: roleContent[role],\n    };\n  }\n  if (role === `user`) {\n    return {\n      ...coreMessage,\n      content: roleContent[role],\n    };\n  }\n  if (role === `assistant`) {\n    return {\n      ...coreMessage,\n      content: roleContent[role],\n    };\n  }\n\n  throw new Error(\n    `Encountered unknown role ${role} when converting V4 CoreMessage -> V4 LanguageModelV1Prompt, input message: ${JSON.stringify(coreMessage, null, 2)}`,\n  );\n}\n\n/**\n * Convert an AI SDK V5 ModelMessage to a V2 LanguageModel prompt message.\n * Used for creating LLM prompt messages without AI SDK streamText/generateText.\n */\nexport function aiV5ModelMessageToV2PromptMessage(modelMessage: AIV5Type.ModelMessage): AIV5LanguageModelV2Message {\n  if (modelMessage.role === `system`) {\n    return modelMessage;\n  }\n\n  if (typeof modelMessage.content === `string` && (modelMessage.role === `assistant` || modelMessage.role === `user`)) {\n    return {\n      role: modelMessage.role,\n      content: [{ type: 'text', text: modelMessage.content }],\n      providerOptions: modelMessage.providerOptions,\n    };\n  }\n\n  if (typeof modelMessage.content === `string`) {\n    throw new Error(\n      `Saw text content for input ModelMessage, but the role is ${modelMessage.role}. This is only allowed for \"system\", \"assistant\", and \"user\" roles.`,\n    );\n  }\n\n  const roleContent: {\n    user: Extract<AIV5LanguageModelV2Message, { role: 'user' }>['content'];\n    assistant: Extract<AIV5LanguageModelV2Message, { role: 'assistant' }>['content'];\n    tool: Extract<AIV5LanguageModelV2Message, { role: 'tool' }>['content'];\n  } = {\n    user: [],\n    assistant: [],\n    tool: [],\n  };\n\n  const role = modelMessage.role;\n\n  for (const part of modelMessage.content) {\n    const incompatibleMessage = `Saw incompatible message content part type ${part.type} for message role ${role}`;\n\n    switch (part.type) {\n      case 'text': {\n        if (role === `tool`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push(part);\n        break;\n      }\n\n      case 'reasoning': {\n        if (role === `tool` || role === `user`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push(part);\n        break;\n      }\n\n      case 'tool-call': {\n        if (role !== `assistant`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          toolName: sanitizeToolName(part.toolName),\n        });\n        break;\n      }\n\n      case 'tool-result': {\n        if (role === `user`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          toolName: sanitizeToolName(part.toolName),\n        });\n        break;\n      }\n\n      case 'file': {\n        if (role === `tool`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          data: part.data instanceof ArrayBuffer ? new Uint8Array(part.data) : part.data,\n        });\n        break;\n      }\n\n      case 'image': {\n        if (role === `tool`) {\n          throw new Error(incompatibleMessage);\n        }\n        roleContent[role].push({\n          ...part,\n          mediaType: part.mediaType || 'image/unknown',\n          type: 'file',\n          data: part.image instanceof ArrayBuffer ? new Uint8Array(part.image) : part.image,\n        });\n        break;\n      }\n    }\n  }\n\n  if (role === `tool`) {\n    return {\n      ...modelMessage,\n      content: roleContent[role],\n    };\n  }\n  if (role === `user`) {\n    return {\n      ...modelMessage,\n      content: roleContent[role],\n    };\n  }\n  if (role === `assistant`) {\n    return {\n      ...modelMessage,\n      content: roleContent[role],\n    };\n  }\n\n  throw new Error(\n    `Encountered unknown role ${role} when converting V5 ModelMessage -> V5 LanguageModelV2Message, input message: ${JSON.stringify(modelMessage, null, 2)}`,\n  );\n}\n\n/**\n * Convert tool-result `media` parts in a V2 (AI SDK v5 / spec `v2`) prompt\n * using a caller-provided target content-part shape.\n *\n * Mastra's `toModelOutput` and the vendored AI SDK v5 use `{ type: 'media' }`\n * as the authored multimodal tool-result content type. Newer AI SDK provider\n * specs use different content-part shapes, so callers provide the target\n * conversion for their provider spec.\n */\nfunction convertToolResultContent(\n  prompt: LanguageModelV2Prompt,\n  convertMediaPart: (contentPart: Record<string, unknown>, mediaType: string) => unknown,\n): LanguageModelV2Prompt {\n  return prompt.map(message => {\n    if (message.role !== `tool`) return message;\n\n    let messageModified = false;\n    const content = message.content.map(part => {\n      if (part.type !== `tool-result`) return part;\n      const output = part.output as { type?: unknown; value?: unknown } | undefined;\n      if (!output || output.type !== `content` || !Array.isArray(output.value)) return part;\n\n      let outputModified = false;\n      const value = (output.value as unknown[]).map(item => {\n        if (item == null || typeof item !== `object`) return item;\n        const contentPart = item as Record<string, unknown>;\n        if (contentPart.type !== `media` || typeof contentPart.data !== `string`) return item;\n        outputModified = true;\n        const mediaType = typeof contentPart.mediaType === `string` ? contentPart.mediaType : ``;\n        return convertMediaPart(contentPart, mediaType);\n      });\n\n      if (!outputModified) return part;\n      messageModified = true;\n      return { ...part, output: { ...output, value } };\n    });\n\n    return messageModified ? { ...message, content } : message;\n  }) as LanguageModelV2Prompt;\n}\n\n/**\n * Convert v5-authored media tool results to the `image-data`/`file-data` shape\n * expected only by AI SDK v6 (`v3`) providers. V5 providers accept `media`, and\n * V7 providers expect `file` parts with tagged data instead.\n *\n * See: https://github.com/mastra-ai/mastra/issues/17876\n */\nexport function aiV5PromptToAIV6Prompt(prompt: LanguageModelV2Prompt): LanguageModelV2Prompt {\n  return convertToolResultContent(prompt, (contentPart, mediaType) =>\n    mediaType.startsWith(`image/`)\n      ? { type: `image-data`, data: contentPart.data, mediaType }\n      : { type: `file-data`, data: contentPart.data, mediaType },\n  );\n}\n\nexport function aiV5PromptToAIV7Prompt(prompt: LanguageModelV2Prompt): LanguageModelV2Prompt {\n  return convertToolResultContent(prompt, (contentPart, mediaType) => ({\n    type: `file`,\n    data: { type: `data`, data: contentPart.data },\n    mediaType,\n  }));\n}\n","import type { CoreMessage as CoreMessageV4 } from '@internal/ai-sdk-v4';\n\nimport { CacheKeyGenerator } from '../cache/CacheKeyGenerator';\nimport { TypeDetector } from '../detection/TypeDetector';\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","import type { MastraDBMessage, MastraMessagePart, MessageSource } from '../state/types';\n\nexport function stampPart<T extends MastraMessagePart>(part: T): T {\n  if (part.createdAt == null) {\n    part.createdAt = Date.now();\n  }\n\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","import type { CoreMessage as CoreMessageV4, UIMessage as UIMessageV4 } from '@internal/ai-sdk-v4';\n\nimport { AIV4Adapter, AIV5Adapter, AIV6Adapter } from '../adapters';\nimport { TypeDetector } from '../detection/TypeDetector';\nimport type {\n  MastraDBMessage,\n  MastraMessageV1,\n  MessageSource,\n  MemoryInfo,\n  UIMessageWithMetadata,\n} 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(\n      AIV4Adapter.fromUIMessage(message as UIMessageV4 | UIMessageWithMetadata, context, messageSource),\n      messageSource,\n    );\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  // 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 { getResponseProviderItemKey } from '../utils/response-item-metadata';\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 * 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(\n        p =>\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      // 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 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        // 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              output: (() => {\n                const o = part.output;\n                if (o == null || typeof o !== 'object') return o;\n                const obj = o as Record<string, unknown>;\n                // Preserve { type: 'content', value: [...] } — this is the AI SDK's\n                // native multimodal tool result shape. Unwrapping it here causes\n                // convertToModelMessages to receive a raw array which gets stringified.\n                // See: https://github.com/mastra-ai/mastra/issues/17876\n                if (obj.type === 'content' && Array.isArray(obj.value)) return o;\n                // For other wrapped shapes (legacy), unwrap as before\n                if ('value' in obj) return obj.value;\n                return o;\n              })(),\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 */\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: 'image-data', 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: 'file-data', 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\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 * 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  for (const uiMsg of preprocessed) {\n    const produced = AIV5.convertToModelMessages([uiMsg]);\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    converted.push(...produced);\n  }\n\n  const withFileMetadata = restoreAssistantFileProviderMetadata(converted, 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  ): 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);\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  ): AIV5Type.StepResult<any>['content'] {\n    // For tool-only steps without step-start markers, we need different logic\n    // Each tool part represents a complete step (tool call + result)\n    const toolParts = uiMessagesParts.filter(p => p.type?.startsWith('tool-'));\n    const hasStepStart = stepBoundaries.length > 0;\n\n    if (!hasStepStart && toolParts.length > 0) {\n      // No step-start markers but we have tool parts\n      // Each tool part is a separate step, so return only the last tool\n      const lastToolPart = toolParts[toolParts.length - 1];\n      if (!lastToolPart) {\n        return [];\n      }\n      const lastToolIndex = uiMessagesParts.indexOf(lastToolPart);\n      const previousToolPart = toolParts[toolParts.length - 2];\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 } from '../utils/stamp-part';\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    if (\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          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            // 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              rawInput: part.toolInvocation.rawInput,\n              args: {\n                ...existingCallPart.toolInvocation.args,\n                ...part.toolInvocation.args,\n              },\n            };\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    // 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 = CacheKeyGenerator.fromDBParts([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        // Insert at proportional position\n        const insertAt = leftAnchorLatest + offset;\n\n        const rightAnchorLatest =\n          rightAnchorV2 !== -1 ? anchorMap.get(rightAnchorV2)! : latestMessage.content.parts.length;\n\n        if (\n          insertAt >= 0 &&\n          insertAt <= rightAnchorLatest &&\n          !latestMessage.content.parts\n            .slice(insertAt, rightAnchorLatest)\n            .some(p => CacheKeyGenerator.fromDBParts([p]) === CacheKeyGenerator.fromDBParts([part]))\n        ) {\n          MessageMerger.pushNewPart({\n            latestMessage,\n            newMessage: incomingMessage,\n            part,\n            insertAt,\n          });\n          for (const [v2Idx, latestIdx] of anchorMap.entries()) {\n            if (latestIdx >= insertAt) {\n              anchorMap.set(v2Idx, latestIdx + 1);\n            }\n          }\n        }\n      } else {\n        MessageMerger.pushNewPart({\n          latestMessage,\n          newMessage: incomingMessage,\n          part,\n        });\n      }\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  }: {\n    latestMessage: MastraDBMessage;\n    newMessage: MastraDBMessage;\n    part: MastraMessageContentV2['parts'][number];\n    insertAt?: number;\n  }): void {\n    const partKey = CacheKeyGenerator.fromDBParts([part]);\n    const latestPartCount = latestMessage.content.parts.filter(\n      p => CacheKeyGenerator.fromDBParts([p]) === partKey,\n    ).length;\n    const newPartCount = newMessage.content.parts.filter(p => CacheKeyGenerator.fromDBParts([p]) === partKey).length;\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 before text parts when merging assistant messages\n      // Only add after tool invocations, and only if the incoming message doesn't already have step-start\n      const partIndex = newMessage.content.parts.indexOf(part);\n      const hasStepStartBefore = partIndex > 0 && newMessage.content.parts[partIndex - 1]?.type === 'step-start';\n\n      const needsStepStart =\n        latestMessage.role === 'assistant' &&\n        part.type === 'text' &&\n        !hasStepStartBefore &&\n        latestMessage.content.parts.length > 0 &&\n        latestMessage.content.parts.at(-1)?.type === 'tool-invocation';\n\n      const previousStepStart = [...latestMessage.content.parts].reverse().find(p => p.type === 'step-start');\n      const stepStartPart = previousStepStart?.model\n        ? stampPart({\n            type: 'step-start' as const,\n            model: previousStepStart.model,\n          })\n        : ({ type: 'step-start' as const } as MastraMessageContentV2['parts'][number]);\n\n      if (typeof insertAt === 'number') {\n        if (needsStepStart) {\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 (needsStepStart) {\n          latestMessage.content.parts.push(stepStartPart);\n        }\n        latestMessage.content.parts.push(part);\n      }\n    }\n  }\n}\n","import { convertBase64ToUint8Array } from '@ai-sdk/provider-utils-v5';\n\nexport const imageMediaTypeSignatures = [\n  {\n    mediaType: 'image/gif' as const,\n    bytesPrefix: [0x47, 0x49, 0x46],\n    base64Prefix: 'R0lG',\n  },\n  {\n    mediaType: 'image/png' as const,\n    bytesPrefix: [0x89, 0x50, 0x4e, 0x47],\n    base64Prefix: 'iVBORw',\n  },\n  {\n    mediaType: 'image/jpeg' as const,\n    bytesPrefix: [0xff, 0xd8],\n    base64Prefix: '/9j/',\n  },\n  {\n    mediaType: 'image/webp' as const,\n    bytesPrefix: [0x52, 0x49, 0x46, 0x46],\n    base64Prefix: 'UklGRg',\n  },\n  {\n    mediaType: 'image/bmp' as const,\n    bytesPrefix: [0x42, 0x4d],\n    base64Prefix: 'Qk',\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x49, 0x49, 0x2a, 0x00],\n    base64Prefix: 'SUkqAA',\n  },\n  {\n    mediaType: 'image/tiff' as const,\n    bytesPrefix: [0x4d, 0x4d, 0x00, 0x2a],\n    base64Prefix: 'TU0AKg',\n  },\n  {\n    mediaType: 'image/avif' as const,\n    bytesPrefix: [0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66],\n    base64Prefix: 'AAAAIGZ0eXBhdmlm',\n  },\n  {\n    mediaType: 'image/heic' as const,\n    bytesPrefix: [0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63],\n    base64Prefix: 'AAAAIGZ0eXBoZWlj',\n  },\n] as const;\n\nexport const audioMediaTypeSignatures = [\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfb],\n    base64Prefix: '//s=',\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xfa],\n    base64Prefix: '//o=',\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf3],\n    base64Prefix: '//M=',\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xf2],\n    base64Prefix: '//I=',\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe3],\n    base64Prefix: '/+M=',\n  },\n  {\n    mediaType: 'audio/mpeg' as const,\n    bytesPrefix: [0xff, 0xe2],\n    base64Prefix: '/+I=',\n  },\n  {\n    mediaType: 'audio/wav' as const,\n    bytesPrefix: [0x52, 0x49, 0x46, 0x46],\n    base64Prefix: 'UklGR',\n  },\n  {\n    mediaType: 'audio/ogg' as const,\n    bytesPrefix: [0x4f, 0x67, 0x67, 0x53],\n    base64Prefix: 'T2dnUw',\n  },\n  {\n    mediaType: 'audio/flac' as const,\n    bytesPrefix: [0x66, 0x4c, 0x61, 0x43],\n    base64Prefix: 'ZkxhQw',\n  },\n  {\n    mediaType: 'audio/aac' as const,\n    bytesPrefix: [0x40, 0x15, 0x00, 0x00],\n    base64Prefix: 'QBUA',\n  },\n  {\n    mediaType: 'audio/mp4' as const,\n    bytesPrefix: [0x66, 0x74, 0x79, 0x70],\n    base64Prefix: 'ZnR5cA',\n  },\n  {\n    mediaType: 'audio/webm',\n    bytesPrefix: [0x1a, 0x45, 0xdf, 0xa3],\n    base64Prefix: 'GkXf',\n  },\n] as const;\n\nconst stripID3 = (data: Uint8Array | string) => {\n  const bytes = typeof data === 'string' ? convertBase64ToUint8Array(data) : data;\n  const id3Size =\n    // @ts-expect-error - bytes array access\n    ((bytes[6] & 0x7f) << 21) |\n    // @ts-expect-error - bytes array access\n    ((bytes[7] & 0x7f) << 14) |\n    // @ts-expect-error - bytes array access\n    ((bytes[8] & 0x7f) << 7) |\n    // @ts-expect-error - bytes array access\n    (bytes[9] & 0x7f);\n\n  // The raw MP3 starts here\n  return bytes.slice(id3Size + 10);\n};\n\nfunction stripID3TagsIfPresent(data: Uint8Array | string): Uint8Array | string {\n  const hasId3 =\n    (typeof data === 'string' && data.startsWith('SUQz')) ||\n    (typeof data !== 'string' &&\n      data.length > 10 &&\n      data[0] === 0x49 && // 'I'\n      data[1] === 0x44 && // 'D'\n      data[2] === 0x33); // '3'\n\n  return hasId3 ? stripID3(data) : data;\n}\n\nexport function detectMediaType({\n  data,\n  signatures,\n}: {\n  data: Uint8Array | string;\n  signatures: typeof audioMediaTypeSignatures | typeof imageMediaTypeSignatures;\n}): (typeof signatures)[number]['mediaType'] | undefined {\n  const processedData = stripID3TagsIfPresent(data);\n\n  for (const signature of signatures) {\n    if (\n      typeof processedData === 'string'\n        ? processedData.startsWith(signature.base64Prefix)\n        : processedData.length >= signature.bytesPrefix.length &&\n          signature.bytesPrefix.every((byte, index) => processedData[index] === byte)\n    ) {\n      return signature.mediaType;\n    }\n  }\n\n  return undefined;\n}\n","import type { DataContent, ImagePart, FilePart } from '@ai-sdk/provider-utils-v5';\nimport type { LanguageModelV2FilePart, LanguageModelV2TextPart } from '@ai-sdk/provider-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-v5';\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  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      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\nexport async function downloadAssetsFromMessages({\n  messages,\n  downloadConcurrency = 10,\n  downloadRetries = 3,\n  supportedUrls,\n}: {\n  messages: AIV5Type.ModelMessage[];\n  downloadConcurrency?: number;\n  downloadRetries?: number;\n  supportedUrls?: Record<string, RegExp[]>;\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      let data = part.type === 'image' ? part.image : part.data;\n      if (typeof data === 'string') {\n        try {\n          data = new URL(data);\n        } catch {}\n      }\n\n      return { mediaType, data };\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      if (fileItem.isUrlSupportedByModel) {\n        return null;\n      }\n      return {\n        url: fileItem.url.toString(),\n        ...(await downloadFromUrl({ url: fileItem.url, downloadRetries })),\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 './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","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 { getTransformedToolPayload, hasTransformedToolPayload } from '../../tools/payload-transform';\nimport type { IdGeneratorContext } from '../../types';\nimport { createSignal, isCreatedAgentSignal, 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 { TypeDetector } from './detection/TypeDetector';\nimport { MessageMerger } from './merge';\nimport { convertImageFilePart } from './prompt/convert-file';\nimport { convertToV1Messages } from './prompt/convert-to-mastra-v1';\nimport { downloadAssetsFromMessages } from './prompt/download-assets';\nimport { MessageStateManager } from './state';\nimport type {\n  MastraDBMessage,\n  MastraMessagePart,\n  MastraMessageV1,\n  MessageSource,\n  MemoryInfo,\n  UIMessageWithMetadata,\n  SerializedMessageListState,\n} from './state';\nimport type { AIV5Type, AIV5ResponseMessage, AIV6Type, MessageInput, MessageListInput } from './types';\nimport { ensureGeminiCompatibleMessages } from './utils/provider-compat';\nimport { stampPart } from './utils/stamp-part';\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\ntype MessageListAddOptions = {\n  merge?: boolean;\n};\n\nexport class MessageList {\n  private messages: MastraDBMessage[] = [];\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  // 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  private generateMessageId?: (context?: IdGeneratorContext) => string;\n  private _agentNetworkAppend = false;\n  private filterIncompleteToolCalls: boolean;\n  private logger?: IMastraLogger;\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 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   */\n  public startRecording(): void {\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(): 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    this.isRecording = false;\n    const events = this.getRecordedEvents();\n    this.recordedEvents = [];\n    return events;\n  }\n\n  public addSignal(signal: CreatedAgentSignal, options?: { source?: MessageSource }): CreatedAgentSignal {\n    const source = options?.source ?? 'input';\n    const createdAt = 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      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    this.addOne(signalForTranscript.toDBMessage(this.memoryInfo ?? undefined), source);\n    return signalForTranscript;\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    if (this.isRecording) {\n      this.recordedEvents.push({\n        type: 'add',\n        source: messageSource,\n        count: messageArray.length,\n      });\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    return this;\n  }\n\n  public serialize(): SerializedMessageListState {\n    return 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  }\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    for (const message of this.messages) {\n      this.updateLastCreatedAt(message);\n    }\n    return this;\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  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  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 (this.isRecording && allMessages.length > 0) {\n            this.recordedEvents.push({\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 (this.isRecording && userMessages.length > 0) {\n            this.recordedEvents.push({\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 (this.isRecording && responseMessages.length > 0) {\n            this.recordedEvents.push({\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   * @returns Array of removed messages\n   */\n  public removeByIds(ids: string[]): MastraDBMessage[] {\n    const idsSet = new Set(ids);\n    const removed: MastraDBMessage[] = [];\n    this.messages = this.messages.filter(m => {\n      if (idsSet.has(m.id)) {\n        removed.push(m);\n        this.stateManager.removeMessage(m);\n        return false;\n      }\n      return true;\n    });\n    if (this.isRecording && removed.length > 0) {\n      this.recordedEvents.push({\n        type: 'removeByIds',\n        ids,\n        count: removed.length,\n      });\n    }\n    return removed;\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        const messages = [...systemMessages, ...modelMessages];\n\n        return ensureGeminiCompatibleMessages(messages, this.logger);\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          downloadConcurrency: 10,\n          downloadRetries: 3,\n        },\n      ): Promise<LanguageModelV2Prompt> => {\n        const promptMessages = this.getMessagesForModelPrompt();\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              // Key off the value, not its presence: a nullish `modelOutput` means the tool's\n              // toModelOutput opted out of mapping, so the raw result must be kept. Keying off\n              // presence would blank out `output` on the tool message sent to the provider.\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                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        const downloadedAssets = await downloadAssetsFromMessages({\n          messages: modelMessages,\n          downloadConcurrency: options?.downloadConcurrency,\n          downloadRetries: options?.downloadRetries,\n          supportedUrls: options?.supportedUrls,\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                    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 = ensureGeminiCompatibleMessages(messages, this.logger);\n\n        return messages\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      }): 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      }): 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        const messages = [...this.systemMessages, ...Object.values(this.taggedSystemMessages).flat(), ...coreMessages];\n\n        return ensureGeminiCompatibleMessages(messages, this.logger);\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        let messages = [...systemMessages, ...coreMessages];\n\n        messages = ensureGeminiCompatibleMessages(messages, this.logger);\n\n        return messages.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): 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          );\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  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  public drainUnsavedMessages(): MastraDBMessage[] {\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 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        const outputTransform =\n          part.toolInvocation.state === 'result'\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 transformedErrorText =\n          part.toolInvocation.state === 'output-error'\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' ? { errorText: transformedErrorText } : {}),\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' ? { errorText: transformedErrorText } : {}),\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' && transformed.result !== undefined ? { result: transformed.result } : {}),\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      this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, Date.now());\n      this.updateLastCreatedAt(msg);\n\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   * 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    const mergedProviderMetadata =\n      originalPart.providerMetadata !== undefined || inputPartWithMeta.providerMetadata !== undefined\n        ? ({\n            ...((originalPart.providerMetadata ?? {}) as Record<string, Record<string, AIV5Type.JSONValue>>),\n            ...((inputPartWithMeta.providerMetadata ?? {}) as Record<string, Record<string, AIV5Type.JSONValue>>),\n          } as AIV5Type.ProviderMetadata)\n        : undefined;\n\n    msg.content.parts![i] = {\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      ...(mergedProviderMetadata !== undefined ? { providerMetadata: mergedProviderMetadata } : {}),\n    };\n    this.lastCreatedAt = Math.max(this.lastCreatedAt || 0, Date.now());\n    this.updateLastCreatedAt(msg);\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    if (Array.isArray(msg.content.toolInvocations) && inputPart.toolInvocation.state === 'result') {\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    // Move the message to the response source so it gets\n    // picked up by drainUnsavedMessages for re-saving.\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    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    // Don't add a duplicate step-start\n    const lastPart = lastMsg.content.parts[lastMsg.content.parts.length - 1];\n    if (lastPart?.type === 'step-start') {\n      return false;\n    }\n\n    lastMsg.content.parts.push(stampPart({ type: 'step-start' as const }));\n\n    // Ensure the mutated message is persisted\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  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      if (this.isRecording) {\n        this.recordedEvents.push({\n          type: 'addSystem',\n          tag,\n          message: coreMessage,\n        });\n      }\n    } else if (!tag && !this.isDuplicateSystem(coreMessage)) {\n      this.systemMessages.push(coreMessage);\n      if (this.isRecording) {\n        this.recordedEvents.push({\n          type: 'addSystem',\n          message: coreMessage,\n        });\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 getMessageById(id: string) {\n    return this.messages.find(m => m.id === id);\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 latestSealedIndex = this.messages.findLastIndex(message => MessageMerger.isSealed(message));\n    const latestMessage = this.messages.at(-1);\n    const latestMessageIndex = this.messages.length - 1;\n    const latestMessageIsAfterSealedBoundary = latestSealedIndex === -1 || latestMessageIndex > latestSealedIndex;\n\n    if (messageSource === `memory`) {\n      for (const existingMessage of this.messages) {\n        // don't double store any messages\n        if (messagesAreEqual(existingMessage, messageV2)) {\n          return;\n        }\n      }\n    }\n\n    const replacementTarget = exists && id ? this.messages.find(m => m.id === id) : undefined;\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    const isLatestFromMemory = latestMessage ? this.memoryMessages.has(latestMessage) : false;\n    const shouldMerge =\n      options.merge !== false &&\n      latestMessageIsAfterSealedBoundary &&\n      !hasSealedReplacementTarget &&\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        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.messages.push(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.messages.push(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.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n            return this;\n          }\n          this.messages[existingIndex] = messageV2;\n        }\n      } else if (!exists) {\n        this.messages.push(messageV2);\n      }\n\n      this.pushMessageToSource(messageV2, messageSource);\n    }\n\n    for (const storedMessage of this.messages) {\n      this.updateLastCreatedAt(storedMessage);\n    }\n\n    // make sure messages are always stored in order of when they were created!\n    this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\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  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":";;;;;;;;;;;;;;;;;;;;;;;;AAgCA,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,OAAO,aAAa,kBAAkB,GAAG,KAAK,aAAa,kBAAkB,GAAG;CAClF;;;;CAKA,OAAO,gBAAgB,KAAuC;EAC5D,OACE,CAAC,aAAa,gBAAgB,GAAG,KACjC,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