agent-codexcli
# Agent-CodexCLI
English | [简体中文](./README.zh-CN.md)
**Agent-CodexCLI** (`agent-codexcli`) is an MCP server and Agent Skill that lets any MCP-compatible AI agent orchestrate your local [OpenAI Codex CLI](https://github.com/openai/codex) as an execution engine — with session reuse, async polling, mid-flight steering, bounded process-tree cleanup, Git diff tracking, and quota safeguards.
## Features
- **Session Reuse (`session_id`)**: Resume existing Codex threads (`codex exec resume`) to preserve conversation context, prompt cache, and saved session permissions (unless explicitly overridden).
- **Async Execution & Progress Notifications**: Long-running tasks return a lightweight `running` payload (`task_id`, `status`, `session_id`, `elapsed_ms`) once `wait_seconds` elapses, emitting MCP progress notifications every 15 seconds when the client supplies a `progressToken`. Poll with `codex_wait` or check via `codex_status`.
- **Mid-Flight Steering (`codex_steer`)**: Interrupt an active run (once its `session_id` is available) and immediately resume the same `session_id` with updated instructions (`mode: "interrupt"`, default), or enqueue a follow-up (`mode: "queue"`).
- **Focused Reviews (`codex_review`)**: Run `codex exec review` (read-only by default; accepts a `sandbox` override) against uncommitted changes, a base branch, a specific commit, or custom instructions.
- **Process-Tree & Pipe Cleanup**: Terminates Codex and child processes on Windows (`taskkill` + CIM creation-time bounds) and POSIX (detached process group `-pid`), with bounded pipe-drain timeouts so leaked descriptors cannot hang callers.
- **Safe Executable Discovery & Git Summaries**: Resolves `git` and `codex` from trusted absolute `PATH` entries (ignoring working-directory/relative `PATH` entries and disabling `core.fsmonitor`), and captures baseline snapshots before writable runs for best-effort `changed_files` and `git_diff_stat` reporting.
- **Quota & Reset-Card Safeguards**: Automatically stops tasks on HTTP 429 or structured/text quota exhaustion (`status: "rate_limited"`) and includes a best-effort prompt guard against accidental `/usage` or quota reset-card triggers.
## Prerequisites
- **Node.js** `>= 22.0.0`
- **Git** on `PATH` (required for snapshot-based change reporting and Git tests)
- **Codex CLI** (`@openai/codex`) installed locally and authenticated (for example via `codex login` or your configured provider in `~/.codex/config.toml`)
## Installation & Build
```bash
git clone https://github.com/ZqwerR/Agent-CodexCLI.git
cd Agent-CodexCLI
npm install
npm run build
```
## MCP Client Setup
### Generic MCP Client
Add `agent-codexcli` to your MCP client configuration (replace `/path/to/Agent-CodexCLI` with your cloned directory):
```json
{
"mcpServers": {
"agent-codexcli": {
"command": "node",
"args": ["/path/to/Agent-CodexCLI/dist/index.js"]
}
}
}
```
### Installing the Agent Skill
Copy `skills/agent-codexcli` to your agent's skills directory (for example `~/.agents/skills/agent-codexcli` or `~/.gemini/config/skills/agent-codexcli`) so your orchestrator agent follows the recommended workflow automatically.
---
## Antigravity Setup & Best Practices
Antigravity uses a **180-second (3m0s)** default per-call MCP timeout (and exposes `timeoutSeconds` in server configuration). When configuring `agent-codexcli` in `~/.gemini/config/mcp_config.json`, setting both wait budgets to **165 seconds** leaves a margin below the default cap (note that launch/Git snapshot work or interrupt steering adds minor overhead, so 165s is a margin rather than a hard guarantee):
```json
{
"mcpServers": {
"agent-codexcli": {
"command": "node",
"args": ["C:/path/to/Agent-CodexCLI/dist/index.js"],
"env": {
"CODEX_DEFAULT_WAIT_SECONDS": "165",
"CODEX_DEFAULT_POLL_WAIT_SECONDS": "165"
}
}
}
}
```
- For strict host deadlines, pass `wait_seconds: 0` to get `task_id` immediately, then poll with bounded `codex_wait(task_id, wait_seconds: 150)`.
- Avoid passing `wait_seconds >= 180` inside Antigravity unless you also raised `timeoutSeconds` in `mcp_config.json`.
- Copy `skills/agent-codexcli` to `~/.gemini/config/skills/agent-codexcli` to enable `/agent-codexcli`.
- On **Windows**, see [Sandbox, Permissions & Windows Compatibility](#sandbox-permissions--windows-compatibility) before opting into `danger-full-access`.
---
## Model & Reasoning Effort Inheritance
By default, **Agent-CodexCLI does NOT force a model or reasoning effort**:
- When `CODEX_DEFAULT_MODEL` and `CODEX_DEFAULT_REASONING_EFFORT` are unset (and not passed per tool call), `agent-codexcli` omits `--model`, `review_model`, and `model_reasoning_effort` so Codex CLI directly **inherits your local `~/.codex/config.toml`** (including custom providers, auth, MCPs, and plugins).
- If you set `CODEX_DEFAULT_MODEL` or pass `model` per call, `codex_run` / `codex_steer` pass `--model=...`, and `codex_review` sets both `--model=...` and `-c review_model=...`.
- Reported `model` and `reasoning_effort` fields in task summaries reflect requested overrides (and are omitted when inherited from `~/.codex/config.toml`).
## Sandbox, Permissions & Windows Compatibility
- **New `codex_run` tasks** default to **`workspace-write`** across all platforms (overridable via `CODEX_DEFAULT_SANDBOX` or per-call `sandbox`). Note that passing an explicit sandbox flag on new runs overrides named Codex permission profiles from `config.toml`.
- **Resuming sessions (`codex_run(session_id=...)`)**: When `sandbox` is omitted on resume, `agent-codexcli` omits `-c sandbox_mode=...` so Codex preserves the session's saved permissions instead of silently widening a `read-only` session.
- **`codex_review`** defaults to **`read-only`** independently of `CODEX_DEFAULT_SANDBOX` (and accepts an explicit `sandbox` override if needed).
- **Windows Trusted-Use Note**: Codex CLI's `workspace-write` sandbox on Windows can break child commands or file/tool calls. After troubleshooting `workspace-write` in trusted repositories, you can explicitly opt in by passing `sandbox: "danger-full-access"` on `codex_run` or setting `"CODEX_DEFAULT_SANDBOX": "danger-full-access"` in your MCP server `env`.
## Operational Notes, Logs & Safeguards
- **Rate-Limit Circuit Breaker**: If Codex outputs HTTP 429 or structured/text quota errors (`insufficient_quota`, `usage_limit_reached`, etc.), `agent-codexcli` terminates the process tree and preserves `status: "rate_limited"` (`rate_limited: true`) with `rate_limit_reason`. Do not automatically retry; report the reason to the user.
- **Best-Effort Reset-Card Prompt Guard**: Prompts instructing Codex to run `/usage` or redeem a quota reset card are blocked by default (negated mentions like `"Do not run /usage"` and normal paths like `docs/usage.md` are allowed). Opt out with `CODEX_DISABLE_RESET_CARD_GUARD=1` (or `true`).
- **`codex_steer` `queue` Mode**: Rejects per-call `model`, `reasoning_effort`, and `sandbox` overrides (uses saved session settings), and passes the message via CLI flags (`--message=...`), which are visible to local process inspection and subject to platform command-line length limits.
- **Git Change Summaries**: Best-effort snapshots can capture concurrent external workspace edits; untracked files appear in `changed_files` without appearing in `git_diff_stat`.
- **Diagnostic Logs**: Per-task `.log` files are stored in a private user state directory by default (`%LOCALAPPDATA%/agent-codexcli/logs` on Windows; `$XDG_STATE_HOME/agent-codexcli/logs` or `~/.local/state/agent-codexcli/logs` on macOS/Linux). Logs contain raw prompts, command output, and diagnostics and may include sensitive project data; retention is bounded by `CODEX_MAX_LOG_FILES` (default `100`).
## Tool Reference
| Tool | Purpose | Key Parameters |
| --- | --- | --- |
| `codex_run` | Start a new Codex task or resume a `session_id` | `prompt`, `cwd`, `session_id`, `sandbox`, `model`, `reasoning_effort`, `wait_seconds`, `worktree`, `add_dirs`, `images`, `skip_git_repo_check` |
| `codex_review` | Run `codex exec review` (read-only by default) | `cwd`, `uncommitted`, `base`, `commit`, `prompt`, `title`, `sandbox`, `model`, `reasoning_effort`, `wait_seconds` |
| `codex_wait` | Wait for a running task to complete or return minimal running status | `task_id`, `wait_seconds` |
| `codex_status` | Non-blocking check of one task or list of all tracked tasks | `task_id` (optional) |
| `codex_steer` | Interrupt & resume a session (default) or enqueue a follow-up | `prompt`, `task_id` / `session_id`, `mode` (`interrupt` \| `queue`), `cwd`, `sandbox`, `model`, `reasoning_effort`, `wait_seconds`, `queue_resume` |
| `codex_cancel` | Terminate a running task and its child process tree | `task_id` |
## Environment Variables
| Variable | Default | Effect |
| --- | --- | --- |
| `CODEX_DEFAULT_MODEL` | *(unset — inherits `~/.codex/config.toml`)* | Default `--model` (and `review_model` for reviews) override when not specified per call. |
| `CODEX_DEFAULT_REASONING_EFFORT` | *(unset — inherits `~/.codex/config.toml`)* | Default `model_reasoning_effort` override when not specified per call. |
| `CODEX_DEFAULT_SANDBOX` | `workspace-write` | Default sandbox for new `codex_run` tasks (`workspace-write`, `danger-full-access`, or `read-only`). |
| `CODEX_DEFAULT_WAIT_SECONDS` | `300` | Initial sync wait for `codex_run`, `codex_review`, and interrupt `codex_steer` (0–600; e.g. `165` in Antigravity). |
| `CODEX_DEFAULT_POLL_WAIT_SECONDS` | `180` | Wait budget for `codex_wait` (0–600; e.g. `165` in Antigravity). |
| `CODEX_CLI_PATH` | Auto-detected | Explicit path or absolute-`PATH` command for `codex` / `codex.exe` / npm `codex.js`. |
| `CODEX_LOG_DIR` | Private user state dir | Directory for per-task `.log` diagnostics (established before spawning Codex). |
| `CODEX_MAX_TASKS` | `50` | Number of completed tasks retained in memory (5–500). |
| `CODEX_MAX_CONCURRENT_TASKS` | `8` | Maximum simultaneous active Codex tasks (1–50). |
| `CODEX_MAX_LOG_FILES` | `100` | Maximum retained `codex_*.log` files in `CODEX_LOG_DIR` (`0` disables pruning, max `10000`). |
| `CODEX_EXTRA_RATE_LIMIT_PATTERNS` | *(empty)* | Comma-separated regexes or substrings for custom provider rate-limit detection. |
| `CODEX_DISABLE_RESET_CARD_GUARD` | `0` | Set to `1` or `true` to disable the best-effort `/usage` & reset-card prompt guard. |
## Development & Testing
```bash
npm install
npm run typecheck
npm run build
npm test
```
`npm test` runs TypeScript type-checking, compiles `dist/`, and executes the regression suite in `tests/regression.test.mjs` using `tests/fake-codex.mjs`.
## License
[MIT](./LICENSE)
TDQS
Scored across 6 tools
codex_run and codex_steer can both target an existing session, but the descriptions separate continuing a run from interrupting/steering it. wait, status, cancel, and review are clearly differentiated, leaving only minor overlap around session continuation.
All six tools use the codex_ prefix plus a concise snake_case action (run, review, wait, status, steer, cancel), making names highly predictable. status is a noun rather than a verb, but it still fits the consistent action-style pattern.
Six tools map neatly to launching, reviewing, monitoring, waiting on, steering, and cancelling Codex CLI work. There is no obvious padding, and the count is well-scoped for an async CLI execution wrapper.
The set covers the core async execution lifecycle and a read-only review path, with status also serving as a list operation. Minor gaps remain: no dedicated output/history retrieval beyond wait/status, and session management is only implicit through run and steer.