/** * Generic Bot Logs Step * * API endpoint to retrieve bot logs for any bot type. * Queries database to determine bot type, then reads appropriate log file. * * Path: GET /api/bots/logs/:bot_id */ import * as path from 'path'; import * as fs from 'fs'; import { createSupabaseClient, type MotiaRequest } from '../src/lib/supabase'; export const config = { name: 'BotLogsGet', type: 'api', path: '/api/bots/logs/:bot_id', method: 'GET', description: 'Get bot logs for any bot type (generic endpoint)', emits: [], // No events emitted by this read-only endpoint }; // Map bot types to their log directories const BOT_LOG_DIRS: Record = { 'screenshare': '../bots/screenshare-bot/logs', 'screenshare_livekit': '../bots/screenshare-bot/logs', 'tool-forwarder': '../bots/tool-forwarder/logs', 'voice-agent': '../bots/voice-agent/logs', }; export const handler = async (req: MotiaRequest) => { try { const { bot_id } = req.params; if (!bot_id) { return { status: 400, body: { error: 'Validation failed', details: 'Missing bot_id parameter', }, }; } // Query database to get bot type const supabase = createSupabaseClient(); const { data: botData, error: dbError } = await supabase .from('active_bots') .select('bot_type, session_id, room_url, status') .eq('bot_id', bot_id) .single(); if (dbError) { console.error('[BotLogsGet] Database error:', dbError); return { status: 500, body: { error: 'Database query failed', details: dbError.message, }, }; } if (!botData) { return { status: 404, body: { error: 'Bot not found', details: `No active bot found with ID ${bot_id}`, }, }; } const { bot_type } = botData; // Get log directory for bot type const logDirRelative = BOT_LOG_DIRS[bot_type]; if (!logDirRelative) { return { status: 400, body: { error: 'Unsupported bot type', details: `Bot type '${bot_type}' is not configured for log retrieval`, bot_type, }, }; } // Construct log file path const logDir = path.join(__dirname, logDirRelative); const logFilePath = path.join(logDir, `bot-${bot_id}.log`); console.log( `[BotLogsGet] bot_id=${bot_id}, bot_type=${bot_type}, log_file=${logFilePath}` ); // Check if log file exists if (!fs.existsSync(logFilePath)) { // Try to list what files ARE in the log directory let availableFiles: string[] = []; try { if (fs.existsSync(logDir)) { availableFiles = fs.readdirSync(logDir); } } catch (_e) { // Ignore read errors } return { status: 404, body: { error: 'Log file not found', details: `No log file exists for bot ${bot_id}`, bot_id, bot_type, expected_path: logFilePath, log_directory: logDir, available_files: availableFiles.length > 0 ? availableFiles : 'directory not found or empty', }, }; } // Read log file const logContent = fs.readFileSync(logFilePath, 'utf-8'); const lines = logContent.split('\n'); // Get last N lines (default 200, can be controlled by query param) const tailLines = parseInt(req.query.lines || '200', 10); const recentLines = lines.slice(-tailLines); return { status: 200, headers: { 'Content-Type': 'application/json', }, body: { bot_id, bot_type, session_id: botData.session_id, status: botData.status, log_file: logFilePath, total_lines: lines.length, returned_lines: recentLines.length, lines: recentLines, content: recentLines.join('\n'), }, }; } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; const errorStack = error instanceof Error ? error.stack : undefined; console.error('[BotLogsGet] Error:', error); return { status: 500, body: { error: 'Failed to read bot logs', details: errorMessage, stack: process.env.NODE_ENV === 'development' ? errorStack : undefined, }, }; } };