agy_subagents
# codex-agy-subagents
**Turn Google Antigravity CLI (`agy`) into a native-feeling primary/overflow subagent pool for OpenAI Codex — zero third-party dependencies.**
[English](README.md) | [简体中文](README.zh-CN.md) | [Architecture](docs/architecture.md)
[](pyproject.toml)
[-brightgreen.svg)](pyproject.toml)
[](codex_agy_subagents/mcp_server.py)
[](LICENSE)
---
## Why This Project Exists (The Pain Points)
If you do most of your daily engineering inside **OpenAI Codex**, migrating away is painful — your conversation history, project memories, skills, and workflow live in Codex. Yet relying exclusively on Codex's built-in subagents quickly hits four real-world bottlenecks:
1. **Hard 6-subagent concurrency ceiling**: Codex limits concurrent native subagent threads (default 6), forcing large multi-module tasks to serialize.
2. **Slow & expensive native loops**: Over-defensive native execution and high per-token cost make heavy parallel research, log triage, and multi-file edits noticeably slow and pricey.
3. **External MCP tools get silently ignored by Codex**: Modern Codex builds enable `tool_search_always_defer_mcp_tools = true`, hiding external MCP tool schemas from initial context. Even after registering a normal MCP server, Codex's `ultra` mode keeps reflexively calling native `spawn_agent` and ignores external agents unless you manually remind it every turn.
4. **Naive CLI bridges feel nothing like native subagents (and risk rate-limit bans)**: Synchronous wrappers block the main loop and hit 60s MCP timeouts; lack multi-turn follow-up (`send_input`); leave orphan processes/worktrees on Windows; or blast dozens of concurrent requests into a single account at once, triggering 429 storms.
---
## What `codex-agy-subagents` Does
Keep **Codex** as your primary brain (retaining all your conversations, memories, planning, and final code review) while transparently delegating parallel subagent work to your locally authenticated **Antigravity CLI (`agy`)** — with an experience virtually identical to Codex's own built-in subagents:
- **1:1 Native Subagent Lifecycle Symmetry (6 Focused Tools)**:
| Codex Native | `agy_subagents` MCP Tool | Capability |
| :--- | :--- | :--- |
| `spawn_agent` | `mcp__agy_subagents__agy_spawn_agent` | Non-blocking async spawn; immediately returns `agent_id` |
| `wait` / `wait_agent` | `mcp__agy_subagents__agy_wait_agent` | Event-driven batch wait on `agent_ids` (`wait_for="any"` or `"all"`) |
| `send_input` | `mcp__agy_subagents__agy_send_input` | True multi-turn continuation via `agy --conversation <id>` + live mailbox queueing |
| thread status | `mcp__agy_subagents__agy_status` | Non-blocking pool, queue, live step progress, and cooldown inspection |
| `close_agent` | `mcp__agy_subagents__agy_close_agent` | Kills full OS process tree (Windows `taskkill /T /F` / POSIX process group) & cleans Git worktree |
| — | `mcp__agy_subagents__agy_health` | Zero-quota readiness check (binary, proxy, available `agy models`, pool status) |
- **Automatic Invocation Without Manual Reminders**:
- Injects an **AGY-FIRST** (or **AGY-OVERFLOW**) routing policy into Codex's top-level `developer_instructions` (which lands as the very first `role: "developer"` message in both Codex Desktop and Codex CLI — zero hook-trust popups required), reinforced by `AGENTS.md`, a bundled `agy-subagents` Skill, and optional Codex lifecycle hooks (`UserPromptSubmit` / `PreToolUse` / `SubagentStart` / `SubagentStop`).
- Automatic native fallback: if `agy_subagents` enters a 429/auth cooldown, Codex seamlessly falls back to native `spawn_agent`.
- **Smart Tiered Model Routing**:
- **Light tasks** (`tier="light"` / `explorer` / `researcher`) → `gemini-4-hydrogen-xhigh` (fast, read-only sandboxed).
- **Heavy tasks** (`tier="heavy"` / `worker` / `reviewer`) → `gemini-4-neon-xhigh` (deep implementation, debugging, review).
- Fully configurable via environment variables or per-call overrides.
- **Safe Parallel Writes with Git Worktree Isolation & Scope Auditing**:
- Read-only agents share `cwd` with `--sandbox` (zero disk copy overhead).
- Concurrent write agents run in isolated Git worktrees (`agy-sub/<agent_id>`) outside the repo, audit every changed file against `owned_paths` (`scope_status` / `scope_violations`), return `diff_stat`, and **never auto-merge**.
- **Account-Safe Concurrency & Rate-Limit Guardrails**:
- Strictly executes the official local `agy` binary — never reads, stores, intercepts, or forwards OAuth tokens.
- **Queue vs. concurrency decoupling**: Codex can fan out up to **32 queued subagents** in one burst while active `agy` processes stay smoothly throttled (default **5** concurrent).
- **Staggered launch jitter** (`1.5s`) prevents sudden QPS spikes.
- **Exponential-backoff circuit breaker** pauses new launches on `429` / quota / auth errors instead of hammering retries.
- **No nested recursion**: explicitly blocks `agy` workers from spawning nested subagents (preventing both concurrency explosions and `agy -p` stdout result loss).
- **Zero Dependencies & First-Class Windows Support**:
- Pure Python 3.10+ standard library — boots in `<100ms`, zero `pip` packages needed, `CREATE_NO_WINDOW` (no flashing terminal popups), closed `stdin` (prevents `agy -p` hangs), disk-persisted run records (`meta.json`, `output.txt`, `events.jsonl`).
---
## Prerequisites
- **Python 3.10+**
- **Git** (for optional `isolation="worktree"` concurrent writes)
- **OpenAI Codex Desktop or Codex CLI** with MCP support
- **Google Antigravity CLI (`agy` v1.1.15+, tested on v1.5.9)** installed and logged in locally:
```bash
agy --version
agy models
```
---
## Quick Start
### Option 1: One-Command Installer (Recommended)
```bash
git clone https://github.com/Sereneoned/codex-agy-subagents.git
cd codex-agy-subagents
# Preview changes first (makes no edits)
python scripts/install_codex.py --dry-run
# Install in AGY-FIRST mode (prefer agy, keep Codex native subagents as fallback)
python scripts/install_codex.py --mode agy-first
# Optional: pass a local proxy and custom models/concurrency
python scripts/install_codex.py \
--mode agy-first \
--light-model gemini-4-hydrogen-xhigh \
--heavy-model gemini-4-neon-xhigh \
--max-concurrent 5 \
--proxy-url http://127.0.0.1:7890
```
> Prefer overflow-only mode (fill Codex's 6 native slots first, overflow #7+ to `agy`)? Pass `--mode overflow`.
> Want optional Codex CLI lifecycle hooks (`~/.codex/hooks.json`) too? Add `--with-hooks`.
Then **restart Codex Desktop / CLI** and start a new conversation.
### Option 2: Manual Setup
1. Copy the templates from [`examples/config.toml.example`](examples/config.toml.example) into `~/.codex/config.toml` (be sure to keep `tool_timeout_sec = 900` so `agy_wait_agent` never trips Codex's 60s default timeout).
2. Append [`examples/AGENTS.md.example`](examples/AGENTS.md.example) to `~/.codex/AGENTS.md`.
3. Copy [`skills/agy-subagents/SKILL.md`](skills/agy-subagents/SKILL.md) to `~/.codex/skills/agy-subagents/SKILL.md`.
4. Restart Codex and verify with `codex mcp get agy_subagents`.
### Verify It Works
In a fresh Codex chat, try a multi-part task (or run a quick check):
> *"Check `agy_health`, then spawn two parallel `agy` subagents — one light and one heavy — to inspect two different modules and summarize both."*
Active run logs and transcripts are persisted under:
- Windows: `%LOCALAPPDATA%\codex-agy-subagents\runs\`
- macOS/Linux: `~/.local/share/codex-agy-subagents/runs/`
---
## Configuration Reference
All settings live under `[mcp_servers.agy_subagents.env]` in `~/.codex/config.toml`:
| Env Variable | Default | Description |
| :--- | :--- | :--- |
| `AGY_BIN` | auto-detected (`agy` / `~/.gemini/bin/agy`) | Explicit path to the `agy` executable |
| `AGY_LIGHT_MODEL` | `gemini-4-hydrogen-xhigh` | Default model for `tier="light"` (`explorer` / `researcher`) |
| `AGY_HEAVY_MODEL` | `gemini-4-neon-xhigh` | Default model for `tier="heavy"` (`worker` / `reviewer`) |
| `AGY_MAX_CONCURRENT` | `5` | Max live concurrent `agy` subprocesses (`1`–`16`; `4`–`6` recommended) |
| `AGY_MAX_QUEUE` | `32` | Max queued + active subagents accepted per burst (`1`–`64`) |
| `AGY_STAGGER_SEC` | `1.5` | Minimum delay between consecutive launches (seconds) |
| `AGY_COOLDOWN_BASE_SEC` | `15` | Base exponential-backoff pause on `429` / auth errors |
| `AGY_COOLDOWN_MAX_SEC` | `180` | Max circuit-breaker cooldown duration |
| `AGY_DEFAULT_TIMEOUT_SEC` | `600` | Default per-turn timeout passed to `--print-timeout` |
| `AGY_MAX_OUTPUT_CHARS` | `16000` | Max chars returned inline (full output always saved to `output.txt`) |
| `AGY_PROXY_URL` | *(inherits `HTTP(S)_PROXY`)* | Optional proxy URL forwarded to `agy` (set `AGY_NO_PROXY=1` to disable) |
| `AGY_STATE_DIR` | `%LOCALAPPDATA%\codex-agy-subagents` | Directory for persisted run state, transcripts, and worktrees |
---
## Safety & Account Hygiene Notes
- This project **only calls the official `agy` CLI** through documented headless flags (`-p`, `--output-format stream-json`, `--conversation`, `--model`, `--sandbox`). It does **not** reverse-engineer private APIs, scrape or forward OAuth tokens, or rotate credentials.
- If you manage multiple Antigravity accounts with external tools (such as Cockpit Tools), avoid switching accounts mid-flight while `agy` subagents are actively running, as overwriting the shared CLI token file can interrupt in-progress turns or `--conversation` continuations.
- Keep `AGY_MAX_CONCURRENT` moderate (`4`–`6`) and let the queue (`32`) + stagger (`1.5s`) smooth out large parallel bursts.
---
## Development & Tests
```bash
python -m unittest discover -s tests -v
```
Tests run completely offline using a deterministic mock runner plus real local Git worktrees, MCP JSON-RPC protocol checks, circuit-breaker verification, and Codex hook tests.
See [docs/architecture.md](docs/architecture.md) for full technical internals.
## License
[MIT](LICENSE)
TDQS
Scored across 6 tools
Each tool maps to a distinct phase of the subagent lifecycle: spawn, wait, send_input, status, close, health. Descriptions explicitly delineate blocking vs non-blocking and clarify that agy_status is read-only inspection while agy_wait_agent blocks for results, so there is no realistic misselection.
All tools share a uniform agy_ snake_case prefix and readable names. The only inconsistency is style: most use verbs (spawn, wait, send, close) while agy_status and agy_health are noun-style inspection tools, a minor but noticeable deviation.
Six tools cover the complete subagent lifecycle without redundancy, matching the mirrored native Codex primitives almost one-to-one. Nothing feels padded or missing at this scope.
Spawn, wait, follow-up input, status, close, and health give full lifecycle coverage including worktree cleanup and pool diagnostics. Minor gaps: no explicit enumeration of individual agent IDs or metadata beyond the pool aggregate, and no dedicated result-retrieval tool once an agent has already been collected.