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

# 16.1 VSCode Extension Implementation

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

***

OpenCode, as a terminal-native AI programming assistant, has its core interaction interface in the TUI (Terminal User Interface). However, modern developers spend most of their time in IDEs, so OpenCode needs a way to "embed" itself into the IDE workflow. The VSCode extension is OpenCode's first approach to IDE integration, and also the most lightweight one.

This section will thoroughly dissect the VSCode extension implementation under the `sdks/vscode/` directory. Readers will discover that this extension's design philosophy is fundamentally different from typical VSCode extensions -- it does not implement a Language Server, does not embed a WebView panel, and does not even communicate directly with an LLM. Its entire functionality can be summarized in one sentence: **Create a terminal, run the `opencode` command, then communicate with the TUI via HTTP**.

## 16.1.1 `sdks/vscode/` Architecture Overview

### Directory Structure

OpenCode's VSCode extension resides in the `sdks/vscode/` directory of the repository. The entire extension has only one core source file:

```
sdks/vscode/
├── src/
│   └── extension.ts          # All extension logic (138 lines)
├── images/
│   ├── icon.png              # Extension icon
│   ├── button-dark.svg       # Dark theme button icon
│   └── button-light.svg      # Light theme button icon
├── package.json              # Extension manifest
├── tsconfig.json             # TypeScript configuration
└── esbuild.js                # Build script
```

Yes, you read that correctly -- the entire extension's core logic is only **138 lines of TypeScript code**. This is not crude -- it is a deliberate design choice.

### Extension Manifest `package.json`

The core configuration of a VSCode extension is declared in `package.json`. Let's see what capabilities the OpenCode extension registers:

```json
{
  "name": "opencode",
  "displayName": "opencode",
  "description": "opencode for VS Code",
  "version": "1.1.56",
  "publisher": "sst-dev",
  "engines": {
    "vscode": "^1.94.0"
  },
  "main": "./dist/extension.js",
  "contributes": {
    "commands": [
      {
        "command": "opencode.openTerminal",
        "title": "Open opencode",
        "icon": {
          "light": "images/button-dark.svg",
          "dark": "images/button-light.svg"
        }
      },
      {
        "command": "opencode.openNewTerminal",
        "title": "Open opencode in new tab",
        "icon": {
          "light": "images/button-dark.svg",
          "dark": "images/button-light.svg"
        }
      },
      {
        "command": "opencode.addFilepathToTerminal",
        "title": "Add Filepath to Terminal"
      }
    ],
    "menus": {
      "editor/title": [
        {
          "command": "opencode.openNewTerminal",
          "group": "navigation"
        }
      ]
    },
    "keybindings": [
      {
        "command": "opencode.openTerminal",
        "key": "cmd+escape",
        "mac": "cmd+escape",
        "win": "ctrl+escape",
        "linux": "ctrl+escape"
      },
      {
        "command": "opencode.openNewTerminal",
        "key": "cmd+shift+escape",
        "mac": "cmd+shift+escape",
        "win": "ctrl+shift+escape",
        "linux": "ctrl+shift+escape"
      },
      {
        "command": "opencode.addFilepathToTerminal",
        "key": "cmd+alt+k",
        "mac": "cmd+alt+k",
        "win": "ctrl+alt+K",
        "linux": "ctrl+alt+K"
      }
    ]
  }
}
```

From this configuration, we can extract the following key information:

| Command                          | Shortcut           | Function                                   |
| -------------------------------- | ------------------ | ------------------------------------------ |
| `opencode.openTerminal`          | `Cmd+Escape`       | Open/focus the OpenCode terminal           |
| `opencode.openNewTerminal`       | `Cmd+Shift+Escape` | Open OpenCode in a new tab                 |
| `opencode.addFilepathToTerminal` | `Cmd+Alt+K`        | Send the current file path to the terminal |

Note the `menus.editor/title` configuration -- the `openNewTerminal` command is placed in the navigation group of the editor title bar, meaning users can see an OpenCode button in the upper-right corner of the editor.

### Design Philosophy: Terminal as Interface

Most AI programming assistant VSCode extensions choose one or more of the following integration approaches:

1. **WebView Panel**: Embed a complete web interface in the sidebar (like GitHub Copilot Chat)
2. **Language Server Protocol (LSP)**: Provide completions, diagnostics, and other features via LSP
3. **Inline Suggestions**: Display AI suggestions directly in the editor (like Copilot's Ghost Text)

OpenCode's extension chose a completely different path: **reuse VSCode's built-in terminal**. The logic behind this decision is:

* OpenCode itself is a fully-featured TUI application with a rich interactive interface
* The TUI already handles all complex UI logic (message display, tool call progress, permission confirmation, etc.)
* Running OpenCode in a VSCode terminal provides an experience identical to running it in a standalone terminal
* Extension complexity is extremely low, with near-zero maintenance cost

> **Extended Explanation -- VSCode Extension API Lifecycle**
>
> VSCode extensions have two core lifecycle functions:
>
> * `activate(context)`: Called when the extension is activated. VSCode decides when to activate an extension based on the `activationEvents` configuration. If `activationEvents` is an empty array (as with OpenCode), the extension is activated immediately when VSCode starts.
> * `deactivate()`: Called when the extension is deactivated, used for resource cleanup.
>
> `context.subscriptions` is a Disposable array used to register resources that should be automatically cleaned up when the extension is deactivated. Pushing command handlers into it ensures that command bindings are properly removed when the extension is unloaded.

## 16.1.2 Communication with OpenCode Server

### HTTP-Based Terminal Communication Architecture

The communication architecture of the OpenCode VSCode extension can be illustrated as follows:

```
┌─────────────────────────────────────────────────┐
│                   VSCode                         │
│                                                  │
│  ┌──────────────┐         ┌──────────────────┐  │
│  │  Extension    │──HTTP──>│  VSCode Terminal  │  │
│  │  (TypeScript) │         │  (opencode TUI)   │  │
│  │              │<──poll──│  port: random port │  │
│  └──────────────┘         └──────────────────┘  │
│         │                         │              │
│         │ registerCommand()       │ sendText()   │
│         ▼                         ▼              │
│  ┌──────────────┐         ┌──────────────────┐  │
│  │  Command      │         │  OpenCode Process │  │
│  │  Palette      │         │  HTTP Server      │  │
│  │  Keybindings  │         │  /tui/append-prompt│  │
│  └──────────────┘         └──────────────────┘  │
└─────────────────────────────────────────────────┘
```

The core communication flow is as follows:

1. **The extension creates a terminal**, injecting a random port number into the terminal's environment variables
2. **The terminal executes `opencode --port <port>`**, OpenCode starts the TUI and opens an HTTP server on the specified port
3. **The extension polls the health check endpoint** `http://localhost:<port>/app` to confirm the TUI is ready
4. **Subsequent communication** sends content via `POST http://localhost:<port>/tui/append-prompt`

### Port Selection Strategy

```typescript
const port = Math.floor(Math.random() * (65535 - 16384 + 1)) + 16384
```

The extension uses a random port number in the range 16384 to 65535. This is the **dynamic/private port range** (also known as ephemeral ports) defined by IANA (Internet Assigned Numbers Authority), avoiding conflicts with system services and well-known application ports.

> **Extended Explanation -- Port Number Allocation**
>
> TCP/UDP port numbers range from 0-65535, divided into three segments:
>
> * **0-1023**: System/privileged ports (Well-Known Ports), requiring root privileges, such as HTTP(80), HTTPS(443), SSH(22)
> * **1024-49151**: Registered Ports, assigned to specific services, such as MySQL(3306), PostgreSQL(5432)
> * **49152-65535**: Dynamic/Ephemeral Ports, freely usable
>
> OpenCode's choice of the 16384-65535 range is slightly aggressive (it includes part of the registered port region), but in practice the collision probability is extremely low. The operating system's TCP stack will also prevent binding to ports that are already in use.

### Readiness Detection Mechanism

The OpenCode TUI takes time to start (loading configuration, initializing subsystems, etc.), so the extension cannot send requests immediately. The polling mechanism solves this problem:

```typescript
let tries = 10
let connected = false
do {
  await new Promise((resolve) => setTimeout(resolve, 200))
  try {
    await fetch(`http://localhost:${port}/app`)
    connected = true
    break
  } catch (e) {}
  tries--
} while (tries > 0)
```

The strategy is simple: try once every 200 milliseconds, up to 10 times (a maximum wait of 2 seconds total). If OpenCode is not ready within 2 seconds, it gives up on injecting the initial file path (the terminal itself is still usable, and users can type manually).

### `appendPrompt`: Lightweight IPC

```typescript
async function appendPrompt(port: number, text: string) {
  await fetch(`http://localhost:${port}/tui/append-prompt`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ text }),
  })
}
```

This is the most critical function in the entire communication mechanism. It sends a POST request to the OpenCode TUI's HTTP endpoint, with the request body being a simple JSON object `{ text: "..." }`. Upon receiving it, the TUI appends the text to the current input field (rather than submitting it directly), so users can still edit or supplement the content before sending.

> **Extended Explanation -- Inter-Process Communication (IPC)**
>
> Inter-Process Communication (IPC) is a mechanism in operating systems for exchanging data between different processes. Common IPC methods include:

| Method        | Characteristics                        | Use Cases                |
| ------------- | -------------------------------------- | ------------------------ |
| Pipe          | Unidirectional, parent-child processes | Simple data streams      |
| Socket        | Bidirectional, cross-network           | Network communication    |
| Shared Memory | Fastest, requires synchronization      | Large data exchange      |
| HTTP/REST     | Standardized, cross-language           | Loosely coupled services |
| WebSocket     | Bidirectional real-time                | Push notifications       |

> OpenCode chose HTTP over WebSocket or Unix Socket because:
>
> 1. Communication is unidirectional (extension -> TUI), the TUI does not need to proactively push to the extension
> 2. HTTP is the simplest and most convenient protocol for debugging
> 3. The `fetch` API is available in all JavaScript runtimes

## 16.1.3 Core Feature Implementation

Let's analyze the three commands registered by the extension one by one.

### Command One: `opencode.openTerminal` -- Open or Focus Terminal

```typescript
let openTerminalDisposable = vscode.commands.registerCommand(
  "opencode.openTerminal",
  async () => {
    // Check if a terminal named "opencode" already exists
    const existingTerminal = vscode.window.terminals.find(
      (t) => t.name === TERMINAL_NAME
    )
    if (existingTerminal) {
      existingTerminal.show()
      return
    }

    await openTerminal()
  }
)
```

This command implements **idempotency** -- if an OpenCode terminal already exists, it simply focuses it; otherwise it creates a new one. This is the most frequently used command, bound to `Cmd+Escape`, forming a "quick toggle" interaction pattern: press once to switch to OpenCode, press again to return to the editor.

### Command Two: `opencode.openNewTerminal` -- Force Open New Terminal

```typescript
let openNewTerminalDisposable = vscode.commands.registerCommand(
  "opencode.openNewTerminal",
  async () => {
    await openTerminal()
  }
)
```

Directly calls `openTerminal()` to create a new instance. Users may need to run multiple OpenCode instances simultaneously for different tasks.

### Core Function: `openTerminal()`

```typescript
async function openTerminal() {
  const port = Math.floor(Math.random() * (65535 - 16384 + 1)) + 16384
  const terminal = vscode.window.createTerminal({
    name: TERMINAL_NAME,
    iconPath: {
      light: vscode.Uri.file(context.asAbsolutePath("images/button-dark.svg")),
      dark: vscode.Uri.file(context.asAbsolutePath("images/button-light.svg")),
    },
    location: {
      viewColumn: vscode.ViewColumn.Beside,
      preserveFocus: false,
    },
    env: {
      _EXTENSION_OPENCODE_PORT: port.toString(),
      OPENCODE_CALLER: "vscode",
    },
  })

  terminal.show()
  terminal.sendText(`opencode --port ${port}`)

  // ... readiness detection and initial file path injection ...
}
```

Several key design decisions in this function:

1. **Terminal Location**: `viewColumn: vscode.ViewColumn.Beside` means it opens in a split pane next to the editor, not in the bottom panel. This allows users to see both code and OpenCode's output simultaneously.
2. **Environment Variable Injection**:
   * `_EXTENSION_OPENCODE_PORT`: Passes the random port number to the terminal environment, so subsequent `addFilepathToTerminal` commands can find the correct communication port
   * `OPENCODE_CALLER: "vscode"`: Informs OpenCode that it was launched from the VSCode extension. OpenCode can adjust its behavior accordingly
3. **`sendText` to Start OpenCode**: `terminal.sendText(\`opencode --port ${port}\`)`sends command text to the terminal, just as if the user had typed it manually. This is more flexible than using`shellPath`/`shellArgs`, because OpenCode runs in the user's shell environment and can inherit` PATH\`, shell configuration, etc.
4. **Initial File Path Injection**: After creating the terminal, if there is a file open in the current editor, the file path is automatically sent to OpenCode, creating a "start conversation in the context of the current file" experience:

```typescript
const fileRef = getActiveFile()
if (!fileRef) {
  return
}

// Wait for TUI to be ready
let tries = 10
let connected = false
do {
  await new Promise((resolve) => setTimeout(resolve, 200))
  try {
    await fetch(`http://localhost:${port}/app`)
    connected = true
    break
  } catch (e) {}
  tries--
} while (tries > 0)

if (connected) {
  await appendPrompt(port, `In ${fileRef}`)
  terminal.show()
}
```

### Command Three: `opencode.addFilepathToTerminal` -- Send File Path

This is the most interesting command, as it establishes a context bridge between the VSCode editor and the OpenCode terminal:

```typescript
let addFilepathDisposable = vscode.commands.registerCommand(
  "opencode.addFilepathToTerminal",
  async () => {
    const fileRef = getActiveFile()
    if (!fileRef) {
      return
    }

    const terminal = vscode.window.activeTerminal
    if (!terminal) {
      return
    }

    if (terminal.name === TERMINAL_NAME) {
      // @ts-ignore
      const port = terminal.creationOptions.env?.["_EXTENSION_OPENCODE_PORT"]
      port
        ? await appendPrompt(parseInt(port), fileRef)
        : terminal.sendText(fileRef, false)
      terminal.show()
    }
  }
)
```

There is an elegant fallback strategy here:

* If the port number can be obtained (via `creationOptions.env`), it uses HTTP to append the file path to the input field
* If it cannot be obtained (e.g., the terminal was manually created by the user), it uses `sendText(fileRef, false)` to send text directly to the terminal (the second argument `false` means it does not automatically press Enter)

Note the `@ts-ignore` comment -- `creationOptions.env` may not be a public API in VSCode's type definitions. The OpenCode team chose to bypass the type check to access it. This is a pragmatic but risky approach.

### `getActiveFile()`: Smart File Reference Generation

```typescript
function getActiveFile() {
  const activeEditor = vscode.window.activeTextEditor
  if (!activeEditor) {
    return
  }

  const document = activeEditor.document
  const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri)
  if (!workspaceFolder) {
    return
  }

  // Get path relative to workspace root
  const relativePath = vscode.workspace.asRelativePath(document.uri)
  let filepathWithAt = `@${relativePath}`

  // Check for selection and add line numbers
  const selection = activeEditor.selection
  if (!selection.isEmpty) {
    const startLine = selection.start.line + 1  // Convert to 1-based line numbers
    const endLine = selection.end.line + 1

    if (startLine === endLine) {
      filepathWithAt += `#L${startLine}`      // Single line selection
    } else {
      filepathWithAt += `#L${startLine}-${endLine}`  // Multi-line selection
    }
  }

  return filepathWithAt
}
```

The file reference format generated by this function is consistent with GitHub's file line number link format:

* `@src/index.ts` -- Reference the entire file
* `@src/index.ts#L42` -- Reference line 42
* `@src/index.ts#L10-25` -- Reference lines 10-25

This `@` prefix format is OpenCode's "at-mention" syntax -- using `@path/to/file` in a prompt causes OpenCode to automatically read and inject the file content as context into the conversation. This way, when users press `Cmd+Alt+K`, the currently edited file automatically becomes the context for the AI conversation.

## 16.1.4 Summary

OpenCode's VSCode extension is a minimalist IDE integration solution. Its entire source code is only 138 lines, yet it implements three core features: terminal management, HTTP communication, and context passing. This "terminal as interface" design philosophy has several aspects worth learning from:

1. **Minimum Complexity Principle**: Do not re-implement functionality that the TUI already provides in the extension layer
2. **Loosely Coupled Architecture**: The extension and the OpenCode process communicate via HTTP, independent of each other
3. **Graceful Degradation**: Falls back to `sendText` when HTTP is unavailable
4. **Environment Variable Bridging**: Passes port information between processes via `_EXTENSION_OPENCODE_PORT`

However, this approach also has obvious limitations -- it cannot implement IDE-inline code suggestions, real-time diagnostics, code actions, and other deep integration features. These capabilities require more powerful protocol support, which is precisely what the Zed extension and ACP protocol aim to address.

In the next section, we will see that the Zed editor takes a completely different integration approach -- declarative configuration plus ACP protocol communication.
