# Antigravity Code Mode (`antigravity-code-mode`) — Complete Technical Reference > Version: `1.0.0` | License: MIT | Runtime Dependencies: `0` (`"dependencies": {}`) | Node.js: `>=20.0.0` > Scope: Antigravity-exclusive (Antigravity Desktop App/IDE and Antigravity CLI). Unofficial open-source plugin; not affiliated with Google LLC or Anthropic, PBC. > Homepage: https://yunusemrejs.github.io/antigravity-code-mode/ > Repository: https://github.com/yunusemrejs/antigravity-code-mode > npm: https://www.npmjs.com/package/antigravity-code-mode > Author: Emre Kara (`yunusemrejs`, https://yunusemrejs.github.io) --- ## 1. Overview & Problem Solved Modern coding agents connected to multiple MCP servers face two compounding context-window bottlenecks: 1. **Tool schema bloat:** Injecting 50–100+ raw JSON Schema tool definitions consumes thousands of tokens on every turn. 2. **Multi-turn raw payload bloat:** Multi-file workspace scans (`glob` → `grep` → `N × read`) and large API responses (`50–200 KB` JSON) pass raw intermediate data through the LLM context across dozens of sequential round-trips. `antigravity-code-mode` solves both in Antigravity by exposing **4 fixed MCP tools (~316 tokens)** backed by: - **0 ms Cold BM25 + Fuzzy Indexer & Compact `.d.ts` Compiler:** Indexes Antigravity's pre-cached `~/.gemini/antigravity/mcp//.json` files and `mcp_config.json` without spawning upstream servers. - **QuickJS-NG WebAssembly Sandbox (`worker_threads` warm pool):** Runs LLM-generated TypeScript/JavaScript in linear WASM memory (`1.61 ms` warm p50) so intermediate filtering, loops, and `Promise.all` fan-outs stay completely off-context. - **Runtime Host Policy Broker:** Authorizes every `workspace.*`, `mcp.*`, and `kv.*` call at runtime with resolved arguments (`readonly` default vs `readwrite`, `fs.realpathSync` symlink jail, sensitive path denylist, secret redaction, call/memory/time/output budgets). - **Off-Context `$ref` SpillStore & TTL `kv` Store:** Automatically spills oversized outputs (`>16 KB` default) to `$ref:` handles with structural summaries and safe `jqPath` drill-down, while `kv` persists structured intermediate state across turns. - **Live `aux_pane` MCP App Inspector (`ui/inspector.html`):** Single-file `@modelcontextprotocol/ext-apps` inspector showing live token savings, call DAGs, BM25 schema search, and policy audit logs. --- ## 2. Exposed MCP Tool Surface ### LLM-Visible Tools (4 Fixed Tools) 1. **`cm_search({ query: string, server?: string, kind?: "all" | "mcp" | "workspace" | "kv", limit?: number })`** - Searches indexed upstream MCP tools, `workspace.*`, and `kv.*` via BM25 + fuzzy matching. - Returns compact TypeScript `.d.ts` namespaces (`declare namespace github { function search_code(args: { query: string; per_page?: number }): Promise; }`) instead of verbose JSON Schema. - Never spawns upstream MCP server processes during discovery. 2. **`cm_execute({ code: string, mode?: "readonly" | "readwrite", timeoutMs?: number, maxToolCalls?: number, maxOutputBytes?: number, cwd?: string })`** - Strips TypeScript (`node:module.stripTypeScriptTypes` primary on Node `>=22.6`, prebundled `sucrase` fallback on Node `20`–`22.5`). - Executes inside a fresh QuickJS-NG WASM context with `workspace.*`, `mcp..()`, `kv.*`, and `console.log`. - Defaults to `mode: "readonly"` (denies `workspace.edit`, `workspace.exec`, and mutating MCP calls). - Outputs exceeding `maxOutputBytes` (`16384` default, `262144` ceiling) spill automatically to a `$ref:` handle with shape summary + head/tail preview. 3. **`cm_inspect({ handleId?: string, runId?: string, offset?: number, limit?: number, jqPath?: string })`** - Reads a paginated slice or safe non-`eval` `jqPath` projection (`$.records[0..4]`, `.items[*].id`) of a spilled `$ref:` handle, or retrieves telemetry for a `runId`. 4. **`cm_open_inspector({})`** - Opens `ui://code-mode/inspector.html` (`mimeType: "text/html;profile=mcp-app"`) in Antigravity's `aux_pane` and global entrypoints. ### App-Only UI Tools (`_meta.ui.visibility: ["app"]`) - `cm_inspector_snapshot`: Returns telemetry ring buffer, cumulative token savings, active spill/kv stats, and recent policy audit entries. - `cm_inspector_action`: Supports interactive inspector actions (`search`, `clear_spill`, `clear_kv`, `inspect_run`). --- ## 3. Sandbox SDK Reference (Inside `cm_execute`) ```ts declare namespace workspace { function read(args: { path: string; startLine?: number; endLine?: number; maxBytes?: number }): Promise<{ path: string; content: string; totalLines: number; truncated: boolean }>; function glob(args: { pattern: string; cwd?: string; maxResults?: number }): Promise<{ matches: string[]; truncated: boolean }>; function grep(args: { pattern: string; path?: string; glob?: string; maxResults?: number; ignoreCase?: boolean }): Promise<{ matches: Array<{ path: string; line: number; text: string }>; truncated: boolean }>; function edit(args: { path: string; target?: string; replacement?: string; content?: string; create?: boolean }): Promise<{ path: string; changed: boolean; bytesWritten: number }>; function exec(args: { command: string; args?: string[]; cwd?: string; timeoutMs?: number }): Promise<{ exitCode: number; stdout: string; stderr: string; timedOut: boolean }>; } declare namespace kv { function get(key: string): Promise; function set(key: string, value: unknown, ttlSec?: number): Promise<{ ok: true }>; function del(key: string): Promise<{ deleted: boolean }>; function list(): Promise; } // Upstream MCP servers discovered via cm_search are invoked as: // await mcp..(args) ``` --- ## 4. Security Boundaries & Hard Ceilings - **WASM Linear Memory Isolation:** QuickJS-NG WASM (`@jitl/quickjs-ng-wasmfile-release-sync`) runs in `worker_threads` with zero Node.js globals (`process`, `require`, `fs`, `fetch`, `Buffer`). - **Hard Resource Ceilings:** - WASM memory: `64 MB` default / `256 MB` max; stack `256 KB`. - Wall-clock timeout: `60 s` default / `600 s` max -> triggers `worker.terminate()` + automatic worker respawn. - Tool call budget: `25` default / `200` max per execution. - Return output cap: `16 KB` default / `256 KB` max (spills to `$ref`). - SpillStore: `30 min` TTL, max `256` entries / `64 MB` total. - KvStore: `60 min` TTL, max `512` keys / `32 MB` total (`1 MB` per value). - **Path Jail & Sensitive Paths:** `fs.realpathSync` (and nearest existing ancestor check for new files) blocks `..` and symlink traversal outside the workspace root. Sensitive paths (`.env*`, `~/.ssh`, `~/.aws`, `~/.gnupg`, `~/.kube`, `*.pem`, `*.key`, `auth*`, `devices.json`) are denied even in `readwrite` mode. - **Secret Redaction:** `process.env` and upstream MCP auth headers never enter WASM. Outputs and spills scrub Bearer tokens, JWTs, `ghp_`/`gho_`/`sk-`/`npm_`/`xoxb-` keys, and `ANTIGRAVITY_CSRF_TOKEN`, plus ANSI/control characters. - **Exec Hardening:** `workspace.exec` requires `mode: "readwrite"`, runs `execFile` (`shell: false`), blocks shell/script/dangerous wrappers (`sh`, `bash`, `sudo`, `curl`, `node`, `python`, `git -c`/`config`, `find -exec`), and passes only safe env vars (`PATH`, `HOME`, `TMPDIR`, `LANG`, `LC_ALL`, `TERM`, `NODE_ENV`). - **Recursion Guard:** Excludes `code-mode` / `antigravity-code-mode` / `antigravity-code-mode_code-mode` from upstream multiplexing and enforces `ACM_DEPTH <= 1`. - **Lifecycle Hooks (`hooks.json`):** `SessionStart` injects indexed server/tool readiness; `PreToolUse` (`.*cm_execute`) always emits an explicit `decision` (`allow` for read-only, `ask` for `readwrite` or `workspace.exec`). --- ## 5. Reproducible Benchmarks Command: `node bench/run-bench.mjs --json` (or `npm run bench` / `acm bench --json`) Environment: Apple M1 Pro (`darwin/arm64`, 10 cores), Node.js `v24.13.0`, deterministic `Math.ceil(utf8_bytes / 4)` estimator. - **Aggregate (3 workloads):** `40,894` naive tokens -> `904` Code Mode tokens (**97.79% reduction**, `39,990` saved); `32` naive LLM round-trips -> `3` Code Mode turns (**90.63% reduction**). - **60-Tool Enterprise MCP Schema Catalog (`5` servers):** `5,945` naive tokens (`23,778 B`) -> `601` Code Mode tokens (`316` eager + `285` top-5 `.d.ts`) = **89.89% reduction** (`94.68%` eager-only); `0.53 ms` cold index, `0.78 ms` BM25 search, `0` upstream servers spawned. - **Multi-File Workspace Audit (`24` TS files):** `6,626` naive tokens (`26,502 B`, `26` turns) -> `122` Code Mode tokens (`488 B`, `1` turn) = **98.16% token reduction**, **96.15% round-trip collapse**, `81.30 ms` WASM runtime across 20 sandboxed FS calls. - **Large API Payload Filter & `$ref` Spill (`113,290 B` / `200` incidents -> `5` P0):** `28,323` naive tokens (`4` turns) -> `181` Code Mode tokens (`721 B`, `1` turn) = **99.36% token reduction**, **75.00% round-trip collapse**, `143.05 ms` WASM runtime. Auto `$ref` spill preview: `512` tokens (**98.19% reduction**). - **QuickJS-NG WASM Latency (`10` warm runs after 1 warmup):** `27.37 ms` cold worker boot; **`1.61 ms` warm p50**, `2.17 ms` warm p95, `1.64 ms` warm mean. **Honest Short-Task Discipline:** For 1–2 simple calls (reading a single known file or running one quick command), native Antigravity tools remain faster. `rules/AGENTS.md` keeps trivial tasks native and routes 3+ step orchestrations, multi-file audits, and large-payload filtering to Code Mode. --- ## 6. Installation & CLI Commands ```bash # Install into Antigravity (~/.gemini/config/plugins/antigravity-code-mode) npx antigravity-code-mode install # Alternative: curl installer curl -fsSL https://raw.githubusercontent.com/yunusemrejs/antigravity-code-mode/main/scripts/install.sh | bash # Alternative: Antigravity CLI agy plugin install https://github.com/yunusemrejs/antigravity-code-mode # Diagnostics, status, benchmark, uninstall acm doctor acm status --json acm detect --json acm bench --json acm uninstall --scope global ```