react-native-xavia-voice-agent-sdk
v1.3.0
Published
Headless React Native SDK for SIP-based voice agents. Zero UI, pure functionality. Supports multiple independent agent instances with WebRTC audio.
Maintainers
Readme
react-native-xavia-voice-agent-sdk
Headless React Native SDK for SIP-based voice agents. Zero UI, pure functionality. Connect to any SIP/WebRTC server, place and receive calls, control audio routing, and send DTMF tones — all from a single, lightweight package.
Features
- SIP over WebSocket — Full SIP REGISTER/INVITE/BYE/INFO flow via JsSIP
- WebRTC Audio — Native audio via
react-native-webrtcwith echo cancellation, noise suppression, and auto gain control - Multiple Agent Instances — Run independent agents on different SIP servers simultaneously
- Speaker/Earpiece Toggle — Runtime audio routing via
react-native-incall-manager - DTMF Support — Send tones via RFC 2833 (in-band) or SIP INFO fallback
- React Hook —
useVoiceAgenthook for instant React integration - Headless Architecture — No UI included; bring your own components
- TypeScript — Full type definitions included
- Cross-Platform — iOS and Android support
Installation
npm install react-native-xavia-voice-agent-sdkPeer Dependencies
Install these alongside the SDK:
npm install react-native-webrtc react-native-incall-manager| Package | Required | Purpose |
|---------|----------|---------|
| react-native-webrtc | Yes | WebRTC audio engine |
| react-native-incall-manager | No | Speaker/earpiece routing |
| react | Yes | React peer dependency |
| react-native | Yes | React Native peer dependency |
Post-Install (iOS)
cd ios && pod install && cd ..Platform Setup
iOS — ios/<YourApp>/Info.plist
Add the following entries:
<!-- Microphone access for voice calls -->
<key>NSMicrophoneUsageDescription</key>
<string>This app needs microphone access for voice calls</string>
<!-- Background audio for ongoing calls -->
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>voip</string>
</array>
<!-- InCallManager audio session -->
<key>AVAudioSessionCategory</key>
<string>AVAudioSessionCategoryPlayAndRecord</string>ATS Exceptions (Custom TLS Ports)
If your SIP server uses a self-signed certificate or non-standard TLS port (e.g., wss://sip.example.com:8089/ws), add ATS exceptions:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>your-sip-domain.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSTemporaryExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
</dict>
</dict>
</dict>Android — android/app/src/main/AndroidManifest.xml
Add these permissions before <application>:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Required for WebRTC on some devices -->
<uses-library android:name="org.apache.http.legacy" android:required="false" />Note:
CAMERApermission is required by the WebRTC engine even for audio-only calls.
Quick Start
1. Create an Agent
import { VoiceAgent } from 'react-native-xavia-voice-agent-sdk';
const agent = new VoiceAgent({
sip: {
domain: 'sip.example.com',
server: 'wss://sip.example.com:7443/ws',
user: '1001',
password: 'your-password',
displayName: 'Agent 1',
},
autoRegister: true,
onStatusChange: (status) => console.log('Status:', status),
onError: (err) => console.error('Error:', err),
});2. Use with React Hook
import React, { useEffect, useRef } from 'react';
import { View, Text, Button } from 'react-native';
import { VoiceAgent, useVoiceAgent } from 'react-native-xavia-voice-agent-sdk';
function CallScreen() {
const agentRef = useRef<VoiceAgent | null>(null);
useEffect(() => {
const agent = new VoiceAgent({
sip: {
domain: 'sip.example.com',
server: 'wss://sip.example.com:7443/ws',
user: '1001',
password: 'secret',
},
autoRegister: false,
});
agentRef.current = agent;
return () => agent.destroy();
}, []);
return agentRef.current ? <CallControls agent={agentRef.current} /> : null;
}
function CallControls({ agent }: { agent: VoiceAgent }) {
const {
status, isRegistered, isCalling, callDurationMs, error,
register, call, hangup, setMuted, setSpeakerOn,
isMuted, isSpeakerOn, sendDTMF,
} = useVoiceAgent(agent);
const formatDuration = (ms: number) => {
const s = Math.floor(ms / 1000);
return `${Math.floor(s / 60)}:${(s % 60).toString().padStart(2, '0')}`;
};
return (
<View style={{ padding: 20 }}>
<Text>Status: {status}</Text>
{isCalling && <Text>Duration: {formatDuration(callDurationMs)}</Text>}
{error && <Text>Error: {error.message}</Text>}
{!isRegistered && (
<Button title="Register" onPress={register} />
)}
{isRegistered && !isCalling && (
<Button title="Call 1000" onPress={() => call('1000')} />
)}
{isCalling && (
<>
<Button title="Hangup" onPress={hangup} />
<Button title={isMuted ? "Unmute" : "Mute"} onPress={() => setMuted(!isMuted)} />
<Button title={isSpeakerOn ? "Earpiece" : "Speaker"} onPress={() => setSpeakerOn(!isSpeakerOn)} />
<Button title="Send DTMF 1" onPress={() => sendDTMF('1')} />
</>
)}
</View>
);
}3. Multiple Agents (Different Servers)
const salesAgent = new VoiceAgent({
sip: {
domain: 'sales.example.com',
server: 'wss://sales.example.com:7443/ws',
user: '2001',
password: 'sales-pw',
},
autoRegister: true,
});
const supportAgent = new VoiceAgent({
sip: {
domain: 'support.example.com',
server: 'wss://support.example.com:7443/ws',
user: '3001',
password: 'support-pw',
},
autoRegister: true,
});
// Both register simultaneously — fully independentConfiguration
VoiceAgentConfig
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| sip | SipCredentials | required | SIP server credentials |
| sip.domain | string | — | SIP domain (e.g., sip.example.com) |
| sip.server | string | — | WebSocket URL (ws:// or wss://) |
| sip.user | string | — | SIP username |
| sip.password | string | — | SIP password |
| sip.extension | string? | — | Default extension to call |
| sip.displayName | string? | user | Caller display name |
| sip.authorizationUser | string? | user | Digest auth username override |
| sip.realm | string? | domain | Auth realm |
| audio | AudioConfig? | see below | WebRTC audio constraints |
| audio.echoCancellation | boolean | true | Echo cancellation |
| audio.noiseSuppression | boolean | true | Noise suppression |
| audio.autoGainControl | boolean | true | Auto gain control |
| iceServers | IceServer[] | Google STUN | ICE/TURN servers |
| autoRegister | boolean | false | Auto-register on connect |
| autoCallExtension | string? | — | Auto-call after registration |
| callTimeoutMs | number | 30000 | Call establishment timeout (ms) |
| registrationExpiryMs | number | 600000 | Registration expiry (ms) |
| reconnectionAttempts | number | 3 | WebSocket reconnection retries |
| reconnectionDelayMs | number | 2000 | Delay between retries (ms) |
| heartbeatIntervalMs | number | 30000 | SIP OPTIONS ping interval (ms) |
| incomingCallTimeoutMs | number | 45000 | Auto-answer timeout (ms) |
| onStatusChange | callback | — | Status change listener |
| onError | callback | — | Error listener |
| onIncomingCall | callback | — | Incoming call listener |
API Reference
VoiceAgent Class
Constructor
new VoiceAgent(config: VoiceAgentConfig)Methods
| Method | Returns | Description |
|--------|---------|-------------|
| register() | Promise<void> | Register with SIP server |
| unregister() | Promise<void> | Unregister from SIP server |
| call(extension) | Promise<void> | Place outgoing call to extension |
| hangup() | Promise<void> | End active call |
| answer() | Promise<void> | Answer incoming call |
| reject() | Promise<void> | Reject incoming call |
| sendDTMF(tone) | Promise<void> | Send DTMF tone (0-9, *, #, A-D) |
| setMuted(muted) | void | Mute/unmute microphone |
| setSpeakerOn(on) | Promise<void> | Switch to speaker/earpiece |
| connect() | Promise<void> | Initialize SIP + WebRTC stacks |
| destroy() | void | Full cleanup (unregister + close) |
| updateConfig(patch) | void | Update config at runtime |
| getState() | VoiceAgentState | Snapshot of current state |
| on(event, cb) | () => void | Subscribe to event (returns unsubscribe function) |
| off(event, cb) | void | Unsubscribe from event |
Getters
| Getter | Type | Description |
|--------|------|-------------|
| .status | AgentStatus | Current connection/call status |
| .isRegistered | boolean | Whether registered with SIP server |
| .isCalling | boolean | Whether a call is in progress |
| .error | VoiceAgentError \| null | Last error |
| .remoteIdentity | string \| null | Remote party identifier |
| .callDurationMs | number | Current call duration in milliseconds |
| .isMuted | boolean | Whether microphone is muted |
| .isSpeakerOn | boolean | Whether speakerphone is enabled |
useVoiceAgent Hook
const {
// State
status, isRegistered, isCalling, error,
remoteIdentity, callDurationMs,
// Actions
register, unregister, call, hangup,
answer, reject, sendDTMF,
setMuted, setSpeakerOn,
isMuted, isSpeakerOn,
// Config
updateConfig, destroy,
} = useVoiceAgent(agent, autoSync?: boolean);| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| agent | VoiceAgent | required | VoiceAgent instance |
| autoSync | boolean | true | Auto-sync state from agent events |
Events
Subscribe to events using agent.on(eventName, callback):
const unsubscribe = agent.on('callEstablished', (remoteIdentity) => {
console.log('Call connected to', remoteIdentity);
});
// Later, unsubscribe
unsubscribe();| Event | Payload | Description |
|-------|---------|-------------|
| statusChange | AgentStatus | Connection/call status changed |
| error | VoiceAgentError | Error occurred |
| registered | — | Successfully registered with SIP server |
| unregistered | — | Unregistered from SIP server |
| registrationFailed | VoiceAgentError | Registration failed |
| callEstablished | remoteIdentity: string | Call connected |
| callTerminated | — | Call ended normally |
| callFailed | VoiceAgentError | Call failed |
| incomingCall | caller: string | Incoming call received |
| ringing | — | Remote party is ringing |
| dtmfReceived | tone: string | DTMF tone received from remote |
| muteChanged | muted: boolean | Microphone mute state toggled |
| speakerChanged | on: boolean | Speaker state toggled |
| connectivityLost | — | WebSocket disconnected |
| connectivityRestored | — | WebSocket reconnected |
| stateChange | VoiceAgentState | Any state property changed |
Status Lifecycle
disconnected
│
▼
connecting ──► error
│
▼
registering ──► error
│
▼
registered
│
├── calling ──► ringing ──► connected
│ │
│ ▼
│ terminating ──► registered
│
└── ringing (incoming) ──► connected
│
▼
terminating ──► registeredRuntime Permissions
Request microphone permission before calling register() or call():
import { PermissionsAndroid, Platform } from 'react-native';
async function requestMicrophonePermission(): Promise<boolean> {
if (Platform.OS === 'android') {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.RECORD_AUDIO,
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
}
// iOS: Info.plist entry is sufficient; RN handles it via WebRTC
return true;
}
// Usage
const ok = await requestMicrophonePermission();
if (ok) {
agent.register();
}Architecture
┌──────────────────────────────────────────┐
│ VoiceAgent (class) │
│ ┌──────────┐ ┌────────────────────┐ │
│ │ SipStack │ │ MediaManager │ │
│ │ (SIP/WS) │ │ (WebRTC/audio) │ │
│ │ │ │ │ │
│ │ REGISTER │ │ getUserMedia │ │
│ │ INVITE │ │ RTCPeerConnection │ │
│ │ BYE/INFO │ │ Mute / Speaker │ │
│ └──────────┘ └────────────────────┘ │
│ │
│ Events ──► on('callEstablished', ...) │
│ Getters ──► agent.status │
│ Actions ──► agent.call('1000') │
└──────────────────────────────────────────┘
│
▼
react-native-webrtc
react-native-incall-manager (optional)Troubleshooting
| Issue | Likely Cause | Fix |
|-------|--------------|-----|
| REGISTER fails 401 loop | Wrong password or realm | Set sip.realm explicitly in config |
| WebSocket connection refused | Wrong server URL | Use wss:// for TLS, ws:// for plain |
| No audio | Missing permissions | Add RECORD_AUDIO permission in AndroidManifest / Info.plist |
| Speaker not working | InCallManager not installed | npm install react-native-incall-manager && cd ios && pod install |
| Call drops after 30s | No STUN/TURN | Configure iceServers with a TURN server |
| MediaStream error | Permission denied | Check mic permissions in app settings |
| Audio cuts off after 1s | Audio session conflict | Ensure react-native-incall-manager is installed and speaker is toggled |
| Agent hears its own voice | Acoustic echo via speaker | Switch to earpiece mode during calls |
Requirements
- React Native >= 0.73.0
- React >= 18.0.0
- Node.js >= 18.0.0
- iOS deployment target >= 13.0
- Android SDK >= 24 (Android 7.0)
License
MIT
Built by Xavia Solutions
