Overview
TheWebSocketManager class handles all WebSocket communication for voice agents. It manages connection establishment, message sending/receiving, and clean disconnection. This manager extends Node.js EventEmitter to provide event-driven communication patterns.
Key responsibilities:
- Connect to WebSocket servers or attach existing sockets (server-side)
- Send and receive JSON messages over WebSocket
- Handle connection lifecycle events (open, close, error)
- Gracefully handle socket failures and disconnections
src/core/WebSocketManager.ts:9
Constructor
Properties
isConnected
Returns
true if the WebSocket is currently connected and ready to send messages.currentSocket
Returns the underlying WebSocket instance, or
undefined if not connected.Methods
connect()
Connect to a WebSocket server by URL (client-side usage).The WebSocket server URL (e.g.,
ws://localhost:3000 or wss://example.com)- Automatically disconnects any existing connection before connecting
- Emits
connectedevent when connection succeeds - Rejects the promise if connection fails
handleSocket()
Attach an existing WebSocket instance (server-side usage).An existing WebSocket instance from a server connection
- Immediately marks the connection as active
- Attaches all event listeners
- Emits
connectedevent synchronously - Disconnects any existing connection first
send()
Send a JSON message over the WebSocket.A plain JavaScript object that will be JSON-stringified and sent
- Silently returns if not connected
- Checks socket readyState before sending
- Catches and logs send failures
- Emits
errorevent if send fails - Automatically serializes the message to JSON
disconnect()
Disconnect and clean up the WebSocket connection.- Removes all socket event listeners
- Closes the socket if still open or connecting
- Ignores errors during close (socket may already be dead)
- Sets
isConnectedtofalse - Does not emit any events
Events
TheWebSocketManager emits the following events:
connected
Emitted when the WebSocket connection is successfully established.disconnected
Emitted when the WebSocket connection closes.message
Emitted when a JSON message is received from the WebSocket.The parsed JSON message object. Parse errors trigger the
error event instead.error
Emitted when an error occurs (connection error, parse error, send failure).Usage in Agent Architecture
TheWebSocketManager is used internally by voice agents to handle all real-time communication:
Thread Safety
Error Handling
The manager implements defensive error handling:- Send failures: Caught and logged, emits
errorevent - Parse failures: Logged and emits
errorevent, does not crash - Close errors: Silently ignored (socket may already be closed)
- State checks: Validates readyState before operations
Related
- SpeechManager - Uses WebSocketManager to send audio chunks
- TranscriptionManager - Receives audio through WebSocketManager
- VoiceAgent - Creates and manages WebSocketManager instance