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

# 11.4 HTTP Layer

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~160,000 tokens, Output \~12,000 tokens (chapter total) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

In addition to WebSocket, Gateway provides HTTP endpoints to support external integrations, compatible APIs, and web interfaces. The HTTP layer shares the same port as WebSocket (default 18789), distinguished by URL path.

## 11.4.1 HTTP Server Setup

`src/gateway/server-http.ts` is the core file for HTTP routing. It uses Node.js native `http`/`https` modules to create the server:

```typescript
// src/gateway/server-http.ts (key imports)
import {
  createServer as createHttpServer,
  type IncomingMessage,
  type ServerResponse,
} from "node:http";
import { createServer as createHttpsServer } from "node:https";
```

HTTP requests are dispatched based on URL path:

```typescript
// HTTP routing dispatch logic (simplified illustration)
function handleRequest(req: IncomingMessage, res: ServerResponse) {
  const url = new URL(req.url, `http://${req.headers.host}`);
  const pathname = url.pathname;

  // OpenAI compatible API
  if (pathname.startsWith("/v1/")) {
    return handleOpenAiHttpRequest(req, res, options);
  }

  // Open Responses API
  if (pathname.startsWith("/responses")) {
    return handleOpenResponsesHttpRequest(req, res, options);
  }

  // Tool invocation HTTP interface
  if (pathname.startsWith("/tools/")) {
    return handleToolsInvokeHttpRequest(req, res, options);
  }

  // Slack HTTP callback
  if (pathname.startsWith("/slack/")) {
    return handleSlackHttpRequest(req, res);
  }

  // Canvas / A2UI
  if (isCanvasPath(pathname)) {
    return handleA2uiHttpRequest(req, res, canvasHandler);
  }

  // Webhook endpoint
  if (pathname.startsWith("/hook/")) {
    return handleWebhookRequest(req, res, hookDispatchers);
  }

  // Console UI
  if (pathname === "/" || pathname.startsWith("/ui/")) {
    return handleControlUiHttpRequest(req, res, uiState);
  }

  // Avatar API
  if (pathname.startsWith("/avatar")) {
    return handleControlUiAvatarRequest(req, res, cfg);
  }
}
```

HTTP routing uses simple direct path matching without using routing systems from frameworks like Express or Hono—this is because Gateway's HTTP routing is relatively simple and doesn't need complex features like middleware chains.

## 11.4.2 OpenAI Compatible HTTP Interface

`src/gateway/openai-http.ts` implements HTTP endpoints compatible with OpenAI's Chat Completions API. This means any client that supports OpenAI API (such as Cursor, Continue, etc.) can directly connect to OpenClaw Gateway as an LLM backend.

Endpoint: `POST /v1/chat/completions`

```typescript
// src/gateway/openai-http.ts (key types)
type OpenAiChatCompletionRequest = {
  model?: unknown;       // Model identifier (optional, uses Gateway default model)
  stream?: unknown;      // Whether to stream
  messages?: unknown;    // Message list
  user?: unknown;        // User identifier
};
```

Request processing flow:

1. **Authentication**: Using Bearer Token authentication (same as Gateway WebSocket Token)

```typescript
const token = getBearerToken(req);
const authResult = authorizeGatewayConnect({
  auth: { token },
  resolvedAuth: options.auth,
  // ...
});
```

2. **Message Conversion**: Convert OpenAI format message list to OpenClaw internal format

```typescript
function extractTextContent(content: unknown): string {
  if (typeof content === "string") return content;
  if (Array.isArray(content)) {
    return content
      .map((part) => {
        if (part.type === "text" && typeof part.text === "string")
          return part.text;
        return "";
      })
      .join("");
  }
  return "";
}
```

3. **Invoke Agent**: Execute AI inference through the internal `agentCommand()` function
4. **Response Formatting**:
   * **Non-streaming**: Return standard JSON response
   * **Streaming**: Use Server-Sent Events (SSE) to return progressively

```typescript
// SSE streaming write
function writeSse(res: ServerResponse, data: unknown) {
  res.write(`data: ${JSON.stringify(data)}\n\n`);
}
```

SSE format follows OpenAI's streaming response specification: each event is prefixed with `data:` , separated by `\n\n`, and ends with `data: [DONE]\n\n`.

## 11.4.3 Open Responses API

`src/gateway/openresponses-http.ts` implements OpenAI's **Responses API**—this is a newer API format from OpenAI, different from the traditional Chat Completions API.

Endpoint: `POST /responses`

This interface is mainly used to support clients and tools using the Responses API format. The implementation logic is similar to Chat Completions, but the request/response format differs.

## 11.4.4 Tool Invocation HTTP Interface

`src/gateway/tools-invoke-http.ts` provides the ability to directly invoke Gateway tools via HTTP:

Endpoint: `POST /tools/invoke`

This interface allows external systems (such as CI/CD pipelines, automation scripts) to directly call OpenClaw tools without going through an AI Agent. For example:

```bash
# Directly invoke tools via HTTP
curl -X POST http://127.0.0.1:18789/tools/invoke \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"tool": "bash", "params": {"command": "ls -la"}}'
```

### Other HTTP Endpoints

**Webhook Endpoint**: `/hook/:hookId`

Handles webhook callbacks from external services (such as Gmail Pub/Sub pushes). `src/gateway/hooks.ts` parses the webhook payload and injects messages into the corresponding session based on hook configuration.

**Slack HTTP Callback**: `/slack/*`

Some Slack features (such as interactive components, Events API) require HTTP callbacks. The `src/slack/http/` directory handles these requests.

**Console UI**: `/` and `/ui/*`

`src/gateway/control-ui.ts` hosts the built Web UI static files at the root path. Users can access the control panel by visiting `http://127.0.0.1:18789/` in a browser.

**Avatar API**: `/avatar`

`handleControlUiAvatarRequest` returns the AI assistant's avatar image (if configured).

**Canvas/A2UI**: `/a2ui/*`, `/canvas/*`

Canvas and A2UI HTTP endpoints are handled by `src/canvas-host/a2ui.ts`, providing HTML content pushed by Agent.

### HTTP Security

All HTTP endpoints go through authentication checks. `src/gateway/http-common.ts` provides common HTTP helper functions:

```typescript
// Send unauthorized response
export function sendUnauthorized(res: ServerResponse, message?: string) {
  res.statusCode = 401;
  res.setHeader("Content-Type", "application/json");
  res.end(JSON.stringify({ error: message ?? "Unauthorized" }));
}

// Set SSE response headers
export function setSseHeaders(res: ServerResponse) {
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    "Connection": "keep-alive",
  });
}
```

`src/gateway/http-utils.ts` provides utility functions for extracting Bearer Token from requests, parsing Agent ID and Session Key, etc.

***

At this point, we have completed a comprehensive analysis of Gateway's server architecture—from startup flow to WebSocket implementation, and then to the HTTP layer. Gateway's role as a control plane should now be very clear: it is a multi-protocol (WebSocket + HTTP) server that coordinates the work of all subsystems.

In the next chapter, we will dive into Gateway's protocol design and type system—this is key to understanding how Gateway ensures communication correctness.

***

> ### 🔬 Going Deeper: 11.5 Source Deep Dive
>
> That's the end of the chapter's main text. If you're going to **modify this code**, or reproduce it in your own project, read on: [**11.5 Source Deep Dive: The Assembly Site and the Method Routing Table**](https://www.openclawbook.xyz/en/ch11-gateway-server-architecture/11.5-source-deep-dive-assembly-and-method-routing.md) traces the real implementation line by line along with the issues behind it, at a noticeably higher information density.
>
> **The main text is for understanding structure; the deep dive is for understanding trade-offs.**
