Skip to content
98 changes: 78 additions & 20 deletions apps/sandbox-executor/src/sandbox_executor/runners/antigravity.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
from __future__ import annotations

import functools
import os
import re
import shutil
import subprocess
import sys

from sandbox_executor.runners.spec import VALID_EFFORT_LEVELS, ModelCapability, RunnerSpec, has_api_key

# why: discovery runs while agent_defaults is imported, so every CLI start pays this bound when agy is slow.
_AGY_MODELS_TIMEOUT_SECONDS = 5
_GEMINI_MODEL_ID = re.compile(r"gemini-[a-z0-9][a-z0-9.\-]*", re.IGNORECASE)
_ANTIGRAVITY_CLI_CONTAINER_DIR = "/home/holon/.gemini/antigravity-cli"
_CONTAINER_GEMINI_PATHS = (_ANTIGRAVITY_CLI_CONTAINER_DIR, "/home/holon/.gemini")
_HOME_GEMINI_PATHS = ("~/.gemini/antigravity-cli", "~/.gemini")
Expand Down Expand Up @@ -76,48 +83,99 @@ def _session_mounts(home: str) -> list[str]:
return []


def _coordinate_gemini_effort(canonical: str, effort: str | None) -> tuple[str, str | None]:
eff = effort.strip().lower() if effort and effort.strip() else None
def _requested_effort(effort: str | None) -> str | None:
requested = (effort or "").strip().lower()
return requested if requested in VALID_EFFORT_LEVELS else None


inferred_effort = None
base = canonical
def _split_effort_suffix(model: str) -> tuple[str, str | None]:
for level in VALID_EFFORT_LEVELS:
suffix = f"-{level}"
if canonical.endswith(suffix):
inferred_effort = level
base = canonical[: -len(suffix)]
break
if model.endswith(suffix):
return model[: -len(suffix)], level
return model, None


if eff in VALID_EFFORT_LEVELS:
return f"{base}-{eff}", eff
if inferred_effort:
return canonical, inferred_effort
return canonical, None
def _coordinate_gemini_effort(canonical: str, effort: str | None) -> tuple[str, str | None]:
base, suffix_level = _split_effort_suffix(canonical)
requested = _requested_effort(effort)
if requested is not None:
return f"{base}-{requested}", requested
return canonical, suffix_level


def _gemini_capability(canonical_model: str, alias: str) -> ModelCapability:
def _gemini_capability(canonical_model: str, *aliases: str) -> ModelCapability:
return ModelCapability(
runner="antigravity-agent",
canonical_model=canonical_model,
aliases=[alias],
aliases=list(aliases),
effort_levels=list(VALID_EFFORT_LEVELS),
fallback_tier="Primary (Cloud/CLI)",
)


def _listed_gemini_model_ids(listing: str) -> tuple[str, ...]:
first_tokens = (line.split()[0].lower() for line in listing.splitlines() if line.split())
return tuple(dict.fromkeys(token for token in first_tokens if _GEMINI_MODEL_ID.fullmatch(token)))


@functools.cache
def _agy_listed_models() -> tuple[str, ...]:
if shutil.which("agy") is None:
return ()
try:
completed = subprocess.run(
["agy", "models"],
stdin=subprocess.DEVNULL,
capture_output=True,
text=True,
timeout=_AGY_MODELS_TIMEOUT_SECONDS,
check=False,
)
except (OSError, subprocess.SubprocessError):
return ()
if completed.returncode != 0:
return ()
return _listed_gemini_model_ids(completed.stdout)


def _known_model_ids(capabilities: tuple[ModelCapability, ...]) -> set[str]:
known: set[str] = set()
for capability in capabilities:
canonical = capability.canonical_model.lower()
known.add(canonical)
known.update(f"{canonical}-{level}" for level in capability.effort_levels)
return known


def _discover_antigravity_models(spec: RunnerSpec) -> tuple[ModelCapability, ...]:
known = _known_model_ids(spec.model_capabilities)
listed_bases = dict.fromkeys(_split_effort_suffix(model_id)[0] for model_id in _agy_listed_models())
unseen = (model_id for model_id in listed_bases if model_id not in known)
return (*spec.model_capabilities, *(_gemini_capability(model_id) for model_id in unseen))


# why: historical records and default_model still name the gemini-3.8-flash family, so it stays valid next to gemini-4.
ANTIGRAVITY_FALLBACK_CAPABILITIES: tuple[ModelCapability, ...] = (
_gemini_capability("gemini-3.8-flash", "flash"),
_gemini_capability("gemini-3.8-flash-medium", "flash-medium"),
_gemini_capability("gemini-3.8-flash-high", "flash-high"),
_gemini_capability("gemini-4-neon", "neon"),
_gemini_capability("gemini-4-argon", "argon"),
_gemini_capability("gemini-4-carbon", "carbon"),
_gemini_capability("gemini-4-hydrogen", "hydrogen"),
)

SPEC = RunnerSpec(
agent_id="antigravity",
image="holon/agent-antigravity",
default_model="gemini-3.8-flash-medium",
ticker="ANA",
api_key_env_vars=("HOLON_AGENT_KEY",),
credential_check=_check_credentials,
model_capabilities=(
_gemini_capability("gemini-3.8-flash", "flash"),
_gemini_capability("gemini-3.8-flash-medium", "flash-medium"),
_gemini_capability("gemini-3.8-flash-high", "flash-high"),
),
model_capabilities=ANTIGRAVITY_FALLBACK_CAPABILITIES,
model_normalizer=_coordinate_gemini_effort,
model_discovery_hook=_discover_antigravity_models,
provider_api_key_env_vars=("AGY_USER_TOKEN", "GOOGLE_API_KEY", "GEMINI_API_KEY"),
session_detection_paths=_SESSION_DETECTION_PATHS,
harness_markers=(("AGY_", "prefix"), ("ANTIGRAVITY_", "prefix")),
Expand Down
4 changes: 3 additions & 1 deletion apps/sandbox-executor/tests/test_gemini_runner_purged.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def test_antigravity_gemini_models_and_effort_levels_preserved() -> None:

# Test capabilities count and effort levels
caps = get_model_capabilities("antigravity-agent")
assert len(caps) == 3
assert {"gemini-3.8-flash", "gemini-3.8-flash-medium", "gemini-3.8-flash-high"} <= {
cap.canonical_model for cap in caps
}
for cap in caps:
assert cap.effort_levels == ["low", "medium", "high"]

Expand Down
33 changes: 31 additions & 2 deletions apps/sandbox-executor/tests/test_models_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@
)
from sandbox_executor.preflight import PreflightResult, PreflightStatus

ANTIGRAVITY_EXPECTED_MODELS = {
"gemini-3.8-flash",
"gemini-3.8-flash-medium",
"gemini-3.8-flash-high",
"gemini-4-neon",
"gemini-4-carbon",
"gemini-4-hydrogen",
}


def test_models_command_table_display(capsys: pytest.CaptureFixture[str]) -> None:
"""Verify that holon models executes real CLI dispatch and prints a formatted table."""
Expand Down Expand Up @@ -72,6 +81,7 @@ def test_models_agent_filtering_antigravity(capsys: pytest.CaptureFixture[str])
assert "gemini-3.8-flash" in out
assert "gemini-3.8-flash-medium" in out
assert "gemini-3.8-flash-high" in out
assert "gemini-4-neon" in out
assert "low, medium, high" in out

assert "claude-agent" not in out
Expand Down Expand Up @@ -169,7 +179,7 @@ def test_models_json_filtered_agent(capsys: pytest.CaptureFixture[str]) -> None:
captured = capsys.readouterr()
data = json.loads(captured.out)

assert len(data) == 3
assert {entry["canonical_model"] for entry in data} >= ANTIGRAVITY_EXPECTED_MODELS
for entry in data:
assert entry["runner"] == "antigravity-agent"
assert entry["effort_levels"] == ["low", "medium", "high"]
Expand Down Expand Up @@ -327,6 +337,25 @@ def test_doctor_shows_canonical_model_and_alias_in_text_and_json(capsys: pytest.
assert "fable" in payload["model"]["reason"]


@pytest.mark.parametrize("model_flag", ["gemini-4-neon", "neon"])
def test_doctor_accepts_gemini_4_neon_for_antigravity(capsys: pytest.CaptureFixture[str], model_flag: str) -> None:
ok_probe = PreflightResult(
status=PreflightStatus.OK,
agent="antigravity-agent",
model="gemini-4-neon",
image="holon/agent-antigravity",
exit_code=0,
output_excerpt="OK",
hint="",
)
with patch("sandbox_executor.cli.doctor.run_preflight_probe", return_value=ok_probe) as probe:
with pytest.raises(SystemExit) as exc_info:
cli.main(["doctor", "--agent", "antigravity-agent", "--model", model_flag])
assert exc_info.value.code == 0
assert probe.call_args[0][:2] == ("antigravity-agent", "gemini-4-neon")
assert "Model resolved to gemini-4-neon" in capsys.readouterr().out


def test_detect_runner_auth_status_safe_and_opaque() -> None:
"""Verify detect_runner_auth_status produces only known opaque status strings."""
valid_statuses = {
Expand All @@ -339,4 +368,4 @@ def test_detect_runner_auth_status_safe_and_opaque() -> None:
for cap in get_model_capabilities():
status = detect_runner_auth_status(cap.runner)
assert status in valid_statuses
assert len(get_available_models_for_runner("antigravity")) == 3
assert set(get_available_models_for_runner("antigravity")) >= ANTIGRAVITY_EXPECTED_MODELS
102 changes: 101 additions & 1 deletion apps/sandbox-executor/tests/test_runner_specs.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

import pytest
from sandbox_executor import claude_keychain
from sandbox_executor.agent_defaults import normalise_model_and_effort
from sandbox_executor.agent_defaults import is_valid_model_for_runner, normalise_model_and_effort
from sandbox_executor.launcher import antigravity_mounts as launcher_antigravity_mounts
from sandbox_executor.launcher import pi_mounts as launcher_pi_mounts
from sandbox_executor.launcher.mounts import get_agent_session_mounts
Expand Down Expand Up @@ -222,7 +222,21 @@ def test_pi_accepts_models_json_in_pi_coding_agent_dir(
assert RUNNER_SPECS["pi"].check_credentials() is None


@pytest.fixture
def no_agy(monkeypatch: pytest.MonkeyPatch):
antigravity_runner._agy_listed_models.cache_clear()
monkeypatch.setattr(antigravity_runner.shutil, "which", lambda name: None)
yield
antigravity_runner._agy_listed_models.cache_clear()


def _stub_agy_models(monkeypatch: pytest.MonkeyPatch, run) -> None:
monkeypatch.setattr(antigravity_runner.shutil, "which", lambda name: "/usr/bin/agy")
monkeypatch.setattr(antigravity_runner.subprocess, "run", run)


@pytest.mark.parametrize("agent_id", list(RUNNER_SPECS))
@pytest.mark.usefixtures("no_agy")
def test_every_spec_discovers_its_declared_models(agent_id: str) -> None:
spec = RUNNER_SPECS[agent_id]
discovered = spec.discovered_models()
Expand Down Expand Up @@ -254,6 +268,11 @@ def test_model_discovery_hook_replaces_declared_capabilities() -> None:
("gemini-3.8-flash-medium", None, ("gemini-3.8-flash-medium", "medium")),
("gemini-3.8-flash-medium", " LOW ", ("gemini-3.8-flash-low", "low")),
("gemini-3.8-flash-high", "unknown", ("gemini-3.8-flash-high", "high")),
("gemini-4-neon", None, ("gemini-4-neon", None)),
("gemini-4-neon-high", "LOW ", ("gemini-4-neon-low", "low")),
("gemini-4-neon", "max", ("gemini-4-neon", None)),
("gemini-4-neon-medium", None, ("gemini-4-neon-medium", "medium")),
("gemini-4-carbon", "high", ("gemini-4-carbon-high", "high")),
],
)
def test_antigravity_spec_coordinates_model_and_effort(
Expand Down Expand Up @@ -435,3 +454,84 @@ def test_next_fallback_model_stops_at_the_last_rung_and_off_ladder() -> None:
assert next_fallback_model("claude-agent", "claude-haiku-4-5") is None
assert next_fallback_model("antigravity-agent", "gemini-3.8-flash-medium") is None
assert next_fallback_model("pi-agent", "local-model") is None


@pytest.mark.usefixtures("no_agy")
def test_antigravity_fallback_covers_gemini_4_and_legacy_flash_models() -> None:
canonical = {cap.canonical_model for cap in RUNNER_SPECS["antigravity"].discovered_models()}
assert {
"gemini-3.8-flash",
"gemini-3.8-flash-medium",
"gemini-3.8-flash-high",
"gemini-4-neon",
"gemini-4-argon",
"gemini-4-carbon",
"gemini-4-hydrogen",
} <= canonical
assert set(ANTIGRAVITY_LADDER) <= canonical


@pytest.mark.parametrize(
("model", "expected"),
[
("neon", ("gemini-4-neon", None)),
("carbon", ("gemini-4-carbon", None)),
("hydrogen", ("gemini-4-hydrogen", None)),
("gemini-4-neon-high", ("gemini-4-neon-high", "high")),
],
)
def test_antigravity_resolves_gemini_4_aliases_without_inventing_effort(
model: str, expected: tuple[str, str | None]
) -> None:
assert normalise_model_and_effort("antigravity", model) == expected


@pytest.mark.parametrize(
"model", ["gemini-4-neon", "gemini-4-neon-high", "gemini-4-carbon-low", "gemini-4-hydrogen", "neon"]
)
def test_antigravity_accepts_gemini_4_models(model: str) -> None:
assert is_valid_model_for_runner("antigravity-agent", model)


@pytest.mark.usefixtures("no_agy")
def test_antigravity_discovery_adds_listed_gemini_models(monkeypatch: pytest.MonkeyPatch) -> None:
listing = (
"MODEL DESCRIPTION\ngemini-4-neon default\ngemini-4-neon-pro-high new\ngemini-4-neon-pro new\n"
"warning: gemini-x is slow\n\n"
)
calls: list[list[str]] = []

def run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
calls.append(cmd)
assert kwargs["stdin"] is subprocess.DEVNULL
return subprocess.CompletedProcess(cmd, 0, stdout=listing, stderr="")

_stub_agy_models(monkeypatch, run)
spec = RUNNER_SPECS["antigravity"]
discovered = spec.discovered_models()
assert discovered[: len(spec.model_capabilities)] == spec.model_capabilities
assert [cap.canonical_model for cap in discovered[len(spec.model_capabilities) :]] == ["gemini-4-neon-pro"]
spec.discovered_models()
assert calls == [["agy", "models"]]


@pytest.mark.parametrize(
"outcome",
[
subprocess.TimeoutExpired(["agy", "models"], 5),
OSError("agy vanished"),
subprocess.CompletedProcess(["agy", "models"], 1, stdout="gemini-4-neon-pro\n", stderr="auth required"),
],
)
@pytest.mark.usefixtures("no_agy")
def test_antigravity_discovery_falls_back_when_agy_fails(
monkeypatch: pytest.MonkeyPatch, outcome: BaseException | subprocess.CompletedProcess[str]
) -> None:
def run(cmd: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:
if isinstance(outcome, BaseException):
raise outcome
return outcome

_stub_agy_models(monkeypatch, run)
spec = RUNNER_SPECS["antigravity"]
assert spec.discovered_models() == spec.model_capabilities
Loading
Loading