Skip to main content
Glama
README.md
<p align="center">
  <img src="docs/assets/social-preview.svg" alt="Antigravity Code Mode — QuickJS-NG WASM sandbox, 0ms BM25 MCP gateway, and policy-brokered workspace SDK cutting multi-tool context tokens by 97.8%" width="100%" />
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/antigravity-code-mode"><img src="https://img.shields.io/npm/v/antigravity-code-mode?style=flat-square&color=38bdf8&label=npm" alt="npm version" /></a>
  <a href="https://www.npmjs.com/package/antigravity-code-mode"><img src="https://img.shields.io/npm/dm/antigravity-code-mode?style=flat-square&color=10b981&label=downloads" alt="npm downloads" /></a>
  <a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-0ea5e9?style=flat-square" alt="MIT License" /></a>
  <a href="https://github.com/yunusemrejs/antigravity-code-mode/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/yunusemrejs/antigravity-code-mode/ci.yml?style=flat-square&label=CI" alt="CI status" /></a>
  <img src="https://img.shields.io/badge/node-%3E%3D20.0.0-339933?style=flat-square&logo=node.js&logoColor=white" alt="Node >= 20" />
  <img src="https://img.shields.io/badge/runtime%20deps-0-10b981?style=flat-square" alt="Zero runtime dependencies" />
  <img src="https://img.shields.io/badge/sandbox-QuickJS--NG%20WASM-6366f1?style=flat-square" alt="QuickJS-NG WASM Sandbox" />
</p>

# Antigravity Code Mode (`antigravity-code-mode`)

**TL;DR:** **Antigravity Code Mode** is an unofficial, open-source Code Mode plugin built exclusively for **Google Antigravity** (Desktop App/IDE and Antigravity CLI). Instead of flooding your agent's context window with dozens of raw MCP JSON schemas and intermediate multi-turn tool outputs, it exposes **4 fixed tools (~316 tokens)** backed by a **0 ms BM25 + compact `.d.ts` indexer**, a **QuickJS-NG WebAssembly sandbox** (`1.61 ms` warm p50), a **Runtime Host Policy Broker**, automatic **`$ref` output spilling**, and a live **`aux_pane` MCP App Inspector**. Across 3 reproducible multi-tool benchmarks (60 enterprise MCP tools, 24-file TypeScript audit, 113 KB incident API payload), it reduces context tokens from **40,894 to 904 (97.79% reduction)** and collapses **32 LLM round-trips to 3 (90.63% fewer turns)** with **zero runtime npm dependencies** (`"dependencies": {}`).

> **Trademark & Non-Affiliation Notice:** `antigravity-code-mode` is an independent, unofficial open-source plugin. It is not affiliated with, endorsed by, or sponsored by Google LLC or Anthropic, PBC.

---

## 30-Second Quick Install (Antigravity Desktop IDE & CLI)

### Option 1 — `npx` (Recommended, zero runtime deps, no `node-gyp`)

```bash
npx antigravity-code-mode install
```

### Option 2 — One-line shell installer

```bash
curl -fsSL https://raw.githubusercontent.com/yunusemrejs/antigravity-code-mode/main/scripts/install.sh | bash
```

### Option 3 — Antigravity CLI (`agy`)

```bash
agy plugin install https://github.com/yunusemrejs/antigravity-code-mode
```

Verify your installation and live sandbox health:

```bash
acm doctor
```

> When `ANTIGRAVITY_CSRF_TOKEN` is present in an active Antigravity session, `acm install` calls `LanguageServerService/RefreshMcpServers` so the `code-mode` MCP gateway activates without restarting Antigravity.

---

## Architecture

```mermaid
flowchart LR
    LLM["Antigravity Agent<br/>(Desktop IDE / CLI)"] -->|"4 Eager MCP Tools (~316 tok)"| GW["Code Mode MCP Gateway<br/>(dist/mcp-server.mjs)"]

    subgraph CTRL["Control & Index Plane (0 Runtime Deps)"]
        IDX["0ms BM25 + Fuzzy Indexer<br/>& Compact .d.ts Compiler"]
        POL["Runtime Host Policy Broker<br/>(Path Jail / Budgets / Secret Scrub)"]
        STR["Off-Context SpillStore ($ref)<br/>& TTL KV Store"]
        UI["MCP App aux_pane Inspector<br/>(ui/inspector.html)"]
    end

    subgraph EXEC["Isolated Execution Plane"]
        WASM["Warm worker_threads Pool<br/>(QuickJS-NG WASM • 64MB Cap)"]
    end

    GW --> IDX
    GW --> POL
    GW --> UI
    POL <-->|"Async MessagePort RPC"| WASM
    POL <--> STR

    POL -->|"fs.realpathSync Jail"| WS["Workspace SDK<br/>(read / glob / grep / edit / exec)"]
    POL -->|"Lazy Connect + Circuit Breaker"| MUX["Upstream MCP Multiplexer<br/>(Stdio & Streamable HTTP)"]
    IDX -.->|"0ms Cold Read"| CACHE["~/.gemini/antigravity/mcp/<br/>*/*.json + mcp_config.json"]
```

Deep dive: [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md) · [docs/SECURITY.md](docs/SECURITY.md)

---

## Feature & Architecture Comparisons

### 1. Code Mode Comparison Matrix

| Capability | `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` | Native Antigravity (Lazy-MCP + `run_workflow`) | **`antigravity-code-mode`** |
| :--- | :--- | :--- | :--- |
| **Target Surface** | Interactive Claude Code CLI + direct Anthropic API only | Antigravity Desktop IDE & CLI | **Antigravity Desktop IDE & CLI (all configured models)** |
| **MCP Schema Overhead** | On-demand `ToolSearch` | Lazy name list + per-call disk `read_file` turn | **0 ms pre-cached BM25 + compact `.d.ts` (~316 eager tokens)** |
| **Off-Context Data Processing** | JS `REPL` variables stay off-context | Raw MCP JSON returns directly into context | **QuickJS-NG WASM off-context filtering + automatic `$ref` SpillStore** |
| **Multi-Tool Orchestration** | `Promise.all` over built-ins + MCP | Python `run_workflow` (untyped `call_tool`, no MCP search) | **Single-turn TypeScript/JS `workspace.*` + `mcp.<server>.<tool>()` + `kv.*`** |
| **Execution Isolation** | Host process; static pre-classifier blind to dynamic args | Host process | **QuickJS-NG WASM linear memory in `worker_threads` + Runtime Host Policy Broker** |
| **Cross-Turn Off-Context State** | Stateless per REPL call | None | **Host-side TTL `kv` store + `$ref:<id>` handle inspection (`cm_inspect`)** |
| **Live Observability** | Terminal `Ctrl+O` text expansion | Raw tool log text | **Built-in `aux_pane` MCP App Inspector (token savings, call DAG, BM25 explorer, policy log)** |

### 2. Reproducible Benchmark Results

Measured directly with `node bench/run-bench.mjs --json` (also available via `npm run bench` and `acm bench --json`) on **Apple M1 Pro (`darwin/arm64`), Node.js `v24.13.0`**, using the real `SandboxPool`, `WorkspaceSdk`, `SpillStore`, and fixtures in `bench/fixtures/` (`ceil(utf8_bytes / 4)` deterministic token estimator):

| Benchmark Scenario | Naive Baseline | Antigravity Code Mode | Measured Reduction | Runtime Latency |
| :--- | :---: | :---: | :---: | :---: |
| **60-Tool Enterprise MCP Catalog** (5 servers) | `5,945` tok (`23,778 B`) / `2` turns | `601` tok (`316` eager + `285` `.d.ts`) / `1` turn | **89.89%** tokens (`94.68%` eager-only) | `0.53 ms` index · `0.78 ms` BM25 |
| **24-File TypeScript Workspace Audit** | `6,626` tok (`26,502 B`) / `26` turns | `122` tok (`488 B`) / `1` turn | **98.16%** tokens · **96.15%** turns | `81.30 ms` WASM (20 FS calls) |
| **113 KB Incident API Filter (200 → 5 P0)** | `28,323` tok (`113,290 B`) / `4` turns | `181` tok (`721 B`) / `1` turn (`512` tok auto `$ref` spill) | **99.36%** tokens (`98.19%` spill) | `143.05 ms` WASM |
| **Aggregate Multi-Tool Total** | **`40,894` tok / `32` turns** | **`904` tok / `3` turns** | **97.79% tokens · 90.63% turns** | **`1.61 ms` warm p50 · `27.37 ms` cold boot** |

Full methodology, raw JSON schema, and honest short-task ceiling: [docs/BENCHMARKS.md](docs/BENCHMARKS.md) · [bench/run-bench.mjs](bench/run-bench.mjs)

### 3. Sandbox & Runtime Security Isolation Matrix

| Engine Option | Warm Latency | Isolation Boundary | Hard CPU Preemption | `npx` Zero-Dep Reliability |
| :--- | :---: | :--- | :--- | :--- |
| **`QuickJS-NG WASM` + `worker_threads` (Used)** | **`1.61 ms` p50** | **High:** WASM linear memory, 0 Node/FS/Net globals, `setMemoryLimit` (64 MB / 256 MB) | **Yes:** `worker.terminate()` + automatic respawn | **Excellent:** Prebundled `.wasm`, 0 `node-gyp`, identical on macOS/Linux/Windows |
| `node:vm` + `--permission` | `~5–20 ms` | Low–Medium: V8 prototype escape surface (`vm2` CVE history) | Partial | Zero bundle size, insufficient boundary |
| Deno / Bun Subprocess | `~10–30 ms` | High (OS process) | `SIGKILL` | Breaks zero-setup `npx` (requires external binary) |
| `isolated-vm` (C++ V8) | `<5 ms` | High (native crash can bring down host) | Yes | Fragile: requires C++ compiler & `node-gyp` per Node ABI |

### 4. MCP Tools & CLI Reference

#### Exposed MCP Tools (4 LLM-Visible Tools)

| Tool | Key Arguments | Behavior |
| :--- | :--- | :--- |
| `cm_search` | `{ query, server?, kind?, limit? }` | BM25 + fuzzy search over upstream MCP tools, `workspace.*`, and `kv.*`; returns compact `.d.ts` declarations without spawning upstream servers. |
| `cm_execute` | `{ code, mode?, timeoutMs?, maxToolCalls?, maxOutputBytes?, cwd? }` | Runs TypeScript/JS in QuickJS-NG WASM (`mode: "readonly"` default; `"readwrite"` gates mutations). Oversized results spill automatically to `$ref:<id>`. |
| `cm_inspect` | `{ handleId?, runId?, offset?, limit?, jqPath? }` | Paginates or safely queries (`jqPath`, zero `eval`) a spilled `$ref:<id>` handle or inspects run telemetry. |
| `cm_open_inspector` | `{}` | Opens the live Antigravity `aux_pane` MCP App Inspector (`ui://code-mode/inspector.html`). |

#### CLI Commands (`antigravity-code-mode` / `acm`)

| Command | Description |
| :--- | :--- |
| `acm install [--scope global\|workspace] [--mode copy\|symlink] [--force] [--dry-run]` | Installs the prebundled plugin into Antigravity and triggers live `RefreshMcpServers` when available. |
| `acm uninstall [--scope global\|workspace]` | Cleanly removes the installed plugin directory or symlink without touching user data or source repos. |
| `acm detect [--json]` | Detects Antigravity config directories, installed plugins, and cached MCP schemas. |
| `acm doctor [--json]` | Runs non-destructive diagnostics: Node `>=20`, `quickjs.wasm` smoke test, manifest parity, and policy self-check. |
| `acm bench [--json]` | Runs the reproducible benchmark suite (`bench/run-bench.mjs`). |
| `acm status [--json]` | Displays installation status, active version, and indexed upstream server count. |

---

## Frequently Asked Questions

### How is Antigravity Code Mode different from `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE`?
Claude Code's experimental flag runs JavaScript in the host process behind a static permission pre-classifier and is limited to the interactive Claude Code CLI on direct Anthropic endpoints. `antigravity-code-mode` runs inside **Antigravity Desktop IDE & CLI** across any configured model, isolates code in **QuickJS-NG WASM linear memory**, enforces a **Runtime Host Policy Broker** on resolved arguments, adds cross-turn **`kv` + `$ref` spill handles**, and ships a live **`aux_pane` Inspector UI**.

### Does it require `node-gyp`, Docker, Python, or Deno?
No. All runtime code—including `@jitl/quickjs-ng-wasmfile-release-sync`, `@modelcontextprotocol/sdk`, `@modelcontextprotocol/ext-apps`, and `sucrase`—is prebundled into `dist/` and `ui/inspector.html` with `"dependencies": {}`. Only **Node.js >= 20** is required.

### How are API keys, `.env` files, and OAuth tokens protected from LLM-generated code?
Three independent barriers prevent secret exfiltration: (1) `process.env` and upstream MCP auth headers never enter the WASM sandbox, (2) `sensitive-paths.mjs` blocks `.env*`, `~/.ssh`, `~/.aws`, `*.pem/*.key`, `auth*`, and `devices.json` even in `readwrite` mode, and (3) `redactSecrets()` scrubs Bearer tokens, JWTs, `ghp_`/`gho_`/`sk-`/`npm_`/`xoxb-` tokens, and `ANTIGRAVITY_CSRF_TOKEN` before any output or `$ref` spill reaches the model.

### When should the agent NOT use Code Mode?
Do **not** use Code Mode for trivial 1–2 tool tasks (reading a single known file or executing one quick command). Native Antigravity tools are faster and avoid TypeScript generation overhead. The bundled `rules/AGENTS.md` enforces this discipline automatically: use Code Mode for **3+ step orchestrations, multi-file scans, `Promise.all` fan-outs, and large-payload filtering**.

### How does 0 ms MCP tool indexing work without spawning every upstream server?
Antigravity caches lazy MCP tool schemas on disk at `~/.gemini/antigravity/mcp/<serverName>/<toolName>.json`. On startup, `antigravity-code-mode` reads those JSON files directly into its in-memory BM25 index (~`0.53 ms` for 60 tools) and compiles `.d.ts` signatures on demand. Upstream Stdio or Streamable HTTP servers connect lazily only when `cm_execute` actually calls `mcp.<server>.<tool>()`.

### What stops an infinite loop or OOM bug in LLM-generated code from freezing Antigravity?
Each script executes inside a `worker_threads` QuickJS-NG WASM context with a hard `64 MB` default (`256 MB` max) WASM linear memory cap, `256 KB` stack limit, `25`-call tool budget, and `60s` default wall-clock timeout. Exceeding the timeout triggers `worker.terminate()` and transparently respawns a clean warm worker slot.

### How does `$ref` output spilling work when an upstream API returns megabytes of JSON?
If a `cm_execute` return value exceeds `maxOutputBytes` (`16 KB` default), the host stores the sanitized payload in an ephemeral TTL `SpillStore` under a `$ref:<hex>` handle and returns only a structural shape summary plus a compact head/tail preview. The agent can then query specific fields via `cm_inspect({ handleId, jqPath, offset, limit })`.

### Can `cm_execute` modify files or run shell commands by default?
No. `cm_execute` defaults to `mode: "readonly"`, which blocks `workspace.edit`, `workspace.exec`, and mutating MCP calls at the Policy Broker. Setting `mode: "readwrite"` also triggers the `PreToolUse` hook decision gate for user confirmation, and `workspace.exec` runs with `shell: false`, a strict binary/flag denylist, and a sanitized environment.

### How do I open the live `aux_pane` Code Mode Inspector?
Ask Antigravity to open the Code Mode Inspector (invoking `cm_open_inspector`) or use the plugin's suggested prompt. The inspector renders directly in Antigravity's `aux_pane` using `@modelcontextprotocol/ext-apps` with live token savings, call DAG traces, BM25 schema search, and policy audit logs.

### Does `antigravity-code-mode` support Cursor, Windsurf, Codex, or Claude Code?
No. `antigravity-code-mode` is intentionally scoped to **Antigravity Desktop App/IDE and Antigravity CLI** so it can exploit Antigravity-native plugin manifests, `hooks.json`, `~/.gemini/antigravity/mcp/` 0 ms schema pre-caching, `LanguageServerService/RefreshMcpServers`, and `aux_pane` MCP Apps without cross-harness bloat.

---

## Documentation & AI Discovery

- **Landing Page & Interactive Token Calculator:** [https://yunusemrejs.github.io/antigravity-code-mode/](https://yunusemrejs.github.io/antigravity-code-mode/)
- **Architecture:** [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)
- **Security & Threat Model:** [docs/SECURITY.md](docs/SECURITY.md)
- **Reproducible Benchmarks:** [docs/BENCHMARKS.md](docs/BENCHMARKS.md)
- **Release & SEO Checklist:** [docs/RELEASE_AND_SEO_CHECKLIST.md](docs/RELEASE_AND_SEO_CHECKLIST.md)
- **LLM Documentation Indexes:** [llms.txt](llms.txt) · [llms-full.txt](llms-full.txt)
- **Legal & Governance:** [LICENSE](LICENSE) · [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) · [CONTRIBUTING.md](CONTRIBUTING.md) · [CHANGELOG.md](CHANGELOG.md) · [CITATION.cff](CITATION.cff)

---

## Citation

If you reference `antigravity-code-mode` in papers, benchmarks, or architecture reports, please cite [CITATION.cff](CITATION.cff):

```bibtex
@software{kara2026antigravitycodemode,
  author       = {Kara, Emre},
  title        = {{Antigravity Code Mode: QuickJS-NG WASM Sandbox and 0ms BM25 MCP Gateway for Antigravity}},
  version      = {1.0.0},
  year         = {2026},
  month        = nov,
  license      = {MIT},
  url          = {https://github.com/yunusemrejs/antigravity-code-mode}
}
```