/** * Screenshare Bot Kill Step * * API endpoint to gracefully terminate a running screenshare bot. * Sends SIGTERM to the bot process for graceful shutdown. * * ARCHITECTURE: Event-driven + Supabase * - Queries bot from Supabase active_bots table * - Uses OS-level kill (SIGTERM → SIGKILL) * - Updates database status to 'stopping' * * Path: POST /api/bots/screenshare/kill/:bot_id * * URL Parameters: * - bot_id: The bot ID returned from spawn endpoint * * Response: * { * "success": true, * "message": "Bot killed successfully", * "bot_id": "uuid" * } */ import { createSupabaseClient, killProcess, isProcessAlive, type MotiaRequest, type MotiaContext } from '../src/lib/supabase'; export const config = { name: 'ScreenshareBotKill', type: 'api', path: '/api/bots/screenshare/kill/:bot_id', method: 'POST', description: 'Kill screenshare bot process', emits: ['screenshare.bot.killed', 'screenshare.bot.kill.failed'] }; interface KillResponse { success: boolean; message: string; bot_id: string; } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { const botId = req.params?.bot_id; console.log('[ScreenshareBotKill] Kill request:', { bot_id: botId }); // Validate bot_id parameter if (!botId) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required URL parameter: bot_id', }, }; } // Validate bot_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(botId)) { return { status: 400, body: { error: 'Validation failed', details: 'Invalid bot_id format. Must be a valid UUID', }, }; } // Initialize Supabase client const supabase = createSupabaseClient(); // Query bot from Supabase (filter by bot_type to ensure we only kill screenshare bots) const { data: bot, error } = await supabase .from('active_bots') .select('*') .eq('bot_id', botId) .eq('bot_type', 'screenshare') .single(); if (error || !bot) { return { status: 404, body: { error: 'Bot not found', details: `No screenshare bot exists with ID: ${botId}`, }, }; } // Check if bot is already stopped if (bot.status === 'stopped' || bot.status === 'stopping') { return { status: 409, body: { error: 'Bot already stopped', details: `Bot ${botId} is already ${bot.status}`, bot_id: botId, status: bot.status, }, }; } // Check if process is still alive const isAlive = isProcessAlive(bot.pid); if (!isAlive) { console.log(`[ScreenshareBotKill] Bot ${botId} process already dead (PID: ${bot.pid})`); // Update status in database await supabase .from('active_bots') .update({ status: 'stopped', stopped_at: new Date().toISOString(), error_message: 'Process already dead', }) .eq('bot_id', botId); return { status: 409, body: { error: 'Bot already stopped', details: `Bot ${botId} process is not running (PID ${bot.pid} not found)`, bot_id: botId, status: 'stopped', }, }; } // Kill the bot process (SIGTERM → SIGKILL) console.log(`[ScreenshareBotKill] Sending SIGTERM to PID ${bot.pid}`); killProcess(bot.pid); // Update status in database await supabase .from('active_bots') .update({ status: 'stopping', }) .eq('bot_id', botId); const response: KillResponse = { success: true, message: `Bot ${botId} killed successfully (SIGTERM sent to PID ${bot.pid})`, bot_id: botId, }; // Emit success event emit({ topic: 'screenshare.bot.killed', data: { bot_id: botId, session_id: bot.session_id, pid: bot.pid, timestamp: new Date().toISOString(), }, }); console.log('[ScreenshareBotKill] ✅ Bot killed:', botId); return { status: 200, body: response, }; } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; console.error('[ScreenshareBotKill] Error:', error); // Emit failure event emit({ topic: 'screenshare.bot.kill.failed', data: { error: errorMessage, timestamp: new Date().toISOString(), }, }); return { status: 500, body: { error: 'Failed to kill bot', details: errorMessage, }, }; } };