Skip to main content
Glama
README.md
# agent-bridge-mcp

One coding agent hands work to others. `agent-bridge-mcp` is an MCP server that lets a primary agent session delegate tasks to Codex CLI, Claude Code (`claude -p`), Antigravity (`agy`) and local models (Ollama, OpenCode). It adds guard rails to that delegation: one writer per folder, a timed-out worker is killed together with its child processes (on Windows), and a backend whose quota is known to be used up is refused before it starts.

> **How this was built.** AI coding agents wrote almost all of the code in this repository, and other agents reviewed it. My part was to decide what the bridge should do, set the rules the agents work under, and accept or reject what came back. The [field report](docs/field-report-2026-11.md) covers the first three days of real use, including what failed.
>
> Emirhan Bahçacı

## Why it exists

Running several agent CLIs from one session goes wrong in a few repeatable ways:

- Two agents edit the same folder at the same time.
- A worker hangs, or exits and leaves child processes behind.
- A task goes to a provider whose quota ran out an hour ago.
- A worker ends with empty output and the caller treats that as success.

The bridge puts one tool surface in front of four backends and handles these cases in one place.

## What it does

- **Delegation.** Single calls (`delegate_codex`, `delegate_claude`, `delegate_antigravity`, `delegate_local_agent`), parallel batches (`run_parallel_agents`) and background jobs (`start_agent_job`, `check_agent_job`).
- **One writer per folder.** A write-capable run takes a cross-process lock on its `cwd`. A second writer is refused with `CWD_BUSY` on a direct call, and waits its turn inside a batch or a background job.
- **Process control.** On Windows, a timeout or a cancel ends the worker's whole process tree (job objects, with `taskkill /T` as fallback). If processes are still running after a worker exits, the result carries a `LEFTOVER_PROCESSES` warning.
- **Quota awareness.** `bridge_budget` reads the 5-hour and weekly limits of Codex (through `codex app-server`), Antigravity (`agy -p /quota`) and a separately profiled Claude Code (`claude -p /usage`) without sending a prompt to a model, and ranks them `spend`, `normal`, `unknown`, `save` or `blocked`. A `blocked` backend is refused with `COOLDOWN` before any process starts. Local models have no quota and are not ranked.
- **Failure classes.** Every result carries an `error` class such as `EMPTY_OUTPUT`, `QUOTA_EXHAUSTED`, `AUTH_REQUIRED` or `TIMEOUT`, so the caller can react without parsing prose. A read-only run that ends with no text is reported as `EMPTY_OUTPUT`. A write-capable run with no text keeps its status and gets a warning, because its result is the changed files.
- **Containment.** Workers cannot delegate onward (`AGENT_BRIDGE_MAX_DEPTH`), `allowed_commands` is checked against an allowlist, and `prompt_file` reads only from allowed folders and never from files on its credential deny-list.
- **A record.** Each delegation is logged with its duration, model, error class and a hash of the prompt (not the prompt text). `record_outcome` stores whether the result was accepted, fixed or rejected, and `bridge_stats` summarizes the log.

## Status and limits

- New project: first version on 15 November 2026, current version `0.4.0`.
- Developed and used on Windows 11 only. The code has POSIX branches (file locks use `fcntl`), but they are not tested, and on POSIX a timeout or a cancel kills only the worker's main process, not its children.
- Quota reading depends on CLI behavior that can change: `agy -p /quota`, `claude -p /usage` and the Codex `app-server`. A quota reading older than 15 minutes counts as `unknown`, and `unknown` does not block a delegation.
- The unit tests replace the worker CLIs with fakes. Real CLI behavior is covered only by daily use; the [field report](docs/field-report-2026-11.md) shows how that went.
- Some names come from my own setup. Workers are told not to call two MCP servers, `agent-bridge` and `local-llm`; the second is my local-model server, so change that name in `server.py` if yours differs. The model names in `config.example.json` are the ones I use.
- Two optional helpers are not part of this repository: `helpers/ensure_ollama.py`, which starts Ollama on demand (without it, start Ollama yourself), and an OpenCode binary under `bin/opencode`.

## Quick start

Requirements: Windows (see [Status and limits](#status-and-limits)), Python 3.10 or newer, the `mcp` Python package (`mcp>=1.0.0`, installed in step 1), and whichever worker CLIs or runtimes you want to use, each already logged in: Claude Code (`claude`), Codex CLI (`codex`), Antigravity (`agy`), Ollama and/or OpenCode (`opencode` or `opencode-cli`).

1. Clone the repository, install it and create your config file:

```bash
git clone https://github.com/parttimegod/agent-bridge-mcp
cd agent-bridge-mcp
pip install -e .
cp config.example.json config.json
```

2. Adjust `config.json` for your environment (see [`config.json` Settings](#configjson-settings)):
   - Replace the model names with models your own subscriptions offer.
   - To delegate to Claude Code, point `claude_config_dir` at a separate profile folder and log that profile in once (set `CLAUDE_CONFIG_DIR` to the folder and run `claude /login`), or set `claude_allow_orchestrator_account` to `true`. Until then `delegate_claude` returns `WORKER_PROFILE_MISSING`.
   - For local models, pull a model in Ollama and set `default_local_model` to its tag.

3. Register the server in your MCP client. For Claude Code:

```bash
claude mcp add agent-bridge -- python /absolute/path/to/agent-bridge-mcp/server.py
```

For clients that read a JSON file:

```json
{
  "mcpServers": {
    "agent-bridge": {
      "command": "python",
      "args": ["/absolute/path/to/agent-bridge-mcp/server.py"]
    }
  }
}
```

The installed `agent-bridge-mcp` entry point works in place of `python server.py`. Use the Python interpreter you installed into; with another one the server exits and asks for the `mcp` package.

4. Ask your agent to call `bridge_status`, which lists the workers it found, then delegate a first read-only task. This example needs a logged-in Codex CLI. Arguments for `delegate_codex`:

```json
{
  "prompt": "Read src/parser.py and list possible off-by-one errors. Max 150 words.",
  "cwd": "/path/to/project",
  "sandbox": "read-only",
  "timeout_seconds": 300
}
```

The result is a JSON object like this one (shortened, values are examples):

```json
{"ok": true, "id": "3f9c2a71be", "agent": "codex", "model": "<model>", "mode": "read-only", "output": "...", "error": null, "duration_seconds": 131.2}
```

The rest of this page is reference.

## Tools

| Tool | Purpose | Key parameters |
|---|---|---|
| `delegate_codex` | Run a Codex CLI task | `prompt`, `cwd`, `model`, `sandbox`, `reasoning_effort`, `approve_for_me`, `timeout_seconds`, `mcp_servers`, `prompt_file`, `team` |
| `delegate_claude` | Run a task via `claude -p` | `prompt`, `cwd`, `model`, `permission_mode`, `effort`, `timeout_seconds`, `allowed_commands`, `resume_session_id`, `max_budget_usd`, `prompt_file` |
| `delegate_antigravity` | Run an Antigravity (`agy`) task | `prompt`, `cwd`, `model`, `mode`, `effort`, `timeout_seconds`, `resume_session_id`, `prompt_file`, `team` |
| `delegate_local_agent` | Run a local Ollama or OpenCode task | `prompt`, `cwd`, `model`, `mode`, `system`, `temperature`, `max_tokens`, `think`, `timeout_seconds`, `prompt_file` |
| `run_parallel_agents` | Run heterogeneous tasks concurrently | `tasks`, `max_concurrency`, `timeout_seconds` |
| `start_agent_job` | Start a background task | `agent`, `prompt`, `cwd`, `model`, `mode`, `sandbox`, `effort`, `timeout_seconds`, `resume_session_id`, `prompt_file`, `team` |
| `check_agent_job` | Query background job status | `job_id`, `wait_seconds`, `full` |
| `cancel_agent_job` | Cancel a job and terminate its worker (the whole process tree on Windows) | `job_id` |
| `list_agent_jobs` | List background jobs in the current server process | - |
| `bridge_budget` | Read 5-hour and weekly usage limits | `own_usage`, `refresh` |
| `bridge_status` | Report worker availability, cooldowns, budget levels, and notes | `verbose` |
| `bridge_stats` | Summarize delegation logs | `days` |
| `record_outcome` | Record verdict (`accepted`, `fixed`, `rejected`) | `delegation_id`, `verdict`, `note` |
| `set_cooldown` | Set or clear cooldowns (`all` clears every key) | `key`, `minutes`, `reason` |
| `add_worker_note` | Add a dated note under `## <agent>` in `worker_notes.md`, newest first | `agent`, `note` |

## Modes and `team=true`

- **codex (`sandbox`)**: `read-only` (default), `workspace-write`, `danger-full-access` (excluded from default `allowed_modes`).
- **claude (`permission_mode`)**: `read` (default; uses `dontAsk` with `Read,Grep,Glob`, plus command prefixes passed in `allowed_commands`), `edit` (`acceptEdits`; edits files, denies other commands), `auto` (runs commands approved by the safety classifier), `manual`, `dontAsk`, `bypassPermissions` (excluded from default `allowed_modes`). Aliases: `plan` -> `read`, `acceptEdits` -> `edit`, `default` -> `manual`.
- **antigravity (`mode`)**: `plan` (default, read-only), `accept-edits` (write-capable), `auto` (excluded from default `allowed_modes`).
- **local (`mode`)**: `fast` (default, text-only Ollama `/api/chat`), `workspace` (OpenCode read-only; `edit` and `shell` denied), `workspace-write` (OpenCode with `edit` and `shell` allowed; requires an explicit `cwd`). In both workspace modes the total prompt, including the guard header and the rules, is capped at 24,000 characters.
- **`allowed_commands` rule (`delegate_claude`)**: Comma-separated list of command prefixes (up to 20 entries, at most 80 characters per entry). After splitting on commas and stripping whitespace, every entry must match `^[A-Za-z0-9._/\\][A-Za-z0-9._/\\ =+@:-]*$` (no wildcards such as `*` or `?`, `%`, quotes, parentheses, control characters, non-ASCII characters, or leading `-`). Any violation rejects the call with `INVALID_ARGUMENT` before spawning a process.
- **`prompt_file` rule**:
  1. `prompt_file` must be an absolute path and is resolved (following symlinks) with `strict=False`.
  2. Allowed root folders are: (a) the call's `cwd`, only when explicitly passed by the caller and when its resolved path is not a filesystem root, not the user's home folder, and not an ancestor of the home folder; (b) the `agent-bridge` subfolder inside the system temporary directory (`<tempdir>/agent-bridge`, not the entire system temporary directory); (c) each directory in config `prompt_file_roots`, subject to the same root/home/ancestor restriction as `cwd`.
  3. If the resolved path is not inside an allowed root, it is rejected with `ValueError("prompt_file is outside the allowed folders")` (`PROMPT_FILE_INVALID`) before any existence, file-type, or size check.
  4. A case-insensitive deny-list is checked against both the given path and the resolved path: any path component starting with `.claude`, `.codex`, `.gemini`, `.ssh`, `.antigravity`, `.aws`, `.azure`, `.gnupg`, `.kube`, or `.docker`; any file named `.npmrc`, `.netrc`, `_netrc`, `.pypirc`, `.git-credentials`, or `.envrc`; and any file whose name starts with `.env` or ends with `.env`. Blocked paths return the same `"prompt_file is outside the allowed folders"` message.
  5. The target must then be a regular file of at most 200,000 bytes and must decode strictly as UTF-8 (`"prompt_file must be valid UTF-8"` on decode error).
- **`team=true`**: Supported only by `codex` and `antigravity` (`INVALID_ARGUMENT` for other backends). Enables built-in sub-agents on the worker, using the configured lead and sub-agent models (`codex_team_model` / `codex_team_worker_model` or `antigravity_team_model` / `antigravity_team_worker_model`, or `antigravity_tiers` when quota data is available; passing `model` overrides the lead model). Intended for tasks with at least three independent subtasks; token usage is roughly three times a single run.

## Results and Error Classes

Every delegation returns a JSON object with these fields:

| Field | Description |
|---|---|
| `ok` | Success flag (`bool`) |
| `agent`, `model`, `mode` | Backend, model and mode the run used |
| `duration_seconds` | Wall-clock time of the run |
| `error` | Error class name or `null` |
| `output` | Worker response text (truncated above `max_output_chars`, full text written to `output_file`) |
| `files_changed` | Summary of changed files for write-capable runs and Antigravity runs |
| `warnings` | Non-fatal notices such as permission denials, no file changes, or worker-spawned sub-agents |
| `meta` | Metadata such as `num_turns`, `status`, `effort`, `profile`, `tokens_per_sec`, `team`, `subagent_calls` |
| `usage` | Normalized counters: `input`, `output`, `cache_read`, `cache_write`, `cost_usd` |
| `id` | 10-character delegation identifier (matches `job_id` for background jobs) |

Error classes (`error`):

- `EMPTY_PROMPT`: Prompt is empty.
- `PROMPT_FILE_INVALID`: `prompt_file` is not an absolute regular file, exceeds 200,000 bytes, is outside allowed roots, or targets a restricted directory or `.env` file.
- `UNKNOWN_AGENT`: Unknown backend name.
- `INVALID_TASK`: Task object or field type is invalid.
- `INVALID_ARGUMENT`: Invalid argument value (for example, malformed `allowed_commands`, invalid `own_usage`, or `team=true` on an unsupported backend).
- `RECURSION_LIMIT_REACHED`: Current depth reached `AGENT_BRIDGE_MAX_DEPTH`.
- `INVALID_CWD`: `cwd` directory does not exist.
- `CWD_REQUIRED`: `cwd` is empty for a write-capable task.
- `CWD_NOT_ALLOWED`: Write-capable `cwd` points to the home directory, filesystem root, or inside `.claude`, `.claude-pro`, `.codex`, or `.gemini`.
- `CWD_BUSY`: Another active writer holds a lock on the same or an overlapping directory.
- `LOCK_UNAVAILABLE`: Could not open or acquire the lock file.
- `INVALID_MODE`: Mode is invalid for the selected backend.
- `MODE_NOT_ALLOWED`: Mode is not listed in `allowed_modes`.
- `WORKER_PROFILE_MISSING`: No separate Claude worker profile is configured and `claude_allow_orchestrator_account` is false.
- `BINARY_NOT_FOUND`: CLI binary (`claude`, `codex`, or `agy`) was not found.
- `OPENCODE_NOT_FOUND`: `opencode` or `opencode-cli` binary was not found.
- `PROMPT_TOO_LONG`: Local workspace prompt exceeds 24,000 characters.
- `SPAWN_FAILED`: Subprocess failed to start.
- `TIMEOUT`: Execution timed out and the worker was killed (with its whole process tree on Windows).
- `CANCELLED`: Task or background job was cancelled.
- `COOLDOWN`: Target worker or model is in cooldown or its budget level is `blocked`.
- `AUTH_REQUIRED`: Session or API key is missing or invalid.
- `QUOTA_EXHAUSTED`: Rate or usage limit reached.
- `BUDGET_EXHAUSTED`: `max_budget_usd` limit reached.
- `MAX_TURNS`: Claude worker reached its turn limit.
- `EMPTY_OUTPUT`: Read-only run completed with empty output.
- `EMPTY_OUTPUT_TOKEN_LIMIT`: In `fast` mode, `max_tokens` was exhausted during thinking before producing content.
- `OLLAMA_UNAVAILABLE`: Ollama helper could not start or reach Ollama.
- `OLLAMA_REQUEST_FAILED`: Ollama `/api/chat` request failed.
- `WORKER_ERROR`: Unclassified worker failure.
- `INTERNAL_ERROR`: Unhandled exception inside the bridge.
- `STATE_WRITE_FAILED`: `set_cooldown` failed to write `cooldowns.json`.
- `INVALID_VERDICT`: Invalid `verdict` passed to `record_outcome`.
- `UNKNOWN_JOB_ID`: Unknown `job_id` passed to `check_agent_job` or `cancel_agent_job`.

## `config.json` Settings

The home directory is used for `helpers/ensure_ollama.py` lookup, `bin/opencode` lookup, and the fallback working directory when the current working directory is unavailable. It is resolved from environment variable `AGENT_BRIDGE_HOME`, then environment variable `AI_CODING_ROOT` (legacy alias), then `home_dir` in `config.json` (must be a string; relative paths are resolved against the server folder containing `server.py`), and finally the folder that contains `server.py`. A relative `data_dir` (from `AGENT_BRIDGE_DATA_DIR` or `config.json`) is also resolved against the server folder. A custom v2 OpenCode binary must have `"opencode-cli"` in its file name or have `OPENCODE_FORCE_V2` set (`OPENCODE_FORCE_V2=1`).

**Moving from an older private setup**: Set `home_dir` in `config.json` or `AGENT_BRIDGE_HOME` in the environment when `helpers` or `bin` live outside the server folder.

| Key | Default (`config.example.json`) | Description |
|---|---|---|
| `home_dir` | `""` | Base directory fallback (string; relative paths resolve against the server folder) used when `AGENT_BRIDGE_HOME` and `AI_CODING_ROOT` are unset |
| `data_dir` | `"data"` | Directory for logs, locks, jobs, and state files (relative paths resolve against the server folder; overridden by `AGENT_BRIDGE_DATA_DIR`) |
| `opencode_path` | `""` | Explicit path to the `opencode` or `opencode-cli` executable (checked after `OPENCODE_BIN` / `OPENCODE_V2_BIN`) |
| `prompt_file_roots` | `[]` | Additional root directories allowed for `prompt_file` |
| `default_local_model` | `"qwen3.5:9b"` | Default model for `fast` mode (overridden by `AGENT_BRIDGE_LOCAL_MODEL`) |
| `default_local_workspace_model` | `"qwen3.5:9b"` | Default model for `workspace` and `workspace-write` modes |
| `ollama_context_length` | `32768` | Context length for Ollama and OpenCode (overridden by `OLLAMA_CONTEXT_LENGTH`) |
| `ollama_start_wait_seconds` | `60` | Wait timeout in seconds for optional `helpers/ensure_ollama.py` |
| `ollama_takeover` | `"never"` | Policy passed to `ensure_ollama.py` for existing Ollama processes |
| `local_worker_rules_file` | `"local_worker_rules.md"` | Rules file prepended to local workspace prompts |
| `worker_notes_file` | `"worker_notes.md"` | Markdown file used by `add_worker_note` |
| `claude_config_dir` | `""` | Separate `CLAUDE_CONFIG_DIR` for delegated Claude workers (overridden by `AGENT_BRIDGE_CLAUDE_CONFIG_DIR`) |
| `claude_allow_orchestrator_account` | `false` | Allow Claude delegation using the orchestrator's own account when `claude_config_dir` is empty |
| `claude_tools` | `read` / `write` tool sets | Comma-separated `--tools` values for Claude read and write modes |
| `claude_setting_sources` | `"user"` | Value passed to `--setting-sources` for `claude -p` |
| `claude_max_budget_usd` | `0` | Default per-call `--max-budget-usd` cap when `0` is passed (`0` disables) |
| `codex_default_model` | `""` | Default model for solo Codex runs |
| `codex_default_effort` | `"medium"` | Default `model_reasoning_effort` for Codex |
| `codex_worker_mcp` | `"none"` | Codex MCP policy (`"none"` disables all except `mcp_servers`; `"all"` keeps others except `agent-bridge` and `local-llm`) |
| `codex_extra_config` | `["features.network_proxy=false"]` | Extra `-c` flags passed to Codex CLI |
| `codex_team_model` | `"gpt-6.2-astra"` (example) | Lead model used for Codex when `team=true` |
| `codex_team_worker_model` | `"gpt-6.2-sol"` (example) | Sub-agent model named in the Codex `team=true` prompt |
| `antigravity_models` | `[]` | Ordered fallback model list for Antigravity, skipping models in cooldown |
| `antigravity_team_model` | `"gemini-4-argon-high"` (example) | Lead model used for Antigravity when `team=true` |
| `antigravity_team_worker_model` | `"gemini-4-hydrogen-high"` (example) | Sub-agent model named in the Antigravity `team=true` prompt |
| `antigravity_tiers` | `top` / `strong` / `standard` | Tier model names selected by quota state in `budget.py` |
| `antigravity_groups` | Group prefix map | Maps Antigravity model name substrings to quota group keys |
| `allowed_modes` | Per-agent lists | Permitted modes for each backend |
| `max_parallel` | `claude: 1, codex: 2, antigravity: 2` | In-process concurrency cap per backend |
| `cooldown_minutes` | `quota: 30, auth: 10` | Fallback cooldown durations when no reset time is parsed |
| `max_output_chars` | `16000` | Character limit above which `output` is truncated and saved to disk |
| `strip_env_prefixes` | `["CLAUDE", "ANTHROPIC", "USE_LOCAL_OAUTH", "USE_STAGING_OAUTH"]` | Environment variable prefixes stripped from worker subprocesses |
| `budget` | Threshold parameters | Pace and remaining-fraction thresholds used by `budget.py` |

## Environment Variables

| Name | Meaning |
|---|---|
| `AGENT_BRIDGE_CONFIG_PATH` | Path to `config.json` (defaults to `config.json` in the server folder) |
| `AGENT_BRIDGE_HOME` | Home directory for `helpers/ensure_ollama.py` lookup, `bin/opencode` lookup, and fallback working directory |
| `AI_CODING_ROOT` | Legacy alias for `AGENT_BRIDGE_HOME` |
| `AGENT_BRIDGE_DATA_DIR` | Directory for state, logs, locks, jobs, and truncated outputs (relative paths resolve against the server folder) |
| `AGENT_BRIDGE_LOCAL_MODEL` | Default model for `fast` local delegations (overrides `default_local_model`) |
| `AGENT_BRIDGE_CLAUDE_CONFIG_DIR` | Separate `CLAUDE_CONFIG_DIR` profile folder for delegated Claude workers (overrides `claude_config_dir`) |
| `AGENT_BRIDGE_MAX_DEPTH` | Maximum allowed delegation recursion depth (default `1`) |
| `AGENT_BRIDGE_DEPTH` | Current delegation recursion depth (default `0`, incremented in child worker environments) |
| `OLLAMA_BASE_URL` | Base URL for the Ollama API server (default `http://127.0.0.1:11434`) |
| `OLLAMA_CONTEXT_LENGTH` | Context window length (`num_ctx`) for Ollama and OpenCode (overrides `ollama_context_length`) |
| `CLAUDE_BIN` | Explicit path to the `claude` CLI executable |
| `CODEX_BIN` | Explicit path to the `codex` CLI executable |
| `AGY_BIN` | Explicit path to the `agy` CLI executable |
| `OPENCODE_BIN` | Explicit path to the `opencode` or `opencode-cli` executable (takes precedence over `opencode_path`) |
| `OPENCODE_V2_BIN` | Explicit path to the v2 `opencode-cli` executable (takes precedence over `opencode_path`) |
| `OPENCODE_FORCE_V2` | Set to `"1"` to treat the OpenCode binary as v2 even when its file name does not contain `opencode-cli` |
| `CODEX_HOME` | Directory containing Codex `config.toml` for fallback MCP server discovery (defaults to `~/.codex`) |
| `CLAUDE_CODE_GIT_BASH_PATH` | Preserved in the delegated Claude worker environment when present in the parent environment |
| `CLAUDE_CODE_ACCOUNT_UUID` | Compared against the worker profile's `.claude.json` to warn if the worker profile uses the orchestrator's own account |
| `APPDATA` | Windows application data folder used to locate npm Codex and `%APPDATA%/ai.opencode.desktop/cli` |
| `LOCALAPPDATA` | Windows local application data folder used to locate `%LOCALAPPDATA%/agy/bin/agy.exe` |

## State Files and Cooldown

State and log data are stored in `AGENT_BRIDGE_DATA_DIR`, falling back to `data_dir` in `config.json`, or `data/` inside the server folder containing `server.py` (relative `data_dir` values are always resolved against the server folder):

- `delegations.jsonl` (rotates to `delegations.1.jsonl` above 5 MB)
- `cooldowns.json`
- `budget_state.json`
- `quota_history.jsonl`
- `jobs/` (cleaned up after 7 days)
- `locks/` (per-directory write locks; stale locks from dead PIDs or older than 6 hours are removed)
- `outputs/` (full text for truncated outputs; cleaned up after 14 days)
- `local-profile/` (isolated profile directories for OpenCode local workspace runs)

`worker_notes.md` stores dated notes under `## <agent>` headings (`local`, `codex`, `antigravity`, `claude`, `general`). When a run fails with `QUOTA_EXHAUSTED` or `AUTH_REQUIRED`, a cooldown entry is recorded until the parsed reset time or for `cooldown_minutes`. A successful run clears that key's cooldown. To clear a cooldown manually, call `set_cooldown("<key>", 0)`, or `set_cooldown("all", 0)` to clear all keys.

## Usage Budget

`bridge_budget` reads 5-hour and weekly limits for `codex`, `antigravity`, `claude` (only when a separate `claude_config_dir` is configured), and `max` (when `own_usage` JSON text is provided). It returns `order` (sorted from most available to most constrained) along with each department's `level`, `until`, `why`, and scored `buckets`.

Levels:

- `spend`: sufficient weekly margin or nearing weekly reset with unused quota.
- `normal`: usage pace is within normal bounds.
- `unknown`: no fresh data (snapshots older than 15 minutes expire); does not block delegations.
- `save`: running ahead of pace or low 5-hour quota; attaches a `BUDGET:` warning to delegation results.
- `blocked`: quota is exhausted (`<= 2%` remaining or provider-blocked); delegations fail immediately with `COOLDOWN` without spawning a worker process.

For Antigravity, `budget.py` maps quota groups to `antigravity_tiers` to pick `strong`/`team_head`, `single`, and `team_worker` models. Cached snapshots are reused for 120 seconds unless `refresh=True` is passed, and completed delegations trigger a background refresh for that backend. To view the budget table from the command line:

```bash
python budget.py
```

Supported flags: `--json`, `--refresh`, and `--own '<json>'`.

## Troubleshooting

1. **`AUTH_REQUIRED` from the Claude worker:** Log in to the worker profile: set `CLAUDE_CONFIG_DIR` to that profile folder, run `claude /login`, then clear the cooldown with `set_cooldown("claude", 0)`.
2. **Codex Windows sandbox triggers UAC prompts:** Keep `features.network_proxy=false` in `codex_extra_config`; switching between `read-only` and `workspace-write` with the network proxy enabled triggers elevated Windows sandbox setup.
3. **Changes to `server.py` do not take effect:** MCP clients load `server.py` when starting the server process; start a new MCP session or restart the client after editing `server.py`.

## Tests

Run the unit test suite from the repository root:

```bash
python -m unittest discover -s tests
```