/** * Tool Forwarder Bot Kill Step * * API endpoint to gracefully terminate a running tool forwarder 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/tool-forwarder/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: 'ToolForwarderBotKill', type: 'api', path: '/api/bots/tool-forwarder/kill/:bot_id', method: 'POST', description: 'Kill tool forwarder bot process', emits: ['tool-forwarder.bot.killed', 'tool-forwarder.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('[ToolForwarderBotKill] 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 tool-forwarder bots) const { data: bot, error } = await supabase .from('active_bots') .select('*') .eq('bot_id', botId) .eq('bot_type', 'tool-forwarder') .single(); if (error || !bot) { return { status: 404, body: { error: 'Bot not found', details: `No tool-forwarder 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(`[ToolForwarderBotKill] Bot ${botId} process already dead (PID: ${bot.pid})`); // Update status in database await (supabase .from('active_bots') as Record) .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(`[ToolForwarderBotKill] Sending SIGTERM to PID ${bot.pid}`); killProcess(bot.pid); // Update status in database await (supabase .from('active_bots') as Record) .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: 'tool-forwarder.bot.killed', data: { bot_id: botId, pid: bot.pid, timestamp: new Date().toISOString(), }, }); console.log('[ToolForwarderBotKill] ✅ Bot killed:', botId); return { status: 200, body: response, }; } catch (error: unknown) { console.error('[ToolForwarderBotKill] Error:', error); // Emit failure event emit({ topic: 'tool-forwarder.bot.kill.failed', data: { error: error.message, timestamp: new Date().toISOString(), }, }); return { status: 500, body: { error: 'Failed to kill bot', details: error.message, }, }; } };