waha-calls
v0.2.6
Published
Client SDK for WhatsApp calls on WAHA (wahacall): config, browser softphone (WebRTC), events and raw PCM. WAHA-native auth, simple event-driven ergonomics.
Maintainers
Readme
waha-calls
Client SDK for WhatsApp calls on WAHA. One package: config (reject / allow / IVR / AI relay), softphone (browser WebRTC), events (including the AI→agent handoff), raw PCM (Node, for a server-side voice bot), call history and recordings.
- WAHA-native auth — API key + session.
- Event-driven —
offer.accept(),call.mute()/end()/getStats(),.on(...). - Zero runtime dependencies. In Node, inject a WebSocket (
ws). - Wraps endpoints that already exist:
/api/apps,/ws,/ws/calls/audioand the voice-calls app's own/api/apps/voice-calls/{session}(plus/{id}/webrtc).
Requires the voice-calls app installed on the session: the endpoints live under
the app and only exist while it is there. configure() installs it for you. It cannot
share a session with WAHA's own calls app - that one only rejects calls, and the
server refuses to enable both.
Requires the GOWS engine. Live audio also needs WAHA_CALLS_WEBRTC_PUBLIC_IP and the
UDP port open on the server; getUserMedia needs HTTPS (or localhost).
Contents
- Install · Connect · Constructor options
- Configuration — the four modes · every field
- Incoming calls · Outgoing calls
- The active call · WebRTC and ICE · Call quality
- Raw PCM in Node · Voice bot over relay
- Recording · History
- Multi-session · Events · Types
Install
npm install waha-callsIn Node also install a WebSocket implementation:
npm install waha-calls wsConnect
import { WahaCalls } from 'waha-calls';
const waha = new WahaCalls({
baseUrl: 'https://host',
apiKey: 'KEY',
session: 'default', // omit for a multi-session client
});
// The constructor already connects — do not call connect() after it.
waha.on('connectionStatus', (s) => console.log(s)); // connected | disconnected | reconnecting
waha.on('error', (e) => console.error(e));In Node, pass the WebSocket:
import { WebSocket } from 'ws';
const waha = new WahaCalls({ baseUrl, apiKey, session, webSocketImpl: WebSocket });When you are done, close the events socket. close() is deliberate: it will not
reconnect behind your back.
waha.close();⚠️ In Node, a script that skips
close()never exits. The constructor opens the events socket straight away, and an open socket keeps the event loop alive - so a one-shot script that only calls REST methods hangs after its last line, with no error and nothing printed to explain it:const waha = new WahaCalls({ baseUrl, apiKey, session, webSocketImpl: WebSocket }); console.log(await waha.listCalls()); waha.close(); // without this the process hangs here, foreverA long-running listener does not need it - that process is meant to stay up.
Constructor options
| Option | Type | Default | What it does |
| --- | --- | --- | --- |
| baseUrl | string | — | Required. WAHA server, e.g. https://host. |
| apiKey | string | — | Sent as X-Api-Key. |
| session | string | — | Default session for every method and for the events socket. Omit it for multi-session. |
| iceConfig | RTCConfiguration | no ICE servers | STUN/TURN for the browser softphone. See WebRTC and ICE. |
| autoReconnect | boolean | true | Reopen the events socket with backoff when it drops. |
| webSocketImpl | WebSocketCtor | global WebSocket | Required in Node — pass ws. |
autoReconnectdoes not replay what you missed. Events that happened during the gap are gone; uselistCalls()to reconcile after reconnecting.
Configuration
configure() writes the calls app for the session. It takes dm (one-to-one),
group, and recording.
⚠️ This restarts the WhatsApp session. The calls app is declared
restartOnChange, so any call in progress drops and the session cycles throughSTARTING. Configure once at startup — not per incoming call.It keeps whatever the app already had: omitting
recordingleaves an existing recording setting alone, and the app's enabled/disabled state is preserved, soconfigure()afterdisable()does not switch it back on.
await waha.configure({
dm: { mode: 'allow' },
group: { mode: 'reject' },
});The four modes
Set mode per channel. There is no reject: boolean field — the mode is the switch.
The app's own configuration — what you see reading
/api/appsdirectly, or in the dashboard — stores this asreject/autoAnswer/relay.enabled. The SDK mapsmodeonto those for you, so do not sendreject: truetoconfigure().
| Mode | What WAHA does |
| --- | --- |
| 'reject' | Declines the call. Optionally sends message to the caller. |
| 'allow' | Lets it ring so a client (softphone or bot) can answer it. |
| 'ivr' | Answers by itself and plays ivrAudioUrl. Nobody has to be connected. |
| 'relay' | Answers and bridges the audio to your WebSocket, both ways. |
// Decline politely, after letting it ring for 2 s
await waha.configure({
dm: { mode: 'reject', message: 'We do not take calls here — send a message.', waitBeforeDecline: 2 },
group: { mode: 'reject' },
});
// Answer with a recorded message (no client needed)
await waha.configure({
dm: { mode: 'ivr', waitBeforeAnswer: 3, ivrAudioUrl: 'https://host/greeting.mp3' },
group: { mode: 'reject' },
});
// Hand the audio to an AI voice agent
await waha.configure({
dm: {
mode: 'relay',
waitBeforeAnswer: 3,
relay: { url: 'wss://my-bot/voice', hangupOnDisconnect: false },
},
group: { mode: 'reject' },
});Configuration reference
ChannelConfig — applies to dm and group:
| Field | Type | Applies to | What it does |
| --- | --- | --- | --- |
| mode | 'reject' \| 'allow' \| 'ivr' \| 'relay' | all | Required. |
| message | string | reject | Text sent to the caller after declining. |
| waitBeforeDecline | number (s) | reject | Let it ring this long before declining. |
| waitBeforeResponse | number (s) | reject | Wait before sending message. |
| waitBeforeAnswer | number (s) | ivr, relay | Let it ring this long before answering. |
| ivrAudioUrl | string | ivr | Audio played to the caller. |
| messageOnAnswer | string | ivr, relay | Text sent to the chat when the call is answered. |
| relay | RelayConfig | relay | See below. |
RelayConfig:
| Field | Type | What it does |
| --- | --- | --- |
| url | string | Required. WebSocket WAHA dials and relays PCM through. |
| headers | Record<string,string> | Sent when opening the relay socket (e.g. Authorization). |
| greetingAudioUrl | string | Played while the relay connects. Without it the caller hears silence during the handshake. |
| holdAudioUrl | string | Looped hold music while waiting for an agent after an escalate. |
| holdTimeoutSec | number | How long to hold before giving up on the agent. |
| maxDurationSec | number | Hard cap on the call length. |
| hangupOnDisconnect | boolean | Hang up when your WebSocket drops. |
RecordingConfig — see Recording:
| Field | Type | Default | What it does |
| --- | --- | --- | --- |
| enabled | boolean | false | Record every call this session answers. |
| bitrate | number | 32000 | Opus target bitrate. Barely moves CPU. |
| separateChannels | boolean | true | Caller left, this session right. |
Reading it back
await waha.getConfig(); // CallsConfig | null
await waha.isEnabled(); // booleanIncoming calls
waha.on('offer', async (offer) => {
// peer.phone is empty when WhatsApp addressed the call by LID.
console.log('ringing from', offer.peer.phone || offer.peer.lid, 'on', offer.session);
const { call, err } = await offer.accept(); // answers + opens WebRTC audio
if (err) return console.error(err);
audioElement.srcObject = call.stream;
});Offer carries callId, session, peer, and — when it came from an escalate —
escalated, summary and intent.
| Method | What it does |
| --- | --- |
| accept() | Answers and opens the browser softphone. Returns { call?, err? }. Browser only. |
| answer() | Answers without media. For Node bots that pair it with grabPcm(). Returns { err? }. |
| reject() | Declines without answering. Returns { err? }. |
An offer can also be settled somewhere else — on the phone, or by another agent:
offer.on('acceptedElsewhere', () => hideRingingUI());
offer.on('rejectedElsewhere', () => hideRingingUI());
offer.on('ended', (reason) => hideRingingUI(reason));Outgoing calls
placeCall() only makes the phone ring. The audio arrives through grab() once the call
goes active.
const { callId, peerJid } = await waha.placeCall('5511999990000');
waha.on('call', (c) => console.log(c.state)); // Calling → Ringing → Connecting → Active
waha.on('ended', (i) => console.log('ended:', i.reason));
const { call } = await waha.grab(callId); // browser: take the audio
await waha.hangup(callId); // hang up without the Call objectThe SDK sends chatId as you give it; WAHA normalises it server-side, so a bare number
becomes a WhatsApp JID and @lid / group JIDs are passed through untouched.
The active call
call.mute();
call.unmute();
call.toggleMute();
call.isMuted; // boolean
call.stream; // MediaStream | null — attach to an <audio> element
call.callId;
call.session;
call.peer; // { phone, lid?, displayName? }
await call.end(); // hangs up and releases the microphone
call.on('connectionStatus', (s) => {}); // connecting | connected | disconnected
call.on('ended', () => {});WebRTC and ICE
By default the softphone uses no ICE servers: it relies on the server's
WAHA_CALLS_WEBRTC_PUBLIC_IP and the open UDP port, which is enough when the browser can
reach that address directly. Behind symmetric NAT or a restrictive firewall, pass your own
RTCConfiguration:
const waha = new WahaCalls({
baseUrl,
apiKey,
session,
iceConfig: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'turns:turn.example.com:5349', username: 'user', credential: 'pass' },
],
},
});iceConfig is a plain RTCConfiguration, so iceTransportPolicy: 'relay' (force TURN)
and the rest of the standard fields work as usual. It is passed to every Call the client
creates — through offer.accept() and through grab().
Call quality
const stats = await call.getStats();| Field | Meaning |
| --- | --- |
| rtt | Round-trip time, seconds. |
| rxLoss / txLoss | Packet loss fraction, received / sent. |
| rxBitrateKbps / txBitrateKbps | Bitrate in each direction. |
| jitterMs | Jitter, milliseconds. |
rxBitrateKbps: 0on a live call is usually not a bug — it is Opus DTX: a silent peer nearly stops transmitting.
Raw PCM in Node
For transcription, speech synthesis, or any bot that handles the audio itself. No WebRTC involved, so it works server-side.
import { WebSocket } from 'ws';
import { WahaCalls } from 'waha-calls';
const waha = new WahaCalls({ baseUrl, apiKey, session, webSocketImpl: WebSocket });
waha.on('offer', async (offer) => {
await offer.answer(); // answer WITHOUT the softphone
const pcm = await waha.grabPcm(offer.callId);
pcm.onAudio((frame) => stt.write(frame)); // caller → you
pcm.sendAudio(ttsFrame); // you → caller
pcm.on('ended', cleanup);
pcm.on('error', console.error);
// pcm.end() closes the bridge
});Audio is s16le / 16 kHz / mono — 1920 bytes (960 samples) per 60 ms frame, the same
framing as the relay. onAudio() returns an unsubscribe function; sendAudio() returns
false when the socket is closed.
Full runnable example: examples/node-bot.mjs.
Voice bot over relay
In relay mode WAHA dials your WebSocket and bridges the audio both ways — you do not
hold a call object at all. Binary frames are PCM in the framing above. Text frames are
control:
| Frame | Effect |
| --- | --- |
| {"type":"barge_in"} | Drops the audio you have queued (the caller interrupted). |
| {"type":"escalate","summary":"...","intent":"..."} | Hands the call to a human. |
| {"type":"hangup"} | Ends the call. |
WAHA sends call.start when it connects, carrying format: "s16le;16000;mono;60ms".
The handoff reaches the agent as an escalate event with an Offer already built:
waha.on('escalate', async ({ callId, session, peer, summary, intent, offer }) => {
showHandoff(summary, intent);
const { call } = await offer.accept(); // the agent takes over the same call
audioElement.srcObject = call.stream;
});waha.grab(callId, peer?, session?) does the same thing when you only have the id.
Recording
Recording lives in the engine, not here: it attaches the moment a call goes active, before anything knows whether a client will connect — which is why calls answered by the IVR or a relay, with nobody connected, are captured too.
await waha.configure({
dm: { mode: 'allow' },
group: { mode: 'reject' },
recording: { enabled: true, bitrate: 32000, separateChannels: true },
});
waha.on('recording', (r) => {
// Fires AFTER `ended` — the file only closes when the call is over.
console.log(r.durationMs, r.bytes, r.mimetype, r.url);
console.log(r.s3); // { Bucket, Key } — does not expire
console.log(r.droppedSamples); // normally 0; anything else means gaps
});Recordings are always stereo. separateChannels: true (the default) puts the caller on
the left and your session on the right, which makes transcription attribution exact —
measured at 99% of speech attributable to one side on a real call. false mixes both into
each channel, which is what a person on headphones expects. Separated can be mixed down
later; mixed cannot be separated.
⚠️ On S3 without the file proxy, r.url is presigned and expires in about an hour. Keep
r.s3, or fetch the call later:
const call = await waha.getCall(callId);
call?.recording?.s3; // { Bucket, Key } — does not expireHistory and management
// Past calls, newest first
const calls = await waha.listCalls({
direction: 'incoming', // 'incoming' | 'outgoing'
finalState: 'ended',
limit: 20,
offset: 0,
});
// One record, with its recording when there is one
const record = await waha.getCall(callId);
// Delete records — the RECORDING FILES STAY (disk or S3); only the rows go,
// and the record is the only pointer to the audio, so save what matters first
await waha.deleteCall(callId); // throws on unknown callId (404)
const n = await waha.deleteCalls({ // same filters as listCalls
finalState: 'missed',
limit: 100, // omitted limit = everything the
}); // filter matches, NOT first 50
// Decline a ringing call without an Offer (after a reconnect, or from a
// second process). `from` must be the EXACT raw address from the event —
// rebuilt from the number, WhatsApp drops the reject silently.
await waha.rejectCall(callId, from);
// The app itself
await waha.getConfig();
await waha.isEnabled();
await waha.disable(); // switches the app off, KEEPING the configuration
await waha.remove(); // deletes the app and everything in it — irreversibleCallRecord carries id, session, peer, direction, finalState, reason?,
isVideo, isGroup, startedAt (unix ms), endedAt?, durationSeconds? and
recording? — plus the parts behind peer, each present when known: peerLid?,
peerPhone? and peerName? (the contact name at the time of the call).
Record fields are full JIDs ([email protected], ...@lid); live-event CallPeer fields are
bare digits. Strip the suffix to correlate: record.peerLid?.replace(/@.*$/, '') ===
peer.lid.
⚠️ Deleting in batches: limit is capped at 500 by the server (400 above it), and
offset must not be used as a paging cursor for deletes — each batch shifts the survivors
into the offsets just deleted, skipping half the rows. Loop on limit alone until the
returned count comes back smaller. offset without limit has one legitimate delete use:
it spares the newest N rows ("keep the last 100, drop the rest").
Multi-session
Omit session in the constructor and the client subscribes to all sessions (*) over
one events socket. Every event carries its session, and every method takes one:
const waha = new WahaCalls({ baseUrl, apiKey }); // no session → all of them
waha.on('offer', async (offer) => {
console.log('ringing on', offer.session, 'from', offer.peer.phone);
const { call } = await offer.accept(); // the offer knows its own session
});
waha.on('escalate', async ({ session, callId }) => {
const { call } = await waha.grab(callId, undefined, session);
});
await waha.configure({ dm: { mode: 'relay', relay: { url } } }, 'sales');
await waha.placeCall('5511999990000', 'support');
await waha.listCalls({ limit: 20 }, 'support');Requires an API key with access to all sessions. With a single-session key the server
scopes * down to that session automatically. In multi-session mode, calling a method
without a session throws — there is no default.
Events
| Event | Payload | When |
| --- | --- | --- |
| offer | Offer | An incoming call is ringing. |
| call | RawCallData | Call state changed. state is Calling, Ringing, Connecting or Active — the call.ringing event covers both the ringing and connecting engine states. |
| escalate | { session, callId, peer, summary?, intent?, offer? } | The bot handed the call to a human. |
| ended | { session, callId, peer, reason? } | The call ended or was rejected. Fired once, even though the server sends both call.ended and call.rejected. |
| recording | RecordingInfo | A recording was stored. Always after ended. |
| connectionStatus | 'connected' \| 'disconnected' \| 'reconnecting' | Events socket state. |
| error | Error | Something failed. |
Offer: ended(reason?), acceptedElsewhere, rejectedElsewhere.
Call: connectionStatus, ended.
PcmCall: audio(Uint8Array), ended, error.
Types
Everything is exported from the package root:
import type {
WahaCallsOptions, CallsConfig, ChannelConfig, RelayConfig, RecordingConfig,
CallMode, CallStatus, CallDirection, CallPeer, CallStats,
CallRecord, RecordingInfo, ListCallsQuery, RawCallData,
WahaCallsEvents, OfferEvents, CallEvents, PcmCallEvents, Unsubscribe,
} from 'waha-calls';CallPeer is { phone, lid?, displayName? } — phone is empty when WhatsApp addressed
the call by LID, so read lid in that case.
Zero runtime dependencies. Full contract: docs/estudo-sdk-waha-calls.md in the
waha-gows-plus monorepo.
