import { TavusClient, enableCostTracking, type ConversationRequest } from './tavus-client'; import { tavusCostController } from './tavus-cost-controller'; import { getTavusApiKey } from '@buzztrail/shared-config'; import type { TavusErrorObject } from '@buzztrail/shared-types'; import { logger } from '../logger'; /** * Toggle positions for the interface */ export type TopTogglePosition = 'video-tavus' | 'audio-vapi' | 'neither'; export type BottomTogglePosition = 'text-chat' | 'minimized'; /** * Interface state configuration */ export interface InterfaceState { topToggle: TopTogglePosition; bottomToggle: BottomTogglePosition; isTavusInitialized: boolean; isVideoActive: boolean; isAudioActive: boolean; conversationId?: string; sessionId?: string; } /** * Tavus API integration manager */ export class TavusIntegrationManager { private tavusClient: TavusClient | null = null; private interfaceState: InterfaceState; private isInitializing = false; private isTavusClientInitializing = false; private stateChangeCallback?: (state: InterfaceState) => void; private videoStreamReadyCallback?: (stream: MediaStream) => void; private errorCallback?: (error: Error) => void; constructor() { this.interfaceState = { topToggle: 'neither', bottomToggle: 'text-chat', isTavusInitialized: false, isVideoActive: false, isAudioActive: false, }; // Activate cost controller for development tavusCostController.activate(); // Enable cost tracking in TavusClient enableCostTracking((callType: string) => { return tavusCostController.trackApiCall(callType); }); } /** * Initialize the Tavus integration manager */ async initialize(): Promise { if (this.isInitializing) { logger.debug('TavusIntegrationManager already initializing'); return; } if (this.interfaceState.isTavusInitialized) { logger.debug('TavusIntegrationManager already initialized'); return; } this.isInitializing = true; try { logger.info('Initializing TavusIntegrationManager'); // Initialize TavusClient await this.initializeTavusClient(); // Clean up any existing conversations to prevent rate limiting await this.cleanupExistingConversations(); this.interfaceState.isTavusInitialized = true; this.notifyStateChange(); logger.info('TavusIntegrationManager initialized successfully'); } catch (error) { logger.error('Failed to initialize TavusIntegrationManager', error instanceof Error ? error : new Error(String(error))); throw error; } finally { this.isInitializing = false; } } /** * Initialize TavusClient with test API key */ private async initializeTavusClient(): Promise { if (this.tavusClient && this.interfaceState.isTavusInitialized) { console.log('TavusClient already initialized'); return; } if (this.isTavusClientInitializing) { console.log('TavusClient initialization already in progress'); return; } this.isTavusClientInitializing = true; try { console.log('Initializing TavusClient...'); // Initialize TavusClient with API key this.tavusClient = new TavusClient({ apiKey: getTavusApiKey(), debug: true, }); await this.tavusClient.initialize(); console.log('TavusClient initialized successfully'); // Note: Video streaming is now handled separately in setTopToggle // to prevent duplicate calls } catch (error) { console.error('Failed to initialize TavusClient:', error); this.tavusClient = null; this.interfaceState.isTavusInitialized = false; throw error; } finally { this.isTavusClientInitializing = false; } } /** * Clean up any existing conversations to prevent rate limiting */ private async cleanupExistingConversations(): Promise { try { if (!this.tavusClient) { return; } console.log('Cleaning up existing conversations...'); try { // Get existing conversations const conversations = await this.tavusClient.getConversations(); console.log(`Found ${conversations.length} existing conversations`); // End each conversation for (const conversation of conversations) { try { console.log(`Ending conversation: ${conversation.conversationId}`); await this.tavusClient.endConversation(conversation.conversationId); } catch (error) { console.warn(`Failed to end conversation ${conversation.conversationId}:`, error); } } console.log('Finished cleaning up existing conversations'); } catch (error) { console.warn('Could not get existing conversations (API may not support this):', error); } } catch (error) { console.warn('Error cleaning up existing conversations:', error); // Don't throw - this is not critical } } /** * Set top toggle position (Video/Tavus | Audio/Vapi | Neither) */ async setTopToggle( position: TopTogglePosition, options?: { conversationalContext?: string; pageUrl?: string; pageTitle?: string } ): Promise { const previousPosition = this.interfaceState.topToggle; this.interfaceState.topToggle = position; try { if (position === 'video-tavus') { console.log('Video/Tavus mode selected, checking initialization...'); // Initialize Tavus if not already initialized if (!this.interfaceState.isTavusInitialized) { console.log('Tavus not initialized, initializing...'); await this.initialize(); } // Start video streaming console.log('Checking TavusClient and initialization status...'); console.log('TavusClient exists:', !!this.tavusClient); console.log('isTavusInitialized:', this.interfaceState.isTavusInitialized); if (this.tavusClient && this.interfaceState.isTavusInitialized) { console.log('Starting video stream...'); await this.startVideoStream({ conversationalContext: options?.conversationalContext, pageUrl: options?.pageUrl, pageTitle: options?.pageTitle, }); } else { console.error('Cannot start video stream - TavusClient or initialization missing'); } } else { // Clean up video resources when switching away from video mode if (previousPosition === 'video-tavus') { await this.cleanupVideoResources(); } } this.notifyStateChange(); } catch (error) { console.error('Error setting top toggle:', error); if (this.errorCallback) { this.errorCallback(error instanceof Error ? error : new Error('Unknown error')); } } } /** * Set bottom toggle position (Text/Chat | Minimized) */ setBottomToggle(position: BottomTogglePosition): void { this.interfaceState.bottomToggle = position; this.notifyStateChange(); } /** * Start video streaming with Tavus API */ private async startVideoStream(options?: { conversationalContext?: string; pageUrl?: string; pageTitle?: string }): Promise { if (!this.tavusClient || !this.interfaceState.isTavusInitialized) { throw new Error('TavusClient not initialized'); } try { console.log('Attempting to start Tavus video stream...'); // Check cost controls before making API calls if (!tavusCostController.trackApiCall('create_conversation')) { throw new Error('Cost control limit reached. Cannot create conversation.'); } // Build navigation-aware context for demo visibility in logs and API const navContext = `You are assisting users on accu.co.uk. If the user asks for "rivets" or "locking washers" (or similar), reply affirmatively and the host app will navigate to the correct product page. Keep language concise.`; console.groupCollapsed('[Tavus][Demo] Building conversation request'); console.log('context.pageUrl:', options?.pageUrl); console.log('context.pageTitle:', options?.pageTitle); console.log('context.conversationalContext:', options?.conversationalContext); console.log('navContext (demo):', navContext); // Create a conversation with the known good replica and persona IDs // Note: Only send the required fields to avoid API errors const conversationRequest: ConversationRequest = { replicaId: 'rf4703150052', // Known good replica ID personaId: 'p48fdf065d6b', // Known good persona ID // Include conversational_context directly in the create request when provided ...(options?.conversationalContext ? { conversationalContext: `${options.conversationalContext}; ${navContext}` } : { conversationalContext: navContext }), }; console.log('conversationRequest:', conversationRequest); const conversation = await this.tavusClient.createConversation(conversationRequest); console.groupEnd(); this.interfaceState.conversationId = conversation.conversationId; // Start cost monitoring for this conversation tavusCostController.startConversationMonitoring(conversation.conversationId); console.log('Conversation created successfully:', { conversationId: conversation.conversationId, roomUrl: conversation.roomUrl, isActive: conversation.isActive }); // No need to send a separate first message solely for context now // Connect to the WebRTC room to get the video stream if (conversation.roomUrl) { console.log('Connecting to WebRTC room:', conversation.roomUrl); const videoStream = await this.tavusClient.connectToWebRTCRoom( conversation.roomUrl, conversation.accessToken ); console.log('WebRTC video stream connected successfully'); this.interfaceState.sessionId = conversation.conversationId; this.interfaceState.isVideoActive = true; // Notify that video stream is ready if (this.videoStreamReadyCallback) { this.videoStreamReadyCallback(videoStream); } } else { throw new Error('No room URL provided in conversation response'); } } catch (error) { console.error('Failed to start video stream:', error); // Log the actual error details if available if (error && typeof error === 'object') { const errorObj = error as TavusErrorObject; console.error('Error details:', { message: errorObj.message, type: errorObj.type, statusCode: errorObj.statusCode, context: errorObj.context, originalError: errorObj.originalError }); } // Don't set video as active if we failed this.interfaceState.isVideoActive = false; // Notify error callback if available if (this.errorCallback) { this.errorCallback(error as Error); } // Re-throw the error to let it propagate throw error; } } /** * Clean up video resources when switching away from video mode */ private async cleanupVideoResources(): Promise { try { // Stop cost monitoring tavusCostController.stopConversationMonitoring(); if (this.tavusClient && this.interfaceState.conversationId) { console.log('Ending conversation:', this.interfaceState.conversationId); // Check cost controls before making API calls if (tavusCostController.trackApiCall('end_conversation')) { // End the conversation to free up resources await this.tavusClient.endConversation(this.interfaceState.conversationId); } // Stop video stream if active if (this.interfaceState.sessionId) { try { await this.tavusClient.stopVideoStream(this.interfaceState.sessionId); } catch (error) { console.warn('Error stopping video stream:', error); } } } // Reset state this.interfaceState.conversationId = undefined; this.interfaceState.sessionId = undefined; this.interfaceState.isVideoActive = false; console.log('Video resources cleaned up'); } catch (error) { console.error('Error cleaning up video resources:', error); } } /** * Send a message through Tavus API */ sendMessage(message: string): string { if (!this.tavusClient || !this.interfaceState.isTavusInitialized) { throw new Error('TavusClient not initialized'); } try { // For now, return a simulated response // In real implementation, this would use TavusClient.sendMessage() return `Tavus API Response: ${message} (API Connected)`; } catch (error) { console.error('Failed to send message:', error); throw error; } } /** * Get current interface state */ getInterfaceState(): InterfaceState { return { ...this.interfaceState }; } /** * Get cost control statistics */ getCostStats(): Record { return tavusCostController.getUsageStats() as unknown as Record; } /** * Get cost control configuration */ getCostConfig(): Record { return tavusCostController.getConfig() as unknown as Record; } /** * Check if Tavus is initialized */ isTavusInitialized(): boolean { return this.interfaceState.isTavusInitialized; } /** * Check if video is active */ isVideoActive(): boolean { return this.interfaceState.isVideoActive; } /** * Set state change callback */ onStateChange(callback: (state: InterfaceState) => void): void { this.stateChangeCallback = callback; } /** * Set video stream ready callback */ onVideoStreamReady(callback: (stream: MediaStream) => void): void { this.videoStreamReadyCallback = callback; } /** * Set error callback */ onError(callback: (error: Error) => void): void { this.errorCallback = callback; } /** * Notify state change */ private notifyStateChange(): void { if (this.stateChangeCallback) { this.stateChangeCallback(this.getInterfaceState()); } } /** * Cleanup resources */ async cleanup(): Promise { try { await this.cleanupVideoResources(); if (this.tavusClient) { // Additional cleanup if needed this.tavusClient = null; } this.interfaceState.isTavusInitialized = false; console.log('TavusIntegrationManager cleaned up'); } catch (error) { console.error('Error during cleanup:', error); } } }