I have been working on some passion projects recently and occasionally when the implementation caused some parts of the application to fail I noticed that the AI session seemed to be stuck in a loop of retrying to fix the issue. While I have mostly been using free tier AI models, this concerned me as it could be spending too many of my tokens try more and more complex fixes for what is sometimes a simple fix. So I looked into how to limit retries and then prompt me for suggestions about the issues.
So I looked into the process to implement error handling and limit the retry loops. I found that updating the AGENTS.md file was one step but depending on the model I wanted to go a step further and implement hard guardrails in the base opencode.json as well.
This should be added to the
~/.config/opencode/AGENTS.md on macOS/Linux or the %USERPROFILE%\.config\opencode\AGENTS.md on windows
## Error Handling & Retry Limits
- **Strict 2-Retry Cap:** When running builds, tests, or commands (`./gradlew`, `php artisan test`, `composer`, etc.) or attempting to fix a bug, you are allowed a maximum of **2 fix attempts** for the same error or failing task.
- **Stop & Ask for Clarity:** If the error persists after 2 retries (3 total runs including the initial attempt), **STOP immediately**. Do not edit any more files or run further commands.
- **Required Handoff:** Use the `question` tool (or reply directly) to ask the user for clarification. Briefly summarize:
1. What failed and the exact error message.
2. The 2 approaches you already tried and why they didn't work.
3. What specific context, constraint, or manual check you need from the user before continuing.
This rule acts as a circuit breaker that stops the AI from endlessly guessing and burning through tokens when it gets stuck on a bug. If an error isn’t fixed after two retry attempts, it forces the AI to stop editing files and immediately hand control back to you. Instead of continuing to guess, the AI must pause and give you a quick summary of what broke, what it already tried, and what help or context it needs from you to move forward.
To implement the hard guard rails the should be added to the ~/.config/opencode/opencode.json file on macOS/Linux and %USERPROFILE%\.config\opencode\opencode.json file on windows
{
"$schema": "https://opencode.ai/config.json",
"permission": {
"doom_loop": "ask"
},
"agent": {
"build": {
"steps": 12
}
}
}
This configuration acts as a hard safety net to keep OpenCode from getting stuck in expensive loops. The $schema line enables autocomplete and error-checking in your editor, "doom_loop": "ask" pauses the agent and asks for your approval if it tries to repeat the exact same action three times in a row, and "steps": 12 caps the build agent at 12 total tool actions (such as file reads, edits, or terminal commands) per prompt before forcing it to stop and respond to you with text.


