> 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_16_ide_extensions_and_acp/16.3_acp_protocol_deep_analysis.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 16.3 ACP Protocol Deep Analysis

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

***

In the previous two sections, we analyzed OpenCode's integration approaches in VSCode and Zed -- the former achieves lightweight communication through terminal and HTTP, while the latter achieves deep integration through declarative configuration and the ACP protocol. This section will deeply analyze the implementation details of ACP (Agent Client Protocol), which is the core protocol layer for OpenCode's IDE integration.

## 16.3.1 ACP Protocol Introduction

### What is ACP

ACP (Agent Client Protocol) is a standardized protocol that defines the communication specification between **IDEs (clients)** and **AI Agents (servers)**. It is implemented using the `@agentclientprotocol/sdk` library, with a communication format based on JSON-RPC (similar to LSP) and a transport layer using stdio (standard input/output).

ACP defines the following core operations:

| Operation           | Direction       | Description                                                      |
| ------------------- | --------------- | ---------------------------------------------------------------- |
| `initialize`        | Client -> Agent | Capability negotiation, exchange versions and supported features |
| `authenticate`      | Client -> Agent | Authentication request                                           |
| `newSession`        | Client -> Agent | Create a new conversation Session                                |
| `loadSession`       | Client -> Agent | Load an existing Session                                         |
| `prompt`            | Client -> Agent | Send user input                                                  |
| `cancel`            | Client -> Agent | Cancel current operation                                         |
| `sessionUpdate`     | Agent -> Client | Real-time updates (messages, tool calls, progress, etc.)         |
| `requestPermission` | Agent -> Client | Request user approval for sensitive operations                   |

### ACP vs. MCP

> **Extended Explanation -- ACP and MCP: Two Complementary Protocols**
>
> Readers already learned about MCP (Model Context Protocol) in detail in Chapter 8. ACP and MCP are two protocols in the AI Agent ecosystem that work in opposite but complementary directions:
>
> ```
> ┌──────────┐       ACP        ┌──────────────┐       MCP        ┌──────────────┐
> │   IDE    │ <──────────────> │  AI Agent    │ <──────────────> │  External    │
> │ (Client) │   IDE is the    │  (Middle      │  Agent is the   │  Tools       │
> │ Zed,     │   consumer,     │   Layer)      │  consumer,      │  (Provider)  │
> │ VSCode   │   Agent is the  │  OpenCode    │  Tool is the    │  Filesystem, │
> │          │   provider      │              │  provider       │  DB, API     │
> └──────────┘                 └──────────────┘                  └──────────────┘
> ```
>
> * **MCP (Model Context Protocol)**: The Agent acts as a client, connecting to external tools/services (such as filesystems, databases, Web APIs). The Agent consumes the capabilities provided by tools. As we saw in Chapter 8, OpenCode connects to Grep, Glob, Read, and other tool servers through MCP.
> * **ACP (Agent Client Protocol)**: The IDE acts as a client, connecting to the AI Agent. The IDE consumes the capabilities provided by the Agent -- sending prompts, receiving replies, approving permission requests, viewing tool call progress.
>
> The relationship between the two can be analogized as:
>
> * MCP is like the Agent's "hands" -- it operates the external world through MCP
> * ACP is like the Agent's "face" -- it interacts with users (through the IDE) via ACP
>
> A complete AI programming assistant workflow is: User sends a request through the IDE (ACP Client) -> Agent receives the request -> Agent calls tools through MCP to complete the task -> Agent returns results to the IDE through ACP.

### Protocol Lifecycle

A complete ACP Session lifecycle is as follows:

```
Client (IDE)                          Agent (OpenCode)
    |                                       |
    |---- initialize(protocolVersion) ---->|
    |<--- InitializeResponse --------------|  Capability negotiation
    |                                       |
    |---- authenticate(credentials) ------>|
    |<--- AuthenticateResponse ------------|  Authentication (optional)
    |                                       |
    |---- newSession(cwd, mcpServers) ---->|
    |<--- {sessionId, models, modes} ------|  Create Session
    |                                       |
    |---- prompt(sessionId, parts) ------->|
    |<--- sessionUpdate(text_chunk) -------|  ┐
    |<--- sessionUpdate(tool_call) --------|  | Streaming response
    |<--- sessionUpdate(tool_update) ------|  |
    |<--- sessionUpdate(text_chunk) -------|  ┘
    |<--- PromptResponse(usage) ----------|  Complete
    |                                       |
    |---- cancel(sessionId) -------------->|  Cancel (optional)
    |                                       |
```

## 16.3.2 `acp/agent.ts`: Agent Interface Implementation

`acp/agent.ts` is the core file of the entire ACP implementation, totaling 1677 lines of code. It defines the `ACP.Agent` class, which implements the `ACPAgent` interface from `@agentclientprotocol/sdk`.

### Class Structure and Initialization

```typescript
export namespace ACP {
  const log = Log.create({ service: "acp-agent" })

  export async function init({ sdk: _sdk }: { sdk: OpencodeClient }) {
    return {
      create: (connection: AgentSideConnection, fullConfig: ACPConfig) => {
        return new Agent(connection, fullConfig)
      },
    }
  }

  export class Agent implements ACPAgent {
    private connection: AgentSideConnection
    private config: ACPConfig
    private sdk: OpencodeClient
    private sessionManager: ACPSessionManager
    private eventAbort = new AbortController()
    private eventStarted = false
    private permissionQueues = new Map<string, Promise<void>>()
    private permissionOptions: PermissionOption[] = [
      { optionId: "once", kind: "allow_once", name: "Allow once" },
      { optionId: "always", kind: "allow_always", name: "Always allow" },
      { optionId: "reject", kind: "reject_once", name: "Reject" },
    ]

    constructor(connection: AgentSideConnection, config: ACPConfig) {
      this.connection = connection
      this.config = config
      this.sdk = config.sdk
      this.sessionManager = new ACPSessionManager(this.sdk)
      this.startEventSubscription()
    }
    // ...
  }
}
```

`ACP` uses TypeScript's `namespace` to organize code and exposes the `init()` function through the factory pattern. Core member variables:

| Member              | Type                         | Purpose                                                                     |
| ------------------- | ---------------------------- | --------------------------------------------------------------------------- |
| `connection`        | `AgentSideConnection`        | Connection object provided by the ACP SDK, used to send messages to the IDE |
| `config`            | `ACPConfig`                  | Configuration information, including the SDK instance and default model     |
| `sdk`               | `OpencodeClient`             | OpenCode's SDK client, used to call internal APIs                           |
| `sessionManager`    | `ACPSessionManager`          | ACP Session manager                                                         |
| `eventAbort`        | `AbortController`            | Controller for canceling event subscriptions                                |
| `permissionQueues`  | `Map<string, Promise<void>>` | Per-Session queued permission requests                                      |
| `permissionOptions` | `PermissionOption[]`         | Fixed set of three permission options                                       |

The constructor immediately calls `startEventSubscription()` after creation to start the event listening loop.

### `initialize()`: Capability Negotiation

```typescript
async initialize(params: InitializeRequest): Promise<InitializeResponse> {
  log.info("initialize", { protocolVersion: params.protocolVersion })

  const authMethod: AuthMethod = {
    description: "Run `opencode auth login` in the terminal",
    name: "Login with opencode",
    id: "opencode-login",
  }

  // If the client supports terminal-auth, use in-terminal authentication
  if (params.clientCapabilities?._meta?.["terminal-auth"] === true) {
    authMethod._meta = {
      "terminal-auth": {
        command: "opencode",
        args: ["auth", "login"],
        label: "OpenCode Login",
      },
    }
  }

  return {
    protocolVersion: 1,
    agentCapabilities: {
      loadSession: true,
      mcpCapabilities: {
        http: true,
        sse: true,
      },
      promptCapabilities: {
        embeddedContext: true,
        image: true,
      },
      sessionCapabilities: {
        fork: {},
        list: {},
        resume: {},
      },
    },
    authMethods: [authMethod],
    agentInfo: {
      name: "OpenCode",
      version: Installation.VERSION,
    },
  }
}
```

> **Extended Explanation -- Capability Negotiation**
>
> Capability negotiation is a classic pattern in network protocol design. When two systems begin communicating, they first exchange their lists of supported features, then use only mutually supported features in subsequent communication. This pattern appears in many protocols:
>
> * **HTTP Content Negotiation**: Negotiating data formats through `Accept` and `Content-Type` headers
> * **TLS Handshake**: Client and server negotiating encryption algorithms
> * **LSP**: Language server and editor negotiating supported language features
>
> ACP's capability negotiation tells the IDE:
>
> * `loadSession: true`: The Agent supports loading existing Sessions (enabling conversation history recovery)
> * `mcpCapabilities: { http: true, sse: true }`: The Agent supports HTTP and SSE (Server-Sent Events) types of MCP servers
> * `promptCapabilities: { embeddedContext: true, image: true }`: The Agent supports embedded context references and image input
> * `sessionCapabilities: { fork: {}, list: {}, resume: {} }`: The Agent supports Session forking, listing, and resuming operations

The capability set returned by `initialize()` determines which subsequent methods the IDE can call. If the Agent does not declare `loadSession: true`, the IDE will not attempt to call the `loadSession()` method.

### `newSession()` and `loadSession()`: Session Management

```typescript
async newSession(params: NewSessionRequest) {
  const directory = params.cwd
  try {
    const model = await defaultModel(this.config, directory)
    const state = await this.sessionManager.create(
      params.cwd, params.mcpServers, model
    )
    const sessionId = state.id

    log.info("creating_session", {
      sessionId, mcpServers: params.mcpServers.length
    })

    const load = await this.loadSessionMode({
      cwd: directory,
      mcpServers: params.mcpServers,
      sessionId,
    })

    return {
      sessionId,
      models: load.models,
      modes: load.modes,
      _meta: load._meta,
    }
  } catch (e) {
    const error = MessageV2.fromError(e, {
      providerID: this.config.defaultModel?.providerID ?? "unknown",
    })
    if (LoadAPIKeyError.isInstance(error)) {
      throw RequestError.authRequired()
    }
    throw e
  }
}
```

The `newSession()` flow:

1. **Resolve Default Model**: Call `defaultModel()` to determine which LLM model to use
2. **Create Session**: Create a new Session internally in OpenCode through `sessionManager.create()`
3. **Load Session Mode**: Call `loadSessionMode()` to obtain the available model list, Agent modes (such as "code", "architect"), and MCP server configuration
4. **Return Session Information**: Including `sessionId`, available model list, and available mode list

`loadSession()` is more complex because it needs to **replay historical messages**:

```typescript
async loadSession(params: LoadSessionRequest) {
  // ... create Session state ...

  // Replay Session history
  const messages = await this.sdk.session
    .messages({ sessionID: sessionId, directory }, { throwOnError: true })
    .then((x) => x.data)

  // Restore last used model and mode
  const lastUser = messages?.findLast((m) => m.info.role === "user")?.info
  if (lastUser?.role === "user") {
    result.models.currentModelId =
      `${lastUser.model.providerID}/${lastUser.model.modelID}`
    this.sessionManager.setModel(sessionId, {
      providerID: lastUser.model.providerID,
      modelID: lastUser.model.modelID,
    })
  }

  // Replay messages one by one to the IDE
  for (const msg of messages ?? []) {
    await this.processMessage(msg)
  }

  await sendUsageUpdate(this.connection, this.sdk, sessionId, directory)
  return result
}
```

"Replay" means the Agent sends historical messages one by one to the IDE via `sessionUpdate`, and the IDE uses them to reconstruct the conversation interface. This enables users to restore their previous conversation state when they close and reopen the IDE.

Additionally, ACP supports other Session operations:

* **`unstable_listSessions()`**: List all Sessions, supporting pagination (cursor-based pagination)
* **`unstable_forkSession()`**: Fork a Session -- create a branch from a certain conversation node, similar to Git branching
* **`unstable_resumeSession()`**: Resume a Session -- reload state and send usage updates

Note the `unstable_` prefix -- these APIs are still under development, and their interfaces may change in subsequent versions.

### `prompt()`: Core Conversation Processing

`prompt()` is the most critical method of the ACP Agent, handling every user input:

```typescript
async prompt(params: PromptRequest) {
  const sessionID = params.sessionId
  const session = this.sessionManager.get(sessionID)
  const directory = session.cwd
  const model = session.model ?? (await defaultModel(this.config, directory))
  const agent = session.modeId ?? (await AgentModule.defaultAgent())

  // Parse prompt content parts
  const parts: Array<
    | { type: "text"; text: string; synthetic?: boolean; ignored?: boolean }
    | { type: "file"; url: string; filename: string; mime: string }
  > = []

  for (const part of params.prompt) {
    switch (part.type) {
      case "text":
        const audience = part.annotations?.audience
        const forAssistant = audience?.length === 1 && audience[0] === "assistant"
        const forUser = audience?.length === 1 && audience[0] === "user"
        parts.push({
          type: "text" as const,
          text: part.text,
          ...(forAssistant && { synthetic: true }),
          ...(forUser && { ignored: true }),
        })
        break

      case "image":
        // Convert image to file part (data URL or HTTP URL)
        // ...
        break

      case "resource_link":
        // Parse URI (file://, zed://, etc.)
        // ...
        break

      case "resource":
        // Handle embedded resource (text or binary)
        // ...
        break
    }
  }
  // ...
}
```

ACP's prompt content is **multi-part**, where each part can be text, an image, a resource link, or an embedded resource. OpenCode needs to convert these ACP-format contents into its own internal message format.

Particularly noteworthy is the handling of the `audience` annotation:

| ACP audience    | OpenCode Internal Flag | Meaning                                                           |
| --------------- | ---------------------- | ----------------------------------------------------------------- |
| `["assistant"]` | `synthetic: true`      | Synthetic message, visible only to AI (e.g., system instructions) |
| `["user"]`      | `ignored: true`        | Visible only to user, AI does not process (e.g., UI hints)        |
| None or other   | No flag                | Normal message, visible to both parties                           |

`prompt()` also detects slash commands (`/compact`, etc.):

```typescript
const cmd = (() => {
  const text = parts
    .filter((p) => p.type === "text")
    .map((p) => p.text)
    .join("")
    .trim()

  if (!text.startsWith("/")) return
  const [name, ...rest] = text.slice(1).split(/\s+/)
  return { name, args: rest.join(" ").trim() }
})()
```

If the input starts with `/`, it is parsed as a command rather than a regular prompt. Supported commands include custom commands (obtained via `sdk.command.list()`) and built-in commands (such as `/compact` for compressing Session context).

Finally, `prompt()` returns usage statistics:

```typescript
const buildUsage = (msg: AssistantMessage): Usage => ({
  totalTokens:
    msg.tokens.input + msg.tokens.output + msg.tokens.reasoning +
    (msg.tokens.cache?.read ?? 0) + (msg.tokens.cache?.write ?? 0),
  inputTokens: msg.tokens.input,
  outputTokens: msg.tokens.output,
  thoughtTokens: msg.tokens.reasoning || undefined,
  cachedReadTokens: msg.tokens.cache?.read || undefined,
  cachedWriteTokens: msg.tokens.cache?.write || undefined,
})
```

### Event Subscription System

Real-time updates from the ACP Agent are implemented through an event subscription mechanism. The Agent starts an infinite loop at construction time, listening for OpenCode internal events and forwarding them to the IDE:

```typescript
private async runEventSubscription() {
  while (true) {
    if (this.eventAbort.signal.aborted) return
    const events = await this.sdk.global.event({
      signal: this.eventAbort.signal,
    })
    for await (const event of events.stream) {
      if (this.eventAbort.signal.aborted) return
      const payload = (event as any)?.payload
      if (!payload) continue
      await this.handleEvent(payload as Event).catch((error) => {
        log.error("failed to handle event", { error, type: payload.type })
      })
    }
  }
}
```

> **Extended Explanation -- Event-Driven Architecture and Publish-Subscribe Pattern**
>
> Event-Driven Architecture (EDA) is a software design paradigm where system components communicate through events rather than direct calls. The ACP Agent's event subscription is a typical Publish-Subscribe (Pub/Sub) pattern:
>
> * **Publisher**: OpenCode core system (publishing event streams via `sdk.global.event()`)
> * **Subscriber**: ACP Agent (consuming event streams via `for await...of`)
> * **Events**: `permission.asked`, `message.part.updated`, etc.
>
> Compared to direct function calls, the advantage of event-driven architecture lies in **decoupling** -- the OpenCode core does not need to know who is listening to events, and the ACP Agent does not need to understand how events are produced. This allows the system to flexibly add new event consumers (such as extensions for other IDEs in the future).

The event handler `handleEvent()` processes two major categories of events:

#### Permission Request Events (`permission.asked`)

```typescript
case "permission.asked": {
  const permission = event.properties
  const session = this.sessionManager.tryGet(permission.sessionID)
  if (!session) return

  // Use Promise chaining to implement per-Session serial processing
  const prev = this.permissionQueues.get(permission.sessionID)
    ?? Promise.resolve()
  const next = prev.then(async () => {
    const res = await this.connection.requestPermission({
      sessionId: permission.sessionID,
      toolCall: {
        toolCallId: permission.tool?.callID ?? permission.id,
        status: "pending",
        title: permission.permission,
        rawInput: permission.metadata,
        kind: toToolKind(permission.permission),
        locations: toLocations(permission.permission, permission.metadata),
      },
      options: this.permissionOptions,
    })

    // Handle user's selection
    if (res.outcome.outcome !== "selected") {
      await this.sdk.permission.reply({
        requestID: permission.id, reply: "reject", directory,
      })
      return
    }

    // If it's an edit operation and user approved, apply the diff
    if (res.outcome.optionId !== "reject"
        && permission.permission == "edit") {
      const filepath = permission.metadata["filepath"]
      const diff = permission.metadata["diff"]
      const content = await Bun.file(filepath).text()
      const newContent = getNewContent(content, diff)
      if (newContent) {
        this.connection.writeTextFile({
          sessionId: session.id,
          path: filepath,
          content: newContent,
        })
      }
    }

    await this.sdk.permission.reply({
      requestID: permission.id,
      reply: res.outcome.optionId as "once" | "always" | "reject",
      directory,
    })
  })

  this.permissionQueues.set(permission.sessionID, next)
  return
}
```

Key design aspects of permission handling:

1. **Per-Session Serialization**: `permissionQueues` uses Promise chaining to ensure permission requests within the same Session are processed sequentially, avoiding concurrent conflicts
2. **Three Choices**: Allow once, Always allow, Reject
3. **Edit Preview**: For file edit permissions, the Agent applies the diff to the file and notifies the IDE to display the file changes via `writeTextFile`. The `getNewContent()` function uses the `diff` library's `applyPatch()` to apply a unified diff to the original file content

#### Message Part Update Events (`message.part.updated`)

This event fires continuously as the LLM generates responses, and the ACP Agent converts them into updates the IDE can understand:

```typescript
case "message.part.updated": {
  const part = event.properties.part
  const session = this.sessionManager.tryGet(part.sessionID)
  if (!session) return

  if (part.type === "tool") {
    switch (part.state.status) {
      case "pending":
        // Notify IDE: tool call started
        await this.connection.sessionUpdate({
          sessionId, update: {
            sessionUpdate: "tool_call",
            toolCallId: part.callID,
            title: part.tool,
            kind: toToolKind(part.tool),
            status: "pending",
          },
        })
        break

      case "running":
        // Notify IDE: tool is executing
        await this.connection.sessionUpdate({
          sessionId, update: {
            sessionUpdate: "tool_call_update",
            toolCallId: part.callID,
            status: "in_progress",
            kind: toToolKind(part.tool),
            locations: toLocations(part.tool, part.state.input),
            rawInput: part.state.input,
          },
        })
        break

      case "completed":
        // Notify IDE: tool execution completed, with results
        // Special handling: edit-type tools include diff information
        // Special handling: todowrite tool is converted to plan update
        break

      case "error":
        // Notify IDE: tool execution failed
        break
    }
  }

  if (part.type === "text") {
    // Streaming text chunk
    const delta = event.properties.delta
    if (delta && part.ignored !== true) {
      await this.connection.sessionUpdate({
        sessionId, update: {
          sessionUpdate: "agent_message_chunk",
          content: { type: "text", text: delta },
        },
      })
    }
  }

  if (part.type === "reasoning") {
    // Thinking process (Chain-of-Thought)
    const delta = event.properties.delta
    if (delta) {
      await this.connection.sessionUpdate({
        sessionId, update: {
          sessionUpdate: "agent_thought_chunk",
          content: { type: "text", text: delta },
        },
      })
    }
  }
}
```

There are several noteworthy details here:

**Tool Call Lifecycle Mapping**: The four states of OpenCode's internal tools (pending -> running -> completed/error) are precisely mapped to the ACP tool call update protocol. The IDE can use this to display real-time progress of tool execution.

**Special Handling of the Todo Tool**: When the `todowrite` tool completes, the ACP Agent converts the todo list into an ACP "plan" update, allowing the IDE to display the task plan in a dedicated panel:

```typescript
if (part.tool === "todowrite") {
  const parsedTodos = z.array(Todo.Info).safeParse(
    JSON.parse(part.state.output)
  )
  if (parsedTodos.success) {
    await this.connection.sessionUpdate({
      sessionId, update: {
        sessionUpdate: "plan",
        entries: parsedTodos.data.map((todo) => ({
          priority: "medium",
          status: todo.status === "cancelled"
            ? "completed"
            : todo.status,
          content: todo.content,
        })),
      },
    })
  }
}
```

### Tool Classification Mapping

The `toToolKind()` function maps OpenCode's tool names to ACP's standard tool categories:

```typescript
function toToolKind(toolName: string): ToolKind {
  const tool = toolName.toLocaleLowerCase()
  switch (tool) {
    case "bash":
      return "execute"
    case "webfetch":
      return "fetch"
    case "edit":
    case "patch":
    case "write":
      return "edit"
    case "grep":
    case "glob":
    case "context7_resolve_library_id":
    case "context7_get_library_docs":
      return "search"
    case "list":
    case "read":
      return "read"
    default:
      return "other"
  }
}
```

ACP defines six standard tool categories:

| ToolKind  | Meaning                 | Corresponding Tools          |
| --------- | ----------------------- | ---------------------------- |
| `execute` | Execute system commands | `bash`                       |
| `fetch`   | Network requests        | `webfetch`                   |
| `edit`    | File editing            | `edit`, `patch`, `write`     |
| `search`  | Search operations       | `grep`, `glob`, `context7_*` |
| `read`    | File reading            | `list`, `read`               |
| `other`   | Other                   | All unmatched tools          |

The IDE can display different icons and interaction methods based on tool category -- for example, `edit`-type tools might show a diff view, while `execute`-type tools might show terminal output.

The `toLocations()` function extracts file paths from tool input parameters, letting the IDE know which files are being operated on:

```typescript
function toLocations(
  toolName: string, input: Record<string, any>
): { path: string }[] {
  const tool = toolName.toLocaleLowerCase()
  switch (tool) {
    case "read":
    case "edit":
    case "write":
      return input["filePath"] ? [{ path: input["filePath"] }] : []
    case "glob":
    case "grep":
      return input["path"] ? [{ path: input["path"] }] : []
    case "bash":
      return []  // bash has no fixed file path
    default:
      return []
  }
}
```

### `processMessage()`: Historical Message Replay

When a user restores an existing Session, the ACP Agent needs to "replay" historical messages to the IDE. The `processMessage()` function handles all possible message part types:

```typescript
private async processMessage(message: SessionMessageResponse) {
  if (message.info.role !== "assistant" && message.info.role !== "user") return
  const sessionId = message.info.sessionID

  for (const part of message.parts) {
    if (part.type === "tool") {
      // Replay the complete tool call lifecycle
      // pending -> running -> completed/error
    } else if (part.type === "text") {
      // Replay text message
      const audience = part.synthetic
        ? ["assistant"]
        : part.ignored ? ["user"] : undefined
      await this.connection.sessionUpdate({
        sessionId,
        update: {
          sessionUpdate: message.info.role === "user"
            ? "user_message_chunk"
            : "agent_message_chunk",
          content: {
            type: "text", text: part.text,
            ...(audience && { annotations: { audience } }),
          },
        },
      })
    } else if (part.type === "file") {
      // Replay file attachment
      // file:// URL -> resource_link
      // data: URL + image/* -> image block
      // data: URL + text/* -> resource with text
      // data: URL + other -> resource with blob
    } else if (part.type === "reasoning") {
      // Replay thinking process
    }
  }
}
```

The handling of file types is particularly granular -- OpenCode internally uses a unified `{ type: "file", url, filename, mime }` format to store files, but the ACP protocol distinguishes multiple content types. `processMessage()` needs to convert files into the correct ACP content blocks based on URL scheme and MIME type:

| URL Scheme | MIME Type                      | ACP Type                        |
| ---------- | ------------------------------ | ------------------------------- |
| `file://`  | Any                            | `resource_link` (URI reference) |
| `data:`    | `image/*`                      | `image` (inline image)          |
| `data:`    | `text/*` or `application/json` | `resource` (text resource)      |
| `data:`    | Other                          | `resource` (binary blob)        |

### `loadSessionMode()`: Session Mode Loading

This is an internal helper method responsible for loading a Session's complete context information:

```typescript
private async loadSessionMode(params: LoadSessionRequest) {
  const directory = params.cwd
  const model = await defaultModel(this.config, directory)
  const sessionId = params.sessionId

  // 1. Get available Providers and Models
  const providers = await this.sdk.config.providers({ directory })
    .then((x) => x.data!.providers)
  const availableModels = buildAvailableModels(entries, { includeVariants: true })

  // 2. Get available Agent modes
  const modeState = await this.resolveModeState(directory, sessionId)

  // 3. Get available commands
  const commands = await this.config.sdk.command.list({ directory })
    .then((resp) => resp.data!)

  // 4. Register MCP servers passed by the IDE
  for (const server of params.mcpServers) {
    await this.sdk.mcp.add({ directory, name: key, config: mcp })
  }

  // 5. Asynchronously send available commands update
  setTimeout(() => {
    this.connection.sessionUpdate({
      sessionId, update: {
        sessionUpdate: "available_commands_update",
        availableCommands,
      },
    })
  }, 0)

  return { sessionId, models, modes, _meta }
}
```

Step 4 is particularly noteworthy -- IDEs (such as Zed) can pass their own MCP server configurations when creating a Session. OpenCode registers these external MCP servers into its own MCP system, enabling the Agent to use tools provided by the IDE. This is an elegant design where ACP and MCP work together: the IDE not only consumes the Agent's capabilities but can also inject additional tools into the Agent.

### `defaultModel()`: Model Selection Strategy

The `defaultModel()` function implements a multi-level fallback model selection strategy:

```typescript
async function defaultModel(config: ACPConfig, cwd?: string) {
  // 1. If a default model is specified in the config, use it directly
  const configured = config.defaultModel
  if (configured) return configured

  // 2. Read model settings from the user's configuration file
  const specified = await sdk.config.get({ directory })
    .then((resp) => {
      const cfg = resp.data
      if (!cfg || !cfg.model) return undefined
      return Provider.parseModel(cfg.model)
    })

  // 3. If the user-specified model exists in available Providers, use it
  if (specified && providers.length) {
    const provider = providers.find((p) => p.id === specified.providerID)
    if (provider && provider.models[specified.modelID]) return specified
  }

  // 4. If there are no Providers but there is a user config, trust the user
  if (specified && !providers.length) return specified

  // 5. Prefer the OpenCode official Provider
  const opencodeProvider = providers.find((p) => p.id === "opencode")
  if (opencodeProvider?.models["big-pickle"]) {
    return { providerID: "opencode", modelID: "big-pickle" }
  }

  // 6. Use the highest quality available model
  const models = providers.flatMap((p) => Object.values(p.models))
  const [best] = Provider.sort(models)
  if (best) return { providerID: best.providerID, modelID: best.id }

  // 7. Final fallback: OpenCode default
  return { providerID: "opencode", modelID: "big-pickle" }
}
```

This six-level fallback strategy ensures that a usable model can be found in various configuration scenarios.

> **Extended Explanation -- Adapter and Facade Patterns**
>
> The `ACP.Agent` class is essentially an **Adapter** -- it adapts OpenCode's internal API to the standard interface of the ACP protocol. At the same time, it is also a **Facade** -- it hides the complex interactions of multiple OpenCode internal subsystems (Session, Provider, Permission, Command, MCP, etc.) behind a simple interface.
>
> * **Adapter Pattern**: Converts the interface of one class into another interface that clients expect. ACP's `ToolKind` requires categories like "execute" and "edit", while OpenCode internally uses specific tool names. `toToolKind()` is a classic adapter function.
> * **Facade Pattern**: Provides a unified high-level interface for a group of interfaces in a subsystem. The IDE only needs to interact with `ACP.Agent` and does not need to understand the complex logic of OpenCode's internal Session management, Provider selection, Permission handling, etc.

## 16.3.3 `acp/session.ts`: Mapping ACP Sessions to OpenCode Sessions

`acp/session.ts` implements the `ACPSessionManager` class, which serves as the bridge between ACP Sessions and OpenCode's internal Sessions:

```typescript
export class ACPSessionManager {
  private sessions = new Map<string, ACPSessionState>()
  private sdk: OpencodeClient

  constructor(sdk: OpencodeClient) {
    this.sdk = sdk
  }

  async create(
    cwd: string,
    mcpServers: McpServer[],
    model?: ACPSessionState["model"]
  ): Promise<ACPSessionState> {
    // Create an OpenCode Session through the SDK
    const session = await this.sdk.session
      .create({
        title: `ACP Session ${crypto.randomUUID()}`,
        directory: cwd,
      }, { throwOnError: true })
      .then((x) => x.data!)

    // Build ACP Session state
    const state: ACPSessionState = {
      id: session.id,
      cwd,
      mcpServers,
      createdAt: new Date(),
      model,
    }

    this.sessions.set(session.id, state)
    return state
  }

  async load(
    sessionId: string,
    cwd: string,
    mcpServers: McpServer[],
    model?: ACPSessionState["model"]
  ): Promise<ACPSessionState> {
    // Load an existing Session from OpenCode
    const session = await this.sdk.session
      .get({ sessionID: sessionId, directory: cwd }, { throwOnError: true })
      .then((x) => x.data!)

    const state: ACPSessionState = {
      id: sessionId,
      cwd,
      mcpServers,
      createdAt: new Date(session.time.created),
      model,
    }

    this.sessions.set(sessionId, state)
    return state
  }

  get(sessionId: string): ACPSessionState {
    const session = this.sessions.get(sessionId)
    if (!session) {
      throw RequestError.invalidParams(
        JSON.stringify({ error: `Session not found: ${sessionId}` })
      )
    }
    return session
  }

  tryGet(sessionId: string): ACPSessionState | undefined {
    return this.sessions.get(sessionId)
  }

  setModel(sessionId: string, model: ACPSessionState["model"]) {
    const session = this.get(sessionId)
    session.model = model
    this.sessions.set(sessionId, session)
  }

  setMode(sessionId: string, modeId: string) {
    const session = this.get(sessionId)
    session.modeId = modeId
    this.sessions.set(sessionId, session)
  }

  getVariant(sessionId: string) {
    return this.get(sessionId).variant
  }

  setVariant(sessionId: string, variant?: string) {
    const session = this.get(sessionId)
    session.variant = variant
    this.sessions.set(sessionId, session)
  }
}
```

`ACPSessionManager` maintains a `Map<string, ACPSessionState>`, using session ID as the key to store ACP-layer Session state. It provides two retrieval methods:

* `get()`: Throws a `RequestError.invalidParams` exception when not found (for scenarios where the session must exist)
* `tryGet()`: Returns `undefined` when not found (for optional check scenarios, such as checking whether an event belongs to a currently managed Session during event handling)

Note that the `create()` method uses `crypto.randomUUID()` to generate the Session title -- this ensures each ACP Session has a unique identifiable title.

## 16.3.4 `acp/types.ts`: Type Definitions

`acp/types.ts` defines the core types used at the ACP layer:

```typescript
import type { McpServer } from "@agentclientprotocol/sdk"
import type { OpencodeClient } from "@opencode-ai/sdk/v2"

export interface ACPSessionState {
  id: string
  cwd: string
  mcpServers: McpServer[]
  createdAt: Date
  model?: {
    providerID: string
    modelID: string
  }
  variant?: string
  modeId?: string
}

export interface ACPConfig {
  sdk: OpencodeClient
  defaultModel?: {
    providerID: string
    modelID: string
  }
}
```

**`ACPSessionState`** is the state representation of an ACP Session:

| Field        | Type                      | Description                                                        |
| ------------ | ------------------------- | ------------------------------------------------------------------ |
| `id`         | `string`                  | Session unique identifier (same as OpenCode's internal Session ID) |
| `cwd`        | `string`                  | Working directory                                                  |
| `mcpServers` | `McpServer[]`             | MCP server list passed by the IDE                                  |
| `createdAt`  | `Date`                    | Creation time                                                      |
| `model?`     | `{ providerID, modelID }` | Currently used model (optional, may use default)                   |
| `variant?`   | `string`                  | Model variant (e.g., "high", "low" quality levels)                 |
| `modeId?`    | `string`                  | Agent mode ID (e.g., "code", "architect")                          |

**`ACPConfig`** is the ACP Agent's configuration:

| Field           | Type                      | Description                              |
| --------------- | ------------------------- | ---------------------------------------- |
| `sdk`           | `OpencodeClient`          | OpenCode SDK client instance             |
| `defaultModel?` | `{ providerID, modelID }` | Default model specified via command line |

These two types are concise, but they define the contract between the ACP layer and the OpenCode core layer -- `ACPSessionState` contains information that ACP needs but OpenCode's internal Session does not directly provide (such as `mcpServers`, `variant`), while `ACPConfig` encapsulates the global configuration at Agent initialization time.

## 16.3.5 Current Limitations and Future Plans

### Current Limitations

1. **Authentication Not Fully Implemented**: The `authenticate()` method directly throws an exception:

```typescript
async authenticate(_params: AuthenticateRequest) {
  throw new Error("Authentication not implemented")
}
```

The current authentication flow relies on the `authMethods` returned by `initialize()`, guiding users to execute `opencode auth login` through the terminal. The IDE can detect the authentication requirement (via `RequestError.authRequired()`), but the actual authentication flow is completed outside the ACP protocol.

2. **Permission Serialization is Per-Session**: While `permissionQueues` implements sequential processing per Session, permission requests across Sessions are parallel. If multiple Sessions simultaneously request permissions, the IDE needs to manage the display of multiple permission dialogs on its own.
3. **Some APIs Marked as Unstable**: `listSessions`, `forkSession`, `resumeSession` all use the `unstable_` prefix, indicating that the interfaces may change in subsequent versions.
4. **Special Handling of Zed URIs**: The `parseUri()` function includes special handling for the `zed://` URI scheme, which is an implementation detail coupled to a specific IDE:

```typescript
if (uri.startsWith("zed://")) {
  const url = new URL(uri)
  const path = url.searchParams.get("path")
  if (path) {
    return {
      type: "file",
      url: pathToFileURL(path).href,
      filename: name,
      mime: "text/plain",
    }
  }
}
```

Ideally, the ACP protocol should standardize URI schemes rather than handling IDE-specific URI formats on the Agent side.

### Future Directions

1. **Protocol Version Evolution**: The current `protocolVersion` is 1. As the ACP specification matures, future versions may add richer capabilities -- such as Inline Suggestions, Code Actions, Diagnostics, and more.
2. **Richer Permission Model**: The current three-option model (Allow once / Always / Reject) is relatively simple. Future versions may support more fine-grained permission control, such as "allow reading but not writing" or "allow operations only within a specific directory."
3. **Multi-Agent Collaboration**: Currently, each ACP connection corresponds to one Agent instance. In the future, it may support a single IDE connecting to multiple Agents, enabling multi-Agent collaborative work (similar to oh-my-opencode's multi-Agent architecture, but standardized at the protocol level).

## 16.3.6 Chapter Summary

This chapter analyzed OpenCode's three IDE integration approaches:

| Level          | Approach                                              | Complexity           | Feature Depth                                    |
| -------------- | ----------------------------------------------------- | -------------------- | ------------------------------------------------ |
| Lightweight    | VSCode Extension (Terminal + HTTP)                    | 138 lines of code    | Basic context passing                            |
| Declarative    | Zed Extension (TOML + ACP)                            | 0 lines of code      | Complete Agent interaction                       |
| Protocol Layer | ACP Implementation (agent.ts + session.ts + types.ts) | \~1800 lines of code | Session, permissions, tools, streaming responses |

The three form a progressive architecture:

```
VSCode Extension          Zed Extension
    |                        |
    | HTTP                   | Declarative config
    |                        |
    v                        v
OpenCode TUI <----------> ACP Agent
    |                        |
    | Shared internal API    | OpenCode SDK
    |                        |
    v                        v
    OpenCode Core System
```

The VSCode extension communicates directly with the TUI (via HTTP), bypassing the ACP layer; the Zed extension communicates with the Agent through the ACP protocol, gaining richer interaction capabilities. Both approaches ultimately interact with the OpenCode core system, just through different paths.

The ACP protocol represents the future direction of AI Agent integration with IDEs -- a standardized protocol enables any IDE that supports ACP to seamlessly connect with any Agent that supports ACP, just as LSP allows any editor to support intelligent completions for any language. Although OpenCode's ACP implementation is still iterating, it has already demonstrated a complete blueprint for this kind of standardized integration.
