# Understanding the CloddsBot WebSocket Gateway Protocol: A Complete Guide

> Explore the CloddsBot WebSocket Gateway protocol, a JSON-based system for real-time bot communication. Learn about authentication, session management, and dynamic message operations with this comprehensive guide.

- Repository: [AL/CloddsBot](https://github.com/alsk1992/CloddsBot)
- Tags: api-reference
- Published: 2026-09-13

---

**The CloddsBot WebSocket Gateway protocol is a lightweight, JSON-based messaging system that enables real-time bidirectional communication between clients and the bot through a single `/chat` endpoint, supporting authentication, session management, keep-alive heartbeats, and dynamic message operations.**

The **CloddsBot WebSocket Gateway protocol** powers real-time chat interactions in the `alsk1992/CloddsBot` repository. This protocol defines how the browser-based WebChat UI and external clients establish persistent connections, authenticate sessions, and exchange messages. Built around a minimal set of message types, the gateway handles everything from anonymous access to complex multi-session conversations.

## Protocol Architecture and Connection Lifecycle

The gateway exposes a single WebSocket endpoint at `/chat` that manages the entire conversation lifecycle. According to the source code in [`src/gateway/server.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/server.ts), the server expects clients to follow a strict handshake sequence before entering the main chat loop.

The connection flow follows six distinct phases:

1. **Connect** – The client opens a WebSocket connection to `ws(s)://<host>/chat`.
2. **Authenticate** – Immediately after the socket opens, the client sends an `auth` message containing a WebChat token or empty string for anonymous access.
3. **Session binding** – Once the server replies with `authenticated`, the client optionally sends a `switch` message with a specific `sessionId` to bind to an existing conversation.
4. **Keep-alive** – The client initiates a periodic `ping` every approximately 25 seconds; the server responds with `pong` to maintain the connection.
5. **Chat operations** – Users exchange messages through bidirectional `message` payloads, with the server capable of issuing `edit` or `delete` commands to modify history.
6. **Error handling** – Invalid tokens or protocol violations trigger `error` messages, prompting the client to retry authentication.

## Message Types and Payload Specifications

All messages use JSON format with a mandatory `type` field. The protocol implementation in [`public/webchat/js/ws.js`](https://github.com/alsk1992/CloddsBot/blob/main/public/webchat/js/ws.js) defines the client-side message constructors, while [`src/gateway/server.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/server.ts) handles server-side validation and routing.

### Authentication and Session Control

**`auth`** (Client → Server)
Initiates the connection with payload: `{ token, userId, _wsVersion }`. The `token` field accepts a WebChat token or empty string for anonymous sessions, while `userId` provides a temporary client identifier. The server validates credentials against the internal store defined in [`src/gateway/api-routes.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/api-routes.ts).

**`authenticated`** (Server → Client)
Empty payload `{}` confirming successful authentication. Upon receiving this, the client enables keep-alive pings and session switching capabilities.

**`switch`** (Client → Server)
Post-authentication message with `{ sessionId }` payload. This binds the connection to a specific chat session, enabling multiple concurrent conversations through a single WebSocket.

### Keep-Alive Mechanism

**`ping`** / **`pong`** (Bidirectional)
Empty JSON objects `{}` used as heartbeats. The client sends `ping` every 25 seconds to prevent connection timeouts, and the server must reply with `pong`. If the server fails to respond, the client implementation in [`public/webchat/js/ws.js`](https://github.com/alsk1992/CloddsBot/blob/main/public/webchat/js/ws.js) automatically initiates reconnection with exponential back-off.

### Core Chat Operations

**`message`** (Bidirectional)
Primary chat payload containing `{ text, attachments?, messageId? }`. Clients broadcast user input to the server, which then distributes the content to all listeners of the current session. The optional `attachments` array supports rich media objects like `{ type: 'image', url: '...' }`.

**`edit`** (Server → Client)
Updates existing content with `{ messageId, text }`. The bot uses this to modify its previous replies without creating new message entries.

**`delete`** (Server → Client)
Removes messages from the UI using `{ messageId }`. This enables the bot to retract content programmatically.

### Error Reporting

**`error`** (Server → Client)
Reports protocol failures with `{ message }`. Common errors include "Invalid token" for authentication failures, triggering the UI to prompt for re-authentication as implemented in the WebChat client.

## Client Implementation Examples

The repository provides two primary integration patterns: the built-in WebChat UI for browsers and raw WebSocket access for programmatic clients.

### Browser Integration with WebChat

The [`public/webchat/js/ws.js`](https://github.com/alsk1992/CloddsBot/blob/main/public/webchat/js/ws.js) file exports a `WSClient` class that handles connection management, automatic reconnection, and message serialization.

```javascript
import { WSClient } from './ws.js';

const client = new WSClient();
client.connect('YOUR_WEBCHAT_TOKEN', 'web-' + Date.now(), 'my-session-id');

client.on('open', () => console.log('WebSocket opened'));
client.on('message', msg => console.log('Incoming:', msg));
client.on('error', err => console.error('WebSocket error', err));
client.on('close', () => console.log('WebSocket closed'));

// Sending a message with optional attachments
client.send('Hello, Clodds!', [
  { type: 'image', url: 'https://example.com/pic.png' }
]);

```

### Node.js Programmatic Client

For server-to-server communication or custom clients, connect directly to the gateway using the `ws` library. The following example demonstrates manual authentication and message sending:

```javascript
import WebSocket from 'ws';

const ws = new WebSocket('ws://localhost:18789/chat');

ws.on('open', () => {
  ws.send(JSON.stringify({ 
    type: 'auth', 
    token: process.env.WEBCHAT_TOKEN, 
    userId: 'node-' + Date.now() 
  }));
});

ws.on('message', data => {
  const msg = JSON.parse(data);
  if (msg.type === 'authenticated') {
    ws.send(JSON.stringify({ type: 'message', text: 'Hey bot!' }));
  }
});

```

## Gateway Server Implementation

The server-side logic resides in [`src/gateway/server.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/server.ts), which manages connection state, routes messages to appropriate sessions, and enforces authentication. Complementary HTTP endpoints for health checks and token management are defined in [`src/gateway/api-routes.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/api-routes.ts).

Documentation references in [`docs/API.md`](https://github.com/alsk1992/CloddsBot/blob/main/docs/API.md) and [`docs/ARCHITECTURE.md`](https://github.com/alsk1992/CloddsBot/blob/main/docs/ARCHITECTURE.md) provide additional context on the gateway's role within the broader CloddsBot architecture, including scaling considerations and security model details.

## Summary

- The **CloddsBot WebSocket Gateway protocol** uses a single `/chat` endpoint for all real-time communication.
- **JSON message types** cover authentication (`auth`/`authenticated`), session management (`switch`), heartbeats (`ping`/`pong`), and chat operations (`message`, `edit`, `delete`).
- Clients must authenticate immediately upon connection and may bind to specific sessions using the `switch` message.
- **Keep-alive pings** occur every 25 seconds to maintain connection state, with automatic reconnection handled by the client.
- The reference implementation spans [`public/webchat/js/ws.js`](https://github.com/alsk1992/CloddsBot/blob/main/public/webchat/js/ws.js) for clients and [`src/gateway/server.ts`](https://github.com/alsk1992/CloddsBot/blob/main/src/gateway/server.ts) for the gateway server.

## Frequently Asked Questions

### What endpoint does the CloddsBot WebSocket Gateway use?

The gateway exposes a single WebSocket endpoint at `/chat`. Clients connect to `ws://<host>/chat` or `wss://<host>/chat` depending on whether TLS is enabled. This endpoint handles the entire protocol lifecycle from authentication through message exchange.

### How does authentication work in the CloddsBot WebSocket protocol?

Immediately after establishing the WebSocket connection, the client must send an `auth` message containing a `token` (WebChat token or empty string for anonymous access), a temporary `userId`, and the `_wsVersion` field. The server validates the token and responds with `authenticated` before allowing further operations.

### What is the keep-alive interval for CloddsBot WebSocket connections?

The client implementation sends a `ping` message every approximately 25 seconds. The server responds with a `pong` to confirm the connection remains active. If the server fails to respond, the client triggers automatic reconnection with exponential back-off.

### Can I use the CloddsBot WebSocket Gateway without the built-in WebChat UI?

Yes. While [`public/webchat/js/ws.js`](https://github.com/alsk1992/CloddsBot/blob/main/public/webchat/js/ws.js) provides a convenient browser client, any WebSocket-capable client can connect directly to the `/chat` endpoint. The protocol is fully documented in [`docs/API.md`](https://github.com/alsk1992/CloddsBot/blob/main/docs/API.md) and supports programmatic integration from Node.js, Python, or other environments by sending raw JSON messages.