/** * Slidev Control Step * * API endpoint that broadcasts navigation commands to Slidev presentations * via Supabase Realtime. * * Path: POST /api/slidev/control */ export const config = { name: 'SlidevControl', type: 'api', path: '/api/slidev/control', method: 'POST', description: 'Send navigation commands to Slidev presentations', emits: ['slidev.command.sent', 'slidev.command.failed'] }; interface ControlInput { deckId: string; command: 'next' | 'prev' | 'goto'; slideId?: string; sessionId?: string; // For agent authentication } interface ControlOutput { success: boolean; command: string; message: string; } export const handler = async (req: MotiaRequest, { emit }: MotiaContext) => { try { const input: ControlInput = req.body; // Authentication: Support both API key and agent session ID const apiKey = req.headers['x-api-key']; const expectedApiKey = process.env.SLIDEV_API_KEY; const sessionId = input.sessionId; // Check if authenticated via API key const hasValidApiKey = expectedApiKey && apiKey === expectedApiKey; // Check if authenticated via session ID (for voice agents) let hasValidSession = false; if (sessionId && !hasValidApiKey) { const supabaseUrl = process.env.SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY; if (supabaseUrl && supabaseServiceKey) { // Verify session exists and is active const sessionResponse = await fetch( `${supabaseUrl}/rest/v1/conversation_sessions?id=eq.${sessionId}&select=id,status,livekit_room_id`, { headers: { 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}` } } ); if (sessionResponse.ok) { const sessions = await sessionResponse.json(); if (sessions && sessions.length > 0) { const session = sessions[0]; // Session is valid if it's a LiveKit session and status is not abandoned/failed hasValidSession = !!(session.livekit_room_id && ['initiating', 'presenting', 'completed'].includes(session.status)); console.log('[SlidevControl] Agent authentication:', { sessionId, status: session.status, authenticated: hasValidSession }); } } } } // Require either valid API key or valid session if (!hasValidApiKey && !hasValidSession) { return { status: 401, body: { error: 'Authentication failed', details: 'Provide valid x-api-key header or sessionId in body' } }; } // Validate required inputs if (!input.deckId || !input.command) { return { status: 400, body: { error: 'Validation failed', details: 'Missing required fields: deckId and command' } }; } // Validate command type const validCommands = ['next', 'prev', 'goto']; if (!validCommands.includes(input.command)) { return { status: 400, body: { error: 'Validation failed', details: `Invalid command. Must be one of: ${validCommands.join(', ')}` } }; } // Validate slideId is provided for 'goto' command if (input.command === 'goto' && !input.slideId) { return { status: 400, body: { error: 'Validation failed', details: 'slideId is required for goto command' } }; } console.log('[SlidevControl] Sending control command', { deckId: input.deckId, command: input.command, slideId: input.slideId }); // Step 1: Verify deck exists in Supabase const supabaseUrl = process.env.SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY; if (!supabaseUrl || !supabaseServiceKey) { throw new Error('SUPABASE_URL or SUPABASE_SERVICE_KEY not configured'); } const deckResponse = await fetch( `${supabaseUrl}/rest/v1/slidev_decks?deck_id=eq.${input.deckId}&select=id`, { headers: { 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}` } } ); if (!deckResponse.ok) { throw new Error(`Failed to verify deck: ${deckResponse.statusText}`); } const decks = await deckResponse.json(); if (!decks || decks.length === 0) { return { status: 404, body: { error: 'Deck not found', details: `No deck exists with ID: ${input.deckId}` } }; } // Step 2: Insert command to trigger Realtime broadcast const commandData = { deck_id: input.deckId, command: input.command, slide_id: input.slideId || null, timestamp: new Date().toISOString() }; const insertResponse = await fetch( `${supabaseUrl}/rest/v1/slide_control_commands`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'apikey': supabaseServiceKey, 'Authorization': `Bearer ${supabaseServiceKey}`, 'Prefer': 'return=representation' }, body: JSON.stringify(commandData) } ); if (!insertResponse.ok) { const errorText = await insertResponse.text(); throw new Error(`Failed to broadcast command: ${errorText}`); } console.log('[SlidevControl] Command broadcast successfully', { deckId: input.deckId, command: input.command }); const output: ControlOutput = { success: true, command: input.command, message: 'Command broadcast successfully' }; // Emit success event emit({ topic: 'slidev.command.sent', data: { deckId: input.deckId, command: input.command, slideId: input.slideId } }); return { status: 200, body: output }; } catch (error: unknown) { console.error('[SlidevControl] Error:', error); // Emit failure event emit({ topic: 'slidev.command.failed', data: { error: error.message, timestamp: new Date().toISOString() } }); return { status: 500, body: { error: 'Failed to send command', details: error.message } }; } };