Skip to main content
Glama
README.md
# External Swarm (`swarm-claude-codex`)

[![CI](https://github.com/teasunning0721/swarm-claude-codex/actions/workflows/ci.yml/badge.svg)](https://github.com/teasunning0721/swarm-claude-codex/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Node.js >= 20](https://img.shields.io/badge/Node.js-%3E%3D20-339933?logo=node.js&logoColor=white)](https://nodejs.org/)
[![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](package.json)

A self-contained, cross-platform Antigravity plugin and bidirectional stdio MCP bridge that enables **Antigravity**, **Claude Code (`claude`)**, and **OpenAI Codex (`codex`)** to invoke one another as subagents with full live visualization, Git worktree isolation, lifecycle hooks, and interactive Q&A controls.

- **Zero external npm dependencies** (pure Node.js >= 20 ESM)
- **Cross-platform** (Windows, macOS, Linux) with POSIX `0o700`/`0o600` run-store permission hardening and symlink protection
- **Bundled always-on AI rule (`rules/AGENTS.md`)** and **Antigravity lifecycle hooks (`hooks.json`)** (`PreInvocation` + `Stop`) that keep the host agent notified about `Needs Input`, newly finished runs, and active background subagents — and auto-install missing CLIs / MCP registrations when absent
- **High-context, Full Access, Official Plugin & Auto-Archive Defaults**: Launches **Claude Code** with **1M context** (`[1m]` model suffix + `--autocompact 1M`) and **`--chrome`** browser integration, and **Codex / GPT** with **666K context** (`model_context_window=666000`, `model_auto_compact_token_limit=580000`) plus official browser/computer-use/plugin features enabled, **Full Access** by default (`bypassPermissions` / `danger-full-access` + `approval_policy="never"`, opt-out via `--sandboxed`), automatic `chrome-devtools` MCP bridging & auto-approval across hosts, and **automatic Codex session archiving** on completion (keeps Codex Desktop's sidebar clean while seamlessly auto-unarchiving & re-archiving on follow-ups; `--no-archive` / `--auto-archive off` to opt out, `--archive-finished` to archive leftover External Swarm threads)
- **Git Worktree parallel write isolation** (`--worktree` / `worktree: true`) so concurrent write-mode subagents never collide on the main working tree
- **Bidirectional `claude <-> codex` subagent invocation & Live Mid-Run Steering** across **10 `external_swarm_*` MCP tools** (`spawn`, `followup`, `steer`, `status`, `list`, `kill`, `settings`, `wait`, `note`, `ask`) with real-time Claude `stream-json` & Codex `app-server` (`turn/steer` / `turn/interrupt`) steering channels, unified parent-child run trees, and **per-conversation isolation** (`This chat` / `All chats`)
- **Official-`swarm`-parity side-pane UI** (`Overview`, `Tree`, `Graph`, `Raw`, `Detail` with Compact/Detailed timeline, Needs Input inline reply box, Changed Files summary, Export Markdown, local model autocomplete, `Stopped` vs `Failed` counters, and unlimited timeout controls)

---

## AI Quickstart Prompt (Copy-Paste into Antigravity)

Want your AI assistant to set everything up automatically (including installing missing `claude` / `codex` CLIs)? Paste this into Antigravity:

> Install and set up `https://github.com/teasunning0721/swarm-claude-codex` as an Antigravity plugin (`node scripts/setup.mjs --yes --install-clis`). If `claude` or `codex` CLI is missing on this machine, install it automatically and verify with `node scripts/setup.mjs --verify --json`. Once ready, let me know if any CLI still needs one-time login.

Once installed, the bundled always-on rule (`rules/AGENTS.md`), lifecycle hooks (`hooks.json`), and skills (`skills/external-swarm`, `skills/delegate-claude-codex`) are automatically loaded by Antigravity so the AI knows how to delegate to Claude Code and Codex, isolate parallel edits with Git worktrees, wait cleanly for async runs, answer interactive questions, and clean up finished runs.

---

## Requirements

- **Node.js** `>= 20.0.0` (tested in CI on Node 20 and 22 across Ubuntu, macOS, and Windows)
- **Claude Code CLI** (`claude`) and/or **OpenAI Codex CLI** (`codex`) — can be installed automatically via `node scripts/setup.mjs --yes --install-clis` if missing
- **Git** (optional; required only when using `--worktree` isolation or changed-files inspection)
- **Antigravity** (optional for standalone CLI/MCP usage; required for the native side-pane UI and `hooks.json` lifecycle notifications)

---

## One-Click Installation & Setup

Clone the repository from [https://github.com/teasunning0721/swarm-claude-codex](https://github.com/teasunning0721/swarm-claude-codex) (or download it), then run the cross-platform setup tool:

```bash
git clone https://github.com/teasunning0721/swarm-claude-codex.git
cd swarm-claude-codex
# Register plugin, hooks, always-on AI rules, skills, and MCP bridges:
node scripts/setup.mjs --yes

# Or also auto-install missing Claude Code and/or Codex CLIs in one step:
node scripts/setup.mjs --yes --install-clis
```

Preview planned changes without modifying any files first:

```bash
node scripts/setup.mjs --dry-run
```

Verify all registrations (read-only):

```bash
node scripts/setup.mjs --verify
```

Uninstall `external-swarm` registrations cleanly without touching your other plugins or MCP servers:

```bash
node scripts/setup.mjs --uninstall --yes
```

### Setup Options

| Flag | Description |
| --- | --- |
| `-y, --yes` | Non-interactive confirmation (default) |
| `--dry-run` | Print planned changes without writing to disk |
| `--verify` | Verify plugin files, `hooks.json` / `hooks/swarm-hook.mjs`, `rules/AGENTS.md`, Antigravity `config.json`, skills, Claude `.claude.json`, and Codex `config.toml` |
| `--uninstall` | Remove `external-swarm` registrations and installed copies |
| `--install-clis` | Auto-install missing Claude Code and/or Codex CLIs using official installers (skips already-installed CLIs) |
| `--install-claude` | Auto-install Claude Code CLI if missing |
| `--install-codex` | Auto-install OpenAI Codex CLI if missing |
| `--link` | Symlink/junction plugin and skills instead of copying |
| `--skip-antigravity` | Skip Antigravity plugin files and `config.json` |
| `--skip-skills` | Skip installing `skills/` into Antigravity skills directory |
| `--skip-claude` | Skip registering `external_swarm` in `~/.claude.json` |
| `--skip-codex` | Skip registering `[mcp_servers.external_swarm]` in `~/.codex/config.toml` |
| `--json` | Emit structured JSON output |

### What `setup.mjs` Registers

1. **Antigravity Plugin, Hooks & Sidecar**: Copies runtime files (including `hooks.json`, `hooks/swarm-hook.mjs`, and `rules/AGENTS.md`) to `~/.gemini/config/plugins/external-swarm` (or `%USERPROFILE%\.gemini\config\plugins\external-swarm` on Windows) and merges `plugins["external-swarm"]` + `sidecars["external-swarm/board"]` into `config.json` while preserving all existing settings.
2. **Antigravity Skills**: Installs `external-swarm` and `delegate-claude-codex` into `~/.gemini/config/skills/`.
3. **Claude Code MCP Bridge**: Merges `mcpServers.external_swarm` into `~/.claude.json` (`env: {}` so run directories resolve dynamically at runtime).
4. **Codex MCP Bridge**: Updates `[mcp_servers.external_swarm]` in `~/.codex/config.toml` while preserving comments, top-level keys, and all other tables.

---

## Usage

### 1. CLI Delegation (`scripts/delegate.mjs`)

```bash
# Read-only review with Codex
node scripts/delegate.mjs codex --cwd "<repo>" --mode readonly --effort high --title "Architecture review" --json -- "Review lib/store.mjs for edge cases."

# Scoped write task with Claude Code
node scripts/delegate.mjs claude --cwd "<repo>" --mode write --title "Fix edge case" --json -- "Fix the parser bug and run tests."

# Parallel write task isolated in a managed Git worktree (ext-swarm/<runId>)
node scripts/delegate.mjs claude --cwd "<repo>" --mode write --worktree --title "Isolated refactor" --json -- "Refactor module A and run unit tests."

# Uncommitted diff review
node scripts/delegate.mjs codex --cwd "<repo>" --mode review --uncommitted --title "Diff review" --json

# Multi-turn follow-up using sessionId (automatically reuses an active managed worktree)
node scripts/delegate.mjs claude --cwd "<repo>" --resume "<sessionId>" --parent-run-id "<runId>" --mode readonly --title "Follow-up" --json -- "Summarize remaining risks."

# Event-driven wait, live mid-run steering, answer interactive questions, export Markdown, and clean up worktrees
node scripts/delegate.mjs --wait "<runId1>,<runId2>" --wait-mode any --timeout 300 --json
node scripts/delegate.mjs --steer "<runId>" --text "Focus on module B next." --json
node scripts/delegate.mjs --steer "<runId>" --interrupt --text "Stop current refactor and switch to option B." --json
node scripts/delegate.mjs --answer "<runId>" --text "Proceed with option B" --json
node scripts/delegate.mjs --export-md "<runId>"
node scripts/delegate.mjs --cleanup-worktree "<runId>" --json

# Inspect tree, run status, toggle auto-timeout (default 1h / off = unlimited), terminate a run tree, or clean up finished runs
node scripts/delegate.mjs --list --this-chat --json
node scripts/delegate.mjs --status "<runId>" --json
node scripts/delegate.mjs --config --json
node scripts/delegate.mjs --auto-timeout off --json
node scripts/delegate.mjs --disable-timeout "<runId>" --json
node scripts/delegate.mjs --kill "<runId>" --cascade --json
node scripts/delegate.mjs --clear-finished --this-chat --json
```

Large prompts can be piped via stdin using `--prompt -`.

### 2. Bidirectional `claude <-> codex` Mutual Calls (Stdio MCP Bridge)

`lib/mcp-server.mjs` implements a dependency-free newline-delimited JSON-RPC 2.0 stdio MCP server exposing **10 tools** (prefixed `external_swarm_*` to avoid collisions with built-in plugins):

- `external_swarm_spawn` — Spawn a `claude` or `codex` child run (`wait: true` by default; `wait: false` for async background execution; `worktree: true` for isolated Git worktree edits; `noTimeout: true` for unlimited runtime). Returns `worktree` and `changedFiles` metadata on completion.
- `external_swarm_followup` — Resume an existing run's `sessionId` with a follow-up prompt (automatically reuses an uncleaned managed worktree when present).
- `external_swarm_steer` — Inject a live mid-run steering or interjection message into an active `claude` (`stream-json`) or `codex` (`app-server` `turn/steer` / `turn/interrupt`) run without killing or restarting it (`mode: "steer" | "interrupt"`).
- `external_swarm_wait` — Event-driven wait (`fs.watch` + low-frequency fallback) for one or more async `runIds` (`mode: "any" | "all"`, `timeoutSec`), resolving immediately when targeted runs finish or request input (`needsInput` in `"any"` mode) — no tight polling loops.
- `external_swarm_note` — Post a structured progress note (`level: "info" | "warn" | "milestone"`) onto the current or target run's live timeline.
- `external_swarm_ask` — Ask the user or parent agent a question (`prompt`, optional `choices[]`), mark the run `Needs Input` in the side pane, and optionally wait (`wait !== false`) until answered via the side pane or `delegate.mjs --answer`.
- `external_swarm_status` — Read run metadata (`needsInput`, `pendingQuestion`, `worktree`, `changedFiles`) and recent timeline events.
- `external_swarm_list` — List runs and parent-child call trees (filterable by `rootRunId` or `status`).
- `external_swarm_kill` — Kill an active run (and optionally all descendant runs via `cascade: true`).
- `external_swarm_settings` — Read or update persistent auto-timeout settings (`autoTimeoutEnabled: false` for unlimited runtime, `defaultTimeoutSec` default `3600`), or disable timeout on a specific active run.

When `scripts/delegate.mjs` or `lib/runner.mjs` spawns `claude` or `codex`, it automatically injects inline MCP overrides (`--mcp-config` / `--allowedTools` for Claude; `-c mcp_servers.external_swarm.*` with `tool_timeout_sec >= 600` and `default_tools_approval_mode="auto"` for Codex) and propagates lineage environment variables:

- `EXTERNAL_SWARM_PARENT_RUN_ID`
- `EXTERNAL_SWARM_ROOT_RUN_ID`
- `EXTERNAL_SWARM_CONVERSATION_ID`
- `EXTERNAL_SWARM_CALLER`
- `AGY_DELEGATION_DEPTH` (default max depth `4`, overridable via `AGY_MAX_DELEGATION_DEPTH`)
- `AGY_SWARM_CONSOLE_DIR`

### 3. Antigravity Lifecycle Hooks (`hooks.json`)

External Swarm ships plugin-level Antigravity hooks in `hooks.json` backed by `hooks/swarm-hook.mjs`:

- **`PreInvocation`**: Checks the local run store directly (zero HTTP requests) with per-conversation watermarks (`<swarmRoot>/hook-state/`) and notifies the host agent once when runs in the current conversation transition to `Needs Input` or newly complete (`done` / `failed` / `timeout` / `killed`).
- **`Stop`**: Emits a concise one-time reminder if active background subagents are still running for the current conversation so live workers are not silently abandoned.
- **Safety Guarantees**: Strict fail-open JSON output (always exits `0`), fast no-op path when no runs exist for the chat, and **prompt-injection safe** — hooks emit only fixed templates, validated counts, and safe `runId`s (never raw subagent output, prompts, or question text).

### 4. Git Worktree Parallel Write Isolation (`--worktree`)

When running multiple write-mode subagents against the same Git repository:

- Pass `--worktree` (CLI), `worktree: true` (MCP `external_swarm_spawn`), or enable **Git Worktree Isolation** in the side-pane Spawn Modal.
- Each run gets a dedicated branch `ext-swarm/<runId>` checked out at `<swarmRoot>/worktrees/<runId>` (strictly outside the repository tree so untracked files never pollute your workspace).
- On completion, External Swarm captures `git status --porcelain=v1` into `changedFiles` for review in CLI JSON output, MCP results, Export Markdown, and the Detail View.
- When finished reviewing or merging a branch, remove the managed worktree and branch via `node scripts/delegate.mjs --cleanup-worktree "<runId>" --json` (add `--force` if dirty/unmerged) or click **Clean Worktree** in the side pane.

### 5. Side-Pane Board UI

Open the board from Antigravity via `[External Swarm](sidecar://external-swarm/board/)`:

- **Overview**: Live run cards, status counters (`Running`, `Done`, `Stopped`, `Failed`, plus amber `Needs Input` badges), search, `This chat` / `All chats` scope, and global **Auto-stop** timeout toggle.
- **Tree**: Expandable multi-level parent-child hierarchy (`Antigravity -> Claude <-> Codex`) with rolled-up cost/tokens and `Needs Input` highlights.
- **Graph**: Interactive SVG call graph with timeline replay controls.
- **Raw**: Live JSON inspection of the tree state.
- **Detail View**:
  - Live active-run spinner banner and streaming footer.
  - **Needs Input Q&A Card**: Displays the subagent's pending question, optional clickable choice chips, and an inline answer box (`Send Answer`).
  - **Compact / Detailed Toggle & Codex-Style Collapsible Commands**: Switch between high-signal milestones/notes/questions/final replies (`Compact`) and full granular reasoning/tool chatter (`Detailed`). Shell commands (`CMD▶`/`CMD✓`/`CMD✕`) and tool rows collapse by default into clean single-line previews (stripping noisy shell wrappers like `pwsh.exe -Command` / `bash -lc`, with exit-code and output line-count chips) and expand on click with full command, output, and copy actions, plus a one-click `Expand tools` / `Collapse tools` button.
  - **Live UI Asset Hot-Reload**: Edits to `sidecars/board/` frontend files are automatically detected by the sidecar (`uiVersion`) and reloaded in idle side-pane tabs while preserving the active tab/run view.
  - **Worktree Badge & Changed Files Summary**: View the isolated branch name, trigger **Clean Worktree** when done, and expand the collapsible changed-files list (`M` / `A` / `D` / `??`).
  - **Export MD**: Copy or export a formatted Markdown report of the run and all descendants.
  - **Controls**: Parent/child jump links, **Send Follow-up**, **∞ No Limit** (disable timeout on an active run), and **Kill / Kill Tree**.
- **Spawn Modal**: Includes **local model autocomplete** (`lib/models.mjs` inspecting `~/.codex/config.toml` and `~/.claude/settings.json`), per-run **Context Window** override (default `1M` for Claude, `666K` for Codex), **Full Access** and **Browser / Official Plugins** toggles (both enabled by default), and a **Git Worktree Isolation** checkbox.

---

## Cross-Platform Data, Config Paths & Security

| Purpose | Windows | macOS | Linux |
| --- | --- | --- | --- |
| Run store (`runs/`) | `%LOCALAPPDATA%\agy-external-swarm\runs` | `~/Library/Application Support/agy-external-swarm/runs` | `${XDG_STATE_HOME:-~/.local/state}/agy-external-swarm/runs` |
| Antigravity config | `%USERPROFILE%\.gemini\config\config.json` | `~/.gemini/config/config.json` | `~/.gemini/config/config.json` |
| Claude MCP config | `%USERPROFILE%\.claude.json` | `~/.claude.json` | `~/.claude.json` |
| Codex MCP config | `%USERPROFILE%\.codex\config.toml` | `~/.codex/config.toml` | `~/.codex/config.toml` |

**POSIX Permission Hardening**: On macOS and Linux, `lib/store.mjs` creates run-store directories with mode `0o700` and writes JSON metadata and JSONL event logs with mode `0o600`, rejecting unsafe symlink targets inside `runsDir`/`swarmRoot` while preserving standard OS symlinks (`/var -> /private/var`, `/tmp -> /private/tmp`).

Environment overrides:
- `AGY_SWARM_CONSOLE_DIR` — Custom run store root directory
- `ANTIGRAVITY_CONFIG_DIR` — Custom Antigravity config directory
- `CLAUDE_CONFIG_PATH` — Custom `.claude.json` path
- `CODEX_HOME` — Custom `.codex` directory
- `CLAUDE_BIN` / `CODEX_BIN` — Explicit CLI binary overrides
- `EXTERNAL_SWARM_DEFAULT_TIMEOUT_SEC` — Override default subprocess timeout in seconds (default `3600`, or `"off"` / `"infinite"` to disable)
- `EXTERNAL_SWARM_AUTO_TIMEOUT` — Force auto-timeout on/off via environment (`on`/`true`/`1` or `off`/`false`/`0` for unlimited runtime)
- `EXTERNAL_SWARM_CLAUDE_CONTEXT_WINDOW` — Override default Claude context window (default `"1m"`, or `"default"` / `"200k"`)
- `EXTERNAL_SWARM_CODEX_CONTEXT_WINDOW` — Override default Codex context window tokens (default `666000`, accepts `"666k"` / `"1m"` / `"0"`)
- `EXTERNAL_SWARM_CODEX_AUTOCOMPACT` — Override default Codex auto-compact token limit (default `580000`)
- `EXTERNAL_SWARM_FULL_ACCESS` — Override default Full Access mode (`on`/`true`/`1` default, or `off`/`false`/`0` for sandboxed default)
- `EXTERNAL_SWARM_CLAUDE_CHROME` — Override default Claude `--chrome` browser integration (`on`/`true`/`1` default)
- `EXTERNAL_SWARM_OFFICIAL_PLUGINS` — Override default official browser/plugin features & `chrome-devtools` MCP bridging (`on`/`true`/`1` default)
- `AGY_MAX_DELEGATION_DEPTH` — Override max recursion depth (default `4`)

---

## Architecture

```text
external-swarm/
├── plugin.json                  # Antigravity plugin manifest
├── hooks.json                   # Antigravity PreInvocation & Stop hook registration
├── package.json                 # Root ESM manifest & scripts (0 npm dependencies, MIT)
├── LICENSE                      # MIT License
├── CHANGELOG.md                 # Release history (Keep a Changelog)
├── assets/logo.svg              # Plugin icon
├── .github/workflows/ci.yml     # Cross-platform GitHub Actions CI (Ubuntu, macOS, Windows)
├── hooks/
│   └── swarm-hook.mjs           # Fail-open, prompt-injection-safe lifecycle hook runner
├── rules/
│   └── AGENTS.md                # Always-on AI guide: using Claude/Codex + auto-installing CLIs
├── lib/
│   ├── paths.mjs                # Cross-platform store/config paths & CLI discovery
│   ├── store.mjs                # Atomic meta/events store, POSIX 0o700/0o600 hardening, wait/Q&A, Markdown export
│   ├── worktree.mjs             # Managed Git worktree create/inspect/cleanup
│   ├── models.mjs               # Local Claude & Codex model auto-discovery
│   ├── parsers.mjs              # Streaming Claude & Codex JSONL parsers
│   ├── runner.mjs               # Unified CLI spawn/resume runner + MCP injection + worktree + depth guard
│   └── mcp-server.mjs           # Dependency-free stdio MCP server (9 external_swarm_* tools)
├── scripts/
│   ├── delegate.mjs             # CLI entrypoint (spawn, resume, wait, answer, worktree, export-md, kill)
│   └── setup.mjs                # Cross-platform installer, registration & verifier
├── sidecars/board/
│   ├── sidecar.json             # Sidecar manifest (restart_policy: always)
│   ├── main.mjs                 # HTTP/SSE API server (tree, spawn, follow-up, answer, export, worktree cleanup)
│   ├── index.html               # Multi-tab + detail UI
│   ├── styles.css               # Host CSS-token themeable stylesheet
│   ├── graph.js                 # SVG call graph & replay renderer
│   └── app.js                   # Client state, conditional polling, Needs Input Q&A, Compact/Detailed view
└── skills/
    ├── external-swarm/          # Consolidated plugin skill
    └── delegate-claude-codex/   # Portable delegation skill & thin wrapper
```

---

## Testing

```bash
# Run unit + core integration tests
npm test

# Run unit tests only
npm run test:unit

# Run all integration tests (including hooks/MCP, Sidecar UI, and Tier 5 adversarial tests)
npm run test:integration

# Run E2E Tier 2 boundary & security suite
node tests/e2e/run.mjs --tier 2
```

All setup, worktree, hook, and integration tests execute strictly against isolated temporary directories (`mkdtempSync`) and mock CLI stubs — they never touch your real `~/.claude.json`, `~/.codex/config.toml`, `~/.gemini/config/config.json`, or live run store.

---

## Troubleshooting

- **`Unable to locate claude/codex executable`**: Ensure `claude` / `codex` is on `PATH` or set `CLAUDE_BIN` / `CODEX_BIN`. Run `node scripts/setup.mjs --verify` to inspect detected binary paths.
- **Sidecar shows stale UI after plugin update**: Restart the `external-swarm/board` sidecar from Antigravity or terminate its Node process so `restart_policy: "always"` relaunches with the updated bundle.
- **Delegation recursion guard triggered**: Default depth limit is `4` (`Antigravity -> Claude -> Codex -> ...`). Increase temporarily with `AGY_MAX_DELEGATION_DEPTH=6` if deeper chains are intentional.
- **Corrupt JSON config reported by `setup.mjs`**: `setup.mjs` refuses to overwrite malformed `.claude.json` or `config.json` files. Fix the JSON syntax error and re-run `node scripts/setup.mjs --yes`.

---

## License

Released under the [MIT License](LICENSE).