/** * Tavus Bot Manager Service * * Manages Daily.co bot clients that listen for Tavus tool calls. * Runs inside the Motia Railway app - no separate deployment needed. * * Usage: * - Bot spawned via webhook when conversation starts * - Bot joins Daily room and listens for app-messages (via Python child process) * - Forwards tool calls to internal API handlers * - Sends responses back to Tavus */ import { EventEmitter } from 'events'; import { spawn, type ChildProcess } from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; interface BotConfig { roomUrl: string; conversationId: string; apiBaseUrl: string; } interface ActiveBot { roomUrl: string; conversationId: string; process: ChildProcess; isActive: boolean; } class TavusBotManager extends EventEmitter { private activeBots: Map = new Map(); constructor() { super(); console.log('[BotManager] Initialized'); } /** * Spawn a bot for a Tavus conversation * Called when system.replica_joined webhook received */ async spawnBot(config: BotConfig): Promise { const { roomUrl, conversationId, apiBaseUrl } = config; console.log(`[BotManager] Spawning bot for conversation: ${conversationId}`); console.log(`[BotManager] Room URL: ${roomUrl}`); // Check if bot already exists if (this.activeBots.has(conversationId)) { console.log(`[BotManager] Bot already active for ${conversationId}`); return; } // Path to Python bot (in bots/tavus-tool-forwarder directory) const botScriptPath = path.join(__dirname, '../../bots/tavus-tool-forwarder/bot.py'); const venvPython = path.join(__dirname, '../../bots/tavus-tool-forwarder/.venv/bin/python'); // Check if venv exists, otherwise use system python const pythonCmd = fs.existsSync(venvPython) ? venvPython : 'python3'; console.log(`[BotManager] Using Python: ${pythonCmd}`); console.log(`[BotManager] Bot script: ${botScriptPath}`); // Spawn Python bot as child process const botProcess = spawn(pythonCmd, [botScriptPath, roomUrl], { env: { ...process.env, DAILY_API_KEY: process.env.DAILY_API_KEY, API_BASE_URL: apiBaseUrl, PYTHONUNBUFFERED: '1', // Ensure output is not buffered }, }); // Log bot output botProcess.stdout?.on('data', (data) => { console.log(`[Bot ${conversationId}] ${data.toString().trim()}`); }); botProcess.stderr?.on('data', (data) => { console.error(`[Bot ${conversationId}] ERROR: ${data.toString().trim()}`); }); botProcess.on('close', (code) => { console.log(`[BotManager] Bot process exited for ${conversationId} (code: ${code})`); this.activeBots.delete(conversationId); this.emit('bot-exited', { conversationId, exitCode: code }); }); botProcess.on('error', (error) => { console.error(`[BotManager] Bot process error for ${conversationId}:`, error); this.activeBots.delete(conversationId); this.emit('bot-error', { conversationId, error: error.message }); }); const bot: ActiveBot = { roomUrl, conversationId, process: botProcess, isActive: true, }; this.activeBots.set(conversationId, bot); console.log(`[BotManager] ✅ Bot spawned for ${conversationId} (PID: ${botProcess.pid})`); console.log(`[BotManager] Active bots: ${this.activeBots.size}`); // Emit event for monitoring this.emit('bot-spawned', { conversationId, roomUrl, pid: botProcess.pid }); } /** * Kill a bot when conversation ends * Called when system.shutdown webhook received */ killBot(conversationId: string): void { const bot = this.activeBots.get(conversationId); if (!bot) { console.log(`[BotManager] No bot found for ${conversationId}`); return; } console.log(`[BotManager] Killing bot for ${conversationId} (PID: ${bot.process.pid})`); // Kill the Python bot process bot.process.kill('SIGTERM'); // Force kill after 5 seconds if still running setTimeout(() => { if (this.activeBots.has(conversationId)) { console.log(`[BotManager] Force killing bot ${conversationId}`); bot.process.kill('SIGKILL'); } }, 5000); bot.isActive = false; this.activeBots.delete(conversationId); console.log(`[BotManager] ✅ Bot killed for ${conversationId}`); console.log(`[BotManager] Active bots: ${this.activeBots.size}`); // Emit event for monitoring this.emit('bot-killed', { conversationId }); } /** * Get status of all active bots */ getStatus() { return { activeCount: this.activeBots.size, bots: Array.from(this.activeBots.entries()).map(([id, bot]) => ({ conversationId: id, roomUrl: bot.roomUrl, isActive: bot.isActive, pid: bot.process.pid, })), }; } /** * Shutdown all bots */ shutdown(): void { console.log('[BotManager] Shutting down all bots...'); for (const [conversationId] of this.activeBots) { this.killBot(conversationId); } console.log('[BotManager] ✅ All bots shut down'); } } // Singleton instance export const botManager = new TavusBotManager(); // Graceful shutdown process.on('SIGTERM', () => { botManager.shutdown(); }); process.on('SIGINT', () => { botManager.shutdown(); process.exit(0); });