{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "firebase-chat-transport",
  "type": "registry:item",
  "title": "Firebase Chat Transport",
  "description": "Client-side ChatTransport implementation for Firebase AI Logic (Gemini) with multi-turn streaming, tool calling, and Google Search grounding",
  "dependencies": [
    "@ai-sdk/react",
    "ai",
    "firebase",
    "zod",
    "@ai-sdk/ui-utils"
  ],
  "registryDependencies": [],
  "files": [
    {
      "path": "firebase/firebase-chat-transport/firebase-chat-transport.ts",
      "target": "src/mui-treasury/firebase/firebase-chat-transport/firebase-chat-transport.ts",
      "content": "/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { UIMessage } from '@ai-sdk/react';\nimport {\n  type ChatTransport,\n  IdGenerator,\n  type StepResult,\n  type StopCondition,\n  type Tool,\n  type ToolSet,\n  type UIMessageChunk,\n  generateId as generateIdFunc,\n  stepCountIs,\n} from 'ai';\nimport {\n  type ChatSession,\n  type EnhancedGenerateContentResponse,\n  type FileDataPart,\n  type Tool as FirebaseAiTool,\n  type FunctionCall,\n  type FunctionDeclaration,\n  type FunctionResponsePart,\n  type GenerativeModel,\n  GoogleAIBackend,\n  type HybridParams,\n  type InlineDataPart,\n  type ModelParams,\n  type Part,\n  getAI,\n  getGenerativeModel,\n} from 'firebase/ai';\nimport type { FirebaseApp } from 'firebase/app';\nimport { z } from 'zod';\n\ntype ProviderMetadata = Record<string, any>;\n\n/**\n * Options for initializing FirebaseChatTransport.\n *\n * Note: Firebase SDK types are not imported to avoid hard dependency.\n * Users must install firebase package separately.\n */\nexport interface FirebaseChatTransportOptions {\n  /**\n   * Initialized Firebase app instance.\n   * Must be created via initializeApp() from 'firebase/app'.\n   */\n  firebaseApp: FirebaseApp; // FirebaseApp type\n\n  /**\n   * ID generator function for message IDs.\n   * @default AI SDK's generateId\n   */\n  generateId?: IdGenerator;\n\n  /**\n   * Parameters for configuring the generative model.\n   * Includes model name, system instructions, generation config, safety settings, and tools.\n   * @see https://firebase.google.com/docs/reference/js/ai.modelparams\n   */\n  modelParams: ModelParams | HybridParams;\n\n  /**\n   * AI SDK tools for client-side function calling.\n   * Tools are converted to Firebase FunctionDeclarations and executed automatically.\n   * @see https://firebase.google.com/docs/ai-logic/function-calling\n   */\n  tools?: Record<string, Tool>;\n\n  /**\n   * Enable grounding with Google Search.\n   * When enabled, responses may include grounding metadata in message.metadata.grounding.\n   * @see https://firebase.google.com/docs/ai-logic/grounding-google-search\n   */\n  enableGoogleSearch?: boolean;\n\n  /**\n   * Stop condition(s) for tool execution loop.\n   * Controls when to stop executing tools and return final response.\n   * Uses the same API as generateText/streamText stopWhen.\n   *\n   * @default stepCountIs(20)\n   * @example\n   * // Stop after 5 iterations\n   * stopWhen: stepCountIs(5)\n   *\n   * @example\n   * // Stop when specific tool is called\n   * stopWhen: hasToolCall('final_answer')\n   *\n   * @example\n   * // Multiple conditions (OR logic - stops if ANY condition is met)\n   * stopWhen: [stepCountIs(10), hasToolCall('done')]\n   */\n  stopWhen?: StopCondition<any> | Array<StopCondition<any>>;\n}\n\nasync function isStopConditionMet<TOOLS extends ToolSet>({\n  stopConditions,\n  steps,\n}: {\n  stopConditions: Array<StopCondition<TOOLS>>;\n  steps: Array<StepResult<TOOLS>>;\n}): Promise<boolean> {\n  return (\n    await Promise.all(stopConditions.map((condition) => condition({ steps })))\n  ).some((result) => result);\n}\n\n/**\n * Client-side ChatTransport implementation for Firebase AI Logic (Gemini).\n *\n * Enables browser-based chat streaming using Firebase's sendMessageStream API\n * with multi-turn conversation support and automatic tool execution.\n *\n * Features:\n * - Multi-turn text streaming\n * - Multimodal input/output (images, videos, audio)\n *   - Data URLs (base64): converted to inlineData\n *   - Hosted URLs (http/https): converted to fileData with fileUri\n *   - YouTube URLs supported for video analysis\n * - Interleaved text and image generation (requires gemini-2.5-flash-image model)\n * - Thinking/reasoning support (via thoughtSummary, streamed incrementally)\n * - Client-side tool/function calling with automatic execution\n * - Tool call loop (model can call multiple tools until final response)\n * - Configurable stop conditions (via stopWhen option, same API as generateText)\n * - Google Search grounding (via enableGoogleSearch option)\n *\n * Limitations:\n * - Single active chat at a time\n * - No stream reconnection (client-side)\n * - Client-side tool execution only (no server-side tool execution)\n * - No tool approval workflow (tools execute immediately)\n *\n * @example Basic usage\n * ```ts\n * import { initializeApp } from 'firebase/app';\n * import { FirebaseChatTransport } from '@ai-sdk/ui-utils';\n *\n * const app = initializeApp({ ... });\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: { model: 'gemini-2.5-flash' }\n * });\n * ```\n *\n * @example With thinking enabled\n * ```ts\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: {\n *     model: 'gemini-2.5-flash',\n *     generationConfig: {\n *       thinkingConfig: { includeThoughts: true }\n *     }\n *   }\n * });\n * // Reasoning parts will be streamed as 'reasoning' type in message.parts\n * ```\n *\n * @example With interleaved text and image generation\n * ```ts\n * import { ResponseModality } from 'firebase/ai';\n *\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: {\n *     model: 'gemini-2.5-flash-image',\n *     generationConfig: {\n *       responseModalities: [ResponseModality.TEXT, ResponseModality.IMAGE]\n *     }\n *   }\n * });\n * // Images will be emitted as 'file' chunks with data URLs\n * ```\n *\n * @example With tools\n * ```ts\n * import { tool } from 'ai';\n * import { z } from 'zod';\n *\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: { model: 'gemini-2.5-flash' },\n *   tools: {\n *     getWeather: tool({\n *       description: 'Get weather for a city',\n *       inputSchema: z.object({\n *         city: z.string(),\n *         state: z.string(),\n *       }),\n *       execute: async ({ city, state }) => {\n *         return { temperature: 72, conditions: 'sunny' };\n *       },\n *     }),\n *   },\n * });\n * ```\n *\n * @example With Google Search grounding\n * ```ts\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: { model: 'gemini-2.5-flash' },\n *   enableGoogleSearch: true,\n * });\n * // Grounding metadata available in message.metadata.grounding:\n * // - webSearchQueries: string[]\n * // - searchEntryPoint: { renderedContent: string } (required HTML to render)\n * // - groundingChunks: Array<{ web: { uri, title } }>\n * // - groundingSupports: Array<{ segment, groundingChunkIndices, confidenceScores }>\n * ```\n *\n * @example With YouTube URLs in text\n * ```ts\n * // YouTube URLs in text are automatically extracted as fileData parts!\n * // User input: \"Summarize this video https://youtube.com/watch?v=xxx\"\n * // Converted to: [{ text: \"Summarize this video\" }, { fileData: { fileUri: \"...\", mimeType: \"video/*\" } }]\n *\n * // Supported YouTube URL formats:\n * // - https://www.youtube.com/watch?v=VIDEO_ID\n * // - https://youtube.com/watch?v=VIDEO_ID\n * // - https://youtu.be/VIDEO_ID\n * // - https://www.youtube.com/embed/VIDEO_ID\n * ```\n *\n * @example With custom stop conditions\n * ```ts\n * import { stepCountIs, hasToolCall } from 'ai';\n *\n * const transport = new FirebaseChatTransport({\n *   firebaseApp: app,\n *   modelParams: { model: 'gemini-2.5-flash' },\n *   tools: { /* ... *\\/ },\n *   // Stop after 5 tool iterations OR when 'done' tool is called\n *   stopWhen: [stepCountIs(5), hasToolCall('done')],\n * });\n * ```\n */\nexport class FirebaseChatTransport<\n  UI_MESSAGE extends UIMessage,\n> implements ChatTransport<UI_MESSAGE> {\n  private firebaseModel: GenerativeModel;\n  private currentChatId: string | null = null;\n  private chatSession: ChatSession | null = null;\n  private generateId: IdGenerator;\n  private tools: Record<string, Tool>;\n  private stopConditions: Array<StopCondition<any>>;\n\n  constructor(options: FirebaseChatTransportOptions) {\n    const ai = getAI(options.firebaseApp, { backend: new GoogleAIBackend() });\n\n    this.tools = options.tools || {};\n    this.generateId = options.generateId ?? generateIdFunc;\n\n    // Initialize stop conditions (default: stepCountIs(20) to match server-side)\n    const stopWhen = options.stopWhen ?? stepCountIs(20);\n    this.stopConditions = Array.isArray(stopWhen) ? stopWhen : [stopWhen];\n\n    const functionDeclarations = Object.entries(this.tools).map(\n      ([name, tool]) => this.convertToolToFunctionDeclaration(name, tool),\n    );\n\n    // Build tools array with function declarations and/or Google Search\n    const toolsArray: Array<FirebaseAiTool> = [];\n    if (functionDeclarations.length > 0) {\n      toolsArray.push({ functionDeclarations });\n    }\n    if (options.enableGoogleSearch) {\n      toolsArray.push({ googleSearch: {} });\n    }\n\n    const modelParams = { ...options.modelParams } as ModelParams;\n    if (toolsArray.length > 0) {\n      modelParams.tools = toolsArray;\n    }\n\n    this.firebaseModel = getGenerativeModel(ai, modelParams);\n  }\n\n  async sendMessages(\n    options: Parameters<ChatTransport<UI_MESSAGE>['sendMessages']>[0],\n  ): Promise<ReadableStream<UIMessageChunk>> {\n    const { chatId, messages, abortSignal } = options;\n\n    // Check if chat session needs reset\n    if (this.currentChatId !== chatId) {\n      this.currentChatId = chatId;\n      this.chatSession = null;\n    }\n\n    return new ReadableStream<UIMessageChunk>({\n      start: async (controller) => {\n        let isAborted = false;\n\n        // Listen for abort signal\n        if (abortSignal) {\n          abortSignal.addEventListener('abort', () => {\n            isAborted = true;\n            controller.enqueue({ type: 'abort' });\n            controller.close();\n          });\n        }\n\n        try {\n          // Extract and preprocess only the last user message\n          const lastUserMessage = await this.extractLastUserMessage(messages);\n\n          // Create or reuse chat session\n          if (!this.chatSession) {\n            // New session: convert all prior messages as history\n            const priorMessages = messages.slice(0, -1);\n            await this.preprocessMessages(priorMessages);\n            const history =\n              this.convertMessagesToFirebaseContent(priorMessages);\n            this.chatSession = this.firebaseModel.startChat({\n              history: history.length > 0 ? history : undefined,\n            });\n          }\n\n          // Generate message ID for tracking\n          const messageId = this.generateId();\n\n          // Tool execution loop\n          let continueLoop = true;\n          let startEmitted = false;\n          let pendingFunctionResponses: FunctionResponsePart[] | null = null;\n          // Track steps for stop condition evaluation\n          const steps: StepResult<any>[] = [];\n\n          while (continueLoop && !isAborted) {\n            let result;\n\n            if (pendingFunctionResponses) {\n              // Send function responses from previous iteration\n              result = await this.chatSession.sendMessageStream(\n                pendingFunctionResponses,\n              );\n              pendingFunctionResponses = null;\n            } else {\n              // Send initial user message\n              result =\n                await this.chatSession.sendMessageStream(lastUserMessage);\n            }\n\n            // Emit start chunk after connection established (once)\n            if (!startEmitted) {\n              controller.enqueue({\n                type: 'start',\n                messageId,\n              });\n              startEmitted = true;\n            }\n\n            // Stream text and handle interleaved images\n            let hasReasoning = false;\n            let reasoningId: string | null = null;\n            let lastProviderMetadata: ProviderMetadata | undefined = undefined;\n\n            // Simple state: track current text part and emitted images\n            let currentTextId: string | null = null;\n            const emittedImageHashes = new Set<string>();\n\n            for await (const chunk of result.stream) {\n              if (isAborted) break;\n\n              // Extract provider metadata from chunk\n              const providerMetadata = this.extractProviderMetadata(chunk);\n              lastProviderMetadata = providerMetadata;\n\n              // Access parts structure for interleaved streaming\n              const chunkParts = chunk.candidates?.[0]?.content?.parts;\n\n              // Handle thinking/reasoning content (streamed)\n              // If thought exists, process ONLY reasoning and skip text\n              const thought = chunk.thoughtSummary?.();\n              if (thought) {\n                if (!hasReasoning) {\n                  reasoningId = this.generateId();\n                  controller.enqueue({\n                    type: 'reasoning-start',\n                    id: reasoningId,\n                    providerMetadata,\n                  });\n                  hasReasoning = true;\n                }\n\n                controller.enqueue({\n                  type: 'reasoning-delta',\n                  id: reasoningId!,\n                  delta: thought,\n                  providerMetadata,\n                });\n                continue; // Skip text processing while thinking\n              }\n\n              // Close reasoning when thought stops growing and we move to text\n              if (hasReasoning && reasoningId) {\n                controller.enqueue({\n                  type: 'reasoning-end',\n                  id: reasoningId,\n                  providerMetadata,\n                });\n                hasReasoning = false;\n                reasoningId = null;\n              }\n\n              if (chunkParts && chunkParts.length > 0) {\n                for (const part of chunkParts) {\n                  if ('text' in part && part.text) {\n                    // Start text part if not already open\n                    if (!currentTextId) {\n                      currentTextId = this.generateId();\n                      controller.enqueue({\n                        type: 'text-start',\n                        id: currentTextId,\n                        providerMetadata,\n                      });\n                    }\n\n                    // Emit delta directly - Firebase sends incremental text per chunk\n                    controller.enqueue({\n                      type: 'text-delta',\n                      id: currentTextId,\n                      delta: part.text,\n                      providerMetadata,\n                    });\n                  }\n\n                  if ('inlineData' in part && part.inlineData) {\n                    // Dedupe images using hash of length + samples from start/middle/end.\n                    // Using only the first N chars causes collision because images\n                    // often share similar base64 headers (e.g., PNG/JPEG magic bytes).\n                    const data = part.inlineData.data;\n                    const imageHash = `${data.length}:${data.substring(0, 50)}:${data.substring(Math.floor(data.length / 2), Math.floor(data.length / 2) + 50)}:${data.substring(data.length - 50)}`;\n                    if (!emittedImageHashes.has(imageHash)) {\n                      // Close current text part before emitting image\n                      if (currentTextId) {\n                        controller.enqueue({\n                          type: 'text-end',\n                          id: currentTextId,\n                          providerMetadata,\n                        });\n                        currentTextId = null;\n                      }\n\n                      controller.enqueue({\n                        type: 'file',\n                        url: `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`,\n                        mediaType: part.inlineData.mimeType,\n                      });\n                      emittedImageHashes.add(imageHash);\n                    }\n                  }\n                }\n              } else {\n                // Fallback: parts not available, use chunk.text()\n                const text = chunk.text();\n                if (text) {\n                  // Close reasoning when text starts\n                  if (hasReasoning && reasoningId) {\n                    controller.enqueue({\n                      type: 'reasoning-end',\n                      id: reasoningId,\n                      providerMetadata,\n                    });\n                    hasReasoning = false;\n                    reasoningId = null;\n                  }\n\n                  // Start text part if not already open\n                  if (!currentTextId) {\n                    currentTextId = this.generateId();\n                    controller.enqueue({\n                      type: 'text-start',\n                      id: currentTextId,\n                      providerMetadata,\n                    });\n                  }\n\n                  // Emit delta directly\n                  controller.enqueue({\n                    type: 'text-delta',\n                    id: currentTextId,\n                    delta: text,\n                    providerMetadata,\n                  });\n                }\n              }\n            }\n\n            if (isAborted) return;\n\n            // Close any open reasoning part\n            if (hasReasoning && reasoningId) {\n              controller.enqueue({\n                type: 'reasoning-end',\n                id: reasoningId,\n                providerMetadata: lastProviderMetadata,\n              });\n            }\n\n            // Close any open text part\n            if (currentTextId) {\n              controller.enqueue({\n                type: 'text-end',\n                id: currentTextId,\n                providerMetadata: lastProviderMetadata,\n              });\n            }\n\n            // Get final response and check for function calls\n            const response = await result.response;\n            const functionCalls = response.functionCalls?.();\n\n            if (!functionCalls || functionCalls.length === 0) {\n              // Emit any remaining images not emitted during streaming\n              const parts = response.candidates?.[0]?.content?.parts;\n              if (parts) {\n                for (const part of parts) {\n                  if ('inlineData' in part && part.inlineData) {\n                    // Same hash logic as streaming section (length + start/middle/end samples)\n                    const data = part.inlineData.data;\n                    const imageHash = `${data.length}:${data.substring(0, 50)}:${data.substring(Math.floor(data.length / 2), Math.floor(data.length / 2) + 50)}:${data.substring(data.length - 50)}`;\n                    if (!emittedImageHashes.has(imageHash)) {\n                      controller.enqueue({\n                        type: 'file',\n                        url: `data:${part.inlineData.mimeType};base64,${part.inlineData.data}`,\n                        mediaType: part.inlineData.mimeType,\n                      });\n                      emittedImageHashes.add(imageHash);\n                    }\n                  }\n                }\n              }\n\n              // Track this step for stop condition evaluation (matches server-side behavior)\n              // Every LLM response creates a step, regardless of tool calls\n              steps.push({ toolCalls: [] } as unknown as StepResult<any>);\n\n              // No tool calls - emit finish and exit loop\n              const finishReason = response.candidates?.[0]?.finishReason;\n\n              // Extract grounding metadata if available\n              const groundingMetadata =\n                response.candidates?.[0]?.groundingMetadata;\n\n              controller.enqueue({\n                type: 'finish',\n                finishReason: this.mapFinishReason(finishReason),\n                messageMetadata: groundingMetadata,\n              });\n              continueLoop = false;\n            } else {\n              // Track step for stop condition evaluation\n              steps.push({\n                toolCalls: functionCalls.map((fc: FunctionCall) => ({\n                  type: 'tool-call' as const,\n                  toolCallId: this.generateId(),\n                  toolName: fc.name,\n                  input: fc.args,\n                })),\n              } as StepResult<any>);\n\n              // Check stop conditions (OR logic - stops if ANY condition is met)\n              // Cast needed: StopCondition expects full StepResult but built-in\n              // helpers (stepCountIs, hasToolCall) only access steps.length and toolCalls\n              const shouldStop = await isStopConditionMet({\n                stopConditions: this.stopConditions,\n                steps,\n              });\n\n              if (shouldStop) {\n                // Stop condition met - finish with tool-calls reason\n                controller.enqueue({\n                  type: 'finish',\n                  finishReason: 'tool-calls',\n                });\n                continueLoop = false;\n              } else {\n                // Execute tools and prepare responses for next iteration\n                pendingFunctionResponses = await this.executeTools(\n                  functionCalls,\n                  controller,\n                );\n              }\n            }\n          }\n\n          controller.close();\n        } catch (error) {\n          // Emit error chunk and close gracefully\n          controller.enqueue({\n            type: 'error',\n            errorText: error instanceof Error ? error.message : 'Unknown error',\n          });\n          controller.close();\n        }\n      },\n    });\n  }\n\n  async reconnectToStream(\n    _: Parameters<ChatTransport<UI_MESSAGE>['reconnectToStream']>[0],\n  ): Promise<ReadableStream<UIMessageChunk> | null> {\n    // Client-side cannot reconnect to streams\n    // Would need server-side persistence\n    return null;\n  }\n\n  /**\n   * Convert UI message role to Firebase Content role.\n   */\n  private convertRole(role: UI_MESSAGE['role']): 'user' | 'model' {\n    return role === 'assistant' ? 'model' : 'user';\n  }\n\n  /**\n   * Convert UI messages to Firebase Content format.\n   * - Text parts: YouTube URLs extracted as fileData parts\n   * - File parts: converted to inlineData (data URLs) or fileData (hosted URLs)\n   */\n  private convertMessagesToFirebaseContent(\n    messages: UI_MESSAGE[],\n  ): Array<{ role: 'user' | 'model'; parts: Part[] }> {\n    return messages\n      .map((message) => ({\n        role: this.convertRole(message.role),\n        parts: message.parts.flatMap(\n          (part: UI_MESSAGE['parts'][number]): Part[] => {\n            if (part.type === 'text') {\n              return this.convertTextToPartsWithYouTube(part.text);\n            }\n            if (part.type === 'file') {\n              return [this.convertFileToFirebasePart(part.url, part.mediaType)];\n            }\n            return [];\n          },\n        ),\n      }))\n      .filter((content) => content.parts.length > 0);\n  }\n\n  /**\n   * Extract and preprocess last user message from messages array.\n   * - Converts blob URLs to data URLs\n   * - Extracts YouTube URLs from text as fileData parts\n   * Throws if last message is not from user.\n   */\n  private async extractLastUserMessage(\n    messages: UI_MESSAGE[],\n  ): Promise<Part[]> {\n    if (messages.length === 0) {\n      throw new Error('Cannot send empty message history');\n    }\n\n    const lastMessage = messages[messages.length - 1];\n\n    if (lastMessage.role !== 'user') {\n      throw new Error(\n        'Last message must be from user. Firebase requires user message to generate response.',\n      );\n    }\n\n    // Preprocess only the last message (convert blob URLs)\n    await this.preprocessMessages([lastMessage]);\n\n    const parts = lastMessage.parts.flatMap(\n      (part: UI_MESSAGE['parts'][number]): Part[] => {\n        if (part.type === 'text') {\n          return this.convertTextToPartsWithYouTube(part.text);\n        }\n        if (part.type === 'file') {\n          return [this.convertFileToFirebasePart(part.url, part.mediaType)];\n        }\n        return [];\n      },\n    );\n\n    if (parts.length === 0) {\n      throw new Error('Last message has no text or file content');\n    }\n\n    return parts;\n  }\n\n  /**\n   * Map Firebase finish reason to AI SDK format.\n   */\n  private mapFinishReason(\n    finishReason?: string,\n  ): 'stop' | 'length' | 'content-filter' | 'other' {\n    switch (finishReason) {\n      case 'STOP':\n        return 'stop';\n      case 'MAX_TOKENS':\n        return 'length';\n      case 'SAFETY':\n        return 'content-filter';\n      default:\n        return 'other';\n    }\n  }\n\n  /**\n   * Execute Firebase function calls and emit tool chunks.\n   * Returns array of function responses to send back to Firebase.\n   */\n  private async executeTools(\n    functionCalls: FunctionCall[],\n    controller: ReadableStreamDefaultController<UIMessageChunk>,\n  ): Promise<FunctionResponsePart[]> {\n    const results: FunctionResponsePart[] = [];\n\n    for (const call of functionCalls) {\n      const toolCallId = this.generateId();\n      const toolName = call.name;\n\n      // Emit tool-input-start\n      controller.enqueue({\n        type: 'tool-input-start',\n        toolCallId,\n        toolName,\n      });\n\n      // Emit tool-input-available (Firebase provides complete input)\n      controller.enqueue({\n        type: 'tool-input-available',\n        toolCallId,\n        toolName,\n        input: call.args,\n      });\n\n      try {\n        // Look up and execute tool\n        const tool = this.tools[toolName];\n        if (!tool) {\n          throw new Error(`Tool '${toolName}' not found`);\n        }\n\n        if (!tool.execute) {\n          throw new Error(`Tool '${toolName}' has no execute function`);\n        }\n\n        const output = await tool.execute(call.args, {\n          toolCallId,\n          messages: [],\n        });\n\n        // Emit tool-output-available\n        controller.enqueue({\n          type: 'tool-output-available',\n          toolCallId,\n          output: output ?? null,\n        });\n\n        // Build Firebase function response\n        results.push({\n          functionResponse: {\n            name: toolName,\n            response: output ?? null,\n          },\n        });\n      } catch (error) {\n        const errorText =\n          error instanceof Error ? error.message : 'Unknown error';\n\n        // Emit tool-output-error\n        controller.enqueue({\n          type: 'tool-output-error',\n          toolCallId,\n          errorText,\n        });\n\n        // Return error response to Firebase\n        results.push({\n          functionResponse: {\n            name: toolName,\n            response: { error: errorText },\n          },\n        });\n      }\n    }\n\n    return results;\n  }\n\n  /**\n   * Convert AI SDK Tool to Firebase FunctionDeclaration.\n   */\n  private convertToolToFunctionDeclaration(\n    toolName: string,\n    tool: Tool,\n  ): FunctionDeclaration {\n    return {\n      name: toolName,\n      description: tool.description || '',\n      parameters: this.convertSchemaToFirebase(tool.inputSchema),\n    };\n  }\n\n  /**\n   * Convert AI SDK schema to Firebase Schema format.\n   * Uses Zod's built-in toJSONSchema for Zod schemas, passes through JSON schemas.\n   * Strips fields not supported by Gemini's OpenAPI Schema subset.\n   */\n  private convertSchemaToFirebase(\n    schema: Tool['inputSchema'],\n  ): FunctionDeclaration['parameters'] {\n    let jsonSchema: Record<string, unknown>;\n    if (schema !== null && typeof schema === 'object' && '_zod' in schema) {\n      jsonSchema = z.toJSONSchema(schema, {\n        target: 'draft-7',\n        io: 'output',\n        reused: 'inline',\n      }) as Record<string, unknown>;\n    } else {\n      jsonSchema = schema as Record<string, unknown>;\n    }\n    return this.stripUnsupportedSchemaFields(\n      jsonSchema,\n    ) as FunctionDeclaration['parameters'];\n  }\n\n  /**\n   * Recursively strip JSON Schema fields not supported by Gemini API.\n   * Gemini uses OpenAPI Schema subset which doesn't support $schema, additionalProperties, etc.\n   */\n  private stripUnsupportedSchemaFields(obj: unknown): unknown {\n    if (obj === null || typeof obj !== 'object') {\n      return obj;\n    }\n\n    if (Array.isArray(obj)) {\n      return obj.map((item) => this.stripUnsupportedSchemaFields(item));\n    }\n\n    const unsupportedFields = ['$schema', 'additionalProperties'];\n    const result: Record<string, unknown> = {};\n\n    for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n      if (!unsupportedFields.includes(key)) {\n        result[key] = this.stripUnsupportedSchemaFields(value);\n      }\n    }\n\n    return result;\n  }\n\n  /**\n   * YouTube URL pattern to match various formats:\n   * - https://www.youtube.com/watch?v=VIDEO_ID\n   * - https://youtube.com/watch?v=VIDEO_ID\n   * - https://youtu.be/VIDEO_ID\n   * - https://www.youtube.com/embed/VIDEO_ID\n   */\n  private static readonly YOUTUBE_URL_REGEX =\n    /https?:\\/\\/(?:www\\.)?(?:youtube\\.com\\/(?:watch\\?v=|embed\\/)|youtu\\.be\\/)[\\w-]+(?:[?&][\\w=-]*)*(?:#[\\w-]*)?/g;\n\n  /**\n   * Check if URL is a YouTube URL.\n   */\n  private isYouTubeUrl(url: string): boolean {\n    return (\n      url.includes('youtube.com/') ||\n      url.includes('youtu.be/') ||\n      url.includes('youtube.googleapis.com/')\n    );\n  }\n\n  /**\n   * Convert a text part to Firebase Parts, extracting YouTube URLs as fileData.\n   * Example: \"Summarize https://youtube.com/watch?v=xxx please\"\n   * Becomes: [{ text: \"Summarize \" }, { fileData: {...} }, { text: \" please\" }]\n   */\n  private convertTextToPartsWithYouTube(text: string): Part[] {\n    const parts: Part[] = [];\n    let lastIndex = 0;\n\n    // Reset regex state\n    FirebaseChatTransport.YOUTUBE_URL_REGEX.lastIndex = 0;\n\n    let match;\n    while (\n      (match = FirebaseChatTransport.YOUTUBE_URL_REGEX.exec(text)) !== null\n    ) {\n      // Add text before the URL\n      if (match.index > lastIndex) {\n        const textBefore = text.slice(lastIndex, match.index).trim();\n        if (textBefore) {\n          parts.push({ text: textBefore });\n        }\n      }\n\n      // Add YouTube URL as fileData\n      parts.push({\n        fileData: {\n          mimeType: 'video/*',\n          fileUri: match[0],\n        },\n      });\n\n      lastIndex = match.index + match[0].length;\n    }\n\n    // Add remaining text after last URL\n    if (lastIndex < text.length) {\n      const textAfter = text.slice(lastIndex).trim();\n      if (textAfter) {\n        parts.push({ text: textAfter });\n      }\n    }\n\n    // No YouTube URLs found, return original text\n    if (parts.length === 0) {\n      return [{ text }];\n    }\n\n    return parts;\n  }\n\n  /**\n   * Convert a file part URL to Firebase Part format.\n   * Supports:\n   * - Data URLs (data:...): converted to inlineData\n   * - Hosted URLs (http/https): converted to fileData with fileUri\n   *\n   * @see https://firebase.google.com/docs/ai-logic/input-file-requirements\n   */\n  private convertFileToFirebasePart(\n    url: string,\n    mimeType: string,\n  ): InlineDataPart | FileDataPart {\n    // YouTube URL: use fileData with video/*\n    if (this.isYouTubeUrl(url)) {\n      return {\n        fileData: {\n          mimeType: 'video/*',\n          fileUri: url,\n        },\n      };\n    }\n\n    // Data URL: use inlineData\n    if (url.startsWith('data:')) {\n      const base64Match = url.match(/^data:[^;]+;base64,(.+)$/);\n      if (!base64Match) {\n        throw new Error(\n          'Invalid data URL format. Expected base64 encoded data URL.',\n        );\n      }\n      return {\n        inlineData: {\n          mimeType,\n          data: base64Match[1],\n        },\n      };\n    }\n\n    // Hosted URL (http/https): use fileData\n    if (url.startsWith('http://') || url.startsWith('https://')) {\n      return {\n        fileData: {\n          mimeType,\n          fileUri: url,\n        },\n      };\n    }\n\n    throw new Error(\n      `Unsupported URL format: ${url.substring(\n        0,\n        50,\n      )}. Expected data: or http(s): URL.`,\n    );\n  }\n\n  /**\n   * Convert blob URL to base64 data URL.\n   */\n  private async blobUrlToDataUrl(blobUrl: string): Promise<string> {\n    const response = await fetch(blobUrl);\n    const blob = await response.blob();\n    return new Promise((resolve, reject) => {\n      const reader = new FileReader();\n      reader.onloadend = () => resolve(reader.result as string);\n      reader.onerror = reject;\n      reader.readAsDataURL(blob);\n    });\n  }\n\n  /**\n   * Pre-process messages to convert blob URLs to data URLs.\n   */\n  private async preprocessMessages(messages: UI_MESSAGE[]): Promise<void> {\n    for (const message of messages) {\n      for (const part of message.parts) {\n        if (part.type === 'file' && part.url && part.url.startsWith('blob:')) {\n          // Convert blob URL to data URL in place\n          (part as { url: string }).url = await this.blobUrlToDataUrl(part.url);\n        }\n      }\n    }\n  }\n\n  /**\n   * Extract provider metadata from Firebase chunk.\n   * Includes usageMetadata when available.\n   */\n  private extractProviderMetadata(\n    chunk: EnhancedGenerateContentResponse,\n  ): ProviderMetadata | undefined {\n    if (chunk.usageMetadata) {\n      return { firebase: { usageMetadata: chunk.usageMetadata } };\n    }\n    return undefined;\n  }\n}\n",
      "type": "registry:item"
    },
    {
      "path": "firebase/firebase-chat-transport/index.ts",
      "target": "src/mui-treasury/firebase/firebase-chat-transport/index.ts",
      "content": "export * from './firebase-chat-transport';\nexport { FirebaseChatTransport as default } from './firebase-chat-transport';\n",
      "type": "registry:item"
    }
  ],
  "meta": {
    "category": "ai",
    "subcategory": "firebase",
    "previewClassName": "h-[624px!important]"
  }
}