mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-22 13:29:19 +08:00
feat(antigravity): add native Google Antigravity IDE integration (#3817)
## Description Native Google Antigravity IDE integration for Headroom. Antigravity reads its model endpoints from its own model-provider settings (not env vars), so this follows the existing proxy-only `wrap` pattern: start the Headroom proxy and print the custom OpenAI-compatible provider settings to add in the IDE. A new MCP registrar installs Headroom into Antigravity's global `mcp_config.json`. Closes #727 ## Type of Change - [x] New feature (non-breaking change that adds functionality) ## Changes Made - `headroom wrap antigravity` — starts the proxy and prints the custom OpenAI-compatible model-provider settings for Antigravity (same proxy-only pattern as `wrap cursor`; per-project `/p/<name>` base-URL prefixes for dashboard attribution). - `headroom mcp install --agent antigravity` — new `AntigravityRegistrar` for the global `mcp_config.json` under `~/.gemini/`. Prefers an already-existing config location, refuses to overwrite unparseable JSON, clears Antigravity's per-surface MCP cache dirs on uninstall. - Registers the `antigravity` slice in the persistent install env registry. - Docs: `proxy.mdx` gains an Antigravity IDE section covering `wrap`, `mcp install`, and the existing `/v1internal:streamGenerateContent` Cloud Code compatibility endpoint for native google-antigravity clients. ## Testing - [x] Unit tests pass (`pytest`) - [x] Linting passes (`ruff check .`) - [ ] Type checking passes (`mypy headroom`) - [x] New tests added for new functionality - [x] Manual testing performed ### Test Output ```text $ pytest tests/test_cli/test_wrap_antigravity.py \ tests/test_mcp_registry/test_antigravity_registrar.py \ tests/test_provider_antigravity.py 34 passed, 1 warning in 0.75s (the warning is a pre-existing `asyncio_mode` config notice, unrelated) $ ruff check <changed files> All checks passed! $ ruff format --check <changed files> 7 files already formatted ``` ## Real Behavior Proof - Environment: Linux, Python 3.12, branch `fix/727-antigravity-integration` - Exact command / steps: `wrap --help` (lists `antigravity`, exit 0); `wrap antigravity --help` (prints the Antigravity IDE setup instructions for the custom OpenAI-compatible model-provider flow); `wrap antigravity --prepare-only` (exit 0). - Observed result: the new command is wired into the CLI and its help text documents the custom-provider setup flow. - Not tested: end-to-end `mcp install` against a real Antigravity IDE (the MCP SDK extra is not installed in this environment; registrar behavior is covered by its unit tests); live proxy traffic from an actual Antigravity client. ## Runtime Rollout Safety - Rollout-managed feature(s): none (new additive commands only) - Minimum rollout channel: n/a - Stable/default behavior changed: no — existing `wrap` / `mcp install` flows are untouched - Kill switch / disable path: do not run the new commands; `headroom mcp uninstall --agent antigravity` removes the MCP registration - Unsafe override required: no - Qualification impact: none - Rollback path: revert the single commit ## Review Readiness - [x] I have performed a self-review - [x] This PR is ready for human review ## Checklist - [x] My code follows the project's style guidelines - [x] I have performed a self-review of my code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] New and existing unit tests pass locally with my changes - [x] I did **not** edit `CHANGELOG.md` — it is generated by release-please from my Conventional Commit PR title ## Additional Notes - `mypy` was not run (not installed in this environment); `ruff check` and `ruff format` are clean on all changed files. - Antigravity reads endpoints from its model-provider settings, not env vars, so `wrap antigravity` prints setup instructions instead of launching the IDE. <!-- devin-review-badge-begin --> --- <a href="https://app.devin.ai/review/headroomlabs-ai/headroom/pull/3817" target="_blank"><picture><source media="(prefers-color-scheme: dark)" srcset="https://static.devin.ai/assets/gh-devin-review-dark.svg?v=4"><img src="https://static.devin.ai/assets/gh-devin-review-light.svg?v=4" alt="Devin Review"></picture></a> <!-- devin-review-badge-end --> --------- Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
@@ -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.
|
||||
|
||||
+26
-6
@@ -139,9 +139,9 @@ def mcp_install(proxy_url: str, agents: tuple[str, ...], force: bool) -> None:
|
||||
|
||||
\b
|
||||
By 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.
|
||||
|
||||
\b
|
||||
Examples:
|
||||
@@ -188,18 +188,38 @@ def mcp_install(proxy_url: str, agents: tuple[str, ...], force: bool) -> None:
|
||||
|
||||
|
||||
@mcp.command("uninstall")
|
||||
def mcp_uninstall() -> None:
|
||||
@click.option(
|
||||
"--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.
|
||||
|
||||
\b
|
||||
Removes 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():
|
||||
continue
|
||||
removed_names: list[str] = []
|
||||
|
||||
+78
-2
@@ -11,6 +11,7 @@ Usage:
|
||||
headroom wrap vibe # Start proxy + Mistral Vibe
|
||||
headroom wrap grok # Start proxy + Grok CLI
|
||||
headroom wrap cursor # Start proxy + print Cursor config instructions
|
||||
headroom wrap antigravity # Start proxy + print Antigravity config instructions
|
||||
headroom wrap grok-build # Start proxy + configure Grok Build
|
||||
headroom wrap openclaw # Install + configure OpenClaw plugin
|
||||
headroom 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 Vibe
|
||||
headroom 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
|
||||
# =============================================================================
|
||||
|
||||
|
||||
@wrap.command(context_settings={"ignore_unknown_options": True})
|
||||
@_retired_context_tool_option
|
||||
@proxy_port_option()
|
||||
@click.option("--no-proxy", is_flag=True, help="Skip proxy startup (use existing proxy)")
|
||||
@click.option("--learn", is_flag=True, help="Enable live traffic learning")
|
||||
@click.option("--memory", is_flag=True, help="Enable persistent cross-session memory")
|
||||
@click.option("--verbose", "-v", is_flag=True, help="Verbose output")
|
||||
@click.option("--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
|
||||
# =============================================================================
|
||||
|
||||
@@ -59,6 +59,7 @@ class ToolTarget(str, Enum):
|
||||
GROK = "grok"
|
||||
OPENCLAW = "openclaw"
|
||||
OPENCODE = "opencode"
|
||||
ANTIGRAVITY = "antigravity"
|
||||
|
||||
|
||||
def iso_utc_now() -> str:
|
||||
|
||||
@@ -9,6 +9,7 @@ from collections.abc import Iterable
|
||||
import click
|
||||
|
||||
from headroom import paths as _paths
|
||||
from headroom.mcp_registry.antigravity import AntigravityRegistrar
|
||||
from headroom.providers.grok.runtime import DEFAULT_API_URL as _GROK_DEFAULT_API_URL
|
||||
from headroom.providers.install_registry import build_install_target_envs
|
||||
from 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]:
|
||||
continue
|
||||
if 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)
|
||||
|
||||
@@ -13,6 +13,7 @@ without changing the calling code.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from .antigravity import AntigravityRegistrar
|
||||
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
|
||||
from .claude import ClaudeConfigMutationError, ClaudeRegistrar
|
||||
from .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",
|
||||
|
||||
@@ -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)
|
||||
@@ -6,6 +6,7 @@ from collections.abc import Iterable
|
||||
|
||||
from headroom.install.runtime import resolve_headroom_command
|
||||
|
||||
from .antigravity import AntigravityRegistrar
|
||||
from .base import MCPRegistrar, RegisterResult, RegisterStatus, ServerSpec
|
||||
from .claude import ClaudeRegistrar
|
||||
from .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:
|
||||
|
||||
@@ -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",
|
||||
]
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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 lines
|
||||
@@ -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:
|
||||
|
||||
@@ -6,6 +6,9 @@ from collections.abc import Callable
|
||||
|
||||
from headroom.install.models import DeploymentManifest, ManagedMutation
|
||||
from 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,
|
||||
|
||||
@@ -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 xAI
|
||||
session 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-all
|
||||
passthrough succeed on a shared proxy whose OpenAI target is the default.
|
||||
"""
|
||||
target = api_target(proxy, "openai")
|
||||
|
||||
@@ -199,6 +199,33 @@ class TestMCPUninstallCommand:
|
||||
assert result.exit_code == 0
|
||||
assert "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."""
|
||||
|
||||
@@ -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"] == 7777
|
||||
@@ -426,3 +426,46 @@ def test_persistent_task_does_not_inherit_service_backend_defaults() -> None:
|
||||
|
||||
assert "HEADROOM_EMBEDDER_RUNTIME" not in manifest.base_env
|
||||
assert "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()
|
||||
|
||||
@@ -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
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -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()
|
||||
@@ -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])
|
||||
@@ -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 result
|
||||
@@ -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 False
|
||||
assert is_grok_cli_request({"user-agent": "litellm-grok/1.0"}) is False
|
||||
assert 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 False
|
||||
assert is_grok_cli_request({}) is False
|
||||
|
||||
|
||||
|
||||
@@ -104,6 +104,25 @@ def test_openai_compatible_base_url_routes_grok_to_xai_on_default_target() -> No
|
||||
assert 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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user