/** * Centralized Tavus Credit Configuration Module * * This module provides environment-aware settings, timeout defaults, and runtime * configuration for all Tavus API interactions. It serves as the single source of * truth for credit optimization settings across the application. * * @module tavus-credit-config */ /** * Timeout configuration for Tavus conversations * * These settings control when conversations automatically end to optimize credit usage: * - max_call_duration: Maximum duration for a conversation (0-3600 seconds) * - participant_left_timeout: Time to wait after participant leaves (0-300 seconds) * - participant_absent_timeout: Time to wait if no one joins (0-300 seconds) */ export interface TavusTimeoutConfig { /** Maximum call duration in seconds (0-3600). Default: 180 (3 minutes) */ max_call_duration: number; /** Timeout in seconds after participant leaves (0-300). Default: 10 */ participant_left_timeout: number; /** Timeout in seconds if participant is absent (0-300). Default: 30 */ participant_absent_timeout: number; } /** * Complete environment configuration for Tavus integration * * Provides all runtime settings needed for credit-optimized Tavus API usage, * including timeouts, proxy settings, rate limiting, and usage restrictions. */ export interface TavusEnvironmentConfig { /** Current environment (development, staging, or production) */ environment: 'development' | 'staging' | 'production'; /** Timeout configuration for conversation management */ timeouts: TavusTimeoutConfig; /** URL for the fake Tavus proxy server (for development/testing) */ proxyServerUrl: string; /** Enable strict validation and error checking */ enableStrictMode: boolean; /** Enable rate limiting for API calls */ enableRateLimiting: boolean; /** Delay in milliseconds between rate-limited API calls */ rateLimitDelay: number; /** Maximum number of API calls allowed per session (development/staging) */ usageLimit: number; } /** * Default timeout values for all environments * * These conservative defaults minimize credit consumption while maintaining * good user experience. Can be overridden via environment variables. * * @constant */ export const DEFAULT_TIMEOUTS: TavusTimeoutConfig = { max_call_duration: 180, // 3 minutes maximum conversation duration participant_left_timeout: 10, // 10 seconds after participant leaves participant_absent_timeout: 30 // 30 seconds if no one joins }; /** * Minimum and maximum allowed values for timeout configurations * * Used for validation to ensure timeout values are within Tavus API limits * * @constant */ export const TIMEOUT_LIMITS = { max_call_duration: { min: 0, max: 3600 }, participant_left_timeout: { min: 0, max: 300 }, participant_absent_timeout: { min: 0, max: 300 } } as const; /** * Detect the current runtime environment * * Uses multiple detection strategies in order of priority: * 1. Explicit TAVUS_ENVIRONMENT variable * 2. Standard NODE_ENV variable * 3. Hostname-based detection * 4. Default to 'development' * * @returns The detected environment * @private */ function detectEnvironment(): 'development' | 'staging' | 'production' { // Check explicit Tavus environment override const tavusEnv = process.env.TAVUS_ENVIRONMENT; if (tavusEnv === 'development' || tavusEnv === 'staging' || tavusEnv === 'production') { return tavusEnv; } // Check NODE_ENV const nodeEnv = process.env.NODE_ENV; if (nodeEnv === 'development' || nodeEnv === 'staging' || nodeEnv === 'production') { return nodeEnv; } // Try hostname-based detection (for browser environments) if (typeof window !== 'undefined' && window.location) { const hostname = window.location.hostname; if (hostname.includes('localhost') || hostname.includes('127.0.0.1')) { return 'development'; } if (hostname.includes('staging')) { return 'staging'; } if (hostname.includes('production') || hostname.includes('.com')) { return 'production'; } } // Default to development for safety return 'development'; } /** * Get the proxy server URL based on environment * * Returns the appropriate fake Tavus server URL for testing and development. * Can be overridden via TAVUS_PROXY_SERVER_URL environment variable. * * @param env - The current environment * @returns The proxy server URL * @private */ function getProxyUrl(env: 'development' | 'staging' | 'production'): string { // Check for explicit override if (process.env.TAVUS_PROXY_SERVER_URL) { return process.env.TAVUS_PROXY_SERVER_URL; } // Environment-specific defaults switch (env) { case 'development': return process.env.FAKE_SERVER_URL || 'http://localhost:3001'; case 'staging': return process.env.FAKE_SERVER_URL || 'https://fake-server.staging.buzztrail.ai'; case 'production': return process.env.FAKE_SERVER_URL || 'https://fake-server.production.buzztrail.ai'; default: return 'http://localhost:3001'; } } /** * Validate a timeout value against allowed limits * * Ensures timeout values are within API-specified ranges. Returns the * validated value or falls back to the default if invalid. * * @param value - The timeout value to validate * @param timeoutType - The type of timeout being validated * @returns The validated timeout value * @private */ function validateTimeout( value: number, timeoutType: keyof TavusTimeoutConfig ): number { const limits = TIMEOUT_LIMITS[timeoutType]; const defaultValue = DEFAULT_TIMEOUTS[timeoutType]; // Check if value is a valid number if (isNaN(value) || !isFinite(value)) { console.warn( `[Tavus Config] Invalid ${timeoutType}: ${value}. Using default: ${defaultValue}` ); return defaultValue; } // Clamp value within allowed range if (value < limits.min || value > limits.max) { console.warn( `[Tavus Config] ${timeoutType} out of range (${limits.min}-${limits.max}): ${value}. ` + `Using default: ${defaultValue}` ); return defaultValue; } return value; } /** * Parse an integer from environment variable with fallback * * Safely parses an integer from a string value, returning the fallback * value if parsing fails or the environment variable is not set. * * @param envValue - The environment variable value (may be undefined) * @param fallback - The fallback value to use if parsing fails * @returns The parsed integer or fallback value * @private */ function parseIntWithFallback(envValue: string | undefined, fallback: number): number { if (!envValue) { return fallback; } const parsed = parseInt(envValue, 10); return isNaN(parsed) ? fallback : parsed; } /** * Get default timeout configuration with environment variable overrides * * Returns timeout settings that can be customized via environment variables: * - TAVUS_MAX_CALL_DURATION: Override max_call_duration * - TAVUS_PARTICIPANT_LEFT_TIMEOUT: Override participant_left_timeout * - TAVUS_PARTICIPANT_ABSENT_TIMEOUT: Override participant_absent_timeout * * All values are validated against API limits and fall back to safe defaults * if invalid values are provided. * * @returns Timeout configuration with validated values * @example * ```typescript * const timeouts = getDefaultTimeouts(); * console.log(timeouts.max_call_duration); // 3600 or env override * ``` */ export function getDefaultTimeouts(): TavusTimeoutConfig { const maxCallDuration = parseIntWithFallback( process.env.TAVUS_MAX_CALL_DURATION, DEFAULT_TIMEOUTS.max_call_duration ); const participantLeftTimeout = parseIntWithFallback( process.env.TAVUS_PARTICIPANT_LEFT_TIMEOUT, DEFAULT_TIMEOUTS.participant_left_timeout ); const participantAbsentTimeout = parseIntWithFallback( process.env.TAVUS_PARTICIPANT_ABSENT_TIMEOUT, DEFAULT_TIMEOUTS.participant_absent_timeout ); return { max_call_duration: validateTimeout(maxCallDuration, 'max_call_duration'), participant_left_timeout: validateTimeout(participantLeftTimeout, 'participant_left_timeout'), participant_absent_timeout: validateTimeout(participantAbsentTimeout, 'participant_absent_timeout') }; } /** * Get runtime configuration based on current environment * * Returns complete environment-aware configuration for Tavus API integration. * Automatically detects the environment and applies appropriate settings. * * Supported environment variables: * - TAVUS_ENVIRONMENT / NODE_ENV: Set environment explicitly * - TAVUS_MAX_CALL_DURATION: Override max call duration (0-3600) * - TAVUS_PARTICIPANT_LEFT_TIMEOUT: Override left timeout (0-300) * - TAVUS_PARTICIPANT_ABSENT_TIMEOUT: Override absent timeout (0-300) * - TAVUS_PROXY_SERVER_URL: Override proxy server URL * - TAVUS_ENABLE_STRICT_MODE: Enable strict validation ('true'/'false') * - TAVUS_ENABLE_RATE_LIMITING: Enable rate limiting ('true'/'false') * - TAVUS_RATE_LIMIT_DELAY: Delay between rate-limited calls in ms * - TAVUS_USAGE_LIMIT: Maximum API calls per session in dev/staging * * @returns Complete environment configuration * @example * ```typescript * const config = getTavusConfig(); * console.log(`Environment: ${config.environment}`); * console.log(`Max duration: ${config.timeouts.max_call_duration}s`); * console.log(`Proxy: ${config.proxyServerUrl}`); * ``` */ export function getTavusConfig(): TavusEnvironmentConfig { const env = detectEnvironment(); const timeouts = getDefaultTimeouts(); const proxyServerUrl = getProxyUrl(env); // Parse rate limiting configuration const enableRateLimiting = process.env.TAVUS_ENABLE_RATE_LIMITING !== 'false'; const rateLimitDelay = parseIntWithFallback( process.env.TAVUS_RATE_LIMIT_DELAY, 1000 // Default 1 second between calls ); // Parse usage limit configuration const usageLimit = parseIntWithFallback( process.env.TAVUS_USAGE_LIMIT, 10 // Default 10 calls per session in dev ); // Parse strict mode configuration const enableStrictMode = process.env.TAVUS_ENABLE_STRICT_MODE === 'true'; return { environment: env, timeouts, proxyServerUrl, enableStrictMode, enableRateLimiting, rateLimitDelay, usageLimit }; } /** * Validate a complete timeout configuration * * Checks if all timeout values in a configuration object are valid. * Returns true if all values pass validation. * * @param config - The timeout configuration to validate * @returns True if configuration is valid * @example * ```typescript * const config = { max_call_duration: 3600, participant_left_timeout: 10, participant_absent_timeout: 60 }; * if (validateTimeoutConfig(config)) { * // Configuration is valid * } * ``` */ export function validateTimeoutConfig(config: TavusTimeoutConfig): boolean { const maxCallValid = config.max_call_duration >= TIMEOUT_LIMITS.max_call_duration.min && config.max_call_duration <= TIMEOUT_LIMITS.max_call_duration.max; const leftTimeoutValid = config.participant_left_timeout >= TIMEOUT_LIMITS.participant_left_timeout.min && config.participant_left_timeout <= TIMEOUT_LIMITS.participant_left_timeout.max; const absentTimeoutValid = config.participant_absent_timeout >= TIMEOUT_LIMITS.participant_absent_timeout.min && config.participant_absent_timeout <= TIMEOUT_LIMITS.participant_absent_timeout.max; return maxCallValid && leftTimeoutValid && absentTimeoutValid; } /** * Get environment-specific usage limits * * Returns appropriate API usage limits based on environment: * - Development: Limited calls for testing * - Staging: Moderate limits for integration testing * - Production: Unlimited (managed by customer quotas) * * @param env - The environment to get limits for (defaults to current) * @returns Maximum API calls allowed per session * @example * ```typescript * const limit = getUsageLimit('development'); * console.log(`Development limit: ${limit} calls`); * ``` */ export function getUsageLimit(env?: 'development' | 'staging' | 'production'): number { const environment = env || detectEnvironment(); // Check for explicit override if (process.env.TAVUS_USAGE_LIMIT) { return parseIntWithFallback(process.env.TAVUS_USAGE_LIMIT, 10); } // Environment-specific defaults switch (environment) { case 'development': return 10; // Very limited for local development case 'staging': return 50; // Moderate limit for integration testing case 'production': return Infinity; // No limit (managed by customer quotas) default: return 10; } }