/** * Express API routes for bot management */ import { Router, type Request, type Response } from 'express'; import { v4 as uuidv4 } from 'uuid'; import { createClient } from '@supabase/supabase-js'; import { ScreenshareBot } from '../bots/ScreenshareBot'; import { botRegistry } from '../bots/BotRegistry'; import { generateLiveKitToken } from '../services/livekit'; import type { SpawnBotRequest, SpawnBotResponse, BotConfig } from '../bots/types'; const router = Router(); /** * POST /api/bots/screenshare/spawn-livekit * Spawn a new screenshare bot for a LiveKit room */ router.post('/api/bots/screenshare/spawn-livekit', (req: Request, res: Response) => { void (async () => { try { const { room_name, deck_url, session_id, screenshare_token }: SpawnBotRequest = req.body; // Validate request if (!room_name || !deck_url || !session_id) { res.status(400).json({ error: 'Missing required fields', required: ['room_name', 'deck_url', 'session_id'] }); return; } const botId = uuidv4(); const timestamp = new Date().toISOString(); console.log(`[API] Spawn bot request received:`, { botId, room_name, session_id, deck_url }); // Generate LiveKit token if not provided const livekitUrl = process.env.LIVEKIT_URL; if (!livekitUrl) { res.status(500).json({ error: 'LiveKit URL not configured' }); return; } const token = screenshare_token || await generateLiveKitToken({ roomName: room_name, participantName: `Screenshare Bot`, participantIdentity: `bot-${botId}` }); // Create bot configuration const config: BotConfig = { botId, roomName: room_name, deckUrl: deck_url, sessionId: session_id, screenshareToken: token, livekitUrl: `${livekitUrl}?token=${token}` }; // Create and start bot const bot = new ScreenshareBot(config); botRegistry.register(botId, bot); // Start bot asynchronously bot.start().catch(error => { console.error(`[API] Bot ${botId} failed to start:`, error); botRegistry.unregister(botId); }); // Insert into Supabase active_bots table const supabaseUrl = process.env.SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_KEY; if (supabaseUrl && supabaseKey) { const supabase = createClient(supabaseUrl, supabaseKey); await supabase.from('active_bots').insert({ bot_id: botId, bot_type: 'screenshare_livekit', session_id, status: 'spawning', created_at: timestamp }); } const response: SpawnBotResponse = { bot_id: botId, status: 'spawning', room_name }; res.status(201).json(response); console.log(`[API] Bot ${botId} spawned successfully`); } catch (error) { console.error('[API] Spawn bot error:', error); res.status(500).json({ error: 'Failed to spawn bot', details: error instanceof Error ? error.message : 'Unknown error' }); } })(); }); /** * POST /api/bots/:id/kill * Stop and remove a bot */ router.post('/api/bots/:id/kill', (req: Request, res: Response) => { void (async () => { try { const botId = req.params.id; console.log(`[API] Kill bot request:`, { botId }); const bot = botRegistry.get(botId); if (!bot) { res.status(404).json({ error: 'Bot not found' }); return; } // Stop the bot await bot.stop(); // Remove from registry botRegistry.unregister(botId); // Update Supabase const supabaseUrl = process.env.SUPABASE_URL; const supabaseKey = process.env.SUPABASE_SERVICE_KEY; if (supabaseUrl && supabaseKey) { const supabase = createClient(supabaseUrl, supabaseKey); await supabase .from('active_bots') .update({ status: 'stopped' }) .eq('bot_id', botId); } res.json({ bot_id: botId, status: 'stopped', message: 'Bot stopped successfully' }); console.log(`[API] Bot ${botId} killed successfully`); } catch (error) { console.error('[API] Kill bot error:', error); res.status(500).json({ error: 'Failed to kill bot', details: error instanceof Error ? error.message : 'Unknown error' }); } })(); }); /** * GET /api/bots/:id/status * Get status of a specific bot */ router.get('/api/bots/:id/status', (req: Request, res: Response): void => { try { const botId = req.params.id; const bot = botRegistry.get(botId); if (!bot) { res.status(404).json({ error: 'Bot not found' }); return; } const status = bot.getStatus(); res.json(status); } catch (error) { console.error('[API] Get bot status error:', error); res.status(500).json({ error: 'Failed to get bot status', details: error instanceof Error ? error.message : 'Unknown error' }); } }); /** * GET /api/bots/status * Get status of all bots */ router.get('/api/bots/status', (_req: Request, res: Response): void => { try { const allStatus = botRegistry.getAllStatus(); res.json({ count: botRegistry.getCount(), bots: allStatus }); } catch (error) { console.error('[API] Get all bots status error:', error); res.status(500).json({ error: 'Failed to get bots status', details: error instanceof Error ? error.message : 'Unknown error' }); } }); export default router;