[日本語版](../../user-guide/cli-setup-guide.md)

# CommandMate CLI Setup Guide

This guide explains how to install and get started with CommandMate via npm.

---

## Table of Contents

1. [Prerequisites](#prerequisites)
2. [Installation](#installation)
3. [Initial Setup](#initial-setup)
4. [Starting and Stopping the Server](#starting-and-stopping-the-server)
5. [CLI Command Reference](#cli-command-reference)
6. [Troubleshooting](#troubleshooting)
7. [Upgrading](#upgrading)
8. [Uninstalling](#uninstalling)

---

## Prerequisites

The following tools are required to use CommandMate.

| Tool | Version | Required | Check Command |
|------|---------|----------|---------------|
| Node.js | v22+ | Yes | `node -v` |
| npm | - | Yes | `npm -v` |
| Git | - | Yes | `git --version` |
| tmux | - | Yes | `tmux -V` |
| gh CLI | - | Optional | `gh --version` |
| Claude Code | - | Optional | `claude --version` |
| Codex CLI | - | Optional | `codex --version` |
| Gemini CLI | - | Optional | `gemini --version` |
| GitHub Copilot CLI | - | Optional | `copilot --version` |
| OpenCode | - | Optional | `opencode --version` |
| Antigravity CLI | - | Optional | `agy --version` (only with the declaration `CM_ANTIGRAVITY_USAGE=api-key` / `enterprise`; otherwise only whether it is on PATH) |
| Command Code CLI | - | Optional | `commandcode --version` |

Every agent CLI is optional. CommandMate starts with none of them installed, but a
worktree cannot start a session for an agent whose CLI is missing.
`commandmate init` reports a version (or "not found") for every row above. Antigravity CLI is the one exception: without the declaration neither `init` nor `quickstart` starts `agy` (no `agy --version`), and `init` (and `quickstart` when there is no `.env` yet and it runs the `init` steps) reports only whether it is on PATH (`found (version not checked; …)`) or not found (out of care for Section 6 of the Google Antigravity Additional Terms; Issue #4480).

> **Note**: `vibe-local` is a seat for a local script driving an Ollama model.
> There is no published artifact to check, so `init` does not check for one.

### Checking Prerequisites

```bash
# Check all dependencies
node -v && npm -v && git --version && tmux -V
```

### Installing Each Tool

#### macOS

```bash
# Using Homebrew
brew install node git tmux
```

#### Ubuntu/Debian

```bash
sudo apt update
sudo apt install nodejs npm git tmux
```

#### Agent CLIs

Install only the agents you intend to use — one line per agent.

```bash
npm install -g @anthropic-ai/claude-code   # Claude Code (claude)
npm install -g @openai/codex               # Codex CLI (codex)
npm install -g @google/gemini-cli          # Gemini CLI (gemini)
npm install -g opencode-ai                 # OpenCode (opencode)
npm install -g @opencode/cli               # OpenCode V2 (opencode2)
npm install -g command-code                # Command Code CLI (commandcode)
brew install copilot-cli                   # GitHub Copilot CLI (copilot)
                                           # or: npm i -g @github/copilot
```

The Antigravity CLI (`agy`) is not published on npm. See the
[official documentation](https://antigravity.google/docs/cli/reference) for how to get it.

> **Note**: The `command-code` package installs four executables — `cmd`, `cmdc`,
> `command-code` and `commandcode`. CommandMate launches `commandcode`, because
> `cmd` collides with the Windows shell.

#### OpenCode (1.x) and OpenCode V2 side by side

What OpenCode V2 can do, how it differs from 1.x and what it cannot do yet are in the [OpenCode V2 guide](./opencode-v2.md).

OpenCode V2 (the `OpenCode V2` agent) is installed with `npm install -g @opencode/cli`. That package
registers **two** executables, `opencode2` **and `opencode`**. So installing V2 puts a second `opencode`
on `PATH` next to OpenCode 1.x's (`opencode-ai`, or the `~/.opencode/bin` installer), and which one runs
is decided by nothing but the order of `PATH`.

CommandMate tells them apart by what `--version` prints, not by the name.

| Agent | Counted as installed when | Launched with |
|---|---|---|
| OpenCode | an `opencode` on `PATH` answers `--version` with `1.x` (e.g. `1.18.33`) | its absolute path |
| OpenCode V2 | `opencode2`; failing that, an `opencode` that answers `opencode v2.x` | its absolute path |

When `opencode` points only at V2, OpenCode counts as not installed, and starting it says why (that
`opencode` is OpenCode V2). When V2 is installed under the `opencode` name only, OpenCode V2 cannot use
its wrapper (which starts `opencode2` by name) and launches with `--standalone`, without structured events.

**V2 self-update**: in the OpenCode V2 sessions CommandMate starts, V2's own update check is turned off
(`OPENCODE_DISABLE_AUTOUPDATE=1` and `COREPACK_ENABLE_AUTO_PIN=0`). On start V2 checks for updates by
running `pnpm` / `yarn` and the like in the directory it was started from, and where those are corepack
shims they write a `"packageManager"` field into the project's `package.json`. Update V2 with
`npm install -g @opencode/cli`.

**Shared data**: OpenCode 1.x and V2 use the same `~/.local/share/opencode/opencode.db`. V2 rebuilds
tables in it, so after V2 has run, OpenCode 1.x can fail to start with `no such column: …`. CommandMate
then reads opencode's log (`~/.local/share/opencode/log/opencode.log`) and shows that cause as the start
error. When both are installed, the "Default agents for new branches" card on the More screen also shows
a one-line notice. This is opencode's problem and CommandMate cannot repair the database. Either:

- **Use one of them.** For V2 only, uninstall OpenCode 1.x; for 1.x only, remove V2 with
  `npm uninstall -g @opencode/cli`.
- **Give OpenCode 1.x its own data directory.** OpenCode 1.x keeps its data under `XDG_DATA_HOME`, so put
  a wrapper named `opencode` early on `PATH` that runs the 1.x binary with a different one (1.x's login
  moves with it, so log in again in 1.x):

  ```bash
  #!/bin/sh
  # e.g. ~/bin/opencode, with ~/bin first on PATH
  XDG_DATA_HOME="$HOME/.local/share/opencode-v1" exec "$HOME/.opencode/bin/opencode" "$@"
  ```

  CommandMate asks the wrapper for `--version` too; it answers `1.x`, so it is launched as OpenCode.

Starting an agent that is not installed answers with both facts — that it is
missing, and **how to install it** — in one sentence. For example:

```text
Command Code CLI (commandcode) is not installed or not in PATH. Install with: npm install -g command-code
```

> **Note**: Native Windows is not supported because CommandMate depends on tmux. On Windows, run CommandMate inside WSL2 — see the [WSL2 Setup Guide](./wsl2-setup.md).

---

## Installation

Install globally using npm.

```bash
npm install -g commandmate
```

Verify the installation:

```bash
commandmate --version
```

### Trying it first with `npx`

```bash
npx commandmate@latest
```

Always write `npx commandmate@latest`, not bare `npx commandmate`. If CommandMate is already
installed globally, bare `npx commandmate` runs that existing binary without ever checking the
registry, so you silently keep running an old version. `@latest` forces npx to resolve the newest
release. This only affects `npx` — `npm install -g commandmate` always resolves from the registry.

For anything beyond a first look, prefer the global install. `npx` unpacks CommandMate into the npm
cache, and `commandmate start --daemon` runs the background server out of that cache directory — a
later `npx` run or a cache clean can delete it out from under the running server.

Running `commandmate` with no arguments walks you through the whole first run: it checks
your dependencies, asks a few setup questions on first use, starts the server in the
background, waits for it to come up, and opens the UI in your browser.
Run it again later and it skips straight to opening the UI (or tells you the server is
already running).

- Already have a `.env`? The setup questions are skipped.
- Don't want the browser to open? Use `commandmate --no-open` (also skipped automatically
  on CI and headless sessions).
- Windows: CommandMate depends on tmux, so it runs on Windows via WSL2 (native Windows is not
  supported). See the [WSL2 Setup Guide](./wsl2-setup.md).

### Developer setup (from source)

For contributors or those building a development environment:

```bash
git clone https://github.com/Kewton/CommandMate.git
cd CommandMate
./scripts/setup.sh  # Auto-runs dependency check, env setup, build, and launch
```

Manual setup (for customization):

```bash
git clone https://github.com/Kewton/CommandMate.git
cd CommandMate
./scripts/preflight-check.sh          # Dependency check
npm install
./scripts/setup-env.sh                # Interactive .env generation
npm run db:init
npm run build
npm start
```

> **Note**: `./scripts/*` scripts are only available in the development environment. For global
> installs (`npm install -g`), use the `commandmate` CLI.

---

## Initial Setup

### Interactive Mode (recommended)

```bash
commandmate init
```

The interactive setup configures:
- Worktree root directory
- Server port (default: 3000)
- External access permission (for mobile access)
- Authentication token (auto-generated when external access is enabled)

### Non-interactive Mode

To set up with default values:

```bash
commandmate init --defaults
```

### Overwriting Existing Configuration

To overwrite existing settings:

```bash
commandmate init --force
```

---

## Starting and Stopping the Server

### Starting the Server

#### Background Start (recommended)

```bash
commandmate start --daemon
```

#### Foreground Start

```bash
commandmate start
```

#### Development Mode

```bash
commandmate start --dev
```

#### Start on a Specific Port

```bash
commandmate start --port 3001
```

### Checking Server Status

```bash
commandmate status              # Main server status
commandmate status --all        # All servers (main + worktrees)
commandmate status --issue 135  # Worktree server for Issue #135
```

### Stopping the Server

```bash
commandmate stop                # Stop the main server
commandmate stop --issue 135    # Stop the worktree server for Issue #135
```

#### Force Stop

```bash
commandmate stop --force
```

### Accessing via Browser

After starting the server, open your browser at:

```
http://127.0.0.1:3000
```

> **Port change**: Use the port specified with the `--port` option.

> **`127.0.0.1`, not `localhost`**: CommandMate binds `127.0.0.1` by default (`CM_BIND`).
> On macOS and elsewhere `localhost` resolves to `::1` (IPv6) first, which CommandMate does
> not listen on — if another process holds `::1:3000`, your browser silently talks to it
> instead. The startup self-check reports this in the server log and in `commandmate status`.

---

## CLI Command Reference

### commandmate --version

Display the version.

```bash
commandmate --version
```

### commandmate init

Perform initial setup.

```bash
commandmate init [options]
```

| Option | Description |
|--------|-------------|
| `--defaults` | Set up non-interactively with default values |
| `--force` | Overwrite existing settings |

### commandmate start

Start the server.

```bash
commandmate start [options]
```

| Option | Description |
|--------|-------------|
| `--daemon` | Start in background |
| `--dev` | Start in development mode |
| `-p, --port <number>` | Specify port (default: 3000) |
| `-i, --issue <number>` | Start a server for a specific issue worktree (Issue #136) |
| `--auto-port` | Automatically allocate a port for the worktree server (Issue #136) |
| `--auth` | Enable token authentication (Issue #331) |
| `--auth-expire <duration>` | Token expiration (e.g., `24h`, `7d`, `90m`) |
| `--https` | Enable HTTPS |
| `--cert <path>` | Path to TLS certificate file |
| `--key <path>` | Path to TLS private key file |
| `--allow-http` | Suppress the HTTPS warning when using `--auth` without certificates |
| `--allowed-ips <cidrs>` | Allowed IP addresses/CIDR ranges (comma-separated, Issue #331) |
| `--trust-proxy` | Trust the `X-Forwarded-For` header from a reverse proxy |

#### Parallel Worktree Development (Issue #136)

Run an independent server per worktree.

```bash
commandmate start --issue 135 --auto-port  # Start a server for Issue #135 (auto port)
commandmate start --issue 135 --port 3135  # Start on a specific port
```

#### Authentication / External Access (Issue #331)

```bash
commandmate start --auth --auth-expire 24h          # Token auth (24h expiry)
commandmate start --auth --allowed-ips 192.168.1.0/24  # With IP restriction
commandmate start --https --cert ./cert.pem --key ./key.pem  # HTTPS
```

### commandmate stop

Stop the server.

```bash
commandmate stop [options]
```

| Option | Description |
|--------|-------------|
| `-f, --force` | Force stop (SIGKILL) |
| `-i, --issue <number>` | Stop the server for a specific issue worktree (Issue #136) |

### commandmate status

Display server status.

```bash
commandmate status [options]
```

| Option | Description |
|--------|-------------|
| `-i, --issue <number>` | Show status for a specific issue worktree (Issue #136) |
| `-a, --all` | Show status for all servers (main + worktrees) |

For a running server (or one with a stale PID file) it also prints a `Log:` line with the file `start --daemon` writes the server's output to.

### commandmate update

Update CommandMate to the latest version (stop -> `npm install -g commandmate@latest` -> restart).

```bash
commandmate update [options]
```

| Option | Description |
|--------|-------------|
| `--check` | Only check for updates (no install, stop or restart) |
| `-y, --yes` | Skip the confirmation prompt (required for non-interactive use) |

See [Upgrading](#upgrading) for details and caveats.

### commandmate issue

GitHub Issue management command (requires gh CLI).

```bash
commandmate issue create [options]
commandmate issue search <query>
commandmate issue list
```

| Subcommand | Description |
|------------|-------------|
| `create` | Create a new Issue |
| `search <query>` | Search Issues |
| `list` | List Issues |

#### create options

| Option | Description |
|--------|-------------|
| `--title <title>` | Issue title |
| `--body <body>` | Issue body |
| `--bug` | Use Bug Report template |
| `--feature` | Use Feature Request template |
| `--question` | Use Question template |
| `--labels <labels>` | Labels (comma-separated) |

### commandmate docs

Display CommandMate documentation.

```bash
commandmate docs [options]
```

| Option | Description |
|--------|-------------|
| `--section <name>` | Display specified section content |
| `--search <query>` | Search within documentation |
| `--all` | List all available sections |

---

## Troubleshooting

Sessions that look stuck, a bare `tmux attach` that looks empty, phone access and other common
questions are collected in [Troubleshooting & FAQ](./troubleshooting.md).

### command not found Error

If you see `commandmate: command not found`:

```bash
# Check npm global bin path
npm config get prefix

# Add to PATH (bash/zsh)
export PATH="$(npm config get prefix)/bin:$PATH"

# Persist (~/.bashrc or ~/.zshrc)
echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
```

### Permission Error (EACCES)

If you get a permission error with `npm install -g`:

#### Method 1: Change npm prefix (recommended)

```bash
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH

# Persist
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
source ~/.zshrc

# Reinstall
npm install -g commandmate
```

#### Method 2: Use sudo (not recommended)

```bash
sudo npm install -g commandmate
```

### Port Conflict

If you see `Error: Port 3000 is already in use`:

```bash
# Start on a different port
commandmate start --port 3001

# Or check and stop the process listening on the port
# (without -sTCP:LISTEN this also stops clients merely connected to it, such as your browser)
lsof -nP -iTCP:3000 -sTCP:LISTEN
lsof -nP -iTCP:3000 -sTCP:LISTEN -t | xargs kill -9
```

### Server Won't Start

```bash
# Check status
commandmate status

# Force stop and restart
commandmate stop --force
commandmate start --daemon

# Check logs (in config directory; commandmate status also prints the path on its Log: line)
tail -f ~/.commandmate/logs/server.log
# a parallel server started with --issue 135 has its own file
tail -f ~/.commandmate/logs/server-135.log
```

`commandmate start --daemon` (and `commandmate update`, which restarts through it) appends the server's stdout and stderr to `logs/server.log` in the config directory (`logs/server-<N>.log` for an `--issue <N>` server). The file is owner-only (0600), and so are the rotated `server.log.1` and later generations (an existing 0640 file written by `scripts/start.sh` is tightened to 0600 when the CLI daemon opens or rotates it). Each start writes a separator line (`=== <timestamp> commandmate start --daemon ... ===`).

- **Rotation**: at start, a log of 10MB or more is moved to `server.log.1`, shifting older generations to `.2` and `.3` (three generations kept, the same approach as `scripts/build-and-start.sh`). It is not rotated while the server runs, so a long-running server's log can grow past 10MB.
- If the log file cannot be opened (the directory cannot be created, a symbolic link is in the way, etc.), a warning is printed and the server starts with its output discarded.
- `CM_LOG_DIR` does not move this file (`CM_LOG_DIR` is a separate setting, used by the server for conversation logs and by the CLI for its security log).
- A foreground start (`commandmate start`) prints to the terminal only and does not write this file.

### Dependency Errors

```bash
# tmux not found
brew install tmux  # macOS
sudo apt install tmux  # Ubuntu/Debian

# Node.js version too old
node -v  # v22+ required
```

### Database Errors

```bash
# Reset database (data will be deleted)
rm -rf ~/.commandmate/data
commandmate init --force
```

---

## Upgrading

If CommandMate is installed globally (`npm install -g commandmate`), a single `commandmate update` upgrades it.

```bash
commandmate update
```

In a global install, it runs the following steps:

1. Query the npm registry for the latest version and compare it with the current one
2. Only when an update exists, print the caveats and ask for confirmation (defaults to no)
3. Stop the server if it is running
4. Run `npm install -g commandmate@latest`
5. Verify that the installed version matches the latest version
6. Restart the server it stopped and wait for it to respond (up to 30 seconds)

If the server was not running beforehand, it is not started for you.
If you are already up to date, if your local version is newer, or if either version is a prerelease, the update is skipped.

### Checking for Updates Only

`--check` prints the versions and changes nothing.

```bash
commandmate update --check
```

```
Current: v0.9.0
Latest: v0.10.0
Update available: yes
```

### Non-interactive Use

Use `--yes` to skip the confirmation prompt.

```bash
commandmate update --yes
```

Without `--yes` in an environment that has no TTY (CI, scripts), nothing is updated and the command exits with code `2`.

### Caveats

- **Startup options are not restored**: after the restart the server only uses the settings in `.env`. If you started it with `--auth`, `--auth-expire`, `--cert`, `--key`, `--allow-http`, `--allowed-ips`, `--trust-proxy`, `--port` or `--dev`, start it again manually after the update (`--auth` generates a new token on every start, so existing tokens are invalidated).
- **Worktree servers (`--issue`) are not stopped or restarted for you**: `npm install -g` replaces the package directory (`dist/`, `.next/`), so a running worktree server may crash. Stop them **before** updating with `commandmate stop --issue <number>` and restart them afterwards with `commandmate start --issue <number>`. The command warns you when it detects running worktree servers.
- **Permission errors (EACCES)**: do not re-run with `sudo`. Fix the npm global directory permissions as described in [Permission Error (EACCES)](#permission-error-eacces), then run `commandmate update` again.
- **When authentication is enabled**: the post-restart check degrades to "the server responds" and finishes with a warning instead of a strict readiness check. Set `CM_AUTH_TOKEN` for the strict check (IP restrictions and self-signed certificates degrade it the same way).
- **If the update fails**: the command prints a rollback command for the version you had before (`npm install -g commandmate@<previous-version>`). If the server cannot be stopped, the update aborts without changing anything.

### Upgrading Manually (fallback)

If you cannot use `commandmate update`, upgrade manually as before.

```bash
commandmate stop
npm install -g commandmate@latest
commandmate start --daemon
```

In a git clone (development) environment, `commandmate update` does not update anything; it prints these steps and exits.

```bash
git pull
npm install
npm run build:all
commandmate stop && commandmate start --daemon   # or: npm start
```

> Run `npm run build:all`, not `npm run build`. The latter only builds Next.js and leaves the server (`dist/server`) and the CLI (`dist/cli`) stale.

After upgrading, verify the version:

```bash
commandmate --version
```

---

## Uninstalling

### 1. Stop the Server

```bash
commandmate stop
```

### 2. Uninstall the Package

```bash
npm uninstall -g commandmate
```

### 3. Remove Configuration Files (optional)

```bash
# Completely remove configuration and data
rm -rf ~/.commandmate
```

---

## Next Steps

- [Web App Guide](./webapp-guide.md) - Basic browser operations
- [Quick Start Guide](./quick-start.md) - The minimum contract-and-verify loop, then a five-minute flow
- [Deployment Guide](../../DEPLOYMENT.md) - Production environment deployment

---

## Related Documentation

- [README](../../../README.md) - Project overview
- [Architecture](../../architecture.md) - System design
- [Trust & Safety](../../TRUST_AND_SAFETY.md) - Security and permissions
