All files / shared/services unified-conversation.service.ts

0% Statements 0/51
0% Branches 0/57
0% Functions 0/10
0% Lines 0/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
import { v4 as uuidv4 } from 'uuid';
import type {
  Conversation,
  ConversationSchema,
  Customer
} 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?: any;
  created_at: string;
}
 
export interface DailyRoom {
  name: string;
  url: string;
  created_at: string;
  config: any;
}
 
export interface TavusAPIClient {
  createConversation(config: any): Promise<any>;
}
 
export interface DailyAPIClient {
  createRoom(config: any): Promise<DailyRoom>;
}
 
export interface DatabaseManager {
  createConversation(conversation: Partial<Conversation>): Promise<Conversation>;
  updateConversation(id: string, updates: Partial<Conversation>): Promise<void>;
  getConversationById(id: string): Promise<Conversation | null>;
}
 
/**
 * 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<ConversationResponse> {
    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'
      }).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: any): Promise<DailyRoom> {
    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<any> {
    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<any> {
    // 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
    Iif (!config.persona_id) {
      errors.push('persona_id is required');
    }
 
    Iif (!config.customer_id) {
      errors.push('customer_id is required');
    }
 
    Iif (!config.environment) {
      errors.push('environment is required');
    }
 
    // Validate room configuration
    Iif (config.room_config) {
      Iif (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');
      }
 
      Iif (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: boolean = false): Promise<any> {
    const conversation = await this.db.getConversationById(conversationId);
 
    Iif (!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
    };
 
    Iif (verbose) {
      // Include detailed analytics data
      (response as any).shutdown_reason = conversation.shutdown_reason;
      (response as any).transcript = conversation.transcript ? JSON.parse(conversation.transcript) : null;
      (response as any).system = conversation.system_events ? JSON.parse(conversation.system_events) : null;
      (response as any).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;