/** * TavusClientProxy - Proxy routing layer for Tavus API calls * * This class wraps the TavusClient to ensure all Tavus API calls go through * the proxy server with credit control infrastructure. It maintains backward * compatibility with the existing TavusClient interface while adding: * - Automatic proxy routing based on environment * - Comprehensive logging of all API calls * - Support for both legacy (personaKey) and new (persona_id/replica_id) formats * - Optional strict mode for detecting direct TavusClient usage * * @module tavus-client-proxy */ import { getTavusConfig, type TavusEnvironmentConfig } from '@buzztrail/shared-config'; import { TavusClient, type TavusConfig, type ConversationRequest, type ConversationResponse, type TavusReplica, type ReplicaStatus, type TavusPipelineMode, type TavusResponse, type TavusError, } from './tavus-client'; /** * Proxy-specific configuration options */ export interface TavusProxyConfig extends TavusConfig { /** * Enable strict mode - warns if TavusClient is used directly * @default false */ strictMode?: boolean; /** * Custom proxy server URL (overrides environment-based detection) */ customProxyUrl?: string; /** * Enable detailed proxy routing logs * @default true */ enableProxyLogging?: boolean; /** * Skip proxy routing (for testing/development only) * @default false */ skipProxy?: boolean; } /** * TavusClientProxy - Routes all Tavus API calls through proxy server * * This is a drop-in replacement for TavusClient that ensures all API calls * go through the credit control infrastructure. Usage is identical to TavusClient: * * @example * ```typescript * // Before (direct API calls): * const client = new TavusClient({ apiKey: 'key', debug: true }); * * // After (proxied API calls): * const client = new TavusClientProxy({ apiKey: 'key', debug: true }); * * // API usage remains the same: * await client.initialize(); * const conversation = await client.createConversation({ * replicaId: 'replica-id', * personaId: 'persona-id' * }); * ``` */ export class TavusClientProxy { private client: TavusClient; private config: TavusProxyConfig; private envConfig: TavusEnvironmentConfig; private proxyUrl: string; private callCount = 0; /** * Create a new TavusClientProxy instance * * @param config - Configuration matching TavusClient interface */ constructor(config: TavusProxyConfig = {}) { this.config = { enableProxyLogging: true, skipProxy: false, strictMode: false, ...config, }; // Get environment configuration this.envConfig = getTavusConfig(); // Determine proxy URL this.proxyUrl = this.config.customProxyUrl || this.envConfig.proxyServerUrl; // Log proxy initialization if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Initializing with proxy routing'); console.log(`[TavusClientProxy] Environment: ${this.envConfig.environment}`); console.log(`[TavusClientProxy] Proxy URL: ${this.proxyUrl}`); console.log(`[TavusClientProxy] Timeouts:`, this.envConfig.timeouts); console.log(`[TavusClientProxy] Strict Mode: ${this.config.strictMode}`); } // Create underlying TavusClient with proxy URL const clientConfig: TavusConfig = { ...config, // Route through proxy server baseUrl: this.config.skipProxy ? config.baseUrl : this.proxyUrl, }; this.client = new TavusClient(clientConfig); // Warn if strict mode is enabled and direct TavusClient usage is detected if (this.config.strictMode && typeof window !== 'undefined') { this.setupStrictModeDetection(); } } /** * Initialize the Tavus client * * This must be called before making any API requests. */ initialize(): void { if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Initializing Tavus client'); } void this.client.initialize(); } /** * Create a conversation with stock avatar * * Routes the request through the proxy server with automatic timeout * enforcement and credit tracking. * * @param request - Conversation creation parameters * @returns Conversation details including room URL and access token */ async createConversation(request: ConversationRequest): Promise { this.callCount++; // Check usage limits in development/staging if (this.envConfig.environment !== 'production') { if (this.callCount > this.envConfig.usageLimit) { const error = new Error( `Usage limit exceeded: ${this.callCount}/${this.envConfig.usageLimit} calls made. ` + `Set TAVUS_USAGE_LIMIT environment variable to increase limit.` ); console.error('[TavusClientProxy] Usage limit exceeded', { callCount: this.callCount, limit: this.envConfig.usageLimit, environment: this.envConfig.environment, }); throw error; } } // Merge timeout configuration into request const proxyRequest: ConversationRequest = { ...request, properties: { ...request.properties, // Apply timeout defaults from configuration max_call_duration: request.properties?.max_call_duration ?? this.envConfig.timeouts.max_call_duration, participant_left_timeout: request.properties?.participant_left_timeout ?? this.envConfig.timeouts.participant_left_timeout, participant_absent_timeout: request.properties?.participant_absent_timeout ?? this.envConfig.timeouts.participant_absent_timeout, }, }; if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Creating conversation via proxy', { callNumber: this.callCount, replicaId: request.replicaId, personaId: request.personaId, proxyUrl: this.proxyUrl, timeouts: proxyRequest.properties, environment: this.envConfig.environment, }); } try { const response = await this.client.createConversation(proxyRequest); if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Conversation created successfully', { conversationId: response.conversationId, roomUrl: response.roomUrl, isActive: response.isActive, }); } return response; } catch (error) { if (this.config.enableProxyLogging) { console.error('[TavusClientProxy] Conversation creation failed', { error: error instanceof Error ? error.message : String(error), request: { replicaId: request.replicaId, personaId: request.personaId, }, }); } throw error; } } /** * End an active conversation * * Routes the request through the proxy server. * * @param conversationId - ID of the conversation to end */ async endConversation(conversationId: string): Promise { if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Ending conversation via proxy', { conversationId, proxyUrl: this.proxyUrl, }); } try { await this.client.endConversation(conversationId); if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Conversation ended successfully', { conversationId, }); } } catch (error) { if (this.config.enableProxyLogging) { console.error('[TavusClientProxy] Failed to end conversation', { conversationId, error: error instanceof Error ? error.message : String(error), }); } throw error; } } /** * Get all available replicas * * Routes the request through the proxy server. * * @returns List of available replicas */ async getReplicas(): Promise { if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Fetching replicas via proxy'); } try { const replicas = await this.client.getReplicas(); if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Replicas fetched successfully', { count: replicas.length, }); } return replicas; } catch (error) { if (this.config.enableProxyLogging) { console.error('[TavusClientProxy] Failed to fetch replicas', { error: error instanceof Error ? error.message : String(error), }); } throw error; } } /** * Get a specific replica by ID * * Routes the request through the proxy server. * * @param replicaId - ID of the replica to fetch * @returns Replica details */ async getReplica(replicaId: string): Promise { if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Fetching replica via proxy', { replicaId }); } try { const replicas = await this.client.getReplicas(); const replica = replicas.find(r => r.replicaId === replicaId); if (!replica) { throw new Error(`Replica with ID ${replicaId} not found`); } if (this.config.enableProxyLogging) { console.log('[TavusClientProxy] Replica fetched successfully', { replicaId: replica.replicaId, status: replica.status, }); } return replica; } catch (error) { if (this.config.enableProxyLogging) { console.error('[TavusClientProxy] Failed to fetch replica', { replicaId, error: error instanceof Error ? error.message : String(error), }); } throw error; } } /** * Get current call count (for usage tracking) * * @returns Number of API calls made by this instance */ getCallCount(): number { return this.callCount; } /** * Get current environment configuration * * @returns Environment configuration being used */ getEnvironmentConfig(): TavusEnvironmentConfig { return this.envConfig; } /** * Get proxy URL being used * * @returns Proxy server URL */ getProxyUrl(): string { return this.proxyUrl; } /** * Reset call counter (useful for testing) */ resetCallCount(): void { this.callCount = 0; } /** * Check if the client is initialized * * @returns True if the underlying TavusClient is initialized */ get initialized(): boolean { return this.client.initialized; } /** * Set up strict mode detection for direct TavusClient usage * This is helpful during migration to identify code that bypasses the proxy * * @private */ private setupStrictModeDetection(): void { // This would need to be implemented with a global flag or similar mechanism // to detect if TavusClient is being instantiated directly elsewhere console.warn( '[TavusClientProxy] Strict mode enabled - direct TavusClient usage will be logged' ); // Store a flag in window to indicate proxy is in use if (typeof window !== 'undefined') { (window as { __TAVUS_PROXY_ACTIVE__?: boolean }).__TAVUS_PROXY_ACTIVE__ = true; } } /** * Access the underlying TavusClient (for advanced use cases only) * * WARNING: Using the underlying client directly will bypass proxy routing * and credit control. Only use this if you know what you're doing. * * @returns The underlying TavusClient instance */ getUnderlyingClient(): TavusClient { if (this.config.strictMode) { console.warn( '[TavusClientProxy] Accessing underlying client in strict mode - ' + 'this bypasses proxy routing!' ); } return this.client; } } /** * Type export for backward compatibility */ export type { TavusConfig, ConversationRequest, ConversationResponse, TavusReplica, ReplicaStatus, TavusPipelineMode, TavusResponse, TavusError };