# Headless Mode

> Run CodeBuddy Code programmatically without an interactive UI

## Overview

Headless mode allows you to run CodeBuddy Code programmatically through command-line scripts and automation tools without any interactive UI.

Headless mode also supports scheduled task capabilities. In script, SDK, or server-side integration scenarios, you can use tools such as `CronCreate`, `CronList`, and `CronDelete` to create, view, and cancel scheduled tasks.

 > **⚠️ Important Note:** `-y` (or `--dangerously-skip-permissions`) is a required parameter for non-interactive mode. When using the `-p/--print` parameter for non-interactive execution, this parameter must be added to perform operations that require authorization (file read/write, command execution, network requests, etc.), otherwise these operations will be blocked. Only use this parameter in trusted environments and explicit task scenarios. See [CLI Reference](cli-reference.md) for details.

## Basic Usage

The primary command-line interface for CodeBuddy Code is the `codebuddy` (or `cbc`) command. Use the `--print` (or `-p`) flag to run in non-interactive mode and print the final result:

```bash
codebuddy -p "Stage my changes and write a set of commits for them" \
  --allowedTools "Bash,Read" \
  --permission-mode acceptEdits
```

## Configuration Options

Headless mode leverages all available CLI options in CodeBuddy Code. Here are key options for automation and scripting:

| Flag                       | Description                                                                                            | Example                                                                                                                   |
| :------------------------- | :----------------------------------------------------------------------------------------------------- | :------------------------------------------------------------------------------------------------------------------------ |
| `--print`, `-p`            | Run in non-interactive mode                                                                            | `codebuddy -p "query"`                                                                                                    |
| `--output-format`          | Specify output format (`text`, `json`, `stream-json`)                                                  | `codebuddy -p --output-format json`                                                                                       |
| `--resume`, `-r`           | Resume a conversation by session ID                                                                    | `codebuddy --resume abc123`                                                                                               |
| `--continue`, `-c`         | Continue the most recent conversation                                                                  | `codebuddy --continue`                                                                                                    |
| `--verbose`                | Enable verbose logging                                                                                 | `codebuddy --verbose`                                                                                                     |
| `--append-system-prompt`   | Append to system prompt (only works with `--print`)                                                    | `codebuddy --append-system-prompt "Custom instructions"`                                                                  |
| `--allowedTools`           | List of allowed tools, space-separated or<br /><br />comma-separated string                            | `codebuddy --allowedTools mcp__slack mcp__filesystem`<br /><br />`codebuddy --allowedTools "Bash(npm install),mcp__filesystem"` |
| `--disallowedTools`        | List of disallowed tools, space-separated or<br /><br />comma-separated string                         | `codebuddy --disallowedTools mcp__splunk mcp__github`<br /><br />`codebuddy --disallowedTools "Bash(git commit),mcp__github"`   |
| `--settings`               | Load additional settings configuration from a JSON file or JSON string                                 | `codebuddy -p --settings '{"model":"gpt-5"}' "query"`                                                                     |
| `--setting-sources`        | Specify which settings sources to load (options: `user`, `project`, `local`)                           | `codebuddy -p --setting-sources project,local "query"`                                                                    |
| `--mcp-config`             | Load MCP servers from a JSON file                                                                      | `codebuddy --mcp-config servers.json`                                                                                     |
| `--permission-prompt-tool` | MCP tool for handling permission prompts (only works with `--print`)                                   | ❌ Not supported                                                                                                          |

> **Note:** The `--permission-prompt-tool` feature is currently not supported.

For a complete list of CLI options and features, please refer to the [CLI Reference](cli-reference.md) documentation.

## Multi-turn Conversations

For multi-turn conversations, you can resume a conversation or continue from the most recent session:

```bash
# Continue the most recent conversation
codebuddy --continue "Now refactor for better performance"

# Resume a specific conversation by session ID
codebuddy --resume 550e8400-e29b-41d4-a716-446655440000 "Update tests"

# Resume in non-interactive mode
codebuddy --resume 550e8400-e29b-41d4-a716-446655440000 "Fix all linting issues" -p
```

## Output Formats

### Text Output (Default)

```bash
codebuddy -p "Explain the file src/components/Header.tsx"
# Output: This is a React component that displays...
```

### JSON Output

Returns structured data with metadata:

```bash
codebuddy -p "How does the data layer work?" --output-format json
```

Response format:

```json
{
 ...
}
```

### Stream JSON Output

Streams as each message is received:

```bash
codebuddy -p "Build an application" --output-format stream-json
```

Each conversation begins with an initial `init` system message, followed by a list of user and assistant messages, and ends with a final `result` system message containing statistics. Each message is emitted as a separate JSON object.

### Structured JSON Output

To get output that conforms to a specific schema, use `--output-format json` with `--json-schema` and a [JSON Schema](https://json-schema.org/) definition. The response includes metadata about the request (session ID, usage, etc.), with the structured output in the `structured_output` field.

This example extracts function names from auth.py and returns them as an array of strings:

```bash
codebuddy -p "Extract the main function names from auth.py" \
  --output-format json \
  --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}'
```

> **Tip**: Use tools like [jq](https://jqlang.github.io/jq/) to parse the response and extract specific fields:
>
> ```bash
> # Extract text result
> codebuddy -p "Summarize this project" --output-format json | jq -r '.result'
>
> # Extract structured output
> codebuddy -p "Extract function names from auth.py" \
>   --output-format json \
>   --json-schema '{"type":"object","properties":{"functions":{"type":"array","items":{"type":"string"}}},"required":["functions"]}' \
>   | jq '.structured_output'
> ```

## Input Formats

### Text Input (Default)

```bash
# Direct argument
codebuddy -p "Explain this code"

# From stdin
echo "Explain this code" | codebuddy -p
```

### Stream JSON Input

A stream of messages provided via `stdin`, where each message represents a user turn. This allows for multi-turn conversations without restarting the `codebuddy` binary, and allows providing guidance to the model while it processes requests.

Each message is a JSON "user message" object following the same format as the output message schema. Messages are formatted using [jsonl](https://jsonlines.org/) format, where each line of input is a complete JSON object. Stream JSON input requires `-p` and `--output-format stream-json`.

```bash
echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Explain this code"}]}}' | \
  codebuddy -p --output-format=stream-json --input-format=stream-json --verbose

# Single message (with image)
echo '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Text prompt, such as referring to the text in the following image"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"raw base64 (without protocol prefix)"}}]}}' \
  | codebuddy -p --input-format stream-json --output-format stream-json

# Multi-turn conversation (multi-line JSON, continuously sent to the same process)
printf '%s\n' \
  '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"First question"}]}}' \
  '{"type":"user","message":{"role":"user","content":[{"type":"text","text":"Second question"}]}}' \
  | codebuddy -p --input-format stream-json --output-format stream-json --verbose
```

## Agent Integration Examples

### SRE Incident Response Bot

```bash
#!/bin/bash

# Automated incident response agent
investigate_incident() {
    local incident_description="$1"
    local severity="${2:-medium}"

    codebuddy -p "Incident: $incident_description (Severity: $severity)" \
      --append-system-prompt "You are an SRE expert. Diagnose the issue, assess impact, and provide immediate action items." \
      --output-format json \
      --allowedTools "Bash,Read,WebSearch,mcp__datadog" \
      --mcp-config monitoring-tools.json
}

# Usage
investigate_incident "Payment API returning 500 errors" "high"
```

### Automated Security Review

```bash
# Security audit agent for PRs
audit_pr() {
    local pr_number="$1"

    gh pr diff "$pr_number" | codebuddy -p \
      --append-system-prompt "You are a security engineer. Review this PR for vulnerabilities, unsafe patterns, and compliance issues." \
      --output-format json \
      --allowedTools "Read,Grep,WebSearch"
}

# Use and save to file
audit_pr 123 > security-report.json
```

### Multi-turn Legal Assistant

```bash
# Legal document review with session persistence
session_id=$(codebuddy -p "Start legal review session" --output-format json | jq -r '.session_id')

# Review contract in multiple steps
codebuddy -p --resume "$session_id" "Review liability clauses in contract.pdf"
codebuddy -p --resume "$session_id" "Check compliance with GDPR requirements"
codebuddy -p --resume "$session_id" "Generate executive summary of risks"
```

## Best Practices

* **Use JSON output format** for programmatically parsing responses:

  ```bash
  # Parse JSON response using jq
  result=$(codebuddy -p "Generate code" --output-format json)
  code=$(echo "$result" | jq -r '.result')
  cost=$(echo "$result" | jq -r '.total_cost_usd')
  ```

* **Handle errors gracefully** - Check exit codes and stderr:

  ```bash
  if ! codebuddy -p "$prompt" 2>error.log; then
      echo "An error occurred:" >&2
      cat error.log >&2
      exit 1
  fi
  ```

* **Use session management** to maintain context across multi-turn conversations

* **Consider timeouts** for long-running operations:

  ```bash
  timeout 300 codebuddy -p "$complex_prompt" || echo "Timed out after 5 minutes"
  ```

* **Respect rate limits** when making multiple requests, by adding delays between calls

* **Use `-y`** to perform operations requiring authorization in non-interactive mode:

  ```bash
  # Complete example in non-interactive mode
  codebuddy -p "Analyze code and run tests" \
    --output-format json \
    -y \
    --allowedTools "Bash,Read,Grep"
  ```

  > **⚠️ Important Note:** `-y` (or `--dangerously-skip-permissions`) is a required parameter for non-interactive mode. When using the `-p/--print` parameter for non-interactive execution, this parameter must be added to perform operations that require authorization (file read/write, command execution, network requests, etc.), otherwise these operations will be blocked. Only use this parameter in trusted environments and explicit task scenarios. See [CLI Reference](cli-reference.md) for details.

## Related Resources

* [CLI Reference](cli-reference.md) - Complete CLI documentation
* [Common Workflows](common-workflows.md) - Step-by-step guides for common use cases
* [Interactive Mode](interactive-mode.md) - Interactive session features
* [IAM Permissions](iam.md) - Tool permissions and access control

---

> **Tip**: Headless mode is ideal for CI/CD pipelines, automation scripts, and agent integrations. Combine it with MCP servers to extend functionality.
