> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hubtalk.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Calls from your website: Web SDK

> `POST /v1/calls/web`, the `@hubtalk-ai/web-sdk` browser SDK and the ready-made widget: a conversation with the agent right on your website.

# Calls from your website: Web SDK

A visitor to your website presses a button and talks to the agent from the browser — over the microphone, with no phone line. This is what the `POST /v1/calls/web` endpoint and the [`@hubtalk-ai/web-sdk`](https://www.npmjs.com/package/@hubtalk-ai/web-sdk) browser SDK are for; the SDK also ships a ready-made widget: a button in the corner of the page and a call panel.

If someone just needs to talk to the agent and nothing has to be embedded, a [demo link](https://docs.hubtalk.ai/v4/platform/demo-links.md) is enough. The Web SDK is for when the call starts on your website, on your domain, with variables your system knows.

## How it works

1. The visitor presses the call button on your page.
2. The page asks **your server** to start a call. The server calls `POST /v1/calls/web` with the organization's [API key](https://docs.hubtalk.ai/v4/web-api/start.md) and gets a session: `access_token` and `url`.
3. The server hands the session to the page, and the page passes it to the SDK. From there the conversation runs directly between the browser and the platform, and the call state reaches the page as events.

> [!WARNING]
>
> **The API key never reaches the browser.** Only your server knows it. The page gets a one-time session for one call — it lets the browser into this conversation and nothing else.

## What you need first

* **The agent is published.** The published version takes the call; a draft does not connect. A web call needs no telephony binding.
* **An API key is issued** — the **API keys** section, see [Access key](https://docs.hubtalk.ai/v4/web-api/start.md). The key stays on your server.
* **The page is served over HTTPS.** Without a secure connection the browser does not grant the microphone. `localhost` during development is the exception.

## `POST /v1/calls/web`

Creates a web call and issues a session for the browser. Your server makes the request, with the `Authorization: Bearer <API key>` header.

| Field | Type | Required | Default | Description |
| - | - | - | - | - |
| `agent_id` | string | yes | — | The agent name. Must be **published**. |
| `dynamic_variables` | object | no | `{}` | Scenario variables — the same `{{var}}` as in nodes: client name, order number. |
| `metadata` | object | no | `{}` | Your opaque payload for matching. Returned unchanged in the call object and in every [webhook](https://docs.hubtalk.ai/v4/web-api/webhooks.md). |
| `avatar` | boolean | no | `false` | Ask for a live avatar on this call, see [Live avatar](#live-avatar). Only `true` or `false`: a string or a number is `422`. |
| `avatar_quality` | string | no | agent setting | Avatar video quality: `low`, `medium`, `high`, `very_high`. An unknown value does not break the call: the platform skips it and uses the agent's quality setting. |

```bash theme={null}
curl -X POST "$BASE_URL/v1/calls/web" \
  -H "Authorization: Bearer $HUBTALK_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: 6f1c2a90-site-call-1" \
  -d '{
    "agent_id": "clinic_booking",
    "dynamic_variables": {"client_name": "Emily"},
    "metadata": {"lead_id": "L-1042"}
  }'
```

**Response — `201 Created`**: the [call object](https://docs.hubtalk.ai/v4/web-api/calls.md#the-call-object) plus three session fields.

| Field | Description |
| - | - |
| `access_token` | The token for the browser. Lives **2 hours** and is never refreshed. |
| `url` | The address the browser connects to. |
| `room` | The call room; equal to `call_id`. |
| `call_id` | The call id, `web-<uuid>`. Read the call with `GET /v1/calls/{call_id}` and find it in webhooks by this id. |

You can hand the whole response to the page and pass it to the SDK as is: the SDK ignores extra fields.

**Errors**

| Status | `error.code` | Condition |
| - | - | - |
| 404 | `agent_not_found` | no agent with this name in your organization |
| 409 | `agent_not_published` | the agent has no published version |
| 422 | `invalid_request` | the body fails schema validation; field details are in `message` |
| 429 | `org_concurrency_limit` | the organization's concurrent call limit is reached |
| 503 | `agent_dispatch_failed` | the platform has nowhere to connect the agent right now — retry later |

Key and rate limit errors common to all endpoints are in [Errors](https://docs.hubtalk.ai/v4/web-api/errors.md).

**Retries.** The `Idempotency-Key` header protects against a double call on retries: a repeat with the same key within 24 hours returns the same session, and no second call is made. One retry key per call: the next visitor needs a new one.

**One session per call.** The token lives 2 hours and is never refreshed, so issue a new session for every call rather than holding one on an open page.

### The call in History and webhooks

A web call shows up in [History](https://docs.hubtalk.ai/v4/platform/campaign-history) right away as an active conversation on the **Web call** channel (`channel: "web"`, `direction: "web"`). Transcript, recording, post-call analysis and [webhooks](https://docs.hubtalk.ai/v4/web-api/webhooks.md) work as for a phone call. In the scenario, `{{direction}}` equals `web` — the agent can use it to talk to a website visitor differently than on the phone.

The lifecycle is shorter than a phone call's: `queued` → `ongoing` → `ended`, with no `ringing` and no `failed`. Number and trunk fields of a web call are empty, `answered_at` is `null`.

## Installing the SDK

```bash theme={null}
npm install @hubtalk-ai/web-sdk
```

```ts theme={null}
import { VoiceClient } from '@hubtalk-ai/web-sdk';
```

**Without a bundler.** The package's `dist` folder holds ready-made files for a plain `<script>` tag: `voice-client.bundle.js` — the client, `widget.bundle.js` and `widget.css` — the [widget](#the-ready-made-widget). Host them on your own server:

```html theme={null}
<script src="/sdk/voice-client.bundle.js"></script>
<script>
  const client = new VoiceClient();
</script>
```

No third-party CDN is needed: everything the SDK requires is inside these files.

## Your first call

On the server, an endpoint that calls `POST /v1/calls/web` and returns the response to the page. An example in Node.js (Express):

```js theme={null}
app.post('/api/start-voice-call', async (req, res) => {
  const r = await fetch(`${process.env.HUBTALK_BASE_URL}/v1/calls/web`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${process.env.HUBTALK_API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      agent_id: 'clinic_booking',
      dynamic_variables: { client_name: req.user?.name ?? '' },
    }),
  });
  res.status(r.status).json(await r.json());
});
```

The server sets the call variables. If a value comes from the page, accept only the fields you expect yourself — that way a visitor cannot slip foreign data into the scenario.

On the page:

```ts theme={null}
const client = new VoiceClient();

startButton.addEventListener('click', async () => {
  const session = await fetch('/api/start-voice-call', { method: 'POST' }).then((r) => r.json());
  await client.startCall(session);
});

client.on('transcript', ({ role, text, final, id }) => renderBubble(id, role, text, final));
client.on('callEnded', ({ reason }) => console.log('call ended:', reason));

endButton.addEventListener('click', () => client.stopCall());
```

> [!NOTE]
>
> **Call `startCall` inside a click handler.** The browser allows the agent's audio and the microphone only after a user action. On iPhone Safari a network request between the click and `startCall()` can use up that action — in that case fetch the session ahead of time, for example when the call panel opens.

## VoiceClient

### Options

`new VoiceClient(options?)` — every option is optional.

| Option | Default | Description |
| - | - | - |
| `audioContainer` | a hidden `<div>` the SDK creates | Where the SDK puts the `<audio>` elements with the agent's voice. |
| `logger` | `console` | Your own log sink `{ error, debug }`. Tokens are masked in logs either way. |
| `logLevel` | `'error'` | `'silent'`, `'error'` or `'debug'`. |
| `connectTimeoutMs` | 15 seconds | How long to wait for the connection. |

### Methods

| Method | What it does |
| - | - |
| `startCall(session, options?)` | Connects and turns on the microphone. Takes the `POST /v1/calls/web` response as is, or `{ accessToken, url }`. A second call during a call fails with `ALREADY_IN_CALL`. `{ audio: false }` — a [text-only call](#text-only-calls). |
| `stopCall()` | Ends the call. With no call, does nothing and raises no error. |
| `sendText(text)` | Sends the visitor's text to the agent: the agent interrupts its speech and answers it as it would answer speech. Outside a call — `NOT_IN_CALL`; text over 1000 characters is truncated. The message is not added to the chat by itself — it comes back as a `transcript` event with `role: 'user'`. |
| `setMicrophoneEnabled(enabled)` | Turns the microphone off and on during a voice call; the call goes on. `isMicrophoneEnabled()` returns the current state. |
| `resumeAudio()` | Turns the agent's audio back on when the browser blocked it (the `audioPlaybackBlocked` event). Call it from an Enable sound button. |
| `getState()` | Connection state: `idle`, `connecting`, `connected`, `reconnecting`, `disconnected`, `error`. |
| `getAgentState()` | What the agent is doing: `unknown`, `initializing`, `listening`, `thinking`, `speaking`. |
| `getCallId()` | The call's `call_id` — the same one `GET /v1/calls/{call_id}` takes; `null` before connecting. |
| `on` / `off` / `once` | Subscribe to an event, unsubscribe, subscribe once. |
| `destroy()` | Ends the call and releases everything; the client is not usable afterwards. |

### Events

| Event | Payload |
| - | - |
| `callStarted` | `{ callId }` |
| `callEnded` | `{ callId, reason }`. `reason`: `local` — you ended it (`stopCall`), `remote` — the agent ended it, `connection_lost` — the connection dropped, `error` — a failure. |
| `connectionStateChanged` | `{ state, previous }` |
| `agentStateChanged` | `{ state, previous }` |
| `agentSpeakingStarted` / `agentSpeakingStopped` | `{}` |
| `transcript` | `{ role, text, final, id }` — a line of the conversation, `role`: `user` or `agent`. While `final: false` the line is still growing: render one bubble per `id` and update it. |
| `microphoneStateChanged` | `{ enabled }` — the microphone is on or off. |
| `audioPlaybackBlocked` | `{}` — the browser blocked the agent's audio. The call goes on; show a button that calls `resumeAudio()`. |
| `error` | `VoiceError` — see below. |

### Text-only calls

`startCall(session, { audio: false })` starts the same call with no microphone and no sound: the browser asks for no permissions, and the conversation runs in text through `sendText()` and `transcript` events. This is the mode for a visitor who cannot or does not want to speak aloud. The agent's replies arrive at speaking pace.

### SDK errors

Every failure is a `VoiceError` object: `{ code, message, state, cause? }`. Decide by `code`; `message` is a line for logs, and the visitor-facing text is yours.

| Code | When |
| - | - |
| `INVALID_PARAMS` | the session has no `access_token` or `url` |
| `WEBRTC_UNSUPPORTED` | the browser does not support calls, or the page is not on HTTPS |
| `MICROPHONE_PERMISSION_DENIED` | the visitor denied the microphone |
| `MICROPHONE_UNAVAILABLE` | there is no microphone, or it is busy |
| `AUDIO_PLAYBACK_BLOCKED` | the browser blocked the audio again after `resumeAudio()` |
| `TOKEN_EXPIRED` | the session expired before the call started |
| `TOKEN_INVALID` | the platform rejected the session token |
| `CONNECTION_FAILED` | could not connect |
| `CONNECTION_LOST` | the connection dropped and did not come back |
| `ALREADY_IN_CALL` | a call is already running |
| `NOT_IN_CALL` | an action outside a call: `sendText`, a microphone toggle |
| `SERVER_ERROR` | any other failure |

## The ready-made widget

If you do not need your own layout, the package has a widget: a button in the corner of the page and a call panel with the agent's state, a timer, microphone and end buttons, a chat and the transcript after the call. Widget texts are in English or Russian.

```ts theme={null}
import { mountWidget } from '@hubtalk-ai/web-sdk/widget';
import '@hubtalk-ai/web-sdk/widget.css';

const widget = mountWidget({
  container: document.getElementById('support'),
  locale: 'en',
  async createSession() {
    const r = await fetch('/api/start-voice-call', { method: 'POST' });
    if (!r.ok) throw new Error('Session unavailable');
    return r.json(); // { access_token, url, … } — never the API key
  },
});

// when leaving the page or removing the component
widget.destroy();
```

Without a bundler — the same files from `dist`:

```html theme={null}
<link rel="stylesheet" href="/sdk/widget.css">
<div id="support"></div>
<script src="/sdk/widget.bundle.js"></script>
<script>
  HubTalkWidget.mountWidget({
    container: document.getElementById('support'),
    createSession: async () => {
      const r = await fetch('/api/start-voice-call', { method: 'POST' });
      if (!r.ok) throw new Error('Session unavailable');
      return r.json();
    },
  });
</script>
```

| Option | Default | Description |
| - | - | - |
| `container` | required | The page element the widget lives in. |
| `createSession` | required | A function that asks your server to start a call and returns the `POST /v1/calls/web` response. The widget calls it when the visitor presses **Start conversation**. |
| `locale` | `'en'` | Language of the widget texts: `'en'` or `'ru'`. |
| `mode` | `'standard'` | `'standard'` — the call and chat panel; `'avatar'` — the panel with the [live avatar](#live-avatar) card. |
| `screenAdaptation` | `{ mode: 'height' }` | How the open panel sits on the screen. `'height'` — a corner panel half the screen tall. `'full-height'` — a panel from the site header down to the bottom of the screen; the widget finds the header itself, or pass its selector in `headerSelector`. On phones the panel fills the screen in either mode. |
| `renderCallDetails` | none | A function that draws your own form in the panel once — for example, a choice of request topic. `createSession` reads the form values itself. The widget hides the form during the call. |
| `avatar` | none | Avatar card settings for `'avatar'` mode, see below. |

The widget styles come in a separate `widget.css` file and apply only inside the widget — they do not change the look of your page.

### Live avatar

In `'avatar'` mode the panel shows **live video of an AI avatar**: a face that speaks with the agent's voice, in sync with the speech. The video travels over the same connection as the audio.

* **Platform support turns the avatar on for the agent** and sets which face appears in the call. Write to support naming the agent that needs the avatar, and ask which face was chosen.
* **Your server asks for the avatar** with `"avatar": true` in `POST /v1/calls/web`. The widget tells you when: `createSession` receives `{ avatar, avatarQuality }`, and `avatar` is `true` in `'avatar'` mode. This is a request, not a guarantee: if the agent has no avatar turned on, the call is audio-only, and the API response does not change.
* **The placeholder is yours.** While there is no video — before the call, in the first seconds, when the video drops — the stage shows your image `avatar.posterUrl` or a pair of silent clips. Pick a placeholder that looks like the avatar's face, or the switch will be noticeable.

```ts theme={null}
mountWidget({
  container: document.getElementById('support'),
  mode: 'avatar',
  async createSession({ avatar, avatarQuality }) {
    const r = await fetch('/api/start-voice-call', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ avatar, avatar_quality: avatarQuality }),
    });
    if (!r.ok) throw new Error('Session unavailable');
    return r.json();
  },
  avatar: {
    name: 'Alina',
    subtitle: 'Clinic assistant',
    posterUrl: '/presenter/poster.jpg',
    liveCaptions: true,
  },
});
```

| `avatar` option | Default | Description |
| - | - | - |
| `posterUrl` | required | The placeholder image, from your server. |
| `listeningVideoUrl`, `speakingVideoUrl` | none | Silent "listening" and "speaking" placeholder clips — both or neither. Without them the image stays. |
| `name`, `subtitle` | "AI assistant", none | Name and caption in the panel header. |
| `quality` | agent setting | `low`, `medium`, `high`, `very_high`. Passed to `createSession` as `avatarQuality` — forward it as `avatar_quality`. |
| `liveCaptions` | `false` | The agent's last replies as captions under the video. |

While the video plays, an **AI avatar** label shows on it. If your jurisdiction requires telling visitors they are talking to AI, that stays on your side: the label helps but does not replace such a notice.

Without the widget, the same video is available in `VoiceClient`: the `agentVideoChanged` event (`{ available }`) says whether video is there, and `attachAgentVideo(element)` puts it into your `<video>`.

## Page requirements

* **HTTPS.** Without a secure connection the browser does not grant the microphone, and `startCall` fails with `WEBRTC_UNSUPPORTED`.
* **Content Security Policy.** If your site has a CSP, allow: the host the SDK files load from — in `script-src` and `style-src`; your server and the address from the session's `url` field (HTTPS and WSS) — in `connect-src`; `blob:` — in `media-src`. For the avatar: the placeholder image host — in `img-src`, the clip host — in `media-src`; with clips also `style-src-attr 'unsafe-inline'`.
* **Browsers.** WebRTC support is required — every modern desktop and mobile browser has it.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.