> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_03_overall_architecture_design/3.1_client-server_architecture.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 3.1 Client-Server Architecture

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2025-02-17

***

## 3.1.1 Why Does a CLI Tool Need a Server?

This is probably the first question many people have when they look at the OpenCode source code: why does a CLI tool running in a terminal embed an HTTP Server?

The answer lies in OpenCode's **multi-frontend architecture** vision. Although the terminal is the primary interaction method, OpenCode simultaneously supports Web UI, VSCode extensions, desktop applications, and other frontends. All of these frontends need to communicate with OpenCode's core engine -- and an HTTP API is the most universal, most standard way to communicate.

```
+--------------+  +--------------+  +--------------+
|   TUI (Ink)  |  |  Web UI      |  |  VSCode Ext  |
|   Terminal   |  |  Browser UI  |  |  Editor Ext  |
+------+-------+  +------+-------+  +------+-------+
       |                 |                 |
       |     HTTP API + SSE Events         |
       |                 |                 |
       +-----------------+-----------------+
                         |
              +----------v----------+
              |   Server (Hono)     |
              |   Port 4096         |
              |                     |
              |   +---------------+ |
              |   | Core Engine   | |
              |   | Session/Tool/ | |
              |   | Agent/Provider| |
              |   +---------------+ |
              +---------------------+
```

This design brings several important benefits:

1. **Frontend agnosticism**: The core engine does not need to know who is calling it. The TUI, Web UI, and VSCode extension all use exactly the same API.
2. **Testability**: Standard HTTP testing tools can be used to automate API testing.
3. **Remote access**: In theory, the OpenCode Server can run on a remote server, with users connecting via a browser or local client.

## 3.1.2 Server Implementation: The Hono-Based Routing System

OpenCode uses **Hono** as its HTTP framework. From the imports in `server/server.ts`:

```typescript
import { Hono } from "hono"
import { cors } from "hono/cors"
import { streamSSE } from "hono/streaming"
import { basicAuth } from "hono/basic-auth"
```

> **Extended Explanation: Hono**
>
> Hono is an ultra-lightweight web framework originally designed for Cloudflare Workers, but it also supports Bun, Deno, Node.js, and other runtimes. Its API design is similar to Express, but with better performance and stronger type support. Choosing Hono over Express is consistent with OpenCode's choice of Bun as its runtime -- both pursue a modern, high-performance technology stack.

The Server's default listening address is `http://localhost:4096`. At startup, all modules of the core engine are initialized and exposed through the routing system as APIs.

## 3.1.3 API Route Overview

From the `server/routes/` directory, we can see that the Server provides 12 route modules:

```
server/routes/
├── session.ts       # Session management
├── config.ts        # Configuration queries
├── project.ts       # Project management
├── provider.ts      # Provider/model queries
├── mcp.ts           # MCP service management
├── permission.ts    # Permission management
├── pty.ts           # Pseudo-terminal
├── file.ts          # File operations
├── question.ts      # Interactive questions
├── tui.ts           # TUI-specific routes
├── global.ts        # Global routes
└── experimental.ts  # Experimental features
```

Main API endpoints (per `specs/project.md`):

```
# Project Management
GET    /project                              -> Get all projects
POST   /project/init                         -> Initialize a project

# Session Management
GET    /project/:id/session                  -> Get all sessions for a project
POST   /project/:id/session                  -> Create a new session
DELETE /project/:id/session/:sid             -> Delete a session
POST   /project/:id/session/:sid/init        -> Initialize a session
POST   /project/:id/session/:sid/abort       -> Abort a session
POST   /project/:id/session/:sid/compact     -> Compact session context
POST   /project/:id/session/:sid/share       -> Share a session

# Message Management
GET    /project/:id/session/:sid/message     -> Get all messages
POST   /project/:id/session/:sid/message     -> Send a new message (triggers AI response)

# Revert Management
POST   /project/:id/session/:sid/revert      -> Revert to the previous snapshot
POST   /project/:id/session/:sid/unrevert    -> Undo a revert

# Permission Management
POST   /project/:id/session/:sid/permission/:pid -> Respond to a permission request

# File Operations
GET    /project/:id/session/:sid/file/status  -> Get file change status
GET    /project/:id/session/:sid/find/file    -> Search for files
```

This is a complete RESTful API covering all of OpenCode's core operations.

## 3.1.4 Server-Sent Events (SSE) Real-Time Push Mechanism

In AI conversation scenarios, LLM responses are **streaming** -- generated token by token. This means that HTTP's traditional request-response model is insufficient; a mechanism for **server-initiated pushing** is needed.

OpenCode uses **Server-Sent Events (SSE)** to achieve this.

> **Extended Explanation: What is SSE?**
>
> Server-Sent Events is a standard HTML5 technology that allows a server to push events to a client unidirectionally over a persistent HTTP connection.
>
> **SSE vs WebSocket**:

| Feature       | SSE                                  | WebSocket                                                |
| ------------- | ------------------------------------ | -------------------------------------------------------- |
| Direction     | Unidirectional (server -> client)    | Bidirectional                                            |
| Protocol      | Standard HTTP                        | Separate protocol (ws\://)                               |
| Reconnection  | Automatic                            | Must be implemented manually                             |
| Compatibility | Nearly all browsers and HTTP clients | Requires special support                                 |
| Use case      | Server event pushing, streaming data | Real-time bidirectional communication (e.g., chat rooms) |

> For OpenCode's use case -- pushing the LLM's streaming responses and various event notifications from the server -- SSE is the perfect choice: simple, reliable, and based on standard HTTP.

From the source code, we can see SSE in use:

```typescript
import { streamSSE } from "hono/streaming"
```

When a frontend (TUI or Web UI) connects to the Server, it establishes an SSE connection. The Server pushes the following types of events through this connection:

* **Message updates**: Text increments (deltas) generated by the LLM
* **Chain-of-thought updates**: The LLM's reasoning process
* **Tool call events**: Tool execution started, execution completed
* **Permission requests**: The Agent needs user authorization
* **Session state changes**: Busy/idle/error

Events propagate from the core engine to the Server via the Bus (event bus), and the Server then pushes them to the frontend via SSE. This forms a complete event propagation chain:

```
Core Engine (Session/Tool/Agent)
    |
    | Bus.publish(event)
    v
Event Bus (Bus)
    |
    | Bus.subscribe(event)
    v
Server (SSE Route)
    |
    | streamSSE(event)
    v
Frontend (TUI / Web UI / VSCode)
```
