/** * Screenshare Bot Spawn (LiveKit) Step * * API endpoint to spawn a Pipecat-based screenshare bot that joins a LiveKit room * and streams a Slidev presentation deck. * * ARCHITECTURE: Event-driven + Supabase + HTTP-based bot spawning * - Stateless step (no shared in-memory state) * - Stores bot metadata in Supabase active_bots table * - Delegates bot spawning to bot-spawner service via HTTP API * - Uses pre-generated LiveKit access token for authentication * - Emits events for monitoring * - Implements retry logic with exponential backoff * * Path: POST /api/bots/screenshare/spawn-livekit */ // OLD IMPLEMENTATION (Kept for rollback capability) // 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'; import type { MotiaRequest, MotiaContext } from '../src/lib/supabase'; export const config = { name: 'ScreenshareBotSpawnLiveKit', type: 'api', path: '/api/bots/screenshare/spawn-livekit', method: 'POST', description: 'Spawn screenshare bot for LiveKit room', emits: ['screenshare.bot.spawned.livekit', 'screenshare.bot.spawn.failed.livekit'] }; interface SpawnRequest { room_name: string; deck_url: string; session_id: string; screenshare_token: string; } // Bot Spawner service configuration const BOT_SPAWNER_URL = process.env.BOT_SPAWNER_URL || 'http://bot-spawner.railway.internal:3001'; const BOT_SPAWNER_TIMEOUT = 10000; // 10 second timeout const RETRY_DELAYS = [2000, 4000, 8000]; // Exponential backoff: 2s, 4s, 8s /** * Helper function to make HTTP request to bot-spawner with retry logic */ async function spawnBotViaHTTP(payload: SpawnRequest, attempt = 0): Promise<{ bot_id: string; status: string; estimated_join_time?: string; message?: string; }> { const url = `${BOT_SPAWNER_URL}/api/bots/screenshare/spawn-livekit`; console.log(`[BOT_SPAWNER] Attempt ${attempt + 1}/${RETRY_DELAYS.length + 1}: POST ${url}`, { session_id: payload.session_id, room_name: payload.room_name, }); try { const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), BOT_SPAWNER_TIMEOUT); const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(payload), signal: controller.signal, }); clearTimeout(timeoutId); const responseData = await response.json(); console.log(`[BOT_SPAWNER] Response (${response.status}):`, responseData); // Success case if (response.ok) { return responseData; } // Handle specific error cases if (response.status === 503) { // Service Unavailable - bot-spawner is down throw new Error(`Bot spawner service unavailable (503). ${responseData.details || ''}`); } if (response.status === 400) { // Bad Request - invalid payload (don't retry) throw new Error(`Invalid spawn request (400): ${responseData.details || responseData.error}`); } if (response.status === 409) { // Conflict - bot already exists (don't retry, but this is expected) console.log(`[BOT_SPAWNER] Bot already exists for session ${payload.session_id}`); return responseData; } if (response.status === 500) { // Internal Server Error - bot-spawner bug throw new Error(`Bot spawner internal error (500): ${responseData.details || responseData.error}`); } // Generic error for other status codes throw new Error(`Bot spawner returned ${response.status}: ${responseData.error || 'Unknown error'}`); } catch (error: unknown) { // Handle timeout if (error instanceof Error && error.name === 'AbortError') { console.error(`[BOT_SPAWNER] Request timeout after ${BOT_SPAWNER_TIMEOUT}ms`); throw new Error(`Bot spawner request timeout (exceeded ${BOT_SPAWNER_TIMEOUT}ms)`); } // Handle network errors if (error && typeof error === 'object' && 'code' in error) { const nodeError = error as NodeJS.ErrnoException; if (nodeError.code === 'ECONNREFUSED' || nodeError.code === 'ENOTFOUND') { console.error(`[BOT_SPAWNER] Network error:`, nodeError.message); throw new Error(`Cannot connect to bot spawner service: ${nodeError.message}`); } } // For 400 errors, don't retry if (error instanceof Error && error.message.includes('(400)')) { throw error; } // For other errors, check if we should retry if (attempt < RETRY_DELAYS.length) { const delay = RETRY_DELAYS[attempt]; const errorMessage = error instanceof Error ? error.message : 'Unknown error'; console.warn(`[BOT_SPAWNER] Request failed, retrying in ${delay}ms...`, errorMessage); await new Promise(resolve => setTimeout(resolve, delay)); return spawnBotViaHTTP(payload, attempt + 1); } // Max retries exhausted console.error(`[BOT_SPAWNER] Max retries (${RETRY_DELAYS.length + 1}) exhausted`); throw error; } } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { const { room_name, deck_url, session_id, screenshare_token } = req.body as SpawnRequest; console.log('[ScreenshareBotSpawnLiveKit] Spawn request:', { session_id, room_name, deck_url, has_token: !!screenshare_token, }); // Validate required fields if (!room_name || !deck_url || !session_id || !screenshare_token) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required fields: room_name, deck_url, session_id, screenshare_token', }, }; } // 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', }, }; } console.log(`[BOT_SPAWNER] Delegating spawn to bot-spawner service for session ${session_id}`); // Delegate bot spawning to bot-spawner service via HTTP const spawnResponse = await spawnBotViaHTTP({ room_name, deck_url, session_id, screenshare_token, }); console.log(`[BOT_SPAWNER] Bot spawn successful:`, { bot_id: spawnResponse.bot_id, status: spawnResponse.status, session_id, }); // Emit success event emit({ topic: 'screenshare.bot.spawned.livekit', data: { bot_id: spawnResponse.bot_id, session_id, room_name, deck_url, }, }); return { status: 200, body: { bot_id: spawnResponse.bot_id, status: spawnResponse.status, estimated_join_time: spawnResponse.estimated_join_time || '5s', message: spawnResponse.message || `LiveKit bot spawned successfully for session ${session_id}`, }, }; } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : 'Unknown error'; console.error('[ScreenshareBotSpawnLiveKit] Error:', error); emit({ topic: 'screenshare.bot.spawn.failed.livekit', data: { error: errorMessage, timestamp: new Date().toISOString(), }, }); return { status: 500, body: { error: 'Failed to spawn LiveKit bot', details: errorMessage, }, }; } }; // OLD IMPLEMENTATION (Commented out for rollback capability) /* async function handler_OLD_PYTHON_SPAWN(req: MotiaRequest, { emit }: MotiaContext) { // [Previous implementation that spawned Python processes directly] // This code has been replaced with HTTP API calls to bot-spawner service // See git history or above for the new implementation // Kept here for emergency rollback if needed } */