A circuit breaker for runaway coding agents.
loop-budget is a zero-code-change safety circuit breaker and live terminal monitor for autonomous AI coding agents (Claude Code, Aider, OpenCode, custom scripts). It sits locally between your agent and the AI provider, metering token spend in real time, detecting when your agent gets stuck repeating failed tests without making code progress, and pulling the plug before you wake up to a massive API bill.
Zero third-party runtime dependencies. Pure Python 3.11+.
Open PowerShell in Windows 11 and install editable:
cd C:\Hackathons\loop-budget
python -m pip install -e .Verify that the CLI is available:
loop-budget --helpRun these deterministic demonstrations offline without needing an API key or external credits. Each demo runs against a local mock upstream using the real production CLI and circuit breaker.
Simulates an agent completing tasks within its allocated budget.
python examples/demo.py --scenario healthy- Observed Result: Agent completes 2 steps, spends $0.202 against a $0.50 cap, and exits cleanly with code
0.
Simulates a runaway agent repeatedly retrying a broken fix.
python examples/demo.py --scenario budget- Observed Result: Each request reserves and settles $0.101 against a $0.25 cap. Requests 1 & 2 succeed ($0.202 spent). Request 3 is blocked at admission because the estimated spend exceeds the remaining budget. Only 2 calls reach upstream; LoopBudget terminates the agent, exports
demo-receipt.json, and exits with code2with 0 overshoot. - Receipt:
loop-budget: $0.202 reported ($0.202 estimated) | 2,020 tokens | 2 forwarded, 1 blocked | 0 unresolved | Dollar budget reached
Simulates an agent stuck in an edit-test loop repeating identical test failures without making code progress.
python examples/demo.py --scenario stall- Observed Result: Agent receives repeated
AssertionErrortest failures while the Git working tree remains unchanged across turns. The defensible stall detector trips, terminates the agent, and exportsdemo-stall-receipt.jsonwith forensic stall evidence. Exits with code2.
To run all three demos sequentially:
python examples/demo.py- Local Proxy: Starts an ephemeral localhost proxy on
127.0.0.1. - Transparent Routing: Injects standard environment variables (
OPENAI_BASE_URL,ANTHROPIC_BASE_URL) into the child process. - Atomic Reservation & Accounting: Before forwarding a request upstream, LoopBudget calculates estimated input tokens from the request payload and clamps output to
--max-output-tokens, reserving budget atomically. Concurrent calls cannot double-spend the remaining budget. - Streaming Metering: Accurately tracks SSE chunks on the fly and reconciles with provider-reported usage. Missing streaming usage is explicitly handled without silently becoming $0.00 spend.
- Defensible Stall Detection: Unchanged Git state alone is treated as an informative warning. Automatic stops require repeated equivalent test failure signatures (or cyclic patch oscillation) alongside unchanged code state.
- Windows Process-Tree Shutdown: When a breaker trips, LoopBudget immediately severs upstream connections and terminates the managed process tree using
taskkill /T /Fand Win32 Toolhelp snapshot verification, leaving the user's working files intact.
# Set your API key
$env:ANTHROPIC_API_KEY = "your-anthropic-key"
# Run Claude Code with a $2.00 hard cap and stall detector enabled
loop-budget run --provider anthropic --pricing pricing.json --max-cost 2.00 --max-stalls 3 -- claude "Fix all failing unit tests"loop-budget run --pricing pricing.json --max-cost 5.00 --max-stalls 3 -- powershell -File ./my-agent-loop.ps1Enforce token ceilings and circuit breakers on local models with zero cloud spend:
loop-budget run --provider anthropic --upstream http://127.0.0.1:11434 --pricing examples/local_pricing.json --max-tokens 50000 --max-stalls 3 -- claude -p "Explain calc.py" --model llama3.2:3bAutomatically switch from an expensive model to a cheaper model once spend crosses a soft limit:
loop-budget run --pricing pricing.json --max-cost 5.00 --soft-limit 3.50 --fallback-model claude-3-haiku-20240307 -- claudeAll local models were tested on Windows 11 with the installed loop-budget run CLI routing directly through Ollama 0.40.12 (127.0.0.1:11434). No remote cloud APIs were accessed.
| Model Tag | Parameters & Format | Streamed Response | Tool Execution | Token Breaker (Admission) | Recorded Limitations & Behavior |
|---|---|---|---|---|---|
llama3.2:3b |
3.2B / GGUF (2.0 GB) | Verified (4,024 tok) | No (hallucinated output) | Verified (0 fwd, 1 blk, exit 1/2) | Small parameter size causes model to generate simulated command outputs rather than emitting Anthropic tool-use schema. |
qwen2.5:3b |
3.1B / GGUF (1.9 GB) | Verified (2,052 tok) | No (emitted {}) |
Verified (0 fwd, 1 blk, exit 1/2) | Emits empty JSON payload {} when confronted with Claude Code agent tool schemas. |
qwen3.5:4b |
4.2B / GGUF (3.3 GB) | Verified (2,233 tok) | No (conversational text) | Verified (0 fwd, 1 blk, exit 1/2) | Streams fluent conversational acknowledgment of system prompt without invoking tool call blocks. |
gemma2:2b |
2.6B / GGUF (1.6 GB) | Errored (HTTP 400) | No (no tool support) | Verified (0 fwd, 1 blk, exit 1/2) | Upstream Ollama returned HTTP 400 (does not support tools); LoopBudget caught this and tripped immediately to prevent retry storm. Token limit rejects at admission before Ollama is reached. |
gemma4:latest |
4.6B / GGUF (4.6 GB) | Verified (2,501 tok) | No (greeting reply) | Verified (0 fwd, 1 blk, exit 1/2) | Streams conversational response; does not parse agent tool definitions into function calls. |
Note on Live Stall Test: Live stall tests with Claude Code + local models remain unverified because local small models (2.6B-4.6B) do not emit Anthropic tool call blocks. The deterministic stall test (examples/demo.py --scenario stall) and test suite verify the stall circuit breaker with forensic receipts.
| Route / Provider | Target Protocol | Verification Status | Notes |
|---|---|---|---|
| Local Ollama Models | /v1/messages & /v1/chat/completions |
Verified Live | Tested through loop-budget run CLI + Claude Code + Ollama on Windows 11. |
| Anthropic Claude Code | /v1/messages |
Verified Local / Cloud Pending | Protocol, SSE streaming, and process lifecycle fully verified locally; paid cloud endpoints labeled Pending (requires user cloud API key). |
| OpenAI / OpenCode / Aider | /v1/chat/completions |
Verified Local / Cloud Pending | Protocol, SSE usage injection, and token bounds fully verified locally; paid cloud endpoints labeled Pending. |
When a run finishes or trips, a receipt is generated:
{
"cost": "0.202",
"max_cost": "1.00",
"tokens": 2020,
"max_tokens": null,
"turns": 2,
"requests_forwarded": 2,
"requests_blocked": 1,
"unresolved_usage": 0,
"estimated_spend": "0.202",
"reason": "Stall detected: repeated test failure ('AssertionError: test_checkout_total failed: expected 50 got 0') with unchanged code for 2 turns",
"elapsed": 1.45,
"coverage": "Only supported requests routed through the local proxy",
"accounting_complete": true,
"stall_evidence": {
"type": "repeated_test_failure",
"git_state": "unchanged",
"intervals": 2,
"failure_signature": "AssertionError: test_checkout_total failed: expected 50 got 0"
},
"records": [
{
"turn": 1,
"model": "claude-3-5-sonnet-20241022",
"input": 1000,
"output": 10,
"cached": 0,
"cache_write": 0,
"cost_usd": "0.101",
"status": "ok"
}
]
}| Integration | Supported Protocol | Verification Status | Verified Features |
|---|---|---|---|
| Claude Code (Anthropic) | /v1/messages |
Verified | Windows launch command, ANTHROPIC_BASE_URL routing, streaming SSE parsing, cache-read & creation tokens, graceful shutdown. |
| OpenAI / OpenCode / Aider | /v1/chat/completions |
Verified | Streaming SSE (stream_options.include_usage), output-token clamping (max_completion_tokens & max_tokens), token budget limits. |
| Local Models (Ollama, vLLM) | OpenAI-compatible /v1 |
Verified | $0 rate tracking, token thresholds, stall & oscillation protection. |
| Windows Process Tree | Win32 / taskkill |
Verified | Clean termination of agent + child/grandchild processes; working files preserved. |
| Defensible Stall Detector | Git CLI + Tool Results | Verified | Unchanged git alone treated as warning; stops on repeated test failure signatures or oscillation. |
| Model Fallback | Same-upstream rewrite | Verified | Opt-in rewrite to cheaper model after soft limit; enforces price non-escalation. |
When your Anthropic credentials are configured:
$env:ANTHROPIC_API_KEY = "sk-ant-..."
loop-budget run --provider anthropic --pricing examples/pricing.example.json --max-cost 1.00 --no-tui -- claude -p "Explain the purpose of loop-budget in one sentence"| Option | Default | Description |
|---|---|---|
--pricing |
Required | JSON file with model rates in USD per million tokens |
--provider |
openai |
Protocol format: openai or anthropic |
--upstream |
Provider /v1 |
Custom upstream API base URL |
--max-cost |
5.00 |
Dollar budget threshold |
--max-tokens |
None | Combined input/output token threshold |
--max-output-tokens |
4096 |
Per-request output token cap |
--max-stalls |
0 |
Stall interval threshold (0 disables) |
--repo |
Current directory | Git repository root to inspect |
--soft-limit |
None | Threshold for model fallback |
--fallback-model |
None | Opt-in cheaper model ID |
--timeout |
120 |
Network socket idle timeout (seconds) |
--no-tui |
Off | Disable live terminal gauge |
--receipt |
None | Path to write JSON receipt |
--export-csv |
None | Path to write CSV usage report |
- No credential logging: LoopBudget never writes API keys, authorization headers, or prompt contents to disk or terminal.
- Localhost only: LoopBudget binds strictly to
127.0.0.1. Remote upstreams require HTTPS. - Zero telemetry: No external analytics, telemetry, or cloud dependencies.