Skip to main content

Call Control

When your voice app receives a call.received webhook, your server takes ownership of the call and controls it via the Update Call API. Actions take effect while a voice app controls the call: from its call.received webhook until the call ends or a transfer succeeds. An update sent while no voice app controls the call is accepted and has no effect.

Text
┌─────────┐ ┌───────────┐ ┌─────────────┐
│ Caller │ │ DialStack │ │ Your Server │
└────┬────┘ └─────┬─────┘ └──────┬──────┘
│ │ │
│ 1. Call arrives │ │
│────────────────────────▶│ │
│ │ │
│ │ 2. Webhook POST │
│ │─────────────────────────▶│
│ │ │
│ │ 3. POST /v1/calls/{id} │
│ │◀─────────────────────────│
│ │ (attach audio) │
│ │ │
│ 4. Bidirectional audio │ │
│◀───────────────────────▶│◀────────────────────────▶│
│ (WebSocket) │ (WebSocket) │
│ │ │

Actions​

Use the Update Call API to send actions. Actions are processed sequentially. When the last one finishes, the call stays connected, with the caller hearing silence, until you send another update.

Attach Audio Stream​

Connect bidirectional audio to your WebSocket server (see WebSocket API for the message protocol):

JavaScript
await dialstack.calls.update(
callId,
{ actions: [{ type: 'attach', url: 'wss://your-server.example.com/voice/stream' }] },
{ dialstackAccount: accountId }
);

The url must use wss://, so the call's audio is encrypted in transit. It is used exactly as given, including any query string, so you can carry a per-call token in the path or the query string.

The attach action blocks until the WebSocket disconnects, then processing continues with the next action. Processing also continues with the next action if the WebSocket can't be connected at all, for example because your server refuses it. If no action follows, the caller hears silence until you send another update.

Transfer​

Transfer the caller to an extension, an E.164 phone number, or a SIP address:

JavaScript
await dialstack.calls.update(
callId,
{ actions: [{ type: 'transfer', target: '100' }] },
{ dialstackAccount: accountId }
);

A successful transfer is final, as a blind transfer from a phone is: no later actions run, later updates have no effect, and the call keeps its call_id and its call-log entry. A transfer to a phone number or SIP address succeeds when the target answers, and the call then ends when either of them hangs up. A transfer to an extension succeeds at once: the call is handed to that extension's own routing (see Combining Actions). If the transfer fails (no answer, busy, rejected), processing continues with the next action.

Transfer to a SIP address (e.g. an AI voice agent)​

The target can also be a sip: URI, which routes the live call to an external SIP address such as an AI voice agent. Your server provides the full address — for example, after registering the call with your agent provider and receiving an identifier to dial:

JavaScript
await dialstack.calls.update(
callId,
{ actions: [{ type: 'transfer', target: 'sip:agent-7f3c@sip.example-ai.com' }] },
{ dialstackAccount: accountId }
);

This leg is not encrypted: signaling is plain SIP and the audio is connected over plain RTP. sips: URIs and ;transport=tls aren't supported. You can append ;transport=tcp or ;transport=udp to the URI to select the signaling transport. If the call's audio must be encrypted in transit, for example because it carries protected health information, stream it with attach instead.

Hang Up​

End the call:

JavaScript
await dialstack.calls.update(
callId,
{ actions: [{ type: 'hangup' }] },
{ dialstackAccount: accountId }
);

The call ends immediately, and no later actions run.

Combining Actions​

Chain actions for fallback behavior:

JSON
{
"actions": [
{ "type": "attach", "url": "wss://ai.example.com/voice" },
{ "type": "transfer", "target": "+14165550123" },
{ "type": "hangup" }
]
}

This connects to your AI voice assistant first. When the WebSocket disconnects (e.g., AI hands off), or can't be connected at all, the call transfers to +1 416 555 0123. If that transfer fails (no answer, busy, rejected), the call is hung up. If it succeeds, the caller stays with the target and the hangup doesn't run.

When the transfer target is an extension, that extension's own routing and no-answer behavior apply (for example, sending the caller to voicemail). No later actions run.

A transfer to a phone number shows the original caller by default. Set caller_id to called_number to show the number the call came in on, or to did with caller_id_did to show a specific number on the account. See Caller ID.

JSON
{
"actions": [{ "type": "transfer", "target": "+14165550123", "caller_id": "called_number" }]
}

Replacing Actions​

Sending a new update replaces all pending actions immediately. The current action is interrupted, and processing starts from the first action in the new list. After a transfer succeeds, updates have no effect.

JavaScript
// AI decides to transfer the call
await dialstack.calls.update(
callId,
{ actions: [{ type: 'transfer', target: '100' }] },
{ dialstackAccount: accountId }
);

WebSocket Audio Streaming​

When DialStack executes an attach action, it connects to your WebSocket URL and streams audio bidirectionally: μ-law at 8 kHz, in base64-encoded JSON messages. The WebSocket API reference has the audio format and every message, including the begin message that opens the session and the end message sent before DialStack closes it.

Keypad Input​

When the caller presses a key, DialStack sends a dtmf message on the same WebSocket:

JSON
{ "event": "dtmf", "timestamp": 5320, "digit": "5" }

digit is 0–9, *, #, or A–D (found only on special-purpose keypads). Each key arrives as one message once it is released, in order with the audio messages around it, and timestamp uses the same clock as theirs. Use it to collect an account number or a menu choice without leaving your voice app.

Ending the Session​

Either side can close the WebSocket to end the audio session. When it closes, DialStack continues processing with the next action. With no next action, the caller hears silence until you send another update.

Using MediaStream (SDK)​

The SDK provides a MediaStream class that parses the WebSocket messages and emits begin, audio, dtmf, close (with the close code and reason) and error events. After begin, stream.callId, stream.accountId and stream.audioFormat are set.

JavaScript
import { MediaStream } from '@dialstack/sdk-server';
import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws) => {
const stream = new MediaStream(ws);

stream.on('begin', (event) => {
console.log('Call started:', event.call_id);
console.log('Audio format:', event.audio_format);

// Send greeting audio
stream.sendAudio(greetingAudioBase64);
});

stream.on('audio', (event) => {
// event.payload contains base64-encoded μ-law audio
// event.timestamp contains the audio timestamp

// Process with your AI pipeline and respond
const responseAudio = processAudio(event.payload);
stream.sendAudio(responseAudio);

// Or send raw Buffer (auto base64-encoded)
stream.sendAudioBuffer(audioBuffer);
});

stream.on('dtmf', (event) => {
// event.digit is the key the caller pressed: 0-9, *, # or A-D
console.log('Caller pressed', event.digit);
});

stream.on('close', (code, reason) => {
console.log('Stream closed:', code, reason);
});

stream.on('error', (error) => {
console.error('Stream error:', error);
});
});

Complete Example: AI Voice Assistant​

JavaScript
import express from 'express';
import { WebSocketServer } from 'ws';
import { DialStack, MediaStream } from '@dialstack/sdk-server';

const app = express();
const dialstack = new DialStack(process.env.DIALSTACK_API_KEY);
const VOICE_APP_SECRET = process.env.VOICE_APP_SECRET;

// Webhook endpoint
app.post('/voice/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
let event;
try {
event = DialStack.webhooks.constructEvent(
req.body,
req.headers['x-dialstack-signature'],
VOICE_APP_SECRET
);
} catch (err) {
return res.sendStatus(401);
}

const { call_id, account_id, from_number, from_name } = event;
console.log(`Incoming call from ${from_name || from_number}`);

res.sendStatus(200);

// Attach audio stream with fallback transfer
await dialstack.calls.update(
call_id,
{
actions: [
{ type: 'attach', url: 'wss://your-server.example.com/voice/stream' },
{ type: 'transfer', target: '100' },
],
},
{ dialstackAccount: account_id }
);
});

// WebSocket server for audio streaming
const wss = new WebSocketServer({ noServer: true });

wss.on('connection', (ws) => {
const stream = new MediaStream(ws);

stream.on('begin', (event) => {
console.log(`Audio stream started for call ${stream.callId}`);
stream.sendAudio(generateGreetingAudio());
});

stream.on('audio', (event) => {
const audioBuffer = Buffer.from(event.payload, 'base64');
processAudioWithAI(audioBuffer, (responseAudio) => {
stream.sendAudio(responseAudio);
});
});

stream.on('close', () => {
console.log(`Audio stream ended for call ${stream.callId}`);
});
});

const server = app.listen(3000);
server.on('upgrade', (request, socket, head) => {
if (request.url === '/voice/stream') {
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit('connection', ws, request);
});
} else {
socket.destroy();
}
});

See also​

  • Voice Apps — creating a voice app, its webhooks, and dial plan nodes.
  • Listeners — stream one-way audio without taking over the call.
  • WebSocket API — the audio streaming protocol.
  • Update Call — the full list of actions.