/** * Screenshare Bot Spawn Step * * API endpoint to spawn a Pipecat-based screenshare bot that joins a Daily.co room * and streams a Slidev presentation deck. * * ARCHITECTURE: Event-driven + Supabase * - Stateless step (no shared in-memory state) * - Stores bot metadata in Supabase active_bots table * - Spawns detached bot process (orphaned, survives parent termination) * - Emits events for monitoring * * Path: POST /api/bots/screenshare/spawn */ import { spawn } from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import { v4 as uuidv4 } from 'uuid'; import { createSupabaseClient , type MotiaRequest, type MotiaContext } from '../src/lib/supabase'; export const config = { name: 'ScreenshareBotSpawn', type: 'api', path: '/api/bots/screenshare/spawn', method: 'POST', description: 'Spawn screenshare bot for presentation session', emits: ['screenshare.bot.spawned', 'screenshare.bot.spawn.failed'] }; interface SpawnRequest { room_url: string; deck_url: string; session_id: string; meeting_token?: string; } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { const { room_url, deck_url, session_id, meeting_token } = req.body as SpawnRequest; console.log('[ScreenshareBotSpawn] Spawn request:', { session_id, room_url, deck_url, has_token: !!meeting_token, }); // Log detected transport type early for debugging const isLiveKit = room_url.startsWith('wss://') && room_url.includes('.livekit.'); const isDaily = room_url.startsWith('https://') && room_url.includes('.daily.co/'); console.log(`[ScreenshareBotSpawn] Detected transport: ${isLiveKit ? 'LiveKit' : isDaily ? 'Daily.co' : 'unknown'}`); // Validate required fields if (!room_url || !deck_url || !session_id) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required fields: room_url, deck_url, session_id', }, }; } // Validate room_url format and detect transport type let transportType: 'daily' | 'livekit'; if (room_url.startsWith('https://') && room_url.includes('.daily.co/')) { transportType = 'daily'; } else if (room_url.startsWith('wss://') && room_url.includes('.livekit.')) { transportType = 'livekit'; } else { return { status: 400, body: { error: 'Validation failed', details: 'Invalid room_url format. Must be a Daily.co URL (https://*.daily.co/*) or LiveKit URL (wss://*.livekit.*/*)', examples: { daily: 'https://example.daily.co/room-name', livekit: 'wss://example.livekit.cloud/room-name', }, }, }; } // Validate deck_url format if (!deck_url.startsWith('http://') && !deck_url.startsWith('https://') && !deck_url.startsWith('file://')) { return { status: 400, body: { error: 'Validation failed', details: 'Invalid deck_url format. Must be an HTTP(S) or file:// URL', }, }; } // Validate session_id format (UUID) const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; if (!uuidRegex.test(session_id)) { return { status: 400, body: { error: 'Validation failed', details: 'Invalid session_id format. Must be a valid UUID', }, }; } // Check required env vars based on transport type if (transportType === 'daily' && !process.env.DAILY_PIPECAT_API_KEY) { return { status: 500, body: { error: 'Server configuration error', details: 'DAILY_PIPECAT_API_KEY not configured (required for Daily.co transport)', }, }; } if (transportType === 'livekit' && (!process.env.LIVEKIT_API_KEY || !process.env.LIVEKIT_API_SECRET)) { return { status: 500, body: { error: 'Server configuration error', details: 'LIVEKIT_API_KEY and LIVEKIT_API_SECRET not configured (required for LiveKit transport)', }, }; } // Initialize Supabase client const supabase = createSupabaseClient(); // Check if bot already exists for this session const { data: existingBots } = await supabase .from('active_bots') .select('*') .eq('session_id', session_id) .in('status', ['spawning', 'running']); if (existingBots && existingBots.length > 0) { const existingBot = existingBots[0]; console.log(`[ScreenshareBotSpawn] Bot already exists: ${existingBot.bot_id}`); return { status: 409, body: { error: 'Bot already exists', details: `A bot is already active for session ${session_id}`, bot_id: existingBot.bot_id, status: existingBot.status, }, }; } // Generate bot ID const botId = uuidv4(); // Prepare Python bot paths const botScriptPath = path.join(__dirname, '../bots/screenshare-bot/bot.py'); const venvPython = path.join(__dirname, '../bots/screenshare-bot/.venv/bin/python'); const pythonCmd = fs.existsSync(venvPython) ? venvPython : 'python3'; // Prepare log file const logDir = path.join(__dirname, '../bots/screenshare-bot/logs'); if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir, { recursive: true }); } const logFilePath = path.join(logDir, `bot-${botId}.log`); // Build command arguments (pass bot_id to bot for status updates) const args = [botScriptPath, room_url, deck_url, session_id, botId]; if (meeting_token) { args.push(meeting_token); } console.log(`[ScreenshareBotSpawn] Spawning bot ${botId}`); console.log(`[ScreenshareBotSpawn] Command: ${pythonCmd} ${args.join(' ')}`); console.log(`[ScreenshareBotSpawn] Log file: ${logFilePath}`); // Prepare environment based on transport type const botEnv: Record = { ...process.env as Record, TRANSPORT_TYPE: transportType, SUPABASE_URL: process.env.SUPABASE_URL || '', SUPABASE_SERVICE_KEY: process.env.SUPABASE_SERVICE_KEY || '', PYTHONUNBUFFERED: '1', }; // Add transport-specific API keys if (transportType === 'daily') { botEnv.DAILY_PIPECAT_API_KEY = process.env.DAILY_PIPECAT_API_KEY || ''; } else if (transportType === 'livekit') { botEnv.LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || ''; botEnv.LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || ''; botEnv.LIVEKIT_URL = process.env.LIVEKIT_URL || ''; // Optional: LiveKit server URL } // Spawn bot process (detached, orphaned) const botProcess = spawn(pythonCmd, args, { env: botEnv, cwd: path.join(__dirname, '../bots/screenshare-bot'), stdio: ['ignore', 'pipe', 'pipe'], detached: true, // Important: detach so bot survives parent termination }); // Detach from parent (bot becomes orphaned/independent) botProcess.unref(); // Check if process has a PID if (!botProcess.pid) { throw new Error('Failed to spawn bot process: no PID assigned'); } const pid = botProcess.pid; // Create log stream for bot output const logStream = fs.createWriteStream(logFilePath, { flags: 'a' }); logStream.write(`\n=== Bot ${botId} started at ${new Date().toISOString()} ===\n`); logStream.write(`Transport Type: ${transportType}\n`); logStream.write(`Command: ${pythonCmd} ${args.join(' ')}\n`); logStream.write(`PID: ${pid}\n`); logStream.write(`Room URL: ${room_url}\n`); logStream.write(`Deck URL: ${deck_url}\n`); logStream.write(`Session ID: ${session_id}\n\n`); // Pipe bot output to log file botProcess.stdout?.on('data', (data) => { const output = data.toString(); logStream.write(`[STDOUT] ${output}`); }); botProcess.stderr?.on('data', (data) => { const error = data.toString(); logStream.write(`[STDERR] ${error}`); }); botProcess.on('exit', (code, signal) => { logStream.write(`\n=== Bot ${botId} exited at ${new Date().toISOString()} (code: ${code}, signal: ${signal}) ===\n`); logStream.end(); // Update database on exit supabase .from('active_bots') .update({ status: code === 0 ? 'stopped' : 'error', stopped_at: new Date().toISOString(), error_message: code !== 0 ? `Process exited with code ${code}` : null, }) .eq('bot_id', botId) .then(() => console.log(`[ScreenshareBotSpawn] Bot ${botId} status updated to ${code === 0 ? 'stopped' : 'error'}`)) .catch((err) => console.error(`[ScreenshareBotSpawn] Failed to update bot status:`, err)); }); // Store bot metadata in Supabase const { data: _botData, error: insertError } = await supabase .from('active_bots') .insert({ bot_id: botId, bot_type: 'screenshare', pid, session_id, room_url, deck_url, status: 'spawning', log_file_path: logFilePath, }) .select() .single(); if (insertError) { console.error('[ScreenshareBotSpawn] Failed to store bot in database:', insertError); // Kill the bot if DB insert failed try { process.kill(pid, 'SIGKILL'); } catch { // Ignore - process may already be dead } throw new Error(`Failed to store bot metadata: ${insertError.message}`); } console.log(`[ScreenshareBotSpawn] ✅ Bot ${botId} spawned successfully (PID: ${pid})`); // Emit success event emit({ topic: 'screenshare.bot.spawned', data: { bot_id: botId, session_id, room_url, deck_url, pid, }, }); return { status: 200, body: { bot_id: botId, status: 'spawning', pid, estimated_join_time: '5s', message: `Bot spawned successfully for session ${session_id}`, log_file: logFilePath, }, }; } catch (error: unknown) { console.error('[ScreenshareBotSpawn] Error:', error); emit({ topic: 'screenshare.bot.spawn.failed', data: { error: error.message, timestamp: new Date().toISOString(), }, }); return { status: 500, body: { error: 'Failed to spawn bot', details: error.message, }, }; } };