Your agent needs exit conditions — here's how to stop infinite loops before they drain your budget
Your agent just spent $47 trying to "fix" a test that was already passing. It ran the same command 200 times, each time convinced this would be the attempt that worked.
This is what happens when you build one-shot agents that never learned when to stop.
The difference between a demo agent and a production agent isn't intelligence — it's loop engineering. Your agent needs to know when it's done, when it's stuck, and when it's making things worse.
Exit conditions aren't just about saving money. They're about building agents that ship instead of agents that spin.
Here's the pattern that stops runaway loops:
LOOP_CONFIG = {
"max_attempts": 5,
"success_conditions": [
"tests_passing",
"build_successful",
"no_errors_in_output"
],
"failure_conditions": [
"same_error_3_times",
"no_progress_for_10_minutes",
"token_budget_exceeded"
],
"escalation_trigger": "human_review_needed"
}Every agent task needs three types of boundaries:
- Success exits: "Stop when the tests pass" or "Stop when the API returns 200"
- Failure exits: "Stop if you see the same error 3 times" or "Stop if you haven't made progress in 15 minutes"
- Budget exits: "Stop after 5 attempts" or "Stop after spending $10"
The magic happens when you combine attempts with validation. Don't just count loops — measure progress.
Here's what good exit conditions look like in practice:
def should_continue_loop(attempt_count, last_result, progress_history):
# Budget boundary
if attempt_count >= MAX_ATTEMPTS:
return False, "max_attempts_reached"
# Success boundary
if last_result.status == "success":
return False, "task_completed"
# Progress boundary
if no_progress_in_last_n_attempts(progress_history, 3):
return False, "stuck_in_loop"
# Error pattern boundary
if same_error_repeated(progress_history, 3):
return False, "recurring_error"
return True, "continue"The best agents I've built use what I call "Ralph-style durable loops" — they persist across sessions, survive crashes, and pick up where they left off. But they only work because every loop has bulletproof exit conditions.
Warning: Agents without exit conditions will find creative ways to burn your budget. I've seen agents spend hours trying to "fix" a permissions error by running the same command with slight variations.
Your agent should fail fast and fail informatively. When it hits an exit condition, it should tell you exactly what it tried, what didn't work, and what it thinks you should do next.
The difference between a $5 task and a $50 task usually isn't complexity — it's loop discipline.
If you're running coding agents that sometimes disappear into infinite loops, you need session management with built-in exit conditions. The pattern I use wraps every agent session in tmux with Ralph-style loop detection and automatic recovery.