Skip to content

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".

On Windows, only a daemon started with daemon start survives independently of the process that launched it. Other background sessions, shell commands, hooks, and tunnels are terminated when their owning CLI exits; neither --bg nor daemon stop --keep-workers removes this lifecycle constraint. Tasks that need to keep running should be hosted by the resident daemon. When the daemon restarts itself, child processes of the old process are terminated, while the new daemon runs independently. Behavior on macOS/Linux remains unchanged.

Concepts

ConceptDescription
WorkerA running CLI process, registered via a PID file in ~/.codebuddy/sessions/
DaemonA 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 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:

TypePathContentTrigger
telemetry~/.codebuddy/logs/{date}/{workspace}.logInfo/Warn/Error from all modulesAlways (default priority)
process~/.codebuddy/logs/{name}.logProcess stdout/stderrbg/daemon only
debug~/.codebuddy/debug/{sessionId}.txtDetailed debug informationRequires --debug
transcript~/.codebuddy/projects/{id}/{sessionId}.jsonlConversation historyAlways

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

VariableDescription
CODEBUDDY_SESSION_KINDWorker type (interactive / bg / daemon)
CODEBUDDY_SESSION_NAMEBackground session display name
CODEBUDDY_SESSION_LOGBackground session log path
CODEBUDDY_GATEWAY_AUTHAuthentication mode (none / password)

System Service Registration

Register the daemon as an OS-level service for automatic startup on login and automatic crash recovery.

Install / Uninstall

bash
# Register as a system service and start the daemon immediately
codebuddy daemon install

# Specify port and permission mode
codebuddy daemon install --port 8080 --permission-mode bypassPermissions

# Remove system service registration
codebuddy daemon uninstall

After installation, codebuddy daemon status will show the system service status:

json
{
  "status": "running",
  "pid": 42567,
  "endpoint": "http://127.0.0.1:9527",
  "systemService": {
    "installed": true,
    "backend": "launchd",
    "configPath": "/Users/xxx/Library/LaunchAgents/com.codebuddy.daemon.plist"
  }
}

Platform Support

PlatformBackendService TypeConfig Path
macOSlaunchdLaunch Agent (user-level)~/Library/LaunchAgents/com.codebuddy.daemon.plist
LinuxsystemdUser Unit~/.config/systemd/user/codebuddy-daemon.service
WindowsTask SchedulerScheduled Task (user-level)schtasks /tn "CodeBuddy Daemon"

All platforms use user-level services, requiring no administrator privileges.

Auto-Update

The system service + auto-update form a complete zero-intervention operations chain:

  1. System login → System service automatically starts the daemon
  2. Hourly → Background checks for new versions and silently installs them
  3. When idle → Forks a new daemon process → Old process exits normally (does not trigger crash restart)
  4. On crash → System service automatically recovers (KeepAlive / Restart=on-failure)

Design details: The system service is configured to restart only on abnormal exit. Auto-update's graceful restart exits with code 0, which does not trigger the system service's restart mechanism—the new process has already been forked by the update process itself.

Management Command Reference

bash
# macOS native management
launchctl list | grep codebuddy
launchctl stop com.codebuddy.daemon
launchctl start com.codebuddy.daemon

# Linux native management
systemctl --user status codebuddy-daemon
systemctl --user stop codebuddy-daemon
systemctl --user start codebuddy-daemon

# Windows native management
schtasks /query /tn "CodeBuddy Daemon"

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 (body uses Gateway Protocol format, must include id/type)
curl -X POST http://127.0.0.1:9090/api/v1/runs \
  -H "Content-Type: application/json" \
  -H "X-CodeBuddy-Request: 1" \
  -d '{"id": "run-1", "type": "message", "payload": {"text": "Review the code changes in this PR"}}'
# Response: {"data": {"runId": "uuid-xxx", "status": "accepted"}}

Note: /api/v1/runs requests must include the X-CodeBuddy-Request header, and the body must use the Gateway Protocol format (id and type are required; the prompt text goes in payload.text). See the HTTP API documentation for field details.

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--servedaemon start
LifecycleTied to terminal, exits when terminal closesBackground resident, independent of terminal
StartupRuns in foregroundForks a detached child process
ManagementStop with Ctrl+Cdaemon stop/status/restart
Multiple startsCreates a new process each timeIdempotent, maintains only one daemon
Typical useTemporary development/debuggingLong-running service