# Daemon Mode and Background Sessions

Daemon mode runs CodeBuddy Code as a **background resident service**, independent of any terminal window. Once started, it provides a full HTTP API and Web UI, ready to accept requests at any time.

**Core value**: Transform the CLI from "use and go" to "always on standby".

## Concepts

| Concept | Description |
|---------|-------------|
| **Worker** | A running CLI process, registered via a PID file in `~/.codebuddy/sessions/` |
| **Daemon** | A background resident HTTP service process (`--serve` mode), managed via `daemon start` |
| **Background Session (bg)** | A non-interactive task started with `--bg`, with output automatically logged to a file |

## Daemon Management

### Starting the Daemon

```bash
# Start the daemon (runs in background, auto-assigns port)
codebuddy daemon start

# Specify a port
codebuddy daemon start --port 8080

# Specify bind address (allow remote access)
codebuddy daemon start --host 0.0.0.0

# Specify permission mode (defaults to delegate mode)
codebuddy daemon start --permission-mode default

# Pass other standard parameters (model, mcp-config, etc. are automatically inherited)
codebuddy daemon start --model claude-sonnet-4-20250514 --mcp-config ./mcp.json
```

Once started, the daemon runs as a detached process and the parent process exits immediately. Local addresses have password-free access by default; non-local addresses automatically enable password authentication.

> **Default delegate mode**: The daemon runs in delegate mode by default—the main agent only handles coordination and scheduling, without directly modifying code. All implementation work is done through subagents. You can switch to other modes via `--permission-mode`.

> **Parameter inheritance**: Standard CLI parameters specified with `daemon start` (`--model`, `--permission-mode`, `--mcp-config`, `--tools`, `--agent`, `--settings`, etc.) are automatically inherited by daemon child processes.

> **Idempotent startup**: Running `daemon start` multiple times does not create multiple daemons. If a daemon is already running, it returns the existing daemon's information.

### Checking Status

```bash
codebuddy daemon status
# {"status":"running","pid":12345,"endpoint":"http://127.0.0.1:51862","startedAt":1775498920401}
```

### Stopping / Restarting

```bash
codebuddy daemon stop
codebuddy daemon restart
```

## Background Sessions

### Starting Background Tasks

```bash
# Execute a task in the background
codebuddy --bg "implement login page"

# Specify a name (easier to find)
codebuddy --bg --name feature-login "implement login page"
```

Background sessions run in `--print -y` mode (no TUI + skip permission confirmations), with stdout/stderr redirected to `~/.codebuddy/logs/{name}.log`.

### Process Management Commands

```bash
# List all active Workers
codebuddy ps

# View background session logs
codebuddy logs feature-login

# Follow logs continuously (similar to tail -f)
codebuddy logs feature-login -f

# Attach to a background session
codebuddy attach feature-login

# Kill a background session
codebuddy kill feature-login
```

## HTTP API

All Worker and Daemon management capabilities are exposed via REST APIs. The Web UI Workers page is built on top of these APIs.

See the Workers & Daemon section in the [HTTP API documentation](http-api.md) for details.

### Examples

```bash
# List all Workers
curl http://127.0.0.1:8080/api/v1/workers

# Start a Daemon
curl -X POST http://127.0.0.1:8080/api/v1/daemon/start \
  -H "Content-Type: application/json" \
  -d '{"port": 9090}'

# View Worker logs (telemetry logs)
curl "http://127.0.0.1:8080/api/v1/workers/12345/logs?type=telemetry&tail=100"

# Kill a Worker
curl -X DELETE http://127.0.0.1:8080/api/v1/workers/12345
```

## Web UI

After starting in `--serve` mode, the Web UI provides three management pages:

- **Workers** — Worker process management and Daemon control
- **Logs** — Standalone log viewer with Worker selection, log type switching, and keyword search
- **Metrics** — System resource monitoring and per-Worker process-level metrics

## Log System

The log API supports 4 types, with automatic priority-based selection:

| Type | Path | Content | Trigger |
|------|------|---------|---------|
| `telemetry` | `~/.codebuddy/logs/{date}/{workspace}.log` | Info/Warn/Error from all modules | Always (default priority) |
| `process` | `~/.codebuddy/logs/{name}.log` | Process stdout/stderr | bg/daemon only |
| `debug` | `~/.codebuddy/debug/{sessionId}.txt` | Detailed debug information | Requires `--debug` |
| `transcript` | `~/.codebuddy/projects/{id}/{sessionId}.jsonl` | Conversation history | Always |

## PID File Registry

Each CLI process registers a PID file in `~/.codebuddy/sessions/` on startup:

```
~/.codebuddy/sessions/
├── 12345.json          # Local process (PID as filename)
├── 67890.json          # Another local process
└── manual-abc123.json  # Manually added remote Worker
```

PID file contents:

```json
{
  "pid": 12345,
  "sessionId": "interactive-12345",
  "cwd": "/home/user/project",
  "startedAt": 1775498920401,
  "kind": "interactive",
  "url": "http://127.0.0.1:8080",
  "mode": "local",
  "version": "2.78.1",
  "hostname": "my-machine"
}
```

Process liveness is detected via `kill -0`. Manually added remote Workers are detected via heartbeat timeout (2 minutes).

## Environment Variables

| Variable | Description |
|----------|-------------|
| `CODEBUDDY_SESSION_KIND` | Worker type (interactive / bg / daemon) |
| `CODEBUDDY_SESSION_NAME` | Background session display name |
| `CODEBUDDY_SESSION_LOG` | Background session log path |
| `CODEBUDDY_GATEWAY_AUTH` | Authentication mode (none / password) |

## Use Cases

### Persistent Development Server

Start a daemon once during daily development, then interact with the AI anytime through the browser or API without opening a terminal each time.

```bash
codebuddy daemon start --port 8080
# Open http://127.0.0.1:8080 in your browser
# The service keeps running after closing the terminal
```

### CI/CD Automation Backend

Start a daemon in a CI pipeline as an Agent service, and have other steps call it via HTTP API for code reviews, test generation, and other tasks.

```bash
# CI startup
codebuddy daemon start --port 9090

# Other CI steps call the API
curl -X POST http://127.0.0.1:9090/api/v1/runs \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Review the code changes in this PR"}'
```

### Shared Agent for Teams

Start a daemon on a development machine bound to a LAN address, allowing team members to share the same Agent environment through the Web UI.

```bash
codebuddy daemon start --host 0.0.0.0 --port 8080
# Colleagues access http://192.168.1.100:8080
```

### Batch Background Tasks

Use `--bg` to start multiple background sessions for different tasks simultaneously, and manage them with `ps`/`logs`/`kill`.

```bash
codebuddy --bg --name "refactor-auth" "refactor the auth module"
codebuddy --bg --name "add-tests" "add unit tests for the utils directory"
codebuddy --bg --name "fix-types" "fix all TypeScript type errors"

# Check progress
codebuddy ps
codebuddy logs refactor-auth
```

### WeChat/WeCom Bot Backend

Run the daemon as a persistent backend service for a chatbot, receiving messages through long-lived connections.

```bash
codebuddy daemon start
# Connect to WeChat/WeCom channels via the remote control feature
```

### IDE Extension Backend

IDE plugins connect to the daemon via the ACP protocol, providing AI-assisted programming without restarting the CLI process each time the IDE is opened.

## Difference from --serve

| Feature | `--serve` | `daemon start` |
|---------|-----------|-----------------|
| Lifecycle | Tied to terminal, exits when terminal closes | Background resident, independent of terminal |
| Startup | Runs in foreground | Forks a detached child process |
| Management | Stop with Ctrl+C | `daemon stop/status/restart` |
| Multiple starts | Creates a new process each time | Idempotent, maintains only one daemon |
| Typical use | Temporary development/debugging | Long-running service |
