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

# WebSocket Message Types and Schemas

> Complete reference for all WebSocket message types, schemas, and their JSON structures.

Reference for all WebSocket message types. Use this when building integrations to understand the exact JSON format for every message you send and receive.

**What you'll learn:** Base message structure, client-to-server messages, server-to-client messages, and event payloads.

<Note>
  **Testing requires a valid API key.** All examples in this section require authentication with either a web integration token or API key for Dasha BlackBox.
</Note>

<Accordion title="Base message structure">
  All WebSocket messages share these common fields:

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "messageType",
    "timestamp": "2025-01-20T10:00:00Z",
    "channelId": null
  }
  ```
</Accordion>

| Field       | Type                | Required | Description                             |
| ----------- | ------------------- | -------- | --------------------------------------- |
| `type`      | `string`            | Yes      | Message type identifier                 |
| `timestamp` | `string` (ISO 8601) | Yes      | Message timestamp                       |
| `channelId` | `string \| null`    | No       | Optional channel identifier for routing |

## Client to server messages

Messages you send to the Dasha BlackBox server.

<Accordion title="initialize">
  Start a new conversation with an agent. Send immediately after WebSocket connection opens.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "initialize",
    "timestamp": "2025-01-20T10:00:00Z",
    "request": {
      "callType": "chat",
      "additionalData": {
        "userId": "user-123",
        "context": "support"
      }
    }
  }
  ```
</Accordion>

#### WebCallStartMessage schema

| Field                    | Type                               | Required | Description                              |
| ------------------------ | ---------------------------------- | -------- | ---------------------------------------- |
| `type`                   | `"initialize"`                     | Yes      | Message type                             |
| `timestamp`              | `string` (ISO 8601)                | Yes      | Message timestamp                        |
| `channelId`              | `string \| null`                   | No       | Channel identifier                       |
| `request`                | `object`                           | Yes\*    | Call configuration (production endpoint) |
| `request.callType`       | `"chat" \| "webCall" \| "onPhone"` | Yes      | Type of conversation                     |
| `request.additionalData` | `object`                           | No       | Custom data passed to agent prompts      |
| `request.endpoint`       | `string \| null`                   | No       | Phone number for `onPhone` calls         |
| `devRequest`             | `object`                           | Yes\*    | Call configuration (dev endpoint)        |

\*Either `request` (production) or `devRequest` (development) is required, depending on which endpoint you're using.

***

<Accordion title="incomingChatMessage">
  Send a text message to the agent during chat conversations.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "incomingChatMessage",
    "content": "Hello, I need help with my order",
    "timestamp": "2025-01-20T10:01:00Z"
  }
  ```
</Accordion>

#### IncomingChatMessage schema

| Field       | Type                    | Required | Description          |
| ----------- | ----------------------- | -------- | -------------------- |
| `type`      | `"incomingChatMessage"` | Yes      | Message type         |
| `content`   | `string`                | Yes      | Text message content |
| `timestamp` | `string` (ISO 8601)     | Yes      | Message timestamp    |
| `channelId` | `string \| null`        | No       | Channel identifier   |

***

<Accordion title="sdpAnswer">
  Respond to WebRTC SDP offer for voice calls. Send in response to `sdpInvite` message.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "sdpAnswer",
    "timestamp": "2025-01-20T10:00:02Z",
    "data": {
      "sdpAnswer": "v=0\r\no=- 1234567890 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE audio\r\n..."
    }
  }
  ```
</Accordion>

#### SdpAnswerMessage schema

| Field            | Type                | Required | Description              |
| ---------------- | ------------------- | -------- | ------------------------ |
| `type`           | `"sdpAnswer"`       | Yes      | Message type             |
| `timestamp`      | `string` (ISO 8601) | Yes      | Message timestamp        |
| `channelId`      | `string \| null`    | No       | Channel identifier       |
| `data.sdpAnswer` | `string`            | Yes      | WebRTC SDP answer string |

***

<Accordion title="websocketToolResponse">
  Return the result of a tool execution requested via WebSocket. Send in response to `websocketToolRequest` message.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "websocketToolResponse",
    "timestamp": "2025-01-20T10:00:05Z",
    "content": {
      "id": "tool-request-abc123",
      "result": {
        "status": "success",
        "customer": {
          "id": "cust-456",
          "name": "John Smith",
          "email": "john@example.com"
        }
      }
    }
  }
  ```
</Accordion>

#### WebsocketToolResponseMessage schema

| Field            | Type                      | Required | Description                            |
| ---------------- | ------------------------- | -------- | -------------------------------------- |
| `type`           | `"websocketToolResponse"` | Yes      | Message type                           |
| `timestamp`      | `string` (ISO 8601)       | Yes      | Message timestamp                      |
| `channelId`      | `string \| null`          | No       | Channel identifier                     |
| `content.id`     | `string`                  | Yes      | Request ID from `websocketToolRequest` |
| `content.result` | `unknown`                 | Yes      | Tool execution result (any JSON value) |

***

<Accordion title="terminate">
  End the conversation gracefully. Wait for `conversationResult` before closing the WebSocket.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "terminate",
    "timestamp": "2025-01-20T10:05:00Z"
  }
  ```
</Accordion>

#### TerminateMessage schema

| Field       | Type                | Required | Description        |
| ----------- | ------------------- | -------- | ------------------ |
| `type`      | `"terminate"`       | Yes      | Message type       |
| `timestamp` | `string` (ISO 8601) | Yes      | Message timestamp  |
| `channelId` | `string \| null`    | No       | Channel identifier |

***

## Server to client messages

Messages you receive from the Dasha BlackBox server.

<Accordion title="event">
  System events indicating connection state and lifecycle changes.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "event",
    "name": "connection",
    "timestamp": "2025-01-20T10:00:01Z",
    "data": {
      "recordId": "call-abc123",
      "endpoint": null
    }
  }
  ```
</Accordion>

#### EventHistoryMessage schema

| Field                                  | Type                | Description                          |
| -------------------------------------- | ------------------- | ------------------------------------ |
| `type`                                 | `"event"`           | Message type                         |
| `name`                                 | `string`            | Event name (see below)               |
| `timestamp`                            | `string` (ISO 8601) | Event timestamp                      |
| `channelId`                            | `string \| null`    | Channel identifier                   |
| `data.recordId`                        | `string \| null`    | Call record ID                       |
| `data.endpoint`                        | `string \| null`    | Phone endpoint (for `onPhone` calls) |
| `data.startEstablishConnectionTimeISO` | `string \| null`    | Connection start time                |
| `data.endEstablishConnectionTimeISO`   | `string \| null`    | Connection established time          |

#### Event names

| Event        | Description                 | When Triggered                          |
| ------------ | --------------------------- | --------------------------------------- |
| `connection` | Agent session ready         | After `initialize` is processed         |
| `opened`     | Conversation started        | Voice call connected or chat opened     |
| `closed`     | Conversation ended          | After `terminate` or natural completion |
| `failedOpen` | Failed to open conversation | Agent unavailable, auth failed, etc.    |

***

### text

Text messages from agent or user speech transcription.

<Accordion title="Agent response">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "text",
    "timestamp": "2025-01-20T10:01:05Z",
    "content": {
      "source": "assistant",
      "text": "Hello! I'd be happy to help you with your order. Could you provide your order number?",
      "name": null,
      "synthStartISOTimes": "2025-01-20T10:01:03Z",
      "synthEndISOTimes": "2025-01-20T10:01:04Z",
      "playStartISOTimes": "2025-01-20T10:01:04Z",
      "playEndISOTimes": "2025-01-20T10:01:08Z"
    }
  }
  ```
</Accordion>

<Accordion title="User message (echo/transcription)">
  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "text",
    "timestamp": "2025-01-20T10:01:00Z",
    "content": {
      "source": "user",
      "text": "Hello, I need help with my order",
      "name": null,
      "type": "final",
      "segmentId": "seg-abc123",
      "startISOTimes": "2025-01-20T10:00:58Z",
      "endISOTimes": "2025-01-20T10:01:00Z"
    }
  }
  ```
</Accordion>

#### TextHistoryMessage schema

| Field            | Type                    | Description            |
| ---------------- | ----------------------- | ---------------------- |
| `type`           | `"text"`                | Message type           |
| `timestamp`      | `string` (ISO 8601)     | Message timestamp      |
| `channelId`      | `string \| null`        | Channel identifier     |
| `content.source` | `"assistant" \| "user"` | Message sender         |
| `content.text`   | `string \| null`        | Message text content   |
| `content.name`   | `string \| null`        | Sender name (optional) |

**Additional fields for assistant messages:**

| Field                        | Type             | Description               |
| ---------------------------- | ---------------- | ------------------------- |
| `content.synthStartISOTimes` | `string \| null` | TTS synthesis start time  |
| `content.synthEndISOTimes`   | `string \| null` | TTS synthesis end time    |
| `content.playStartISOTimes`  | `string \| null` | Audio playback start time |
| `content.playEndISOTimes`    | `string \| null` | Audio playback end time   |

**Additional fields for user messages:**

| Field                   | Type                                    | Description               |
| ----------------------- | --------------------------------------- | ------------------------- |
| `content.type`          | `"potential" \| "confident" \| "final"` | Recognition confidence    |
| `content.segmentId`     | `string`                                | Speech segment identifier |
| `content.startISOTimes` | `string`                                | Speech start time         |
| `content.endISOTimes`   | `string \| null`                        | Speech end time           |

#### Recognition types

| Type        | Description                      | Use Case                      |
| ----------- | -------------------------------- | ----------------------------- |
| `potential` | Low confidence interim result    | Show real-time transcription  |
| `confident` | Medium confidence interim result | Update transcription display  |
| `final`     | Final confirmed transcription    | Store in conversation history |

***

<Accordion title="sdpInvite">
  WebRTC SDP offer for voice call setup. Respond with `sdpAnswer`.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "sdpInvite",
    "timestamp": "2025-01-20T10:00:02Z",
    "data": {
      "sdpOffer": "v=0\r\no=- 1234567890 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE audio\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\n..."
    }
  }
  ```
</Accordion>

#### SdpInviteMessage schema

| Field           | Type                | Description             |
| --------------- | ------------------- | ----------------------- |
| `type`          | `"sdpInvite"`       | Message type            |
| `timestamp`     | `string` (ISO 8601) | Message timestamp       |
| `channelId`     | `string \| null`    | Channel identifier      |
| `data.sdpOffer` | `string`            | WebRTC SDP offer string |

***

<Accordion title="toolCall">
  Notification that the agent is calling a tool/function.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "toolCall",
    "timestamp": "2025-01-20T10:02:00Z",
    "name": "lookupOrder",
    "args": {
      "orderId": "ORD-12345"
    },
    "callId": "tc-abc123",
    "startISOTimes": "2025-01-20T10:02:00Z"
  }
  ```
</Accordion>

#### ToolCallHistoryMessage schema

| Field           | Type                | Description            |
| --------------- | ------------------- | ---------------------- |
| `type`          | `"toolCall"`        | Message type           |
| `timestamp`     | `string` (ISO 8601) | Message timestamp      |
| `channelId`     | `string \| null`    | Channel identifier     |
| `name`          | `string`            | Tool name              |
| `args`          | `object`            | Tool arguments         |
| `callId`        | `string`            | Unique call identifier |
| `startISOTimes` | `string` (ISO 8601) | Tool call start time   |

***

<Accordion title="toolCallResult">
  Result of a tool execution.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "toolCallResult",
    "timestamp": "2025-01-20T10:02:03Z",
    "name": "lookupOrder",
    "callId": "tc-abc123",
    "startISOTimes": "2025-01-20T10:02:00Z",
    "endISOTimes": "2025-01-20T10:02:03Z",
    "result": {
      "orderId": "ORD-12345",
      "status": "shipped",
      "trackingNumber": "1Z999AA10123456784",
      "estimatedDelivery": "2025-01-22"
    }
  }
  ```
</Accordion>

#### ToolCallResultHistoryMessage schema

| Field           | Type                | Description                                 |
| --------------- | ------------------- | ------------------------------------------- |
| `type`          | `"toolCallResult"`  | Message type                                |
| `timestamp`     | `string` (ISO 8601) | Message timestamp                           |
| `channelId`     | `string \| null`    | Channel identifier                          |
| `name`          | `string`            | Tool name                                   |
| `callId`        | `string`            | Unique call identifier (matches `toolCall`) |
| `startISOTimes` | `string` (ISO 8601) | Tool call start time                        |
| `endISOTimes`   | `string` (ISO 8601) | Tool call end time                          |
| `result`        | `unknown`           | Tool execution result                       |

***

<Accordion title="websocketToolRequest">
  Request to execute a tool via WebSocket (for tools configured with WebSocket execution). Respond with `websocketToolResponse`.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "websocketToolRequest",
    "timestamp": "2025-01-20T10:02:00Z",
    "channelId": null,
    "content": {
      "id": "wtr-abc123",
      "toolName": "updateCart",
      "args": {
        "action": "add",
        "productId": "PROD-789",
        "quantity": 2
      }
    }
  }
  ```
</Accordion>

#### WebsocketToolRequestHistoryMessage schema

| Field              | Type                     | Description                  |
| ------------------ | ------------------------ | ---------------------------- |
| `type`             | `"websocketToolRequest"` | Message type                 |
| `timestamp`        | `string` (ISO 8601)      | Message timestamp            |
| `channelId`        | `string \| null`         | Channel identifier           |
| `content.id`       | `string`                 | Request ID (use in response) |
| `content.toolName` | `string`                 | Tool name to execute         |
| `content.args`     | `unknown`                | Tool arguments               |

***

<Accordion title="conversationResult">
  Final conversation summary and metadata. Sent after `terminate` or when conversation ends.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "conversationResult",
    "timestamp": "2025-01-20T10:05:00Z",
    "result": {
      "status": "completed",
      "duration": 240,
      "callId": "call-abc123",
      "agentId": "agent-xyz789",
      "transcript": [
        {"role": "user", "content": "Hello, I need help with my order"},
        {"role": "assistant", "content": "Hello! I'd be happy to help you with your order..."}
      ],
      "metadata": {
        "resolvedIssue": true,
        "sentiment": "positive"
      }
    }
  }
  ```
</Accordion>

#### ConversationResultHistoryMessage schema

| Field       | Type                   | Description                 |
| ----------- | ---------------------- | --------------------------- |
| `type`      | `"conversationResult"` | Message type                |
| `timestamp` | `string` (ISO 8601)    | Message timestamp           |
| `channelId` | `string \| null`       | Channel identifier          |
| `result`    | `object`               | Conversation result payload |

The `result` object structure depends on your agent configuration.

***

<Accordion title="error">
  Error notification from the server.

  ```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
  {
    "type": "error",
    "timestamp": "2025-01-20T10:00:00Z",
    "channelId": null,
    "data": {
      "message": "Invalid token"
    }
  }
  ```
</Accordion>

#### ErrorHistoryMessage schema

| Field          | Type                | Description        |
| -------------- | ------------------- | ------------------ |
| `type`         | `"error"`           | Message type       |
| `timestamp`    | `string` (ISO 8601) | Message timestamp  |
| `channelId`    | `string \| null`    | Channel identifier |
| `data.message` | `string`            | Error message      |

#### Common error messages

| Error                    | Cause                   | Resolution                          |
| ------------------------ | ----------------------- | ----------------------------------- |
| `Invalid token`          | Authentication failed   | Check token validity in dashboard   |
| `Token expired`          | Token has expired       | Generate new token                  |
| `Agent not found`        | Invalid agent reference | Verify agent ID                     |
| `Rate limit exceeded`    | Too many requests       | Implement backoff, reduce frequency |
| `Connection timeout`     | Session timed out       | Reconnect with new session          |
| `Invalid message format` | Malformed JSON          | Validate message structure          |

***

## Message flow diagrams

<Accordion title="Chat conversation">
  ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
  sequenceDiagram
      participant Client
      participant Server as Dasha BlackBox Server
      participant Agent

      Client->>Server: initialize (callType: "chat")
      Server->>Client: event (name: "connection")

      Client->>Server: incomingChatMessage
      Server->>Client: text (source: "user", echo)
      Agent->>Server: Generate response
      Server->>Client: text (source: "assistant")

      Client->>Server: terminate
      Server->>Client: conversationResult
      Server->>Client: event (name: "closed")
  ```
</Accordion>

<Accordion title="Voice call">
  ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
  sequenceDiagram
      participant Client
      participant Server as Dasha BlackBox Server
      participant Agent

      Client->>Server: initialize (callType: "webCall")
      Server->>Client: event (name: "connection")
      Server->>Client: sdpInvite
      Client->>Server: sdpAnswer
      Server->>Client: event (name: "opened")

      Note over Client,Agent: WebRTC audio streaming

      Server->>Client: text (source: "user", transcription)
      Server->>Client: text (source: "assistant", response)

      Client->>Server: terminate
      Server->>Client: conversationResult
      Server->>Client: event (name: "closed")
  ```
</Accordion>

<Accordion title="Tool execution via WebSocket">
  ```mermaid theme={"theme":{"light":"github-light","dark":"github-dark"}}
  sequenceDiagram
      participant Client
      participant Server as Dasha BlackBox Server
      participant Agent

      Client->>Server: incomingChatMessage
      Server->>Client: text (source: "user", echo)

      Agent->>Server: Decide to call tool
      Server->>Client: toolCall (notification)
      Server->>Client: websocketToolRequest

      Client->>Client: Execute tool
      Client->>Server: websocketToolResponse

      Server->>Client: toolCallResult
      Agent->>Server: Generate response with result
      Server->>Client: text (source: "assistant")
  ```
</Accordion>

<Accordion title="TypeScript types">
  Use these types for type-safe message handling:

  ```typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Base message structure
  interface BaseMessage {
    type: string;
    timestamp: string;
    channelId?: string | null;
  }

  // Client to server messages
  interface InitializeMessage extends BaseMessage {
    type: 'initialize';
    request?: {
      callType: 'chat' | 'webCall' | 'onPhone';
      additionalData?: Record<string, unknown>;
      endpoint?: string | null;
    };
  }

  interface IncomingChatMessage extends BaseMessage {
    type: 'incomingChatMessage';
    content: string;
  }

  interface SdpAnswerMessage extends BaseMessage {
    type: 'sdpAnswer';
    data: { sdpAnswer: string };
  }

  interface WebsocketToolResponseMessage extends BaseMessage {
    type: 'websocketToolResponse';
    content: {
      id: string;
      result: unknown;
    };
  }

  interface TerminateMessage extends BaseMessage {
    type: 'terminate';
  }

  type ClientMessage =
    | InitializeMessage
    | IncomingChatMessage
    | SdpAnswerMessage
    | WebsocketToolResponseMessage
    | TerminateMessage;

  // Server to client messages
  interface EventMessage extends BaseMessage {
    type: 'event';
    name: 'connection' | 'opened' | 'closed' | 'failedOpen';
    data?: {
      recordId?: string | null;
      endpoint?: string | null;
    };
  }

  interface TextMessage extends BaseMessage {
    type: 'text';
    content: {
      source: 'assistant' | 'user';
      text: string | null;
      name?: string | null;
      type?: 'potential' | 'confident' | 'final';
      segmentId?: string;
    };
  }

  interface SdpInviteMessage extends BaseMessage {
    type: 'sdpInvite';
    data: { sdpOffer: string };
  }

  interface ToolCallMessage extends BaseMessage {
    type: 'toolCall';
    name: string;
    args: Record<string, unknown>;
    callId: string;
    startISOTimes: string;
  }

  interface ToolCallResultMessage extends BaseMessage {
    type: 'toolCallResult';
    name: string;
    callId: string;
    result: unknown;
    startISOTimes: string;
    endISOTimes: string;
  }

  interface WebsocketToolRequestMessage extends BaseMessage {
    type: 'websocketToolRequest';
    content: {
      id: string;
      toolName: string;
      args: unknown;
    };
  }

  interface ConversationResultMessage extends BaseMessage {
    type: 'conversationResult';
    result: Record<string, unknown>;
  }

  interface ErrorMessage extends BaseMessage {
    type: 'error';
    data: { message: string };
  }

  type ServerMessage =
    | EventMessage
    | TextMessage
    | SdpInviteMessage
    | ToolCallMessage
    | ToolCallResultMessage
    | WebsocketToolRequestMessage
    | ConversationResultMessage
    | ErrorMessage;

  // Type guard helper
  function isServerMessage(msg: unknown): msg is ServerMessage {
    return (
      typeof msg === 'object' &&
      msg !== null &&
      'type' in msg &&
      typeof (msg as { type: unknown }).type === 'string'
    );
  }
  ```
</Accordion>

## Next steps

<CardGroup cols={2}>
  <Card title="Chat Implementation" icon="comments" href="/docs/websockets/chat-implementation">
    Build a complete chat interface with these messages
  </Card>

  <Card title="Tool Execution" icon="wrench" href="/docs/websockets/tool-execution">
    Handle tool calls via WebSocket
  </Card>

  <Card title="Error Handling" icon="triangle-exclamation" href="/docs/websockets/error-handling">
    Handle errors and edge cases
  </Card>

  <Card title="Voice Implementation" icon="phone" href="/docs/websockets/voice-call-implementation">
    WebRTC voice call message flow
  </Card>
</CardGroup>
