src — gateway

Module: src-gateway Cohesion: 0.80 Members: 0

src — gateway

The src/gateway module provides a robust, centralized WebSocket gateway designed for multi-client communication. It acts as a unified control plane, enabling real-time interaction between various clients such as agents, tools, and user interfaces. Inspired by established WebSocket gateway patterns, it offers features like session management, authentication, message routing, and agent registration.

This module is critical for enabling the real-time, interactive nature of the system, allowing different components to communicate and coordinate seamlessly.

Core Concepts

Before diving into the components, understanding the fundamental concepts is key:

Architecture Overview

The gateway module employs an abstract base server (GatewayServer) and a concrete WebSocket implementation (WebSocketGateway). This separation allows for potential future transport layers while keeping core logic consistent.

classDiagram
    direction LR
    class EventEmitter {
        +emit()
        +on()
    }
    class GatewayServer {
        -config: GatewayConfig
        -clients: Map<string, ClientState>
        -sessions: SessionManager
        -handlers: Map<GatewayMessageType, MessageHandler>
        +constructor()
        +start()
        +stop()
        +registerHandler()
        #onConnect()
        #onDisconnect()
        #onMessage()
        #sendToClient()
        +broadcastToSession()
    }
    class WebSocketGateway {
        -wsConfig: WebSocketTransportConfig
        -wss: WebSocketServer
        -httpServer: HttpServer
        -wsClients: Map<string, WebSocketClient>
        +constructor()
        +start()
        +stop()
        -handleConnection()
        -handleMessage()
        #sendToClient()
        +broadcast()
        +broadcastToSession()
    }
    class SessionManager {
        -sessions: Map<string, Session>
        +createSession()
        +addClient()
        +removeClient()
        +getClients()
        +cleanup()
    }
    class AgentRegistry {
        -agents: Map<string, RegisteredAgent>
        -gateway: WebSocketGateway
        +constructor()
        +register()
        +updateStatus()
        +getAgent()
        +findByCapability()
    }

    EventEmitter <|-- GatewayServer
    GatewayServer <|-- WebSocketGateway
    GatewayServer "1" *-- "1" SessionManager : manages
    WebSocketGateway "1" *-- "1" AgentRegistry : uses

  1. GatewayServer (src/gateway/server.ts): The abstract base class. It defines the core logic for managing client states, sessions, message handlers, and authentication. It's transport-agnostic, meaning it doesn't care how messages are sent or received, only what to do with them.
  2. WebSocketGateway (src/gateway/ws-transport.ts): Extends GatewayServer to provide a concrete implementation using WebSockets. It handles the low-level WebSocket server setup, connection management, message serialization/deserialization, and heartbeat mechanisms.
  3. SessionManager (src/gateway/server.ts): A utility class used by GatewayServer to manage logical sessions, allowing clients to join and leave, and facilitating message broadcasting within a session.
  4. AgentRegistry (src/gateway/ws-transport.ts): Manages the registration and lifecycle of various agents (e.g., AI models, tool executors) connected via the WebSocketGateway.

Key Components

1. src/gateway/types.ts

This file defines all the essential types and interfaces used throughout the gateway module:

2. src/gateway/server.ts

This file contains the core, transport-agnostic logic of the gateway.

createMessage(type, payload, sessionId?)

A utility function to construct a standard GatewayMessage object, assigning a unique ID and timestamp.

createErrorMessage(code, message, details?)

A specialized utility to create an error type GatewayMessage with a structured error payload.

SessionManager Class

Manages the lifecycle and client membership of sessions.

GatewayServer Class

The abstract base class for the gateway server. It extends EventEmitter to allow for event-driven communication within the server.

Singleton Access

3. src/gateway/ws-transport.ts

This file implements the WebSocket-specific transport layer for the gateway.

WebSocketTransportConfig & DEFAULT_WS_CONFIG

Extends GatewayConfig with WebSocket-specific settings like path, perMessageDeflate, maxPayload, heartbeatInterval, clientTimeout, and corsOrigins.

isOriginAllowed(origin, allowedOrigins)

A security utility function to validate incoming WebSocket connection origins against a list of allowed patterns, supporting wildcards. This is crucial for preventing Cross-Site WebSocket Hijacking (CSWH).

WebSocketGateway Class

Extends GatewayServer to provide a concrete WebSocket implementation.

AgentRegistry Class

Manages the registration and status of agents connected to the WebSocketGateway.

Control Messages

Singleton Access

Message Flow Example: Client Connect and Auth

  1. Client Connect:

  1. Client Authentication:

Extensibility

Security Considerations

Connection to the Rest of the Codebase

The src/gateway module serves as the central nervous system for real-time communication. Other modules would interact with it by:

By providing a well-defined message format and a robust, extensible server, the src/gateway module ensures that all components can communicate effectively and securely in a real-time environment.