> 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.1-acp-protocol-overview.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 40.1 ACP Protocol Overview

> **Generated by**: Claude Opus 4.6 (initial draft) / Claude Opus 5 (`v2026.3.9` revision) **Token usage**: Input \~320k tokens, Output \~6k tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`)

***

As the AI Agent ecosystem expands rapidly, interoperability between different Agent systems has become a critical requirement. ACP (Agent Communication Protocol) emerged to address this need—it defines a standard protocol for Agent-to-Agent communication, allowing IDEs, editors, and other clients to interact with AI Agents in a unified manner. OpenClaw implements the ACP protocol server-side through the `src/acp/` module, serving as a bridge connecting external clients (such as IDE plugins).

> **Sidebar: Agent Communication Protocol (ACP)** ACP is an open standard for Agent communication, analogous to the role of LSP (Language Server Protocol) in programming language toolchains. Just as LSP allows any editor to reuse the same language server's capabilities (code completion, go-to-definition, etc.), ACP enables any client to interact with AI Agents in a standardized way—creating sessions, sending prompts, receiving streaming responses, managing tool calls, and more. ACP uses JSON-RPC style NDJSON (Newline-Delimited JSON) as its transport format, communicating over stdio pipes.

## 40.1.1 ACP SDK Dependencies

OpenClaw's ACP implementation is built on the `@agentclientprotocol/sdk` package, which provides core protocol types and connection management:

```typescript
import {
  AgentSideConnection,  // Agent-side connection (server)
  ClientSideConnection, // Client-side connection
  ndJsonStream,         // NDJSON stream transport
  PROTOCOL_VERSION,     // Protocol version number
  type Agent,           // Agent interface
  type PromptRequest,   // Prompt request
  type PromptResponse,  // Prompt response
  type SessionNotification, // Session notification
  // ...
} from "@agentclientprotocol/sdk";
```

Key abstractions provided by the SDK:

| Type                   | Role      | Description                                                       |
| ---------------------- | --------- | ----------------------------------------------------------------- |
| `AgentSideConnection`  | Server    | Connection management on the Agent side, receives client requests |
| `ClientSideConnection` | Client    | Connection management on the client side, sends requests to Agent |
| `ndJsonStream`         | Transport | Wraps stdin/stdout as a bidirectional NDJSON stream               |
| `Agent`                | Interface | Set of methods that an Agent must implement                       |

## 40.1.2 ACP Server Architecture

OpenClaw's ACP server consists of three layers:

```
ACP Client (IDE / Terminal)
    ↕ stdio (NDJSON)
AcpGatewayAgent (Translation Layer)
    ↕ WebSocket
OpenClaw Gateway
```

### Server Startup

`serveAcpGateway()` is the entry point for the ACP server:

```typescript
// src/acp/server.ts (simplified)

export function serveAcpGateway(opts: AcpServerOptions = {}) {
  const cfg = loadConfig();
  const connection = buildGatewayConnectionDetails({ config: cfg });
  const auth = resolveGatewayAuth({ ... });

  // 1. Create Gateway WebSocket client
  const gateway = new GatewayClient({
    url: connection.url,
    token: token || undefined,
    password: password || undefined,
    clientName: "CLI",
    clientDisplayName: "ACP",
    onEvent: (evt) => agent?.handleGatewayEvent(evt),
    onHelloOk: () => agent?.handleGatewayReconnect(),
    onClose: (code, reason) =>
      agent?.handleGatewayDisconnect(`${code}: ${reason}`),
  });

  // 2. Wrap stdin/stdout as NDJSON stream
  const input = Writable.toWeb(process.stdout);
  const output = Readable.toWeb(process.stdin);
  const stream = ndJsonStream(input, output);

  // 3. Create ACP Agent connection
  new AgentSideConnection((conn) => {
    agent = new AcpGatewayAgent(conn, gateway, opts);
    agent.start();
    return agent;
  }, stream);

  gateway.start();
}
```

Note the stdio direction handling: In the ACP protocol, the Agent **sends** messages to the client via `stdout` and **receives** messages from the client via `stdin`—therefore the assignment `input = stdout`, `output = stdin` is correct (from the stream perspective, writing to stdout is the Agent's output, reading from stdin is the Agent's input).

### Command-Line Arguments

The ACP server is launched via the `openclaw acp` command and supports the following arguments:

```
openclaw acp [options]

Options:
  --url <url>             Gateway WebSocket URL
  --token <token>         Gateway authentication token
  --password <password>   Gateway authentication password
  --session <key>         Default session key
  --session-label <label> Default session label
  --require-existing      Only use existing sessions
  --reset-session         Reset session before first use
  --no-prefix-cwd         Don't add working directory to prompt
  --verbose, -v           Verbose logging to stderr
```

### ACP Agent Information

Each ACP Agent must declare its identity information:

```typescript
export const ACP_AGENT_INFO = {
  name: "openclaw-acp",
  title: "OpenClaw ACP Gateway",
  version: VERSION,  // Dynamically read OpenClaw version
};
```

## 40.1.3 Translation Layer: AcpGatewayAgent

`AcpGatewayAgent` is the core of the entire ACP implementation—it implements the ACP `Agent` interface, translating ACP protocol requests into OpenClaw Gateway RPC calls, and translating Gateway event streams back into ACP session notifications.

### Protocol Initialization

```typescript
async initialize(_params: InitializeRequest): Promise<InitializeResponse> {
  return {
    protocolVersion: PROTOCOL_VERSION,
    agentCapabilities: {
      loadSession: true,
      promptCapabilities: {
        image: true,     // Supports image input
        audio: false,    // Does not support audio
        embeddedContext: true,  // Supports embedded context
      },
      mcpCapabilities: {
        http: false,     // Does not support MCP over HTTP
        sse: false,      // Does not support MCP over SSE
      },
      sessionCapabilities: { list: {} },
    },
    agentInfo: ACP_AGENT_INFO,
    authMethods: [],
  };
}
```

The initialization response declares the Agent's capability set. The current implementation supports images and embedded context, but does not support audio and MCP server integration.

### Session Management

Sessions between ACP and OpenClaw need to be mapped:

```typescript
// Create new session
async newSession(params: NewSessionRequest): Promise<NewSessionResponse> {
  const sessionId = randomUUID();
  // Parse session metadata (sessionKey, label, reset, etc.)
  const meta = parseSessionMeta(params._meta);
  // Resolve final sessionKey
  const sessionKey = await resolveSessionKey({
    meta,
    fallbackKey: `acp:${sessionId}`,
    gateway: this.gateway,
    opts: this.opts,
  });
  // Optionally reset session
  await resetSessionIfNeeded({ meta, sessionKey, ... });
  // Create ACP session record
  const session = this.sessionStore.createSession({
    sessionId,
    sessionKey,
    cwd: params.cwd,
  });
  // Send list of available commands
  await this.sendAvailableCommands(session.sessionId);
  return { sessionId: session.sessionId };
}
```

Session key resolution supports multiple approaches:

1. **By label**: `sessionLabel` → call `sessions.resolve` RPC to look up by label
2. **By key**: `sessionKey` → use directly or verify existence
3. **Fallback**: Generate new key in `acp:{uuid}` format

The ACP session store (`AcpSessionStore`) is a simple in-memory Map maintaining `sessionId → AcpSession` mapping and a reverse index of `runId → sessionId`.

### Prompt Handling

```typescript
async prompt(params: PromptRequest): Promise<PromptResponse> {
  const session = this.sessionStore.getSession(params.sessionId);
  // Cancel previous active run
  if (session.abortController) {
    this.sessionStore.cancelActiveRun(params.sessionId);
  }

  // Extract text and attachments
  const userText = extractTextFromPrompt(params.prompt);
  const attachments = extractAttachmentsFromPrompt(params.prompt);
  // Optionally prefix working directory
  const message = prefixCwd
    ? `[Working directory: ${session.cwd}]\n\n${userText}`
    : userText;

  // Forward to Gateway's chat.send
  return new Promise<PromptResponse>((resolve, reject) => {
    this.pendingPrompts.set(params.sessionId, {
      sessionId, sessionKey, idempotencyKey: runId,
      resolve, reject,
    });

    this.gateway.request("chat.send", {
      sessionKey: session.sessionKey,
      message,
      attachments: attachments.length > 0 ? attachments : undefined,
      idempotencyKey: runId,
      // ...
    }, { expectFinal: true });
  });
}
```

Key design aspects of prompt handling:

* **Working directory prefix**: By default, prepends `[Working directory: /path/to/project]` to user messages, letting the Agent know the user's working context
* **Idempotency key**: Uses `runId` (UUID) as `idempotencyKey` to prevent duplicate processing
* **Promise bridge**: Converts Gateway's event-driven responses into Promise-style synchronous returns

### Event Translation

Gateway events need to be translated into ACP session update notifications:

```typescript
// chat event → ACP session update
private async handleChatEvent(evt: EventFrame): Promise<void> {
  const { sessionKey, state, messageData } = evt.payload;
  const pending = this.findPendingBySessionKey(sessionKey);

  if (state === "delta" && messageData) {
    // Incremental text → agent_message_chunk
    const fullText = /* extract text */;
    const newText = fullText.slice(pending.sentTextLength);
    pending.sentTextLength = fullText.length;
    await this.connection.sessionUpdate({
      sessionId: pending.sessionId,
      update: {
        sessionUpdate: "agent_message_chunk",
        content: { type: "text", text: newText },
      },
    });
    return;
  }

  if (state === "final") {
    // Complete → end_turn
    this.finishPrompt(pending.sessionId, pending, "end_turn");
  }
}

// agent event → tool call notification
private async handleAgentEvent(evt: EventFrame): Promise<void> {
  if (stream === "tool" && phase === "start") {
    await this.connection.sessionUpdate({
      sessionId: pending.sessionId,
      update: {
        sessionUpdate: "tool_call",
        toolCallId,
        title: formatToolTitle(name, args),
        status: "in_progress",
        kind: inferToolKind(name),
      },
    });
  }
}
```

Two core mappings for event translation:

| Gateway Event       | ACP Notification            | Description                                                         |
| ------------------- | --------------------------- | ------------------------------------------------------------------- |
| `chat.delta`        | `agent_message_chunk`       | Streaming text increment (delta calculated: `fullText - sentSoFar`) |
| `chat.final`        | `PromptResponse(end_turn)`  | Prompt complete                                                     |
| `chat.aborted`      | `PromptResponse(cancelled)` | Cancelled by user                                                   |
| `chat.error`        | `PromptResponse(refusal)`   | Agent refusal or error                                              |
| `agent.tool.start`  | `tool_call`                 | Tool call started                                                   |
| `agent.tool.result` | `tool_call_update`          | Tool call completed/failed                                          |

The incremental text handling deserves attention: Gateway's `delta` events send **cumulative full text** (not incremental). The ACP translation layer tracks sent characters via a `sentTextLength` counter, sending only the new portion. This design's advantage is supporting out-of-order and retransmission—even if a delta event is missed, subsequent complete text can self-correct.

### Tool Type Inference

`inferToolKind()` infers the ACP tool type based on tool name:

```typescript
export function inferToolKind(name?: string): ToolKind {
  const normalized = name?.toLowerCase();
  if (normalized?.includes("read"))   return "read";
  if (normalized?.includes("write"))  return "edit";
  if (normalized?.includes("delete")) return "delete";
  if (normalized?.includes("exec"))   return "execute";
  if (normalized?.includes("fetch"))  return "fetch";
  if (normalized?.includes("search")) return "search";
  return "other";
}
```

This is a **heuristic** classification—mapping OpenClaw's rich tool names to ACP's limited tool categories through keyword matching.

## 40.1.4 ACP Client

`client.ts` provides a reference implementation of the ACP client for interacting with ACP Agents from the command line:

```typescript
export async function createAcpClient(opts: AcpClientOptions = {}) {
  // 1. Start ACP server process
  const agent = spawn("openclaw", ["acp", ...serverArgs], {
    stdio: ["pipe", "pipe", "inherit"],
    cwd,
  });

  // 2. Establish NDJSON stream connection
  const stream = ndJsonStream(
    Writable.toWeb(agent.stdin),
    Readable.toWeb(agent.stdout),
  );

  // 3. Create client connection
  const client = new ClientSideConnection(
    () => ({
      sessionUpdate: async (params) => {
        // Handle streaming output
        printSessionUpdate(params);
      },
      requestPermission: async (params) => {
        // Auto-approve permission requests
        return { outcome: { outcome: "selected", optionId: "allow" } };
      },
    }),
    stream,
  );

  // 4. Protocol initialization
  await client.initialize({
    protocolVersion: PROTOCOL_VERSION,
    clientCapabilities: {
      fs: { readTextFile: true, writeTextFile: true },
      terminal: true,
    },
    clientInfo: { name: "openclaw-acp-client", version: "1.0.0" },
  });

  // 5. Create session
  const session = await client.newSession({ cwd, mcpServers: [] });
  return { client, agent, sessionId: session.sessionId };
}
```

The client communicates with the ACP server via `stdio`:

```
[ACP Client Process]
    stdin  → write requests  → [ACP Server's stdin]
    stdout ← receive responses ← [ACP Server's stdout]
    stderr ← log output  ← [ACP Server's stderr]
```

Interactive mode (`runAcpClientInteractive`) provides a simple REPL interface:

```
OpenClaw ACP client
Session: a1b2c3d4-...
Type a prompt, or "exit" to quit.

> Analyze the architecture of this project
[tool] read: filePath: src/index.ts (in_progress)
[tool update] tool_123: completed
This project uses a layered architecture...

[end_turn]

>
```

### Session Update Handling

Session update notifications received by the client are translated into human-readable output:

```typescript
function printSessionUpdate(notification: SessionNotification) {
  switch (notification.update.sessionUpdate) {
    case "agent_message_chunk":
      // Stream Agent's text reply
      process.stdout.write(notification.update.content.text);
      break;
    case "tool_call":
      // Tool call started
      console.log(`\n[tool] ${update.title} (${update.status})`);
      break;
    case "tool_call_update":
      // Tool call status update
      console.log(`[tool update] ${update.toolCallId}: ${update.status}`);
      break;
    case "available_commands_update":
      // Available commands list
      const names = update.availableCommands.map(cmd => `/${cmd.name}`);
      console.log(`\n[commands] ${names.join(" ")}`);
      break;
  }
}
```

## 40.1.5 Available Commands

The ACP server pushes a list of available slash commands when creating a session:

```typescript
export function getAvailableCommands(): AvailableCommand[] {
  return [
    { name: "help", description: "Show help and common commands." },
    { name: "status", description: "Show current status." },
    { name: "think", description: "Set thinking level." },
    { name: "model", description: "Select a model." },
    { name: "reset", description: "Reset the session." },
    { name: "compact", description: "Compact the session history." },
    { name: "stop", description: "Stop the current run." },
    // ... 25+ commands total
  ];
}
```

These commands align with OpenClaw's chat command system (Chapter 33), but are exposed to external clients through the ACP protocol, enabling IDE plugins and other tools to provide command completion and quick actions.

## 40.1.6 Metadata Helper Functions

The ACP protocol's `_meta` field is used to pass extended information. `meta.ts` provides type-safe reading utilities:

```typescript
// Multi-key lookup, compatible with different client naming conventions
export function readString(
  meta: Record<string, unknown> | null | undefined,
  keys: string[],
): string | undefined {
  for (const key of keys) {
    const value = meta[key];
    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }
  return undefined;
}
```

The multi-key lookup design allows the same configuration to be passed through different key names. For example, `readString(meta, ["sessionKey", "session", "key"])` accepts three key names—improving compatibility with different client implementations.

***

## Section Summary

1. **ACP is a standard protocol for Agent-to-Agent communication**, similar to LSP for language toolchains, communicating via NDJSON over stdio.
2. **Three-layer architecture**: ACP client ↔ AcpGatewayAgent (translation layer) ↔ OpenClaw Gateway, with the translation layer responsible for protocol conversion.
3. **AcpGatewayAgent** implements the ACP `Agent` interface, translating requests like `prompt`/`newSession`/`cancel` into Gateway RPC calls like `chat.send`/`sessions.resolve`/`chat.abort`.
4. **Event translation** converts Gateway's `chat.delta`/`agent.tool` events into ACP's `agent_message_chunk`/`tool_call` notifications, with incremental text calculated via delta to avoid duplicate transmission.
5. **Session mapping** supports three approaches to establish correspondence between ACP and OpenClaw sessions: by key, by label, or auto-generated.
6. **Tool type inference** uses heuristic keyword matching to map OpenClaw tool names to ACP standard categories.
7. **Command exposure** exposes 25+ slash commands through the ACP protocol to external clients, supporting IDE plugin command completion.
