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

# 12.1 CLI Startup Flow

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generated on**: 2026-02-17

***

In the previous eleven chapters, we deeply analyzed the core of OpenCode—Session, Tool, Agent, Provider, MCP, permissions, snapshots, the event bus, and other modules. These modules constitute the "engine," but users do not interact with the engine directly—they converse with OpenCode through the **Command-Line Interface (CLI)**. This chapter examines OpenCode's frontend implementation from the perspective of user interaction.

## 12.1.1 Entry File index.ts

OpenCode's CLI entry file is `packages/opencode/src/index.ts`. It uses the **yargs** framework to handle command-line argument parsing and subcommand dispatching:

```typescript
// index.ts
import yargs from "yargs"
import { hideBin } from "yargs/helpers"

const cli = yargs(hideBin(process.argv))
  .parserConfiguration({ "populate--": true })
  .scriptName("opencode")
  .wrap(100)
  .help("help", "show help").alias("help", "h")
  .version("version", "show version number", Installation.VERSION)
  .alias("version", "v")
  .option("print-logs", { describe: "print logs to stderr", type: "boolean" })
  .option("log-level", {
    describe: "log level",
    type: "string",
    choices: ["DEBUG", "INFO", "WARN", "ERROR"],
  })
  .middleware(async (opts) => {
    // Global middleware: initialize the logging system
    await Log.init({
      print: process.argv.includes("--print-logs"),
      dev: Installation.isLocal(),
      level: opts.logLevel ?? (Installation.isLocal() ? "DEBUG" : "INFO"),
    })

    // Set environment variable flags
    process.env.AGENT = "1"
    process.env.OPENCODE = "1"
  })
  .usage("\n" + UI.logo())
  // Register all subcommands
  .command(TuiThreadCommand)    // Default command $0
  .command(RunCommand)           // opencode run
  .command(ServeCommand)         // opencode serve
  .command(WebCommand)           // opencode web
  .command(AuthCommand)          // opencode auth
  .command(McpCommand)           // opencode mcp
  .command(ModelsCommand)        // opencode models
  .command(SessionCommand)       // opencode session
  .command(ExportCommand)        // opencode export
  .command(ImportCommand)        // opencode import
  .command(GenerateCommand)      // opencode generate
  .command(GithubCommand)        // opencode github
  .command(PrCommand)            // opencode pr
  .command(StatsCommand)         // opencode stats
  .command(UpgradeCommand)       // opencode upgrade
  .command(UninstallCommand)     // opencode uninstall
  .command(AcpCommand)           // opencode acp
  .command(AgentCommand)         // opencode agent
  .command(AttachCommand)        // opencode attach
  .strict()

await cli.parse()
```

> **Extended Explanation: What is yargs?**
>
> yargs is one of the most popular command-line argument parsing libraries in the Node.js ecosystem. It provides:
>
> * A subcommand system
> * Argument type validation
> * Automatic help documentation generation
> * Shell auto-completion script generation
> * Middleware support
>
> OpenCode uses the `"populate--": true` configuration, which allows arguments after `--` to be collected into the `args["--"]` array—this is used in the `opencode run` command to pass extra arguments to shell commands.

Several design points are worth noting:

1. **`TuiThreadCommand` uses the `$0` command name**: This means that when users run `opencode` without a subcommand, the TUI interactive interface launches by default.
2. **Global middleware**: The logging system is initialized before any subcommand executes. This ensures that even if a subcommand fails, error logs are properly recorded.
3. **`process.env.AGENT = "1"`**: This sets environment variable flags so that child processes (such as shells started via the `bash` tool) know they are running within an OpenCode environment.

## 12.1.2 cli/bootstrap.ts — Instance Context Bootstrapping

Most subcommands need to initialize OpenCode's Instance context before executing (loading configuration, connecting to storage, initializing modules, etc.). The `bootstrap()` function encapsulates this process:

```typescript
// cli/bootstrap.ts
export async function bootstrap<T>(directory: string, cb: () => Promise<T>) {
  return Instance.provide({
    directory,
    init: InstanceBootstrap,
    fn: async () => {
      try {
        const result = await cb()
        return result
      } finally {
        await Instance.dispose()
      }
    },
  })
}
```

`bootstrap()` does three things:

1. **`Instance.provide()`**: Creates an Instance context under the specified directory and runs the `InstanceBootstrap` initialization function (loading project configuration, detecting Git information, starting file watchers, etc.).
2. **Executes the callback**: Runs the specific command logic within the Instance context.
3. **Cleans up resources**: Regardless of whether the command succeeds or fails (`finally`), it calls `Instance.dispose()` to clean up resources (closing file watchers, clearing timers, disconnecting MCP connections, etc.).

This "acquire context -> execute -> clean up" pattern is similar to how database connections are used—ensuring that resources are never leaked.

## 12.1.3 cli/cmd/cmd.ts — Subcommand Registration

Each subcommand is a yargs `CommandModule`. OpenCode provides a simple type wrapper:

```typescript
// cli/cmd/cmd.ts
type WithDoubleDash<T> = T & { "--"?: string[] }

export function cmd<T, U>(input: CommandModule<T, WithDoubleDash<U>>) {
  return input
}
```

The sole purpose of the `cmd()` function is to add the type definition for the `"--"` parameter. Each subcommand is defined following this pattern:

```typescript
export const MyCommand = cmd({
  command: "mycommand [args]",     // Command name and positional arguments
  describe: "description text",     // Help documentation description
  builder: (yargs) => yargs         // Parameter definitions
    .option("flag", { type: "boolean" }),
  handler: async (args) => {        // Command handler function
    // Execution logic
  },
})
```

## 12.1.4 Overview of All Subcommands

Below is the complete list of 19 subcommands registered by OpenCode:

| Command        | File            | Function                                  |
| -------------- | --------------- | ----------------------------------------- |
| `$0` (default) | `tui/thread.ts` | Launch the TUI interactive interface      |
| `run`          | `run.ts`        | Execute a single prompt (non-interactive) |
| `serve`        | `serve.ts`      | Start a headless HTTP Server              |
| `web`          | `web.ts`        | Start the Server and open the Web UI      |
| `auth`         | `auth.ts`       | Manage authentication credentials         |
| `mcp`          | `mcp.ts`        | MCP Server management                     |
| `models`       | `models.ts`     | List available models                     |
| `session`      | `session.ts`    | Session management                        |
| `export`       | `export.ts`     | Export session data                       |
| `import`       | `import.ts`     | Import session data                       |
| `generate`     | `generate.ts`   | Generate OpenAPI specification            |
| `github`       | `github.ts`     | GitHub integration                        |
| `pr`           | `pr.ts`         | Pull Request operations                   |
| `stats`        | `stats.ts`      | Usage statistics                          |
| `upgrade`      | `upgrade.ts`    | Version upgrade                           |
| `uninstall`    | `uninstall.ts`  | Uninstall cleanup                         |
| `acp`          | `acp.ts`        | Agent Client Protocol                     |
| `agent`        | `agent.ts`      | Agent management                          |
| `attach`       | `tui/attach.ts` | Connect to a running Server               |

These commands can be grouped into four functional categories:

* **Interactive**: `$0` (TUI), `attach`, `web`
* **Execution**: `run`, `pr`, `github`
* **Management**: `auth`, `mcp`, `models`, `session`, `agent`, `export`, `import`, `stats`
* **Infrastructure**: `serve`, `generate`, `upgrade`, `uninstall`, `acp`

## 12.1.5 Error Handling

The `try/catch/finally` block in the entry file handles all uncaught errors:

```typescript
try {
  await cli.parse()
} catch (e) {
  // Collect error information
  let data: Record<string, any> = {}
  if (e instanceof NamedError) {
    Object.assign(data, e.toObject().data)
  }
  if (e instanceof Error) {
    Object.assign(data, { name: e.name, message: e.message, stack: e.stack })
  }

  // Write to logs
  Log.Default.error("fatal", data)

  // Format and display to the user
  const formatted = FormatError(e)
  if (formatted) UI.error(formatted)
  if (formatted === undefined) {
    UI.error("Unexpected error, check log file at " + Log.file() + " for more details")
  }

  process.exitCode = 1
} finally {
  // Explicitly exit to prevent child processes from hanging
  process.exit()
}
```

The `FormatError()` function (defined in `cli/error.ts`) recognizes specific error types and generates user-friendly error messages:

* **MCP Server failure**: Shows which MCP Server failed to start and why.
* **Model not found**: Shows the model name the user specified and suggests alternatives.
* **Provider initialization failure**: Shows which Provider failed to initialize.
* **Configuration file error**: Shows the configuration file path and the specific location of the parsing error.

The final `process.exit()` is a deliberate design decision—the comment explains that it ensures child processes that do not respond to SIGTERM signals (such as MCP Servers running in Docker containers) are properly terminated.
