·

Claude Code --max-turns: Headless Limits

Prepared and checked using AI. Sources are linked in the article.

claude-code tutorial workflow ai-coding

To limit a Claude Code headless run, pass --max-turns N with -p: --max-turns caps agentic turns in print mode and has no limit by default. Automation should capture both the process exit status and JSON output, treat a reached limit as incomplete work, and require an explicit retry policy before continuing.

Start a bounded print-mode run

You need an installed, authenticated Claude Code CLI; follow the installation and authentication steps before running unattended jobs. Run from the project directory you want the agent to work in.

For example, ask for an architecture summary with a three-turn cap:

claude -p "Summarize this project's architecture." \
  --max-turns 3 \
  --output-format json

-p runs non-interactively, and --output-format json returns the result with session metadata. Claude Code exits with zero on success and a nonzero status on failure. Startup errors can go to stderr, while failures inside a run can appear on stdout, so preserve both streams.

The turn cap does not grant tool permissions. For tasks requiring approvals, configure the permissions separately: --allowedTools approves specified tools without prompting; it does not restrict the complete tool set.

What counts as a turn?

A turn is one pass through the agent loop: Claude produces output, requested tools execute, and their results feed into the next pass. Multiple tool calls can occur in one turn, so the cap is not a tool-call count.

Allow room for the final text-only response. An illustrative sequence is:

  1. Read relevant files.
  2. Make an edit and run a check.
  3. Produce the final answer.

A limit that stops this sequence before the final response produces error_max_turns, with no final result field. Choosing a very small cap can therefore stop useful work before Claude summarizes it.

With --input-format stream-json, queued messages can start another turn with their own limit. For a simple bounded batch job, prefer one prompt per invocation; do not treat a streaming conversation’s turn cap as a lifetime limit on the process.

Handle the result before using the answer

The result message includes subtype, is_error, num_turns, session_id, and total_cost_usd. Keep these diagnostics when a run stops. Accept an answer only when the process succeeded, the subtype is success, and is_error is false.

The following shell wrapper requires jq and uses illustrative output files named agent-result.json and agent-stderr.log. Give each concurrent job its own output paths. It uses jq’s -e for conditional checks and -s to validate the complete output as one JSON value.

#!/bin/sh

result_file=agent-result.json
error_file=agent-stderr.log
status=0

claude -p "Summarize this project's architecture." \
  --max-turns 3 \
  --output-format json \
  </dev/null >"$result_file" 2>"$error_file" || status=$?

if ! jq -se '
  length == 1 and
  (.[0] | type == "object" and .type == "result")
' "$result_file" >/dev/null; then
  printf '%s\n' "Missing or invalid result; inspect saved output." >&2
  exit 1
fi

if jq -e '.subtype == "error_max_turns"' \
  "$result_file" >/dev/null; then
  jq '{subtype, session_id, num_turns, total_cost_usd, errors}' \
    "$result_file" >&2
  exit 2
fi

if [ "$status" -ne 0 ] || ! jq -e '
  .subtype == "success" and
  .is_error == false and
  (.result | type == "string")
' "$result_file" >/dev/null; then
  printf '%s\n' "Agent run failed; inspect saved output." >&2
  exit 1
fi

jq -r '.result' "$result_file"

Exit status 2 is this wrapper’s chosen signal for a turn-limit stop, not a promised Claude Code exit code. Missing JSON, unknown error subtypes, and other failures remain failures. For broader completion handling, see detecting headless coding-agent completion.

Review or resume after a limit

Because tools execute during earlier turns, treat a limit stop as potentially containing partial changes. Inspect the working copy and run the task’s required checks before accepting, discarding, or extending the work. A successful agent response should still pass your normal acceptance checks.

For a bounded continuation, set session_id to the saved result’s session ID and submit a narrower follow-up:

claude -p \
  --resume "$session_id" \
  --max-turns 3 \
  --output-format json \
  "Summarize the findings already gathered. Do not investigate further."

Use a specific session ID when jobs overlap. Keep a retry count and an overall job deadline in the surrounding automation; repeatedly launching capped continuations defeats the purpose of bounding the job.

If spend is the concern, --max-budget-usd separately stops a print-mode run based on estimated API spend. Spend can exceed that threshold, so leave headroom. Use your runner’s timeout separately when elapsed time matters.

Where Parallel Code fits

Parallel Code is our free, open-source desktop app for macOS and Linux that runs several AI coding agents in parallel, each isolated in its own git worktree. Its diff-first review surface fits the review step when an editing task stops at a limit and you need to inspect the partial changes.