On this page⌄

Docs · Reference

Headless mode

Run CCode from scripts, CI jobs and your own programs: no terminal interface, output you can parse, and a session you can drive.

Command
ccode -p
Output
text · JSON
Input
text · JSON
Version
1.12.3+

Headless mode is the same CCode as in your terminal: the same tools, skills, hooks, MCP servers, memory, permission rules and plan. Every run is a session you can continue. It works on every plan, the Free plan included.

Ways to run it#

  • ccode -p "<prompt>"The answer as text, in a shell script
  • --output-format jsonOne JSON object with the answer, usage and session id
  • --output-format stream-jsonEvery message as it happens, one JSON line each
  • --input-format stream-json --output-format stream-jsonA long-lived session your program sends messages and commands to

Basic usage#

Pass the prompt after -p. The answer is written to stdout as plain text.

shell
ccode -p "Summarize what this project does in three bullet points"

Leave the prompt out to read it from stdin:

shell
cat error.log | ccode -p
git diff | ccode -p --output-format json

stdout carries only the answer. Errors, retry notices and, with --verbose, tool activity go to stderr.

Permissions#

No one is there to approve tool calls, so a call that needs approval is refused unless you choose otherwise. Your saved allow and deny rules apply in every case.

  • --yes, -yApprove every permission request.
  • --permission-mode acceptEditsFile edits run; shell commands still need approval.
  • --permission-mode bypassPermissionsNothing asks. Deny rules in your settings still apply.
  • --permission-mode planRead-only: CCode explores and proposes a plan.
  • --permission-prompt-tool stdioYour program decides each call.

Structured output#

--output-format json prints one result object when the run ends.

shell
ccode -p "How many TODO comments are in src/?" --output-format json
output
{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "result": "There are 14 TODO comments in src/.",
  "num_turns": 3,
  "duration_ms": 8420,
  "total_cost_usd": 0.0213,
  "usage": { "input_tokens": 11174, "output_tokens": 165, "cache_read_input_tokens": 17024 },
  "permission_denials": [],
  "session_id": "20261201-132352-2xc1j"
}
shell
ccode -p "Name the main entry point of this project" --output-format json | jq -r '.result'

Streaming#

--output-format stream-json prints one JSON object per line as the run goes: each reply, each round of tool results and the result. Add --include-partial-messages to receive text as it is written.

shell
ccode -p "Explain the retry logic in src/http.ts" \
  --output-format stream-json --include-partial-messages |
  jq -rj 'select(.type == "stream_event" and .event.delta.type? == "text_delta") | .event.delta.text'

Background work the agent starts (commands, monitors, subagents) is announced when it starts and when it ends. A one-shot run waits for that work before it exits.

Sessions#

Every run is saved, and every line carries its session_id.

shell
# Continue the most recent session in this folder
ccode -p "Now add tests for that change" --continue

# Resume a specific session
id=$(ccode -p "Review src/auth.ts for bugs" --output-format json | jq -r '.session_id')
ccode -p "Fix the first bug you found" --resume "$id" --yes

# Work on a copy; the original stays as it was
ccode -p "Rewrite it with async iterators" --resume "$id" --fork

--max-turns <n> stops a message after n model calls; the result is then error_max_turns. --no-session-persistence runs without saving.

Drive a session#

With --input-format stream-json, CCode reads JSON lines from stdin for as long as you keep it open, and answers on stdout in the stream format.

shell
ccode -p --input-format stream-json --output-format stream-json

Send a message as one line:

stdin
{"type":"user","message":{"role":"user","content":"List the files in src/"},"uuid":"u-1"}

Messages are answered one at a time, in order, and each ends in its own result line. The uuid is optional; set it to refer to the message later. Close stdin to end the session: queued messages are answered first.

Control requests#

A control request is answered right away, also in the middle of a turn, with a response carrying the same request_id.

stdin
{"type":"control_request","request_id":"1","request":{"subtype":"interrupt"}}
stdout
{"type":"control_response","response":{"subtype":"success","request_id":"1","response":{"still_queued":[]}}}
  • initialize—Describes the session: id, version, model, permission mode, state, commands and tools.
  • interruptcancel_queued (optional)Stops the turn in progress. With cancel_queued: true, also removes the messages still waiting.
  • cancel_async_messagemessage_uuidRemoves one queued message.
  • set_permission_modemodeSwitches the permission mode from the next tool call on.
  • set_modelmodelSwitches the model from the next call on. Use an id that ccode models lists.
  • stop_tasktask_idStops a background command, monitor or agent.
  • background_taskstool_use_id (optional)Moves the shell command running in the foreground to the background.

A request that fails is answered with "subtype": "error" and an error message.

Approve tool calls#

With --permission-prompt-tool stdio, CCode asks your program before each tool call that needs approval:

stdout
{"type":"control_request","request_id":"8a7c…","request":{"subtype":"can_use_tool","tool_name":"bash","input":{"command":"rm -rf build"},"tool_use_id":"call_3"}}
stdin
{"type":"control_response","response":{"subtype":"success","request_id":"8a7c…","response":{"behavior":"allow"}}}
  • {"behavior": "allow"}The call runs.
  • {"behavior": "deny", "message": "…"}The call doesn't run; the agent reads your message and continues.
  • {"behavior": "deny", "interrupt": true}The call doesn't run and the turn ends.

Message reference#

Every line on stdout is a JSON object with a type. All except control messages carry a uuid and the session_id.

  • system / initStarts each turn: working directory, version, model, permission mode, tools, skills and commands.
  • assistantOne reply: text, thinking and tool calls, with its token usage.
  • userThe results of the tool calls in the reply before it.
  • stream_eventText and thinking as they are written. Only with --include-partial-messages.
  • system / task_started, task_notificationBackground work starting and ending: commands, monitors and agents.
  • system / api_retryA model call failed and is being retried.
  • system / compact_boundaryThe conversation was summarized to free up context.
  • resultEnds every turn. See The result below.

The result#

  • subtypesuccess, error_max_turns or error_during_execution.
  • is_errortrue unless subtype is success.
  • resultThe answer's text, on success.
  • errorsWhat went wrong, on errors.
  • num_turnsModel calls made in this turn.
  • duration_msHow long the turn took.
  • usageTokens used in this turn.
  • total_cost_usdWhat the run has cost so far.
  • permission_denialsTool calls that were not allowed to run.
  • session_idThe session, to continue it later.

Flags#

  • -p, --print [prompt]Run headless. With no prompt, read it from stdin.
  • --output-format <format>text (default), json or stream-json.
  • --input-format <format>text (default) or stream-json. stream-json needs --output-format stream-json.
  • --include-partial-messagesAdd stream_event lines. Needs --output-format stream-json.
  • --replay-user-messagesWrite each message you send back on stdout. Needs --input-format stream-json.
  • --permission-prompt-tool stdioAsk your program to approve tool calls. Needs --input-format stream-json.
  • --max-turns <n>Stop a message after n model calls.
  • --no-session-persistenceDon't save the session.
  • --yes, -yApprove every permission request.
  • --permission-mode <mode>default, acceptEdits, plan or bypassPermissions.
  • --model <id>The model for this run.
  • --continue, -cContinue the most recent session in this folder.
  • --resume <id>, -r <id>Resume a session by id.
  • --forkWith -c or -r: work on a copy of the session.
  • --add-dir <path>Another working directory. Repeatable.
  • --verboseLog tool activity and token counts to stderr.

Exit codes#

  • 0The last result was a success.
  • 1The last result was an error.
  • 2The command line was wrong, or the session couldn't be started (for example, no session to resume).
  • 130A second Ctrl+C in the same turn ended the run.
  • 143The run was ended with SIGTERM.

Ctrl+C stops the turn in progress. In a one-shot run that ends the run; in a session driven over stdin the session goes on.

Examples#

Review a pull request in CI

shell
{
  echo "Review this diff. List real bugs only, one per line, as file:line: problem."
  gh pr diff "$PR"
} | ccode -p --permission-mode plan --max-turns 15 --output-format json > review.json

jq -e '.is_error | not' review.json > /dev/null || exit 1
jq -r '.result' review.json

A minimal client in Node.js

javascript
import { spawn } from "node:child_process";
import { createInterface } from "node:readline";

const ccode = spawn("ccode", [
  "-p", "--input-format", "stream-json", "--output-format", "stream-json",
  "--permission-prompt-tool", "stdio",
]);
const send = (value) => ccode.stdin.write(JSON.stringify(value) + "\n");

createInterface({ input: ccode.stdout }).on("line", (raw) => {
  const line = JSON.parse(raw);
  if (line.type === "control_request" && line.request.subtype === "can_use_tool") {
    const allow = line.request.tool_name === "Read";
    send({
      type: "control_response",
      response: {
        subtype: "success",
        request_id: line.request_id,
        response: allow ? { behavior: "allow" } : { behavior: "deny", message: "Read-only session." },
      },
    });
  }
  if (line.type === "result") {
    console.log(line.is_error ? line.errors : line.result);
    ccode.stdin.end();
  }
});

send({ type: "user", message: { role: "user", content: "What does src/index.ts export?" } });

Limits#

  • Messages sent on stdin are text only.
  • An approval runs a tool call as written; it can't change the call.
  • A tool call's input arrives with the complete reply, not while it is written.
  • Subagents appear as tasks; their own messages are not on the stream.
  • CCode can't ask you questions during a headless run, so put the choices you care about in the prompt.

Usage counts against your plan's limits as in the terminal. To call models directly from your own code instead, see the API.