Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
feat(antigravity): add native Google Antigravity IDE integration (#3817)
APcd4367b040bf
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdxindex e72df58c0..d1abf0ffc 100644--- a/docs/content/docs/proxy.mdx+++ b/docs/content/docs/proxy.mdx@@ -519,6 +519,26 @@ Google Cloud Code Assist / Antigravity compatibility endpoint used by Pi-style `The proxy also accepts:- `POST /v1/v1internal:streamGenerateContent`+### Antigravity IDE++Google's Antigravity IDE can route its model traffic through the proxy:++```bash+headroom wrap antigravity # Start proxy + print Antigravity setup instructions+headroom mcp install --agent antigravity # Register the Headroom MCP server in Antigravity+```++`wrap antigravity` prints a custom OpenAI-compatible model-provider base URL+to add in Antigravity's model-provider settings; Antigravity fetches the model+list from `GET /v1/models` on its own. Native Cloud Code Assist traffic+(`google-antigravity` clients) is accepted on+[`POST /v1internal:streamGenerateContent`](#post-v1internalstreamgeneratecontent)+and routed upstream like any other Cloud Code request.++MCP registration writes to Antigravity's global `mcp_config.json` under+`~/.gemini/` (preferring the install's current location when one already+exists) and refuses to overwrite a config file that does not parse as JSON.+### `POST /v1/compress`Compression-only endpoint. Compresses messages and returns them without ever making a **completion request to an LLM provider** — no generation, no provider API key, no upstream chat call. Used by the TypeScript SDK, by LiteLLM's `headroom` guardrail, and by API gateways running Headroom as a sidecar.diff --git a/headroom/cli/mcp.py b/headroom/cli/mcp.pyindex bfcf3e134..52d04cf45 100644--- a/headroom/cli/mcp.py+++ b/headroom/cli/mcp.py@@ -139,9 +139,9 @@ def mcp_install(proxy_url: str, agents: tuple[str, ...], force: bool) -> None:\bBy default this installs into every agent that has a registrar and is- detected on this system (Claude Code today; Cursor / Codex / Continue /- others added in subsequent releases). Pass ``--agent NAME`` one or more- times to restrict the installation.+ detected on this system (Antigravity IDE, Claude Code, Codex, Grok CLI,+ OpenCode today; Cursor / Continue / others added in subsequent releases).+ Pass ``--agent NAME`` one or more times to restrict the installation.\bExamples:@@ -188,18 +188,38 @@ def mcp_install(proxy_url: str, agents: tuple[str, ...], force: bool) -> None:@mcp.command("uninstall")-def mcp_uninstall() -> None:+ "--agent",+ "agents",+ multiple=True,+ help="Restrict uninstallation to specific agents (default: every detected agent).",+)+def mcp_uninstall(agents: tuple[str, ...]) -> None:"""Remove Headroom MCP server from detected agent configs.\bRemoves headroom from every agent registrar known to Headroom. Other MCP- servers are preserved.+ servers are preserved. Pass ``--agent NAME`` one or more times to restrict+ the uninstallation.++ \b+ Examples:+ headroom mcp uninstall # every detected agent+ headroom mcp uninstall --agent antigravity # Antigravity IDE only"""from headroom.mcp_registry import get_all_registrars+ registrars = get_all_registrars()+ if agents:+ wanted = {agent.strip().lower() for agent in agents if agent.strip()}+ registrars = [registrar for registrar in registrars if registrar.name in wanted]+ if not registrars:+ click.echo("No agents matched the requested filter.")+ raise SystemExit(1)+removed = False- for registrar in get_all_registrars():+ for registrar in registrars:if not registrar.detect():continueremoved_names: list[str] = []diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex 1c5a288e1..c9e977fc7 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -11,6 +11,7 @@ Usage:headroom wrap vibe # Start proxy + Mistral Vibeheadroom wrap grok # Start proxy + Grok CLIheadroom wrap cursor # Start proxy + print Cursor config instructions+ headroom wrap antigravity # Start proxy + print Antigravity config instructionsheadroom wrap grok-build # Start proxy + configure Grok Buildheadroom wrap openclaw # Install + configure OpenClaw pluginheadroom wrap claude --port 9999 # Custom proxy port@@ -81,6 +82,9 @@ from headroom.copilot_auth import (resolve_subscription_bearer_token_details,)from headroom.providers.aider import build_launch_env as _build_aider_launch_env+from headroom.providers.antigravity import (+ render_setup_lines as _render_antigravity_setup_lines,+)from headroom.providers.claude import (CONTEXT_1M_SUFFIX,DEFAULT_1M_MODEL,@@ -314,7 +318,15 @@ def _append_text(path: Path, content: str) -> None:fsutil.append_text(path, content)-_AGENT_SAVINGS_TARGET_AGENTS = {"claude", "codex", "cursor", "grok", "grok_build", "opencode"}+_AGENT_SAVINGS_TARGET_AGENTS = {+ "antigravity",+ "claude",+ "codex",+ "cursor",+ "grok",+ "grok_build",+ "opencode",+}_WRAP_PROXY_TIMEOUT_ENV = "HEADROOM_WRAP_PROXY_TIMEOUT"_WRAP_PROXY_TIMEOUT_DEFAULT_SECONDS = 45_WRAP_PROXY_TIMEOUT_ML_DEFAULT_SECONDS = 90@@ -330,7 +342,14 @@ _WRAP_PROXY_TIMEOUT_ML_MODULES = ("torch", "sentence_transformers", "spacy")_TOOL_SEARCH_ENV = TOOL_SEARCH_ENV_TOOL_SEARCH_DEFAULT = TOOL_SEARCH_DEFAULT_TOOL_SEARCH_FOUNDRY_DEFAULT = TOOL_SEARCH_FOUNDRY_DEFAULT-_AGENT_SAVINGS_WRAP_AGENTS = {"claude", "codex", "cursor", "grok", "grok_build"}+_AGENT_SAVINGS_WRAP_AGENTS = {+ "antigravity",+ "claude",+ "codex",+ "cursor",+ "grok",+ "grok_build",+}# 1M context window for `wrap claude` (#1158). Claude Code only sends the# `context-1m` beta header — unlocking the 1M window for entitled subscription@@ -5634,6 +5653,7 @@ def wrap(ctx: click.Context) -> None:headroom wrap vibe # Mistral Vibeheadroom wrap grok # Grok CLI (xAI)headroom wrap cursor # Cursor (prints config instructions)+ headroom wrap antigravity # Antigravity IDE (prints config instructions)headroom wrap grok-build # Grok Build (updates ~/.grok/config.toml)headroom wrap cline # Cline (VS Code; prints config instructions)headroom wrap continue # Continue (VS Code/JetBrains; injects systemMessage)@@ -7662,6 +7682,62 @@ def cursor()+# =============================================================================+# Antigravity IDE+# =============================================================================++[email protected](context_settings={"ignore_unknown_options": True})+@_retired_context_tool_option+@proxy_port_option()[email protected]("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")[email protected]("--learn", is_flag=True, help="Enable live traffic learning")[email protected]("--memory", is_flag=True, help="Enable persistent cross-session memory")[email protected]("--verbose", "-v", is_flag=True, help="Verbose output")[email protected]("--prepare-only", is_flag=True, hidden=True)+def antigravity(+ port: int,+ no_proxy: bool,+ learn: bool,+ memory: bool,+ verbose: bool,+ prepare_only: bool,+) -> None:+ """Start Headroom proxy for use with Antigravity IDE.++ \b+ Antigravity reads its model endpoints from its model-provider settings,+ not from environment variables. This command starts the proxy and prints+ the settings to add as a custom OpenAI-compatible model provider.++ \b+ After running this command, open Antigravity and add a custom model+ provider with the printed base URL. Antigravity fetches the model list+ from GET /v1/models automatically.++ \b+ Example:+ headroom wrap antigravity # Start proxy + Antigravity settings+ headroom wrap antigravity --port 9999 # Custom proxy port+ """+ if prepare_only:+ return++ def _print_antigravity_setup(actual_port: int) -> None:+ for line in _render_antigravity_setup_lines(actual_port, project=_project_name_from_cwd()):+ click.echo(line)++ _run_proxy_only_watcher(+ agent_label="antigravity",+ port=port,+ no_proxy=no_proxy,+ learn=learn,+ memory=memory,+ agent_type="antigravity",+ print_setup_lines=_print_antigravity_setup,+ )++# =============================================================================# Grok Build# =============================================================================diff --git a/headroom/install/models.py b/headroom/install/models.pyindex c37c19f66..a502d74f8 100644--- a/headroom/install/models.py+++ b/headroom/install/models.py@@ -59,6 +59,7 @@ class ToolTarget(str, Enum):GROK = "grok"OPENCLAW = "openclaw"OPENCODE = "opencode"+ ANTIGRAVITY = "antigravity"def iso_utc_now() -> str:diff --git a/headroom/install/planner.py b/headroom/install/planner.pyindex 27085b7bc..4c55c2567 100644--- a/headroom/install/planner.py+++ b/headroom/install/planner.py@@ -9,6 +9,7 @@ from collections.abc import Iterableimport clickfrom headroom import paths as _paths+from headroom.mcp_registry.antigravity import AntigravityRegistrarfrom headroom.providers.grok.runtime import DEFAULT_API_URL as _GROK_DEFAULT_API_URLfrom headroom.providers.install_registry import build_install_target_envsfrom headroom.rollout import RolloutChannel@@ -34,6 +35,7 @@ SUPPORTED_TARGETS = [ToolTarget.GROK,ToolTarget.OPENCLAW,ToolTarget.OPENCODE,+ ToolTarget.ANTIGRAVITY,]PROVIDER_SCOPE_TARGETS = [ToolTarget.CLAUDE,@@ -63,9 +65,26 @@ def detect_targets() -> list[str]:continueif target == ToolTarget.GROK_BUILD and shutil.which("grok"):detected.append(target.value)+ if target == ToolTarget.ANTIGRAVITY and _antigravity_detected():+ detected.append(target.value)return detected+def _antigravity_detected() -> bool:+ """Detect an Antigravity IDE install via its own markers.++ The bare ``~/.gemini`` home is not enough: Gemini CLI keeps its session+ data there too, so a Gemini-CLI-only host must not count as Antigravity+ (a false positive suppresses the auto-install defaults in+ ``resolve_targets``). The MCP registrar owns the authoritative gate —+ the ``~/.gemini/antigravity`` or ``~/.gemini/config`` directories, or an+ existing MCP config file — so reuse it here instead of re-implementing+ the check.+ """++ return AntigravityRegistrar().detect()++def resolve_targets(provider_mode: str, requested_targets: Iterable[str], *, scope: str = ConfigScope.USER.value) -> list[str]:@@ -190,11 +209,15 @@ def build_manifest(# Grok / Grok Build need proxy upstream = xAI. Only auto-set when no other# OpenAI-compatible tools share this proxy (those may need api.openai.com /# Copilot). Explicit OPENAI_TARGET_API_URL in extra_env still wins below.+ # Antigravity speaks the OpenAI protocol (custom OpenAI-compatible model+ # provider), so it belongs in the exclusion set too: a Grok + Antigravity+ # deployment must not send Antigravity's traffic to xAI._openai_native = {ToolTarget.CODEX.value,ToolTarget.COPILOT.value,ToolTarget.AIDER.value,ToolTarget.OPENCODE.value,+ ToolTarget.ANTIGRAVITY.value,}_grok_targets = {ToolTarget.GROK.value, ToolTarget.GROK_BUILD.value}target_set = set(resolved_targets)diff --git a/headroom/mcp_registry/__init__.py b/headroom/mcp_registry/__init__.pyindex f19ad1ba7..e9fa7be90 100644--- a/headroom/mcp_registry/__init__.py+++ b/headroom/mcp_registry/__init__.py@@ -13,6 +13,7 @@ without changing the calling code.from __future__ import annotations+from .antigravity import AntigravityRegistrarfrom .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpecfrom .claude import ClaudeConfigMutationError, ClaudeRegistrarfrom .codex import CodexRegistrar@@ -32,6 +33,7 @@ from .server_json import build_server_json, render_server_json__all__ = ["DEFAULT_PROXY_URL","CLAUDE_SERENA_CONTEXT",+ "AntigravityRegistrar","ClaudeConfigMutationError","ClaudeRegistrar","CodexRegistrar",diff --git a/headroom/mcp_registry/antigravity.py b/headroom/mcp_registry/antigravity.pynew file mode 100644index 000000000..6f7e76712--- /dev/null+++ b/headroom/mcp_registry/antigravity.py@@ -0,0 +1,248 @@+"""Antigravity IDE MCP registrar.++Antigravity (Google's AI-first IDE) stores MCP server configuration in a+JSON file holding a top-level ``mcpServers`` object::++ {+ "mcpServers": {+ "headroom": {+ "command": "/path/to/headroom",+ "args": ["mcp", "serve"],+ "env": {"HEADROOM_PROXY_URL": "http://127.0.0.1:8787"}+ }+ }+ }++The on-disk location has moved between Antigravity releases — Google's+current Antigravity codelab identifies ``~/.gemini/config/mcp_config.json``+as the active Desktop config, while older guides cite+``~/.gemini/antigravity/mcp_config.json`` — so this registrar treats the+former as authoritative: it probes the known candidates in order and uses+the first one that exists, falling back to the current location when none+does yet. Uninstall removes the entry from every candidate that still holds+it, so a stale duplicate in the legacy location can never survive.++Only global configuration is supported: Antigravity does not read+per-project MCP files.+"""++from __future__ import annotations++import json+import logging+import shutil+from pathlib import Path+from typing import Any++from headroom import fsutil++from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec++logger = logging.getLogger(__name__)+++def _config_candidates(home: Path) -> list[Path]:+ """Known Antigravity MCP config locations, current first."""+ gemini_dir = home / ".gemini"+ return [+ gemini_dir / "config" / "mcp_config.json",+ gemini_dir / "antigravity" / "mcp_config.json",+ ]+++def _mcp_cache_dirs(home: Path, server_name: str) -> list[Path]:+ """Local MCP server caches Antigravity keeps per install surface."""+ gemini_dir = home / ".gemini"+ return [+ gemini_dir / "antigravity-ide" / "mcp" / server_name,+ gemini_dir / "antigravity" / "mcp" / server_name,+ gemini_dir / "antigravity-cli" / "mcp" / server_name,+ ]+++class AntigravityRegistrar(MCPRegistrar):+ """Register MCP servers with Antigravity IDE."""++ name = "antigravity"+ display_name = "Antigravity IDE"++ def __init__(self, *, home_dir: Path | None = None) -> None:+ """Allow ``home_dir`` override for testing."""+ self._home = home_dir if home_dir is not None else Path.home()++ def _resolve_config(self) -> Path:+ """Return the config file to use.++ The current Desktop location (``~/.gemini/config/mcp_config.json``)+ is authoritative: when its parent directory exists the IDE reads+ that location, so a stale legacy file must not capture the+ registration. Otherwise use the first existing candidate, falling+ back to the current location when none does yet.+ """+ candidates = _config_candidates(self._home)+ if candidates[0].parent.is_dir():+ return candidates[0]+ for candidate in candidates:+ if candidate.exists():+ return candidate+ return candidates[0]++ def detect(self) -> bool:+ home = self._home+ gemini_dir = home / ".gemini"+ if (gemini_dir / "antigravity").is_dir():+ return True+ # The current Desktop config lives directly under ~/.gemini/config;+ # an install that has not created its MCP file yet still counts.+ if (gemini_dir / "config").is_dir():+ return True+ return any(candidate.exists() for candidate in _config_candidates(home))++ def get_server(self, server_name: str) -> ServerSpec | None:+ data = self._load_config()+ if data is None:+ return None+ servers = data.get("mcpServers", {})+ if not isinstance(servers, dict):+ return None+ entry = servers.get(server_name)+ if not isinstance(entry, dict):+ return None+ return _entry_to_spec(server_name, entry)++ def register_server(self, spec: ServerSpec, *, force: bool = False) -> RegisterResult:+ existing = self.get_server(spec.name)++ if existing is not None and _specs_equivalent(existing, spec):+ return RegisterResult(RegisterStatus.ALREADY, "matches current configuration")++ if existing is not None and not force:+ return RegisterResult(RegisterStatus.MISMATCH, _diff_specs(existing, spec))++ config_path = self._resolve_config()+ data = self._load_config()+ if data is None and config_path.exists():+ # The file exists but would not parse: refuse to overwrite it and+ # turn a hand-edited typo into total loss of the user's MCP setup.+ return RegisterResult(+ RegisterStatus.FAILED,+ f"{config_path} is not valid JSON. Fix or move it, then re-run — "+ "refusing to overwrite it and lose your MCP servers.",+ )+ payload: dict[str, Any] = data if isinstance(data, dict) else {}+ servers = payload.get("mcpServers")+ if not isinstance(servers, dict):+ servers = {}+ payload["mcpServers"] = servers+ servers[spec.name] = _spec_to_entry(spec)++ try:+ config_path.parent.mkdir(parents=True, exist_ok=True)+ fsutil.write_text(config_path, json.dumps(payload, indent=2) + "\n")+ except OSError as exc:+ return RegisterResult(RegisterStatus.FAILED, f"could not write {config_path}: {exc}")+ verb = "updated" if existing is not None else "wrote"+ return RegisterResult(RegisterStatus.REGISTERED, f"{verb} {spec.name} in {config_path}")++ def unregister_server(self, server_name: str) -> bool:+ removed = False+ remaining: list[Path] = []+ for config_path in _config_candidates(self._home):+ if not config_path.exists():+ continue+ data = self._load_config(config_path)+ if not isinstance(data, dict):+ # Refuse to touch a file that does not parse — the same rule+ # register_server follows — and keep checking the rest.+ continue+ servers = data.get("mcpServers")+ if not isinstance(servers, dict) or server_name not in servers:+ continue+ del servers[server_name]+ try:+ fsutil.write_text(config_path, json.dumps(data, indent=2) + "\n")+ except OSError:+ # The write failed, so this config still registers the+ # server. Record it and report failure instead of claiming a+ # removal that the untouched file contradicts.+ remaining.append(config_path)+ continue+ removed = True+ if not removed:+ return False+ # Antigravity caches each MCP server under ~/.gemini/<surface>/mcp/;+ # a removed entry keeps loading from cache until that directory goes.+ # Clear it whenever at least one config entry was removed, even if a+ # failed write means this still reports False below.+ for cache_dir in _mcp_cache_dirs(self._home, server_name):+ try:+ shutil.rmtree(cache_dir)+ except OSError:+ pass+ if remaining:+ logger.warning(+ "could not remove %r from %s; the server stays registered there",+ server_name,+ ", ".join(str(path) for path in remaining),+ )+ return False+ return True++ def _load_config(self, config_path: Path | None = None) -> dict[str, Any] | None:+ """Load a config file, defaulting to the resolved one.++ Returns ``None`` when the file does not exist or does not parse;+ callers distinguish those cases via :meth:`_resolve_config` + exists.+ """+ path = config_path if config_path is not None else self._resolve_config()+ if not path.exists():+ return None+ try:+ data = json.loads(fsutil.read_text(path))+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):+ return None+ return data if isinstance(data, dict) else None+++def _entry_to_spec(name: str, entry: dict[str, Any]) -> ServerSpec:+ args_value = entry.get("args", [])+ args = tuple(str(x) for x in args_value) if isinstance(args_value, list) else ()+ env_value = entry.get("env", {})+ env = {str(k): str(v) for k, v in env_value.items()} if isinstance(env_value, dict) else {}+ return ServerSpec(+ name=name,+ command=str(entry.get("command", "")),+ args=args,+ env=env,+ )+++def _spec_to_entry(spec: ServerSpec) -> dict[str, Any]:+ entry: dict[str, Any] = {"command": spec.command}+ if spec.args:+ entry["args"] = list(spec.args)+ if spec.env:+ entry["env"] = dict(spec.env)+ return entry+++def _specs_equivalent(a: ServerSpec, b: ServerSpec) -> bool:+ return (+ a.name == b.name+ and a.command == b.command+ and tuple(a.args) == tuple(b.args)+ and dict(a.env) == dict(b.env)+ )+++def _diff_specs(existing: ServerSpec, requested: ServerSpec) -> str:+ parts: list[str] = []+ if existing.command != requested.command:+ parts.append(f"command {existing.command!r} -> {requested.command!r}")+ if tuple(existing.args) != tuple(requested.args):+ parts.append(f"args {list(existing.args)} -> {list(requested.args)}")+ if dict(existing.env) != dict(requested.env):+ parts.append(f"env {dict(existing.env)} -> {dict(requested.env)}")+ if not parts:+ return "spec differs in unidentified field(s)"+ return "; ".join(parts)diff --git a/headroom/mcp_registry/install.py b/headroom/mcp_registry/install.pyindex 4d1fbeb72..6614fdfeb 100644--- a/headroom/mcp_registry/install.py+++ b/headroom/mcp_registry/install.py@@ -6,6 +6,7 @@ from collections.abc import Iterablefrom headroom.install.runtime import resolve_headroom_command+from .antigravity import AntigravityRegistrarfrom .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpecfrom .claude import ClaudeRegistrarfrom .codex import CodexRegistrar@@ -22,7 +23,13 @@ def get_all_registrars() -> list[MCPRegistrar]:The list grows as we add adapters for Cursor, Continue, Cline, etc."""- return [ClaudeRegistrar(), CodexRegistrar(), GrokRegistrar(), OpencodeRegistrar()]+ return [+ AntigravityRegistrar(),+ ClaudeRegistrar(),+ CodexRegistrar(),+ GrokRegistrar(),+ OpencodeRegistrar(),+ ]def build_headroom_spec(proxy_url: str = DEFAULT_PROXY_URL) -> ServerSpec:diff --git a/headroom/providers/antigravity/__init__.py b/headroom/providers/antigravity/__init__.pynew file mode 100644index 000000000..820dbc57c--- /dev/null+++ b/headroom/providers/antigravity/__init__.py@@ -0,0 +1,11 @@+"""Antigravity IDE-specific provider helpers."""++from .install import build_install_env+from .runtime import AntigravityProxyTargets, build_proxy_targets, render_setup_lines++__all__ = [+ "AntigravityProxyTargets",+ "build_install_env",+ "build_proxy_targets",+ "render_setup_lines",+]diff --git a/headroom/providers/antigravity/install.py b/headroom/providers/antigravity/install.pynew file mode 100644index 000000000..d7d241213--- /dev/null+++ b/headroom/providers/antigravity/install.py@@ -0,0 +1,15 @@+"""Antigravity IDE install-time helpers."""++from __future__ import annotations++from .runtime import build_proxy_targets+++def build_install_env(*, port: int, backend: str) -> dict[str, str]:+ """Build the persistent install environment for Antigravity IDE."""+ del backend+ targets = build_proxy_targets(port)+ return {+ "OPENAI_BASE_URL": targets.openai_base_url,+ "ANTHROPIC_BASE_URL": targets.anthropic_base_url,+ }diff --git a/headroom/providers/antigravity/runtime.py b/headroom/providers/antigravity/runtime.pynew file mode 100644index 000000000..4da900bc6--- /dev/null+++ b/headroom/providers/antigravity/runtime.py@@ -0,0 +1,57 @@+"""Runtime helpers for Antigravity IDE integrations."""++from __future__ import annotations++from dataclasses import dataclass++from headroom.providers.claude import proxy_base_url as claude_proxy_base_url+from headroom.providers.codex import proxy_base_url as codex_proxy_base_url+from headroom.proxy.project_context import with_project_prefix+++@dataclass(frozen=True)+class AntigravityProxyTargets:+ """Resolved local proxy targets shown in Antigravity setup instructions."""++ openai_base_url: str+ anthropic_base_url: str+++def build_proxy_targets(port: int, project: str | None = None) -> AntigravityProxyTargets:+ """Build the local proxy URLs shown to Antigravity users.++ ``project`` (the wrap launch directory) is encoded as a ``/p/<name>``+ base-URL prefix because Antigravity's custom model-provider settings+ cannot send custom headers; the proxy strips it and attributes savings+ per project.+ """+ return AntigravityProxyTargets(+ openai_base_url=with_project_prefix(codex_proxy_base_url(port), project),+ anthropic_base_url=with_project_prefix(claude_proxy_base_url(port), project),+ )+++def render_setup_lines(port: int, project: str | None = None) -> list[str]:+ """Render the Antigravity setup instructions for the local proxy."""+ targets = build_proxy_targets(port, project)+ lines = [+ " Headroom proxy is running. Configure Antigravity:",+ "",+ " Antigravity reads model endpoints from its model-provider settings,",+ " not from environment variables. Add a custom OpenAI-compatible",+ " model provider pointing at the proxy:",+ "",+ f" Base URL: {targets.openai_base_url}",+ " API Key: your-openai-api-key",+ "",+ " Antigravity fetches the model list from GET /v1/models automatically,",+ " so there is nothing else to register.",+ ]+ if project:+ lines += [+ "",+ f" Dashboard savings will be attributed to project '{project}'",+ " (the directory this command was run from). Re-run from another",+ " project directory to get that project's URL.",+ ]+ return linesdiff --git a/headroom/providers/grok/runtime.py b/headroom/providers/grok/runtime.pyindex 130bc818f..ddf3d1acd 100644--- a/headroom/providers/grok/runtime.py+++ b/headroom/providers/grok/runtime.py@@ -15,9 +15,11 @@ PROXY_ENV_KEY = "GROK_MODELS_BASE_URL"# process-wide OPENAI target is still api.openai.com (Claude/Codex-started)._XAI_TOKEN_AUTH_HEADER = "x-xai-token-auth"_XAI_TOKEN_AUTH_VALUE = "xai-grok-cli"-# UA product tokens emitted by Grok CLI 0.2.x. Matched against whitespace-split-# tokens so unrelated clients ("litellm-grok/1.0") cannot collide.-_GROK_UA_PREFIXES = ("grok-pager/", "grok-shell/")+# UA product tokens emitted by Grok clients. Matched against whitespace-split+# tokens so unrelated clients ("litellm-grok/1.0") cannot collide: "grok/" is+# how Grok Build (xAI's IDE) identifies itself, and the codebase's own client+# classification (auth_policy CLIENT_UA_MAP) already reads it that way.+_GROK_UA_PREFIXES = ("grok-pager/", "grok-shell/", "grok/")def _header_value(headers: Mapping[str, str], name: str) -> str | None:@@ -30,13 +32,14 @@ def _header_value(headers: Mapping[str, str], name: str) -> str | None:def is_grok_cli_request(headers: Mapping[str, str]) -> bool:- """Return True when inbound headers identify the official Grok CLI.+ """Return True when inbound headers identify a Grok client (CLI or Build).Grok cannot stamp ``x-headroom-base-url`` (no custom attribution headers),- so shared-proxy routing must recognize the CLI from wire signals instead.+ so shared-proxy routing must recognize it from wire signals instead.Detection is intentionally narrow: only the official token-auth marker and- known Grok UA product tokens (prefix match on whitespace-split tokens) —- never model-id heuristics.+ known Grok UA product tokens — ``grok-pager/`` / ``grok-shell/`` for the+ CLI, ``grok/`` for Grok Build — prefix-matched against whitespace-split+ tokens, never model-id heuristics."""token_auth = _header_value(headers, _XAI_TOKEN_AUTH_HEADER)if token_auth is not None and token_auth.strip().lower() == _XAI_TOKEN_AUTH_VALUE:diff --git a/headroom/providers/install_registry.py b/headroom/providers/install_registry.pyindex a998bed90..6299279b8 100644--- a/headroom/providers/install_registry.py+++ b/headroom/providers/install_registry.py@@ -6,6 +6,9 @@ from collections.abc import Callablefrom headroom.install.models import DeploymentManifest, ManagedMutationfrom headroom.providers.aider.install import build_install_env as _build_aider_install_env+from headroom.providers.antigravity.install import (+ build_install_env as _build_antigravity_install_env,+)from headroom.providers.claude.install import (apply_provider_scope as _apply_claude_provider_scope,)@@ -50,6 +53,7 @@ _ProviderScopeApplier = Callable[[DeploymentManifest], ManagedMutation | None]_ProviderScopeReverter = Callable[[ManagedMutation, DeploymentManifest], None]_ENV_BUILDERS: dict[str, _InstallEnvBuilder] = {+ "antigravity": _build_antigravity_install_env,"claude": _build_claude_install_env,"copilot": _build_copilot_install_env,"codex": _build_codex_install_env,diff --git a/headroom/providers/proxy_targets.py b/headroom/providers/proxy_targets.pyindex eba99925f..24b1cba74 100644--- a/headroom/providers/proxy_targets.py+++ b/headroom/providers/proxy_targets.py@@ -43,10 +43,10 @@ logger = logging.getLogger("headroom.proxy")def route_grok_to_xai(headers: Mapping[str, str], openai_target: str) -> bool:- """Return True when Grok CLI traffic should be redirected to ``api.x.ai``.+ """Return True when Grok CLI / Grok Build traffic should be redirected to ``api.x.ai``.- Grok CLI cannot set ``x-headroom-base-url``, so a shared proxy started for- Claude/Codex has to recognize it from wire signals or it forwards xAI+ Neither Grok client can set ``x-headroom-base-url``, so a shared proxy started for+ Claude/Codex has to recognize them from wire signals or it forwards xAIsession tokens to ``api.openai.com``.Only applies while the OpenAI target is still the default. An operator who@@ -70,7 +70,7 @@ def route_grok_to_xai(headers: Mapping[str, str], openai_target: str) -> bool:def openai_compatible_base_url(proxy: Any, headers: Mapping[str, str]) -> str:"""Resolve upstream for OpenAI-compatible metadata/passthrough traffic.- Routes official Grok CLI to ``api.x.ai`` so ``GET /v1/models`` and catch-all+ Routes official Grok CLI / Grok Build to ``api.x.ai`` so ``GET /v1/models`` and catch-allpassthrough succeed on a shared proxy whose OpenAI target is the default."""target = api_target(proxy, "openai")diff --git a/tests/test_cli/test_mcp.py b/tests/test_cli/test_mcp.pyindex 86f02994a..6d2d29ac8 100644--- a/tests/test_cli/test_mcp.py+++ b/tests/test_cli/test_mcp.py@@ -199,6 +199,33 @@ class TestMCPUninstallCommand:assert result.exit_code == 0assert "not configured" in result.output.lower()+ def test_uninstall_agent_filter_restricts_registrars(self):+ """--agent limits uninstallation to the named registrars."""+ antigravity = FakeRegistrar()+ antigravity.name = "antigravity"+ claude = FakeRegistrar()+ claude.name = "claude"++ runner = CliRunner()+ with patch(+ "headroom.mcp_registry.get_all_registrars",+ return_value=[antigravity, claude],+ ):+ result = runner.invoke(main, ["mcp", "uninstall", "--agent", "antigravity"])++ assert result.exit_code == 0+ assert antigravity.removed == ["headroom"]+ assert claude.removed == []++ def test_uninstall_agent_filter_no_match_exits_nonzero(self):+ """--agent with no matching registrar exits non-zero."""+ runner = CliRunner()+ with patch("headroom.mcp_registry.get_all_registrars", return_value=[FakeRegistrar()]):+ result = runner.invoke(main, ["mcp", "uninstall", "--agent", "bogus"])++ assert result.exit_code == 1+ assert "no agents matched" in result.output.lower()+class TestMCPStatusCommand:"""Test 'headroom mcp status' command."""diff --git a/tests/test_cli/test_wrap_antigravity.py b/tests/test_cli/test_wrap_antigravity.pynew file mode 100644index 000000000..955f551d0--- /dev/null+++ b/tests/test_cli/test_wrap_antigravity.py@@ -0,0 +1,97 @@+"""Tests for the `headroom wrap antigravity` command."""++from __future__ import annotations++from typing import Any+from unittest.mock import patch++from click.testing import CliRunner++from headroom.cli import wrap as wrap_mod+from headroom.cli.main import main+++def test_wrap_help_lists_antigravity() -> None:+ result = CliRunner().invoke(main, ["wrap", "--help"])+ assert result.exit_code == 0, result.output+ assert "antigravity" in result.output+++def test_wrap_antigravity_help_mentions_custom_model_provider() -> None:+ result = CliRunner().invoke(main, ["wrap", "antigravity", "--help"])+ assert result.exit_code == 0, result.output+ assert "Antigravity" in result.output+ assert "OpenAI-compatible" in result.output+++def test_wrap_antigravity_prepare_only_exits_cleanly() -> None:+ result = CliRunner().invoke(main, ["wrap", "antigravity", "--prepare-only"])+ assert result.exit_code == 0, result.output+++def test_wrap_antigravity_uses_proxy_only_watcher_with_antigravity_type() -> None:+ captured: dict[str, Any] = {}++ def fake_watcher(**kwargs: Any) -> None:+ captured.update(kwargs)++ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):+ result = CliRunner().invoke(main, ["wrap", "antigravity", "--port", "8787"])++ assert result.exit_code == 0, result.output+ assert captured["agent_label"] == "antigravity"+ assert captured["agent_type"] == "antigravity"+ assert captured["port"] == 8787+++def test_wrap_antigravity_setup_lines_render_actual_port(monkeypatch) -> None:+ monkeypatch.setattr(wrap_mod, "_project_name_from_cwd", lambda: None)+ captured: dict[str, Any] = {}++ def fake_watcher(**kwargs: Any) -> None:+ captured.update(kwargs)++ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):+ result = CliRunner().invoke(main, ["wrap", "antigravity"])++ assert result.exit_code == 0, result.output+ print_setup_lines = captured["print_setup_lines"]++ with patch("click.echo") as echo_mock:+ print_setup_lines(9999)++ rendered = "\n".join(call.args[0] for call in echo_mock.call_args_list)+ assert "http://127.0.0.1:9999/v1" in rendered+ assert "Antigravity" in rendered+++def test_wrap_antigravity_honors_headroom_port_env(monkeypatch) -> None:+ """HEADROOM_PORT configures the proxy port like every other wrap command."""+ monkeypatch.setenv("HEADROOM_PORT", "9999")+ monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)+ captured: dict[str, Any] = {}++ def fake_watcher(**kwargs: Any) -> None:+ captured.update(kwargs)++ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):+ result = CliRunner().invoke(main, ["wrap", "antigravity"])++ assert result.exit_code == 0, result.output+ assert captured["port"] == 9999+++def test_wrap_antigravity_explicit_port_overrides_env(monkeypatch) -> None:+ """An explicit --port always wins over HEADROOM_PORT."""+ monkeypatch.setenv("HEADROOM_PORT", "9999")+ monkeypatch.delenv("HEADROOM_PORT_DISCOVERY", raising=False)+ captured: dict[str, Any] = {}++ def fake_watcher(**kwargs: Any) -> None:+ captured.update(kwargs)++ with patch.object(wrap_mod, "_run_proxy_only_watcher", side_effect=fake_watcher):+ result = CliRunner().invoke(main, ["wrap", "antigravity", "--port", "7777"])++ assert result.exit_code == 0, result.output+ assert captured["port"] == 7777diff --git a/tests/test_install/test_planner.py b/tests/test_install/test_planner.pyindex dfe5f4525..2a4aca030 100644--- a/tests/test_install/test_planner.py+++ b/tests/test_install/test_planner.py@@ -426,3 +426,46 @@ def test_persistent_task_does_not_inherit_service_backend_defaults() -> None:assert "HEADROOM_EMBEDDER_RUNTIME" not in manifest.base_envassert "HEADROOM_KOMPRESS_BACKEND" not in manifest.base_env+++def test_build_manifest_grok_with_antigravity_does_not_force_xai() -> None:+ """Do not route Antigravity's OpenAI-compatible traffic to xAI.++ Antigravity uses the proxy as a custom OpenAI-compatible model provider,+ so a Grok + Antigravity deployment must keep the shared OpenAI upstream+ instead of switching it to xAI.+ """+ manifest = build_manifest(+ **_base_manifest_kwargs(targets=["grok_build", "antigravity"], backend="openai")+ )++ assert "OPENAI_TARGET_API_URL" not in manifest.base_env+ assert "--openai-api-url" not in manifest.proxy_args+++def test_detect_targets_ignores_shared_gemini_home(monkeypatch, tmp_path) -> None:+ """A Gemini-CLI-only home must not detect Antigravity.++ Gemini CLI keeps session data under ``~/.gemini/tmp/``; that shared home+ directory alone must not register as an Antigravity install, or an+ ``auto`` deployment would pick up Antigravity and skip the usual+ Claude/Codex/Copilot defaults.+ """+ (tmp_path / ".gemini" / "tmp" / "chats").mkdir(parents=True)+ monkeypatch.setattr("pathlib.Path.home", classmethod(lambda cls: tmp_path))+ monkeypatch.setattr("headroom.install.planner.shutil.which", lambda *_args, **_kwargs: None)++ from headroom.install.planner import detect_targets++ assert ToolTarget.ANTIGRAVITY.value not in detect_targets()+++def test_detect_targets_finds_antigravity_config_dir(monkeypatch, tmp_path) -> None:+ """The Antigravity ``~/.gemini/config`` directory still counts as a hit."""+ (tmp_path / ".gemini" / "config").mkdir(parents=True)+ monkeypatch.setattr("pathlib.Path.home", classmethod(lambda cls: tmp_path))+ monkeypatch.setattr("headroom.install.planner.shutil.which", lambda *_args, **_kwargs: None)++ from headroom.install.planner import detect_targets++ assert ToolTarget.ANTIGRAVITY.value in detect_targets()diff --git a/tests/test_install/test_providers.py b/tests/test_install/test_providers.pyindex ccbf30dcd..749eb59d5 100644--- a/tests/test_install/test_providers.py+++ b/tests/test_install/test_providers.py@@ -949,6 +949,67 @@ def test_planner_provider_scope_unsupported_error_excludes_opencode() -> None:resolve_targets("manual", ["cursor"], scope="provider")+# ---------------------------------------------------------------------------+# Planner-level antigravity smoke tests+# ---------------------------------------------------------------------------+++def test_planner_resolves_antigravity_as_install_target() -> None:+ from headroom.install.planner import resolve_targets++ targets = resolve_targets("manual", ["antigravity"])+ assert "antigravity" in targets+++def test_planner_antigravity_in_supported_targets_enum() -> None:+ from headroom.install.models import ToolTarget+ from headroom.install.planner import PROVIDER_SCOPE_TARGETS, SUPPORTED_TARGETS++ assert ToolTarget.ANTIGRAVITY in SUPPORTED_TARGETS+ assert ToolTarget.ANTIGRAVITY not in PROVIDER_SCOPE_TARGETS+++def test_planner_antigravity_rejected_in_provider_scope() -> None:+ import click+ import pytest++ from headroom.install.planner import resolve_targets++ with pytest.raises(click.ClickException, match="unsupported targets"):+ resolve_targets("manual", ["antigravity"], scope="provider")+++def test_planner_build_tool_envs_includes_antigravity() -> None:+ from headroom.install.planner import build_tool_envs++ envs = build_tool_envs(port=8787, backend="anthropic", targets=["antigravity"])+ assert "antigravity" in envs+ assert envs["antigravity"]["OPENAI_BASE_URL"] == "http://127.0.0.1:8787/v1"+ assert envs["antigravity"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:8787"+++def test_planner_resolve_all_includes_antigravity() -> None:+ from headroom.install.planner import resolve_targets++ targets = resolve_targets("all", [])+ assert "antigravity" in targets+++def test_planner_detect_targets_ignores_bare_gemini_dir(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from pathlib import Path as StdPath++ from headroom.install.planner import detect_targets++ # Gemini CLI keeps its own session data under ~/.gemini/, so the shared+ # home directory alone must not count as an Antigravity install.+ (tmp_path / ".gemini").mkdir()+ monkeypatch.setattr(StdPath, "home", classmethod(lambda cls: tmp_path))++ assert "antigravity" not in detect_targets()++# ---------------------------------------------------------------------------# Opencode revert OSError fallback# ---------------------------------------------------------------------------diff --git a/tests/test_mcp_registry/test_antigravity_registrar.py b/tests/test_mcp_registry/test_antigravity_registrar.pynew file mode 100644index 000000000..f24999ab0--- /dev/null+++ b/tests/test_mcp_registry/test_antigravity_registrar.py@@ -0,0 +1,302 @@+"""Tests for the Antigravity IDE MCP registrar."""++from __future__ import annotations++import json+from pathlib import Path++from headroom.mcp_registry.antigravity import AntigravityRegistrar+from headroom.mcp_registry.base import RegisterStatus, ServerSpec+from headroom.mcp_registry.install import get_all_registrars, install_everywhere+++def _make_registrar(tmp_path: Path) -> AntigravityRegistrar:+ return AntigravityRegistrar(home_dir=tmp_path)+++def _spec() -> ServerSpec:+ return ServerSpec(+ name="headroom",+ command="/usr/bin/headroom",+ args=("mcp", "serve"),+ env={"HEADROOM_PROXY_URL": "http://127.0.0.1:8787"},+ )+++def _config_path(tmp_path: Path) -> Path:+ return tmp_path / ".gemini" / "config" / "mcp_config.json"+++def _legacy_config_path(tmp_path: Path) -> Path:+ return tmp_path / ".gemini" / "antigravity" / "mcp_config.json"+++def test_detect_true_when_antigravity_dir_exists(tmp_path: Path) -> None:+ (tmp_path / ".gemini" / "antigravity").mkdir(parents=True)+ assert _make_registrar(tmp_path).detect() is True+++def test_detect_true_when_config_dir_exists(tmp_path: Path) -> None:+ # The current Desktop config lives directly under ~/.gemini/config; an+ # install that has not created its MCP file yet still counts.+ (tmp_path / ".gemini" / "config").mkdir(parents=True)+ assert _make_registrar(tmp_path).detect() is True+++def test_detect_true_when_only_config_file_exists(tmp_path: Path) -> None:+ config = _config_path(tmp_path)+ config.parent.mkdir(parents=True)+ config.write_text(json.dumps({"mcpServers": {}}))+ assert _make_registrar(tmp_path).detect() is True+++def test_detect_false_when_nothing_exists(tmp_path: Path) -> None:+ assert _make_registrar(tmp_path).detect() is False+++def test_register_creates_config_with_mcp_servers(tmp_path: Path) -> None:+ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ config = _config_path(tmp_path)+ assert config.exists()+ payload = json.loads(config.read_text())+ entry = payload["mcpServers"]["headroom"]+ assert entry["command"] == "/usr/bin/headroom"+ assert entry["args"] == ["mcp", "serve"]+ assert entry["env"] == {"HEADROOM_PROXY_URL": "http://127.0.0.1:8787"}+++def test_register_uses_legacy_location_when_current_missing(tmp_path: Path) -> None:+ legacy = _legacy_config_path(tmp_path)+ legacy.parent.mkdir(parents=True)+ legacy.write_text(json.dumps({"mcpServers": {}}))++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ assert json.loads(legacy.read_text())["mcpServers"]["headroom"]["command"] == (+ "/usr/bin/headroom"+ )+ # The current location is left alone when the legacy one already exists.+ assert not _config_path(tmp_path).exists()+++def test_register_prefers_current_location_when_both_exist(tmp_path: Path) -> None:+ current = _config_path(tmp_path)+ current.parent.mkdir(parents=True)+ current.write_text(json.dumps({"mcpServers": {}}))+ legacy = _legacy_config_path(tmp_path)+ legacy.parent.mkdir(parents=True)+ legacy.write_text(json.dumps({"mcpServers": {}}))++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ assert "headroom" in json.loads(current.read_text())["mcpServers"]+ # The stale legacy file is not touched: the IDE reads the current one.+ assert "headroom" not in json.loads(legacy.read_text())["mcpServers"]+++def test_get_server_reads_current_location_when_both_exist(tmp_path: Path) -> None:+ current = _config_path(tmp_path)+ current.parent.mkdir(parents=True)+ current.write_text(json.dumps({"mcpServers": {"headroom": {"command": "/current/headroom"}}}))+ legacy = _legacy_config_path(tmp_path)+ legacy.parent.mkdir(parents=True)+ legacy.write_text(json.dumps({"mcpServers": {"headroom": {"command": "/stale/headroom"}}}))++ server = _make_registrar(tmp_path).get_server("headroom")++ assert server is not None+ assert server.command == "/current/headroom"+++def test_register_is_idempotent(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ assert registrar.register_server(_spec()).status == RegisterStatus.REGISTERED+ second = registrar.register_server(_spec())+ assert second.status == RegisterStatus.ALREADY+++def test_register_mismatch_without_force_leaves_file_alone(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ registrar.register_server(_spec())++ other = ServerSpec(name="headroom", command="/other/headroom", args=("mcp", "serve"))+ result = registrar.register_server(other)++ assert result.status == RegisterStatus.MISMATCH+ assert registrar.get_server("headroom") is not None+ assert registrar.get_server("headroom").command == "/usr/bin/headroom" # type: ignore[union-attr]+++def test_register_force_overwrites_mismatch(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ registrar.register_server(_spec())++ other = ServerSpec(name="headroom", command="/other/headroom", args=("mcp", "serve"))+ result = registrar.register_server(other, force=True)++ assert result.status == RegisterStatus.REGISTERED+ assert registrar.get_server("headroom") is not None+ assert registrar.get_server("headroom").command == "/other/headroom" # type: ignore[union-attr]+++def test_register_preserves_other_servers(tmp_path: Path) -> None:+ config = _config_path(tmp_path)+ config.parent.mkdir(parents=True)+ config.write_text(+ json.dumps({"mcpServers": {"other": {"command": "other-server", "args": []}}})+ )++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ payload = json.loads(config.read_text())+ assert payload["mcpServers"]["other"] == {"command": "other-server", "args": []}+ assert payload["mcpServers"]["headroom"]["command"] == "/usr/bin/headroom"+++def test_register_refuses_to_overwrite_unparseable_config(tmp_path: Path) -> None:+ config = _config_path(tmp_path)+ config.parent.mkdir(parents=True)+ config.write_text("{ not valid json")++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.FAILED+ assert "not valid JSON" in (result.detail or "")+ assert config.read_text() == "{ not valid json"+++def test_get_server_returns_none_when_absent(tmp_path: Path) -> None:+ assert _make_registrar(tmp_path).get_server("headroom") is None+++def test_get_server_reads_existing_entry(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ registrar.register_server(_spec())++ server = registrar.get_server("headroom")++ assert server is not None+ assert server.name == "headroom"+ assert server.command == "/usr/bin/headroom"+ assert tuple(server.args) == ("mcp", "serve")+ assert dict(server.env) == {"HEADROOM_PROXY_URL": "http://127.0.0.1:8787"}+++def test_unregister_removes_entry_and_cache_dirs(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ registrar.register_server(_spec())+ cache_dir = tmp_path / ".gemini" / "antigravity-ide" / "mcp" / "headroom"+ cache_dir.mkdir(parents=True)++ assert registrar.unregister_server("headroom") is True++ assert registrar.get_server("headroom") is None+ assert not cache_dir.exists()+++def test_unregister_returns_false_when_absent(tmp_path: Path) -> None:+ assert _make_registrar(tmp_path).unregister_server("headroom") is False+++def test_unregister_removes_entry_from_all_locations(tmp_path: Path) -> None:+ registrar = _make_registrar(tmp_path)+ for path in (_config_path(tmp_path), _legacy_config_path(tmp_path)):+ path.parent.mkdir(parents=True)+ path.write_text(+ json.dumps(+ {+ "mcpServers": {+ "headroom": {"command": "/usr/bin/headroom"},+ "other": {"command": "other-server"},+ }+ }+ )+ )++ assert registrar.unregister_server("headroom") is True++ for path in (_config_path(tmp_path), _legacy_config_path(tmp_path)):+ payload = json.loads(path.read_text())+ assert "headroom" not in payload["mcpServers"]+ # Unrelated entries are preserved in both files.+ assert payload["mcpServers"]["other"] == {"command": "other-server"}+++def test_registrar_name_and_display_name() -> None:+ registrar = AntigravityRegistrar(home_dir=Path("/nonexistent"))+ assert registrar.name == "antigravity"+ assert registrar.display_name == "Antigravity IDE"+++def test_get_all_registrars_includes_antigravity() -> None:+ names = [registrar.name for registrar in get_all_registrars()]+ assert "antigravity" in names+++def test_install_everywhere_installs_into_detected_antigravity(tmp_path: Path) -> None:+ (tmp_path / ".gemini" / "antigravity").mkdir(parents=True)+ registrar = AntigravityRegistrar(home_dir=tmp_path)++ results = install_everywhere(registrars=[registrar], agents=["antigravity"])++ assert set(results) == {"antigravity"}+ assert results["antigravity"].status == RegisterStatus.REGISTERED+ assert registrar.get_server("headroom") is not None+++def test_install_everywhere_registers_with_only_config_dir(tmp_path: Path) -> None:+ # First-time setup: only the current Desktop config directory exists, no+ # MCP file yet. An explicit install must attempt registration instead of+ # bailing out as NOT_DETECTED.+ (tmp_path / ".gemini" / "config").mkdir(parents=True)+ registrar = AntigravityRegistrar(home_dir=tmp_path)++ results = install_everywhere(registrars=[registrar], agents=["antigravity"])++ assert set(results) == {"antigravity"}+ assert results["antigravity"].status == RegisterStatus.REGISTERED+ assert registrar.get_server("headroom") is not None+ assert (tmp_path / ".gemini" / "config" / "mcp_config.json").exists()+++def test_register_prefers_current_location_when_config_dir_exists(+ tmp_path: Path,+) -> None:+ """Registration must land in the active Desktop config, not a stale legacy file.++ With ``~/.gemini/config/`` present (the current Desktop install marker)+ and a legacy ``~/.gemini/antigravity/mcp_config.json`` also on disk, the+ registration goes to ``~/.gemini/config/mcp_config.json`` — the location+ the running IDE actually reads.+ """+ legacy = _legacy_config_path(tmp_path)+ legacy.parent.mkdir(parents=True)+ legacy.write_text(json.dumps({"mcpServers": {"other": {"command": "other-cmd"}}}))+ (tmp_path / ".gemini" / "config").mkdir(parents=True)++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ current = _config_path(tmp_path)+ servers = json.loads(current.read_text())["mcpServers"]+ assert servers["headroom"]["command"] == "/usr/bin/headroom"+ # The legacy file is left alone.+ assert "headroom" not in json.loads(legacy.read_text())["mcpServers"]+++def test_register_uses_legacy_location_when_no_config_dir(tmp_path: Path) -> None:+ """A legacy-only install still registers into its existing config file."""+ legacy = _legacy_config_path(tmp_path)+ legacy.parent.mkdir(parents=True)+ legacy.write_text(json.dumps({"mcpServers": {}}))++ result = _make_registrar(tmp_path).register_server(_spec())++ assert result.status == RegisterStatus.REGISTERED+ assert "headroom" in json.loads(legacy.read_text())["mcpServers"]+ assert not _config_path(tmp_path).exists()diff --git a/tests/test_mcp_registry_antigravity.py b/tests/test_mcp_registry_antigravity.pynew file mode 100644index 000000000..2750a59bb--- /dev/null+++ b/tests/test_mcp_registry_antigravity.py@@ -0,0 +1,64 @@+from __future__ import annotations++import json+from pathlib import Path++import pytest++from headroom import fsutil+from headroom.mcp_registry.antigravity import AntigravityRegistrar, _config_candidates+from headroom.mcp_registry.install import build_headroom_spec+++def _write_config(path: Path, servers: dict) -> None:+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps({"mcpServers": servers}), encoding="utf-8")+++def _servers(path: Path) -> dict:+ return json.loads(path.read_text(encoding="utf-8"))["mcpServers"]+++def test_antigravity_registrar_register_writes_current_location(tmp_path: Path) -> None:+ registrar = AntigravityRegistrar(home_dir=tmp_path)++ result = registrar.register_server(build_headroom_spec("http://127.0.0.1:9999"))++ assert result.status.value == "registered"+ assert "headroom" in _servers(_config_candidates(tmp_path)[0])+++def test_antigravity_unregister_removes_entry_from_every_candidate(+ tmp_path: Path,+) -> None:+ registrar = AntigravityRegistrar(home_dir=tmp_path)+ for candidate in _config_candidates(tmp_path):+ _write_config(candidate, {"headroom": {"command": "headroom"}})++ assert registrar.unregister_server("headroom") is True+ for candidate in _config_candidates(tmp_path):+ assert "headroom" not in _servers(candidate)+++def test_antigravity_unregister_reports_failure_when_a_write_fails(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ registrar = AntigravityRegistrar(home_dir=tmp_path)+ candidates = _config_candidates(tmp_path)+ for candidate in candidates:+ _write_config(candidate, {"headroom": {"command": "headroom"}})++ real_write = fsutil.write_text++ def fail_first(path: Path, content: str) -> None:+ if path == candidates[0]:+ raise OSError("read-only filesystem")+ return real_write(path, content)++ monkeypatch.setattr(fsutil, "write_text", fail_first)++ # The second config was cleaned up, but the failed one still registers the+ # server — so this must not report success.+ assert registrar.unregister_server("headroom") is False+ assert "headroom" in _servers(candidates[0])+ assert "headroom" not in _servers(candidates[1])diff --git a/tests/test_provider_antigravity.py b/tests/test_provider_antigravity.pynew file mode 100644index 000000000..8b1833050--- /dev/null+++ b/tests/test_provider_antigravity.py@@ -0,0 +1,88 @@+from __future__ import annotations++from headroom.providers.antigravity import (+ build_install_env,+ build_proxy_targets,+ render_setup_lines,+)+++def test_antigravity_proxy_targets_openai_base_url() -> None:+ targets = build_proxy_targets(8787)+ assert targets.openai_base_url == "http://127.0.0.1:8787/v1"+++def test_antigravity_proxy_targets_anthropic_base_url() -> None:+ targets = build_proxy_targets(8787)+ assert targets.anthropic_base_url == "http://127.0.0.1:8787"+++def test_antigravity_proxy_targets_use_given_port() -> None:+ targets = build_proxy_targets(9999)+ assert targets.openai_base_url == "http://127.0.0.1:9999/v1"+ assert targets.anthropic_base_url == "http://127.0.0.1:9999"+++def test_antigravity_proxy_targets_apply_project_prefix() -> None:+ targets = build_proxy_targets(8787, project="myrepo")+ assert targets.openai_base_url == "http://127.0.0.1:8787/p/myrepo/v1"+ assert targets.anthropic_base_url == "http://127.0.0.1:8787/p/myrepo"+++def test_antigravity_proxy_targets_ignore_blank_project() -> None:+ targets = build_proxy_targets(8787, project=" ")+ assert targets.openai_base_url == "http://127.0.0.1:8787/v1"+ assert targets.anthropic_base_url == "http://127.0.0.1:8787"+++def test_antigravity_build_install_env_sets_base_urls() -> None:+ env = build_install_env(port=8787, backend="ignored")+ assert env == {+ "OPENAI_BASE_URL": "http://127.0.0.1:8787/v1",+ "ANTHROPIC_BASE_URL": "http://127.0.0.1:8787",+ }+++def test_antigravity_build_install_env_uses_given_port() -> None:+ env = build_install_env(port=9999, backend="ignored")+ assert env["OPENAI_BASE_URL"] == "http://127.0.0.1:9999/v1"+ assert env["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:9999"+++def test_antigravity_render_setup_lines_contains_proxy_url() -> None:+ lines = render_setup_lines(8787)+ joined = "\n".join(lines)+ assert "http://127.0.0.1:8787/v1" in joined+ assert "Antigravity" in joined+++def test_antigravity_render_setup_lines_mentions_custom_provider() -> None:+ joined = "\n".join(render_setup_lines(8787))+ assert "OpenAI-compatible" in joined+ assert "/v1/models" in joined+++def test_antigravity_render_setup_lines_project_attribution() -> None:+ lines = render_setup_lines(8787, project="my-sf-project")+ joined = "\n".join(lines)+ assert "my-sf-project" in joined+ plain = "\n".join(render_setup_lines(8787))+ assert "attributed" not in plain+++def test_antigravity_install_registry_includes_antigravity() -> None:+ from headroom.providers.install_registry import build_install_target_envs++ result = build_install_target_envs(port=1234, backend="ignored", targets=["antigravity"])+ assert result["antigravity"]["OPENAI_BASE_URL"] == "http://127.0.0.1:1234/v1"+ assert result["antigravity"]["ANTHROPIC_BASE_URL"] == "http://127.0.0.1:1234"+++def test_antigravity_install_registry_unknown_target_skipped() -> None:+ from headroom.providers.install_registry import build_install_target_envs++ result = build_install_target_envs(+ port=1234, backend="ignored", targets=["antigravity", "unknown-tool"]+ )+ assert "unknown-tool" not in result+ assert "antigravity" in resultdiff --git a/tests/test_provider_grok.py b/tests/test_provider_grok.pyindex 02d11c90e..df83ba688 100644--- a/tests/test_provider_grok.py+++ b/tests/test_provider_grok.py@@ -28,12 +28,15 @@ def test_is_grok_cli_request_matches_known_user_agents() -> None:is True)assert is_grok_cli_request({"user-agent": "grok-shell/0.2.112"}) is True+ # Grok Build stamps grok/<version>; per-request xAI routing must recognize+ # it too, matching the repo's own client classification (CLIENT_UA_MAP).+ assert is_grok_cli_request({"user-agent": "grok/1.2.3"}) is True# Non-Grok OpenAI-compatible clients must not match, including wrappers- # whose name merely contains "grok" — they carry OpenAI credentials.+ # whose name merely contains "grok" — they carry OpenAI credentials. The+ # prefix anchor keeps them out: only a token starting with "grok/" matches.assert is_grok_cli_request({"user-agent": "codex-tui/0.146.0"}) is Falseassert is_grok_cli_request({"user-agent": "litellm-grok/1.0"}) is Falseassert is_grok_cli_request({"user-agent": "my-grok-shell/1.0"}) is False- assert is_grok_cli_request({"user-agent": "grok/0.1.0"}) is Falseassert is_grok_cli_request({}) is Falsediff --git a/tests/test_provider_proxy_targets.py b/tests/test_provider_proxy_targets.pyindex 5e5c7bf3a..6b3aa2193 100644--- a/tests/test_provider_proxy_targets.py+++ b/tests/test_provider_proxy_targets.py@@ -104,6 +104,25 @@ def test_openai_compatible_base_url_routes_grok_to_xai_on_default_target() -> Noassert select_passthrough_base_url(proxy, grok_headers) == "https://api.x.ai"+def test_openai_compatible_base_url_routes_grok_build_to_xai_on_default_target() -> None:+ """Grok Build + Antigravity manifest case: the OpenAI target stays default.++ Antigravity needs api.openai.com, so the manifest cannot point the whole+ proxy at xAI; Grok Build's ``grok/`` user agent must still route there per+ request — for direct inference and for model-list/passthrough alike.+ """+ proxy = _proxy(OPENAI_API_URL="https://api.openai.com")+ grok_build_headers = {"user-agent": "grok/1.2.3"}++ assert openai_compatible_base_url(proxy, grok_build_headers) == "https://api.x.ai"+ assert select_passthrough_base_url(proxy, grok_build_headers) == "https://api.x.ai"+ # Antigravity traffic keeps the default OpenAI target.+ assert (+ openai_compatible_base_url(proxy, {"user-agent": "antigravity/1.0.0"})+ == "https://api.openai.com"+ )++def test_openai_compatible_base_url_respects_configured_openai_target() -> None:"""An operator gateway is chosen for every OpenAI-compatible client.