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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 | /**
* 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;
Iif (tavusEnv === 'development' || tavusEnv === 'staging' || tavusEnv === 'production') {
return tavusEnv;
}
// Check NODE_ENV
const nodeEnv = process.env.NODE_ENV;
Iif (nodeEnv === 'development' || nodeEnv === 'staging' || nodeEnv === 'production') {
return nodeEnv;
}
// Try hostname-based detection (for browser environments)
Iif (typeof window !== 'undefined' && window.location) {
const hostname = window.location.hostname;
Iif (hostname.includes('localhost') || hostname.includes('127.0.0.1')) {
return 'development';
}
Iif (hostname.includes('staging')) {
return 'staging';
}
Iif (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
Iif (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
Iif (isNaN(value) || !isFinite(value)) {
console.warn(
`[Tavus Config] Invalid ${timeoutType}: ${value}. Using default: ${defaultValue}`
);
return defaultValue;
}
// Clamp value within allowed range
Iif (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 {
Iif (!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
Iif (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;
}
} |