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

# WebSocket — streaming

> Exchange text conversation turns over a persistent WebSocket connection. The only transport for text mode — there is no REST message endpoint.

## Why WebSocket?

There is no REST endpoint for sending a text message and getting a reply — the WebSocket is the
only way to exchange conversation turns in text mode. Opening one persistent, authenticated
connection avoids repeating auth and connection setup on every turn, and lets the server push
events proactively (like a session-expiry warning) without the client polling for them.

> [!NOTE]
>
> This is a persistent connection, not token-by-token streaming. Each turn gets exactly one
> `response` frame containing the AI's complete reply — there is no `chunk` frame or partial-text
> event. If you want a "typing" or token-reveal effect in your UI, animate the complete response
> client-side (see [Building a streaming UI](https://humain.mintlify.site/web/streaming-ui.md)) rather than expecting the server
> to send partial tokens.

## Wire protocol

The WebSocket endpoint is `GET {agent_url}/v1/sessions/{sid}/ws` — served on the `agent_url`
returned by `POST /v1/sessions`, not necessarily the host you called to open the session.

### Authentication

Non-browser clients (native apps, servers, embedded devices) send the same bearer token used to
open the session, in the `Authorization` header on the upgrade request.

Browsers cannot set custom headers on a WebSocket handshake, so first mint a short-lived,
single-use ticket:

```bash theme={null}
curl -X POST https://api.humain.ai/v1/sessions/$SESSION_ID/ws-ticket \
  -H "Authorization: Bearer hk_live_your_credential_here"
# → {"ticket":"wst_...","expires_in":30}
```

Then pass it as `?ticket=` on the WS URL instead of the raw token:

```
wss://api.humain.ai/v1/sessions/{sid}/ws?ticket=wst_...
```

### Sending a message

Send one UTF-8 JSON text frame per turn:

```json theme={null}
{"type": "message", "content": "What are your opening hours?"}
```

### Receiving a response

```json theme={null}
{"type": "response", "content": "We are open Monday to Friday, 9 AM–6 PM.", "message_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6"}
```

`message_id` is a fresh UUID per response — use it to deduplicate if you retry sending logic on
your end.

### Session expiry warning

Sent once, 60 seconds (configurable) before the session's hard time limit:

```json theme={null}
{"type": "session_expiring", "message": "Your session will expire in 60 seconds."}
```

The session is not closed yet when this arrives — you can still send turns until the actual
`SESSION_ENDED` error/close.

### Frame types

**type** `string` *required*

One of `message` (client → server), `response`, `error`, or `session_expiring` (server → client).

**content** `string`

On a `message` frame, the user's text input. On a `response` frame, the AI's complete reply.

**message\_id** `string`

Present only on `response` frames. A fresh UUID per response, for client-side deduplication.

**code** `string`

Present only on `error` frames. One of `TURN_ERROR`, `SESSION_ENDED`, or `SERVICE_UNAVAILABLE`
— see [Error frames](#error-frames) below.

**message** `string`

On `error` frames, a human-readable description — for `TURN_ERROR`, this string is prefixed
with the real machine-readable reason (e.g. `"INPUT_REJECTED: Contains a blocked phrase."`).
On `session_expiring`, a display-ready warning string.

### Error frames

Errors during a turn arrive as a **JSON frame on the same open connection** — the WebSocket is
not closed with a 4xxx code the way some APIs do it.

```json theme={null}
{"type": "error", "code": "TURN_ERROR", "message": "INPUT_REJECTED: Contains a blocked phrase."}
```

`code` is one of:

| Code | Meaning |
| - | - |
| `TURN_ERROR` | Any pipeline failure — guardrail rejection, FraudGuard block, rate limit, or provider error. The real reason is the `SCREAMING_SNAKE_CASE` prefix of `message`, before the first `: `. |
| `SESSION_ENDED` | The session's time limit was reached. The connection is closed after this frame — open a new session to continue. |
| `SERVICE_UNAVAILABLE` | The server's turn pipeline is not configured (misconfiguration, not a per-request failure). |

To get the specific guardrail/FraudGuard reason out of a `TURN_ERROR`, split `message` on the
first `": "`:

```javascript theme={null}
const [reasonCode, ...rest] = frame.message.split(': ');
// reasonCode: "INPUT_REJECTED" | "RATE_LIMITED" | "CREDENTIAL_BLOCKED" | "PROVIDER_ERROR" | ...
```

## Browser integration

```javascript JavaScript (browser) theme={null}
const BASE_URL = 'https://api.humain.ai';
const token = 'hk_live_your_credential_here';

// 1. Open a session (HTTP POST) — capture agent_url
const { session_id, agent_url } = await fetch(`${BASE_URL}/v1/sessions`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ mode: 'text' }),
}).then(r => r.json());

// 2. Mint a single-use WS ticket — browsers can't set headers on the WS handshake
const { ticket } = await fetch(`${agent_url}/v1/sessions/${session_id}/ws-ticket`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${token}` },
}).then(r => r.json());

// 3. Upgrade to WebSocket, on agent_url, with the ticket
const wsUrl = agent_url.replace(/^http/, 'ws');
const ws = new WebSocket(`${wsUrl}/v1/sessions/${session_id}/ws?ticket=${ticket}`);

ws.onopen = () => {
  ws.send(JSON.stringify({ type: 'message', content: 'What are your opening hours?' }));
};

ws.onmessage = (event) => {
  const frame = JSON.parse(event.data);

  if (frame.type === 'response') {
    updateChatUI(frame.content); // Full reply — ready to display immediately
  }

  if (frame.type === 'error') {
    console.error('Turn error:', frame.code, frame.message);
    if (frame.code === 'SESSION_ENDED') {
      // Connection will close — open a new session to continue
    }
  }

  if (frame.type === 'session_expiring') {
    showWarningBanner(frame.message);
  }
};
```

```javascript Node.js (ws library) theme={null}
import WebSocket from 'ws';

const TOKEN = process.env.HUMAIN_TOKEN;
const BASE = 'https://api.humain.ai';

// 1. Open session
const { session_id, agent_url } = await fetch(`${BASE}/v1/sessions`, {
  method: 'POST',
  headers: { 'Authorization': `Bearer ${TOKEN}`, 'Content-Type': 'application/json' },
  body: JSON.stringify({ mode: 'text' }),
}).then(r => r.json());

// 2. Connect directly with the Bearer header — Node isn't limited like a browser
const wsUrl = agent_url.replace(/^http/, 'ws');
const ws = new WebSocket(`${wsUrl}/v1/sessions/${session_id}/ws`, {
  headers: { 'Authorization': `Bearer ${TOKEN}` },
});

ws.on('open', () => {
  ws.send(JSON.stringify({ type: 'message', content: process.argv[2] ?? 'Hello!' }));
});

ws.on('message', (data) => {
  const frame = JSON.parse(data.toString());
  if (frame.type === 'response') {
    console.log(frame.content);
    ws.close();
  }
  if (frame.type === 'error') {
    console.error('Error:', frame.code, frame.message);
    ws.close();
  }
});
```

## Reconnection strategy

The session is **not** ended when the connection drops — the same session can be reconnected
to (potentially served by a different agent process). WebSocket connections can drop due to
network interruptions; implement reconnection with exponential back-off:

```javascript theme={null}
class HumainStream {
  #token;
  #sessionId;
  #agentUrl;
  #ws = null;
  #reconnectDelay = 1000;
  #maxDelay = 30000;

  constructor(token, sessionId, agentUrl) {
    this.#token = token;
    this.#sessionId = sessionId;
    this.#agentUrl = agentUrl;
  }

  async connect() {
    // Browsers need a fresh ticket every time — tickets are single-use.
    const { ticket } = await fetch(
      `${this.#agentUrl}/v1/sessions/${this.#sessionId}/ws-ticket`,
      { method: 'POST', headers: { 'Authorization': `Bearer ${this.#token}` } }
    ).then(r => r.json());

    const wsUrl = this.#agentUrl.replace(/^http/, 'ws');
    this.#ws = new WebSocket(`${wsUrl}/v1/sessions/${this.#sessionId}/ws?ticket=${ticket}`);

    this.#ws.onopen = () => {
      this.#reconnectDelay = 1000; // Reset on successful connect
      this.onopen?.();
    };

    this.#ws.onmessage = (e) => {
      const frame = JSON.parse(e.data);
      if (frame.type === 'error' && frame.code === 'SESSION_ENDED') {
        this.onended?.(frame); // Don't reconnect — session is gone
        return;
      }
      this.onmessage?.(frame);
    };

    this.#ws.onclose = () => {
      // Any close other than an explicit SESSION_ENDED frame is treated as
      // a transient network drop — reconnect with back-off.
      setTimeout(() => this.connect(), this.#reconnectDelay);
      this.#reconnectDelay = Math.min(this.#reconnectDelay * 2, this.#maxDelay);
    };
  }

  send(content) {
    this.#ws?.send(JSON.stringify({ type: 'message', content }));
  }
}
```

> [!NOTE]
>
> When reconnecting mid-session, the server still has the conversation history in its own store —
> you do not need to resend previous turns. Send the next user input directly once the new
> connection is open.


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