src — server

Module: src-server Cohesion: 0.80 Members: 0

src — server

The src/server module is the backbone of the Code Buddy application, providing the core HTTP REST API and WebSocket server. It acts as the central gateway for interacting with the AI agent, managing sessions, tools, system health, and various internal protocols. This module is designed to be robust, secure, and extensible, handling concerns like authentication, authorization, rate limiting, logging, and error management.

Architecture Overview

The server module is built on Express.js, providing a flexible and widely understood framework for handling HTTP requests. It orchestrates a chain of middleware for cross-cutting concerns before routing requests to specific handlers. A WebSocket server runs alongside the HTTP server, enabling real-time communication.

The src/server/index.ts file is the main entry point, responsible for:

  1. Configuration: Loading server settings from environment variables and constants.ts.
  2. Middleware Setup: Applying global middleware for security, logging, rate limiting, and authentication.
  3. Route Registration: Mounting various API routers for different functionalities (chat, tools, sessions, health, etc.).
  4. WebSocket Initialization: Setting up the WebSocket server for real-time interactions.
  5. Startup & Shutdown: Managing the server's lifecycle.
graph TD
    A[src/server/index.ts] --> B(Express Application)
    B -- Configures --> C(Middleware Chain)
    C --> C1(Request ID)
    C --> C2(Security Headers)
    C --> C3(Logging)
    C --> C4(CORS)
    C --> C5(Body Parsing)
    C --> C6(Rate Limiting)
    C --> C7(Authentication)
    C --> C8(CSRF Protection)
    B -- Mounts --> D(API Routes)
    D --> D1[/api/chat]
    D --> D2[/api/tools]
    D --> D3[/api/sessions]
    D --> D4[/api/health]
    D --> D5[/api/metrics]
    D --> D6[/api/workflows]
    D --> D7[/api/a2a]
    D --> D8[/api/acp]
    D --> D9[/__codebuddy__/dashboard]
    B -- Initializes --> E(WebSocket Server)
    E --> E1(src/server/websocket/index.ts)
    D1 -- Uses --> F(src/agent/codebuddy-agent.ts)
    D7 & D8 -- Uses --> G(src/protocols/a2a/index.ts)
    C7 -- Uses --> H(src/server/auth/index.ts)
    C6 -- Uses --> I(src/server/middleware/rate-limit.ts)
    C3 -- Uses --> J(src/utils/logger.ts)
    C5 -- Uses --> K(src/server/middleware/error-handler.ts)

Key Components

1. Main Server (src/server/index.ts)

This file is the orchestrator. The startServer function initializes the Express application via createApp, sets up the WebSocket server, and starts listening for incoming connections. It also handles the graceful shutdown of the server via stopServer.

Key Functions:

The createApp function is particularly important as it defines the order of middleware and routes:

  1. requestIdMiddleware: Assigns a unique ID to each request.
  2. createSecurityHeadersMiddleware: Adds HTTP security headers (CSP, HSTS, etc.).
  3. createLoggingMiddleware: Logs incoming requests and outgoing responses.
  4. cors: Handles Cross-Origin Resource Sharing.
  5. express.json, express.urlencoded: Parses request bodies.
  6. createRateLimitMiddleware: Applies global and route-specific rate limits.
  7. createAuthMiddleware: Authenticates requests using API keys or JWTs.
  8. CSRFProtection: Provides CSRF token generation and validation for state-changing requests.
  9. API Routes: Various routers are mounted for specific functionalities.
  10. notFoundHandler: Catches requests to undefined routes (404).
  11. errorHandler: Centralized error handling for all API errors.

2. Authentication & Authorization (src/server/auth/)

This sub-module provides the mechanisms for securing API access.

src/server/auth/api-keys.ts

Manages API keys, which are long-lived credentials for programmatic access.

Key Functions:

src/server/auth/jwt.ts

Handles JSON Web Tokens (JWTs) for session-based or short-lived authentication.

Key Functions:

3. Middleware (src/server/middleware/)

This directory contains reusable Express middleware functions that handle common concerns across API routes.

src/server/middleware/auth.ts

Integrates API key and JWT validation into the Express request lifecycle.

Key Functions:

src/server/middleware/error-handler.ts

Provides a centralized and structured approach to error handling.

Key Components:

src/server/middleware/logging.ts

Provides request and response logging, along with basic request statistics.

Key Functions:

src/server/middleware/rate-limit.ts

Implements a sliding window rate limiting mechanism to protect the API from abuse.

Key Functions:

src/server/middleware/security-headers.ts

Adds essential HTTP security headers to enhance the application's security posture.

Key Functions:

4. API Routes (src/server/routes/)

This directory contains the route definitions for various API functionalities. Each file typically exports an Express Router instance.

src/server/routes/a2a-protocol.ts

Implements endpoints for the Google Agent-to-Agent (A2A) protocol, enabling discovery and interaction with other agents.

Key Function:

src/server/routes/acp.ts

Provides an HTTP transport layer for the Agent Communication Protocol (ACP), including named persistent sessions and task queuing.

Key Function:

src/server/routes/canvas.ts

Manages an agent-driven visual workspace, serving HTML/CSS/JS content and A2UI host pages.

Key Function:

src/server/routes/chat.ts

Provides endpoints for interacting with the Code Buddy AI agent for chat completions.

Key Routes:

Dependencies:

5. Dashboard (src/server/dashboard.ts)

This module provides a singleton Dashboard class for managing and exposing status and metrics for a web-based control UI.

Key Class:

Integration Points

The src/server module integrates with many other parts of the Code Buddy codebase:

Configuration

The server's behavior is highly configurable through environment variables and the ServerConfig interface.

Key Configuration Options (from DEFAULT_CONFIG in src/server/index.ts):

These settings can be overridden by environment variables (e.g., PORT, JWT_SECRET, AUTH_ENABLED) or by passing a Partial object to startServer.

Development & Contribution Notes