> 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/ch40-acp/40.4-source-deep-dive-two-opposite-acp-subsystems.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 40.4 Source Deep Dive: Two ACP Subsystems Pointing Opposite Ways

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

***

The most confusing thing on a first read of `src/acp/` (7,101 lines): **it contains two subsystems pointing in opposite directions.**

```
A. ACP bridge     OpenClaw acts as an ACP Agent, called by Zed and similar   (OpenClaw is the callee)
B. ACP Runtime    OpenClaw acts as host, running external ACP agents as its own runtime (OpenClaw is the caller)
```

Sort that out and everything in §40.1–40.3 falls into place.

## 40.4.1 A: The ACP Bridge (`openclaw acp`)

Fundamentally a **bidirectional translator**:

```
stdio NDJSON (ACP side)  ←→  Gateway WS (internal side)
```

### The startup order is deliberate

```
connect to the Gateway first → wait for hello-ok → only then attach stdio
```

(`src/acp/server.ts:113-131`)

**Why not the other way?** Because an editor may send `newSession` the instant stdio is attached. If the Gateway isn't connected yet, that request lands nowhere.

> **A general pattern: when bridging two systems, establish the downstream connection before accepting upstream requests.** Reverse the order and you have to handle an entire class of "request arrived but downstream isn't ready" races.

### Method mapping is thin

| ACP method       | Gateway method                  |
| ---------------- | ------------------------------- |
| `prompt`         | `chat.send` (`expectFinal`)     |
| `cancel`         | `chat.abort`                    |
| `setSessionMode` | `sessions.patch{thinkingLevel}` |

(`src/acp/translator.ts:411-659`)

Thinness is a virtue — the thinner the translation layer, the less semantic drift between the two sides.

### Two layers of session ID

```
ACP sessionId       in-process memory, acp:<uuid>, isolated by default
       ↕
Gateway sessionKey  persisted
```

**Sharing an existing agent session requires explicit opt-in via `_meta.sessionKey` / `sessionLabel`.**

Isolation by default is right: opening an ACP session in an editor shouldn't automatically take over the main-session context you have running on Telegram.

### `runId` serves three purposes at once

```ts
// src/acp/translator.ts:594-628 (excerpt)
const runId = randomUUID();
this.sessionStore.setActiveRun(params.sessionId, runId, abortController);
this.gateway.request("chat.send", {
  sessionKey: session.sessionKey,
  message,
  idempotencyKey: runId,   // ← serves as both idempotency key and event-correlation key
}, { expectFinal: true });
```

One `runId` is simultaneously:

1. The local handle for the active run (used for cancel);
2. **The idempotency key sent to the Gateway** (§12.5.1);
3. **The correlation key for the returning event stream** (identifying which events belong to this run).

Those three purposes are naturally aligned — each needs "a unique identifier for this run." Merging them into one value eliminates the mapping tables between them.

### Three defensive details

| Defense                                                 | Notes                                                                                                                                                |
| ------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| **2 MB prompt cap accumulated chunk by chunk**          | A CWE-400 (resource exhaustion) fix; it **accumulates as it receives** rather than checking the final size, cutting off the moment the cap is passed |
| Session creation rate limit, 120 per 10s                | Against session floods                                                                                                                               |
| **Gateway `error` maps to ACP `end_turn`, not refusal** | Original comment: **"don't make transient backend errors look like a deliberate refusal"** (`translator.ts:810-814`)                                 |

The third is worth sitting with. An editor receiving `refusal` displays "the agent refused your request," and the user assumes a content-policy issue — when actually the gateway just hiccupped.

> **Misclassifying an error misleads the user's next action.** Shown "refused," a user rewrites the prompt; shown "ended," a user retries — and the latter is correct. Same thinking as §45.3's "who is the error message for": an error isn't merely a record, it's guidance for downstream behavior.

## 40.4.2 B: ACP Runtime + Control Plane

The reverse: OpenClaw acts as an **ACP host**, treating external ACP agents (paired with the acpx plugin) as its own agent runtime.

### Concurrency: per-sessionKey actor queues

`AcpSessionManager` uses **a per-sessionKey serial actor queue** plus **a TTL-evicted runtime cache**.

That's the same instinct as §13.6.1's session lanes — same session serial, different sessions parallel. **The same concurrency primitive reused twice in the system.**

### Persistent bindings: a deterministic sessionKey

`persistent-bindings` generates a **deterministic sessionKey** from

```
the first 16 characters of sha256(channel:accountId:conversationId)
```

pinning a Discord thread or Telegram topic to a specific ACP session.

The advantage of a hash over an auto-increment ID or random UUID: **stateless and recomputable.** After a Gateway restart the same key can be derived without any lookup table — the binding is durable by construction.

> The same technique as §26.4.2's cron staggering by job-id SHA-256: **replace a mapping table that would otherwise need persisting with a deterministic hash.**

### Configuration as desired state

```
config change → automatic close + re-init to converge
```

(`persistent-bindings.lifecycle.ts:14-90`)

The comment says **"configuration as desired state"** — no incremental diffing, just tear down and rebuild so the runtime converges to the config.

For a resource whose rebuild cost is acceptable, that's far more reliable than hand-written diff logic: diffing must cover every combination of changes; "rebuild everything" has exactly one path.

> **The deciding factor is rebuild cost.** Rebuilding an ACP session takes milliseconds, so take the simple reliable full-rebuild path; if you were rebuilding a multi-gigabyte index, incremental would be mandatory.

***

## Section Summary

1. **`src/acp/` holds two subsystems pointing opposite ways**: the ACP bridge (OpenClaw called by an editor) and the ACP Runtime (OpenClaw calling external agents) — separating them is the key to reading this directory.
2. **The bridge's startup order**: connect the Gateway and await hello-ok before attaching stdio — **establish the downstream connection before accepting upstream requests**, avoiding a whole class of races.
3. **Two layers of session ID**: ACP `sessionId` (in-memory, isolated by default) ↔ Gateway `sessionKey` (persisted); sharing an existing session requires explicit opt-in.
4. **`runId` serves three purposes at once**: active-run handle + idempotency key + event-correlation key — naturally aligned, and merging them eliminates mapping tables.
5. **A 2 MB prompt cap accumulated as it receives** (not checked at the end); **Gateway errors map to `end_turn` rather than refusal** — misclassifying an error misleads the user's next action.
6. **The Runtime side reuses per-sessionKey serial queues** (the same primitive as session lanes) and **generates a deterministic sessionKey from `sha256(channel:account:conversation)`** instead of persisting a mapping table.
7. **"Configuration as desired state"**: close + re-init on change rather than incremental diffing — **the deciding factor is rebuild cost**, and a millisecond rebuild should take the simple reliable path.
