import { v4 as uuidv4 } from 'uuid'; import type { Conversation } from '@buzztrail/shared-database'; // Configuration interface for unified conversation creation export interface UnifiedConversationConfig { persona_id: string; replica_id?: string; conversation_name?: string; callback_url?: string; // Daily.js room configuration room_config?: { participant_left_timeout?: number; // Default: 60 seconds enable_closed_captions?: boolean; // Default: true enable_chat?: boolean; enable_screenshare?: boolean; max_participants?: number; room_privacy?: 'public' | 'private'; }; // Customer context customer_id: string; environment: 'development' | 'staging' | 'production'; } export interface ConversationResponse { conversation_id: string; conversation_name: string; status: string; conversation_url: string; daily_room_url?: string; room_config?: Record; created_at: string; } export interface DailyRoom { name: string; url: string; created_at: string; config: Record; } export interface TavusAPIClient { createConversation(config: Record): Promise>; } export interface DailyAPIClient { createRoom(config: Record): Promise; } export interface DatabaseManager { createConversation(conversation: Partial): Promise; updateConversation(id: string, updates: Partial): Promise; getConversationById(id: string): Promise; } /** * Unified Conversation Service * * Provides consistent conversation creation across fake and real Tavus servers * with comprehensive configuration and data capture. */ export class UnifiedConversationService { private db: DatabaseManager; private tavusClient: TavusAPIClient; private dailyClient: DailyAPIClient; constructor( db: DatabaseManager, tavusClient: TavusAPIClient, dailyClient: DailyAPIClient ) { this.db = db; this.tavusClient = tavusClient; this.dailyClient = dailyClient; } /** * Create a conversation with unified configuration for both fake and real servers */ async createConversation(config: UnifiedConversationConfig): Promise { const conversationId = uuidv4(); const roomName = this.generateRoomName(config.customer_id, config.persona_id); try { // Create Daily.js room with enhanced configuration const dailyRoom = await this.createDailyRoom(roomName, { participant_left_timeout: config.room_config?.participant_left_timeout || 60, enable_closed_captions: config.room_config?.enable_closed_captions ?? true, enable_chat: config.room_config?.enable_chat ?? true, max_participants: config.room_config?.max_participants || 2, room_privacy: config.room_config?.room_privacy || 'private' }); // Store conversation in database first const conversation = await this.db.createConversation({ id: conversationId, customer_id: config.customer_id, conversation_name: config.conversation_name || `Conversation with ${config.persona_id}`, persona_id: config.persona_id, replica_id: config.replica_id, status: 'created', daily_room_name: roomName, daily_room_url: dailyRoom.url, conversation_url: this.generateConversationUrl(conversationId), room_config: JSON.stringify(config.room_config), participant_left_timeout: config.room_config?.participant_left_timeout || 60, enable_closed_captions: config.room_config?.enable_closed_captions ?? true, callback_url: config.callback_url, environment: config.environment, source_type: config.environment === 'development' ? 'fake' : 'real', created_at: new Date().toISOString() }); // Create conversation with appropriate service let tavusResponse; if (config.environment === 'development') { tavusResponse = await this.createFakeConversation(conversation); } else { tavusResponse = await this.createRealConversation(conversation, config); } // Update conversation with Tavus response data await this.db.updateConversation(conversationId, { status: tavusResponse.status, conversation_url: tavusResponse.conversation_url }); return { conversation_id: conversationId, conversation_name: conversation.conversation_name || '', status: tavusResponse.status, conversation_url: tavusResponse.conversation_url, daily_room_url: dailyRoom.url, room_config: config.room_config, created_at: conversation.created_at }; } catch (error) { // Update conversation status to failed await this.db.updateConversation(conversationId, { status: 'failed' // eslint-disable-next-line @typescript-eslint/no-empty-function }).catch(() => {}); // Ignore errors in error handling throw new Error(`Failed to create conversation: ${error.message}`); } } /** * Create Daily.js room with enhanced configuration */ private async createDailyRoom(roomName: string, config: Record): Promise { return await this.dailyClient.createRoom({ name: roomName, properties: { start_video_off: false, start_audio_off: false, enable_chat: config.enable_chat, enable_screenshare: config.enable_screenshare || false, max_participants: config.max_participants, participant_left_timeout: config.participant_left_timeout, enable_closed_captions: config.enable_closed_captions, room_privacy: config.room_privacy, // Auto-expire room after 2 hours exp: Math.floor(Date.now() / 1000) + (2 * 60 * 60) } }); } /** * Create real Tavus conversation with our callback URL */ private async createRealConversation(conversation: Conversation, config: UnifiedConversationConfig): Promise> { return await this.tavusClient.createConversation({ persona_id: config.persona_id, replica_id: config.replica_id, conversation_name: conversation.conversation_name, callback_url: `${process.env.BASE_URL}/api/webhooks/tavus/${conversation.id}`, properties: { participant_left_timeout: config.room_config?.participant_left_timeout || 60, enable_closed_captions: config.room_config?.enable_closed_captions ?? true } }); } /** * Create fake conversation that simulates real Tavus behavior */ private async createFakeConversation(conversation: Conversation): Promise> { // Simulate real Tavus conversation creation with consistent structure return { conversation_id: conversation.id, status: 'created', conversation_url: conversation.conversation_url, daily_room_url: conversation.daily_room_url, created_at: conversation.created_at }; } /** * Generate a unique room name for Daily.js */ private generateRoomName(customerId: string, personaId: string): string { const timestamp = Date.now(); const shortId = uuidv4().split('-')[0]; return `conv-${customerId.slice(0, 8)}-${personaId.slice(0, 8)}-${shortId}-${timestamp}`; } /** * Generate conversation URL for the conversation interface */ private generateConversationUrl(conversationId: string): string { const baseUrl = process.env.BASE_URL || 'http://localhost:3000'; return `${baseUrl}/conversations/${conversationId}`; } /** * Validate conversation configuration */ async validateConversationConfig(config: UnifiedConversationConfig): Promise<{ valid: boolean; message?: string; errors?: string[]; }> { const errors: string[] = []; // Required fields validation if (!config.persona_id) { errors.push('persona_id is required'); } if (!config.customer_id) { errors.push('customer_id is required'); } if (!config.environment) { errors.push('environment is required'); } // Validate room configuration if (config.room_config) { if (config.room_config.participant_left_timeout && (config.room_config.participant_left_timeout < 10 || config.room_config.participant_left_timeout > 300)) { errors.push('participant_left_timeout must be between 10 and 300 seconds'); } if (config.room_config.max_participants && (config.room_config.max_participants < 1 || config.room_config.max_participants > 10)) { errors.push('max_participants must be between 1 and 10'); } } // Validate customer exists (if database available) try { // This would need to be implemented based on your database structure // const customer = await this.db.getCustomerById(config.customer_id); // if (!customer) { // errors.push('Customer not found'); // } } catch (error) { // Log but don't fail validation for database connectivity issues console.warn('Could not validate customer:', error.message); } return { valid: errors.length === 0, message: errors.length > 0 ? errors.join(', ') : undefined, errors: errors.length > 0 ? errors : undefined }; } /** * Get conversation with analytics data */ async getConversationWithAnalytics(customerId: string, conversationId: string, verbose = false): Promise | null> { const conversation = await this.db.getConversationById(conversationId); if (!conversation || conversation.customer_id !== customerId) { return null; } const response = { conversation_id: conversation.id, conversation_name: conversation.conversation_name, status: conversation.status, persona_id: conversation.persona_id, replica_id: conversation.replica_id, created_at: conversation.created_at, started_at: conversation.started_at, ended_at: conversation.ended_at, duration_seconds: conversation.duration_seconds, conversation_url: conversation.conversation_url, daily_room_url: conversation.daily_room_url }; if (verbose) { // Include detailed analytics data (response as Record).shutdown_reason = conversation.shutdown_reason; (response as Record).transcript = conversation.transcript ? JSON.parse(conversation.transcript) : null; (response as Record).system = conversation.system_events ? JSON.parse(conversation.system_events) : null; (response as Record).application = { perception_analysis: conversation.perception_analysis ? JSON.parse(conversation.perception_analysis) : null }; // Include analytics if available // const analytics = await this.db.getConversationAnalytics(conversationId); // if (analytics.length > 0) { // (response as any).analytics = analytics; // } // Include webhook events // const webhookEvents = await this.db.getConversationWebhookEvents(conversationId); // if (webhookEvents.length > 0) { // (response as any).webhook_events = webhookEvents; // } } return response; } } export default UnifiedConversationService;