Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(antigravity): drive agy correctly — de-lag, real subagent, honest test + auth

Ruben Lütkec0e1f55741e7
diff --git a/jarvis/brain/provider_test.py b/jarvis/brain/provider_test.py
index a6a4d92ec0..8287961e83 100644
--- a/jarvis/brain/provider_test.py
+++ b/jarvis/brain/provider_test.py
@@ -198,6 +198,12 @@ def _default_codex_status() -> Any:
return CodexAuthService().status()
+def _default_antigravity_status() -> Any:
+ from jarvis.google_cli.auth_service import GoogleCliAuthService
+
+ return GoogleCliAuthService().status()
+
+
async def _silence_chunks():
"""One ~0.5 s 16 kHz mono PCM16 silence chunk — enough for a cloud STT to
authenticate and answer (with an empty transcript); never long enough to
@@ -219,6 +225,7 @@ async def run_provider_test(
make_tts: Callable[[Any, str], Any] | None = None,
make_stt: Callable[[Any, str], Any] | None = None,
codex_status: Callable[[], Any] | None = None,
+ antigravity_status: Callable[[], Any] | None = None,
timeout_s: float = 25.0,
) -> ProviderTestResult:
"""Run a REAL minimal call against ``spec``'s provider and classify it.
@@ -242,6 +249,22 @@ async def run_provider_test(
provider, NOT_CONFIGURED, getattr(st, "message", "") or "Not connected.",
)
+ # Antigravity is OAuth-only (Google subscription): a connected login IS a
+ # working brain. NEVER run a real agy/gemini turn here — it is slow (~8s) and
+ # bills the subscription; the connected status is the honest, instant signal.
+ # (A real turn would also false-OK on AntigravityBrain's empty progress tick.)
+ if spec.auth_mode == "antigravity":
+ status_fn = antigravity_status or _default_antigravity_status
+ try:
+ st = status_fn()
+ except Exception as exc: # noqa: BLE001
+ return ProviderTestResult(provider, ERROR, f"{type(exc).__name__}: {exc}")
+ if getattr(st, "connected", False):
+ return ProviderTestResult(provider, OK, getattr(st, "message", "") or "Connected.")
+ return ProviderTestResult(
+ provider, NOT_CONFIGURED, getattr(st, "message", "") or "Not connected.",
+ )
+
# API-key providers: a missing credential is "not_configured" — nothing to test.
if spec.auth_mode == "api_key":
is_present = present if present is not None else _is_credential_present(spec)
diff --git a/jarvis/google_cli/auth_service.py b/jarvis/google_cli/auth_service.py
index 434b3203fa..478af30e3b 100644
--- a/jarvis/google_cli/auth_service.py
+++ b/jarvis/google_cli/auth_service.py
@@ -21,7 +21,6 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
-from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.google_cli.resolver import GoogleCli, resolve_google_cli
log = logging.getLogger(__name__)
@@ -164,19 +163,21 @@ class GoogleCliAuthService:
def start_login(self) -> subprocess.Popen[bytes]:
"""Spawn the official CLI login in a visible console. Raises if absent.
- ``agy`` uses ``agy login``; the Gemini CLI drops into its interactive
- auth picker on a bare run. Detached with a fresh console (Windows) /
- new session (POSIX) so the device/OAuth URL is reachable under pythonw.
+ Neither CLI has a dedicated ``login`` subcommand — verified 2026-06-21,
+ ``agy login`` simply HANGS (it is not a real subcommand; ``agy help``
+ lists only changelog/help/install/models/plugin/update). Both ``agy`` and
+ the Gemini CLI drop into the interactive "Sign in with Google" flow on a
+ bare run, so we launch the bare binary. Detached with a fresh console
+ (Windows) / new session (POSIX) so the device/OAuth URL is reachable
+ under pythonw.
"""
cli = self._resolve()
if cli is None:
raise FileNotFoundError(
"No Google CLI found (install agy or the Gemini CLI)."
)
- argv = (
- [*cli.argv_prefix, "login"] if cli.kind == "agy" else list(cli.argv_prefix)
- )
- log.info("Starting Google CLI login (interactive, kind=%s)", cli.kind)
+ argv = list(cli.argv_prefix) # bare interactive run — no `login` subcommand
+ log.info("Starting Google CLI login (interactive bare run, kind=%s)", cli.kind)
if sys.platform == "win32":
kwargs: dict[str, Any] = {"creationflags": _NEW_CONSOLE_FLAGS}
else:
@@ -189,26 +190,15 @@ class GoogleCliAuthService:
return subprocess.Popen(argv, **kwargs) # noqa: S603 — fixed argv, shell=False
def logout_blocking(self) -> tuple[bool, str | None]:
- """Disconnect: ``agy logout`` (best effort) then remove the on-disk creds.
+ """Disconnect by removing the on-disk OAuth creds.
- Returns ``(ok, error)``. ``ok`` is True when the creds were removed or
- the CLI logout succeeded.
- """
- cli = self._resolve()
- if cli is not None and cli.kind == "agy":
- try:
- proc = subprocess.run(
- [*cli.argv_prefix, "logout"],
- capture_output=True,
- text=True,
- timeout=15.0,
- creationflags=NO_WINDOW_CREATIONFLAGS,
- )
- if proc.returncode == 0:
- return True, None
- except (OSError, subprocess.SubprocessError) as exc:
- log.warning("agy logout failed (%s); removing creds", exc)
+ Neither CLI has a ``logout`` subcommand (verified 2026-06-21) — ``agy
+ logout`` would hang like ``agy login``. Removing ``~/.gemini/oauth_creds
+ .json`` IS the disconnect; the isolated brain home re-syncs to the absent
+ creds on the next turn (see ``isolated_home``), so agy logs out there too.
+ Returns ``(ok, error)``; ``ok`` is True when the creds are gone.
+ """
try:
(_gemini_home() / "oauth_creds.json").unlink(missing_ok=True)
return True, None
diff --git a/jarvis/google_cli/isolated_home.py b/jarvis/google_cli/isolated_home.py
new file mode 100644
index 0000000000..d58b16e19a
--- /dev/null
+++ b/jarvis/google_cli/isolated_home.py
@@ -0,0 +1,113 @@
+"""Isolated, hook/mcp-free CLI home for driving ``agy``/``gemini`` headlessly.
+
+Why this exists (the lag fix): the user's real ``~/.gemini/settings.json`` is
+polluted with dozens of duplicated BridgeSpace PowerShell ``SessionStart`` /
+``BeforeAgent`` hooks plus ``mcpServers``; ``agy`` boots ALL of them on every
+``--print`` turn — a 13 s storm of ``powershell.exe`` + ``npm exec`` spawns.
+Pointing the child's HOME at an isolated home that carries only the copied OAuth
+login + a minimal ``settings.json`` (no ``hooks``, no ``mcpServers``) drops a
+turn to ~8 s and stops the per-turn MCP boot (verified live 2026-06-21).
+
+Shared by the brain (``jarvis.plugins.brain.antigravity``) and the mission worker
+(``jarvis.missions.workers.google_cli_worker``); it is CLI infrastructure, so it
+lives next to the resolver/pty_runner rather than in either consumer.
+
+Google ToS: only the OAuth login *material* is copied (presence-only, never read
+into business logic); the token is never scraped to make our own HTTP request.
+"""
+from __future__ import annotations
+
+import json
+import logging
+import os
+import shutil
+import threading
+from contextlib import suppress
+
+from jarvis.core.config import DATA_DIR
+
+log = logging.getLogger(__name__)
+
+# Serializes isolated-home (re)builds across concurrent turns/workers.
+_ISO_HOME_LOCK = threading.Lock()
+
+# Login material mirrored from the real ~/.gemini into the isolated home.
+_LOGIN_FILES: tuple[str, ...] = ("oauth_creds.json", "google_accounts.json", "installation_id")
+_MTIME_MARKER = ".jarvis_src_mtime"
+
+
+def real_gemini_dir() -> str:
+ """The user's real ~/.gemini dir — read-only source of the OAuth login."""
+ return os.path.join(os.path.expanduser("~"), ".gemini")
+
+
+def iso_home_root() -> str:
+ """Stable dir hosting the isolated, hook/mcp-free CLI home (HOME points here)."""
+ return os.path.join(str(DATA_DIR), "agy_cli_home")
+
+
+def ensure_isolated_home(*, real_dir: str, dest_root: str, model: str) -> str | None:
+ """Build/refresh an isolated CLI home so agy/gemini never boot the user's
+ per-turn hooks or MCP servers — the actual lag fix.
+
+ Keeps the OAuth login (so the subscription stays signed in under the
+ redirected HOME) but a minimal ``settings.json`` with the model pinned and
+ **no** ``hooks`` / ``mcpServers``. When the real creds vanish (logout removed
+ ``~/.gemini/oauth_creds.json``) the stale copy is dropped so the CLI is logged
+ out under the redirected HOME too.
+
+ Returns the home dir to point ``HOME``/``USERPROFILE`` at, or ``None`` on
+ failure (the caller then leaves HOME alone and the CLI uses the real home).
+ """
+ try:
+ with _ISO_HOME_LOCK:
+ g = os.path.join(dest_root, ".gemini")
+ os.makedirs(g, exist_ok=True)
+ creds = os.path.join(real_dir, "oauth_creds.json")
+ marker = os.path.join(g, _MTIME_MARKER)
+ if os.path.isfile(creds):
+ # Re-sync only when the real creds change (a fresh login), so the
+ # CLI's own token refresh inside the home is not clobbered.
+ stamp = repr(os.path.getmtime(creds))
+ prev: str | None = None
+ if os.path.isfile(marker):
+ with suppress(OSError):
+ with open(marker, encoding="utf-8") as fh:
+ prev = fh.read().strip()
+ if prev != stamp:
+ for fname in _LOGIN_FILES:
+ src = os.path.join(real_dir, fname)
+ if os.path.isfile(src):
+ shutil.copy2(src, os.path.join(g, fname))
+ with open(marker, "w", encoding="utf-8") as fh:
+ fh.write(stamp)
+ else:
+ # Logout removed the real creds → drop the stale copy so the CLI
+ # is logged out under the redirected HOME too.
+ for fname in ("oauth_creds.json", "google_accounts.json", _MTIME_MARKER):
+ with suppress(OSError):
+ os.remove(os.path.join(g, fname))
+ settings = {
+ "security": {"auth": {"selectedType": "oauth-personal"}},
+ "model": {"name": model},
+ }
+ tmp = os.path.join(g, "settings.json.tmp")
+ with open(tmp, "w", encoding="utf-8") as fh:
+ json.dump(settings, fh)
+ os.replace(tmp, os.path.join(g, "settings.json"))
+ return dest_root
+ except OSError as exc:
+ log.warning("isolated CLI home setup failed: %s", exc)
+ return None
+
+
+def redirect_home_env(env: dict[str, str], iso: str) -> dict[str, str]:
+ """Point ``env``'s HOME at the isolated home so the CLI reads our minimal,
+ hook/mcp-free settings. Mutates and returns ``env`` for convenience."""
+ env["USERPROFILE"] = iso
+ env["HOME"] = iso
+ drive, rest = os.path.splitdrive(iso)
+ if drive:
+ env["HOMEDRIVE"] = drive
+ env["HOMEPATH"] = rest or "\\"
+ return env
diff --git a/jarvis/missions/init.py b/jarvis/missions/init.py
index 70ec9ac9a5..2406def436 100644
--- a/jarvis/missions/init.py
+++ b/jarvis/missions/init.py
@@ -51,6 +51,7 @@ from .worker_runtime.provider_map import (
from .workers.claude_direct_worker import ClaudeDirectWorker
from .workers.codex_direct_worker import CodexDirectWorker
from .workers.gemini_worker import GeminiWorker
+from .workers.google_cli_worker import GoogleCliWorker
logger = logging.getLogger(__name__)
@@ -540,15 +541,20 @@ async def bootstrap_missions(
return ClaudeDirectWorker(mcp_servers=_assemble_worker_mcp_servers())
return CodexDirectWorker()
if kind == "antigravity":
- # "antigravity" (Google subscription): reuse GeminiWorker — it already
- # drives `gemini -p ... --yolo` in the worktree — but the worker env has
- # the Gemini API key stripped (see the env builder below), so the CLI
- # falls back to the ~/.gemini OAuth login and bills the subscription.
+ # "antigravity" (Google subscription): drive the official `agy` CLI
+ # over a PTY with --dangerously-skip-permissions so it can write files
+ # in the worktree. The worker env has the Gemini API key stripped (see
+ # the env builder), so the CLI uses the ~/.gemini OAuth login and bills
+ # the subscription. GoogleCliWorker falls back to GeminiWorker when the
+ # resolver finds the Gemini CLI instead of agy (it writes to a pipe; agy
+ # emits 0 bytes over a pipe and needs the PTY). The previous code reused
+ # GeminiWorker here, which drove `gemini` with gemini flags and never
+ # invoked agy at all (the gemini consumer-OAuth was sunset 2026-06-18).
logger.info(
- "Mission worker -> GeminiWorker over the Google subscription "
- "(OAuth login, no API key) — billed against Antigravity/Gemini."
+ "Mission worker -> GoogleCliWorker over the Google subscription "
+ "(agy over PTY, OAuth login, no API key) — billed against Antigravity."
)
- return GeminiWorker()
+ return GoogleCliWorker()
if kind == "gemini":
# Reached when [brain.sub_jarvis].provider == "gemini" was selected
# (the user's "selected provider must run" mandate) OR, legacy, when
diff --git a/jarvis/missions/workers/google_cli_worker.py b/jarvis/missions/workers/google_cli_worker.py
new file mode 100644
index 0000000000..7f648aad53
--- /dev/null
+++ b/jarvis/missions/workers/google_cli_worker.py
@@ -0,0 +1,226 @@
+"""GoogleCliWorker — drive the official Antigravity ``agy`` CLI as a Phase-6 worker.
+
+Bills mission work against the user's Google subscription (OAuth, no API key).
+
+Two backends, picked by the resolver:
+- ``agy`` (the official successor): a TUI tool that emits **0 bytes over a plain
+ pipe**, so it is driven over a PTY via :func:`run_cli_over_pty`, with agy's
+ write-capable flag ``--dangerously-skip-permissions`` so it can create/edit
+ files inside the per-mission git worktree. agy understands only ``--print`` /
+ ``--model`` / ``--dangerously-skip-permissions`` — NOT the gemini-CLI flags
+ (``--prompt``/``--yolo``/``--output-format``), which is why the GeminiWorker
+ cannot drive it.
+- the Gemini CLI (resolver fallback): writes clean output to a pipe, so we
+ delegate to the proven :class:`GeminiWorker` unchanged.
+
+agy is driven through an isolated, hook/mcp-free CLI home (:mod:`jarvis.google_cli.
+isolated_home`) so it does not boot the user's per-turn PowerShell hooks + npm MCP
+servers, and with the PATH repaired for its internal ``cmd.exe``/``npm`` spawns.
+
+Isolation is unchanged: the worker runs in the caller's git worktree (``cwd``),
+and the child PID is assigned to the per-mission Job Object via ``on_spawn`` so
+the kernel reaps the tree on cancel/timeout/crash (Windows). Google ToS: only the
+official binary is driven; the OAuth token is never read into our own client.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import os
+import shutil
+import time
+import uuid
+from collections.abc import AsyncIterator
+from contextlib import suppress
+from pathlib import Path
+from typing import Any, Literal
+
+from jarvis.google_cli.isolated_home import (
+ ensure_isolated_home,
+ iso_home_root,
+ real_gemini_dir,
+ redirect_home_env,
+)
+from jarvis.google_cli.pty_runner import repair_agy_path, run_cli_over_pty
+from jarvis.google_cli.resolver import resolve_google_cli
+
+from .gemini_worker import GeminiWorker
+from .stream_consumer import ClaudeResult, ClaudeSystemInit
+
+logger = logging.getLogger(__name__)
+
+# Dropped from the child so the subscription OAuth login wins and an accidental
+# API key can never bill the wrong account / break the OAuth path.
+_DROP_ENV: tuple[str, ...] = (
+ "GEMINI_API_KEY",
+ "GOOGLE_API_KEY",
+ "GOOGLE_AISTUDIO_API_KEY",
+ "GOOGLE_APPLICATION_CREDENTIALS",
+)
+
+# 20 min hard cap — mirrors GeminiWorker's 1200 s (user mandate 2026-06-09).
+_WORKER_TIMEOUT_S: float = 1200.0
+
+
+def _build_agy_worker_argv(exe: str, prompt: str) -> list[str]:
+ """agy worker argv: one non-interactive prompt with auto-approved tools so it
+ can write files in the worktree. Newlines are collapsed to spaces — agy takes
+ the whole prompt as a single ``--print`` argument."""
+ safe_prompt = " ".join(prompt.split())
+ return [exe, "--print", safe_prompt, "--dangerously-skip-permissions"]
+
+
+def _build_agy_worker_env(base_env: dict[str, str]) -> dict[str, str]:
+ """Worker child env for agy: drop API keys (OAuth wins), repair PATH for agy's
+ internal cmd/npm spawns, and redirect HOME to the isolated hook/mcp-free home."""
+ env = {k: v for k, v in base_env.items() if k not in _DROP_ENV}
+ node = shutil.which("node") or shutil.which("node.exe")
+ env["PATH"] = repair_agy_path(
+ env.get("PATH", ""), node_dir=os.path.dirname(node) if node else None
+ )
+ iso = ensure_isolated_home(
+ real_dir=real_gemini_dir(), dest_root=iso_home_root(), model="gemini-3.5-flash"
+ )
+ if iso:
+ redirect_home_env(env, iso)
+ return env
+
+
+class GoogleCliWorker:
+ """Phase-6 worker driving the official Google CLI (agy over PTY, gemini over pipe).
+
+ ``cli`` is declared ``"claude"`` (like GeminiWorker) so the Phase-6 telemetry
+ schema needs no migration; the synthetic init event's ``model`` field carries
+ ``antigravity/agy`` so debugging stays unambiguous.
+ """
+
+ cli: Literal["claude"] = "claude"
+
+ def __init__(self) -> None:
+ self.last_pid: int | None = None
+ self.last_session_id: str | None = None
+ self._gemini_fallback = GeminiWorker()
+
+ async def spawn(
+ self,
+ prompt: str,
+ *,
+ worktree: Path,
+ env: dict[str, str],
+ job: Any,
+ worker_id: str,
+ log_dir: Path,
+ model: str = "gemini-3.5-flash",
+ allowed_tools: str = "", # parity, ignored by agy
+ permission_mode: str = "yolo",
+ max_turns: int = 20,
+ resume_session_id: str | None = None,
+ extra_args: tuple[str, ...] = (),
+ **_unused: Any,
+ ) -> AsyncIterator[Any]:
+ cli = resolve_google_cli()
+ session_id = resume_session_id or str(uuid.uuid4())
+ self.last_session_id = session_id
+
+ if cli is None:
+ yield ClaudeSystemInit(
+ session_id=session_id, model="antigravity/none", tools=[], cwd=str(worktree)
+ )
+ yield ClaudeResult(
+ subtype="error_during_execution",
+ is_error=True,
+ cost_usd=None,
+ num_turns=None,
+ session_id=session_id,
+ duration_ms=0,
+ result="No Google CLI found — install Antigravity (agy) or the Gemini CLI.",
+ )
+ return
+
+ if cli.kind != "agy":
+ # The Gemini CLI writes clean output to a pipe — reuse the proven worker.
+ logger.info(
+ "GoogleCliWorker[%s] -> GeminiWorker fallback (resolver kind=%s)",
+ worker_id, cli.kind,
+ )
+ async for ev in self._gemini_fallback.spawn(
+ prompt,
+ worktree=worktree,
+ env=env,
+ job=job,
+ worker_id=worker_id,
+ log_dir=log_dir,
+ model=model,
+ allowed_tools=allowed_tools,
+ permission_mode=permission_mode,
+ max_turns=max_turns,
+ resume_session_id=resume_session_id,
+ extra_args=extra_args,
+ **_unused,
+ ):
+ yield ev
+ self.last_pid = self._gemini_fallback.last_pid
+ self.last_session_id = self._gemini_fallback.last_session_id
+ return
+
+ # agy path: PTY + write-mode + isolated hook/mcp-free home.
+ exe = cli.argv_prefix[0]
+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors GeminiWorker)
+ argv = _build_agy_worker_argv(exe, prompt)
+ agy_env = _build_agy_worker_env(env)
+
+ yield ClaudeSystemInit(
+ session_id=session_id, model="antigravity/agy", tools=[], cwd=str(worktree)
+ )
+ logger.info(
+ "GoogleCliWorker[%s] spawn agy over PTY: cwd=%s (Google subscription, OAuth)",
+ worker_id, worktree,
+ )
+
+ loop = asyncio.get_running_loop()
+
+ def _assign(pid: int) -> None:
+ self.last_pid = pid
+ try:
+ job.assign(pid)
+ except Exception: # noqa: BLE001
+ logger.warning(
+ "GoogleCliWorker[%s]: job.assign(pid=%s) failed", worker_id, pid,
+ exc_info=True,
+ )
+
+ t0 = time.perf_counter()
+ result = await loop.run_in_executor(
+ None,
+ lambda: run_cli_over_pty(
+ tuple(argv),
+ timeout_s=_WORKER_TIMEOUT_S,
+ cwd=str(worktree),
+ env=agy_env,
+ on_spawn=_assign,
+ ),
+ )
+ wall_ms = int((time.perf_counter() - t0) * 1000)
+
+ with suppress(OSError):
+ (log_dir / "stream.jsonl").write_text(result.text, encoding="utf-8")
+ with suppress(OSError):
+ (log_dir / "stderr.log").write_text(result.raw[:20000], encoding="utf-8")
+
+ is_error = bool(result.error) or result.timed_out or result.exit_status not in (0, None)
+ text = result.text or (result.error or "")
+ if result.timed_out:
+ text = f"{text}\n[timeout after {_WORKER_TIMEOUT_S:.0f}s]".strip()
+ logger.info(
+ "GoogleCliWorker[%s] agy done: error=%s %dms text=%d chars",
+ worker_id, is_error, wall_ms, len(result.text),
+ )
+ yield ClaudeResult(
+ subtype="success" if not is_error else "error_during_execution",
+ is_error=is_error,
+ cost_usd=None,
+ num_turns=None,
+ session_id=session_id,
+ duration_ms=wall_ms,
+ result=text[:4000],
+ )
diff --git a/jarvis/plugins/brain/antigravity.py b/jarvis/plugins/brain/antigravity.py
index f7c77990ea..0954442916 100644
--- a/jarvis/plugins/brain/antigravity.py
+++ b/jarvis/plugins/brain/antigravity.py
@@ -29,13 +29,32 @@ from contextlib import suppress
from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS
from jarvis.core.protocols import BrainDelta, BrainRequest
+from jarvis.google_cli.isolated_home import (
+ ensure_isolated_home as _ensure_isolated_home,
+)
+from jarvis.google_cli.isolated_home import (
+ iso_home_root as _iso_home_root,
+)
+from jarvis.google_cli.isolated_home import (
+ real_gemini_dir as _real_gemini_dir,
+)
+from jarvis.google_cli.isolated_home import redirect_home_env
+from jarvis.google_cli.pty_runner import repair_agy_path, run_cli_over_pty
from jarvis.google_cli.resolver import GoogleCli, resolve_google_cli
+from .cli_prompt_context import (
+ extract_reply_language_directive,
+ render_cli_standing_instructions,
+)
+
log = logging.getLogger(__name__)
# Fallback only — the active model comes from [brain.providers.antigravity].model.
-# Matches the user's ~/.gemini/settings.json default; overridable, no code change.
-DEFAULT_MODEL = "gemini-3.1-pro-preview"
+# Flash is the fast default. NOTE (verified 2026-06-21, agy 1.0.10): agy ignores
+# both --model and settings.json model.name and runs its own IDE-configured
+# default, so this value only steers the gemini-CLI fallback path; for agy it is
+# informational. Kept in sync with the curated catalog (model_catalog.py).
+DEFAULT_MODEL = "gemini-3.5-flash"
# Hard cap for a single CLI brain turn. The agent CLI is slow (cold start +
# 20k-token system prompt); 120 s leaves headroom without hanging the brain
@@ -92,6 +111,9 @@ def _build_cli_prompt(req: BrainRequest) -> str:
instruction plus the last ~6 user/assistant turns for context.
"""
lines: list[str] = [_CLI_SYSTEM, ""]
+ prefs = render_cli_standing_instructions(req.system)
+ if prefs:
+ lines.extend([prefs, ""])
convo = [
m
for m in req.messages
@@ -101,6 +123,13 @@ def _build_cli_prompt(req: BrainRequest) -> str:
for m in convo:
speaker = "User" if m.role == "user" else "Assistant"
lines.append(f"{speaker}: {m.content}")
+ # The reply-language directive rides LAST (highest recency) so the CLI model
+ # answers in the turn's resolved language instead of anchoring to the German
+ # persona — without this the directive is dropped and an English request is
+ # answered in German (live bug 2026-06-21).
+ lang_directive = extract_reply_language_directive(req.system)
+ if lang_directive:
+ lines.extend(["", lang_directive])
lines.append("Assistant:")
return "\n".join(lines)
@@ -141,6 +170,16 @@ class AntigravityBrain:
def __init__(self, model: str | None = None) -> None:
self._model = model or DEFAULT_MODEL
+ def can_call_tools(self) -> bool:
+ """Runtime tool-calling capability (NOT the static ``supports_tools``).
+
+ Antigravity always drives the Google-subscription CLI (``agy`` over a PTY
+ or the Gemini CLI over a pipe) on a flattened prompt — it has no
+ chat-completions/function-calling path and drops every tool. The caller
+ (``BrainManager``) uses this to delegate tool/Computer-Use turns to a
+ tool-capable provider instead of letting the CLI silently no-op."""
+ return False
+
async def complete(self, req: BrainRequest) -> AsyncIterator[BrainDelta]:
cli = resolve_google_cli()
if cli is None:
@@ -151,13 +190,99 @@ class AntigravityBrain:
prompt = _build_cli_prompt(req)
argv = _build_argv(cli, prompt, self._model)
- workdir = tempfile.mkdtemp(prefix="jarvis-antigravity-brain-")
+ # agy is a TUI tool: over a plain pipe it emits 0 bytes (the brain then
+ # sees "no answer"). It must be driven over a real pseudo-terminal. The
+ # Gemini CLI writes clean JSON to a pipe, so it keeps the fast path.
+ if cli.kind == "agy":
+ async for delta in self._complete_via_pty(argv, prompt):
+ yield delta
+ else:
+ async for delta in self._complete_via_pipe(argv, prompt):
+ yield delta
+
+ def _build_child_env(self, *, harden_path: bool) -> dict[str, str]:
+ """Child env: drop API keys (subscription login wins), redirect HOME to an
+ isolated hook/mcp-free CLI home (the lag fix), and — for the agy/PTY case
+ on Windows — repair the PATH so agy's internal ``cmd.exe``/``npm`` spawns
+ resolve even from a degraded launch env."""
env = {k: v for k, v in os.environ.items() if k not in _DROP_ENV}
+ if harden_path and sys.platform == "win32":
+ node = shutil.which("node") or shutil.which("node.exe")
+ node_dir = os.path.dirname(node) if node else None
+ env["PATH"] = repair_agy_path(env.get("PATH", ""), node_dir=node_dir)
+ # Redirect HOME so the CLI reads our minimal settings.json (no per-turn
+ # PowerShell hook storm, no npm MCP boot) instead of the user's ~/.gemini.
+ iso = _ensure_isolated_home(
+ real_dir=_real_gemini_dir(), dest_root=_iso_home_root(), model=self._model
+ )
+ if iso:
+ redirect_home_env(env, iso)
+ return env
+
+ async def _complete_via_pty(
+ self, argv: list[str], prompt: str
+ ) -> AsyncIterator[BrainDelta]:
+ """Drive ``agy`` over a ConPTY/PTY (it has no usable pipe output)."""
+ workdir = tempfile.mkdtemp(prefix="jarvis-antigravity-brain-")
+ env = self._build_child_env(harden_path=True)
+ loop = asyncio.get_running_loop()
+ log.info(
+ "AntigravityBrain(agy/PTY): driving %s (model=%s, prompt=%d chars)",
+ argv[0], self._model, len(prompt),
+ )
+ t0 = time.monotonic()
+ fut = loop.run_in_executor(
+ None,
+ lambda: run_cli_over_pty(
+ tuple(argv), timeout_s=_CLI_TIMEOUT_S, cwd=workdir, env=env
+ ),
+ )
+ try:
+ while not fut.done():
+ done, _ = await asyncio.wait({fut}, timeout=3.0)
+ if not done:
+ # No-text progress tick keeps the caller's no-progress
+ # deadline alive through the slow agent spin-up.
+ yield BrainDelta(content="")
+ result = fut.result()
+ finally:
+ with suppress(OSError):
+ shutil.rmtree(workdir, ignore_errors=True)
+
+ elapsed = time.monotonic() - t0
+ if result.error:
+ log.warning("AntigravityBrain(agy/PTY) unavailable: %s", result.error)
+ raise RuntimeError(
+ f"Antigravity (Google login) is unavailable: {result.error}"
+ )
+ if result.timed_out:
+ log.warning("AntigravityBrain(agy/PTY): no answer within %.0fs", _CLI_TIMEOUT_S)
+ raise RuntimeError(
+ f"Antigravity (Google login) did not answer within {_CLI_TIMEOUT_S:.0f}s."
+ )
+ if not result.text:
+ log.warning(
+ "AntigravityBrain(agy/PTY): empty answer after %.1fs rc=%s",
+ elapsed, result.exit_status,
+ )
+ raise RuntimeError("Antigravity (Google login) returned no answer.")
+ log.info(
+ "AntigravityBrain(agy) turn ok: %d chars in %.1fs",
+ len(result.text), elapsed,
+ )
+ yield BrainDelta(content=result.text)
+ yield BrainDelta(finish_reason="stop")
+
+ async def _complete_via_pipe(
+ self, argv: list[str], prompt: str
+ ) -> AsyncIterator[BrainDelta]:
+ """Drive the Gemini CLI over pipes — it emits clean JSON on stdout."""
+ workdir = tempfile.mkdtemp(prefix="jarvis-antigravity-brain-")
+ env = self._build_child_env(harden_path=False)
creationflags = NO_WINDOW_CREATIONFLAGS if sys.platform == "win32" else 0
log.info(
- "AntigravityBrain: spawning %s (kind=%s, model=%s, prompt=%d chars)",
- cli.argv_prefix[0],
- cli.kind,
+ "AntigravityBrain(gemini/pipe): spawning %s (model=%s, prompt=%d chars)",
+ argv[0],
self._model,
len(prompt),
)
diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.py
index 38e1b15096..07477b8931 100644
--- a/jarvis/ui/web/provider_spec.py
+++ b/jarvis/ui/web/provider_spec.py
@@ -82,7 +82,10 @@ PROVIDERS: tuple[ProviderSpec, ...] = (
auth_mode="antigravity",
secret_keys=(),
dashboard_url="https://antigravity.google",
- login_cli=("agy", "login"),
+ # agy has NO `login` subcommand (verified 2026-06-21) — the bare binary
+ # drops into the interactive "Sign in with Google" flow. The Connect
+ # button drives POST /api/antigravity/login (start_login → bare run).
+ login_cli=("agy",),
install_hint="Install Antigravity (agy) or sign in with the Gemini CLI",
credential_path_hint="~/.gemini/oauth_creds.json",
),
diff --git a/tests/missions/workers/test_google_cli_worker.py b/tests/missions/workers/test_google_cli_worker.py
new file mode 100644
index 0000000000..b11ea0e91d
--- /dev/null
+++ b/tests/missions/workers/test_google_cli_worker.py
@@ -0,0 +1,136 @@
+"""GoogleCliWorker drives the official Antigravity ``agy`` CLI as a Phase-6 worker.
+
+agy emits 0 bytes over a plain pipe, so the worker MUST drive it over a PTY (via
+``run_cli_over_pty``) with agy's write-capable flag ``--dangerously-skip-permissions``
+— never the gemini-CLI pipe path with gemini flags. When the resolver falls back
+to the Gemini CLI (kind != "agy") it delegates to the proven GeminiWorker.
+"""
+from __future__ import annotations
+
+import pytest
+
+import jarvis.missions.workers.google_cli_worker as mod
+from jarvis.google_cli.pty_runner import PtyRunResult
+from jarvis.google_cli.resolver import GoogleCli
+from jarvis.missions.workers.google_cli_worker import (
+ GoogleCliWorker,
+ _build_agy_worker_argv,
+ _build_agy_worker_env,
+)
+
+
+class _FakeJob:
+ def __init__(self) -> None:
+ self.assigned: list[int] = []
+
+ def assign(self, pid: int) -> None:
+ self.assigned.append(pid)
+
+
+def test_agy_worker_argv_is_print_plus_skip_permissions() -> None:
+ argv = _build_agy_worker_argv("agy.exe", "Create a file\nThen stop")
+ assert argv[0] == "agy.exe"
+ assert "--print" in argv
+ assert "--dangerously-skip-permissions" in argv # auto-approve so it can write
+ # gemini-CLI flags must NOT appear — agy doesn't understand them.
+ assert "--yolo" not in argv
+ assert "--output-format" not in argv
+ assert "-o" not in argv
+ # newlines collapsed into the single --print argument.
+ assert "\n" not in argv[argv.index("--print") + 1]
+
+
+def test_agy_worker_env_drops_api_keys_and_redirects_home(monkeypatch) -> None:
+ monkeypatch.setattr(mod, "ensure_isolated_home", lambda **k: "/iso")
+ env = _build_agy_worker_env({"GEMINI_API_KEY": "x", "GOOGLE_API_KEY": "y", "PATH": "/p"})
+ assert "GEMINI_API_KEY" not in env # OAuth subscription wins
+ assert "GOOGLE_API_KEY" not in env
+ assert env["HOME"] == "/iso" # hook/mcp-free isolated home
+
+
+async def test_spawn_agy_uses_pty_and_assigns_job(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(
+ mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
+ )
+ monkeypatch.setattr(mod, "ensure_isolated_home", lambda **k: str(tmp_path / "iso"))
+ captured: dict = {}
+
+ def _fake_run(argv, *, timeout_s, cwd=None, env=None, on_spawn=None, **kw):
+ captured["argv"] = list(argv)
+ captured["cwd"] = cwd
+ captured["env"] = env
+ if on_spawn:
+ on_spawn(4321)
+ return PtyRunResult(
+ text="done writing files", raw="raw", exit_status=0, timed_out=False, error=None
+ )
+
+ monkeypatch.setattr(mod, "run_cli_over_pty", _fake_run)
+ job = _FakeJob()
+ worker = GoogleCliWorker()
+ events = [
+ e
+ async for e in worker.spawn(
+ "Build hello.py",
+ worktree=tmp_path,
+ env={"GEMINI_API_KEY": "x", "PATH": "/p"},
+ job=job,
+ worker_id="w1",
+ log_dir=tmp_path / "logs",
+ )
+ ]
+ assert "--dangerously-skip-permissions" in captured["argv"]
+ assert captured["cwd"] == str(tmp_path)
+ assert "GEMINI_API_KEY" not in captured["env"] # OAuth, not the key
+ assert job.assigned == [4321] # PID assigned to the Job Object via on_spawn
+ kinds = [type(e).__name__ for e in events]
+ assert "ClaudeSystemInit" in kinds and "ClaudeResult" in kinds
+ result = next(e for e in events if type(e).__name__ == "ClaudeResult")
+ assert result.is_error is False
+ assert "done writing files" in result.result
+
+
+async def test_spawn_agy_timeout_is_error(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(
+ mod, "resolve_google_cli", lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"])
+ )
+ monkeypatch.setattr(mod, "ensure_isolated_home", lambda **k: str(tmp_path / "iso"))
+ monkeypatch.setattr(
+ mod,
+ "run_cli_over_pty",
+ lambda *a, **k: PtyRunResult(text="", raw="", exit_status=None, timed_out=True, error=None),
+ )
+ worker = GoogleCliWorker()
+ events = [
+ e
+ async for e in worker.spawn(
+ "x", worktree=tmp_path, env={}, job=_FakeJob(), worker_id="w", log_dir=tmp_path / "l"
+ )
+ ]
+ result = next(e for e in events if type(e).__name__ == "ClaudeResult")
+ assert result.is_error is True
+
+
+async def test_spawn_gemini_kind_delegates_to_gemini_worker(monkeypatch, tmp_path) -> None:
+ monkeypatch.setattr(
+ mod, "resolve_google_cli", lambda: GoogleCli(kind="gemini", argv_prefix=["gemini"])
+ )
+ called = {"gemini": False}
+
+ async def _fake_gemini_spawn(self, prompt, **kw):
+ called["gemini"] = True
+ yield "GEMINI_EVENT"
+
+ monkeypatch.setattr(mod.GeminiWorker, "spawn", _fake_gemini_spawn)
+ worker = GoogleCliWorker()
+ events = [
+ e
+ async for e in worker.spawn(
+ "x", worktree=tmp_path, env={}, job=_FakeJob(), worker_id="w", log_dir=tmp_path / "l"
+ )
+ ]
+ assert called["gemini"] is True # Gemini CLI uses the pipe path, not the PTY
+ assert "GEMINI_EVENT" in events
diff --git a/tests/unit/brain/test_antigravity_routing.py b/tests/unit/brain/test_antigravity_routing.py
new file mode 100644
index 0000000000..8599c978a4
--- /dev/null
+++ b/tests/unit/brain/test_antigravity_routing.py
@@ -0,0 +1,56 @@
+"""Antigravity must be a first-class active brain in the fallback chain.
+
+Two regressions guarded here (both the same class as the 2026-06-09 "Gemini
+answered while Codex was the active brain" bug):
+
+1. TIER_DEFAULTS_BY_PROVIDER had no "antigravity" row, so `_fast_model` /
+ `_deep_model` returned None when no model was pinned and `_build_fallback_chain`
+ SILENTLY DROPPED antigravity — the chosen brain never answered.
+2. The deep_brain-hijack guard exempted only "codex". With antigravity active and
+ a foreign deep_brain (e.g. gemini), deep/code intents led with that other
+ provider — antigravity (itself a frontier subscription brain) never answered a
+ hard question.
+"""
+from __future__ import annotations
+
+import pytest
+
+from jarvis.brain.manager import TIER_DEFAULTS_BY_PROVIDER, BrainManager
+from jarvis.core.bus import EventBus
+from jarvis.core.config import load_config
+
+
+def test_antigravity_has_tier_defaults_for_router_and_deep() -> None:
+ assert TIER_DEFAULTS_BY_PROVIDER["router"].get("antigravity")
+ assert TIER_DEFAULTS_BY_PROVIDER["deep"].get("antigravity")
+
+
+def test_antigravity_fast_and_deep_model_not_none_without_pin() -> None:
+ cfg = load_config()
+ cfg.brain.primary = "antigravity"
+ cfg.brain.router.provider = "antigravity"
+ cfg.brain.router.fallback_provider = "antigravity"
+ if "antigravity" in cfg.brain.providers:
+ cfg.brain.providers["antigravity"].model = "" # unpinned
+ mgr = BrainManager.from_tier_config(
+ "router", cfg, EventBus(), provider_override="antigravity"
+ )
+ # Tier default kicks in → antigravity is not dropped from the chain.
+ assert mgr._fast_model("antigravity")
+ assert mgr._deep_model("antigravity")
+
+
+def test_antigravity_active_leads_deep_not_foreign_deep_brain(monkeypatch) -> None:
+ cfg = load_config()
+ cfg.brain.primary = "antigravity"
+ cfg.brain.router.provider = "antigravity"
+ cfg.brain.router.fallback_provider = "gemini" # deliberate cross-provider split
+ mgr = BrainManager.from_tier_config(
+ "router", cfg, EventBus(), provider_override="antigravity"
+ )
+ # Force both eligible so step-0 (deep_brain) is genuinely in play.
+ monkeypatch.setattr(mgr._registry, "available", lambda: ["antigravity", "gemini"])
+ assert mgr._config.brain.deep_brain == "gemini" # explicit split preserved
+ deep_chain = mgr._build_fallback_chain("deep")
+ # antigravity (a frontier subscription brain) leads deep/code, NOT gemini.
+ assert deep_chain[0][0] == "antigravity"
diff --git a/tests/unit/brain/test_provider_test_service.py b/tests/unit/brain/test_provider_test_service.py
index 59c27fbd31..e8313925d2 100644
--- a/tests/unit/brain/test_provider_test_service.py
+++ b/tests/unit/brain/test_provider_test_service.py
@@ -102,6 +102,40 @@ def test_codex_not_connected_is_not_configured() -> None:
assert res.status == "not_configured"
+def test_antigravity_connected_is_ok_without_billed_call() -> None:
+ # antigravity is OAuth-only: a connected Google login IS a working brain.
+ # The real agy/gemini turn (~8s, bills the subscription) must NOT run on Test.
+ called = False
+
+ async def probe(_p, _m): # pragma: no cover - must NOT run
+ nonlocal called
+ called = True
+ return HealthResult(provider="antigravity", model="m", ok=True)
+
+ res = _run(
+ run_provider_test(
+ get_spec("antigravity"), _cfg(), present=True, brain_probe=probe,
+ antigravity_status=lambda: SimpleNamespace(
+ installed=True, connected=True, message="Connected via Google subscription"
+ ),
+ )
+ )
+ assert res.status == "ok"
+ assert called is False # no slow/billed agy turn on a button click
+
+
+def test_antigravity_not_connected_is_not_configured() -> None:
+ res = _run(
+ run_provider_test(
+ get_spec("antigravity"), _cfg(), present=True,
+ antigravity_status=lambda: SimpleNamespace(
+ installed=True, connected=False, message="Not connected"
+ ),
+ )
+ )
+ assert res.status == "not_configured"
+
+
def test_tts_synthesis_credits_error_is_no_credits() -> None:
class _Boom:
async def synthesize(self, _text, voice=None):
diff --git a/tests/unit/google_cli/test_auth_service.py b/tests/unit/google_cli/test_auth_service.py
index 00cf31ea3b..71047e6930 100644
--- a/tests/unit/google_cli/test_auth_service.py
+++ b/tests/unit/google_cli/test_auth_service.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import json
+import jarvis.google_cli.auth_service as auth_mod
from jarvis.google_cli.auth_service import (
GoogleCliAuthService,
_derive_google_auth,
@@ -91,3 +92,37 @@ def test_status_installed_but_logged_out(tmp_path, monkeypatch):
st = svc.status()
assert st.installed and not st.connected
assert st.cli_kind == "agy"
+
+
+def test_start_login_uses_bare_agy_not_login_subcommand(monkeypatch):
+ # agy has NO `login` subcommand (verified 2026-06-21: `agy login` hangs
+ # forever). The login is an interactive bare run, so start_login must NOT
+ # append "login" — that would spawn a hung process behind the Connect button.
+ svc = GoogleCliAuthService()
+ svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]) # type: ignore[method-assign]
+ captured: dict = {}
+
+ def _fake_popen(argv, **kw):
+ captured["argv"] = list(argv)
+ return object()
+
+ monkeypatch.setattr(auth_mod.subprocess, "Popen", _fake_popen)
+ svc.start_login()
+ assert captured["argv"] == ["agy.exe"] # bare binary, no "login"
+
+
+def test_logout_removes_creds_without_calling_agy_logout(tmp_path, monkeypatch):
+ # agy has NO `logout` subcommand either; removing the on-disk OAuth creds IS
+ # the disconnect. Trying `agy logout` would hang/time out for nothing.
+ gem = _seed_gemini_home(tmp_path)
+ monkeypatch.setenv("GEMINI_HOME", str(gem))
+ svc = GoogleCliAuthService()
+ svc._resolve = lambda: GoogleCli(kind="agy", argv_prefix=["agy.exe"]) # type: ignore[method-assign]
+
+ def _no_run(*a, **k):
+ raise AssertionError("agy logout must not be invoked (no such subcommand)")
+
+ monkeypatch.setattr(auth_mod.subprocess, "run", _no_run)
+ ok, err = svc.logout_blocking()
+ assert ok and err is None
+ assert not (gem / "oauth_creds.json").is_file() # creds actually removed
diff --git a/tests/unit/google_cli/test_pty_runner.py b/tests/unit/google_cli/test_pty_runner.py
new file mode 100644
index 0000000000..7c7ac6bb0f
--- /dev/null
+++ b/tests/unit/google_cli/test_pty_runner.py
@@ -0,0 +1,286 @@
+"""Tests for the ConPTY/PTY runner that drives the Antigravity ``agy`` CLI.
+
+``agy`` is a TUI tool: over a plain pipe it emits 0 bytes; over a real
+pseudo-terminal it renders the answer wrapped in ANSI control sequences and
+window-title OSC frames. The runner spawns it over a PTY (cross-platform seam),
+reads until exit/timeout, strips the terminal noise, and extracts the answer.
+
+No real CLI, PTY, or network is touched — the backend is faked.
+"""
+from __future__ import annotations
+
+import pytest
+
+import os
+
+from jarvis.google_cli.pty_runner import (
+ PtyRunResult,
+ extract_cli_answer,
+ repair_agy_path,
+ run_cli_over_pty,
+ strip_terminal_noise,
+)
+
+# A faithful slice of a real ``agy --print`` capture over ConPTY (PONG probe,
+# 2026-06-21): screen-setup CSI codes + three npm/cmd window-title OSC frames +
+# the answer "PONG" + trailing cmd.exe title.
+_REAL_AGY_CAPTURE = (
+ "\r\x1b[?9001h\x1b[?1004h\x1b[?25l\x1b[2J\x1b[m\x1b[H"
+ "\x1b]0;npm\x07\x1b[?25h\x1b]0;npm exec @iflow-mcp/ollama-mcp\x07"
+ "\x1b]0;npm exec firecrawl-mcp\x07PONG\r\r\n"
+ "\x1b]0;C:\\windows\\system32\\cmd.exe \x07\r\n"
+)
+
+
+# ---- strip_terminal_noise -------------------------------------------------
+
+
+def test_strip_removes_csi_sequences():
+ assert strip_terminal_noise("\x1b[2J\x1b[H\x1b[mPONG") == "PONG"
+
+
+def test_strip_removes_osc_window_titles():
+ assert strip_terminal_noise("\x1b]0;npm exec firecrawl-mcp\x07PONG") == "PONG"
+
+
+def test_strip_removes_osc_terminated_by_st():
+ # OSC may end with ST (ESC \) instead of BEL.
+ assert strip_terminal_noise("\x1b]0;title\x1b\\PONG") == "PONG"
+
+
+def test_strip_real_capture_yields_clean_answer():
+ cleaned = strip_terminal_noise(_REAL_AGY_CAPTURE)
+ assert "\x1b" not in cleaned
+ assert "\x07" not in cleaned
+ assert "npm exec" not in cleaned # window titles gone
+ assert "PONG" in cleaned
+
+
+def test_strip_preserves_plain_text_and_newlines():
+ assert strip_terminal_noise("line one\nline two\n") == "line one\nline two\n"
+
+
+# ---- extract_cli_answer ---------------------------------------------------
+
+
+def test_extract_answer_from_real_capture():
+ assert extract_cli_answer(_REAL_AGY_CAPTURE) == "PONG"
+
+
+def test_extract_multiline_answer_preserved():
+ raw = "\x1b[2J\x1b[Hfirst line\r\nsecond line\r\n"
+ assert extract_cli_answer(raw) == "first line\nsecond line"
+
+
+def test_extract_empty_when_only_noise():
+ assert extract_cli_answer("\x1b[2J\x1b[H\x1b]0;npm\x07\r\n") == ""
+
+
+# agy renders a Braille progress spinner (U+2800-U+28FF) by repeatedly
+# rewriting the SAME line with a leading CR ("\r⠋ Fetching...\r⠙ Fetching...").
+# Over a PTY capture those frames arrive as bare-CR overwrites; the old
+# CR->LF rewrite turned each frame into its own line, so 18 "⠋ Fetching
+# available models..." lines leaked into the cleaned answer (real 2026-06-21
+# `agy models` capture). The answer is only the text after the last CR.
+_REAL_AGY_SPINNER_CAPTURE = (
+ "\x1b[?25l"
+ "\r⠋ Fetching available models..."
+ "\r⠙ Fetching available models..."
+ "\x1b]0;npm\x07"
+ "\r⠹ Fetching available models..."
+ "\r⠸ Fetching available models..."
+ "\rGemini 3.5 Flash (Medium)\r\n"
+ "Gemini 3.1 Pro (Low)\r\n"
+ "GPT-OSS 120B (Medium)\r\n"
+)
+
+
+def test_extract_drops_spinner_overwrite_frames():
+ out = extract_cli_answer(_REAL_AGY_SPINNER_CAPTURE)
+ assert "Fetching available models" not in out # transient status gone
+ assert "⠋" not in out and "⠹" not in out # no Braille glyphs
+ assert out == "Gemini 3.5 Flash (Medium)\nGemini 3.1 Pro (Low)\nGPT-OSS 120B (Medium)"
+
+
+def test_extract_spinner_then_answer():
+ # A short turn: a couple of "Thinking" spinner frames, then the answer.
+ raw = "\r⠋ Thinking...\r⠙ Thinking...\rpong\r\n"
+ assert extract_cli_answer(raw) == "pong"
+
+
+def test_extract_strips_trailing_lone_spinner_glyph():
+ # Belt-and-suspenders: a stray spinner glyph on the final visible line.
+ assert extract_cli_answer("⠋ answer text\r\n") == "answer text"
+
+
+# ---- repair_agy_path ------------------------------------------------------
+# agy spawns cmd.exe + npm internally (MCP servers); in a degraded environment
+# (PATH stripped of System32 / Node) that fails with "chcp nicht erkannt". The
+# child PATH must carry the standard Windows system dirs.
+
+
+def test_repair_path_adds_system32_when_missing():
+ out = repair_agy_path(
+ r"C:\Some\Other",
+ is_windows=True,
+ system_root=r"C:\Windows",
+ )
+ parts = [p.lower() for p in out.split(os.pathsep)]
+ assert r"c:\windows\system32" in parts
+ assert r"c:\windows\system32\wbem" in parts
+ assert r"c:\some\other" in parts.__str__() or r"c:\some\other" in parts
+
+
+def test_repair_path_idempotent_when_present():
+ existing = os.pathsep.join([r"C:\Windows\System32", r"C:\Windows\System32\Wbem", r"C:\Windows"])
+ out = repair_agy_path(existing, is_windows=True, system_root=r"C:\Windows")
+ # No duplicate System32 entries.
+ assert out.lower().count(r"c:\windows\system32".lower()) == existing.lower().count(
+ r"c:\windows\system32".lower()
+ )
+
+
+def test_repair_path_includes_node_dir_when_given():
+ out = repair_agy_path(
+ "", is_windows=True, system_root=r"C:\Windows", node_dir=r"C:\Program Files\nodejs"
+ )
+ assert r"c:\program files\nodejs" in [p.lower() for p in out.split(os.pathsep)]
+
+
+def test_repair_path_noop_on_posix():
+ assert repair_agy_path("/usr/bin:/bin", is_windows=False) == "/usr/bin:/bin"
+
+
+# ---- run_cli_over_pty -----------------------------------------------------
+
+
+class _FakeHandle:
+ """A fake PtyHandle: yields queued chunks, then EOF; tracks terminate."""
+
+ def __init__(self, chunks: list[str], *, exit_status: int = 0) -> None:
+ self._chunks = list(chunks)
+ self._exit = exit_status
+ self.terminated = False
+ self._alive = True
+
+ @property
+ def pid(self) -> int:
+ return 4242
+
+ @property
+ def exitstatus(self) -> int | None:
+ return None if self._alive else self._exit
+
+ def read(self, size: int) -> str:
+ if self._chunks:
+ return self._chunks.pop(0)
+ self._alive = False
+ raise EOFError
+
+ def isalive(self) -> bool:
+ return self._alive
+
+ def terminate(self, force: bool) -> None:
+ self.terminated = True
+ self._alive = False
+
+ def write(self, data: str) -> None: # parity, unused
+ pass
+
+ def setwinsize(self, rows: int, cols: int) -> None:
+ pass
+
+
+class _FakeBackend:
+ """Captures the spawn kwargs and returns a pre-seeded fake handle."""
+
+ def __init__(self, handle: _FakeHandle) -> None:
+ self._handle = handle
+ self.spawn_kwargs: dict | None = None
+
+ def spawn(self, argv, cwd, cols, rows, env=None): # noqa: ANN001
+ self.spawn_kwargs = {
+ "argv": argv,
+ "cwd": cwd,
+ "cols": cols,
+ "rows": rows,
+ "env": env,
+ }
+ return self._handle
+
+
+def test_run_reads_until_eof_and_extracts_answer():
+ handle = _FakeHandle(["\x1b[2J\x1b[H", "PONG\r\n"])
+ backend = _FakeBackend(handle)
+ result = run_cli_over_pty(
+ ("agy", "--print", "x"), timeout_s=5.0, backend=backend,
+ )
+ assert isinstance(result, PtyRunResult)
+ assert result.text == "PONG"
+ assert result.timed_out is False
+ assert result.error is None
+ assert handle.terminated is False # exited cleanly, no kill needed
+
+
+def test_run_passes_env_and_cwd_to_backend():
+ backend = _FakeBackend(_FakeHandle(["ok\r\n"]))
+ run_cli_over_pty(
+ ("agy", "--print", "x"),
+ timeout_s=5.0,
+ cwd="/tmp/work",
+ env={"PATH": "/safe"},
+ backend=backend,
+ )
+ assert backend.spawn_kwargs["cwd"] == "/tmp/work"
+ assert backend.spawn_kwargs["env"] == {"PATH": "/safe"}
+
+
+def test_run_times_out_and_terminates():
+ # Never EOFs, never goes dead on its own -> the deadline must fire.
+ class _NeverEnds(_FakeHandle):
+ def read(self, size: int) -> str:
+ return "" # no data, still alive
+
+ def isalive(self) -> bool:
+ return True
+
+ handle = _NeverEnds([])
+ backend = _FakeBackend(handle)
+ # A fake clock so the test doesn't actually wait.
+ ticks = iter([0.0, 0.1, 0.2, 99.0, 99.0, 99.0])
+ result = run_cli_over_pty(
+ ("agy", "--print", "x"),
+ timeout_s=1.0,
+ backend=backend,
+ _now=lambda: next(ticks),
+ _sleep=lambda _s: None,
+ )
+ assert result.timed_out is True
+ assert handle.terminated is True
+
+
+def test_run_invokes_on_spawn_with_pid():
+ """The worker uses on_spawn to assign the child PID to its Job Object."""
+ handle = _FakeHandle(["ok\r\n"])
+ backend = _FakeBackend(handle)
+ seen: list[int] = []
+ run_cli_over_pty(
+ ("agy", "--print", "x"),
+ timeout_s=5.0,
+ backend=backend,
+ on_spawn=seen.append,
+ )
+ assert seen == [4242] # _FakeHandle.pid
+
+
+def test_run_no_pty_backend_returns_error_result():
+ class _NullBackend:
+ def spawn(self, *a, **k): # noqa: ANN002, ANN003
+ raise RuntimeError("No pseudo-terminal backend available on this host")
+
+ result = run_cli_over_pty(
+ ("agy", "--print", "x"), timeout_s=5.0, backend=_NullBackend(),
+ )
+ assert result.text == ""
+ assert result.error is not None
+ assert "pseudo-terminal" in result.error
diff --git a/tests/unit/plugins/brain/test_antigravity_brain.py b/tests/unit/plugins/brain/test_antigravity_brain.py
index 10db45c789..0eb94a02c0 100644
--- a/tests/unit/plugins/brain/test_antigravity_brain.py
+++ b/tests/unit/plugins/brain/test_antigravity_brain.py
@@ -5,19 +5,84 @@ The subprocess is faked; no real CLI or network is touched.
from __future__ import annotations
import asyncio
+import json
+import os
+from pathlib import Path
import pytest
from jarvis.core.protocols import BrainMessage, BrainRequest
-from jarvis.plugins.brain import antigravity as agmod
-from jarvis.plugins.brain.antigravity import AntigravityBrain, _parse_cli_answer
from jarvis.google_cli.resolver import GoogleCli
+from jarvis.plugins.brain import antigravity as agmod
+from jarvis.plugins.brain.antigravity import (
+ AntigravityBrain,
+ _build_cli_prompt,
+ _parse_cli_answer,
+)
+
+
[email protected](autouse=True)
+def _isolate_agy_home(monkeypatch, tmp_path_factory):
+ """Never let a test write the isolated agy home into the real data/ dir."""
+ root = str(tmp_path_factory.mktemp("agy-iso-home"))
+ monkeypatch.setattr(agmod, "_iso_home_root", lambda: root)
def _req(text: str = "Hello") -> BrainRequest:
return BrainRequest(messages=(BrainMessage(role="user", content=text),))
+def _system_with_standing_instructions() -> str:
+ return (
+ "STATIC PERSONA BLOCK\n\n"
+ "USER PREFERENCES & STANDING INSTRUCTIONS (from Jarvis.md):\n"
+ "The following are personal preferences written by the user.\n\n"
+ "Always start every sentence with schef.\n\n"
+ "END USER PREFERENCES & STANDING INSTRUCTIONS\n\n"
+ "REGISTRIERTE WERKZEUGE (vollstaendige Liste):\n"
+ "- search_web\n"
+ )
+
+
+def test_cli_prompt_includes_standing_instructions_without_heavy_router_prompt():
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="Was ist das wertvollste Unternehmen?"),),
+ system=_system_with_standing_instructions(),
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "Always start every sentence with schef." in prompt
+ assert "Jarvis.md" in prompt
+ assert "REGISTRIERTE WERKZEUGE" not in prompt
+ assert "STATIC PERSONA BLOCK" not in prompt
+
+
+def test_cli_prompt_carries_reply_language_directive():
+ """The authoritative reply-language directive (appended LAST to the system
+ prompt by BrainManager) must reach the flattened CLI prompt.
+
+ Live bug 2026-06-21: an English request was answered in German because the
+ agy/Gemini brain kept only the standing-instructions block and dropped the
+ trailing "REPLY LANGUAGE — MANDATORY" line — so the model never learned the
+ turn's resolved language and anchored to the German persona.
+ """
+ directive = (
+ "REPLY LANGUAGE — MANDATORY: Always reply in English, no matter which "
+ "language the user writes or speaks in."
+ )
+ req = BrainRequest(
+ messages=(BrainMessage(role="user", content="Build me an HTML file please."),),
+ system=_system_with_standing_instructions() + "\n\n" + directive,
+ )
+
+ prompt = _build_cli_prompt(req)
+
+ assert "Always reply in English" in prompt
+ # No regression: the standing-instructions block still flows through.
+ assert "Always start every sentence with schef." in prompt
+
+
def test_parse_json_response():
assert _parse_cli_answer('{"response": "OK"}') == "OK"
@@ -175,3 +240,179 @@ def test_build_argv_gemini_keeps_skip_trust():
assert "--print" in argv or "-p" in argv
assert "--skip-trust" in argv
assert "plan" in argv
+
+
+# ---- agy over ConPTY -------------------------------------------------------
+# agy is a TUI tool: a plain pipe yields 0 bytes (the brain then sees no answer).
+# It must be driven over a pseudo-terminal via pty_runner.run_cli_over_pty.
+
+
+def _agy_cli() -> GoogleCli:
+ return GoogleCli(kind="agy", argv_prefix=["agy.exe"])
+
+
+def _fake_pty_result(text: str = "", *, error: str | None = None, timed_out: bool = False):
+ from jarvis.google_cli.pty_runner import PtyRunResult
+
+ return PtyRunResult(
+ text=text, raw=text, exit_status=0, timed_out=timed_out, error=error
+ )
+
+
+async def test_complete_agy_drives_pty_runner(monkeypatch):
+ """kind='agy' must go through the PTY runner, not create_subprocess_exec."""
+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)
+ captured: dict[str, object] = {}
+
+ def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):
+ captured["argv"] = list(argv)
+ return _fake_pty_result("Servus von agy!")
+
+ monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)
+ # Guard: the pipe path must NOT be taken for agy.
+ async def _boom(*a, **k):
+ raise AssertionError("agy must not use create_subprocess_exec")
+
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", _boom)
+
+ brain = AntigravityBrain()
+ chunks = [d async for d in brain.complete(_req())]
+ texts = "".join(d.content for d in chunks if d.content)
+ assert "Servus von agy!" in texts
+ assert any(d.finish_reason == "stop" for d in chunks)
+ assert captured["argv"][0] == "agy.exe"
+ assert "--print" in captured["argv"]
+
+
+async def test_complete_agy_drops_key_and_hardens_path(monkeypatch):
+ """The child env drops GEMINI_API_KEY and (on Windows) carries System32."""
+ monkeypatch.setenv("GEMINI_API_KEY", "should-not-leak")
+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)
+ captured: dict[str, object] = {}
+
+ def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):
+ captured["env"] = env
+ return _fake_pty_result("ok")
+
+ monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)
+ brain = AntigravityBrain()
+ async for _ in brain.complete(_req()):
+ pass
+ env = captured["env"]
+ assert env is not None
+ assert "GEMINI_API_KEY" not in env
+ import sys as _sys
+
+ if _sys.platform == "win32":
+ assert "System32" in env.get("PATH", "")
+
+
+# ---- isolated, hook/mcp-free CLI home (lag fix) ----------------------------
+# agy reads the user's ~/.gemini/settings.json, which on this machine carries
+# dozens of duplicated BridgeSpace PowerShell SessionStart/BeforeAgent hooks +
+# mcpServers; agy boots ALL of them per --print turn (13s). Pointing HOME at an
+# isolated home with a hook/mcp-free settings.json (and the copied OAuth creds)
+# drops a turn to ~8s and kills the npm MCP boot (verified live 2026-06-21).
+
+
+def _fake_real_gemini(tmp_path) -> str:
+ real = tmp_path / "real" / ".gemini"
+ real.mkdir(parents=True)
+ (real / "oauth_creds.json").write_text('{"access_token":"a","refresh_token":"r"}')
+ (real / "google_accounts.json").write_text('"[email protected]"')
+ (real / "settings.json").write_text(
+ json.dumps(
+ {
+ "hooks": {"SessionStart": [{"command": "powershell ...", "type": "command"}] * 5},
+ "mcpServers": {"github": {"command": "npx"}},
+ "security": {"auth": {"selectedType": "oauth-personal"}},
+ "model": {"name": "gemini-3.1-pro-preview"},
+ }
+ )
+ )
+ return str(real)
+
+
+def test_isolated_home_strips_hooks_and_mcp(tmp_path):
+ real = _fake_real_gemini(tmp_path)
+ dest = str(tmp_path / "iso")
+ home = agmod._ensure_isolated_home(
+ real_dir=real,
+ dest_root=dest,
+ model="Gemini 3.5 Flash (Medium)",
+ )
+ g = os.path.join(home, ".gemini")
+ settings = json.load(open(os.path.join(g, "settings.json"), encoding="utf-8"))
+ assert "hooks" not in settings # no per-turn PowerShell hook storm
+ assert "mcpServers" not in settings # no per-turn npm MCP boot
+ assert settings["model"]["name"] == "Gemini 3.5 Flash (Medium)"
+ assert settings["security"]["auth"]["selectedType"] == "oauth-personal"
+ # OAuth login carried over so agy stays signed in under the redirected HOME
+ assert os.path.isfile(os.path.join(g, "oauth_creds.json"))
+ assert os.path.isfile(os.path.join(g, "google_accounts.json"))
+
+
+def test_isolated_home_drops_copied_creds_after_logout(tmp_path):
+ # First sync copies the login in; then the real creds vanish (logout removes
+ # ~/.gemini/oauth_creds.json). The next sync must drop the stale iso copy, or
+ # agy would stay signed in under the redirected HOME despite the logout.
+ real = _fake_real_gemini(tmp_path)
+ dest = str(tmp_path / "iso")
+ agmod._ensure_isolated_home(real_dir=real, dest_root=dest, model="gemini-3.5-flash")
+ iso_creds = os.path.join(dest, ".gemini", "oauth_creds.json")
+ assert os.path.isfile(iso_creds) # carried in on first sync
+
+ os.remove(os.path.join(real, "oauth_creds.json")) # simulate logout
+ agmod._ensure_isolated_home(real_dir=real, dest_root=dest, model="gemini-3.5-flash")
+ assert not os.path.isfile(iso_creds) # stale copy dropped -> agy logged out too
+
+
+async def test_complete_agy_redirects_home_to_isolated(monkeypatch, tmp_path):
+ real = _fake_real_gemini(tmp_path)
+ iso_root = str(tmp_path / "iso")
+ monkeypatch.setattr(agmod, "_real_gemini_dir", lambda: real)
+ monkeypatch.setattr(agmod, "_iso_home_root", lambda: iso_root)
+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)
+ captured: dict[str, object] = {}
+
+ def _fake_run(argv, *, timeout_s, cwd=None, env=None, **kw):
+ captured["env"] = env
+ return _fake_pty_result("ok")
+
+ monkeypatch.setattr(agmod, "run_cli_over_pty", _fake_run)
+ brain = AntigravityBrain()
+ async for _ in brain.complete(_req()):
+ pass
+ env = captured["env"]
+ assert env.get("USERPROFILE") == iso_root # HOME redirected off the real one
+ assert env.get("HOME") == iso_root
+ settings_path = Path(iso_root) / ".gemini" / "settings.json"
+ settings = json.loads(settings_path.read_text(encoding="utf-8"))
+ assert "hooks" not in settings and "mcpServers" not in settings
+
+
+async def test_complete_agy_empty_answer_raises(monkeypatch):
+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)
+ monkeypatch.setattr(agmod, "run_cli_over_pty", lambda *a, **k: _fake_pty_result(""))
+ brain = AntigravityBrain()
+ with pytest.raises(RuntimeError):
+ async for _ in brain.complete(_req()):
+ pass
+
+
+async def test_complete_agy_pty_unavailable_raises(monkeypatch):
+ monkeypatch.setattr(agmod, "resolve_google_cli", _agy_cli)
+ monkeypatch.setattr(
+ agmod,
+ "run_cli_over_pty",
+ lambda *a, **k: _fake_pty_result("", error="No pseudo-terminal backend available"),
+ )
+ brain = AntigravityBrain()
+ with pytest.raises(RuntimeError):
+ async for _ in brain.complete(_req()):
+ pass
diff --git a/tests/unit/ui/test_provider_spec_antigravity.py b/tests/unit/ui/test_provider_spec_antigravity.py
index f4147c5039..62c6e44899 100644
--- a/tests/unit/ui/test_provider_spec_antigravity.py
+++ b/tests/unit/ui/test_provider_spec_antigravity.py
@@ -18,6 +18,8 @@ def test_antigravity_provider_spec():
assert spec.auth_mode == "antigravity"
assert spec.secret_keys == () # OAuth-only, no API-key slot
assert spec.login_cli is not None
+ # agy has no `login` subcommand (it hangs) — the login is a bare interactive run.
+ assert "login" not in spec.login_cli
def test_antigravity_excluded_from_live_catalog():