whats the timeout? do i have nay bug ? import { NextResponse } from 'next/server';
// Note: Install livekit-server-sdk package: pnpm add livekit-server-sdk
import { SipClient } from 'livekit-server-sdk';
_// Support both standard and humanlike_livekit prefixed environment variables_
const LIVEKIT_URL = process.env.HUMANLIKE_LIVEKIT_URL || process.env.HUMANLIKE_LIVEKIT_URL;
const LIVEKIT_API_KEY = process.env.HUMANLIKE_LIVEKIT_API_KEY || process.env.HUMANLIKE_LIVEKIT_API_KEY;
const LIVEKIT_API_SECRET = process.env.HUMANLIKE_LIVEKIT_API_SECRET || process.env.HUMANLIKE_LIVEKIT_API_SECRET;
// SIP Configuration
const SIP_ADDRESS = process.env.SIP_ADDRESS || '
sip.telnyx.com';
// Hardcoded SIP credentials
const SIP_USERNAME = 'livekituser2025';
const SIP_PASSWORD = 'SecurePass123LK2025';
// SIP Trunk ID to use
const SIP_TRUNK_ID = 'ST_TtPALWZ45DVd';
// Default "from" number: +1-650-900-8341 (normalized to E.164 format)
const DEFAULT_FROM_NUMBER = '
+16509008341';
const SIP_TRUNK_NUMBERS = (process.env.SIP_TRUNK_NUMBERS || process.env.HUMANLIKE_LIVEKIT_SIP_TRUNK_NUMBERS || DEFAULT_FROM_NUMBER).split(',').map(
n =>
n.trim());
export async function *POST*(_request_: Request) {
console.log('📞 Phone call API endpoint called');
if (!LIVEKIT_URL || !LIVEKIT_API_KEY || !LIVEKIT_API_SECRET) {
console.error('❌ LiveKit environment variables not configured');
return NextResponse.json(
{
error: 'LiveKit environment variables are not fully configured. Please set LIVEKIT_URL, LIVEKIT_API_KEY, and LIVEKIT_API_SECRET.'
},
{ status: 500 }
);
}
try {
const body = await
request.json();
const phoneNumber = body.phoneNumber?.trim();
console.log('📞📞📞 PHONE NUMBER RECEIVED 📞📞📞');
console.log('Raw phone number from request:', body.phoneNumber);
console.log('Trimmed phone number:', phoneNumber);
console.log('Phone number type:', typeof phoneNumber);
console.log('Phone number length:', phoneNumber?.length);
if (!phoneNumber) {
console.error('❌ Phone number is missing or empty');
return NextResponse.json(
{ error: 'phoneNumber is required' },
{ status: 400 }
);
}
// Validate phone number format (E.164 format: +[country code][number])
const phoneRegex = /^\+[1-9]\d{1,14}$/;
const isValidFormat = phoneRegex.test(phoneNumber);
console.log('📞 Making phone call to:', phoneNumber);
console.log('📞 Full phone number details:', {
original: body.phoneNumber,
trimmed: phoneNumber,
isValid: phoneNumber && phoneNumber.length > 0,
isValidFormat,
phoneNumberLength: phoneNumber.length,
startsWithPlus: phoneNumber.startsWith('+')
});
if (!isValidFormat) {
console.error('❌ Invalid phone number format:', phoneNumber);
console.error(' Expected format: +[country code][number] (E.164 format)');
console.error(' Example:
+306972804021 or
+16509008341');
return NextResponse.json(
{
error: 'Invalid phone number format. Please use E.164 format (e.g.,
+306972804021)',
received: phoneNumber,
expectedFormat: '+[country code][number]'
},
{ status: 400 }
);
}
console.log('📋 SIP Configuration:', {
address: SIP_ADDRESS,
hasUsername: !!SIP_USERNAME,
hasPassword: !!SIP_PASSWORD,
trunkId: SIP_TRUNK_ID,
trunkNumbers: SIP_TRUNK_NUMBERS,
fromNumber: DEFAULT_FROM_NUMBER,
livekitUrl: LIVEKIT_URL?.substring(0, 20) + '...',
hasApiKey: !!LIVEKIT_API_KEY,
hasApiSecret: !!LIVEKIT_API_SECRET
});
// Initialize SIP client
const sipClient = new SipClient(
LIVEKIT_URL,
LIVEKIT_API_KEY,
LIVEKIT_API_SECRET
);
// Trunk options - transport is required for outbound trunks
// Using UDP as default transport (common for SIP)
// SIPTransport enum values: 0 = UDP, 1 = TCP, 2 = TLS
const trunkOptions = {
transport: 0 as any,
// SIPTransport.UDP = 0
authUsername: SIP_USERNAME,
authPassword: SIP_PASSWORD
};
// Use existing SIP trunk ID or create new one
let trunkId = SIP_TRUNK_ID;
console.log('🔧 Using SIP trunk ID:', trunkId);
// If trunk doesn't exist, create it
try {
// Try to get existing trunk first (optional - you might want to skip this)
// const trunk = await sipClient.getSipTrunk(trunkId);
_// console.log('_✅
Using existing SIP trunk:', trunkId);
} catch (error) {
// If trunk doesn't exist, create it
console.log('🔧 Creating new SIP outbound trunk...');
const trunk = await sipClient.createSipOutboundTrunk(
'HumanlikeAI Trunk',
SIP_ADDRESS,
SIP_TRUNK_NUMBERS,
trunkOptions
);
trunkId = trunk.sipTrunkId;
console.log('✅ SIP trunk created:', {
sipTrunkId: trunk.sipTrunkId,
address: SIP_ADDRESS,
numbers: SIP_TRUNK_NUMBERS,
fromNumber: DEFAULT_FROM_NUMBER
});
}
console.log('✅ Using SIP trunk:', {
sipTrunkId: trunkId,
address: SIP_ADDRESS,
numbers: SIP_TRUNK_NUMBERS,
fromNumber: DEFAULT_FROM_NUMBER
});
// Create room name (generate unique room name or use provided one)
const roomName = body.roomName || `sip-room-${Date.now()}-${Math.random().toString(36).substring(7)}`;
const participantIdentity = body.participantIdentity || 'sip-test';
const participantName = body.participantName || 'Test Caller';
console.log('📞 Creating SIP participant to make call...');
console.log('📞 Call details:', {
sipTrunkId: trunkId,
phoneNumber,
roomName,
participantIdentity,
participantName
});
// Create SIP participant (this actually makes the phone call)
const fromNumber = body.sipNumber || DEFAULT_FROM_NUMBER;
const participantOptions = {
fromNumber,
// The "from" number (caller ID)
participantIdentity,
participantName,
participantAttributes: body.participantAttributes || {},
playRingtone: body.playRingtone ?? true,
hidePhoneNumber: body.hidePhoneNumber ?? false,
krispEnabled: body.krispEnabled ?? false,
waitUntilAnswered: true,
playDialtone: true
};
console.log('📞 SIP Participant Options:', JSON.stringify(participantOptions, null, 2));
const participant = await sipClient.createSipParticipant(
trunkId,
phoneNumber,
// Number to dial
roomName,
participantOptions
);
console.log('✅✅✅ SIP PARTICIPANT CREATED - CALL INITIATED ✅✅✅');
console.log('Participant Info:', JSON.stringify(participant, null, 2));
console.log('Call Details:', {
callTo: phoneNumber,
callFrom: fromNumber,
trunkId: trunkId,
roomName: roomName
});
return NextResponse.json({
success: true,
message: 'SIP call initiated successfully',
participant: {
participantId: participant.participantId,
participantIdentity: participant.participantIdentity,
roomName: participant.roomName
},
call: {
to: phoneNumber,
from: fromNumber,
trunkId: trunkId,
roomName: roomName
},
note:
Call initiated from ${fromNumber} to ${phoneNumber}
});
} catch (error) {
console.error('❌ Error creating SIP trunk:', error);
return NextResponse.json(
{
error: 'Failed to create SIP trunk',
details: error instanceof Error ? error.message : 'Unknown error'
},
{ status: 500 }
);
}
}
// GET endpoint for testing
export async function *GET*() {
return NextResponse.json({
status: 'ok',
message: 'Phone call API endpoint is ready',
timestamp: new Date().toISOString(),
hasSipConfig: {
hasAddress: !!SIP_ADDRESS,
hasUsername: !!SIP_USERNAME,
hasPassword: !!SIP_PASSWORD,
hasNumbers: SIP_TRUNK_NUMBERS.length > 0
},
sipConfig: {
address: SIP_ADDRESS,
numbers: SIP_TRUNK_NUMBERS,
// Don't expose passwords
hasAuth: !!SIP_USERNAME && !!SIP_PASSWORD
}
});
}