Guides · Updated October 22, 2026
How to set a hard budget for AI coding agents in CI
An agent in CI runs with nobody watching: no one presses Esc when it starts retrying the same failing test, and a workflow that fires on every push can run it hundreds of times a month. The fix is layers: a per-run cap inside the agent, a timeout on the job, and a hard spend limit on the key the runner uses. Here is what Claude Code, Codex CLI and Cursor CLI each offer for headless runs as of October 2026, and where the gaps are.
The four layers
| Layer | Stops | Claude Code (claude -p) | Codex CLI (codex exec) | Cursor CLI (agent -p) |
|---|---|---|---|---|
| Per-run dollar cap | One expensive run | --max-budget-usd | None (experimental token budget only) | None |
| Per-run step cap | Endless agentic turns | --max-turns | None documented | None documented |
| Job timeout | Hung or looping jobs | Your CI system, e.g. timeout-minutes in GitHub Actions | ||
| Key / account limit | The monthly total | Console workspace spend limit | OpenAI project hard spend limit | Account spend limit; service-account limits on Enterprise |
The key limit is the only one that is a hard dollar ceiling no matter what the agent does, so set it first. The per-run caps keep any single run from using a large share of it.
Give CI its own key with its own limit
- Claude: create a separate workspace in the Claude Console for CI, put its API key in your CI secrets, and set a workspace spend limit. (The automatic “Claude Code” workspace can’t issue API keys.) You can also run CI on a subscription with a
CLAUDE_CODE_OAUTH_TOKENfromclaude setup-token, but then CI draws on that person’s plan limits, and Anthropic recommends an API key for secrets shared across repositories. - Codex: a dedicated OpenAI project and key, with Project settings → Limits → Enforce a hard limit turned on. Without the checkbox it is only an alert. Requests past the limit fail with
project_spend_limit_exceeded(OpenAI spend limits). - Cursor: the CLI authenticates with
CURSOR_API_KEYfrom Dashboard → API Keys, and headless requests draw on that account’s usage like interactive ones, so the account’s monthly spend limit (see limiting Cursor agent costs) is the ceiling. On Enterprise, a service account keeps CI off a person’s account and has its own per-billing-period spend limit; past it, requests fail with “Service account spend limit reached”.
Monthly limits are not instant (OpenAI and Cursor both note spend can briefly pass them) and they are monthly, which is why the per-run layers below still matter.
Claude Code: --max-budget-usd and --max-turns
Print mode has a real per-run cap. From the CLI reference, the run stops once estimated spend reaches the amount, subagent spend counts, and once the cap is hit Claude Code won’t start more subagents and stops background ones (v2.1.217 or later). --max-turns exits with an error after that many agentic turns.
claude -p --max-budget-usd 3.00 --max-turns 40 \ --output-format json "Fix the failing test in src/billing" > result.json jq '.total_cost_usd' result.json # the run's estimated cost, for your CI logs
In the official GitHub Action (anthropics/claude-code-action), claude_args passes any CLI argument, so the same flags go there:
- uses: anthropics/claude-code-action@v1
timeout-minutes: 20
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
claude_args: "--max-turns 30 --max-budget-usd 3"Caveats: the cap is checked against Claude Code’s own estimate, the final response can push spend past it (leave headroom), and with --continue or --resume earlier runs’ spend doesn’t count toward the new cap.
Codex CLI: no per-run cap, so lean on the project limit
codex exec has no flag that stops a run at a dollar amount. The config reference lists a token “rollout budget” (features.rollout_budget) that is under development and off by default. What you do get:
--jsonstreams events, and eachturn.completedevent carriesusagewith input, cached input and output tokens, so you can log what a run used.- OpenAI’s Codex GitHub Action (
openai/codex-action@v1) runscodex execbehind a proxy so the API key isn’t exposed to the rest of the job. OpenAI’s non-interactive docs say not to setOPENAI_API_KEYorCODEX_API_KEYas a job-level variable in workflows that run repository code; if you call the CLI yourself, setCODEX_API_KEYinline for that one command. - Keep the sandbox narrow (
--sandbox workspace-writerather thandanger-full-access) and add a job timeout.
Cursor CLI: no per-run cap, and no cost in the output
Cursor’s CLI parameters have no budget or turn limit, and the documented --output-format json result reports duration but no cost. So for agent -p in CI, the account or service-account spend limit plus a job timeout are your controls. Cursor recommends restricting what the agent may do in CI with permission rules (for example denying Shell(git)) and doing pushes and comments in separate deterministic steps.
Always set a job timeout
A timeout is the one control that works the same for all three agents and costs nothing. GitHub Actions jobs default to a 360-minute limit, far longer than any agent task should take:
jobs:
agent-fix:
runs-on: ubuntu-latest
timeout-minutes: 20 # whole job
steps:
- uses: actions/checkout@v5
- name: Run agent
timeout-minutes: 15 # just the agent step
run: ...Also watch the trigger: an agent on every push or synchronize event multiplies cost by how often people push. Run it on a label, a comment, or a failed CI run instead, and use concurrency to cancel superseded runs.
Add loop detection and caps with LoopGuard
Per-run dollar caps don’t notice that the agent has run the same failing command ten times, and Codex and Cursor don’t have them at all. LoopGuard is an open-source (MIT) CLI that installs PreToolUse/Stop hooks for Claude Code and Codex (and preToolUse/stop for Cursor) and checks every tool call against loop heuristics and session and daily dollar caps. It reads the agents’ own local logs, so it needs no proxy and no extra key. On a fresh runner:
npm i -g loopguard-cli loopguard init --agent claude,codex # writes ~/.claude/settings.json and ~/.codex/hooks.json loopguard config set sessionCapUsd 3 # estimated $ per agent session loopguard config set loop.maxRepeats 3 # repeats of the same call (with no progress) allowed within 10 minutes claude -p --max-budget-usd 3 "..." # Claude Code: hooks load from ~/.claude codex exec --dangerously-bypass-hook-trust \ --sandbox workspace-write "..." # Codex: see the trust note below loopguard report --by session # estimated cost per session, for the job log
What to know before relying on it in CI:
- Claude Code
--bareskips hooks. Anthropic recommends--barefor scripted runs, and it doesn’t read~/.claude, so LoopGuard won’t run. Either leave--bareoff, or pass the settings file that holds the hooks with--settings ~/.claude/settings.json, which the headless docs list as the way to load settings in bare mode. Don’t use--no-session-persistenceeither: LoopGuard prices the session from its transcript. - Codex needs its hooks trusted. Codex skips new hooks until someone trusts them in
/hooks, and a fresh runner has no saved trust, socodex execwould skip LoopGuard without a warning. For a runner you control,--dangerously-bypass-hook-trustruns enabled hooks for that invocation; only use it where you control every hook on the machine. Don’t use--ephemeral, which stops Codex writing the session log LoopGuard reads. Codex hooks can’t end a session, so a tripped cap denies every further tool call. - Cursor headless runs are not cost-capped.
agent -pdoesn’t send token counts to any hook, so LoopGuard’s session and daily caps can’t see that spend. Loop detection still blocks repeated tool calls that make no progress. - The daily cap is per machine. It sums spend in that runner’s logs for the local day. On an ephemeral runner that is one job; on a persistent self-hosted runner it covers every job that day.
- Costs are estimates at API list prices, and checks happen at tool calls and turn ends, so spend can pass a cap by up to one turn. LoopGuard fails open: on an internal error the agent keeps working and the error goes to
~/.loopguard/errors.log. Keep the key limit as the backstop.
Related
- How to stop runaway Claude Code, Codex and Cursor agent loops
- How to track AI coding agent token costs per session
- How to set a spending limit for Claude Code
- How to limit Cursor agent usage costs
- How to cap OpenAI Codex CLI spend
- Claude Code usage limit reached: why it happens and how to monitor it
- Claude Code stuck in a loop: how to break it and stop it repeating the same command
- Codex usage limit reached: 5-hour and weekly limits explained
- Cursor agent stuck in a loop: how to stop it, roll back, and keep it from repeating
- Why Claude Code uses so many tokens, and how to use fewer
- How to set a budget limit for Aider
- GitHub Copilot agent mode stuck in a loop: how to stop it and keep it from repeating
- Cline stuck in a loop: how to stop it, roll back, and cap what it spends
- Gemini CLI usage limits: daily quotas, the June 2026 change, and keeping costs in check
- Codex stuck in a loop: how to stop it, undo it, and keep it from repeating