/** * Screenshare Bot Process Manager * * Manages Pipecat-based screenshare bot processes that join Daily.co rooms * and stream Slidev presentations. * * Usage: * - Bot spawned via API when presentation session starts * - Bot joins Daily room and streams Slidev deck (via Python child process) * - Listens for slide control commands via Supabase Realtime * - Sends responses back to presentation session */ import { EventEmitter } from 'events'; import { spawn, type ChildProcess } from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import { v4 as uuidv4 } from 'uuid'; interface BotSpawnConfig { roomUrl: string; deckUrl: string; sessionId: string; meetingToken?: string; } interface ActiveBot { botId: string; roomUrl: string; deckUrl: string; sessionId: string; process: ChildProcess; pid?: number; status: 'spawning' | 'running' | 'stopping' | 'stopped' | 'error'; spawnedAt: Date; stoppedAt?: Date; error?: string; } // Use global state to persist bots across Motia module reloads // Motia dynamically imports step files on each request, breaking singleton pattern declare global { // eslint-disable-next-line no-var var __screenshareBotManagerState: Map | undefined; } class ScreenshareBotManager extends EventEmitter { private activeBots: Map; constructor() { super(); // Initialize global state if it doesn't exist if (!global.__screenshareBotManagerState) { global.__screenshareBotManagerState = new Map(); console.log('[ScreenshareBotManager] Initialized NEW global state'); } else { console.log('[ScreenshareBotManager] Using EXISTING global state with', global.__screenshareBotManagerState.size, 'bots'); } // Reference the global state this.activeBots = global.__screenshareBotManagerState; } /** * Spawn a screenshare bot for a presentation session * * @param config Bot spawn configuration * @returns Bot ID and process details */ async spawnBot(config: BotSpawnConfig): Promise<{ botId: string; status: string; pid?: number; estimatedJoinTime: string; }> { const { roomUrl, deckUrl, sessionId, meetingToken } = config; const botId = uuidv4(); console.log(`[ScreenshareBotManager] Spawning bot ${botId}:`, { sessionId, roomUrl, deckUrl, }); // Path to Python bot (in bots/screenshare-bot directory) const botScriptPath = path.join(__dirname, '../../bots/screenshare-bot/bot.py'); const venvPython = path.join(__dirname, '../../bots/screenshare-bot/.venv/bin/python'); // Check if venv exists, otherwise use system python const pythonCmd = fs.existsSync(venvPython) ? venvPython : 'python3'; console.log(`[ScreenshareBotManager] Using Python: ${pythonCmd}`); console.log(`[ScreenshareBotManager] Bot script: ${botScriptPath}`); // DIAGNOSTIC: Check if python and script exist console.log(`[ScreenshareBotManager] DEBUG: Python exists: ${fs.existsSync(pythonCmd)}`); console.log(`[ScreenshareBotManager] DEBUG: Script exists: ${fs.existsSync(botScriptPath)}`); // Build command arguments const args = [botScriptPath, roomUrl, deckUrl, sessionId]; if (meetingToken) { args.push(meetingToken); } console.log(`[ScreenshareBotManager] Command: ${pythonCmd} ${args.join(' ')}`); console.log(`[ScreenshareBotManager] DEBUG: About to spawn process...`); // Create log directory and files for bot output (fallback for debugging) const botLogDir = path.join(__dirname, '../../bots/screenshare-bot/logs'); const botLogFile = path.join(botLogDir, `bot-${botId}.log`); // Ensure log directory exists if (!fs.existsSync(botLogDir)) { fs.mkdirSync(botLogDir, { recursive: true }); } // Create log file stream const logStream = fs.createWriteStream(botLogFile, { flags: 'a' }); logStream.write(`\n=== Bot ${botId} started at ${new Date().toISOString()} ===\n`); logStream.write(`Command: ${pythonCmd} ${args.join(' ')}\n`); logStream.write(`Working directory: ${path.join(__dirname, '../../bots/screenshare-bot')}\n\n`); // Spawn Python bot as child process const botProcess = spawn(pythonCmd, args, { env: { ...process.env, DAILY_PIPECAT_API_KEY: process.env.DAILY_PIPECAT_API_KEY, SUPABASE_URL: process.env.SUPABASE_URL, SUPABASE_SERVICE_KEY: process.env.SUPABASE_SERVICE_KEY, PYTHONUNBUFFERED: '1', // Ensure output is not buffered }, cwd: path.join(__dirname, '../../bots/screenshare-bot'), // Run from bot directory stdio: ['ignore', 'pipe', 'pipe'], // Explicitly pipe stdout and stderr }); console.log(`[ScreenshareBotManager] DEBUG: spawn() returned`); // Listen for 'spawn' event to confirm process started botProcess.on('spawn', () => { console.log(`[ScreenshareBotManager] DEBUG: 'spawn' event fired for bot ${botId}`); }); // Create bot record const bot: ActiveBot = { botId, roomUrl, deckUrl, sessionId, process: botProcess, pid: botProcess.pid, status: 'spawning', spawnedAt: new Date(), }; this.activeBots.set(botId, bot); // Log bot output console.log(`[ScreenshareBotManager] DEBUG: botProcess.stdout = ${botProcess.stdout}`); console.log(`[ScreenshareBotManager] DEBUG: botProcess.stderr = ${botProcess.stderr}`); console.log(`[ScreenshareBotManager] DEBUG: botProcess.pid = ${botProcess.pid}`); console.log(`[ScreenshareBotManager] DEBUG: Attaching stdout listener for bot ${botId}`); console.log(`[ScreenshareBotManager] Log file: ${botLogFile}`); botProcess.stdout?.on('data', (data) => { console.log(`[ScreenshareBotManager] DEBUG: stdout data received for bot ${botId}`); const output = data.toString().trim(); console.log(`[Bot ${botId}] ${output}`); // Write to log file logStream.write(`[STDOUT] ${output}\n`); // Detect when bot successfully joins room if (output.includes('Room joined successfully') || output.includes('✅ Room joined')) { bot.status = 'running'; this.emit('bot-joined', { botId, sessionId, roomUrl }); } }); console.log(`[ScreenshareBotManager] DEBUG: Attaching stderr listener for bot ${botId}`); botProcess.stderr?.on('data', (data) => { console.log(`[ScreenshareBotManager] DEBUG: stderr data received for bot ${botId}`); const error = data.toString().trim(); console.error(`[Bot ${botId}] ERROR: ${error}`); // Write to log file logStream.write(`[STDERR] ${error}\n`); // Track critical errors if (error.includes('ERROR') || error.includes('Fatal') || error.includes('failed')) { bot.error = error; } }); console.log(`[ScreenshareBotManager] DEBUG: Attaching exit listener for bot ${botId}`); botProcess.on('exit', (code, signal) => { console.log(`[ScreenshareBotManager] DEBUG: exit event fired for bot ${botId} with code ${code}, signal ${signal}`); console.log(`[ScreenshareBotManager] Bot ${botId} exited (code: ${code}, signal: ${signal})`); bot.status = code === 0 ? 'stopped' : 'error'; bot.stoppedAt = new Date(); if (code !== 0 && !bot.error) { bot.error = `Process exited with code ${code}`; } this.emit('bot-exited', { botId, sessionId, exitCode: code, error: bot.error, }); }); console.log(`[ScreenshareBotManager] DEBUG: Attaching close listener for bot ${botId}`); botProcess.on('close', (code, signal) => { console.log(`[ScreenshareBotManager] DEBUG: close event fired for bot ${botId} with code ${code}, signal ${signal}`); // Close log stream logStream.write(`\n=== Bot ${botId} closed at ${new Date().toISOString()} (code: ${code}, signal: ${signal}) ===\n`); logStream.end(); // Keep bot record for 5 minutes for status queries setTimeout(() => { this.activeBots.delete(botId); }, 5 * 60 * 1000); }); botProcess.on('error', (error) => { console.error(`[ScreenshareBotManager] Bot ${botId} process error:`, error); bot.status = 'error'; bot.error = error.message; bot.stoppedAt = new Date(); this.emit('bot-error', { botId, sessionId, error: error.message, }); // Keep bot record for 5 minutes for status queries setTimeout(() => { this.activeBots.delete(botId); }, 5 * 60 * 1000); }); console.log( `[ScreenshareBotManager] ✅ Bot ${botId} spawned (PID: ${botProcess.pid})` ); console.log(`[ScreenshareBotManager] Active bots: ${this.activeBots.size}`); // Emit event for monitoring this.emit('bot-spawned', { botId, sessionId, roomUrl, deckUrl, pid: botProcess.pid, }); return { botId, status: 'spawning', pid: botProcess.pid, estimatedJoinTime: '5s', }; } /** * Kill a bot by bot ID * * @param botId Bot ID to kill */ killBot(botId: string): void { const bot = this.activeBots.get(botId); if (!bot) { console.log(`[ScreenshareBotManager] No bot found with ID: ${botId}`); throw new Error(`Bot not found: ${botId}`); } console.log( `[ScreenshareBotManager] Killing bot ${botId} (PID: ${bot.pid})` ); // Update status bot.status = 'stopping'; // Send SIGTERM for graceful shutdown bot.process.kill('SIGTERM'); // Force kill after 10 seconds if still running setTimeout(() => { if (this.activeBots.has(botId) && bot.status !== 'stopped') { console.log(`[ScreenshareBotManager] Force killing bot ${botId}`); bot.process.kill('SIGKILL'); } }, 10000); console.log(`[ScreenshareBotManager] ✅ SIGTERM sent to bot ${botId}`); // Emit event for monitoring this.emit('bot-killed', { botId, sessionId: bot.sessionId }); } /** * Get bot status by bot ID * * @param botId Bot ID to query * @returns Bot status details or null if not found */ getBotStatus(botId: string): ActiveBot | null { const bot = this.activeBots.get(botId); if (!bot) { return null; } return { botId: bot.botId, roomUrl: bot.roomUrl, deckUrl: bot.deckUrl, sessionId: bot.sessionId, process: bot.process, // Note: Don't serialize this in API responses pid: bot.pid, status: bot.status, spawnedAt: bot.spawnedAt, stoppedAt: bot.stoppedAt, error: bot.error, }; } /** * Get status of all bots * * @returns Status summary of all bots */ getAllBotsStatus() { return { activeCount: this.activeBots.size, bots: Array.from(this.activeBots.entries()).map(([id, bot]) => ({ botId: id, sessionId: bot.sessionId, roomUrl: bot.roomUrl, deckUrl: bot.deckUrl, status: bot.status, pid: bot.pid, spawnedAt: bot.spawnedAt, stoppedAt: bot.stoppedAt, error: bot.error, })), }; } /** * Find bot by session ID * * @param sessionId Session ID to search for * @returns Bot ID if found, null otherwise */ findBotBySessionId(sessionId: string): string | null { for (const [botId, bot] of this.activeBots.entries()) { if (bot.sessionId === sessionId) { return botId; } } return null; } /** * Shutdown all bots (graceful shutdown) */ shutdown(): void { console.log('[ScreenshareBotManager] Shutting down all bots...'); for (const [botId] of this.activeBots) { try { this.killBot(botId); } catch (error) { console.error(`[ScreenshareBotManager] Error killing bot ${botId}:`, error); } } console.log('[ScreenshareBotManager] ✅ All bots shut down'); } } // Singleton instance export const screenshareBotManager = new ScreenshareBotManager(); // Graceful shutdown handlers process.on('SIGTERM', () => { screenshareBotManager.shutdown(); }); process.on('SIGINT', () => { screenshareBotManager.shutdown(); process.exit(0); });