Skip to content
Cost & Performance Simple

Cap Turns for Safety

Limit agentic conversation turns with --max-turns to prevent runaway loops in automation

Command

$ "color:#7C5CFC">claude -p "Refactor auth.py to use JWT" \
    "color:#d97757">--max-turns 10 \
    "color:#d97757">--max-budget-usd 2.00 \
    "color:#d97757">--output-format json

Response

{
  "type": "result",
  "subtype": "error_max_turns",
  "is_error": false,
  "result": "Partial progress: extracted token validation...",
  "total_cost_usd": 1.42,
  "num_turns": 10
}

Parsing Code

059669">">const data = JSON.parse(output);
059669">">if (data.subtype === 059669059669">">'error_max_turns') {
  059669">">console.warn(059669">`Hit turn cap after ${data.num_turns} turns ($${data.total_cost_usd})`);
  059669">">// Resume with --continue to pick up where it left off
} 059669">">else {
  console.log(data.result);
}

Gotchas

! --max-turns caps conversation turns, NOT tool calls within a turn — a single turn can invoke multiple tools
! Only works in --print mode — ignored in interactive sessions
! Combine with --max-budget-usd for double safety: turns AND cost

Related Recipes