> 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.5-source-deep-dive-assembly-and-method-routing.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 11.5 Source Deep Dive: The Assembly Site and the Method Routing Table

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~278,000 tokens, Output \~13,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

> **About "Source Deep Dive" sections** From here on, several chapters end with one. They sit closer to the source than the main text and carry higher information density, tracing real implementations line by line along with the issues behind them. **The main text is for understanding structure; the deep dive is for understanding trade-offs.** If you only want to know what a piece does, the main text suffices. If you're going to modify it — or reproduce it in your own project — read the deep dive.

§11.1–11.4 covered the Gateway's role, startup flow, WebSocket layer, and HTTP layer. This section goes into three blocks of source: **how the method routing table is designed, how the assembly function orchestrates subsystems, and how the HTTP surface multiplexes one port**.

## 11.5.1 One Port, Three Identities

`src/gateway/`: 43,673 lines across 242 files. Every runtime activity converges on this one process and one port (18789 by default, loopback-only by default).

It is simultaneously:

| Identity                      | Serving                                                                                              |
| ----------------------------- | ---------------------------------------------------------------------------------------------------- |
| **WebSocket JSON-RPC server** | CLI, macOS/iOS/Android apps, web console, ACP bridge                                                 |
| **HTTP multiplexer**          | Webhooks, OpenAI-compatible API, OpenResponses API, tool-invocation API, Canvas host, Control UI SPA |
| **In-process orchestrator**   | Starting, monitoring, and broadcasting state for channels, agents, nodes, cron, heartbeat            |

The architectural invariants are stated in `docs/concepts/architecture.md`:

* **One Gateway per host** — it is the only process permitted to hold a WhatsApp session;
* **Handshake mandatory**;
* **No event replay** — a client that notices a `seq` gap must refresh on its own.

```mermaid
flowchart LR
    subgraph Channels
        TG[Telegram/Discord/Slack/...]
    end
    subgraph GW["Gateway process :18789 (WS+HTTP multiplexed)"]
        CH[ChannelManager<br/>backoff restart / health sweep] --> AG[Agent runtime<br/>agentCommandFromIngress]
        AG <--> EV[in-process event bus<br/>onAgentEvent]
        WS[WS server<br/>req/res/event] <--> EV
        HTTP[HTTP stage pipeline<br/>hooks→tools→/v1/*→canvas→UI] --> AG
        NR[NodeRegistry<br/>reverse RPC + APNs wake]
        WS --> NR
        DISC[Bonjour _openclaw-gw._tcp<br/>wide-area DNS-SD / tailscale serve]
    end
    TG --> CH
    CLI[CLI 'operator'] -->|ws| WS
    MAC[macOS menu bar 'operator/ui'] -->|ws| WS
    WEBUI[Web Control UI 'webchat'] -->|ws| WS
    ACP[Zed etc. ↔ openclaw acp bridge] -->|ws| WS
    IOS[iOS/Android 'role:node'] -->|ws| WS
    NH[openclaw node run<br/>node-host 'role:node'] -->|ws| WS
    NR -.node.invoke.request.-> IOS
    NR -.node.invoke.request.-> NH
```

## 11.5.2 Method Registration: One Flat Routing Table

`BASE_METHODS` (`src/gateway/server-methods-list.ts:4-105`) lists about a hundred methods; channel plugins may contribute their own `gatewayMethods` (`:107-110`).

Both the method list and the event list are returned to the client in `hello-ok` for capability discovery (§12.5.2).

Grouped by prefix:

| Domain            | Representative methods                                                                              | Handler file (`src/gateway/server-methods/`)                  |
| ----------------- | --------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| Sessions / chat   | `chat.send/history/abort`, `sessions.list/patch/reset/compact`                                      | `chat.ts`, `sessions.ts`                                      |
| Agent             | `agent`, `agent.wait`, `agents.create/update/delete`, `agents.files.*`                              | `agent.ts`, `agents.ts`                                       |
| Channels / send   | `channels.status/logout`, `send`, `talk.*`, `tts.*`                                                 | `channels.ts`, `send.ts`, `talk.ts`, `tts.ts`                 |
| Nodes             | `node.list/describe/invoke/rename`, `node.pair.*`, `node.pending.*`, `node.event`                   | `nodes.ts`, `nodes-pending.ts`                                |
| Device admission  | `device.pair.list/approve/reject/remove`, `device.token.rotate/revoke`                              | `devices.ts`                                                  |
| Exec approval     | `exec.approvals.get/set`, `exec.approval.request/resolve/waitDecision`                              | `exec-approvals.ts`, `exec-approval.ts`                       |
| Config / ops      | `config.get/set/apply/patch/schema`, `update.run`, `doctor.*`, `logs.tail`, `health`                | `config.ts`, `update.ts`, `doctor.ts`, `logs.ts`, `health.ts` |
| Scheduling / wake | `cron.*`, `wake`, `last-heartbeat`, `set-heartbeats`                                                | `cron.ts`, `system.ts`                                        |
| Other             | `skills.*`, `models.list`, `tools.catalog`, `secrets.resolve/reload`, `wizard.*`, `browser.request` | same-named files                                              |

### The dispatcher's three gates

`handleGatewayRequest()` (`src/gateway/server-methods.ts:100-157`) sets three gates before a handler runs:

```ts
// src/gateway/server-methods.ts:46-64 (excerpt)
const role = parseGatewayRole(roleRaw);           // operator | node
if (!isRoleAuthorizedForMethod(role, method)) {   // nodes can only call node-specific methods
  return errorShape(ErrorCodes.INVALID_REQUEST, `unauthorized role: ${role}`);
}
if (scopes.includes(ADMIN_SCOPE)) return null;
const scopeAuth = authorizeOperatorScopesForMethod(method, scopes);
if (!scopeAuth.allowed)
  return errorShape(ErrorCodes.INVALID_REQUEST, `missing scope: ${scopeAuth.missingScope}`);
```

**Gate one: role isolation.**

The role model is minimal — only `operator` and `node` (`src/gateway/role-policy.ts:3`).

And the isolation is **bidirectional**: nodes can only call node-specific methods, and **operators conversely cannot call them**.

> That reversal matters. It means a compromised operator client can't impersonate a node to answer invoke requests. **Isolation here isn't "higher privilege contains lower" — it's two disjoint sets.**

**Gate two: scope check.** Five scopes (§12.5.3); `ADMIN_SCOPE` short-circuits.

**Gate three: a control-plane write budget.**

The three methods that **can change machine state** — `config.apply`, `config.patch`, `update.run` — are limited to **3 calls per 60 seconds per client** (`server-methods.ts:38,109-134`).

What it defends against: a runaway automation (or a hijacked agent) rewriting config in a loop.

> A practical pattern: **give methods that mutate the system's own state their own budget**, separate from business-method rate limiting. Changing config three times in a minute is already extreme in normal use; more than that always means something is wrong.

**Bonus: flood guard.** A connection that repeatedly receives unauthorized responses gets its logs suppressed and is eventually disconnected (`message-handler.ts:1183-1209`) — protecting both the log volume and against using the server as an oracle for probing.

## 11.5.3 The Assembly Site: `startGatewayServer`

`server.impl.ts:266`, a thousand-plus-line startup function wiring together a dozen subsystems. §43.4.5 warned against starting your reading here — but by this point you have the context.

Startup sequence:

```
① Config snapshot and legacy migration
② Secrets runtime snapshot (falls back to last-known-good on failure, :353-397)
③ Auth bootstrap (auto-generates and writes back a token if missing)
④ Plugin loading (merging plugin handlers and method names)
⑤ createGatewayRuntimeState (HTTP/WS servers, broadcaster, chat run state)
⑥ NodeRegistry / subscription manager
⑦ cron
⑧ mDNS / wide-area discovery
⑨ Maintenance timers (tick / health / dedupe / media)
⑩ Agent event bridge
⑪ heartbeat
⑫ Channel health monitor
⑬ Tailscale exposure
⑭ Sidecars (browser control, channel startup)
⑮ Config hot reloader (hot/restart dual paths, rollback protection)
```

Step ② — falling back to last-known-good on failure — is another degradation chain (§44.2): failing to resolve a secret doesn't block startup; the last successful snapshot is used, so *one bad SecretRef* doesn't prevent the entire gateway from coming up.

### Three orchestrated object types, three integration styles

**Channels: in-process execution + backoff restart**

`createChannelManager` (`src/gateway/server-channels.ts`) keeps three tables per channel plugin: abort controller, task, runtime snapshot.

After a crash it **restarts with exponential backoff**: 5s start, 5min cap, at most 10 attempts (`:13-19`).

`channel-health-monitor` sweeps every 5 minutes by default and restarts unhealthy channels.

**Agents: decoupled through an in-process event bus**

The Gateway **does not hold the agent loop directly**:

```
pi runtime's assistant/tool/lifecycle streams
        ↓ onAgentEvent(createAgentEventHandler(...))  server.impl.ts:727-740
   WS agent/chat events
        ↓
broadcast to operators; pushed per-session to subscribed nodes
```

In reverse: the `chat.send` and `agent` methods feed requests into `agentCommandFromIngress`.

**This same bus also serves the OpenAI HTTP API** (§11.5.4) — one agent-run implementation, three entry points.

**Nodes: declarations are only claims**

Connections with `role === "node"` are registered into the `NodeRegistry` at handshake (`message-handler.ts:1096-1144`).

**The `commands` a node declares are first filtered by a server-side per-platform allowlist** (`message-handler.ts:990-1001`).

The docs put it plainly: **"caps/commands/permissions are only claims."** What a node can do is decided by Gateway-side policy, not by the node's self-report.

> This principle applies to any protocol where clients declare capabilities: **declarations are for negotiation, not authorization.**

### Manual dependency injection

All handlers share a `GatewayRequestContext` (`server.impl.ts:814-864`) carrying deps, cron, nodeRegistry, broadcast, channel control functions, and so on.

**No DI container — one thousand-line function lays the whole assembly graph out flat.**

> **The trade-off is clear**: what you buy is greppability — want to know where `nodeRegistry` comes from? Search once and you see it created in the assembly function and passed down. What you pay is the cognitive load of that file.
>
> In an architecture where all subsystems share one process, that's a reasonable trade. If it ever needs to split into multiple processes, this function is the first thing that has to be taken apart.

## 11.5.4 The HTTP Surface: A Stage Pipeline

`handleRequest` (`src/gateway/server-http.ts:612-736`) hands each HTTP request to a chain of stages; **whoever claims it first wins**:

```
hooks
  → tools-invoke (POST /tools/invoke)
  → slack (channel callback)
  → openresponses (POST /v1/responses)
  → openai (POST /v1/chat/completions)
  → canvas auth / static assets
  → plugin routes
  → Control UI SPA (fallback)
```

Both LLM endpoints are **disabled by default** (`server.impl.ts:236-243`) and must be explicitly enabled under `gateway.http.endpoints.*`. Authentication reuses Gateway auth (`Authorization: Bearer <token>`).

The docs classify them as a **full operator-access surface** — **past authentication you are a trusted operator of that gateway**, so they belong only behind loopback / tailnet / private ingress (Appendix G.5).

### The OpenAI-compatible layer: the agent *is* the model

The mapping strategy is worth noting: it **does not** proxy requests to an underlying model. It **exposes the entire OpenClaw agent as if it were a model**:

```ts
// src/gateway/openai-http.ts:434-441
const { sessionKey, messageChannel } = resolveGatewayRequestContext({
  req, model, user,
  sessionPrefix: "openai",
  defaultMessageChannel: "webchat",
  useMessageChannelHeader: true,
});
```

Concretely:

| Aspect        | Behavior                                                                                                                    |
| ------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `model` field | Encodes the target agent (`"openclaw:<agentId>"` or the `x-openclaw-agent-id` header)                                       |
| Sessions      | Stateless per request by default; **when OpenAI's `user` field is present, a stable session key is derived from it**        |
| Messages      | Only the last user turn is taken (images are limited by mime / size / URL allowlist)                                        |
| Execution     | Runs a **complete agent turn** through `agentCommandFromIngress` (possibly with several tool calls)                         |
| Streaming     | Subscribes to the agent event bus and converts assistant deltas into SSE `chat.completion.chunk` (`openai-http.ts:516-554`) |
| usage         | **Always 0** — honestly signaling this is a compatibility shim                                                              |

Deriving a stable session key from `user` is a **stateful graft onto a stateless protocol**: consecutive requests from the same `user` land in the same agent session.

The `usage` choice is interesting: **rather than fabricating a plausible but inaccurate number, return 0 to indicate "there is no meaningful value here."**

> **The trade-off** (§45.2): this shape gets routing, tools, and sessions for free; the cost is distorted usage semantics and no per-user permission granularity.
>
> The docs honestly label it full operator-access, but **"an OpenAI-compatible endpoint" is a shape that invites users to wire it into third-party frontends as an ordinary inference API** — the boundary is maintained only by deployment discipline. This is a classic case of *interface shape not matching security semantics*.

**OpenResponses** (`src/gateway/openresponses-http.ts`) implements the newer protocol along the same lines, additionally supporting client function tools and `input_file` / `input_image` (PDF parsing, private-IP blocking, per-hop redirect allowlists). Fields like `store` and `previous_response_id` are **accepted and ignored**.

## 11.5.5 Multiple Gateways and Remote Topologies

`gateway.mode` has exactly two values (`src/config/types.gateway.ts:373-376`):

| Value    | Meaning                                                                          |
| -------- | -------------------------------------------------------------------------------- |
| `local`  | Run a Gateway on this machine                                                    |
| `remote` | Pure client pointing at a remote one (**starting a local gateway is forbidden**) |

Remote configuration `gateway.remote` (`types.gateway.ts:188-203`) carries `url`, `transport: "ssh"|"direct"`, token/password, `tlsFingerprint` (certificate pinning), and `sshTarget` / `sshIdentity`.

**Multiple gateways on one machine use `--profile`**: it automatically namespaces `OPENCLAW_STATE_DIR` / `OPENCLAW_CONFIG_PATH` and suffixes service names (Appendix F.1), with an independent port per instance.

Derived port conventions:

```
browser control = base + 2
CDP             = browser.controlPort + 9 .. +108
```

The docs recommend leaving at least 20 ports between instances' base ports. The typical use is a **primary bot plus a rescue bot** — the mitigation for the single-failure-domain risk in §45.2.

### One important invariant

> **Nodes never run a gateway service.**

Cross-machine command flow is always:

```
channel → Gateway (runs the agent) → node.invoke → node executes → back to Gateway → back to channel
```

**The Gateway is the sole owner of state and admission.** That invariant is what lets you reason about the whole system's trust model in one place.

***

## Section Summary

1. **One process, one port, three identities**: WS JSON-RPC server + HTTP multiplexer + in-process orchestrator; the invariants are "one Gateway per host, handshake mandatory, no event replay."
2. **A flat routing table of \~100 methods** with three dispatcher gates: **bidirectional role isolation** (nodes can only call node methods, and **operators conversely cannot**), scope checks, and a **control-plane write budget** (config-mutating methods limited to 3 per 60s).
3. **Role isolation is two disjoint sets, not "higher privilege contains lower"** — a compromised operator can't impersonate a node.
4. **A 15-step assembly sequence**; secrets resolution failure falls back to last-known-good; **manual DI with no container** buys greppability at the cost of a thousand-line assembly function.
5. **Three orchestration styles**: channels run in-process with exponential-backoff restart (5s→5min, ≤10 attempts); agents decouple through an in-process event bus (one implementation, three entry points); **node capability declarations are only claims**, filtered by a server-side per-platform allowlist.
6. **The HTTP surface is a stage pipeline, first claimant wins**; both LLM endpoints are disabled by default and classified as a **full operator-access surface**.
7. **The OpenAI-compatible layer is "the agent as the model," not a proxy**: `user` derives a stable session key (a stateful graft onto a stateless protocol); **usage is always 0** (better to signal meaninglessness than fabricate). The risk is that this interface shape invites use as an ordinary inference API.
8. **Invariant: nodes never run a gateway service** — the Gateway is the sole owner of state and admission, so the trust model needs reasoning about in only one place.
