Understanding the CloddsBot WebSocket Gateway Protocol: A Complete Guide
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, the server expects clients to follow a strict handshake sequence before entering the main chat loop.
The connection flow follows six distinct phases:
- Connect – The client opens a WebSocket connection to
ws(s)://<host>/chat. - Authenticate – Immediately after the socket opens, the client sends an
authmessage containing a WebChat token or empty string for anonymous access. - Session binding – Once the server replies with
authenticated, the client optionally sends aswitchmessage with a specificsessionIdto bind to an existing conversation. - Keep-alive – The client initiates a periodic
pingevery approximately 25 seconds; the server responds withpongto maintain the connection. - Chat operations – Users exchange messages through bidirectional
messagepayloads, with the server capable of issuingeditordeletecommands to modify history. - Error handling – Invalid tokens or protocol violations trigger
errormessages, 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 defines the client-side message constructors, while 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.
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 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 file exports a WSClient class that handles connection management, automatic reconnection, and message serialization.
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:
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, 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.
Documentation references in docs/API.md and 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
/chatendpoint 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
switchmessage. - 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.jsfor clients andsrc/gateway/server.tsfor 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 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 and supports programmatic integration from Node.js, Python, or other environments by sending raw JSON messages.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →