/** * Tavus.io API Client for video avatar generation and streaming * * This client handles authentication, video avatar generation, and streaming * capabilities using the Tavus.io API. It supports multiple pipeline modes * and integrates with Raven-0 for page awareness and perception analysis. * * For prototype/local development, API keys are stored insecurely. * In production, this should be changed to use secure key management. */ // Test API key for development - DO NOT USE IN PRODUCTION import { getTavusApiKey } from '@buzztrail/tavus-client'; const TEST_TAVUS_API_KEY = getTavusApiKey(); import type { UserPreferences } from '@buzztrail/shared-types'; import type { TavusConversationObject } from '@buzztrail/tavus-types'; import { getTavusLogger } from './tavus-logger-browser'; import { logger as appLogger } from '../logger'; // Cost tracking for development let costTrackingEnabled = false; let costTrackingCallback: ((callType: string) => boolean) | null = null; /** * Enable cost tracking for development */ export function enableCostTracking(callback: (callType: string) => boolean): void { costTrackingEnabled = true; costTrackingCallback = callback; } /** * Disable cost tracking */ export function disableCostTracking(): void { costTrackingEnabled = false; costTrackingCallback = null; } // WebRTC video streaming implementation /** * Pipeline modes supported by Tavus.io API */ export type TavusPipelineMode = 'basic' | 'enhanced' | 'premium' | 'enterprise'; /** * Replica status from Tavus API */ export type ReplicaStatus = 'training' | 'completed' | 'failed' | 'pending'; /** * Configuration for TavusClient initialization */ export interface TavusConfig { /** API key for Tavus.io authentication (optional - will use test key if not provided) */ apiKey?: string; /** Base URL for Tavus API (defaults to v2) */ baseUrl?: string; /** Default pipeline mode */ defaultPipelineMode?: TavusPipelineMode; /** User preferences for video settings */ userPreferences?: UserPreferences; /** Whether to enable debug logging */ debug?: boolean; } /** * Replica information from Tavus API */ export interface TavusReplica { /** Unique identifier for the replica */ replicaId: string; /** Human-readable name for the replica */ replicaName: string; /** Type of replica (e.g., 'user', 'system') */ replicaType: string; /** Current status of the replica */ status: ReplicaStatus; /** Training progress (e.g., "100/100") */ trainingProgress?: string; /** URL to thumbnail video */ thumbnailVideoUrl?: string; /** Timestamp when replica was created */ createdAt: string; /** Timestamp when replica was last updated */ updatedAt: string; /** Error message if status is 'failed' */ errorMessage?: string; } /** * Page analysis result from Raven-0 integration */ export interface PageAnalysis { /** Extracted page title */ title: string; /** Page description or summary */ description: string; /** List of interactive elements found */ interactiveElements: InteractiveElement[]; /** Navigation opportunities within the site */ navigationOptions: NavigationOption[]; /** Content summary for AI context */ contentSummary: string; /** User intent analysis */ userIntent: string; /** Page type classification */ pageType: 'e-commerce' | 'help-desk' | 'blog' | 'saas' | 'other'; } /** * Interactive element found on the page */ export interface InteractiveElement { /** Element type (button, form, link, etc.) */ type: string; /** Element text or label */ text: string; /** Element's href or action */ action?: string; /** Element's position on page */ position: { x: number; y: number; }; /** Whether element is currently visible */ visible: boolean; } /** * Navigation option within the same site */ export interface NavigationOption { /** URL to navigate to */ url: string; /** Link text or description */ text: string; /** Whether this is a primary navigation option */ primary: boolean; } /** * Perception analysis result from Raven-0 */ export interface PerceptionAnalysis { /** Overall page sentiment */ sentiment: 'positive' | 'negative' | 'neutral'; /** User engagement level */ engagementLevel: 'low' | 'medium' | 'high'; /** Recommended AI behavior */ recommendedBehavior: string; /** Contextual insights */ insights: string[]; /** Confidence score (0-1) */ confidence: number; } /** * Message context for sending to Tavus API */ export interface MessageContext { /** Current page URL */ pageUrl: string; /** Page title */ pageTitle: string; /** Page analysis results */ pageAnalysis?: PageAnalysis; /** User's current persona */ persona?: string; /** Pipeline mode to use */ pipelineMode?: TavusPipelineMode; } /** * Response from Tavus API */ export interface TavusResponse { /** Success status */ success: boolean; /** Response data */ data?: Record; /** Error message if failed */ error?: string; /** HTTP status code */ statusCode?: number; } /** * Error types for TavusClient */ export type TavusErrorType = | 'authentication' | 'network' | 'rate_limit' | 'validation' | 'server' | 'timeout' | 'unknown'; /** * Enhanced error information */ export interface TavusError { /** Error type for categorization */ type: TavusErrorType; /** Human-readable error message */ message: string; /** Original error object */ originalError?: Error; /** HTTP status code if applicable */ statusCode?: number; /** Retry information */ retryable: boolean; /** Suggested retry delay in milliseconds */ retryDelay?: number; /** Context information */ context?: Record; } /** * Retry configuration for API calls */ export interface RetryConfig { /** Maximum number of retry attempts */ maxRetries: number; /** Base delay between retries in milliseconds */ baseDelay: number; /** Maximum delay between retries in milliseconds */ maxDelay: number; /** Whether to use exponential backoff */ exponentialBackoff: boolean; /** HTTP status codes that should trigger retries */ retryStatusCodes: number[]; } /** * Video visibility state */ export interface VideoVisibilityState { /** Whether user video is currently visible */ isVisible: boolean; /** Last time visibility was changed */ lastChanged: Date; /** User who changed the visibility */ changedBy?: string; /** Reason for the change */ reason?: string; } /** * Tavus session for video avatar generation */ export interface TavusSession { /** Unique session identifier */ sessionId: string; /** Replica ID to use for this session */ replicaId: string; /** Persona ID for behavior configuration */ personaId: string; /** WebRTC room URL for real-time streaming */ webRtcRoomUrl: string; /** Current session status */ status: 'pending' | 'active' | 'ended' | 'error'; /** URL to session transcript */ transcriptUrl?: string; /** URL to session recording */ recordingUrl?: string; /** Session start timestamp */ startedAt: string; /** Session end timestamp */ endedAt?: string; /** Error message if status is 'error' */ error?: string; } /** * Configuration for Replica models */ export interface ReplicaConfig { /** Unique replica identifier */ replicaId: string; /** Human-readable display name */ displayName: string; /** URL to avatar preview image */ avatarUrl: string; /** Model type (Replica or Phoenix) */ modelType: 'Replica' | 'Phoenix'; /** Creation timestamp */ createdAt: string; /** Last update timestamp */ updatedAt?: string; /** Training progress (0-100) */ trainingProgress?: number; /** Whether replica is ready for use */ isReady: boolean; } /** * Configuration for Persona settings */ export interface PersonaConfig { /** Unique persona identifier */ personaId: string; /** Human-readable name */ name: string; /** Description of persona behavior */ description: string; /** Prompt template for persona */ promptTemplate: string; /** Language code (ISO 639-1) */ language: string; /** Voice engine to use */ voiceEngine: string; /** Pipeline mode for this persona */ pipelineMode: TavusPipelineMode; } /** * Video streaming session information */ export interface VideoStreamSession { /** Session ID */ sessionId: string; /** WebRTC room URL */ roomUrl: string; /** Room access token */ accessToken: string; /** Whether session is active */ isActive: boolean; /** Session start time */ startTime: string; /** Current video quality */ videoQuality: 'low' | 'medium' | 'high' | 'ultra'; /** Current audio quality */ audioQuality: 'low' | 'medium' | 'high'; /** Pipeline mode being used */ pipelineMode: TavusPipelineMode; } import { mergeRecordingConfig } from './tavus-recording-config'; /** * Conversation creation request */ export interface ConversationRequest { /** Stock replica ID to use */ replicaId: string; /** Stock persona ID for behavior */ personaId: string; /** Optional conversation name */ conversationName?: string; /** Optional webhook callback URL */ callbackUrl?: string; /** Optional conversational context to seed the session */ conversationalContext?: string; /** Conversation properties */ properties?: { /** Maximum call duration in minutes */ max_call_duration?: number; /** Timeout when participant leaves (0 = no timeout) */ participant_left_timeout?: number; /** Language for the conversation */ language?: string; /** Whether to enable video */ enableVideo?: boolean; /** Whether to enable audio */ enableAudio?: boolean; /** Recording configuration */ enable_recording?: boolean; aws_assume_role_arn?: string; recording_s3_bucket_region?: string; recording_s3_bucket_name?: string; /** Custom conversation settings */ customSettings?: Record; }; } /** * Conversation response */ export interface ConversationResponse { /** Conversation ID */ conversationId: string; /** WebRTC room URL for real-time streaming */ roomUrl: string; /** Room access token */ accessToken: string; /** Whether conversation is active */ isActive: boolean; /** Conversation start time */ startTime: string; /** Replica ID being used */ replicaId: string; /** Persona ID being used */ personaId: string; /** Error message if conversation failed */ error?: string; } /** * Tavus.io API Client * * Handles authentication, video avatar generation, and streaming * with support for multiple pipeline modes and Raven-0 integration. */ export class TavusClient { private apiKey: string; private baseUrl: string; private defaultPipelineMode: TavusPipelineMode; private userPreferences?: UserPreferences; private debug: boolean; private isInitialized = false; // Error handling and retry configuration private retryConfig: RetryConfig = { maxRetries: 3, baseDelay: 1000, maxDelay: 10000, exponentialBackoff: true, retryStatusCodes: [429, 500, 502, 503, 504], }; // Video visibility state private videoVisibilityState: VideoVisibilityState = { isVisible: true, lastChanged: new Date(), changedBy: 'system', reason: 'initialization', }; // Error tracking private errorCount = new Map(); private lastError?: TavusError; // Automatic conversation ending private conversationTimers: Map = new Map(); private activeConversations: Map = new Map(); constructor(config: TavusConfig) { // Use provided API key or fall back to test key for development this.apiKey = config.apiKey ?? TEST_TAVUS_API_KEY; this.baseUrl = config.baseUrl ?? 'https://tavusapi.com/v2'; this.defaultPipelineMode = config.defaultPipelineMode ?? 'basic'; this.userPreferences = config.userPreferences; this.debug = config.debug ?? false; } /** * Patch a persona using JSON Patch (RFC 6902). See Tavus API docs. */ async patchPersona( personaId: string, operations: Record[] ): Promise<{ success: boolean }> { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before patching personas'); } const endpoint = `/personas/${personaId}`; const response = await this.makeRequest(endpoint, { method: 'PATCH', body: operations as unknown as Record, }); if (!response.success) { throw new Error(response.error || 'Failed to patch persona'); } if (this.debug) { appLogger.info('Patched persona successfully', { personaId, operations }); } return { success: true }; } /** * Ensure the persona has a navigation tool defined for demo purposes. * Uses replace op first; on failure callers can retry with add. */ async setPersonaNavigationTool(personaId: string): Promise { const toolsDefinition = [ { type: 'function', function: { name: 'navigate_to_accu', description: 'Navigate the user to specific Accu product pages when they ask. Use target values: "rivets" or "locking_washers".', parameters: { type: 'object', properties: { target: { type: 'string', enum: ['rivets', 'locking_washers'], description: 'Where to navigate the browser within accu.co.uk', }, }, required: ['target'], }, }, }, ]; // Try replace first try { await this.patchPersona(personaId, [ { op: 'replace', path: '/layers/llm/tools', value: toolsDefinition, }, ]); return; } catch (e) { if (this.debug) { console.warn('Replace tools failed, attempting add:', e); } // Fallback to add await this.patchPersona(personaId, [ { op: 'add', path: '/layers/llm/tools', value: toolsDefinition, }, ]); } } /** * Append or replace persona context with navigation instructions. */ async upsertPersonaContext(personaId: string, context: string): Promise { try { await this.patchPersona(personaId, [ { op: 'replace', path: '/context', value: context }, ]); } catch (e) { if (this.debug) { console.warn('Replace context failed, attempting add:', e); } await this.patchPersona(personaId, [ { op: 'add', path: '/context', value: context }, ]); } } /** * Initialize the Tavus client * Validates API key and sets up connection */ async initialize(config?: Partial): Promise { try { // Update config if provided if (config) { if (config.apiKey) this.apiKey = config.apiKey; if (config.baseUrl) this.baseUrl = config.baseUrl; if (config.defaultPipelineMode) this.defaultPipelineMode = config.defaultPipelineMode; if (config.userPreferences) this.userPreferences = config.userPreferences; if (config.debug !== undefined) this.debug = config.debug; } // Validate API key (should always have one due to fallback) if (!this.apiKey || this.apiKey.trim() === '') { throw new Error('Tavus API key is required'); } // Test API connection by fetching replicas await this.testConnection(); this.isInitialized = true; if (this.debug) { appLogger.info('TavusClient initialized successfully'); } } catch (error) { this.isInitialized = false; throw new Error(`Failed to initialize TavusClient: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Send a message to the Tavus API with page context */ async sendMessage(message: string, pageContext: MessageContext): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before sending messages'); } try { const response = await this.makeRequest('/conversations/message', { method: 'POST', body: { message, page_context: pageContext, pipeline_mode: pageContext.pipelineMode || this.defaultPipelineMode, persona: pageContext.persona, }, }); if (!response.success) { throw new Error(response.error || 'Failed to send message'); } return (response.data?.response as string) || 'No response received'; } catch (error) { if (this.debug) { console.error('Error sending message to Tavus:', error); } throw error; } } /** * Analyze the current page using Raven-0 integration */ analyzePage(): PageAnalysis { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before analyzing pages'); } try { // Check if we're in a browser environment if (typeof document === 'undefined') { return { title: 'Unknown Page', description: 'Page analysis not available in non-browser environment', interactiveElements: [], navigationOptions: [], contentSummary: 'No content available', userIntent: 'unknown', pageType: 'other', }; } // Extract page information const pageTitle = document.title || 'Untitled Page'; const pageDescription = this.extractPageDescription(); const pageType = this.classifyPageType(); const userIntent = this.analyzeUserIntent(); // Extract interactive elements const interactiveElements = this.extractInteractiveElements(); // Extract navigation options const navigationOptions = this.extractNavigationOptions(); // Generate content summary const contentSummary = this.generateContentSummary(); if (this.debug) { console.log('Page analysis completed:', { title: pageTitle, type: pageType, intent: userIntent, elements: interactiveElements.length, navigation: navigationOptions.length, }); } return { title: pageTitle, description: pageDescription, interactiveElements, navigationOptions, contentSummary, userIntent, pageType, }; } catch (error) { if (this.debug) { console.error('Error analyzing page:', error); } throw error; } } /** * Extract page description from meta tags or content */ private extractPageDescription(): string { try { // Try to get description from meta tag const metaDescription = document.querySelector('meta[name="description"]'); if (metaDescription) { return metaDescription.getAttribute('content') || ''; } // Try to get description from Open Graph const ogDescription = document.querySelector('meta[property="og:description"]'); if (ogDescription) { return ogDescription.getAttribute('content') || ''; } // Fallback: extract from first paragraph const firstParagraph = document.querySelector('p'); if (firstParagraph) { return firstParagraph.textContent?.trim().substring(0, 200) || ''; } return 'No description available'; } catch { return 'Error extracting description'; } } /** * Check if page has e-commerce indicators */ private isEcommercePage(url: string, title: string, bodyText: string): boolean { const ecommerceIndicators = [ '/product', '/shop', '/store', '/cart', '/checkout', 'buy', 'shop', 'store', 'add to cart', 'buy now', '$', 'price' ]; return ecommerceIndicators.some(indicator => url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator) ); } /** * Check if page has help desk indicators */ private isHelpDeskPage(url: string, title: string, bodyText: string): boolean { const helpDeskIndicators = [ '/help', '/support', '/faq', '/contact', 'help', 'support', 'faq', 'contact us' ]; return helpDeskIndicators.some(indicator => url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator) ); } /** * Check if page has blog indicators */ private isBlogPage(url: string, title: string): boolean { const blogIndicators = ['/blog', '/article', '/post', 'blog', 'article']; return blogIndicators.some(indicator => url.includes(indicator) || title.includes(indicator) ) || !!document.querySelector('article') || !!document.querySelector('.blog') || !!document.querySelector('.post'); } /** * Check if page has SaaS indicators */ private isSaaSPage(url: string, title: string, bodyText: string): boolean { const saasIndicators = [ '/dashboard', '/app', '/login', '/signup', 'dashboard', 'app', 'platform', 'login', 'sign up' ]; return saasIndicators.some(indicator => url.includes(indicator) || title.includes(indicator) || bodyText.includes(indicator) ); } /** * Classify the page type based on content and structure */ private classifyPageType(): PageAnalysis['pageType'] { try { const url = window.location.href.toLowerCase(); const title = document.title.toLowerCase(); const bodyText = document.body.textContent?.toLowerCase() || ''; if (this.isEcommercePage(url, title, bodyText)) { return 'e-commerce'; } if (this.isHelpDeskPage(url, title, bodyText)) { return 'help-desk'; } if (this.isBlogPage(url, title)) { return 'blog'; } if (this.isSaaSPage(url, title, bodyText)) { return 'saas'; } return 'other'; } catch { return 'other'; } } /** * Analyze user intent based on page content and context */ private analyzeUserIntent(): string { try { const url = window.location.href.toLowerCase(); const title = document.title.toLowerCase(); const bodyText = document.body.textContent?.toLowerCase() || ''; // Check for search intent if ( url.includes('search') || url.includes('q=') || title.includes('search') || bodyText.includes('search') ) { return 'searching'; } // Check for learning intent if ( url.includes('/learn') || url.includes('/tutorial') || url.includes('/guide') || title.includes('learn') || title.includes('tutorial') || title.includes('guide') || bodyText.includes('learn') || bodyText.includes('tutorial') ) { return 'learning'; } // Check for purchasing intent if ( url.includes('/product') || url.includes('/buy') || title.includes('buy') || bodyText.includes('buy now') || bodyText.includes('add to cart') ) { return 'purchasing'; } // Check for support intent if ( url.includes('/help') || url.includes('/support') || title.includes('help') || bodyText.includes('help') || bodyText.includes('support') ) { return 'seeking_support'; } return 'browsing'; } catch { return 'unknown'; } } /** * Extract interactive elements from the page */ private extractInteractiveElements(): InteractiveElement[] { try { const elements: InteractiveElement[] = []; const selectors = [ 'button', 'a[href]', 'input[type="submit"]', 'input[type="button"]', 'select', 'textarea', 'form', '[role="button"]', '[role="link"]', '[onclick]', ]; selectors.forEach(selector => { const foundElements = document.querySelectorAll(selector); foundElements.forEach((element, index) => { if (index < 20) { // Limit to first 20 elements per type const rect = element.getBoundingClientRect(); const isVisible = rect.width > 0 && rect.height > 0; if (isVisible) { let text = ''; let action = ''; // Check element type based on tagName and properties if (element.tagName?.toLowerCase() === 'a' || 'href' in element) { text = element.textContent?.trim() || (element as HTMLAnchorElement).title || ''; action = (element as HTMLAnchorElement).href || ''; } else if (element.tagName?.toLowerCase() === 'button' || 'onclick' in element) { text = element.textContent?.trim() || (element as HTMLButtonElement).title || ''; action = (element as HTMLButtonElement).onclick?.toString() || ''; } else if (element.tagName?.toLowerCase() === 'input' || 'value' in element) { const inputElement = element as HTMLInputElement; text = inputElement.value || inputElement.placeholder || inputElement.title || ''; action = inputElement.type || ''; } else { text = element.textContent?.trim() || element.getAttribute?.('title') || ''; action = element.getAttribute?.('onclick') || ''; } if (text) { elements.push({ type: element.tagName.toLowerCase(), text: text.substring(0, 100), // Limit text length action, position: { x: Math.round(rect.left + rect.width / 2), y: Math.round(rect.top + rect.height / 2), }, visible: isVisible, }); } } } }); }); return elements.slice(0, 50); // Limit total elements } catch { return []; } } /** * Extract navigation options from the page */ private extractNavigationOptions(): NavigationOption[] { try { const navigation: NavigationOption[] = []; const currentUrl = window.location.href; // Extract links from navigation elements const navSelectors = [ 'nav a', 'header a', '.navigation a', '.nav a', '.menu a', '.breadcrumb a', ]; navSelectors.forEach(selector => { const links = document.querySelectorAll(selector); links.forEach(link => { // Check if it's an anchor element or has href property if (link.tagName?.toLowerCase() === 'a' || 'href' in link) { const href = (link as HTMLAnchorElement).href || ''; const text = link.textContent?.trim() || ''; if (href && text && href !== currentUrl) { navigation.push({ url: href, text: text.substring(0, 50), primary: link.closest?.('nav') !== null || link.closest?.('header') !== null, }); } } }); }); // Remove duplicates based on URL const uniqueNavigation = navigation.filter((item, index, self) => index === self.findIndex(t => t.url === item.url) ); return uniqueNavigation.slice(0, 20); // Limit to 20 navigation options } catch { return []; } } /** * Generate a content summary for AI context */ private generateContentSummary(): string { try { // Extract main content const mainContent = document.querySelector('main') || document.querySelector('article') || document.querySelector('.content') || document.querySelector('.main') || document.body; if (!mainContent) { return 'No content available'; } // Get text content let text = mainContent.textContent || ''; // Clean up the text text = text .replace(/\s+/g, ' ') .replace(/\n+/g, ' ') .trim(); // Limit to reasonable length if (text.length > 500) { text = text.substring(0, 500) + '...'; } return text || 'No content available'; } catch { return 'Error extracting content'; } } /** * Get perception analysis from Raven-0 */ async getPerceptionAnalysis(): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting perception analysis'); } try { // Get page analysis first const pageAnalysis = this.analyzePage(); // Analyze sentiment based on page content and type const sentiment = this.analyzeSentiment(pageAnalysis); // Determine engagement level const engagementLevel = this.analyzeEngagementLevel(pageAnalysis); // Generate recommended behavior const recommendedBehavior = this.generateRecommendedBehavior(pageAnalysis); // Generate insights const insights = this.generateInsights(pageAnalysis); // Calculate confidence score const confidence = this.calculateConfidence(pageAnalysis); if (this.debug) { console.log('Perception analysis completed:', { sentiment, engagementLevel, confidence, insights: insights.length, }); } return { sentiment, engagementLevel, recommendedBehavior, insights, confidence, }; } catch (error) { if (this.debug) { console.error('Error getting perception analysis:', error); } throw error; } } /** * Analyze sentiment based on page content and context */ private analyzeSentiment(pageAnalysis: PageAnalysis): PerceptionAnalysis['sentiment'] { try { const content = (pageAnalysis.contentSummary + ' ' + pageAnalysis.description).toLowerCase(); const title = pageAnalysis.title.toLowerCase(); // Positive indicators const positiveWords = [ 'success', 'great', 'amazing', 'excellent', 'wonderful', 'fantastic', 'helpful', 'useful', 'beneficial', 'positive', 'good', 'best', 'sale', 'discount', 'offer', 'deal', 'save', 'win', 'free' ]; // Negative indicators const negativeWords = [ 'error', 'problem', 'issue', 'broken', 'failed', 'wrong', 'bad', 'terrible', 'awful', 'horrible', 'negative', 'difficult', 'complaint', 'refund', 'cancel', 'stop', 'block', 'denied' ]; let positiveCount = 0; let negativeCount = 0; positiveWords.forEach(word => { if (content.includes(word) || title.includes(word)) { positiveCount++; } }); negativeWords.forEach(word => { if (content.includes(word) || title.includes(word)) { negativeCount++; } }); if (positiveCount > negativeCount + 2) { return 'positive'; } else if (negativeCount > positiveCount + 2) { return 'negative'; } else { return 'neutral'; } } catch { return 'neutral'; } } /** * Analyze engagement level based on page characteristics */ private analyzeEngagementLevel(pageAnalysis: PageAnalysis): PerceptionAnalysis['engagementLevel'] { try { let score = 0; // Interactive elements increase engagement score += pageAnalysis.interactiveElements.length * 0.1; // Content length indicates engagement potential if (pageAnalysis.contentSummary.length > 200) { score += 0.3; } // Navigation options suggest active site score += pageAnalysis.navigationOptions.length * 0.05; // Page type affects engagement switch (pageAnalysis.pageType) { case 'e-commerce': score += 0.4; // High engagement potential break; case 'saas': score += 0.3; // Moderate engagement break; case 'blog': score += 0.2; // Content engagement break; case 'help-desk': score += 0.1; // Lower engagement break; default: score += 0.1; } // User intent affects engagement switch (pageAnalysis.userIntent) { case 'purchasing': score += 0.5; // High engagement break; case 'learning': score += 0.4; // High engagement break; case 'searching': score += 0.3; // Moderate engagement break; case 'seeking_support': score += 0.2; // Lower engagement break; case 'browsing': score += 0.1; // Low engagement break; default: score += 0.1; } if (score >= 0.8) { return 'high'; } else if (score >= 0.4) { return 'medium'; } else { return 'low'; } } catch { return 'medium'; } } /** * Generate recommended behavior based on page analysis */ private generateRecommendedBehavior(pageAnalysis: PageAnalysis): string { try { const behaviors: string[] = []; // Base behavior on page type switch (pageAnalysis.pageType) { case 'e-commerce': behaviors.push('Product-focused assistance'); behaviors.push('Pricing and feature comparison'); behaviors.push('Purchase guidance'); break; case 'saas': behaviors.push('Feature explanation'); behaviors.push('Onboarding assistance'); behaviors.push('Technical support'); break; case 'blog': behaviors.push('Content summarization'); behaviors.push('Related topic suggestions'); behaviors.push('Reading assistance'); break; case 'help-desk': behaviors.push('Problem-solving assistance'); behaviors.push('FAQ navigation'); behaviors.push('Support escalation'); break; default: behaviors.push('General assistance'); behaviors.push('Information gathering'); } // Adjust based on user intent switch (pageAnalysis.userIntent) { case 'purchasing': behaviors.push('Purchase decision support'); behaviors.push('Product comparison'); break; case 'learning': behaviors.push('Educational content delivery'); behaviors.push('Concept explanation'); break; case 'searching': behaviors.push('Search refinement'); behaviors.push('Result filtering'); break; case 'seeking_support': behaviors.push('Problem diagnosis'); behaviors.push('Solution guidance'); break; case 'browsing': behaviors.push('Content discovery'); behaviors.push('Navigation assistance'); break; } // Add engagement-based recommendations if (pageAnalysis.interactiveElements.length > 10) { behaviors.push('Interactive element guidance'); } if (pageAnalysis.navigationOptions.length > 5) { behaviors.push('Navigation optimization'); } return behaviors.join(', '); } catch { return 'Standard interaction mode'; } } /** * Generate insights based on page analysis */ private generateInsights(pageAnalysis: PageAnalysis): string[] { try { const insights: string[] = []; // Page type insights switch (pageAnalysis.pageType) { case 'e-commerce': insights.push('E-commerce page detected - focus on product assistance'); insights.push('Multiple interactive elements suggest high user engagement'); break; case 'saas': insights.push('SaaS application detected - provide feature guidance'); insights.push('Technical content suggests need for detailed explanations'); break; case 'blog': insights.push('Blog content detected - offer reading assistance'); insights.push('Content-heavy page requires summarization capabilities'); break; case 'help-desk': insights.push('Help desk page detected - prioritize problem-solving'); insights.push('Support-focused content suggests user needs assistance'); break; default: insights.push('General page type - adapt behavior to content'); } // User intent insights switch (pageAnalysis.userIntent) { case 'purchasing': insights.push('User shows purchase intent - provide buying guidance'); break; case 'learning': insights.push('User shows learning intent - offer educational support'); break; case 'searching': insights.push('User is searching - help refine search queries'); break; case 'seeking_support': insights.push('User needs support - provide problem-solving assistance'); break; case 'browsing': insights.push('User is browsing - offer content discovery help'); break; } // Content insights if (pageAnalysis.contentSummary.length > 300) { insights.push('Rich content available for detailed analysis'); } if (pageAnalysis.interactiveElements.length > 15) { insights.push('Highly interactive page - guide user interactions'); } if (pageAnalysis.navigationOptions.length > 10) { insights.push('Complex navigation structure - provide navigation assistance'); } // Engagement insights if (pageAnalysis.interactiveElements.length === 0) { insights.push('Static content page - focus on information delivery'); } return insights.slice(0, 5); // Limit to 5 insights } catch { return ['Page analysis completed successfully']; } } /** * Calculate confidence score for the analysis */ private calculateConfidence(pageAnalysis: PageAnalysis): number { try { let confidence = 0.5; // Base confidence // More content increases confidence if (pageAnalysis.contentSummary.length > 100) { confidence += 0.1; } if (pageAnalysis.contentSummary.length > 300) { confidence += 0.1; } // Clear page type increases confidence if (pageAnalysis.pageType !== 'other') { confidence += 0.2; } // Clear user intent increases confidence if (pageAnalysis.userIntent !== 'unknown' && pageAnalysis.userIntent !== 'browsing') { confidence += 0.15; } // Interactive elements provide more context if (pageAnalysis.interactiveElements.length > 5) { confidence += 0.1; } // Navigation options provide context if (pageAnalysis.navigationOptions.length > 3) { confidence += 0.05; } // Cap at 1.0 return Math.min(confidence, 1.0); } catch { return 0.5; } } /** * Set user video visibility with enhanced error handling */ setUserVideoVisibility(show: boolean, options?: { changedBy?: string; reason?: string; silent?: boolean; }): void { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before setting video visibility'); } // Validate input if (typeof show !== 'boolean') { throw new Error('Video visibility must be a boolean value'); } // Update video visibility state this.videoVisibilityState = { isVisible: show, lastChanged: new Date(), changedBy: options?.changedBy || 'user', reason: options?.reason || 'manual_change', }; // Update user preferences if available if (this.userPreferences) { this.userPreferences.privacy.showUserVideo = show; } // Log the change if (this.debug) { console.log(`User video visibility set to: ${show}`, { changedBy: this.videoVisibilityState.changedBy, reason: this.videoVisibilityState.reason, timestamp: this.videoVisibilityState.lastChanged.toISOString(), }); } // Emit event if not silent if (!options?.silent) { this.emitVideoVisibilityChange(show); } } catch (error) { const tavusError = this.createError(error, 'validation', { operation: 'setUserVideoVisibility', requestedVisibility: show, }); if (this.debug) { console.error('Error setting video visibility:', tavusError); } throw tavusError; } } /** * Get current video visibility state */ getVideoVisibilityState(): VideoVisibilityState { return { ...this.videoVisibilityState }; } /** * Toggle video visibility */ toggleVideoVisibility(options?: { changedBy?: string; reason?: string; }): void { const newVisibility = !this.videoVisibilityState.isVisible; this.setUserVideoVisibility(newVisibility, options); } /** * Emit video visibility change event */ private emitVideoVisibilityChange(isVisible: boolean): void { // This would integrate with the browser extension's event system if (typeof window !== 'undefined' && window.dispatchEvent) { const event = new CustomEvent('tavus-video-visibility-change', { detail: { isVisible, timestamp: new Date().toISOString(), source: 'TavusClient', }, }); window.dispatchEvent(event); } } /** * Create enhanced error object */ private createError( error: unknown, type: TavusErrorType, context?: Record ): TavusError { const message = error instanceof Error ? error.message : String(error); const originalError = error instanceof Error ? error : undefined; const tavusError: TavusError = { type, message, originalError, retryable: this.isRetryableError(type), context, }; // Track error count const currentCount = this.errorCount.get(type) || 0; this.errorCount.set(type, currentCount + 1); this.lastError = tavusError; return tavusError; } /** * Determine if an error is retryable */ private isRetryableError(type: TavusErrorType): boolean { switch (type) { case 'network': case 'timeout': case 'server': return true; case 'authentication': case 'validation': return false; case 'rate_limit': return true; // Rate limits can be retried after delay default: return false; } } /** * Calculate retry delay with exponential backoff */ private calculateRetryDelay(attempt: number): number { if (!this.retryConfig.exponentialBackoff) { return this.retryConfig.baseDelay; } const delay = this.retryConfig.baseDelay * Math.pow(2, attempt - 1); return Math.min(delay, this.retryConfig.maxDelay); } /** * Execute API call with retry logic */ private async executeWithRetry( operation: () => Promise, context?: Record ): Promise { let lastError: TavusError | undefined; for (let attempt = 1; attempt <= this.retryConfig.maxRetries; attempt++) { try { return await operation(); } catch (error) { const tavusError = this.createError(error, 'unknown', { ...context, attempt, maxRetries: this.retryConfig.maxRetries, }); lastError = tavusError; // Don't retry if error is not retryable or we've exhausted retries if (!tavusError.retryable || attempt === this.retryConfig.maxRetries) { throw tavusError; } // Calculate delay before retry const delay = this.calculateRetryDelay(attempt); tavusError.retryDelay = delay; if (this.debug) { console.warn(`Retry attempt ${attempt}/${this.retryConfig.maxRetries} after ${delay}ms:`, tavusError.message); } // Wait before retrying await new Promise(resolve => setTimeout(resolve, delay)); } } throw lastError || new Error('Unknown error occurred'); } /** * Get error statistics */ getErrorStats(): { totalErrors: number; errorCounts: Record; lastError?: TavusError; } { const totalErrors = Array.from(this.errorCount.values()).reduce((sum, count) => sum + count, 0); const errorCounts: Record = { authentication: this.errorCount.get('authentication') || 0, network: this.errorCount.get('network') || 0, rate_limit: this.errorCount.get('rate_limit') || 0, validation: this.errorCount.get('validation') || 0, server: this.errorCount.get('server') || 0, timeout: this.errorCount.get('timeout') || 0, unknown: this.errorCount.get('unknown') || 0, }; return { totalErrors, errorCounts, lastError: this.lastError, }; } /** * Clear error statistics */ clearErrorStats(): void { this.errorCount.clear(); this.lastError = undefined; } /** * Update retry configuration */ updateRetryConfig(config: Partial): void { this.retryConfig = { ...this.retryConfig, ...config }; if (this.debug) { console.log('Retry configuration updated:', this.retryConfig); } } /** * Get available replicas from Tavus API */ async getReplicas(): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before fetching replicas'); } try { const response = await this.makeRequest('/replicas', { method: 'GET', }); if (!response.success) { throw new Error(response.error || 'Failed to fetch replicas'); } return (response.data?.replicas as TavusReplica[]) || []; } catch (error) { if (this.debug) { console.error('Error fetching replicas:', error); } throw error; } } /** * Create a new replica */ async createReplica(name: string, type = 'user'): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before creating replicas'); } try { const response = await this.makeRequest('/replicas', { method: 'POST', body: { replica_name: name, replica_type: type, }, }); if (!response.success) { throw new Error(response.error || 'Failed to create replica'); } return response.data as unknown as TavusReplica; } catch (error) { if (this.debug) { console.error('Error creating replica:', error); } throw error; } } /** * Test API connection by making a simple request */ private async testConnection(): Promise { try { const response = await this.makeRequest('/replicas', { method: 'GET', }); if (!response.success) { throw new Error('API connection test failed'); } } catch (error) { throw new Error(`API connection test failed: ${error instanceof Error ? error.message : 'Unknown error'}`); } } /** * Make HTTP request to Tavus API with enhanced error handling and retry logic */ private async makeRequest( endpoint: string, options: { method: string; body?: Record; } ): Promise { // Track API call for cost control const callType = this.getCallTypeFromEndpoint(endpoint); if (costTrackingEnabled && costTrackingCallback) { if (!costTrackingCallback(callType)) { throw new Error(`Cost control limit reached for ${callType}`); } } return this.executeWithRetry(async () => { const url = `${this.baseUrl}${endpoint}`; const headers: Record = { 'Content-Type': 'application/json', 'x-api-key': this.apiKey, }; const requestOptions: RequestInit = { method: options.method, headers, }; if (options.body) { requestOptions.body = JSON.stringify(options.body); } // Log the request const logger = getTavusLogger(); const requestId = logger.logRequest(options.method, url, headers, options.body); try { const response = await fetch(url, requestOptions); // Handle empty responses (common for DELETE operations) let data: unknown = null; const contentType = response.headers.get('content-type'); const contentLength = response.headers.get('content-length'); // Only try to parse JSON if there's actually content if (contentLength && parseInt(contentLength) > 0) { data = await response.json(); } else if (contentType?.includes('application/json')) { // Try to parse JSON even if content-length is not set try { data = await response.json(); } catch { // If JSON parsing fails, treat as empty response data = null; } } // Log the response logger.logResponse(requestId, response.status, Object.fromEntries(response.headers.entries()), data); if (!response.ok) { // Log the full response for debugging console.error('Tavus API Error Response:', { status: response.status, statusText: response.statusText, data: data, dataType: typeof data, dataKeys: data && typeof data === 'object' ? Object.keys(data) : 'not an object', url: url, method: options.method, body: options.body }); // Determine error type based on status code let errorType: TavusErrorType = 'unknown'; if (response.status === 401 || response.status === 403) { errorType = 'authentication'; } else if (response.status === 429) { errorType = 'rate_limit'; } else if (response.status >= 400 && response.status < 500) { errorType = 'validation'; } else if (response.status >= 500) { errorType = 'server'; } // Try to extract error message from various possible formats let errorMessage = 'Unknown error'; appLogger.debug('Extracting error message from data', { data }); if (data && typeof data === 'object' && 'error' in data && typeof data.error === 'string') { errorMessage = data.error; appLogger.debug('Found error in data.error', { error: data.error }); } else if (data && typeof data === 'object' && 'message' in data && typeof data.message === 'string') { errorMessage = data.message; appLogger.debug('Found error in data.message', { message: data.message }); } else if (data && typeof data === 'object' && 'detail' in data && typeof data.detail === 'string') { errorMessage = data.detail; appLogger.debug('Found error in data.detail', { detail: data.detail }); } else if (data && typeof data === 'string') { errorMessage = data; appLogger.debug('Data is string', { data }); } else if (data && typeof data === 'object') { errorMessage = JSON.stringify(data); appLogger.debug('Data is object, stringified', { errorMessage }); } else { errorMessage = `HTTP ${response.status}: ${response.statusText}`; appLogger.debug('Using default error message', { errorMessage }); } const error = this.createError( new Error(errorMessage), errorType, { endpoint, method: options.method, statusCode: response.status, responseData: data, } ); // Add status code to error error.statusCode = response.status; throw error; } return { success: true, data: data as Record | undefined, statusCode: response.status, }; } catch (error) { // Log error response if we have a requestId if (requestId) { logger.logResponse(requestId, 0, {}, { error: error instanceof Error ? error.message : String(error) }); } // If it's already a TavusError, re-throw it if (error && typeof error === 'object' && 'type' in error) { throw error; } // Create network error const networkError = this.createError( error, 'network', { endpoint, method: options.method, url, } ); throw networkError; } }, { operation: 'makeRequest', endpoint, method: options.method, }); } /** * Check if client is initialized */ get initialized(): boolean { return this.isInitialized; } /** * Get current pipeline mode */ get pipelineMode(): TavusPipelineMode { return this.defaultPipelineMode; } /** * Set pipeline mode */ setPipelineMode(mode: TavusPipelineMode): void { this.defaultPipelineMode = mode; if (this.debug) { appLogger.info(`Pipeline mode set to: ${mode}`); } } /** * Create a new video avatar generation session */ async createVideoSession( replicaId: string, personaId: string, pipelineMode?: TavusPipelineMode ): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before creating video sessions'); } try { const response = await this.makeRequest('/sessions', { method: 'POST', body: { replica_id: replicaId, persona_id: personaId, pipeline_mode: pipelineMode || this.defaultPipelineMode, enable_streaming: true, }, }); if (!response.success) { throw new Error(response.error || 'Failed to create video session'); } return response.data as unknown as TavusSession; } catch (error) { if (this.debug) { console.error('Error creating video session:', error); } throw error; } } /** * Create a conversation with a stock avatar */ async createConversation(request: ConversationRequest): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before creating conversations'); } // Validate request parameters this.validateConversationRequest(request); if (this.debug) { console.log('Creating conversation with request:', { replicaId: request.replicaId, personaId: request.personaId, properties: request.properties, }); } // Prepare the request body according to Tavus API documentation const requestBody: Record = { replica_id: request.replicaId, persona_id: request.personaId, }; // Optional fields per Conversation Customizations if (request.conversationName) { requestBody.conversation_name = request.conversationName; } if (request.callbackUrl) { requestBody.callback_url = request.callbackUrl; } if (request.conversationalContext) { requestBody.conversational_context = request.conversationalContext; } // Always include properties with default recording configuration const properties = mergeRecordingConfig( request.properties || {}, request.personaId ); // Only include properties if there are any to include if (Object.keys(properties).length > 0) { requestBody.properties = properties; } const response = await this.makeRequest('/conversations', { method: 'POST', body: requestBody, }); if (!response.success) { const error = this.createError( new Error(response.error || 'Failed to create conversation'), 'server', { operation: 'createConversation', replicaId: request.replicaId, personaId: request.personaId, statusCode: response.statusCode, } ); throw error; } // Map the response to our interface const conversationResponse: ConversationResponse = { conversationId: (response.data?.conversation_id || response.data?.conversationId) as string, roomUrl: (response.data?.conversation_url || response.data?.roomUrl) as string, accessToken: (response.data?.access_token || response.data?.accessToken) as string, isActive: (response.data?.status === 'active' || response.data?.isActive) as boolean, startTime: (response.data?.created_at || response.data?.startTime) as string, replicaId: (response.data?.replica_id || response.data?.replicaId) as string, personaId: (response.data?.persona_id || response.data?.personaId) as string, error: response.data?.error as string | undefined, }; if (this.debug) { console.log('Conversation created successfully:', conversationResponse); } return conversationResponse; } catch (error) { // If it's already a TavusError, re-throw it if (error && typeof error === 'object' && 'type' in error) { throw error; } // Create validation error for invalid requests const tavusError = this.createError(error, 'validation', { operation: 'createConversation', request: { replicaId: request.replicaId, personaId: request.personaId, }, }); if (this.debug) { console.error('Error creating conversation:', tavusError); } throw tavusError; } } /** * Validate conversation creation request */ private validateConversationRequest(request: ConversationRequest): void { const errors: string[] = []; if (!request.replicaId || typeof request.replicaId !== 'string' || request.replicaId.trim() === '') { errors.push('replicaId is required and must be a non-empty string'); } if (!request.personaId || typeof request.personaId !== 'string' || request.personaId.trim() === '') { errors.push('personaId is required and must be a non-empty string'); } if (request.properties?.participant_left_timeout !== undefined && (typeof request.properties.participant_left_timeout !== 'number' || request.properties.participant_left_timeout < 0)) { errors.push('participant_left_timeout must be a non-negative number'); } if (request.properties?.language && typeof request.properties.language !== 'string') { errors.push('language must be a string'); } if (request.properties?.enableVideo !== undefined && typeof request.properties.enableVideo !== 'boolean') { errors.push('enableVideo must be a boolean'); } if (request.properties?.enableAudio !== undefined && typeof request.properties.enableAudio !== 'boolean') { errors.push('enableAudio must be a boolean'); } if (errors.length > 0) { const error = this.createError( new Error(`Conversation request validation failed: ${errors.join(', ')}`), 'validation', { operation: 'validateConversationRequest', errors, request: { replicaId: request.replicaId, personaId: request.personaId, }, } ); throw error; } } /** * Start real-time video streaming session with enhanced error handling */ async startVideoStream( sessionId: string, videoQuality: 'low' | 'medium' | 'high' | 'ultra' = 'medium' ): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before starting video streams'); } // Validate session ID if (!sessionId || typeof sessionId !== 'string') { const error = this.createError( new Error('Session ID is required and must be a string'), 'validation', { operation: 'startVideoStream', sessionId } ); throw error; } if (this.debug) { console.log('Starting video stream:', { sessionId, videoQuality }); } const response = await this.makeRequest(`/sessions/${sessionId}/stream`, { method: 'POST', body: { video_quality: videoQuality, enable_webrtc: true, }, }); if (!response.success) { const error = this.createError( new Error(response.error || 'Failed to start video stream'), 'server', { operation: 'startVideoStream', sessionId, videoQuality, statusCode: response.statusCode, } ); throw error; } if (this.debug) { console.log('Video stream started successfully:', { sessionId: response.data?.sessionId, roomUrl: response.data?.roomUrl, isActive: response.data?.isActive, }); } return response.data as unknown as VideoStreamSession; } catch (error) { // If it's already a TavusError, re-throw it if (error && typeof error === 'object' && 'type' in error) { throw error; } const tavusError = this.createError(error, 'network', { operation: 'startVideoStream', sessionId, videoQuality, }); if (this.debug) { console.error('Error starting video stream:', tavusError); } throw tavusError; } } /** * Get conversation status and details */ async getConversation(conversationId: string): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting conversation details'); } if (!conversationId || typeof conversationId !== 'string') { const error = this.createError( new Error('Conversation ID is required and must be a string'), 'validation', { operation: 'getConversation', conversationId } ); throw error; } if (this.debug) { console.log('Getting conversation details:', { conversationId }); } const response = await this.makeRequest(`/conversations/${conversationId}`, { method: 'GET', }); if (!response.success) { const error = this.createError( new Error(response.error || 'Failed to get conversation details'), 'server', { operation: 'getConversation', conversationId, statusCode: response.statusCode, } ); throw error; } // Map the response to our interface const conversationResponse: ConversationResponse = { conversationId: (response.data?.conversation_id || response.data?.conversationId) as string, roomUrl: (response.data?.conversation_url || response.data?.roomUrl) as string, accessToken: (response.data?.access_token || response.data?.accessToken) as string, isActive: (response.data?.status === 'active' || response.data?.isActive) as boolean, startTime: (response.data?.created_at || response.data?.startTime) as string, replicaId: (response.data?.replica_id || response.data?.replicaId) as string, personaId: (response.data?.persona_id || response.data?.personaId) as string, error: response.data?.error as string | undefined, }; return conversationResponse; } catch (error) { if (error && typeof error === 'object' && 'type' in error) { throw error; } const tavusError = this.createError(error, 'network', { operation: 'getConversation', conversationId, }); if (this.debug) { console.error('Error getting conversation:', tavusError); } throw tavusError; } } /** * End a conversation */ async endConversation(conversationId: string): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before ending conversations'); } if (!conversationId || typeof conversationId !== 'string') { const error = this.createError( new Error('Conversation ID is required and must be a string'), 'validation', { operation: 'endConversation', conversationId } ); throw error; } if (this.debug) { console.log('Ending conversation:', { conversationId }); } const response = await this.makeRequest(`/conversations/${conversationId}`, { method: 'DELETE', }); if (!response.success) { const error = this.createError( new Error(response.error || 'Failed to end conversation'), 'server', { operation: 'endConversation', conversationId, statusCode: response.statusCode, } ); throw error; } if (this.debug) { console.log('Conversation ended successfully:', { conversationId }); } } catch (error) { if (error && typeof error === 'object' && 'type' in error) { throw error; } const tavusError = this.createError(error, 'network', { operation: 'endConversation', conversationId, }); if (this.debug) { console.error('Error ending conversation:', tavusError); } throw tavusError; } } /** * Stop video streaming session */ async stopVideoStream(sessionId: string): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before stopping video streams'); } try { const response = await this.makeRequest(`/sessions/${sessionId}/stream`, { method: 'DELETE', }); if (!response.success) { throw new Error(response.error || 'Failed to stop video stream'); } } catch (error) { if (this.debug) { console.error('Error stopping video stream:', error); } throw error; } } /** * Get session status and details */ async getSession(sessionId: string): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting session details'); } try { const response = await this.makeRequest(`/sessions/${sessionId}`, { method: 'GET', }); if (!response.success) { throw new Error(response.error || 'Failed to get session details'); } return response.data as unknown as TavusSession; } catch (error) { if (this.debug) { console.error('Error getting session details:', error); } throw error; } } /** * End a video session */ async endSession(sessionId: string): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before ending sessions'); } try { const response = await this.makeRequest(`/sessions/${sessionId}`, { method: 'DELETE', }); if (!response.success) { throw new Error(response.error || 'Failed to end session'); } } catch (error) { if (this.debug) { console.error('Error ending session:', error); } throw error; } } /** * Get available personas */ async getPersonas(): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before fetching personas'); } try { const response = await this.makeRequest('/personas', { method: 'GET', }); if (!response.success) { throw new Error(response.error || 'Failed to fetch personas'); } return (response.data?.personas || []) as PersonaConfig[]; } catch (error) { if (this.debug) { console.error('Error fetching personas:', error); } throw error; } } /** * Create a new persona */ async createPersona(config: Omit): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before creating personas'); } try { const response = await this.makeRequest('/personas', { method: 'POST', body: { name: config.name, description: config.description, prompt_template: config.promptTemplate, language: config.language, voice_engine: config.voiceEngine, pipeline_mode: config.pipelineMode, }, }); if (!response.success) { throw new Error(response.error || 'Failed to create persona'); } return response.data as unknown as PersonaConfig; } catch (error) { if (this.debug) { console.error('Error creating persona:', error); } throw error; } } /** * Get session transcript */ async getSessionTranscript(sessionId: string): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting transcripts'); } try { const response = await this.makeRequest(`/sessions/${sessionId}/transcript`, { method: 'GET', }); if (!response.success) { throw new Error(response.error || 'Failed to get session transcript'); } return (response.data?.transcript || '') as string; } catch (error) { if (this.debug) { console.error('Error getting session transcript:', error); } throw error; } } /** * Get session recording URL */ async getSessionRecording(sessionId: string): Promise { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting recordings'); } try { const response = await this.makeRequest(`/sessions/${sessionId}/recording`, { method: 'GET', }); if (!response.success) { throw new Error(response.error || 'Failed to get session recording'); } return (response.data?.recording_url || '') as string; } catch (error) { if (this.debug) { console.error('Error getting session recording:', error); } throw error; } } /** * Get existing conversations for cleanup */ async getConversations(): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before getting conversations'); } if (this.debug) { console.log('Getting existing conversations...'); } const response = await this.makeRequest('/conversations', { method: 'GET', }); if (!response.success) { const error = this.createError( new Error(response.error || 'Failed to get conversations'), 'server', { operation: 'getConversations', statusCode: response.statusCode, } ); throw error; } if (this.debug) { console.log('Conversations retrieved successfully:', response.data); } // Map the response to our interface const conversations = (response.data?.conversations || []) as TavusConversationObject[]; return conversations.map((conv: TavusConversationObject) => ({ conversationId: (conv.conversation_id || conv.conversationId) ?? '', roomUrl: (conv.conversation_url || conv.roomUrl) ?? '', accessToken: (conv.access_token || conv.accessToken) ?? '', isActive: (conv.status === 'active' || conv.isActive) ?? false, startTime: (conv.created_at || conv.startTime) ?? '', replicaId: (conv.replica_id || conv.replicaId) ?? '', personaId: (conv.persona_id || conv.personaId) ?? '', error: conv.error, })); } catch (error) { // If it's already a TavusError, re-throw it if (error && typeof error === 'object' && 'type' in error) { throw error; } const tavusError = this.createError(error, 'network', { operation: 'getConversations', }); if (this.debug) { console.error('Error getting conversations:', tavusError); } throw tavusError; } } /** * Connect to WebRTC room and get video stream from Tavus conversation */ async connectToWebRTCRoom(roomUrl: string, accessToken?: string): Promise { try { if (!this.isInitialized) { throw new Error('TavusClient must be initialized before connecting to WebRTC room'); } if (!roomUrl || typeof roomUrl !== 'string') { throw new Error('Room URL is required for WebRTC connection'); } if (this.debug) { console.log('Connecting to Tavus room using Daily.js:', { roomUrl, hasAccessToken: !!accessToken }); } // Load Daily.js from CDN if not already loaded if (typeof window !== 'undefined' && !window.Daily) { const script = document.createElement('script'); script.src = 'https://unpkg.com/@daily-co/daily-js'; script.crossOrigin = 'anonymous'; document.head.appendChild(script); // Wait for Daily.js to load await new Promise((resolve, reject) => { script.onload = () => resolve(); script.onerror = () => reject(new Error('Failed to load Daily.js')); }); } // Create Daily call frame const callFrame = window.Daily.createFrame({ showLeaveButton: false, showFullscreenButton: false, showLocalVideo: false, showParticipantsBar: false, iframeStyle: { width: '100%', height: '100%', border: '0px', borderRadius: '8px', }, }); // Set up event handlers callFrame.on('joining-meeting', (): void => { if (this.debug) { console.log('Joining Tavus meeting...'); } }); callFrame.on('joined-meeting', (): void => { if (this.debug) { console.log('Successfully joined Tavus meeting'); } }); callFrame.on('participant-joined', (event): void => { if (this.debug) { console.log('Participant joined:', event.participant); } }); callFrame.on('participant-updated', (event): void => { if (this.debug) { console.log('Participant updated:', event.participant); } }); callFrame.on('error', (event) => { console.error('Daily call error:', event); throw new Error(`Daily call error: ${event.errorMsg || 'Unknown error'}`); }); // Join the room await callFrame.join({ url: roomUrl }); // Wait for the meeting to be fully joined await new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Timeout waiting for meeting to join')); }, 10000); callFrame.on('joined-meeting', () => { clearTimeout(timeout); resolve(); }); callFrame.on('error', (event) => { clearTimeout(timeout); reject(new Error(`Failed to join meeting: ${event.errorMsg}`)); }); }); // Get the video stream from the Daily call const participants = callFrame.participants(); const remoteParticipants = Object.values(participants).filter( (participant) => participant.owner && participant.video ); if (remoteParticipants.length === 0) { throw new Error('No remote video participants found in Tavus room'); } // Get the first remote participant's video stream const remoteParticipant = remoteParticipants[0]; if (!remoteParticipant) { throw new Error('No remote participants found in Tavus room'); } const videoTrack = remoteParticipant.videoTrack; if (!videoTrack) { throw new Error('No video track available from remote participant'); } // Create a MediaStream from the video track const stream = new MediaStream([videoTrack]); if (this.debug) { console.log('Successfully connected to Tavus video stream via Daily.js'); } return stream; } catch (error) { if (this.debug) { console.error('Error connecting to WebRTC room:', error); } // No fallbacks - just throw the error throw error; } } /** * Determine call type from API endpoint */ private getCallTypeFromEndpoint(endpoint: string): string { if (endpoint.includes('/conversations') && endpoint.includes('POST')) { return 'create_conversation'; } else if (endpoint.includes('/conversations') && endpoint.includes('GET')) { return 'get_conversation'; } else if (endpoint.includes('/conversations') && endpoint.includes('DELETE')) { return 'end_conversation'; } else if (endpoint.includes('/replicas')) { return 'get_replicas'; } else if (endpoint.includes('/personas')) { return 'get_personas'; } else if (endpoint.includes('/sessions')) { return 'video_stream'; } else { return 'default'; } } }