tencent cloud

Headless Mode

Download
Focus Mode
Font Size
Last updated: 2026-09-30 18:15:48
AI-Translated

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:
-y (or --dangerously-skip-permissions) is a required parameter for non-interactive mode. When the -p/--print parameter is used for non-interactive execution, this parameter must be added to perform operations that require authorization (file read/write, command execution, network requests, and so on), otherwise these operations will be blocked. Use this parameter only in trusted environments and for well-defined task scenarios. For details, see CLI Reference.

Basic Usage

The primary command-line interface of 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:
codebuddy -p "Stage my changes and write a set of commits for them" \\
--allowedTools "Bash,Read" \\
--permission-mode acceptEdits

Configuration Option

Headless mode leverages all available CLI options in CodeBuddy Code. The following are key options for automation and scripting:
Flag
Description
Example
--print, -p
Run in non-interactive mode.
codebuddy -p "query"
--output-format
Specify the output format (text, json, stream-json).
codebuddy -p --output-format json
--resume, -r
Resume 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 the system prompt (only used with --print).
codebuddy --append-system-prompt "custom instruction"
--allowedTools
List of allowed tools, separated by spaces or<br /><br />commas as a string
codebuddy --allowedTools mcp__slack mcp__filesystem<br /><br />codebuddy --allowedTools "Bash(npm install),mcp__filesystem"
--disallowedTools
List of disallowed tools, separated by spaces or<br /><br />commas as a string
codebuddy --disallowedTools mcp__splunk mcp__github<br /><br />codebuddy --disallowedTools "Bash(git commit),mcp__github"
--settings
Load additional settings from a JSON file or JSON string.
codebuddy -p --settings '{"model":"gpt-5"}' "query"
--setting-sources
Specify the setting sources to load (options: user, project, local).
codebuddy -p --setting-sources project,local "query"
--mcp-config
Load MCP server from a JSON file.
codebuddy --mcp-config servers.json
--permission-prompt-tool
MCP tool for handling permission prompts (only used with --print)
❌ Not supported.
Note:
The --permission-prompt-tool feature is not currently supported.
For a complete list of CLI options and features, see the CLI Reference documentation.

Multi-Turn Conversation

For multi-turn conversations, you can resume a conversation or continue from the most recent session:
# Continue the most recent conversation
codebuddy --continue "Refactor now to improve 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 Format

Text Output (Default)

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

JSON Output

Return structured data that includes metadata:
codebuddy -p "How does the data layer work?" --output-format json
Response format:
{
...
}

Streaming JSON Output

Stream each message as it is received:
codebuddy -p "Build an application" --output-format stream-json
Each conversation starts with an initial init system message, followed by a list of user and assistant messages, and ends with a final result system message that contains statistics. Each message is emitted as a separate JSON object.

Background Task Events (Async)

When the model starts a background command (Bash / PowerShell), a background workflow, or a background Agent subtask with run_in_background: true, the CLI emits a separate system event for each task on the stream-json output stream, carrying a unique task_id (used to distinguish between concurrent tasks), and the tool_use_id links back to the tool_use that initiated the task:
Task started → system / subtype: "task_started"
Task progress (each time a tool_use is completed, sub-agent/workflow tasks only) → system / subtype: "task_progress" (with usage)
Task status change → system / subtype: "task_updated" (with patch)
Task completed/failed/stopped → system / subtype: "task_notification"
// Task started (pushed immediately when entering the running state)
{"type":"system","subtype":"task_started","task_id":"agent-00f6","tool_use_id":"toolu_01","description":"bg agent","task_type":"Agent","uuid":"...","session_id":"..."}
// Progress (emitted each time a tool_use is completed, carrying cumulative usage + the latest tool name; not emitted for shell tasks)
{"type":"system","subtype":"task_progress","task_id":"agent-00f6","description":"bg agent","usage":{"total_tokens":320,"tool_uses":2,"duration_ms":157},"last_tool_name":"Bash","uuid":"...","session_id":"..."}
// State transition (patch carries the changed fields; end_time is added for terminal states)
{"type":"system","subtype":"task_updated","task_id":"agent-00f6","patch":{"status":"completed","end_time":1783945615966},"status":"completed","uuid":"...","session_id":"..."}
// Task completed (may arrive after the result of the turn that triggered it; sub-agent carries usage)
{"type":"system","subtype":"task_notification","task_id":"agent-00f6","tool_use_id":"toolu_01","status":"completed","summary":"Background agent \\"bg agent\\" completed","output_file":"/.../bg-tasks/agent-00f6.stdout.log","usage":{"total_tokens":480,"tool_uses":2,"duration_ms":250},"session_id":"..."}
Field description:
Field
Event
Description
task_id
All
Unique ID of the background task, which runs through started → progress → updated → notification and is used to distinguish concurrent tasks and route to TaskOutput.
tool_use_id
Most (optional)
Associates back to that tool_use in the model
description / task_type
started / progress
Task command description / tool type (Bash / PowerShell / Workflow / Agent)
usage
progress (required) / notification (available for sub-agent, omitted for shell)
{ total_tokens, tool_uses, duration_ms } (aligned with TaskUsage of CC)
last_tool_name
progress (optional)
Name of the most recently executed tool
patch / status
updated
Fields changed in this update (at least status, and end_time for terminal states)
status
notification
completed / failed / stopped (killed/cancelled normalized to stopped)
summary
notification
Human-readable completion summary
output_file / output_stderr_file
notification (optional)
Path where background task output is written to disk (file mode), from which the complete output can be read
The progress event (task_progress) is event-driven, pushed once each time a tool_use is completed, rather than based on periodic polling. Background shell tasks (Bash/PowerShell) do not emit progress, and only sub-agent / workflow tasks do.
The terminal state may arrive only via task_updated: for some background tasks, the terminal state arrives only through task_updated (patch.status is terminal) without a corresponding task_notification. Consumers tracking "active tasks" should clean up the terminal status of both equally, including completed / failed / stopped / killed.
Important (stdio long-connection scenario): A background task may complete only after the result of the turn that triggered it. When --input-format stream-json --output-format stream-json is used (a long connection with stdin kept open), the CLI actively pushes task_notification back to the same output stream after the task actually ends, so you do not need to send new input. Therefore, consumers should continuously read the output stream and not stop reading after receiving the first result, otherwise they will miss background completion events. The pure -p single-shot mode (where the process exits with the first result) does not support background tasks and returns an explicit error.
Disabling background tasks: in scenarios where background tasks are not supported or not needed, set the environment variable CODEBUDDY_CODE_DISABLE_BACKGROUND_TASKS=1 to disable background tasks. The run_in_background parameter for Bash / PowerShell / Agent is hidden from the tool schema, and even if the model still sends it, it is ignored or downgraded to foreground execution, so no background task events are generated and no cross-turn push-back occurs. The SDK's query() single-shot usage automatically injects this variable (because query() stops at the first result and cannot receive cross-turn push-back events). SDK usage with continuous reading (JS unstable_v2_createSession / Python CodeBuddySDKClient) is not affected.

Structured JSON Output

To obtain output that conforms to a specific schema, use --output-format json with --json-schema and a JSON Schema definition. The response includes metadata about the request (session ID, usage, and so on), and the structured output is in the structured_output field.
This example extracts function names from auth.py and returns them as a string array:
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 a tool such as jq to parse the response and extract specific fields:
# Extract text results
codebuddy -p "Summarize this project" --output-format json | jq -r '.result'

# Extract structured output
codebuddy -p "Extract the 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 Format

Text Input (Default)

# Direct parameters
codebuddy -p "Explain this code"

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

Streaming JSON Input

A message stream is provided via stdin, where each message represents a user turn. This enables multi-turn conversations without restarting the codebuddy binary and allows guidance to be provided to the model while it processes requests.
Each message is a JSON "user message" object that follows the same format as the output message schema. Messages are formatted using jsonl, where each input line is a complete JSON object. Streaming JSON input requires -p and --output-format stream-json.
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 copy that references the following image"},{"type":"image","source":{"type":"base64","media_type":"image/png","data":"Raw base64 (without the protocol prefix)"}}]}}' \\
| codebuddy -p --input-format stream-json --output-format stream-json

# Multi-turn conversation (multiple lines of 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 Example

SRE Incident Response Bot

#!/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 the 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 returns 500 error" "high"

Automated Security Review

# 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, insecure patterns, and compliance issues." \\
--output-format json \\
--allowedTools "Read,Grep,WebSearch"
}

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

Multi-Turn Legal Assistant

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

# Review contracts in multiple steps
codebuddy -p --resume "$session_id" "Review the liability clauses in contract.pdf"
codebuddy -p --resume "$session_id" "Check compliance with GDPR requirements"
codebuddy -p --resume "$session_id" "Generate a risk executive summary"

Tips

Use JSON output format for programmatic response parsing:
# Parse JSON responses with 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:
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 multiple conversation turns.
Consider timeouts for long-running operations:
timeout 300 codebuddy -p "$complex_prompt" || echo "Timed out after 5 minutes"
Respect rate limits by adding delays between calls when making multiple requests.
Use -y to perform operations requiring authorization in non-interactive mode:
# Complete example in non-interactive mode
codebuddy -p "Analyze the code and run tests" \\
--output-format json \\
-y \\
--allowedTools "Bash,Read,Grep"
Important:
-y (or --dangerously-skip-permissions) is a required parameter for non-interactive mode. When using the -p/--print parameter for non-interactive execution, you must add this parameter to perform operations that require authorization (such as file read/write, command execution, and network requests). Otherwise, these operations will be blocked. Use this parameter only in trusted environments and for well-defined task scenarios. For details, see CLI Reference.
Note:
Headless mode is well-suited for CI/CD pipelines, automation scripts, and agent integrations. Combine it with MCP servers to extend functionality.


Help and Support

Was this page helpful?

Help us improve! Rate your documentation experience in 5 mins.

Feedback