{"version":3,"sources":["../src/convert-to-built-in-ai-messages.ts","../src/tool-calling/format-tool-results.ts","../src/tool-calling/build-json-system-prompt.ts","../src/tool-calling/parse-json-function-calls.ts","../src/utils/warnings.ts","../src/utils/prompt-utils.ts","../src/utils/tool-utils.ts","../src/models/session-manager.ts","../src/streaming/tool-call-detector.ts","../src/built-in-ai-language-model.ts","../src/built-in-ai-embedding-model.ts","../src/built-in-ai-provider.ts"],"sourcesContent":["import {\n  LanguageModelV3Prompt,\n  LanguageModelV3ToolCallPart,\n  LanguageModelV3ToolResultPart,\n  LanguageModelV3ToolResultOutput,\n  UnsupportedFunctionalityError,\n} from \"@ai-sdk/provider\";\nimport { formatToolResults } from \"./tool-calling/format-tool-results\";\nimport type { ToolResult } from \"./tool-calling/types\";\nexport interface ConvertedMessages {\n  systemMessage?: string;\n  messages: LanguageModelMessage[];\n}\n\n/**\n * Convert base64 string to Uint8Array for built-in AI compatibility\n * Built-in AI supports BufferSource (including Uint8Array) for image/audio data\n */\nfunction convertBase64ToUint8Array(base64: string): Uint8Array {\n  try {\n    const binaryString = atob(base64);\n    const bytes = new Uint8Array(binaryString.length);\n    for (let i = 0; i < binaryString.length; i++) {\n      bytes[i] = binaryString.charCodeAt(i);\n    }\n    return bytes;\n  } catch (error) {\n    throw new Error(`Failed to convert base64 to Uint8Array: ${error}`);\n  }\n}\n\n/**\n * Convert file data to the appropriate format for built-in AI\n * Built-in AI supports: Blob, BufferSource (Uint8Array), URLs\n */\nfunction convertFileData(\n  data: URL | Uint8Array | string,\n  mediaType: string,\n): Uint8Array | string {\n  // Handle different data types from Vercel AI SDK\n  if (data instanceof URL) {\n    // URLs - keep as string (if supported by provider)\n    return data.toString();\n  }\n\n  if (data instanceof Uint8Array) {\n    // Already in correct format\n    return data;\n  }\n\n  if (typeof data === \"string\") {\n    // Base64 string from AI SDK - convert to Uint8Array\n    return convertBase64ToUint8Array(data);\n  }\n\n  // Exhaustive check - this should never happen with the union type\n  const exhaustiveCheck: never = data;\n  throw new Error(`Unexpected data type for ${mediaType}: ${exhaustiveCheck}`);\n}\n\nfunction normalizeToolArguments(input: unknown): unknown {\n  if (input === undefined) {\n    return {};\n  }\n\n  if (typeof input === \"string\") {\n    try {\n      return JSON.parse(input);\n    } catch {\n      return input;\n    }\n  }\n\n  return input ?? {};\n}\n\nfunction formatToolCallsJson(parts: LanguageModelV3ToolCallPart[]): string {\n  if (!parts.length) {\n    return \"\";\n  }\n\n  const payloads = parts.map((call) => {\n    const payload: Record<string, unknown> = {\n      name: call.toolName,\n      arguments: normalizeToolArguments(call.input),\n    };\n\n    if (call.toolCallId) {\n      payload.id = call.toolCallId;\n    }\n\n    return JSON.stringify(payload);\n  });\n\n  return `\\`\\`\\`tool_call\n${payloads.join(\"\\n\")}\n\\`\\`\\``;\n}\n\nfunction convertToolResultOutput(output: LanguageModelV3ToolResultOutput): {\n  value: unknown;\n  isError: boolean;\n} {\n  switch (output.type) {\n    case \"text\":\n      return { value: output.value, isError: false };\n    case \"json\":\n      return { value: output.value, isError: false };\n    case \"error-text\":\n      return { value: output.value, isError: true };\n    case \"error-json\":\n      return { value: output.value, isError: true };\n    case \"content\":\n      return { value: output.value, isError: false };\n    case \"execution-denied\":\n      return { value: output.reason, isError: true };\n    default: {\n      const exhaustiveCheck: never = output;\n      return { value: exhaustiveCheck, isError: false };\n    }\n  }\n}\n\nfunction toToolResult(part: LanguageModelV3ToolResultPart): ToolResult {\n  const { value, isError } = convertToolResultOutput(part.output);\n  return {\n    toolCallId: part.toolCallId,\n    toolName: part.toolName,\n    result: value,\n    isError,\n  };\n}\n\n/**\n * Convert Vercel AI SDK prompt format to built-in AI Prompt API format\n * Returns system message (for initialPrompts) and regular messages (for prompt method)\n */\nexport function convertToBuiltInAIMessages(\n  prompt: LanguageModelV3Prompt,\n): ConvertedMessages {\n  const normalizedPrompt = prompt.slice();\n\n  let systemMessage: string | undefined;\n  const messages: LanguageModelMessage[] = [];\n\n  for (const message of normalizedPrompt) {\n    switch (message.role) {\n      case \"system\": {\n        // There's only ever one system message from AI SDK\n        systemMessage = message.content;\n        break;\n      }\n\n      case \"user\": {\n        messages.push({\n          role: \"user\",\n          content: message.content.map((part) => {\n            switch (part.type) {\n              case \"text\": {\n                return {\n                  type: \"text\",\n                  value: part.text,\n                } as LanguageModelMessageContent;\n              }\n\n              case \"file\": {\n                const { mediaType, data } = part;\n\n                if (mediaType?.startsWith(\"image/\")) {\n                  const convertedData = convertFileData(data, mediaType);\n\n                  return {\n                    type: \"image\",\n                    value: convertedData,\n                  } as LanguageModelMessageContent;\n                } else if (mediaType?.startsWith(\"audio/\")) {\n                  const convertedData = convertFileData(data, mediaType);\n\n                  return {\n                    type: \"audio\",\n                    value: convertedData,\n                  } as LanguageModelMessageContent;\n                } else {\n                  throw new UnsupportedFunctionalityError({\n                    functionality: `file type: ${mediaType}`,\n                  });\n                }\n              }\n\n              default: {\n                const exhaustiveCheck: never = part;\n                throw new UnsupportedFunctionalityError({\n                  functionality: `content type: ${(exhaustiveCheck as { type?: string }).type ?? \"unknown\"}`,\n                });\n              }\n            }\n          }),\n        } as LanguageModelMessage);\n        break;\n      }\n\n      case \"assistant\": {\n        let text = \"\";\n        const toolCallParts: LanguageModelV3ToolCallPart[] = [];\n\n        for (const part of message.content) {\n          switch (part.type) {\n            case \"text\": {\n              text += part.text;\n              break;\n            }\n            case \"reasoning\": {\n              text += part.text;\n              break;\n            }\n            case \"tool-call\": {\n              toolCallParts.push(part);\n              break;\n            }\n            case \"file\": {\n              throw new UnsupportedFunctionalityError({\n                functionality: \"assistant file attachments\",\n              });\n            }\n            case \"tool-result\": {\n              throw new UnsupportedFunctionalityError({\n                functionality:\n                  \"tool-result parts in assistant messages (should be in tool messages)\",\n              });\n            }\n            default: {\n              const exhaustiveCheck: never = part;\n              throw new UnsupportedFunctionalityError({\n                functionality: `assistant part type: ${(exhaustiveCheck as { type?: string }).type ?? \"unknown\"}`,\n              });\n            }\n          }\n        }\n\n        const toolCallJson = formatToolCallsJson(toolCallParts);\n        const contentSegments: string[] = [];\n\n        if (text.trim().length > 0) {\n          contentSegments.push(text);\n        } else if (text.length > 0) {\n          // preserve purely whitespace responses so we don't lose formatting\n          contentSegments.push(text);\n        }\n\n        if (toolCallJson) {\n          contentSegments.push(toolCallJson);\n        }\n\n        const content =\n          contentSegments.length > 0 ? contentSegments.join(\"\\n\") : \"\";\n\n        messages.push({\n          role: \"assistant\",\n          content,\n        } as LanguageModelMessage);\n        break;\n      }\n\n      case \"tool\": {\n        const toolParts = message.content as LanguageModelV3ToolResultPart[];\n        const results: ToolResult[] = toolParts.map(toToolResult);\n        const toolResultsJson = formatToolResults(results);\n\n        messages.push({\n          role: \"user\",\n          content: toolResultsJson,\n        } as LanguageModelMessage);\n        break;\n      }\n\n      default: {\n        const exhaustiveCheck: never = message;\n        throw new Error(\n          `Unsupported role: ${(exhaustiveCheck as { role?: string }).role ?? \"unknown\"}`,\n        );\n      }\n    }\n  }\n\n  return { systemMessage, messages };\n}\n","import type { ToolResult } from \"./types\";\n\n/**\n * Builds a JSON-serializable payload for a single tool result.\n * Includes tool name, result data, error flag, and optional call ID.\n *\n * @param result - The tool execution result to format\n * @returns Object containing formatted result data ready for JSON serialization\n */\nfunction buildResultPayload(result: ToolResult): Record<string, unknown> {\n  const payload: Record<string, unknown> = {\n    name: result.toolName,\n    result: result.result ?? null,\n    error: Boolean(result.isError),\n  };\n\n  if (result.toolCallId) {\n    payload.id = result.toolCallId;\n  }\n\n  return payload;\n}\n\n/**\n * Formats tool execution results as JSON for continuation in the conversation.\n *\n * Each result is serialized as a single JSON object. Multiple results (for parallel\n * execution scenarios) are emitted on separate lines within a ```tool_result code fence.\n *\n * @param results - Array of tool execution results to format\n * @returns Formatted string with results in tool_result code fence, or empty string if no results\n * @example\n * ```typescript\n * formatToolResults([\n *   { toolCallId: \"call_123\", toolName: \"search\", result: { data: \"...\" } }\n * ])\n * // Returns: ```tool_result\\n{\"id\":\"call_123\",\"name\":\"search\",\"result\":{...},\"error\":false}\\n```\n * ```\n */\nexport function formatToolResults(results: ToolResult[]): string {\n  if (!results || results.length === 0) {\n    return \"\";\n  }\n\n  const payloads = results.map((result) =>\n    JSON.stringify(buildResultPayload(result)),\n  );\n\n  return `\\`\\`\\`tool_result\n${payloads.join(\"\\n\")}\n\\`\\`\\``;\n}\n\n/**\n * Formats a single tool result.\n * Convenience wrapper around formatToolResults for single result scenarios.\n *\n * @param result - The tool execution result to format\n * @returns Formatted string with result in tool_result code fence\n */\nexport function formatSingleToolResult(result: ToolResult): string {\n  return formatToolResults([result]);\n}\n","import type {\n  JSONSchema7,\n  LanguageModelV3FunctionTool,\n} from \"@ai-sdk/provider\";\nimport type { ToolDefinition } from \"./types\";\n\n/**\n * Builds an enhanced system prompt for JSON-based tool calling.\n * The model receives JSON schemas and is expected to return JSON tool calls.\n *\n * @param originalSystemPrompt - The original system prompt (if any)\n * @param tools - Array of available tool definitions\n * @param options - Configuration options for tool calling behavior (unused, kept for backwards compatibility)\n * @returns Enhanced system prompt with JSON tool calling instructions\n */\nexport function buildJsonToolSystemPrompt(\n  originalSystemPrompt: string | undefined,\n  tools: Array<ToolDefinition | LanguageModelV3FunctionTool>,\n  options?: { allowParallelToolCalls?: boolean },\n): string {\n  if (!tools || tools.length === 0) {\n    return originalSystemPrompt || \"\";\n  }\n\n  const parallelInstruction =\n    \"Only request one tool call at a time. Wait for tool results before asking for another tool.\";\n\n  const toolSchemas = tools.map((tool) => {\n    const schema = getParameters(tool);\n    return {\n      name: tool.name,\n      description: tool.description ?? \"No description provided.\",\n      parameters: schema || { type: \"object\", properties: {} },\n    };\n  });\n\n  const toolsJson = JSON.stringify(toolSchemas, null, 2);\n\n  const instructionBody = `You are a helpful AI assistant with access to tools.\n\n# Available Tools\n${toolsJson}\n\n# Tool Calling Instructions\n${parallelInstruction}\n\nTo call a tool, output JSON in this exact format inside a \\`\\`\\`tool_call code fence:\n\n\\`\\`\\`tool_call\n{\"name\": \"tool_name\", \"arguments\": {\"param1\": \"value1\", \"param2\": \"value2\"}}\n\\`\\`\\`\n\nTool responses will be provided in \\`\\`\\`tool_result fences. Each line contains JSON like:\n\\`\\`\\`tool_result\n{\"id\": \"call_123\", \"name\": \"tool_name\", \"result\": {...}, \"error\": false}\n\\`\\`\\`\nUse the \\`result\\` payload (and treat \\`error\\` as a boolean flag) when continuing the conversation.\n\nImportant:\n- Use exact tool and parameter names from the schema above\n- Arguments must be a valid JSON object matching the tool's parameters\n- You can include brief reasoning before or after the tool call\n- If no tool is needed, respond directly without tool_call fences`;\n\n  if (originalSystemPrompt?.trim()) {\n    return `${originalSystemPrompt.trim()}\\n\\n${instructionBody}`;\n  }\n\n  return instructionBody;\n}\n\n/**\n * Extracts the parameters/input schema from a tool definition.\n * Handles both ToolDefinition (parameters field) and LanguageModelV3FunctionTool (inputSchema field).\n *\n * @param tool - The tool definition to extract parameters from\n * @returns The JSON Schema for the tool's parameters, or undefined if not present\n */\nfunction getParameters(\n  tool: ToolDefinition | LanguageModelV3FunctionTool,\n): JSONSchema7 | undefined {\n  if (\"parameters\" in tool) {\n    return tool.parameters;\n  }\n\n  return tool.inputSchema as JSONSchema7 | undefined;\n}\n","import type { ParsedResponse, ParsedToolCall } from \"./types\";\n\n/**\n * Regular expression to match JSON tool call code fences.\n * Matches blocks like ```tool_call or ```tool-call with content inside.\n */\nconst JSON_TOOL_CALL_FENCE_REGEX = /```tool[_-]?call\\s*([\\s\\S]*?)```/gi;\n\n/**\n * Generates a unique identifier for a tool call.\n * Uses timestamp and random string to ensure uniqueness.\n *\n * @returns A unique tool call ID in the format \"call_{timestamp}_{random}\"\n */\nfunction generateToolCallId(): string {\n  return `call_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;\n}\n\n/**\n * Parses JSON-formatted tool calls from model response.\n * Supports multiple formats:\n * 1. Single object: {\"name\": \"tool\", \"arguments\": {...}}\n * 2. Array: [{\"name\": \"tool1\", ...}, {\"name\": \"tool2\", ...}]\n * 3. Newline-separated objects:\n *    {\"name\": \"tool1\", \"arguments\": {...}}\n *    {\"name\": \"tool2\", \"arguments\": {...}}\n *\n * @param response - The model's response text to parse\n * @returns Object containing parsed tool calls and remaining text content\n */\nexport function parseJsonFunctionCalls(response: string): ParsedResponse {\n  const matches = Array.from(response.matchAll(JSON_TOOL_CALL_FENCE_REGEX));\n  JSON_TOOL_CALL_FENCE_REGEX.lastIndex = 0;\n\n  if (matches.length === 0) {\n    return { toolCalls: [], textContent: response };\n  }\n\n  const toolCalls: ParsedToolCall[] = [];\n  let textContent = response;\n\n  for (const match of matches) {\n    const [fullFence, innerContent] = match;\n    textContent = textContent.replace(fullFence, \"\");\n\n    try {\n      const trimmed = innerContent.trim();\n\n      // Try parsing as a single JSON value first (object or array)\n      try {\n        const parsed = JSON.parse(trimmed);\n        const callsArray = Array.isArray(parsed) ? parsed : [parsed];\n\n        for (const call of callsArray) {\n          if (!call.name) continue;\n\n          toolCalls.push({\n            type: \"tool-call\",\n            toolCallId: call.id || generateToolCallId(),\n            toolName: call.name,\n            args: call.arguments || {},\n          });\n        }\n      } catch {\n        // If single JSON parsing fails, try parsing as newline-separated JSON objects\n        const lines = trimmed.split(\"\\n\").filter((line) => line.trim());\n\n        for (const line of lines) {\n          try {\n            const call = JSON.parse(line.trim());\n            if (!call.name) continue;\n\n            toolCalls.push({\n              type: \"tool-call\",\n              toolCallId: call.id || generateToolCallId(),\n              toolName: call.name,\n              args: call.arguments || {},\n            });\n          } catch {\n            // Skip invalid JSON lines\n            continue;\n          }\n        }\n      }\n    } catch (error) {\n      console.warn(\"Failed to parse JSON tool call:\", error);\n      continue;\n    }\n  }\n\n  textContent = textContent.replace(/\\n{2,}/g, \"\\n\");\n\n  return { toolCalls, textContent: textContent.trim() };\n}\n\n/**\n * Checks if a response contains JSON-formatted tool calls.\n *\n * @param response - The model's response text to check\n * @returns true if the response contains tool call fences, false otherwise\n */\nexport function hasJsonFunctionCalls(response: string): boolean {\n  const hasMatch = JSON_TOOL_CALL_FENCE_REGEX.test(response);\n  JSON_TOOL_CALL_FENCE_REGEX.lastIndex = 0;\n  return hasMatch;\n}\n\n/**\n * Extracts the first JSON tool call code fence block from a response.\n *\n * @param response - The model's response text to extract from\n * @returns The first tool call fence block (including delimiters), or null if none found\n */\nexport function extractJsonFunctionCallsBlock(response: string): string | null {\n  const match = JSON_TOOL_CALL_FENCE_REGEX.exec(response);\n  JSON_TOOL_CALL_FENCE_REGEX.lastIndex = 0;\n  return match ? match[0] : null;\n}\n","/**\n * Warning generation utilities for unsupported settings and tools\n */\n\nimport type {\n  SharedV3Warning,\n  LanguageModelV3ProviderTool,\n} from \"@ai-sdk/provider\";\n\n/**\n * Creates a warning for an unsupported setting\n *\n * @param setting - Name of the setting that is not supported\n * @param details - Additional details about why it's not supported\n * @returns A call warning object\n *\n * @example\n * ```typescript\n * const warning = createUnsupportedSettingWarning(\n *   \"maxOutputTokens\",\n *   \"maxOutputTokens is not supported by Prompt API\"\n * );\n * ```\n */\nexport function createUnsupportedSettingWarning(\n  feature: string,\n  details: string,\n): SharedV3Warning {\n  return {\n    type: \"unsupported\",\n    feature,\n    details,\n  };\n}\n\n/**\n * Creates a warning for an unsupported tool type\n *\n * @param tool - The provider-defined tool that is not supported\n * @param details - Additional details about why it's not supported\n * @returns A call warning object\n *\n * @example\n * ```typescript\n * const warning = createUnsupportedToolWarning(\n *   providerTool,\n *   \"Only function tools are supported by the Prompt API polyfill\"\n * );\n * ```\n */\nexport function createUnsupportedToolWarning(\n  tool: LanguageModelV3ProviderTool,\n  details: string,\n): SharedV3Warning {\n  return {\n    type: \"unsupported\",\n    feature: `tool:${tool.name}`,\n    details,\n  };\n}\n\n/**\n * Gathers all warnings for unsupported call options\n *\n * @param options - The call options to check\n * @returns Array of warnings for any unsupported settings\n *\n * @example\n * ```typescript\n * const warnings = gatherUnsupportedSettingWarnings({\n *   maxOutputTokens: 100,\n *   topP: 0.9,\n *   temperature: 0.7,\n * });\n * // Returns warnings for maxOutputTokens and topP\n * ```\n */\nexport function gatherUnsupportedSettingWarnings(options: {\n  maxOutputTokens?: number;\n  stopSequences?: string[];\n  topP?: number;\n  presencePenalty?: number;\n  frequencyPenalty?: number;\n  seed?: number;\n  toolChoice?: unknown;\n}): SharedV3Warning[] {\n  const warnings: SharedV3Warning[] = [];\n\n  if (options.maxOutputTokens != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"maxOutputTokens\",\n        \"maxOutputTokens is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.stopSequences != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"stopSequences\",\n        \"stopSequences is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.topP != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"topP\",\n        \"topP is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.presencePenalty != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"presencePenalty\",\n        \"presencePenalty is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.frequencyPenalty != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"frequencyPenalty\",\n        \"frequencyPenalty is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.seed != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"seed\",\n        \"seed is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  if (options.toolChoice != null) {\n    warnings.push(\n      createUnsupportedSettingWarning(\n        \"toolChoice\",\n        \"toolChoice is not supported by Prompt API\",\n      ),\n    );\n  }\n\n  return warnings;\n}\n","/**\n * Utilities for prompt processing and transformation\n */\n\nimport type { LanguageModelV3Prompt } from \"@ai-sdk/provider\";\n\n/**\n * Detect if the prompt contains multimodal content (images, audio)\n *\n * @param prompt - The prompt to check\n * @returns true if the prompt contains any file content\n */\nexport function hasMultimodalContent(prompt: LanguageModelV3Prompt): boolean {\n  for (const message of prompt) {\n    if (message.role === \"user\") {\n      for (const part of message.content) {\n        if (part.type === \"file\") {\n          return true;\n        }\n      }\n    }\n  }\n  return false;\n}\n\n/**\n * Get expected inputs based on prompt content.\n * Analyzes the prompt to determine what types of inputs (text, image, audio) are used.\n * This information is used to configure the Prompt API session with the correct input capabilities.\n *\n * @param prompt - The prompt to analyze\n * @returns Array of expected input types for session creation (only includes image/audio, text is assumed)\n * @example\n * ```typescript\n * const inputs = getExpectedInputs(prompt);\n * // Returns: [{ type: \"image\" }] if prompt contains images\n * // Returns: [] if prompt only contains text\n * ```\n */\nexport function getExpectedInputs(\n  prompt: LanguageModelV3Prompt,\n): Array<{ type: \"text\" | \"image\" | \"audio\" }> {\n  const inputs = new Set<\"text\" | \"image\" | \"audio\">();\n  // Don't add text by default - it's assumed by the Prompt API\n\n  for (const message of prompt) {\n    if (message.role === \"user\") {\n      for (const part of message.content) {\n        if (part.type === \"file\") {\n          if (part.mediaType?.startsWith(\"image/\")) {\n            inputs.add(\"image\");\n          } else if (part.mediaType?.startsWith(\"audio/\")) {\n            inputs.add(\"audio\");\n          }\n        }\n      }\n    }\n  }\n\n  return Array.from(inputs).map((type) => ({ type }));\n}\n\n/**\n * Prepends a system prompt to the first user message in the conversation.\n *\n * This is necessary because the Prompt API doesn't support separate system messages,\n * so we inject the system prompt into the first user message instead.\n * Creates a shallow copy of messages to avoid mutating the original array.\n *\n * @param messages - The messages array to modify (not mutated, a copy is returned)\n * @param systemPrompt - The system prompt to prepend\n * @returns New messages array with system prompt prepended to first user message\n * @example\n * ```typescript\n * const messages = [{ role: \"user\", content: \"Hello\" }];\n * const updated = prependSystemPromptToMessages(messages, \"You are a helpful assistant.\");\n * // Returns: [{ role: \"user\", content: \"You are a helpful assistant.\\n\\nHello\" }]\n * ```\n */\nexport function prependSystemPromptToMessages(\n  messages: LanguageModelMessage[],\n  systemPrompt: string,\n): LanguageModelMessage[] {\n  if (!systemPrompt.trim()) {\n    return messages;\n  }\n\n  const prompts = messages.map((message) => ({ ...message }));\n  const firstUserIndex = prompts.findIndex(\n    (message) => message.role === \"user\",\n  );\n\n  if (firstUserIndex !== -1) {\n    const firstUserMessage = prompts[firstUserIndex];\n\n    if (Array.isArray(firstUserMessage.content)) {\n      const content = firstUserMessage.content.slice();\n      content.unshift({\n        type: \"text\",\n        value: `${systemPrompt}\\n\\n`,\n      });\n      prompts[firstUserIndex] = {\n        ...firstUserMessage,\n        content,\n      } as LanguageModelMessage;\n    } else if (typeof firstUserMessage.content === \"string\") {\n      prompts[firstUserIndex] = {\n        ...firstUserMessage,\n        content: `${systemPrompt}\\n\\n${firstUserMessage.content}`,\n      } as LanguageModelMessage;\n    }\n  } else {\n    prompts.unshift({\n      role: \"user\",\n      content: systemPrompt,\n    });\n  }\n\n  return prompts;\n}\n","/**\n * Utilities for working with AI SDK tools\n */\n\nimport type {\n  LanguageModelV3FunctionTool,\n  LanguageModelV3ProviderTool,\n} from \"@ai-sdk/provider\";\n\n/**\n * Type guard to check if a tool is a function tool\n *\n * @param tool - The tool to check\n * @returns true if the tool is a LanguageModelV3FunctionTool\n */\nexport function isFunctionTool(\n  tool: LanguageModelV3FunctionTool | LanguageModelV3ProviderTool,\n): tool is LanguageModelV3FunctionTool {\n  return tool.type === \"function\";\n}\n","/**\n * SessionManager handles the lifecycle of browser AI sessions\n * Manages session creation, caching, availability checks, and progress monitoring\n */\n\nimport { LoadSettingError } from \"@ai-sdk/provider\";\n\n/**\n * Progress callback for model download events\n * @param progress - Download progress from 0 to 1\n */\nexport type ProgressCallback = (progress: number) => void;\n\n/**\n * Custom provider options that extend the standard API\n */\ninterface CustomProviderOptions {\n  onQuotaOverflow?: (event: Event) => void;\n}\n\n/**\n * Options for creating a new session\n */\nexport interface SessionCreateOptions\n  extends LanguageModelCreateOptions,\n    CustomProviderOptions {\n  systemMessage?: string;\n  expectedInputs?: Array<{ type: \"text\" | \"image\" | \"audio\" }>;\n  onDownloadProgress?: ProgressCallback;\n}\n\n/**\n * Manages browser AI session lifecycle\n *\n * Responsibilities:\n * - Create and cache AI sessions\n * - Check model availability\n * - Monitor download progress\n * - Handle session options and configuration\n *\n * @example\n * ```typescript\n * const manager = new SessionManager(config);\n *\n * // Check availability first\n * const status = await manager.checkAvailability();\n *\n * // Create session with progress tracking\n * const session = await manager.getSession({\n *   temperature: 0.7,\n *   onDownloadProgress: (p) => console.log(`${p * 100}%`)\n * });\n * ```\n */\nexport class SessionManager {\n  private session: LanguageModel | null = null;\n  private baseOptions: LanguageModelCreateOptions &\n    Partial<CustomProviderOptions>;\n\n  /**\n   * Creates a new SessionManager\n   *\n   * @param baseOptions - Base configuration options for all sessions\n   */\n  constructor(\n    baseOptions: LanguageModelCreateOptions & Partial<CustomProviderOptions>,\n  ) {\n    // Filter out our custom options that aren't part of LanguageModelCreateOptions\n    this.baseOptions = baseOptions;\n  }\n\n  /**\n   * Gets or creates a session with the specified options\n   *\n   * If a session already exists, it will be reused unless force create is needed.\n   *\n   * @param options - Optional session creation options\n   * @returns Promise resolving to a LanguageModel session\n   * @throws {LoadSettingError} When Prompt API is not available or model is unavailable\n   *\n   * @example\n   * ```typescript\n   * const session = await manager.getSession({\n   *   systemMessage: \"You are a helpful assistant\",\n   *   expectedInputs: [{ type: \"image\" }],\n   *   temperature: 0.8\n   * });\n   * ```\n   */\n  async getSession(options?: SessionCreateOptions): Promise<LanguageModel> {\n    // Check if LanguageModel API is available\n    if (typeof LanguageModel === \"undefined\") {\n      throw new LoadSettingError({\n        message:\n          \"Prompt API is not available. This library requires Chrome or Edge browser with built-in AI capabilities.\",\n      });\n    }\n\n    // Return existing session if available\n    if (this.session) {\n      return this.session;\n    }\n\n    // Check availability before attempting to create\n    const availability = await LanguageModel.availability();\n    if (availability === \"unavailable\") {\n      throw new LoadSettingError({\n        message: \"Built-in model not available in this browser\",\n      });\n    }\n\n    // Prepare session options\n    const sessionOptions = this.prepareSessionOptions(options);\n\n    // Create the session\n    this.session = await LanguageModel.create(sessionOptions);\n\n    // Check for onQuotaOverflow in request options first, then fall back to base options\n    const onQuotaOverflow =\n      options?.onQuotaOverflow || this.baseOptions.onQuotaOverflow;\n\n    if (onQuotaOverflow) {\n      this.session.addEventListener(\"quotaoverflow\", onQuotaOverflow);\n    } else {\n      this.session.addEventListener(\"quotaoverflow\", () => {\n        console.warn(\n          \"Model quota exceeded. Consider handling 'quotaoverflow' event.\",\n        );\n      });\n    }\n    return this.session;\n  }\n\n  /**\n   * Creates a session with download progress monitoring\n   *\n   * This is a convenience method for users who want explicit progress tracking.\n   *\n   * @param onDownloadProgress - Optional callback receiving progress (0-1) during download\n   * @returns Promise resolving to a LanguageModel session\n   * @throws {LoadSettingError} When Prompt API is not available or model is unavailable\n   *\n   * @example\n   * ```typescript\n   * const session = await manager.createSessionWithProgress(\n   *   (progress) => {\n   *     console.log(`Download: ${Math.round(progress * 100)}%`);\n   *   }\n   * );\n   * ```\n   */\n  async createSessionWithProgress(\n    onDownloadProgress?: ProgressCallback,\n  ): Promise<LanguageModel> {\n    return this.getSession({ onDownloadProgress });\n  }\n\n  /**\n   * Checks the availability status of the built-in AI model\n   *\n   * @returns Promise resolving to availability status\n   * - \"unavailable\": Model is not supported\n   * - \"downloadable\": Model needs to be downloaded\n   * - \"downloading\": Model is currently downloading\n   * - \"available\": Model is ready to use\n   *\n   * @example\n   * ```typescript\n   * const status = await manager.checkAvailability();\n   * if (status === \"downloadable\") {\n   *   console.log(\"Model needs to be downloaded first\");\n   * }\n   * ```\n   */\n  async checkAvailability(): Promise<Availability> {\n    if (typeof LanguageModel === \"undefined\") {\n      return \"unavailable\";\n    }\n    return LanguageModel.availability();\n  }\n\n  /**\n   * Gets the current session if it exists\n   *\n   * @returns The current session or null if none exists\n   */\n  getCurrentSession(): LanguageModel | null {\n    return this.session;\n  }\n\n  /**\n   * Destroys the current session\n   *\n   * Use this when you want to force creation of a new session\n   * with different options on the next getSession call.\n   */\n  destroySession(): void {\n    if (this.session && typeof this.session.destroy === \"function\") {\n      this.session.destroy();\n    }\n    this.session = null;\n  }\n\n  /**\n   * Prepares merged session options from base config and request options\n   *\n   * @param options - Optional request-specific options\n   * @returns Merged and sanitized options ready for LanguageModel.create()\n   * @private\n   */\n  private prepareSessionOptions(\n    options?: SessionCreateOptions,\n  ): LanguageModelCreateOptions {\n    // Start with base options\n    const mergedOptions: LanguageModelCreateOptions &\n      Partial<CustomProviderOptions> = { ...this.baseOptions };\n\n    // Merge in request-specific options if provided\n    if (options) {\n      const {\n        systemMessage,\n        expectedInputs,\n        onDownloadProgress,\n        onQuotaOverflow,\n        ...createOptions\n      } = options;\n\n      // Merge standard create options\n      Object.assign(mergedOptions, createOptions);\n\n      // Handle system message\n      if (systemMessage) {\n        mergedOptions.initialPrompts = [\n          { role: \"system\", content: systemMessage },\n        ];\n      }\n\n      // Handle expected inputs (for multimodal)\n      if (expectedInputs && expectedInputs.length > 0) {\n        mergedOptions.expectedInputs = expectedInputs;\n      }\n\n      // Handle download progress monitoring\n      if (onDownloadProgress) {\n        mergedOptions.monitor = (m: CreateMonitor) => {\n          m.addEventListener(\"downloadprogress\", (e: ProgressEvent) => {\n            onDownloadProgress(e.loaded); // e.loaded is between 0 and 1\n          });\n        };\n      }\n    }\n\n    // Remove any custom options that aren't part of the standard API\n    this.sanitizeOptions(mergedOptions);\n\n    return mergedOptions;\n  }\n\n  /**\n   * Removes custom options that aren't part of LanguageModel.create API\n   *\n   * @param options - Options object to sanitize in-place\n   * @private\n   */\n  private sanitizeOptions(\n    options: LanguageModelCreateOptions & Partial<CustomProviderOptions>,\n  ): void {\n    // Remove our custom options that the Prompt API doesn't understand\n  }\n}\n","/**\n * ToolCallFenceDetector - Detects and extracts tool call fences from streaming text\n *\n * This module handles the complex task of detecting tool call fences in a stream\n * where fences might be split across multiple chunks. It uses overlap detection\n * to avoid emitting text that might be the beginning of a fence.\n */\n\n/**\n * Result of fence detection operation\n */\nexport interface FenceDetectionResult {\n  /** The complete fence if found, null otherwise */\n  fence: string | null;\n  /** Any text before the fence that can be safely emitted */\n  prefixText: string;\n  /** Text after the fence (if fence was found) */\n  remainingText: string;\n  /** Length of potential partial fence at buffer end */\n  overlapLength: number;\n}\n\n/**\n * Result of streaming fence content detection\n */\nexport interface StreamingFenceResult {\n  /** Whether we're currently inside a fence */\n  inFence: boolean;\n  /** Content that can be safely emitted (either as text or tool-input-delta) */\n  safeContent: string;\n  /** The complete fence if it just closed, null otherwise */\n  completeFence: string | null;\n  /** Text after a completed fence */\n  textAfterFence: string;\n}\n\n/**\n * Detects tool call fences in streaming text with support for partial matches\n *\n * @example\n * ```typescript\n * const detector = new ToolCallFenceDetector();\n *\n * // Add chunks as they arrive\n * detector.addChunk(\"Here's the answer: \");\n * detector.addChunk(\"```tool_call\\n<tool_call>\");\n * detector.addChunk(\"<name>search</name></tool_call>\\n```\");\n *\n * // Detect fence\n * const result = detector.detectFence();\n * if (result.fence) {\n *   console.log(\"Found tool call!\");\n * }\n * ```\n */\nexport class ToolCallFenceDetector {\n  private readonly FENCE_STARTS = [\"```tool_call\"];\n  private readonly FENCE_END = \"```\";\n  private buffer = \"\";\n\n  // Streaming state\n  private inFence = false;\n  private fenceStartBuffer = \"\"; // Accumulated fence content\n\n  /**\n   * Adds a chunk of text to the internal buffer\n   *\n   * @param chunk - Text chunk from the stream\n   */\n  addChunk(chunk: string): void {\n    this.buffer += chunk;\n  }\n\n  /**\n   * Gets the current buffer content\n   */\n  getBuffer(): string {\n    return this.buffer;\n  }\n\n  /**\n   * Clears the internal buffer\n   */\n  clearBuffer(): void {\n    this.buffer = \"\";\n  }\n\n  /**\n   * Detects if there's a complete fence in the buffer\n   *\n   * This method:\n   * 1. Searches for fence start markers\n   * 2. If found, looks for closing fence\n   * 3. Computes overlap for partial fences\n   * 4. Returns safe text that can be emitted\n   *\n   * @returns Detection result with fence info and safe text\n   */\n  detectFence(): FenceDetectionResult {\n    const { index: startIdx, prefix: matchedPrefix } = this.findFenceStart(\n      this.buffer,\n    );\n\n    // No fence start found\n    if (startIdx === -1) {\n      // Compute how much of the buffer end might be a partial fence start\n      const overlap = this.computeOverlapLength(this.buffer, this.FENCE_STARTS);\n      const safeTextLength = this.buffer.length - overlap;\n\n      const prefixText =\n        safeTextLength > 0 ? this.buffer.slice(0, safeTextLength) : \"\";\n      const remaining = overlap > 0 ? this.buffer.slice(-overlap) : \"\";\n\n      // Update buffer to keep only the overlap\n      this.buffer = remaining;\n\n      return {\n        fence: null,\n        prefixText,\n        remainingText: \"\",\n        overlapLength: overlap,\n      };\n    }\n\n    // Found fence start - extract prefix text before it\n    const prefixText = this.buffer.slice(0, startIdx);\n    this.buffer = this.buffer.slice(startIdx);\n\n    // Look for closing fence\n    const prefixLength = matchedPrefix?.length ?? 0;\n    const closingIdx = this.buffer.indexOf(this.FENCE_END, prefixLength);\n\n    // Fence not complete yet\n    if (closingIdx === -1) {\n      // Keep the buffer as-is, waiting for more data\n      return {\n        fence: null,\n        prefixText,\n        remainingText: \"\",\n        overlapLength: 0,\n      };\n    }\n\n    // Complete fence found!\n    const endPos = closingIdx + this.FENCE_END.length;\n    const fence = this.buffer.slice(0, endPos);\n    const remainingText = this.buffer.slice(endPos);\n\n    // Clear the buffer since we extracted everything\n    this.buffer = \"\";\n\n    return {\n      fence,\n      prefixText,\n      remainingText,\n      overlapLength: 0,\n    };\n  }\n\n  /**\n   * Finds the first occurrence of any fence start marker\n   *\n   * @param text - Text to search in\n   * @returns Index of first fence start and which prefix matched\n   * @private\n   */\n  private findFenceStart(text: string): {\n    index: number;\n    prefix: string | null;\n  } {\n    let bestIndex = -1;\n    let matchedPrefix: string | null = null;\n\n    for (const prefix of this.FENCE_STARTS) {\n      const idx = text.indexOf(prefix);\n      if (idx !== -1 && (bestIndex === -1 || idx < bestIndex)) {\n        bestIndex = idx;\n        matchedPrefix = prefix;\n      }\n    }\n\n    return { index: bestIndex, prefix: matchedPrefix };\n  }\n\n  /**\n   * Computes the maximum overlap between the end of text and the start of any prefix\n   *\n   * This is crucial for streaming: if the buffer ends with \"``\", we can't emit it\n   * because the next chunk might be \"`tool_call\", completing a fence marker.\n   *\n   * @param text - Text to check for overlap\n   * @param prefixes - List of prefixes to check against\n   * @returns Length of the maximum overlap found\n   *\n   * @example\n   * ```typescript\n   * computeOverlapLength(\"hello ``\", [\"```tool_call\"])\n   * // Returns: 2 (because \"``\" matches start of \"```tool_call\")\n   *\n   * computeOverlapLength(\"hello `\", [\"```tool_call\"])\n   * // Returns: 1\n   *\n   * computeOverlapLength(\"hello world\", [\"```tool_call\"])\n   * // Returns: 0 (no overlap)\n   * ```\n   *\n   * @private\n   */\n  private computeOverlapLength(text: string, prefixes: string[]): number {\n    let overlap = 0;\n\n    for (const prefix of prefixes) {\n      const maxLength = Math.min(text.length, prefix.length - 1);\n\n      for (let size = maxLength; size > 0; size -= 1) {\n        // Check if the last 'size' characters of text match the first 'size' characters of prefix\n        if (prefix.startsWith(text.slice(-size))) {\n          overlap = Math.max(overlap, size);\n          break;\n        }\n      }\n    }\n\n    return overlap;\n  }\n\n  /**\n   * Checks if the buffer currently contains any text\n   */\n  hasContent(): boolean {\n    return this.buffer.length > 0;\n  }\n\n  /**\n   * Gets the buffer size\n   */\n  getBufferSize(): number {\n    return this.buffer.length;\n  }\n\n  /**\n   * Detect and stream fence content in real-time for true incremental streaming\n   *\n   * This method is designed for streaming tool calls as they arrive:\n   * 1. Detects when a fence starts and transitions to \"inFence\" state\n   * 2. While inFence, emits safe content that won't conflict with fence end marker\n   * 3. When fence ends, returns the complete fence for parsing\n   *\n   * @returns Streaming result with current state and safe content to emit\n   */\n  detectStreamingFence(): StreamingFenceResult {\n    if (!this.inFence) {\n      // Look for fence start\n      const { index: startIdx, prefix: matchedPrefix } = this.findFenceStart(\n        this.buffer,\n      );\n\n      if (startIdx === -1) {\n        // No fence start found - emit safe text\n        const overlap = this.computeOverlapLength(\n          this.buffer,\n          this.FENCE_STARTS,\n        );\n        const safeTextLength = this.buffer.length - overlap;\n        const safeContent =\n          safeTextLength > 0 ? this.buffer.slice(0, safeTextLength) : \"\";\n        this.buffer = this.buffer.slice(safeTextLength);\n\n        return {\n          inFence: false,\n          safeContent,\n          completeFence: null,\n          textAfterFence: \"\",\n        };\n      }\n\n      // Found fence start!\n      const prefixText = this.buffer.slice(0, startIdx);\n      const fenceStartLength = matchedPrefix?.length ?? 0;\n\n      // Move buffer past the fence start marker\n      this.buffer = this.buffer.slice(startIdx + fenceStartLength);\n\n      // Skip newline after fence start if present\n      if (this.buffer.startsWith(\"\\n\")) {\n        this.buffer = this.buffer.slice(1);\n      }\n\n      this.inFence = true;\n      this.fenceStartBuffer = \"\";\n\n      return {\n        inFence: true,\n        safeContent: prefixText, // Emit any text before the fence\n        completeFence: null,\n        textAfterFence: \"\",\n      };\n    }\n\n    // We're inside a fence - look for fence end\n    const closingIdx = this.buffer.indexOf(this.FENCE_END);\n\n    if (closingIdx === -1) {\n      // No fence end yet - emit safe content (leaving potential fence end marker)\n      const overlap = this.computeOverlapLength(this.buffer, [this.FENCE_END]);\n      const safeContentLength = this.buffer.length - overlap;\n\n      if (safeContentLength > 0) {\n        const safeContent = this.buffer.slice(0, safeContentLength);\n        this.fenceStartBuffer += safeContent;\n        this.buffer = this.buffer.slice(safeContentLength);\n\n        return {\n          inFence: true,\n          safeContent,\n          completeFence: null,\n          textAfterFence: \"\",\n        };\n      }\n\n      // Nothing safe to emit yet\n      return {\n        inFence: true,\n        safeContent: \"\",\n        completeFence: null,\n        textAfterFence: \"\",\n      };\n    }\n\n    // Found fence end!\n    const fenceContent = this.buffer.slice(0, closingIdx);\n    this.fenceStartBuffer += fenceContent;\n\n    // Reconstruct complete fence\n    const completeFence = `${this.FENCE_STARTS[0]}\\n${this.fenceStartBuffer}\\n${this.FENCE_END}`;\n\n    // Get text after fence\n    const textAfterFence = this.buffer.slice(\n      closingIdx + this.FENCE_END.length,\n    );\n\n    // Reset state\n    this.inFence = false;\n    this.fenceStartBuffer = \"\";\n    this.buffer = textAfterFence;\n\n    return {\n      inFence: false,\n      safeContent: fenceContent, // Emit the last bit of fence content\n      completeFence,\n      textAfterFence,\n    };\n  }\n\n  /**\n   * Check if currently inside a fence\n   */\n  isInFence(): boolean {\n    return this.inFence;\n  }\n\n  /**\n   * Reset streaming state\n   */\n  resetStreamingState(): void {\n    this.inFence = false;\n    this.fenceStartBuffer = \"\";\n  }\n}\n","import {\n  LanguageModelV3,\n  LanguageModelV3CallOptions,\n  SharedV3Warning,\n  LanguageModelV3Content,\n  LanguageModelV3FinishReason,\n  LanguageModelV3ProviderTool,\n  LanguageModelV3StreamPart,\n  LanguageModelV3ToolCall,\n  JSONValue,\n  LanguageModelV3GenerateResult,\n  LanguageModelV3StreamResult,\n} from \"@ai-sdk/provider\";\nimport { convertToBuiltInAIMessages } from \"./convert-to-built-in-ai-messages\";\nimport {\n  buildJsonToolSystemPrompt,\n  parseJsonFunctionCalls,\n} from \"./tool-calling\";\nimport type { ParsedToolCall } from \"./tool-calling\";\nimport {\n  gatherUnsupportedSettingWarnings,\n  createUnsupportedToolWarning,\n} from \"./utils/warnings\";\nimport {\n  hasMultimodalContent,\n  getExpectedInputs,\n  prependSystemPromptToMessages,\n} from \"./utils/prompt-utils\";\nimport { isFunctionTool } from \"./utils/tool-utils\";\nimport { SessionManager } from \"./models/session-manager\";\nimport { ToolCallFenceDetector } from \"./streaming/tool-call-detector\";\n\nexport type BuiltInAIChatModelId = \"text\";\n\nexport interface BuiltInAIChatSettings extends LanguageModelCreateOptions {\n  /**\n   * Expected input types for the session, for multimodal inputs.\n   */\n  expectedInputs?: Array<{\n    type: \"text\" | \"image\" | \"audio\";\n    languages?: string[];\n  }>;\n\n  /**\n   * Callback invoked when the model quota is exceeded.\n   * @see [Prompt API Quota Overflow](https://github.com/webmachinelearning/prompt-api?tab=readme-ov-file#tokenization-context-window-length-limits-and-overflow)\n   * @param event\n   */\n  onQuotaOverflow?: (event: Event) => void;\n}\n\n/**\n * Check if the browser supports the built-in AI API\n * @returns true if the browser supports the built-in AI API, false otherwise\n */\nexport function doesBrowserSupportBuiltInAI(): boolean {\n  return typeof LanguageModel !== \"undefined\";\n}\n\ntype BuiltInAIConfig = {\n  provider: string;\n  modelId: BuiltInAIChatModelId;\n  options: BuiltInAIChatSettings;\n};\n\n/**\n * Extract tool name from partial fence content for early emission\n * This allows us to emit tool-input-start as soon as we know the tool name\n * Expects JSON format: {\"name\":\"toolName\"\n */\nfunction extractToolName(content: string): string | null {\n  // For JSON mode: {\"name\":\"toolName\"\n  const jsonMatch = content.match(/\\{\\s*\"name\"\\s*:\\s*\"([^\"]+)\"/);\n  if (jsonMatch) {\n    return jsonMatch[1];\n  }\n  return null;\n}\n\n/**\n * Extract the argument section from a streaming tool call fence.\n * Returns the substring after `\"arguments\":` (best-effort for partial JSON).\n */\nfunction extractArgumentsContent(content: string): string {\n  const match = content.match(/\"arguments\"\\s*:\\s*/);\n  if (!match || match.index === undefined) {\n    return \"\";\n  }\n\n  const startIndex = match.index + match[0].length;\n  let result = \"\";\n  let depth = 0;\n  let inString = false;\n  let escaped = false;\n  let started = false;\n\n  for (let i = startIndex; i < content.length; i++) {\n    const char = content[i];\n    result += char;\n\n    if (!started) {\n      if (!/\\s/.test(char)) {\n        started = true;\n        if (char === \"{\" || char === \"[\") {\n          depth = 1;\n        }\n      }\n      continue;\n    }\n\n    if (escaped) {\n      escaped = false;\n      continue;\n    }\n\n    if (char === \"\\\\\") {\n      escaped = true;\n      continue;\n    }\n\n    if (char === '\"') {\n      inString = !inString;\n      continue;\n    }\n\n    if (!inString) {\n      if (char === \"{\" || char === \"[\") {\n        depth += 1;\n      } else if (char === \"}\" || char === \"]\") {\n        if (depth > 0) {\n          depth -= 1;\n          if (depth === 0) {\n            break;\n          }\n        }\n      }\n    }\n  }\n\n  return result;\n}\n\nexport class BuiltInAIChatLanguageModel implements LanguageModelV3 {\n  readonly specificationVersion = \"v3\";\n  readonly modelId: BuiltInAIChatModelId;\n  readonly provider = \"browser-ai\";\n\n  private readonly config: BuiltInAIConfig;\n  private readonly sessionManager: SessionManager;\n\n  constructor(\n    modelId: BuiltInAIChatModelId,\n    options: BuiltInAIChatSettings = {},\n  ) {\n    this.modelId = modelId;\n    this.config = {\n      provider: this.provider,\n      modelId,\n      options,\n    };\n    this.sessionManager = new SessionManager(options);\n  }\n\n  readonly supportedUrls: Record<string, RegExp[]> = {\n    \"image/*\": [/^https?:\\/\\/.+$/],\n    \"audio/*\": [/^https?:\\/\\/.+$/],\n  };\n\n  /**\n   * Gets a session with the specified options\n   * Delegates to SessionManager for all session lifecycle management\n   * @private\n   */\n  private async getSession(\n    options?: LanguageModelCreateOptions,\n    expectedInputs?: Array<{ type: \"text\" | \"image\" | \"audio\" }>,\n    systemMessage?: string,\n    onDownloadProgress?: (progress: number) => void,\n  ): Promise<LanguageModel> {\n    return this.sessionManager.getSession({\n      ...options,\n      expectedInputs,\n      systemMessage,\n      onDownloadProgress,\n    });\n  }\n\n  private getArgs(callOptions: Parameters<LanguageModelV3[\"doGenerate\"]>[0]) {\n    const {\n      prompt,\n      maxOutputTokens,\n      temperature,\n      topP,\n      topK,\n      frequencyPenalty,\n      presencePenalty,\n      stopSequences,\n      responseFormat,\n      seed,\n      tools,\n      toolChoice,\n      providerOptions,\n    } = callOptions;\n    const warnings: SharedV3Warning[] = [];\n\n    // Gather warnings for unsupported settings\n    warnings.push(\n      ...gatherUnsupportedSettingWarnings({\n        maxOutputTokens,\n        stopSequences,\n        topP,\n        presencePenalty,\n        frequencyPenalty,\n        seed,\n        toolChoice,\n      }),\n    );\n\n    // Filter and warn about unsupported tools\n    const functionTools = (tools ?? []).filter(isFunctionTool);\n\n    const unsupportedTools = (tools ?? []).filter(\n      (tool): tool is LanguageModelV3ProviderTool => !isFunctionTool(tool),\n    );\n\n    for (const tool of unsupportedTools) {\n      warnings.push(\n        createUnsupportedToolWarning(\n          tool,\n          \"Only function tools are supported by the Prompt API polyfill\",\n        ),\n      );\n    }\n\n    // Check if this is a multimodal prompt\n    const hasMultiModalInput = hasMultimodalContent(prompt);\n\n    // Convert messages to the DOM API format\n    const { systemMessage, messages } = convertToBuiltInAIMessages(prompt);\n\n    // Handle response format for Prompt API\n    const promptOptions: LanguageModelPromptOptions &\n      LanguageModelCreateCoreOptions = {};\n    if (responseFormat?.type === \"json\") {\n      promptOptions.responseConstraint = responseFormat.schema as Record<\n        string,\n        JSONValue\n      >;\n    }\n\n    // Map supported settings\n    if (temperature !== undefined) {\n      promptOptions.temperature = temperature;\n    }\n\n    if (topK !== undefined) {\n      promptOptions.topK = topK;\n    }\n\n    return {\n      systemMessage,\n      messages,\n      warnings,\n      promptOptions,\n      hasMultiModalInput,\n      expectedInputs: hasMultiModalInput\n        ? getExpectedInputs(prompt)\n        : undefined,\n      functionTools,\n    };\n  }\n\n  /**\n   * Generates a complete text response using the browser's built-in Prompt API\n   * @param options\n   * @returns Promise resolving to the generated content with finish reason, usage stats, and any warnings\n   * @throws {LoadSettingError} When the Prompt API is not available or model needs to be downloaded\n   * @throws {UnsupportedFunctionalityError} When unsupported features like file input are used\n   */\n  public async doGenerate(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3GenerateResult> {\n    const converted = this.getArgs(options);\n    const {\n      systemMessage,\n      messages,\n      warnings,\n      promptOptions,\n      expectedInputs,\n      functionTools,\n    } = converted;\n\n    const session = await this.getSession(undefined, expectedInputs, undefined);\n\n    // Build system prompt with JSON tool calling\n    const systemPrompt = await buildJsonToolSystemPrompt(\n      systemMessage,\n      functionTools,\n      {\n        allowParallelToolCalls: false,\n      },\n    );\n\n    const promptMessages = prependSystemPromptToMessages(\n      messages,\n      systemPrompt,\n    );\n    const rawResponse = await session.prompt(promptMessages, promptOptions);\n\n    // Parse JSON tool calls from response\n    const { toolCalls, textContent } = parseJsonFunctionCalls(rawResponse);\n\n    if (toolCalls.length > 0) {\n      const toolCallsToEmit = toolCalls.slice(0, 1);\n\n      const parts: LanguageModelV3Content[] = [];\n\n      if (textContent) {\n        parts.push({\n          type: \"text\",\n          text: textContent,\n        });\n      }\n\n      for (const call of toolCallsToEmit) {\n        parts.push({\n          type: \"tool-call\",\n          toolCallId: call.toolCallId,\n          toolName: call.toolName,\n          input: JSON.stringify(call.args ?? {}),\n        } satisfies LanguageModelV3ToolCall);\n      }\n\n      return {\n        content: parts,\n        finishReason: { unified: \"tool-calls\", raw: \"tool-calls\" },\n        usage: {\n          inputTokens: {\n            total: undefined,\n            noCache: undefined,\n            cacheRead: undefined,\n            cacheWrite: undefined,\n          },\n          outputTokens: {\n            total: undefined,\n            text: undefined,\n            reasoning: undefined,\n          },\n        },\n        request: { body: { messages: promptMessages, options: promptOptions } },\n        warnings,\n      };\n    }\n\n    const content: LanguageModelV3Content[] = [\n      {\n        type: \"text\",\n        text: textContent || rawResponse,\n      },\n    ];\n\n    return {\n      content,\n      finishReason: { unified: \"stop\", raw: \"stop\" },\n      usage: {\n        inputTokens: {\n          total: undefined,\n          noCache: undefined,\n          cacheRead: undefined,\n          cacheWrite: undefined,\n        },\n        outputTokens: {\n          total: undefined,\n          text: undefined,\n          reasoning: undefined,\n        },\n      },\n      request: { body: { messages: promptMessages, options: promptOptions } },\n      warnings,\n    };\n  }\n\n  /**\n   * Check the availability of the built-in AI model\n   * @returns Promise resolving to \"unavailable\", \"available\", or \"available-after-download\"\n   */\n  public async availability(): Promise<Availability> {\n    return this.sessionManager.checkAvailability();\n  }\n\n  /**\n   * Creates a session with download progress monitoring.\n   *\n   * @example\n   * ```typescript\n   * const session = await model.createSessionWithProgress(\n   *   (progress) => {\n   *     console.log(`Download progress: ${Math.round(progress * 100)}%`);\n   *   }\n   * );\n   * ```\n   *\n   * @param onDownloadProgress Optional callback receiving progress values 0-1 during model download\n   * @returns Promise resolving to a configured LanguageModel session\n   * @throws {LoadSettingError} When the Prompt API is not available or model is unavailable\n   */\n  public async createSessionWithProgress(\n    onDownloadProgress?: (progress: number) => void,\n  ): Promise<LanguageModel> {\n    return this.sessionManager.createSessionWithProgress(onDownloadProgress);\n  }\n\n  /**\n   * Generates a streaming text response using the browser's built-in Prompt API\n   * @param options\n   * @returns Promise resolving to a readable stream of text chunks and request metadata\n   * @throws {LoadSettingError} When the Prompt API is not available or model needs to be downloaded\n   * @throws {UnsupportedFunctionalityError} When unsupported features like file input are used\n   */\n  public async doStream(\n    options: LanguageModelV3CallOptions,\n  ): Promise<LanguageModelV3StreamResult> {\n    const converted = this.getArgs(options);\n    const {\n      systemMessage,\n      messages,\n      warnings,\n      promptOptions,\n      expectedInputs,\n      functionTools,\n    } = converted;\n\n    const session = await this.getSession(undefined, expectedInputs, undefined);\n\n    // Build system prompt with JSON tool calling\n    const systemPrompt = await buildJsonToolSystemPrompt(\n      systemMessage,\n      functionTools,\n      {\n        allowParallelToolCalls: false,\n      },\n    );\n    const promptMessages = prependSystemPromptToMessages(\n      messages,\n      systemPrompt,\n    );\n\n    // Pass abort signal to the native streaming method\n    const streamOptions = {\n      ...promptOptions,\n      signal: options.abortSignal,\n    };\n    const conversationHistory = [...promptMessages];\n    const textId = \"text-0\";\n\n    const stream = new ReadableStream<LanguageModelV3StreamPart>({\n      start: async (controller) => {\n        controller.enqueue({\n          type: \"stream-start\",\n          warnings,\n        });\n\n        let textStarted = false;\n        let finished = false;\n        let aborted = false;\n        let currentReader: ReadableStreamDefaultReader<string> | null = null;\n\n        const ensureTextStart = () => {\n          if (!textStarted) {\n            controller.enqueue({\n              type: \"text-start\",\n              id: textId,\n            });\n            textStarted = true;\n          }\n        };\n\n        const emitTextDelta = (delta: string) => {\n          if (!delta) return;\n          ensureTextStart();\n          controller.enqueue({\n            type: \"text-delta\",\n            id: textId,\n            delta,\n          });\n        };\n\n        const emitTextEndIfNeeded = () => {\n          if (!textStarted) return;\n          controller.enqueue({\n            type: \"text-end\",\n            id: textId,\n          });\n          textStarted = false;\n        };\n\n        const finishStream = (finishReason: LanguageModelV3FinishReason) => {\n          if (finished) return;\n          finished = true;\n          emitTextEndIfNeeded();\n          controller.enqueue({\n            type: \"finish\",\n            finishReason,\n            usage: {\n              inputTokens: {\n                total: session.inputUsage,\n                noCache: undefined,\n                cacheRead: undefined,\n                cacheWrite: undefined,\n              },\n              outputTokens: {\n                total: undefined,\n                text: undefined,\n                reasoning: undefined,\n              },\n            },\n          });\n          controller.close();\n        };\n\n        const abortHandler = () => {\n          if (aborted) {\n            return;\n          }\n          aborted = true;\n          if (currentReader) {\n            currentReader.cancel().catch(() => undefined);\n          }\n          finishStream({ unified: \"stop\", raw: \"aborted\" });\n        };\n\n        if (options.abortSignal) {\n          options.abortSignal.addEventListener(\"abort\", abortHandler);\n        }\n\n        const maxIterations = 10;\n        let iteration = 0;\n\n        try {\n          // Use ToolCallFenceDetector for real-time streaming\n          const fenceDetector = new ToolCallFenceDetector();\n\n          while (iteration < maxIterations && !aborted && !finished) {\n            iteration += 1;\n\n            const promptStream = session.promptStreaming(\n              conversationHistory,\n              streamOptions,\n            );\n            currentReader = promptStream.getReader();\n\n            let toolCalls: ParsedToolCall[] = [];\n            let toolBlockDetected = false;\n            let trailingTextAfterBlock = \"\";\n\n            // Streaming tool call state\n            let currentToolCallId: string | null = null;\n            let toolInputStartEmitted = false;\n            let accumulatedFenceContent = \"\";\n            let streamedArgumentsLength = 0;\n            let insideFence = false;\n\n            while (!aborted) {\n              const { done, value } = await currentReader.read();\n              if (done) {\n                break;\n              }\n\n              // Add chunk to detector\n              fenceDetector.addChunk(value);\n\n              // Process buffer using streaming detection\n              while (fenceDetector.hasContent()) {\n                const wasInsideFence = insideFence;\n                const result = fenceDetector.detectStreamingFence();\n                insideFence = result.inFence;\n\n                let madeProgress = false;\n\n                if (!wasInsideFence && result.inFence) {\n                  if (result.safeContent) {\n                    emitTextDelta(result.safeContent);\n                    madeProgress = true;\n                  }\n\n                  currentToolCallId = `call_${Date.now()}_${Math.random()\n                    .toString(36)\n                    .slice(2, 9)}`;\n                  toolInputStartEmitted = false;\n                  accumulatedFenceContent = \"\";\n                  streamedArgumentsLength = 0;\n                  insideFence = true;\n\n                  continue;\n                }\n\n                if (result.completeFence) {\n                  madeProgress = true;\n                  if (result.safeContent) {\n                    accumulatedFenceContent += result.safeContent;\n                  }\n\n                  if (toolInputStartEmitted && currentToolCallId) {\n                    const argsContent = extractArgumentsContent(\n                      accumulatedFenceContent,\n                    );\n                    if (argsContent.length > streamedArgumentsLength) {\n                      const delta = argsContent.slice(streamedArgumentsLength);\n                      streamedArgumentsLength = argsContent.length;\n                      if (delta.length > 0) {\n                        controller.enqueue({\n                          type: \"tool-input-delta\",\n                          id: currentToolCallId,\n                          delta,\n                        });\n                      }\n                    }\n                  }\n\n                  const parsed = parseJsonFunctionCalls(result.completeFence);\n                  const parsedToolCalls = parsed.toolCalls;\n                  const selectedToolCalls = parsedToolCalls.slice(0, 1);\n\n                  if (selectedToolCalls.length === 0) {\n                    toolCalls = [];\n                    toolBlockDetected = false;\n                    emitTextDelta(result.completeFence);\n                    if (result.textAfterFence) {\n                      emitTextDelta(result.textAfterFence);\n                    }\n\n                    currentToolCallId = null;\n                    toolInputStartEmitted = false;\n                    accumulatedFenceContent = \"\";\n                    streamedArgumentsLength = 0;\n                    insideFence = false;\n                    continue;\n                  }\n\n                  if (selectedToolCalls.length > 0 && currentToolCallId) {\n                    selectedToolCalls[0].toolCallId = currentToolCallId;\n                  }\n\n                  toolCalls = selectedToolCalls;\n                  toolBlockDetected = toolCalls.length > 0;\n\n                  for (const [index, call] of toolCalls.entries()) {\n                    const toolCallId =\n                      index === 0 && currentToolCallId\n                        ? currentToolCallId\n                        : call.toolCallId;\n                    const toolName = call.toolName;\n                    const argsJson = JSON.stringify(call.args ?? {});\n\n                    if (toolCallId === currentToolCallId) {\n                      if (!toolInputStartEmitted) {\n                        controller.enqueue({\n                          type: \"tool-input-start\",\n                          id: toolCallId,\n                          toolName,\n                        });\n                        toolInputStartEmitted = true;\n                      }\n\n                      const argsContent = extractArgumentsContent(\n                        accumulatedFenceContent,\n                      );\n                      if (argsContent.length > streamedArgumentsLength) {\n                        const delta = argsContent.slice(\n                          streamedArgumentsLength,\n                        );\n                        streamedArgumentsLength = argsContent.length;\n                        if (delta.length > 0) {\n                          controller.enqueue({\n                            type: \"tool-input-delta\",\n                            id: toolCallId,\n                            delta,\n                          });\n                        }\n                      }\n                    } else {\n                      controller.enqueue({\n                        type: \"tool-input-start\",\n                        id: toolCallId,\n                        toolName,\n                      });\n                      if (argsJson.length > 0) {\n                        controller.enqueue({\n                          type: \"tool-input-delta\",\n                          id: toolCallId,\n                          delta: argsJson,\n                        });\n                      }\n                    }\n\n                    controller.enqueue({\n                      type: \"tool-input-end\",\n                      id: toolCallId,\n                    });\n                    controller.enqueue({\n                      type: \"tool-call\",\n                      toolCallId,\n                      toolName,\n                      input: argsJson,\n                      providerExecuted: false,\n                    });\n                  }\n\n                  trailingTextAfterBlock += result.textAfterFence;\n                  madeProgress = true;\n\n                  if (toolBlockDetected && currentReader) {\n                    await currentReader.cancel().catch(() => undefined);\n                    break;\n                  }\n\n                  currentToolCallId = null;\n                  toolInputStartEmitted = false;\n                  accumulatedFenceContent = \"\";\n                  streamedArgumentsLength = 0;\n                  insideFence = false;\n                  continue;\n                }\n\n                if (insideFence) {\n                  if (result.safeContent) {\n                    accumulatedFenceContent += result.safeContent;\n                    madeProgress = true;\n\n                    const toolName = extractToolName(accumulatedFenceContent);\n                    if (\n                      toolName &&\n                      !toolInputStartEmitted &&\n                      currentToolCallId\n                    ) {\n                      controller.enqueue({\n                        type: \"tool-input-start\",\n                        id: currentToolCallId,\n                        toolName,\n                      });\n                      toolInputStartEmitted = true;\n                    }\n\n                    if (toolInputStartEmitted && currentToolCallId) {\n                      const argsContent = extractArgumentsContent(\n                        accumulatedFenceContent,\n                      );\n                      if (argsContent.length > streamedArgumentsLength) {\n                        const delta = argsContent.slice(\n                          streamedArgumentsLength,\n                        );\n                        streamedArgumentsLength = argsContent.length;\n                        if (delta.length > 0) {\n                          controller.enqueue({\n                            type: \"tool-input-delta\",\n                            id: currentToolCallId,\n                            delta,\n                          });\n                        }\n                      }\n                    }\n                  }\n\n                  continue;\n                }\n\n                if (!insideFence && result.safeContent) {\n                  emitTextDelta(result.safeContent);\n                  madeProgress = true;\n                }\n\n                if (!madeProgress) {\n                  break;\n                }\n              }\n\n              if (toolBlockDetected) {\n                break;\n              }\n            }\n            currentReader = null;\n\n            if (aborted) {\n              return;\n            }\n\n            // Emit any remaining buffer content if no tool was detected\n            if (!toolBlockDetected && fenceDetector.hasContent()) {\n              emitTextDelta(fenceDetector.getBuffer());\n              fenceDetector.clearBuffer();\n            }\n\n            if (!toolBlockDetected || toolCalls.length === 0) {\n              finishStream({ unified: \"stop\", raw: \"stop\" });\n              return;\n            }\n\n            if (trailingTextAfterBlock) {\n              emitTextDelta(trailingTextAfterBlock);\n            }\n\n            finishStream({ unified: \"tool-calls\", raw: \"tool-calls\" });\n            return;\n          }\n\n          if (!finished && !aborted) {\n            finishStream({ unified: \"other\", raw: \"other\" });\n          }\n        } catch (error) {\n          controller.enqueue({ type: \"error\", error });\n          controller.close();\n        } finally {\n          if (options.abortSignal) {\n            options.abortSignal.removeEventListener(\"abort\", abortHandler);\n          }\n        }\n      },\n    });\n\n    return {\n      stream,\n      request: { body: { messages: promptMessages, options: promptOptions } },\n    };\n  }\n}\n","import {\n  EmbeddingModelV3,\n  EmbeddingModelV3CallOptions,\n  EmbeddingModelV3Result,\n} from \"@ai-sdk/provider\";\nimport { TextEmbedder } from \"@mediapipe/tasks-text\";\n\nexport interface BuiltInAIEmbeddingModelSettings {\n  /**\n   * An optional base path to specify the directory the Wasm files should be loaded from.\n   * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.js'\n   */\n  wasmLoaderPath?: string;\n  /**\n   * It's about 6mb before gzip.\n   * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.wasm'\n   */\n  wasmBinaryPath?: string;\n  /**\n   * The model path to the model asset file.\n   * It's about 6.1mb before gzip.\n   * @default 'https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/universal_sentence_encoder.tflite'\n   */\n  modelAssetPath?: string;\n  /**\n   * Whether to normalize the returned feature vector with L2 norm. Use this\n   * option only if the model does not already contain a native L2_NORMALIZATION\n   * TF Lite Op. In most cases, this is already the case and L2 norm is thus\n   * achieved through TF Lite inference.\n   * @default false\n   */\n  l2Normalize?: boolean;\n  /**\n   * Whether the returned embedding should be quantized to bytes via scalar\n   * quantization. Embeddings are implicitly assumed to be unit-norm and\n   * therefore any dimension is guaranteed to have a value in [-1.0, 1.0]. Use\n   * the l2_normalize option if this is not the case.\n   * @default false\n   */\n  quantize?: boolean;\n  /**\n   * Overrides the default backend to use for the provided model.\n   */\n  delegate?: \"CPU\" | \"GPU\";\n}\n\n// See more:\n// - https://github.com/google-ai-edge/mediapipe\n// - https://ai.google.dev/edge/mediapipe/solutions/text/text_embedder/web_js\nexport class BuiltInAIEmbeddingModel implements EmbeddingModelV3 {\n  readonly specificationVersion = \"v3\";\n  readonly provider = \"google-mediapipe\";\n  readonly modelId: string = \"embedding\";\n  readonly supportsParallelCalls = true;\n  readonly maxEmbeddingsPerCall = undefined;\n\n  private settings: BuiltInAIEmbeddingModelSettings = {\n    wasmLoaderPath:\n      \"https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.js\",\n    wasmBinaryPath:\n      \"https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/text_wasm_internal.wasm\",\n    modelAssetPath:\n      \"https://pub-ddcfe353995744e89b8002f16bf98575.r2.dev/universal_sentence_encoder.tflite\",\n    l2Normalize: false,\n    quantize: false,\n  };\n  private modelAssetBuffer!: Promise<ReadableStreamDefaultReader>;\n  private textEmbedder!: Promise<TextEmbedder>;\n\n  public constructor(settings: BuiltInAIEmbeddingModelSettings = {}) {\n    this.settings = { ...this.settings, ...settings };\n    this.modelAssetBuffer = fetch(this.settings.modelAssetPath!).then(\n      (response) => response.body!.getReader(),\n    )!;\n    this.textEmbedder = this.getTextEmbedder();\n  }\n\n  protected getTextEmbedder = async (): Promise<TextEmbedder> => {\n    return TextEmbedder.createFromOptions(\n      {\n        wasmBinaryPath: this.settings.wasmBinaryPath!,\n        wasmLoaderPath: this.settings.wasmLoaderPath!,\n      },\n      {\n        baseOptions: {\n          modelAssetBuffer: await this.modelAssetBuffer,\n          delegate: this.settings.delegate,\n        },\n        l2Normalize: this.settings.l2Normalize,\n        quantize: this.settings.quantize,\n      },\n    );\n  };\n\n  public doEmbed = async (\n    options: EmbeddingModelV3CallOptions,\n  ): Promise<EmbeddingModelV3Result> => {\n    // Note: abortSignal is not supported by MediaPipe TextEmbedder\n    if (options.abortSignal?.aborted) {\n      throw new Error(\"Operation was aborted\");\n    }\n\n    const embedder = await this.textEmbedder;\n    const embeddings = options.values.map((text) => {\n      const embedderResult = embedder.embed(text);\n      const [embedding] = embedderResult.embeddings;\n      return embedding?.floatEmbedding ?? [];\n    });\n\n    return {\n      embeddings,\n      providerMetadata: {\n        mediapipe: {\n          model: \"universal_sentence_encoder\",\n          provider: \"google-mediapipe\",\n          processed_texts: options.values.length,\n        },\n      },\n      warnings: [],\n    };\n  };\n}\n","import {\n  EmbeddingModelV3,\n  NoSuchModelError,\n  ProviderV3,\n} from \"@ai-sdk/provider\";\nimport {\n  BuiltInAIChatLanguageModel,\n  BuiltInAIChatModelId,\n  BuiltInAIChatSettings,\n} from \"./built-in-ai-language-model\";\nimport {\n  BuiltInAIEmbeddingModel,\n  BuiltInAIEmbeddingModelSettings,\n} from \"./built-in-ai-embedding-model\";\n\nexport interface BuiltInAIProvider extends ProviderV3 {\n  (\n    modelId?: BuiltInAIChatModelId,\n    settings?: BuiltInAIChatSettings,\n  ): BuiltInAIChatLanguageModel;\n\n  /**\n   * Creates a model for text generation.\n   */\n  languageModel(\n    modelId: BuiltInAIChatModelId,\n    settings?: BuiltInAIChatSettings,\n  ): BuiltInAIChatLanguageModel;\n\n  /**\n   * Creates a model for text generation.\n   */\n  chat(\n    modelId: BuiltInAIChatModelId,\n    settings?: BuiltInAIChatSettings,\n  ): BuiltInAIChatLanguageModel;\n\n  embedding(\n    modelId: \"embedding\",\n    settings?: BuiltInAIEmbeddingModelSettings,\n  ): EmbeddingModelV3;\n\n  embeddingModel: (\n    modelId: \"embedding\",\n    settings?: BuiltInAIEmbeddingModelSettings,\n  ) => EmbeddingModelV3;\n\n  // Not implemented\n  imageModel(modelId: string): never;\n  speechModel(modelId: string): never;\n  transcriptionModel(modelId: string): never;\n}\n\nexport interface BuiltInAIProviderSettings {\n  // Currently empty - provider settings are minimal for BuiltInAI\n  // Future provider-level settings can be added here\n}\n\n/**\n * Create a BuiltInAI provider instance.\n */\nexport function createBuiltInAI(\n  options: BuiltInAIProviderSettings = {},\n): BuiltInAIProvider {\n  const createChatModel = (\n    modelId: BuiltInAIChatModelId,\n    settings?: BuiltInAIChatSettings,\n  ) => {\n    return new BuiltInAIChatLanguageModel(modelId, settings);\n  };\n\n  const createEmbeddingModel = (\n    modelId: \"embedding\",\n    settings?: BuiltInAIEmbeddingModelSettings,\n  ) => {\n    return new BuiltInAIEmbeddingModel(settings);\n  };\n\n  const provider = function (\n    modelId: BuiltInAIChatModelId = \"text\",\n    settings?: BuiltInAIChatSettings,\n  ) {\n    if (new.target) {\n      throw new Error(\n        \"The BuiltInAI model function cannot be called with the new keyword.\",\n      );\n    }\n\n    return createChatModel(modelId, settings);\n  };\n\n  provider.specificationVersion = \"v3\" as const;\n  provider.languageModel = createChatModel;\n  provider.chat = createChatModel;\n  provider.embedding = createEmbeddingModel;\n  provider.embeddingModel = createEmbeddingModel;\n\n  provider.imageModel = (modelId: string) => {\n    throw new NoSuchModelError({ modelId, modelType: \"imageModel\" });\n  };\n\n  provider.speechModel = (modelId: string) => {\n    throw new NoSuchModelError({ modelId, modelType: \"speechModel\" });\n  };\n\n  provider.transcriptionModel = (modelId: string) => {\n    throw new NoSuchModelError({ modelId, modelType: \"transcriptionModel\" });\n  };\n\n  return provider;\n}\n\n/**\n * Default BuiltInAI provider instance.\n */\nexport const builtInAI = createBuiltInAI();\n"],"mappings":";AAAA;AAAA,EAKE;AAAA,OACK;;;ACGP,SAAS,mBAAmB,QAA6C;AACvE,QAAM,UAAmC;AAAA,IACvC,MAAM,OAAO;AAAA,IACb,QAAQ,OAAO,UAAU;AAAA,IACzB,OAA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