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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(agents): add Grok Build as a SuperGrok subscription subagent
Harald557715630007
diff --git a/docs/product/personalize-and-connect/providers-and-api-keys.md b/docs/product/personalize-and-connect/providers-and-api-keys.mdindex 20f5512071..f2bc14e8f1 100644--- a/docs/product/personalize-and-connect/providers-and-api-keys.md+++ b/docs/product/personalize-and-connect/providers-and-api-keys.md@@ -47,7 +47,7 @@ choices rather than as a permanent list of every available service.| **Voice input** | Speech recognition in Pipeline mode and dictation | Cloud and on-device cards are available. || **Dictation** | Optional punctuation and wording cleanup after recognition | It improves text; it does not transcribe audio. || **Realtime** | One live model that listens and speaks | Model and voice are selected together; Computer Use remains separate. |-| **Agents** | Longer background work | API-key providers and supported coding-CLI subscriptions appear separately. |+| **Agents** | Longer background work | API-key providers and supported coding-CLI subscriptions (Codex, Claude, Antigravity, Grok Build) appear separately. || **Advanced** | Optional team proxy, telephony, and classic Wiki model | These do not have to be configured for normal chat. |The **Pipeline / Realtime** switch changes the voice-provider tabs, not thediff --git a/jarvis/agent_cli_probe.py b/jarvis/agent_cli_probe.pyindex d41753aa63..9e96eaec46 100644--- a/jarvis/agent_cli_probe.py+++ b/jarvis/agent_cli_probe.py@@ -33,7 +33,7 @@ from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS_VERSION_TIMEOUT_S = 8.0-AgentCliName = Literal["claude", "codex", "antigravity"]+AgentCliName = Literal["claude", "codex", "antigravity", "grok-build"]@dataclass(frozen=True)@@ -214,10 +214,42 @@ def test_antigravity() -> AgentCliTestResult:)+def test_grok_build() -> AgentCliTestResult:+ from jarvis.grok_build_auth import GrokBuildAuthService, grok_build_install_hint++ t0 = time.monotonic()+ ensure_cli_paths()+ from jarvis import grok_build_auth++ grok_build_auth.clear_version_cache()+ status = GrokBuildAuthService().status()+ if not status.installed:+ return _not_installed("grok-build", grok_build_install_hint(), t0)+ ok = status.version is not None+ message = status.message if ok else (+ f"Found at {status.binary_path}, but 'grok --version' did not answer "+ "— the install looks broken."+ )+ return AgentCliTestResult(+ cli="grok-build",+ ok=ok,+ installed=True,+ binary_path=status.binary_path,+ version=status.version,+ connected=status.connected,+ auth_mode=status.mode,+ account=status.user_email,+ message=message,+ searched_path=_searched_path_dirs(),+ duration_ms=int((time.monotonic() - t0) * 1000),+ )++__all__ = ["AgentCliName","AgentCliTestResult","test_antigravity","test_claude","test_codex",+ "test_grok_build",]diff --git a/jarvis/brain/app_control.py b/jarvis/brain/app_control.pyindex c7f4d575c8..e25bfee92f 100644--- a/jarvis/brain/app_control.py+++ b/jarvis/brain/app_control.py@@ -291,6 +291,16 @@ def is_credential_present(spec: ProviderSpec, binary_path: str | None = None) ->return GoogleCliAuthService().status().connectedexcept Exception: # noqa: BLE001 — Google CLI absent is just "not present"return False+ if spec.auth_mode == "grok_build":+ try:+ from jarvis.grok_build_auth import (+ GrokBuildAuthService,+ grok_build_provider_ready,+ )++ return grok_build_provider_ready(GrokBuildAuthService().status())+ except Exception: # noqa: BLE001 — Grok Build CLI absent is just "not present"+ return Falsereturn False@@ -672,6 +682,8 @@ async def _switch_subagent(ANTIGRAVITY_SUBAGENT_SLUGS,CODEX_SUBAGENT_CANONICAL,CODEX_SUBAGENT_SLUGS,+ GROK_BUILD_SUBAGENT_CANONICAL,+ GROK_BUILD_SUBAGENT_SLUGS,JARVIS_TO_WORKER_SLUG,canonical_worker_provider,)@@ -775,6 +787,46 @@ async def _switch_subagent(old=old,)+ if canon in GROK_BUILD_SUBAGENT_SLUGS:+ grok_build_status = None+ try:+ from jarvis.grok_build_auth import (+ GrokBuildAuthService,+ grok_build_provider_ready,+ )++ grok_build_status = await asyncio.to_thread(+ GrokBuildAuthService().status+ )+ except Exception as exc: # noqa: BLE001 — absent CLI is a normal capability miss+ log.debug("Grok Build CLI readiness probe failed: %s", exc)+ if grok_build_status is None or not grok_build_status.installed:+ return {+ "ok": False,+ "error_kind": "subagent_unavailable",+ "error": (+ "Grok Build is not installed. Install the grok CLI from "+ f"x.ai/build, or select the xAI Grok {brand} provider for "+ "key-only execution."+ ),+ }+ if not grok_build_provider_ready(grok_build_status):+ return {+ "ok": False,+ "error_kind": "missing_credential",+ "error": (+ "Grok Build is not connected — sign in with SuperGrok or "+ f"X Premium+ (install grok and run grok login), then "+ f"switch the {brand}."+ ),+ }+ return _complete_agent_switch(+ GROK_BUILD_SUBAGENT_CANONICAL,+ cfg=cfg,+ persist=persist,+ old=old,+ )+if canon not in JARVIS_TO_WORKER_SLUG:# List EVERY worker-capable provider, not just the API/harness ones —# Codex and Antigravity route through their own workers, so omitting them@@ -782,7 +834,11 @@ async def _switch_subagent(# openai/openrouter" reply (forensic 2026-06-27).known = ", ".join(sorted(set(JARVIS_TO_WORKER_SLUG)- | {CODEX_SUBAGENT_CANONICAL, ANTIGRAVITY_SUBAGENT_CANONICAL}+ | {+ CODEX_SUBAGENT_CANONICAL,+ ANTIGRAVITY_SUBAGENT_CANONICAL,+ GROK_BUILD_SUBAGENT_CANONICAL,+ }))return {"ok": False,diff --git a/jarvis/brain/manager.py b/jarvis/brain/manager.pyindex a94198951d..fbb6ba1f02 100644--- a/jarvis/brain/manager.py+++ b/jarvis/brain/manager.py@@ -227,7 +227,7 @@ PROVIDER_ALIASES = {}SUBAGENT_ONLY_BRAIN_PROVIDERS: frozenset[str] = frozenset(- {"antigravity", "codex", "openai-codex"}+ {"antigravity", "codex", "openai-codex", "grok-build", "grok-cli", "grokbuild"})_MAIN_BRAIN_FALLBACK_PROVIDER_ORDER: tuple[str, ...] = (@@ -259,6 +259,7 @@ _PROVIDER_DISPLAY_NAMES: dict[str, str] = {"nvidia": "NVIDIA NIM","gemini": "Google Gemini","antigravity": "Google Antigravity (Gemini)",+ "grok-build": "Grok Build (xAI subscription)",}@@ -2101,12 +2102,16 @@ _SUBAGENT_VOICE_TO_CANONICAL: dict[str, str] = {"grok": "grok","nvidia": "nvidia", "nim": "nvidia", "nemotron": "nvidia","antigravity": "antigravity",+ "grok-build": "grok-build",+ "grokbuild": "grok-build",+ "grok-cli": "grok-build",}_SUBAGENT_DISPLAY: dict[str, str] = {"openai": "OpenAI", "openai-codex": "Codex", "claude-api": "Claude","gemini": "Gemini", "openrouter": "OpenRouter", "grok": "xAI Grok","nvidia": "NVIDIA NIM","antigravity": "Antigravity",+ "grok-build": "Grok Build",}_SUBAGENT_SWITCH_CONFIRM: dict[str, str] = {"de": "Erledigt — dein Sub-Agent läuft ab der nächsten Mission auf {p}.",diff --git a/jarvis/brain/model_catalog.py b/jarvis/brain/model_catalog.pyindex c279e88012..010f5e2bd6 100644--- a/jarvis/brain/model_catalog.py+++ b/jarvis/brain/model_catalog.py@@ -242,6 +242,7 @@ CURATED_MODELS: dict[str, list[ModelInfo]] = {# in every region. The authenticated live catalog replaces this fallback."grok": _curated([+ ("grok-4.6", "Grok 4.6"),("grok-4.3", "Grok 4.3"),("grok-4.5", "Grok 4.5"),]@@ -732,6 +733,23 @@ def _build_provider_catalog() -> dict[str, CatalogSpec]:),live=False,)+ # Grok Build — SuperGrok / X Premium+ CLI worker. No public /v1/models over+ # the subscription login, so curated only. Grok 4.6 is the current Grok+ # Build default (official docs, 2026-08).+ cat["grok-build"] = CatalogSpec(+ "brain",+ "model",+ tuple(+ _curated(+ [+ ("grok-4.6", "Grok 4.6"),+ ("grok-4.3", "Grok 4.3"),+ ("grok-4.5", "Grok 4.5"),+ ]+ )+ ),+ live=False,+ )# Claude CLI — the Anthropic-subscription writer (``claude -p``); no# /v1/models over a plan login, so curated only. The aliases are what the CLI# itself accepts, not dated API ids: they keep pointing at the plan's currentdiff --git a/jarvis/brain/voice_command_gate.py b/jarvis/brain/voice_command_gate.pyindex cca9af7762..02175b03ed 100644--- a/jarvis/brain/voice_command_gate.py+++ b/jarvis/brain/voice_command_gate.py@@ -198,8 +198,9 @@ _SUBAGENT_QUALIFIER = re.compile()# Longer variants first so "openai-codex" wins over "openai"._SUBAGENT_PROVIDER_WORDS = (- "openai-codex", "openrouter", "antigravity", "chatgpt", "anthropic",- "claude", "gemini", "openai", "grok", "codex", "gpt",+ "openai-codex", "openrouter", "antigravity", "grok-build", "grokbuild",+ "grok-cli", "chatgpt", "anthropic", "claude", "gemini", "openai", "grok",+ "codex", "gpt",)_SUBAGENT_SWITCH_VERB = re.compile(r"\b(?:wechsel[n]?|wechsle|umstell\w*|umschalt\w*|stell\w*|set|switch|change|nimm|mach)\b",diff --git a/jarvis/cli_ctl/commands/brain.py b/jarvis/cli_ctl/commands/brain.pyindex 641f6dcabd..f5b129902f 100644--- a/jarvis/cli_ctl/commands/brain.py+++ b/jarvis/cli_ctl/commands/brain.py@@ -17,8 +17,8 @@ app = typer.Typer()_PROVIDER_HELP = (- "Provider id: claude-api | openrouter | openai | gemini | codex | "- "antigravity (the server validates the value)."+ "Provider id: claude-api | openrouter | openai | gemini | grok | "+ "codex | antigravity | grok-build (the server validates the value).")diff --git a/jarvis/core/path_augment.py b/jarvis/core/path_augment.pyindex a97d4f4ddb..c11285080a 100644--- a/jarvis/core/path_augment.py+++ b/jarvis/core/path_augment.py@@ -42,6 +42,8 @@ def _posix_candidates() -> list[str]:"/opt/local/bin",# Native installers (Claude Code, pipx, uv) and the XDG user bin dir.str(home / ".local" / "bin"),+ # Official Grok Build installer (install.sh) may drop ``grok`` here.+ str(home / ".grok" / "bin"),# Claude Code's npm-local migration target (`claude install`).str(home / ".claude" / "local"),# A user-configured npm prefix (`npm config set prefix ~/.npm-global`).@@ -108,6 +110,11 @@ def _windows_candidates() -> list[str]:# the module docstring).dirs.append(str(home / ".local" / "bin"))dirs.append(str(home / ".claude" / "local"))+ # Official Grok Build installer (install.ps1) drops ``grok`` next to+ # other native CLIs; some builds also use a dedicated bin under GROK_HOME.+ dirs.append(str(home / ".grok" / "bin"))+ if local:+ dirs.append(os.path.join(local, "grok", "bin"))return dirsdiff --git a/jarvis/grok_build_auth.py b/jarvis/grok_build_auth.pynew file mode 100644index 0000000000..3a12f6e986--- /dev/null+++ b/jarvis/grok_build_auth.py@@ -0,0 +1,397 @@+"""Grok Build CLI auth service — status, login, logout.++Personal Jarvis drives xAI's ``grok`` coding agent (Grok Build) as a+subscription subagent: SuperGrok / X Premium+ OAuth via ``grok login``, stored+in ``~/.grok/auth.json`` (or ``$GROK_HOME``). This is the xAI sibling of+:mod:`jarvis.codex_auth` and :mod:`jarvis.google_cli.auth_service`.++The existing ``grok`` brain/subagent slug is the **xAI API-key** path. Grok+Build is a separate subscription CLI and must never be confused with it.++Cross-platform (CLOUD.md Rule #1): pure stdlib, ``pathlib``-only, degrades to a+clean "not installed" snapshot when the binary is absent — never raises on a+probe. Subprocess hygiene: version probes use ``CREATE_NO_WINDOW``; the+user-initiated login uses a visible terminal so the browser OAuth prompt is+reachable under ``pythonw.exe``.++No secret value is ever logged: only the binary name and connection booleans.+"""+from __future__ import annotations++import base64+import binascii+import json+import logging+import os+import shutil+import subprocess+import sys+import threading+from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jarvis.core.interactive_terminal import (+ InteractiveTerminalLaunch,+ InteractiveTerminalUnavailable,+ launch_interactive_terminal,+)+from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS++log = logging.getLogger(__name__)++_BINARY_CANDIDATES: tuple[str, ...] = ("grok", "grok.exe", "grok.cmd")+_VERSION_CACHE: dict[str, str | None] = {}+_VERSION_TIMEOUT_S = 8.0+_LOGOUT_TIMEOUT_S = 20.0+_ISO_HOME_LOCK = threading.Lock()+_ISO_HOME_MARKER = ".jarvis_src_mtime"++# Login material mirrored into the isolated worker home. Presence-only — the+# token VALUE is never read into business logic (same rule as Google ToS copy).+_LOGIN_FILES: tuple[str, ...] = ("auth.json",)+++def grok_build_install_command(platform: str | None = None) -> str:+ """Official Grok Build installer for the current OS."""+ target = platform or sys.platform+ if target == "win32":+ return "irm https://x.ai/cli/install.ps1 | iex"+ return "curl -fsSL https://x.ai/cli/install.sh | bash"+++def grok_build_install_hint(platform: str | None = None) -> str:+ """Display-safe native installer."""+ return f"Install Grok Build with: {grok_build_install_command(platform)}"+++def grok_home() -> Path:+ """User-level Grok Build home (``$GROK_HOME`` or ``~/.grok``)."""+ override = os.environ.get("GROK_HOME")+ return Path(override) if override else (Path.home() / ".grok")+++def iso_home_root() -> Path:+ """Isolated worker home — auth only, no user hooks/plugins/sessions."""+ from jarvis.core.config import DATA_DIR++ return Path(DATA_DIR) / "grok-build-worker-home"+++def clear_version_cache() -> None:+ """Drop cached ``grok --version`` results (tests / reinstall)."""+ _VERSION_CACHE.clear()+++def _read_json(path: Path) -> dict[str, Any] | None:+ try:+ raw = path.read_text(encoding="utf-8")+ except (OSError, ValueError):+ return None+ try:+ data = json.loads(raw)+ except (ValueError, json.JSONDecodeError):+ return None+ return data if isinstance(data, dict) else None+++def _derive_auth(auth: dict[str, Any] | None) -> tuple[bool, str]:+ """Return ``(connected, mode)`` from a parsed ``auth.json`` dict.++ Tolerant by design: Grok Build's on-disk shape may evolve; any recognised+ subscription token or account identity is ``subscription``, a stored API+ key field is ``api_key``, and anything else degrades to disconnected.+ """+ if not isinstance(auth, dict):+ return False, "unknown"+ tokens = auth.get("tokens")+ if isinstance(tokens, dict) and any(+ isinstance(tokens.get(k), str) and tokens.get(k).strip()+ for k in ("access_token", "id_token", "refresh_token", "session_token")+ ):+ return True, "subscription"+ for key in (+ "access_token",+ "refresh_token",+ "id_token",+ "session_token",+ "token",+ ):+ value = auth.get(key)+ if isinstance(value, str) and value.strip():+ return True, "subscription"+ user = auth.get("user") if isinstance(auth.get("user"), dict) else None+ account = auth.get("account") if isinstance(auth.get("account"), dict) else None+ identity = user or account+ if isinstance(identity, dict) and any(+ isinstance(identity.get(k), str) and identity.get(k).strip()+ for k in ("email", "user_id", "id", "username")+ ):+ return True, "subscription"+ for key in ("XAI_API_KEY", "xai_api_key", "api_key"):+ value = auth.get(key)+ if isinstance(value, str) and value.strip():+ return True, "api_key"+ return False, "unknown"+++def _email_from_id_token(token: str | None) -> str | None:+ if not isinstance(token, str) or token.count(".") < 2:+ return None+ payload_b64 = token.split(".")[1]+ payload_b64 += "=" * (-len(payload_b64) % 4)+ try:+ payload = json.loads(base64.urlsafe_b64decode(payload_b64))+ except (binascii.Error, ValueError, json.JSONDecodeError):+ return None+ email = payload.get("email") if isinstance(payload, dict) else None+ return email if isinstance(email, str) and email else None+++def _email_from_auth(auth: dict[str, Any] | None) -> str | None:+ if not isinstance(auth, dict):+ return None+ for key in ("email", "user_email"):+ value = auth.get(key)+ if isinstance(value, str) and value.strip():+ return value.strip()+ for nest_key in ("user", "account", "profile"):+ nested = auth.get(nest_key)+ if isinstance(nested, dict):+ email = nested.get("email") or nested.get("emailAddress")+ if isinstance(email, str) and email.strip():+ return email.strip()+ tokens = auth.get("tokens")+ if isinstance(tokens, dict):+ email = _email_from_id_token(tokens.get("id_token"))+ if email:+ return email+ raw_token = auth.get("id_token")+ token = raw_token if isinstance(raw_token, str) else None+ return _email_from_id_token(token)+++def grok_build_login_in(home: Path) -> tuple[bool, str, str | None]:+ """``(connected, mode, email)`` for the login kept in ONE Grok home.++ Never raises; an absent or unparseable ``auth.json`` is disconnected.+ """+ auth = _read_json(home / "auth.json")+ connected, mode = _derive_auth(auth)+ email = _email_from_auth(auth) if connected else None+ return connected, mode, email+++def _latest_login_mtime(home: Path) -> float | None:+ path = home / "auth.json"+ try:+ if path.is_file() and path.stat().st_size > 0:+ return path.stat().st_mtime+ except OSError:+ return None+ return None+++def prepare_worker_home(+ *, src_home: Path | None = None, dest_root: Path | None = None+) -> Path | None:+ """Copy subscription auth into an isolated, hook-free worker home.++ Returns the isolated home path, or ``None`` when there is no login to copy.+ User hooks, plugins and interactive sessions stay in the real ``~/.grok``.+ """+ src = src_home if src_home is not None else grok_home()+ dest = dest_root if dest_root is not None else iso_home_root()+ mtime = _latest_login_mtime(src)+ if mtime is None:+ return None+ with _ISO_HOME_LOCK:+ dest.mkdir(parents=True, exist_ok=True)+ marker = dest / _ISO_HOME_MARKER+ try:+ previous = float(marker.read_text(encoding="utf-8").strip())+ except (OSError, ValueError):+ previous = None+ if previous != mtime:+ for name in _LOGIN_FILES:+ src_path = src / name+ dest_path = dest / name+ try:+ if src_path.is_file() and src_path.stat().st_size > 0:+ shutil.copy2(src_path, dest_path)+ except OSError as exc:+ log.debug("Grok Build auth mirror failed for %s: %s", name, exc)+ (dest / "config.toml").write_text(+ "[cli]\nauto_update = false\n",+ encoding="utf-8",+ )+ marker.write_text(str(mtime), encoding="utf-8")+ return dest+++@dataclass(frozen=True)+class GrokBuildAuthStatus:+ """Snapshot of the Grok Build CLI login for the UI + provider routes."""++ installed: bool = False+ connected: bool = False+ mode: str = "unknown" # "subscription" | "api_key" | "unknown"+ message: str = ""+ version: str | None = None+ user_email: str | None = None+ binary_path: str = "grok"+ error: str | None = None++ def to_dict(self) -> dict[str, Any]:+ return {+ "installed": self.installed,+ "connected": self.connected,+ "mode": self.mode,+ "message": self.message,+ "version": self.version,+ "user_email": self.user_email,+ "binary_path": self.binary_path,+ "error": self.error,+ }+++def grok_build_provider_ready(status: GrokBuildAuthStatus) -> bool:+ """Whether the Grok Build CLI provider can be selected honestly.++ Subscription-only on this card: the xAI API key lives on the separate+ Grok brain/subagent card. A missing binary must never paint Ready.+ """+ return bool(+ status.installed and status.connected and status.mode == "subscription"+ )+++class GrokBuildAuthService:+ """Status / login / logout for the official Grok Build ``grok`` CLI."""++ def __init__(+ self, binary_path: str | None = None, *, grok_home_dir: Path | None = None+ ) -> None:+ self._binary_path = (binary_path or "").strip()+ self._home = Path(grok_home_dir) if grok_home_dir is not None else None++ def _home_dir(self) -> Path:+ return self._home if self._home is not None else grok_home()++ def _resolve_binary(self) -> str | None:+ try:+ from jarvis.core.path_augment import ensure_cli_paths++ ensure_cli_paths()+ except Exception as exc: # noqa: BLE001 — probe failure must not break status+ log.debug("CLI PATH augmentation failed during Grok Build discovery: %s", exc)+ if self._binary_path:+ path = Path(self._binary_path)+ if path.is_file():+ return str(path)+ found = shutil.which(self._binary_path)+ if found:+ return found+ for name in _BINARY_CANDIDATES:+ found = shutil.which(name)+ if found:+ return found+ return None++ def _probe_version(self, binary: str) -> str | None:+ cached = _VERSION_CACHE.get(binary)+ if binary in _VERSION_CACHE:+ return cached+ version: str | None+ try:+ proc = subprocess.run(+ [binary, "--version"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ text=True,+ timeout=_VERSION_TIMEOUT_S,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError):+ version = None+ else:+ out = (proc.stdout or proc.stderr or "").strip()+ version = out.splitlines()[0].strip() if out else None+ _VERSION_CACHE[binary] = version+ return version++ def status(self) -> GrokBuildAuthStatus:+ binary = self._resolve_binary()+ if binary is None:+ return GrokBuildAuthStatus(+ message=f"Grok Build CLI not found. {grok_build_install_hint()}",+ error="no grok build binary",+ )+ version = self._probe_version(binary)+ connected, mode, email = grok_build_login_in(self._home_dir())+ if connected and mode == "subscription":+ message = (+ f"Connected as {email}" if email else "Connected via SuperGrok / X Premium+"+ )+ elif connected and mode == "api_key":+ message = "API key present in Grok Build auth (use the xAI Grok card for API billing)"+ else:+ message = "Grok Build login not connected — sign in with SuperGrok or X Premium+"+ return GrokBuildAuthStatus(+ installed=True,+ connected=connected,+ mode=mode,+ message=message,+ version=version,+ user_email=email,+ binary_path=binary,+ )++ def start_login(self) -> InteractiveTerminalLaunch:+ """Spawn ``grok login`` in a visible terminal. Raises if the CLI is absent."""+ binary = self._resolve_binary()+ if binary is None:+ raise FileNotFoundError(+ f"Grok Build CLI not found. {grok_build_install_hint()}"+ )+ argv = [binary, "login"]+ log.info("Starting Grok Build login (interactive grok login)")+ try:+ return launch_interactive_terminal(argv, title="Grok Build sign-in")+ except InteractiveTerminalUnavailable as exc:+ raise InteractiveTerminalUnavailable(+ f"{exc} Open a terminal and run: grok login"+ ) from exc++ def logout_blocking(self) -> tuple[bool, str | None]:+ """Disconnect via ``grok logout``, falling back to deleting ``auth.json``.++ Returns ``(ok, error)``.+ """+ binary = self._resolve_binary()+ if binary is not None:+ try:+ proc = subprocess.run(+ [binary, "logout"],+ capture_output=True,+ encoding="utf-8",+ errors="replace",+ text=True,+ timeout=_LOGOUT_TIMEOUT_S,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ log.debug("grok logout spawn failed, falling back to file unlink: %s", exc)+ else:+ if proc.returncode == 0:+ return True, None+ log.debug(+ "grok logout exited %s; falling back to auth.json unlink",+ proc.returncode,+ )+ try:+ (self._home_dir() / "auth.json").unlink(missing_ok=True)+ return True, None+ except OSError as exc:+ return False, str(exc)diff --git a/jarvis/missions/init.py b/jarvis/missions/init.pyindex 18fe9e2c80..73aa5bcf4c 100644--- a/jarvis/missions/init.py+++ b/jarvis/missions/init.py@@ -49,6 +49,7 @@ from .voice.readback import MissionReadbackfrom .worker_runtime.provider_map import (ANTIGRAVITY_SUBAGENT_SLUGS,CODEX_SUBAGENT_SLUGS,+ GROK_BUILD_SUBAGENT_SLUGS,)from .workers.api_agent_worker import ApiAgentWorkerfrom .workers.capabilities import (@@ -60,6 +61,7 @@ from .workers.claude_direct_worker import ClaudeDirectWorkerfrom .workers.codex_direct_worker import CodexDirectWorkerfrom .workers.gemini_worker import GeminiWorkerfrom .workers.google_cli_worker import GoogleCliWorker+from .workers.grok_build_direct_worker import GrokBuildDirectWorkerlogger = logging.getLogger(__name__)@@ -372,7 +374,7 @@ def _select_subagent_worker_kind(sub_jarvis_provider: str | None, step_model: st"""Pure routing decision for the Heavy-Task subagent worker.Returns one of ``"claude_direct"`` | ``"codex_direct"`` | ``"antigravity"``- | ``"subjarvis"`` | ``"gemini"``.+ | ``"grok_build"`` | ``"subjarvis"`` | ``"gemini"``.Defense-in-depth (2026-05-29, user mandate: heavy tasks run on theconfigured provider — claude-api -> Claude Max OAuth — and Gemini must@@ -398,6 +400,8 @@ def _select_subagent_worker_kind(sub_jarvis_provider: str | None, step_model: st# stripped from the worker env (the OAuth login then bills the subscription).if sub_jarvis_provider in ANTIGRAVITY_SUBAGENT_SLUGS:return "antigravity"+ if sub_jarvis_provider in GROK_BUILD_SUBAGENT_SLUGS:+ return "grok_build"# openai / openrouter / grok / nvidia run on their own provider via the in-process# ApiAgentWorker (OpenAI-compatible chat API + tool-use loop writing files# into the worktree). They used to fall through to "subjarvis" ->@@ -1243,6 +1247,12 @@ async def bootstrap_missions("(agy over PTY, OAuth login, no API key) — billed against Antigravity.")return GoogleCliWorker(capability_inventory=capability_inventory)+ if kind == "grok_build":+ logger.info(+ "Mission worker -> GrokBuildDirectWorker over the SuperGrok "+ "subscription (grok -p, OAuth login, no API key)."+ )+ return GrokBuildDirectWorker(capability_inventory=capability_inventory)if kind == "api_agent":# openai / openrouter / grok / nvidia: run on the selected# provider via the in-process ApiAgentWorker — seediff --git a/jarvis/missions/worker_runtime/provider_map.py b/jarvis/missions/worker_runtime/provider_map.pyindex eb58514f36..56eac200dd 100644--- a/jarvis/missions/worker_runtime/provider_map.py+++ b/jarvis/missions/worker_runtime/provider_map.py@@ -38,6 +38,8 @@ __all__ = ["CODEX_SUBAGENT_CANONICAL","ANTIGRAVITY_SUBAGENT_SLUGS","ANTIGRAVITY_SUBAGENT_CANONICAL",+ "GROK_BUILD_SUBAGENT_SLUGS",+ "GROK_BUILD_SUBAGENT_CANONICAL",]@@ -67,6 +69,17 @@ CODEX_SUBAGENT_CANONICAL: Final[str] = "openai-codex"ANTIGRAVITY_SUBAGENT_SLUGS: Final[frozenset[str]] = frozenset({"antigravity"})ANTIGRAVITY_SUBAGENT_CANONICAL: Final[str] = "antigravity"+# Subagent slugs that route to the DIRECT Grok Build CLI worker+# (GrokBuildDirectWorker) over the SuperGrok / X Premium+ subscription —+# NOT through MAPPINGS and NOT the xAI API-key slug ``grok``. Mirror of+# CODEX_SUBAGENT_SLUGS so the acceptance set is a SINGLE SOURCE OF TRUTH+# shared by /api/jarvis-agent/switch, the brain-tool path, and the worker+# selector (init._select_subagent_worker_kind).+GROK_BUILD_SUBAGENT_SLUGS: Final[frozenset[str]] = frozenset(+ {"grok-build", "grok-cli", "grokbuild"}+)+GROK_BUILD_SUBAGENT_CANONICAL: Final[str] = "grok-build"+@dataclass(frozen=True, slots=True)class ProviderMapping:diff --git a/jarvis/missions/workers/grok_build_direct_worker.py b/jarvis/missions/workers/grok_build_direct_worker.pynew file mode 100644index 0000000000..8a1ed4fcba--- /dev/null+++ b/jarvis/missions/workers/grok_build_direct_worker.py@@ -0,0 +1,475 @@+"""GrokBuildDirectWorker — drive the official Grok Build ``grok`` CLI.++Bills mission work against the user's SuperGrok / X Premium+ subscription+(OAuth via ``~/.grok/auth.json``). Sibling of :class:`CodexDirectWorker` and+:class:`GoogleCliWorker`.++Headless invocation (official docs):++ grok --no-auto-update --no-alt-screen --always-approve \\+ --output-format streaming-json --cwd <worktree> [-m <model>] -p <prompt>++The worker:++* isolates ``GROK_HOME`` to an auth-only copy so user hooks/plugins from the+ interactive TUI cannot run inside a mission;+* drops ``XAI_API_KEY`` / ``GROK_API_KEY`` so the subscription login wins;+* translates streaming-json NDJSON into the WorkerProtocol's Claude-shaped+ events so the Critic loop stays CLI-agnostic.+"""+from __future__ import annotations++import asyncio+import json+import logging+import shutil+import time+import uuid+from collections.abc import AsyncIterator+from contextlib import suppress+from pathlib import Path+from typing import Any, ClassVar, Literal++from jarvis.grok_build_auth import grok_home, prepare_worker_home++from .capabilities import WorkerCapabilityInventory+from .process_utils import create_worker_subprocess+from .stream_consumer import ClaudeAssistantMessage, ClaudeResult, ClaudeSystemInit++logger = logging.getLogger(__name__)++_DEFAULT_TIMEOUT_S: float = 1200.0+_DEFAULT_FIRST_OUTPUT_TIMEOUT_S: float = 120.0+_STREAM_READLINE_LIMIT: int = 8 * 1024 * 1024+_HARDCAP_GRACE_S: float = 30.0+_DEFAULT_GROK_BUILD_MODEL: str = "grok-4.6"++_DROP_ENV: tuple[str, ...] = ("XAI_API_KEY", "GROK_API_KEY")++_AUTH_FAILURE_MARKERS: tuple[str, ...] = (+ "not logged in",+ "please log in",+ "please login",+ "run grok login",+ "unauthorized",+ "401",+ "authentication failed",+ "auth error",+ "token expired",+ "expired token",+ "invalid token",+)++_USAGE_LIMIT_MARKERS: tuple[str, ...] = (+ "usage limit",+ "rate limit",+ "rate_limit",+ "too many requests",+ "429",+ "quota",+ "try again later",+ "try again at",+)++_FOREIGN_MODEL_PREFIXES: tuple[str, ...] = (+ "claude",+ "gpt-",+ "o1",+ "o3",+ "o4",+ "gemini",+ "sonnet",+ "opus",+ "haiku",+ "fable",+)+++def _resolve_grok_binary() -> str | None:+ try:+ from jarvis.core.path_augment import ensure_cli_paths++ ensure_cli_paths()+ except Exception as exc: # noqa: BLE001 — PATH augmentation is best-effort+ logger.debug("CLI PATH augmentation failed during grok discovery: %s", exc)+ for name in ("grok", "grok.exe", "grok.cmd"):+ path = shutil.which(name)+ if path:+ return path+ return None+++def _normalize_model_for_grok_build(model: str) -> str:+ """Keep a Grok-family model; drop foreign slugs so the CLI default wins."""+ raw = (model or "").strip()+ if not raw:+ return ""+ low = raw.lower()+ if any(low.startswith(prefix) for prefix in _FOREIGN_MODEL_PREFIXES):+ return ""+ if low.startswith("x-ai/"):+ return raw.split("/", 1)[1]+ return raw+++def _build_grok_build_cmd(+ *,+ binary: str,+ prompt: str,+ worktree: Path,+ model: str = "",+ extra_args: tuple[str, ...] = (),+) -> list[str]:+ """Headless Grok Build argv. Prompt is one ``-p`` argument (official flag)."""+ safe_prompt = " ".join(prompt.split())+ cmd: list[str] = [+ binary,+ "--no-auto-update",+ "--no-alt-screen",+ "--always-approve",+ "--output-format",+ "streaming-json",+ "--cwd",+ str(worktree),+ ]+ effective = _normalize_model_for_grok_build(model)+ if effective:+ cmd.extend(["-m", effective])+ cmd.extend(["-p", safe_prompt])+ cmd.extend(extra_args)+ return cmd+++def _build_grok_build_env(base_env: dict[str, str]) -> dict[str, str]:+ """Drop API keys so the SuperGrok login wins; isolate GROK_HOME."""+ env = {k: v for k, v in base_env.items() if k not in _DROP_ENV}+ isolated = prepare_worker_home()+ if isolated is not None:+ env["GROK_HOME"] = str(isolated)+ else:+ env["GROK_HOME"] = str(grok_home())+ return env+++def _coerce_error_text(obj: dict[str, Any]) -> str:+ for key in ("message", "error", "detail", "text"):+ val = obj.get(key)+ if isinstance(val, str) and val.strip():+ return val.strip()+ if isinstance(val, dict):+ for inner in ("message", "error", "text", "detail"):+ iv = val.get(inner)+ if isinstance(iv, str) and iv.strip():+ return iv.strip()+ return str(obj.get("type") or "grok-build error")+++def _is_auth_failure(text: str) -> bool:+ low = (text or "").lower()+ return any(marker in low for marker in _AUTH_FAILURE_MARKERS)+++def _is_usage_limited(text: str) -> bool:+ low = (text or "").lower()+ return any(marker in low for marker in _USAGE_LIMIT_MARKERS)+++def _text_from_event(obj: dict[str, Any]) -> str | None:+ """Best-effort assistant text from a Grok Build streaming-json event."""+ for key in ("text", "delta", "content", "message"):+ val = obj.get(key)+ if isinstance(val, str) and val.strip():+ return val+ if isinstance(val, dict):+ for inner in ("text", "delta", "content"):+ iv = val.get(inner)+ if isinstance(iv, str) and iv.strip():+ return iv+ update = obj.get("update")+ if not isinstance(update, dict):+ params = obj.get("params")+ if isinstance(params, dict):+ update = params.get("update")+ if isinstance(update, dict):+ content = update.get("content")+ if isinstance(content, dict):+ text = content.get("text")+ if isinstance(text, str) and text.strip():+ return text+ if isinstance(content, str) and content.strip():+ return content+ return None+++def _event_looks_like_tool(obj: dict[str, Any]) -> str | None:+ """Return a tool name when the event is a successful file/shell action."""+ kind = str(obj.get("type") or obj.get("event") or "").lower()+ update = obj.get("update")+ session_update = ""+ if isinstance(update, dict):+ session_update = str(update.get("sessionUpdate") or update.get("type") or "").lower()+ kind = kind or session_update+ if any(token in kind for token in ("file", "write", "edit", "patch")):+ return "Write"+ if any(token in kind for token in ("command", "shell", "bash", "tool")):+ return "Bash"+ return None+++class GrokBuildDirectWorker:+ """Heavy worker that calls ``grok -p`` over the SuperGrok subscription."""++ cli: ClassVar[Literal["claude", "codex", "python", "browser"]] = "codex"++ def __init__(+ self,+ *,+ capability_inventory: WorkerCapabilityInventory | None = None,+ ) -> None:+ self.last_pid: int | None = None+ self.last_session_id: str | None = None+ self.capability_inventory = capability_inventory or WorkerCapabilityInventory.build()++ async def spawn(+ self,+ prompt: str,+ *,+ worktree: Path,+ env: dict[str, str],+ job: Any,+ worker_id: str,+ log_dir: Path,+ model: str = "",+ allowed_tools: str = "",+ permission_mode: str = "",+ max_turns: int = 20,+ resume_session_id: str | None = None,+ extra_args: tuple[str, ...] = (),+ timeout_s: float = _DEFAULT_TIMEOUT_S,+ first_output_timeout_s: float = _DEFAULT_FIRST_OUTPUT_TIMEOUT_S,+ mission_id: str = "",+ allow_backend_fallback: bool = True,+ _broker_binding: Any | None = None,+ **_unused: Any,+ ) -> AsyncIterator[Any]:+ del allowed_tools, permission_mode, max_turns, allow_backend_fallback+ del mission_id, _broker_binding+ log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240+ stdout_log = log_dir / "stream.jsonl"+ stderr_log = log_dir / "stderr.log"+ with suppress(OSError):+ stdout_log.write_bytes(b"")++ session_id = resume_session_id or str(uuid.uuid4())+ self.last_session_id = session_id+ effective_model = _normalize_model_for_grok_build(model) or _DEFAULT_GROK_BUILD_MODEL++ binary = _resolve_grok_binary()+ yield ClaudeSystemInit(+ session_id=session_id,+ model=f"grok-build/{effective_model}",+ tools=[],+ cwd=str(worktree),+ external_capabilities=self.capability_inventory.report_for("grok-build"),+ )+ if binary is None:+ yield ClaudeResult(+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ duration_ms=0,+ result="GrokBuildDirectWorker: grok binary not found",+ )+ return++ cmd = _build_grok_build_cmd(+ binary=binary,+ prompt=prompt,+ worktree=worktree,+ model=effective_model,+ extra_args=extra_args,+ )+ env_for_grok = _build_grok_build_env(env)+ logger.info(+ "GrokBuildDirectWorker[%s] spawn: cwd=%s model=%s argv=%s",+ worker_id,+ worktree,+ effective_model,+ [part if part != prompt else "<prompt>" for part in cmd],+ )++ t0 = time.perf_counter()+ try:+ proc = await create_worker_subprocess(+ cmd,+ cwd=str(worktree),+ env=env_for_grok,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ limit=_STREAM_READLINE_LIMIT,+ )+ except FileNotFoundError as exc:+ yield ClaudeResult(+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ duration_ms=int((time.perf_counter() - t0) * 1000),+ result=f"GrokBuildDirectWorker: grok binary not found: {exc}",+ )+ return++ self.last_pid = proc.pid+ try:+ job.assign(proc.pid)+ except Exception: # noqa: BLE001+ logger.warning(+ "GrokBuildDirectWorker[%s]: job.assign(pid=%d) failed",+ worker_id,+ proc.pid,+ exc_info=True,+ )++ timed_out = False+ timeout_message = ""+ text_acc: list[str] = []+ any_tool_use = False+ terminal_kind = "success"+ terminal_message: str | None = None+ got_first_line = False+ deadline = time.monotonic() + timeout_s + _HARDCAP_GRACE_S+ assert proc.stdout is not None # noqa: S101 — PIPE always created+ assert proc.stderr is not None # noqa: S101 — PIPE always created+ stderr_task = asyncio.create_task(proc.stderr.read())++ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ timed_out = True+ timeout_message = (+ f"GrokBuildDirectWorker: subprocess wall-clock timeout "+ f"({timeout_s + _HARDCAP_GRACE_S:.0f}s) exceeded while streaming"+ )+ break+ read_cap = remaining if got_first_line else min(first_output_timeout_s, remaining)+ try:+ raw = await asyncio.wait_for(proc.stdout.readline(), timeout=read_cap)+ except TimeoutError:+ if got_first_line:+ continue+ timed_out = True+ timeout_message = (+ f"GrokBuildDirectWorker: subprocess produced no output within "+ f"{first_output_timeout_s:.0f}s startup timeout; killed for retry"+ )+ break+ except ValueError:+ terminal_kind = "error"+ terminal_message = (+ "GrokBuildDirectWorker: a stdout line exceeded the "+ f"{_STREAM_READLINE_LIMIT // (1024 * 1024)} MiB stream limit"+ )+ logger.error("%s", terminal_message)+ break+ if not raw:+ break+ got_first_line = True+ try:+ with stdout_log.open("ab") as stream_fh:+ stream_fh.write(raw)+ except OSError as exc:+ logger.warning("GrokBuildDirectWorker: stream.jsonl append failed: %s", exc)+ line = raw.decode("utf-8", errors="replace").strip()+ if not line:+ continue+ try:+ obj = json.loads(line)+ except json.JSONDecodeError:+ continue+ if not isinstance(obj, dict):+ continue+ event_type = str(obj.get("type") or obj.get("event") or "").lower()+ if event_type in {"error", "turn.failed", "failed"}:+ terminal_kind = "error"+ terminal_message = _coerce_error_text(obj)+ continue+ if event_type in {"result", "turn.completed", "completed", "done"}:+ text = _text_from_event(obj)+ if text:+ text_acc.append(text)+ continue+ tool_name = _event_looks_like_tool(obj)+ if tool_name:+ any_tool_use = True+ yield ClaudeAssistantMessage(+ message={+ "role": "assistant",+ "content": [{"type": "tool_use", "name": tool_name, "input": {}}],+ },+ session_id=session_id,+ )+ continue+ text = _text_from_event(obj)+ if text:+ text_acc.append(text)+ yield ClaudeAssistantMessage(+ message={+ "role": "assistant",+ "content": [{"type": "text", "text": text}],+ },+ session_id=session_id,+ )++ stderr_bytes = b""+ with suppress(Exception):+ stderr_bytes = await asyncio.wait_for(stderr_task, timeout=2.0)+ if timed_out:+ with suppress(ProcessLookupError, OSError):+ proc.kill()+ with suppress(Exception):+ await asyncio.wait_for(proc.wait(), timeout=5.0)+ else:+ with suppress(Exception):+ await asyncio.wait_for(proc.wait(), timeout=10.0)++ if stderr_bytes:+ with suppress(OSError):+ stderr_log.write_bytes(stderr_bytes)+ stderr_text = stderr_bytes.decode("utf-8", errors="replace")+ combined = " ".join(part for part in (terminal_message, stderr_text) if part)+ if _is_auth_failure(combined):+ terminal_kind = "error"+ terminal_message = (+ terminal_message+ or "Grok Build is not logged in — run grok login on the Agents card."+ )+ elif _is_usage_limited(combined):+ terminal_kind = "error"+ terminal_message = terminal_message or combined.strip() or "Grok Build usage limit"++ duration_ms = int((time.perf_counter() - t0) * 1000)+ result_text = "\n".join(text_acc).strip()+ if timed_out:+ yield ClaudeResult(+ subtype="error_during_execution",+ is_error=True,+ session_id=session_id,+ duration_ms=duration_ms,+ result=timeout_message,+ )+ return+ exit_code = proc.returncode+ is_error = terminal_kind == "error" or (exit_code not in (None, 0) and not result_text)+ if is_error and not result_text:+ result_text = terminal_message or stderr_text.strip() or (+ f"GrokBuildDirectWorker: grok exited {exit_code}"+ )+ if not result_text and any_tool_use:+ result_text = "Grok Build completed tool work in the worktree."+ yield ClaudeResult(+ subtype="success" if not is_error else "error_during_execution",+ is_error=is_error,+ session_id=session_id,+ duration_ms=duration_ms,+ result=result_text,+ )diff --git a/jarvis/ui/web/frontend/public/provider-logos/grok.svg b/jarvis/ui/web/frontend/public/provider-logos/grok.svgnew file mode 100644index 0000000000..9cdb88e7bc--- /dev/null+++ b/jarvis/ui/web/frontend/public/provider-logos/grok.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="#F4F4F5" d="M12 1.8L13.7 8.3L20.2 10L13.7 11.7L12 18.2L10.3 11.7L3.8 10L10.3 8.3zM18.2 14.2L19.1 17.4L22.3 18.3L19.1 19.2L18.2 22.4L17.3 19.2L14.1 18.3L17.3 17.4zM5.8 14.8L6.4 17L8.6 17.6L6.4 18.2L5.8 20.4L5.2 18.2L3 17.6L5.2 17z"/></svg>diff --git a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsxindex a7d54d0885..bf8b619235 100644--- a/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx+++ b/jarvis/ui/web/frontend/src/components/JarvisAgentSection.tsx@@ -9,8 +9,10 @@ import {codexLogout,loginAntigravity,loginClaude,+ loginGrokBuild,logoutAntigravity,logoutClaude,+ logoutGrokBuild,saveSubagentModel,startCodexLogin,switchSubagentProvider,@@ -21,6 +23,7 @@ import {type Billing,type ClaudeStatus,type CodexStatus,+ type GrokBuildStatus,} from "@/hooks/useProviders";import { BrainModelSelector } from "@/components/BrainModelSelector";import { ApiKeyForm } from "@/components/ApiKeyForm";@@ -111,6 +114,7 @@ const PROVIDER_LABELS: Record<string, string> = {// Antigravity drives the Google subscription CLI as a direct worker (OAuth, no// API key), the Google sibling of Codex.antigravity: "Antigravity (Google subscription)",+ "grok-build": "Grok Build",};/**@@ -158,6 +162,7 @@ export function JarvisAgentSection({const [antigravityStatus, setAntigravityStatus] =useState<AntigravityStatus | null>(null);const [claudeStatus, setClaudeStatus] = useState<ClaudeStatus | null>(null);+ const [grokBuildStatus, setGrokBuildStatus] = useState<GrokBuildStatus | null>(null);const [error, setError] = useState<string | null>(null);// The same per-machine view preference the provider tiers read. The subagent// tier used to ignore it, which made Local Mode look broken exactly where a@@ -168,11 +173,12 @@ export function JarvisAgentSection({// provider highlight + the per-provider "Key gesetzt" badges track live.const reload = useCallback(async () => {try {- const [res, codexRes, antigravityRes, claudeRes] = await Promise.all([+ const [res, codexRes, antigravityRes, claudeRes, grokBuildRes] = await Promise.all([fetch("/api/jarvis-agent/status"),fetch("/api/codex/status").catch(() => null),fetch("/api/antigravity/status").catch(() => null),fetch("/api/claude/status").catch(() => null),+ fetch("/api/grok-build/status").catch(() => null),]);if (!res.ok) throw new Error(`HTTP ${res.status}`);const data: SubagentStatus = await res.json();@@ -192,6 +198,11 @@ export function JarvisAgentSection({} else {setClaudeStatus(null);}+ if (grokBuildRes?.ok) {+ setGrokBuildStatus(await grokBuildRes.json());+ } else {+ setGrokBuildStatus(null);+ }setError(null);} catch (e) {setError((e as Error).message);@@ -250,11 +261,15 @@ export function JarvisAgentSection({const claudeRow = inLocalMode(bridge.mapping.find((r) => r.jarvis === "claude-api"),);+ const grokBuildRow = inLocalMode(+ bridge.mapping.find((r) => r.jarvis === "grok-build"),+ );const providerRows = localVisibleRows.filter((r) =>r.jarvis !== "openai-codex" &&r.jarvis !== "antigravity" &&- r.jarvis !== "claude-api",+ r.jarvis !== "claude-api" &&+ r.jarvis !== "grok-build",);// Split the generic providers by access type so each lands in the right// group. Splitting on the backend `billing` field keeps a future provider in@@ -272,7 +287,8 @@ export function JarvisAgentSection({);const apiProviderRows = providerRows.filter((r) => r.billing === "api");const hasSubscriptionColumn =- Boolean(codexRow || antigravityRow || claudeRow) || subProviderRows.length > 0;+ Boolean(codexRow || antigravityRow || claudeRow || grokBuildRow) ||+ subProviderRows.length > 0;const hasApiColumn = Boolean(claudeRow) || apiProviderRows.length > 0;return (@@ -370,6 +386,13 @@ export function JarvisAgentSection({onChanged={reload}/>)}+ {grokBuildRow && (+ <GrokBuildConnectionCard+ status={grokBuildStatus}+ row={grokBuildRow}+ onChanged={reload}+ />+ )}{subProviderRows.map((row) => (<SubagentProviderCard key={row.jarvis} row={row} onSwitched={reload} />))}@@ -432,7 +455,11 @@ function SubagentModelCard({// The subagent worker slug → the catalog provider id (Codex's worker slug// "openai-codex" maps to the catalog's "codex"; all others match 1:1).const catalogProvider =- status.brain_primary === "openai-codex" ? "codex" : status.brain_primary;+ status.brain_primary === "openai-codex"+ ? "codex"+ : status.brain_primary === "grok-build"+ ? "grok-build"+ : status.brain_primary;// Whether the ACTIVE worker's server can be told to download a model. Read// off the provider catalog rather than a provider name, so a second local// server type that ships a puller lights this up on its own (AP-21).@@ -600,6 +627,8 @@ const PROVIDER_ICON: Record<string, string> = {openrouter: "openrouter",nvidia: "nvidia",antigravity: "antigravity",+ grok: "grok",+ "grok-build": "grok",};/**@@ -1221,6 +1250,96 @@ function AntigravityConnectionCard({);}+function GrokBuildConnectionCard({+ status,+ row,+ onChanged,+}: {+ status: GrokBuildStatus | null;+ row: SubagentMappingRow | undefined;+ onChanged: () => void | Promise<void>;+}) {+ const pushToast = useEventStore((s) => s.pushToast);+ const [pending, setPending] = useState(false);+ const { activating, activate } = useSubagentActivate(row, onChanged);+ const connected = Boolean(status?.connected && status.mode === "subscription");+ const installed = status?.installed ?? false;+ const usable = Boolean(installed && row?.key_set);+ const isActive = Boolean(usable && row?.is_active_brain);+ const detail = connected+ ? status?.user_email+ ? `Connected as ${status.user_email}`+ : status?.message || "Connected via SuperGrok / X Premium+"+ : status?.message || "Grok Build login not connected";++ async function connect() {+ setPending(true);+ try {+ await loginGrokBuild();+ pushToast("info", "Grok Build login started — finish it in the browser window");+ await onChanged();+ void pollStatusUntilConnected("/api/grok-build/status", onChanged).then((ok) => {+ if (ok) {+ pushToast("success", `Grok Build connected — now selectable as a ${agentBrandNow()}`);+ }+ });+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(false);+ }+ }++ async function disconnect() {+ setPending(true);+ try {+ await logoutGrokBuild();+ pushToast("info", "Grok Build login disconnected");+ await onChanged();+ } catch (e) {+ pushToast("error", (e as Error).message);+ } finally {+ setPending(false);+ }+ }++ return (+ <AgentCardShell+ label="Grok Build"+ slug={row?.jarvis}+ title="Grok Build"+ billing={row?.billing}+ active={isActive}+ badge={<StatusPill state={isActive ? "active" : usable ? "ready" : "open"} />}+ subtitle={detail}+ warning={+ !installed && (+ <CardHint icon={Terminal}>+ Install Grok Build before connecting (irm https://x.ai/cli/install.ps1 | iex).+ </CardHint>+ )+ }+ footer={+ <>+ {usable && row && (+ <SubagentActiveControl+ row={row}+ activating={activating}+ onActivate={activate}+ />+ )}+ {connected ? (+ <DisconnectButton onClick={disconnect} disabled={pending} />+ ) : (+ <ConnectButton onClick={connect} disabled={pending || !installed} />+ )}+ <CliTestControl endpoint="/api/grok-build/test" onChanged={onChanged} />+ </>+ }+ />+ );+}+function ClaudeConnectionCard({status,row,diff --git a/jarvis/ui/web/frontend/src/hooks/useProviders.ts b/jarvis/ui/web/frontend/src/hooks/useProviders.tsindex 80d66893d9..cda8bb0686 100644--- a/jarvis/ui/web/frontend/src/hooks/useProviders.ts+++ b/jarvis/ui/web/frontend/src/hooks/useProviders.ts@@ -1,6 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";-export type AuthMode = "api_key" | "codex" | "antigravity" | "none";+export type AuthMode = "api_key" | "codex" | "antigravity" | "claude_cli" | "grok_build" | "none";// Mirror of provider_spec.Tier. "dictation" is the odd one out and deliberately// so: it is the OPTIONAL tier that tidies dictated text, and a missing key there// costs nothing — the dictation is delivered exactly as it was recognized. Every@@ -168,6 +168,7 @@ export interface ProviderDescriptor {* in the Subagent section. It is not switchable as the main Brain provider.*/antigravity_status?: AntigravityStatus;+ grok_build_status?: GrokBuildStatus;}export interface CodexStatus {@@ -217,6 +218,22 @@ export interface AntigravityStatus {error: string | null;}+/**+ * Mirror of `jarvis/grok_build_auth.py::GrokBuildAuthStatus.to_dict()`.+ * SuperGrok / X Premium+ sibling of CodexStatus: whether the `grok` CLI is+ * installed and signed in, plus the account email.+ */+export interface GrokBuildStatus {+ installed: boolean;+ connected: boolean;+ mode: string; // "subscription" | "api_key" | "unknown"+ message: string;+ version: string | null;+ user_email: string | null;+ binary_path: string;+ error: string | null;+}+/*** Mirror of `jarvis/claude_auth.py::ClaudeAuthStatus.to_dict()`. The Anthropic* sibling of `CodexStatus` / `AntigravityStatus`: whether the `claude` CLI is@@ -706,6 +723,29 @@ export async function loginClaude(): Promise<void> {}}+/** Starts the interactive SuperGrok sign-in (POST /api/grok-build/login). */+export async function loginGrokBuild(): Promise<void> {+ const res = await fetch("/api/grok-build/login", { method: "POST" });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ const detail = body.detail;+ throw new Error(+ typeof detail === "object" && detail?.message+ ? detail.message+ : detail ?? `HTTP ${res.status}`,+ );+ }+}++/** Disconnects the Grok Build subscription login (POST /api/grok-build/logout). */+export async function logoutGrokBuild(): Promise<void> {+ const res = await fetch("/api/grok-build/logout", { method: "POST" });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) {+ throw new Error(body.detail ?? `HTTP ${res.status}`);+ }+}+/** Disconnects the Claude subscription login (POST /api/claude/logout). */export async function logoutClaude(): Promise<void> {const res = await fetch("/api/claude/logout", { method: "POST" });diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.grok-build.test.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.grok-build.test.tsxnew file mode 100644index 0000000000..c030efb3cc--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.grok-build.test.tsx@@ -0,0 +1,283 @@+/**+ * Component tests for Grok Build in ApiKeysView.+ *+ * Grok Build is an xAI-subscription worker for Subagents only. It must not+ * render as an activatable main Brain card; the SuperGrok login and active+ * toggle live in the Subagent section.+ */+import { afterEach, describe, expect, it, vi } from "vitest";+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";++import { ApiKeysView } from "@/views/ApiKeysView";++vi.mock("@/hooks/useVoiceMode", () => ({+ useVoiceMode: () => ({+ mode: "pipeline",+ realtimeAvailable: false,+ setMode: vi.fn(),+ isLoading: false,+ isSaving: false,+ }),+}));++interface RouteResult {+ status?: number;+ body: unknown;+}++function installFetchMock(routes: Record<string, () => RouteResult>) {+ const calls: { url: string; method: string; body: unknown }[] = [];+ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = String(input);+ const method = (init?.method ?? "GET").toUpperCase();+ let body: unknown = null;+ if (typeof init?.body === "string") {+ try {+ body = JSON.parse(init.body);+ } catch {+ body = init.body;+ }+ }+ calls.push({ url, method, body });+ const prefixes = Object.keys(routes).sort((a, b) => b.length - a.length);+ for (const prefix of prefixes) {+ if (url.startsWith(prefix)) {+ const { status = 200, body: resBody } = routes[prefix]();+ return {+ ok: status >= 200 && status < 300,+ status,+ statusText: status >= 200 && status < 300 ? "OK" : "ERR",+ json: async () => resBody,+ text: async () => JSON.stringify(resBody),+ } as Response;+ }+ }+ throw new Error(`unexpected fetch ${url}`);+ });+ (globalThis as unknown as { fetch: typeof fetch }).fetch =+ fetchMock as unknown as typeof fetch;+ Object.assign(navigator, {+ clipboard: { writeText: vi.fn(async () => undefined) },+ });+ return { fetchMock, calls };+}++function grokBuildDescriptor(overrides: Record<string, unknown> = {}) {+ return {+ id: "grok-build",+ label: "Grok Build (xAI subscription)",+ tier: "brain",+ auth_mode: "grok_build",+ secret_keys: [],+ secrets_set: {},+ dashboard_url: null,+ login_cli: ["grok", "login"],+ install_hint: "irm https://x.ai/cli/install.ps1 | iex",+ credential_path_hint: "~/.grok/auth.json",+ configured: true,+ active: false,+ brain_switchable: false,+ cli_installed: true,+ grok_build_status: {+ installed: true,+ connected: true,+ mode: "subscription",+ message: "Connected via SuperGrok / X Premium+",+ version: "grok 0.2.0",+ user_email: "[email protected]",+ binary_path: "grok",+ error: null,+ },+ ...overrides,+ };+}++const JARVIS_AGENT_EMPTY = {+ configured: true,+ enabled: false,+ binary_path: "",+ binary_detected: null,+ version_pin: null,+ time_cap_min: null,+ concurrency: null,+ state_dir_root: null,+ brain_primary: "gemini",+ provider_slug: null,+ model_override: null,+ model_resolved: null,+ mapping: [+ {+ jarvis: "grok-build",+ openclaw: "grok-cli (direct)",+ env_var: "SuperGrok-OAuth",+ env_fallback: null,+ key_set: true,+ api_key_set: false,+ dedicated_key_set: false,+ shared_key_set: false,+ oauth_connected: true,+ credential_source: "oauth",+ secret_key: null,+ dashboard_url: null,+ credential_help: null,+ is_active_brain: false,+ billing: "subscription",+ label: "Grok Build",+ },+ ],+};++const TELEPHONY_STATUS_EMPTY = {+ available: false,+ configured: false,+ enabled: false,+ account_sid_masked: "",+ phone_number: "",+ public_base_url: "",+ webhook_url: "",+ auth_token_set: false,+ twilio_reachable: false,+ twilio_error: null,+ tts_provider: "",+ tts_voice: "",+ active_calls: 0,+ max_call_seconds: 600,+};+const TELEPHONY_CONFIG_EMPTY = {+ enabled: false,+ account_sid: "",+ phone_number: "",+ public_base_url: "",+ greeting: "",+ language_code: "de-DE",+ fallback_mode: "media",+ max_call_seconds: 600,+ auth_token_set: false,+};++function routesFor(+ provider: Record<string, unknown>,+): Record<string, () => RouteResult> {+ return {+ "/api/providers": () => ({ body: { providers: [provider] } }),+ "/api/jarvis-agent/status": () => ({ body: JARVIS_AGENT_EMPTY }),+ "/api/codex/status": () => ({ body: {} }),+ "/api/antigravity/status": () => ({ body: {} }),+ "/api/claude/status": () => ({ body: {} }),+ "/api/grok-build/status": () => ({+ body: provider.grok_build_status ?? {},+ }),+ "/api/jarvis-agent/switch": () => ({+ body: { ok: true, active: "grok-build", persisted: true },+ }),+ "/api/grok-build/login": () => ({+ body: { ok: true, pid: 123, message: "Grok Build login was started" },+ }),+ "/api/grok-build/logout": () => ({+ body: { ok: true, message: "Grok Build was disconnected" },+ }),+ "/api/telephony/status": () => ({ body: TELEPHONY_STATUS_EMPTY }),+ "/api/telephony/config": () => ({ body: TELEPHONY_CONFIG_EMPTY }),+ "/api/telephony/scripts": () => ({ body: { scripts: [] } }),+ "/api/telephony/calls": () => ({ body: { calls: [] } }),+ };+}++function grokBuildNotConnected() {+ return grokBuildDescriptor({+ grok_build_status: {+ installed: true,+ connected: false,+ mode: "unknown",+ message: "Grok Build login not connected",+ version: "grok 0.2.0",+ user_email: null,+ binary_path: "grok",+ error: null,+ },+ });+}++describe("ApiKeysView — Grok Build (xAI subscription) OAuth card", () => {+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ });++ it("renders the connected subscription card with email AND a Set-active radio", async () => {+ installFetchMock(routesFor(grokBuildDescriptor()));+ render(<ApiKeysView />);+ fireEvent.click(screen.getByRole("tab", { name: /-agents$/i }));+ await waitFor(() => expect(screen.getByText("Grok Build")).toBeTruthy());+ expect(screen.getByText(/ada@example\.com/)).toBeTruthy();+ expect(screen.getByRole("radio")).toBeTruthy();+ });++ it("switches the subagent to Grok Build when connected", async () => {+ const { calls } = installFetchMock(routesFor(grokBuildDescriptor()));+ render(<ApiKeysView />);+ fireEvent.click(screen.getByRole("tab", { name: /-agents$/i }));+ await waitFor(() => screen.getByRole("radio"));+ fireEvent.click(screen.getByRole("radio"));+ await waitFor(() =>+ expect(+ calls.some(+ (c) =>+ c.url.startsWith("/api/jarvis-agent/switch") &&+ c.method === "POST" &&+ (c.body as { provider?: string })?.provider === "grok-build",+ ),+ ).toBe(true),+ );+ });++ it("shows the Connect button while not logged in and starts login", async () => {+ const mapping = {+ ...JARVIS_AGENT_EMPTY,+ mapping: [+ {+ ...JARVIS_AGENT_EMPTY.mapping[0],+ key_set: false,+ oauth_connected: false,+ },+ ],+ };+ const { calls } = installFetchMock({+ ...routesFor(grokBuildNotConnected()),+ "/api/jarvis-agent/status": () => ({ body: mapping }),+ });+ render(<ApiKeysView />);+ fireEvent.click(screen.getByRole("tab", { name: /-agents$/i }));+ await waitFor(() => expect(screen.getByText("Connect")).toBeTruthy());+ fireEvent.click(screen.getByText("Connect"));+ await waitFor(() =>+ expect(+ calls.some(+ (c) => c.url.startsWith("/api/grok-build/login") && c.method === "POST",+ ),+ ).toBe(true),+ );+ });++ it("disconnects via POST /api/grok-build/logout", async () => {+ const { calls } = installFetchMock(routesFor(grokBuildDescriptor()));+ render(<ApiKeysView />);+ fireEvent.click(screen.getByRole("tab", { name: /-agents$/i }));+ const disconnect = await waitFor(() => screen.getByText("Disconnect"));+ fireEvent.click(disconnect);+ await waitFor(() =>+ expect(+ calls.some(+ (c) =>+ c.url.startsWith("/api/grok-build/logout") && c.method === "POST",+ ),+ ).toBe(true),+ );+ });+});diff --git a/jarvis/ui/web/grok_build_routes.py b/jarvis/ui/web/grok_build_routes.pynew file mode 100644index 0000000000..fe18090f06--- /dev/null+++ b/jarvis/ui/web/grok_build_routes.py@@ -0,0 +1,92 @@+"""REST routes for the Grok Build (xAI subscription) provider connect flow.++OAuth-only: the user signs in with SuperGrok / X Premium+ once (via the official+``grok`` CLI), and Jarvis drives that CLI as a subprocess to bill Jarvis-Agent+work against the subscription — no xAI API key. This is the xAI sibling of the+``/api/codex/*`` and ``/api/antigravity/*`` routes.++Kept in its own router module so the feature ships as a self-contained unit.+"""+from __future__ import annotations++import asyncio+import logging+from typing import Any++from fastapi import APIRouter, HTTPException++from jarvis.core.interactive_terminal import InteractiveTerminalUnavailable+from jarvis.grok_build_auth import (+ GrokBuildAuthService,+ grok_build_install_command,+)++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api", tags=["grok-build"])++[email protected]("/grok-build/status")+async def grok_build_status() -> dict[str, Any]:+ """Honest snapshot of the Grok Build login (installed / connected / account).++ Off the event loop: the probe may spawn the CLI binary.+ """+ status = await asyncio.to_thread(GrokBuildAuthService().status)+ return status.to_dict()++[email protected]("/grok-build/test")+async def grok_build_test() -> dict[str, Any]:+ """Live CLI test: binary, version, login.++ Re-augments PATH first, so a CLI installed after app start is found without+ a restart. Runs off the event loop — the probe spawns the real binary.+ """+ from jarvis.agent_cli_probe import test_grok_build++ return (await asyncio.to_thread(test_grok_build)).to_dict()++[email protected]("/grok-build/login")+async def grok_build_login() -> dict[str, Any]:+ """Start the interactive SuperGrok login in a terminal. 409 if no CLI is found."""+ service = GrokBuildAuthService()+ status = await asyncio.to_thread(service.status)+ if not status.installed:+ raise HTTPException(+ status_code=409,+ detail={+ "message": "Grok Build CLI is not installed",+ "install_command": grok_build_install_command(),+ },+ )+ try:+ launch = await asyncio.to_thread(service.start_login)+ except FileNotFoundError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except InteractiveTerminalUnavailable as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except Exception as exc: # noqa: BLE001+ raise HTTPException(+ status_code=500,+ detail=f"Grok Build login could not be started: {type(exc).__name__}: {exc}",+ ) from exc+ return {+ "ok": True,+ "pid": launch.pid,+ "message": "Grok Build login was started in the terminal",+ }++[email protected]("/grok-build/logout")+async def grok_build_logout() -> dict[str, Any]:+ """Disconnect the SuperGrok login (``grok logout`` / remove auth.json)."""+ service = GrokBuildAuthService()+ status = await asyncio.to_thread(service.status)+ if not status.installed:+ raise HTTPException(status_code=409, detail="Grok Build CLI is not installed")+ ok, error = await asyncio.to_thread(service.logout_blocking)+ if not ok:+ raise HTTPException(status_code=500, detail=error or "Grok Build logout failed")+ return {"ok": True, "message": "Grok Build was disconnected"}diff --git a/jarvis/ui/web/provider_routes.py b/jarvis/ui/web/provider_routes.pyindex 54ab28e918..1989626d57 100644--- a/jarvis/ui/web/provider_routes.py+++ b/jarvis/ui/web/provider_routes.py@@ -44,6 +44,12 @@ from jarvis.missions.worker_runtime.provider_map import (from jarvis.missions.worker_runtime.provider_map import (CODEX_SUBAGENT_SLUGS as _CODEX_SUBAGENT_SLUGS,)+from jarvis.missions.worker_runtime.provider_map import (+ GROK_BUILD_SUBAGENT_CANONICAL as _GROK_BUILD_SUBAGENT_CANONICAL, # noqa: F401+)+from jarvis.missions.worker_runtime.provider_map import (+ GROK_BUILD_SUBAGENT_SLUGS as _GROK_BUILD_SUBAGENT_SLUGS,+)from jarvis.setup.wizard import SECRETS as WIZARD_SECRETSfrom .provider_spec import (@@ -327,6 +333,10 @@ def _cli_installed(spec: ProviderSpec) -> bool | None:# service would report the PATH install even when the user pinned a# different binary.return CodexAuthService(_codex_binary_path()).status().installed+ if spec.auth_mode == "grok_build":+ from jarvis.grok_build_auth import GrokBuildAuthService++ return GrokBuildAuthService().status().installedreturn None@@ -547,6 +557,11 @@ def _spec_to_payload(from jarvis.google_cli.auth_service import GoogleCliAuthServiceantigravity_status = GoogleCliAuthService().status().to_dict()+ grok_build_status = None+ if spec.id == "grok-build":+ from jarvis.grok_build_auth import GrokBuildAuthService++ grok_build_status = GrokBuildAuthService().status().to_dict()payload = {"id": spec.id,@@ -627,6 +642,11 @@ def _spec_to_payload("configured": (bool(antigravity_status["connected"])if antigravity_status is not None+ else bool(+ grok_build_status["connected"]+ and grok_build_status["mode"] == "subscription"+ )+ if grok_build_status is not Noneelse bool(codex_status["connected"] and codex_status["mode"] == "chatgpt")if codex_status is not None and not spec.secret_keyselse _is_credential_present(@@ -636,7 +656,9 @@ def _spec_to_payload(),"active": active,"cli_installed": (- _cli_installed(spec)+ bool(grok_build_status["installed"])+ if grok_build_status is not None+ else _cli_installed(spec)if codex_status is Noneelse bool(codex_status["installed"])),@@ -648,6 +670,8 @@ def _spec_to_payload(}if antigravity_status is not None:payload["antigravity_status"] = antigravity_status+ if grok_build_status is not None:+ payload["grok_build_status"] = grok_build_statusif codex_status is not None:payload["codex_status"] = codex_statusif spec.tier == "brain":@@ -1486,6 +1510,10 @@ def _worker_usable(provider: str) -> bool:return bool(GoogleCliAuthService().status().connected or get_jarvis_agent_secret("gemini"))+ if p in _GROK_BUILD_SUBAGENT_SLUGS:+ from jarvis.grok_build_auth import GrokBuildAuthService, grok_build_provider_ready++ return grok_build_provider_ready(GrokBuildAuthService().status())if p in {"claude-api", "claude"}:from jarvis.claude_auth import ClaudeAuthService@@ -2428,7 +2456,11 @@ async def set_brain_model(if cat.tier == "brain":# Codex / Antigravity probes would drive a slow subscription CLI (and# bill a real call); skip the live probe for those OAuth-CLI providers.- do_probe = getattr(spec, "auth_mode", None) not in ("codex", "antigravity")+ do_probe = getattr(spec, "auth_mode", None) not in (+ "codex",+ "antigravity",+ "grok_build",+ )return await _apply_brain_model(provider_id, value, body, request, probe=do_probe)if cat.tier == "tts":return _apply_tts_selection(provider_id, value, cat.selects, body, request)diff --git a/jarvis/ui/web/provider_spec.py b/jarvis/ui/web/provider_spec.pyindex 85beb61482..ea6428977e 100644--- a/jarvis/ui/web/provider_spec.py+++ b/jarvis/ui/web/provider_spec.py@@ -18,7 +18,7 @@ from typing import Literalfrom jarvis.dictation.polish_client import POLISH_FAMILIES-AuthMode = Literal["api_key", "codex", "antigravity", "claude_cli", "none"]+AuthMode = Literal["api_key", "codex", "antigravity", "claude_cli", "grok_build", "none"]Tier = Literal["brain", "tts", "stt", "realtime", "dictation"]# How using a provider is billed. Derived from auth_mode (never branched on a# provider name — see provider_billing): an API key bills per token on an API@@ -127,7 +127,7 @@ def provider_billing(spec: ProviderSpec) -> Billing:* ``none`` → ``"local"`` — no credential, runs on-device.* everything else (``api_key``) → ``"api"`` — pay per token on an API account."""- if spec.auth_mode in ("antigravity", "codex", "claude_cli"):+ if spec.auth_mode in ("antigravity", "codex", "claude_cli", "grok_build"):return "subscription_or_api" if spec.secret_keys else "subscription"if spec.auth_mode == "none":return "local"@@ -477,6 +477,34 @@ PROVIDERS: tuple[ProviderSpec, ...] = ("key also powers Grok Voice TTS."),),+ # ── Brain: xAI subscription via the official Grok Build CLI ──+ # Sibling of Codex / Antigravity / Claude CLI: spends a SuperGrok or+ # X Premium+ login instead of a per-token xAI key. No secret_keys slot —+ # the per-token path for this family already exists as ``grok``.+ #+ # ``brain_switchable=False``: process start-up is a full coding-agent CLI,+ # too slow for a spoken turn, so this must never become the main brain.+ ProviderSpec(+ id="grok-build",+ label="Grok Build (xAI subscription)",+ tier="brain",+ auth_mode="grok_build",+ secret_keys=(),+ dashboard_url=None,+ login_cli=("grok", "login"),+ install_hint=(+ "irm https://x.ai/cli/install.ps1 | iex "+ "(macOS/Linux: curl -fsSL https://x.ai/cli/install.sh | bash)"+ ),+ credential_path_hint="~/.grok/auth.json",+ brain_switchable=False,+ signup_url="https://grok.com/supergrok",+ credential_help=(+ "Sign in with SuperGrok or X Premium+ to run heavy subagent tasks "+ "via the Grok Build CLI — no API key, billed to your subscription. "+ "The xAI API-key path is the separate Grok card."+ ),+ ),ProviderSpec(id="claude-api",label="Claude (API-Key)",diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex c159bfae4f..9d5d31a334 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -357,6 +357,7 @@ class WebServer:from .feedback_routes import router as feedback_routerfrom .friends_routes import router as friends_routerfrom .frontier_routes import router as frontier_router+ from .grok_build_routes import router as grok_build_routerfrom .marketplace_routes import router as marketplace_routerfrom .mcp_routes import router as mcp_routerfrom .missions_auth import router as missions_auth_router@@ -417,6 +418,7 @@ class WebServer:app.include_router(provider_router)app.include_router(antigravity_router)app.include_router(claude_router)+ app.include_router(grok_build_router)# Several subscriptions per coding CLI, switchable without a logout.app.include_router(agent_accounts_router)app.include_router(control_router)@@ -1330,6 +1332,52 @@ class WebServer:})+ # Grok Build is a DIRECT worker (GrokBuildDirectWorker over the+ # official grok CLI) with no worker slug, so it is not in MAPPINGS.+ # SuperGrok / X Premium+ subscription only — the xAI API-key path+ # stays on the separate ``grok`` card.+ grok_build_status = None+ try:+ from jarvis.grok_build_auth import (+ GrokBuildAuthService,+ grok_build_provider_ready,+ )++ grok_build_status = await asyncio.to_thread(+ GrokBuildAuthService().status+ )+ grok_build_connected = (+ grok_build_status.connected+ and grok_build_status.mode == "subscription"+ )+ except Exception: # noqa: BLE001+ grok_build_connected = False+ grok_build_ready = (+ grok_build_provider_ready(grok_build_status)+ if grok_build_status is not None+ else False+ )+ mapping_rows.append(+ {+ "jarvis": "grok-build",+ "openclaw": "grok-cli (direct)",+ "env_var": "SuperGrok-OAuth",+ "env_fallback": None,+ "key_set": grok_build_ready,+ "api_key_set": False,+ "dedicated_key_set": False,+ "shared_key_set": False,+ "oauth_connected": grok_build_connected,+ "credential_source": "oauth" if grok_build_connected else "none",+ "secret_key": None,+ "dashboard_url": None,+ "credential_help": None,+ "is_active_brain": primary == "grok-build",+ "billing": "subscription",+ "label": "Grok Build",+ }+ )+return {"configured": oc_cfg is not None,"enabled": bool(oc_cfg.enabled) if oc_cfg else False,diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.pyindex 173642dd88..f1e9743117 100644--- a/jarvis/ui/web/settings_routes.py+++ b/jarvis/ui/web/settings_routes.py@@ -2972,7 +2972,7 @@ def _available_brain_providers(request: Request) -> list[dict[str, object]]:spec = get_spec(name)kind = ("agent"- if getattr(spec, "auth_mode", "") in ("codex", "antigravity")+ if getattr(spec, "auth_mode", "") in ("codex", "antigravity", "grok_build")else "api")out.append(diff --git a/tests/missions/test_jarvis_agent_worker_routing.py b/tests/missions/test_jarvis_agent_worker_routing.pyindex 41becad4bb..d851cade0a 100644--- a/tests/missions/test_jarvis_agent_worker_routing.py+++ b/tests/missions/test_jarvis_agent_worker_routing.py@@ -62,6 +62,13 @@ def test_api_agent_providers_are_not_a_claude_fallback() -> None:assert subagent_runs_on_claude_fallback("openclaw-claude") is True[email protected]("step_model", ["", "claude-opus-4-8", "gemini-3.1-pro", "grok-4.6"])+def test_grok_build_routes_to_direct_worker(step_model: str) -> None:+ """Choosing 'grok-build' (xAI subscription CLI) is a hard lock."""+ assert _select_subagent_worker_kind("grok-build", step_model) == "grok_build"+ assert _select_subagent_worker_kind("grok-cli", step_model) == "grok_build"++@pytest.mark.parametrize("step_model", ["", "claude-opus-4-8", "gemini-3.1-pro"])def test_antigravity_routes_to_oauth_cli_worker(step_model: str) -> None:"""Choosing 'antigravity' (Google subscription) routes to the dedicated@@ -210,7 +217,8 @@ def test_api_agent_providers_no_longer_flagged_as_claude(provider: str) -> None:@pytest.mark.parametrize(- "provider", ["openai-codex", "chatgpt", "gemini", "claude-api", "antigravity"]+ "provider",+ ["openai-codex", "chatgpt", "gemini", "claude-api", "antigravity", "grok-build"],)def test_native_providers_not_flagged(provider: str) -> None:"""A provider with its own dedicated worker (incl. claude-api itself, whichdiff --git a/tests/missions/worker_runtime/test_provider_map.py b/tests/missions/worker_runtime/test_provider_map.pyindex 4483dd4f90..c4a1341c5e 100644--- a/tests/missions/worker_runtime/test_provider_map.py+++ b/tests/missions/worker_runtime/test_provider_map.py@@ -231,6 +231,18 @@ def test_antigravity_subagent_slugs_ssot() -> None:assert "antigravity" in ANTIGRAVITY_SUBAGENT_SLUGSassert ANTIGRAVITY_SUBAGENT_CANONICAL == "antigravity"+++def test_grok_build_subagent_slugs_are_the_ssot() -> None:+ from jarvis.missions.worker_runtime.provider_map import (+ GROK_BUILD_SUBAGENT_CANONICAL,+ GROK_BUILD_SUBAGENT_SLUGS,+ )++ assert "grok-build" in GROK_BUILD_SUBAGENT_SLUGS+ assert "grok-cli" in GROK_BUILD_SUBAGENT_SLUGS+ assert GROK_BUILD_SUBAGENT_CANONICAL == "grok-build"+ assert "grok" not in GROK_BUILD_SUBAGENT_SLUGS# Not a MAPPINGS provider (OAuth CLI has no worker slug, like codex).assert "antigravity" not in JARVIS_TO_WORKER_SLUGdiff --git a/tests/missions/workers/test_grok_build_direct_worker.py b/tests/missions/workers/test_grok_build_direct_worker.pynew file mode 100644index 0000000000..c5bf273789--- /dev/null+++ b/tests/missions/workers/test_grok_build_direct_worker.py@@ -0,0 +1,64 @@+"""Grok Build worker argv + event translation — no live CLI spawn."""+from __future__ import annotations++from pathlib import Path++from jarvis.missions.workers.grok_build_direct_worker import (+ _build_grok_build_cmd,+ _event_looks_like_tool,+ _normalize_model_for_grok_build,+ _text_from_event,+)+++def test_cmd_is_headless_subscription_shape(tmp_path: Path) -> None:+ cmd = _build_grok_build_cmd(+ binary="grok",+ prompt="Fix the bug",+ worktree=tmp_path,+ model="grok-4.6",+ )+ assert cmd[:6] == [+ "grok",+ "--no-auto-update",+ "--no-alt-screen",+ "--always-approve",+ "--output-format",+ "streaming-json",+ ]+ assert "--cwd" in cmd+ assert str(tmp_path) in cmd+ assert cmd[-2:] == ["-p", "Fix the bug"]+ assert "-m" in cmd+ assert "grok-4.6" in cmd+++def test_cmd_collapses_prompt_newlines(tmp_path: Path) -> None:+ cmd = _build_grok_build_cmd(+ binary="grok",+ prompt="line one\nline two",+ worktree=tmp_path,+ )+ assert cmd[-1] == "line one line two"+++def test_foreign_models_are_dropped() -> None:+ assert _normalize_model_for_grok_build("claude-opus-4-8") == ""+ assert _normalize_model_for_grok_build("gpt-5.5") == ""+ assert _normalize_model_for_grok_build("gemini-3.5-flash") == ""+ assert _normalize_model_for_grok_build("grok-4.6") == "grok-4.6"+ assert _normalize_model_for_grok_build("x-ai/grok-4.6") == "grok-4.6"+++def test_text_from_plain_and_nested_events() -> None:+ assert _text_from_event({"text": "hello"}) == "hello"+ assert (+ _text_from_event({"update": {"content": {"text": "chunk"}}}) == "chunk"+ )+ assert _text_from_event({"type": "progress"}) is None+++def test_tool_event_detection() -> None:+ assert _event_looks_like_tool({"type": "file_write"}) == "Write"+ assert _event_looks_like_tool({"type": "command_execution"}) == "Bash"+ assert _event_looks_like_tool({"type": "assistant"}) is Nonediff --git a/tests/unit/brain/test_antigravity_worker_only.py b/tests/unit/brain/test_antigravity_worker_only.pyindex d0d4f38a33..3d626598b0 100644--- a/tests/unit/brain/test_antigravity_worker_only.py+++ b/tests/unit/brain/test_antigravity_worker_only.py@@ -18,6 +18,12 @@ def test_antigravity_is_not_a_main_brain_tier_default() -> None:assert "antigravity" not in TIER_DEFAULTS_BY_PROVIDER["deep"]+def test_grok_build_is_not_a_main_brain_tier_default() -> None:+ assert "grok-build" in SUBAGENT_ONLY_BRAIN_PROVIDERS+ assert "grok-build" not in TIER_DEFAULTS_BY_PROVIDER["router"]+ assert "grok-build" not in TIER_DEFAULTS_BY_PROVIDER["deep"]++def test_codex_is_not_a_main_brain_tier_default() -> None:assert "codex" in SUBAGENT_ONLY_BRAIN_PROVIDERSassert "openai-codex" in SUBAGENT_ONLY_BRAIN_PROVIDERSdiff --git a/tests/unit/test_agent_cli_probe.py b/tests/unit/test_agent_cli_probe.pyindex 4954ed5f5d..f67f685b83 100644--- a/tests/unit/test_agent_cli_probe.py+++ b/tests/unit/test_agent_cli_probe.py@@ -131,6 +131,21 @@ def test_antigravity_names_the_resolved_cli_kind(monkeypatch):assert "Gemini CLI" in result.message+def test_grok_build_not_installed(monkeypatch):+ from jarvis.grok_build_auth import GrokBuildAuthService, GrokBuildAuthStatus++ monkeypatch.setattr(+ GrokBuildAuthService,+ "status",+ lambda self: GrokBuildAuthStatus(installed=False, message="not found"),+ )+ result = agent_cli_probe.test_grok_build()+ assert result.ok is False+ assert result.installed is False+ assert result.searched_path+ assert "x.ai/cli" in result.message++def test_antigravity_not_installed(monkeypatch):monkeypatch.setattr("jarvis.google_cli.resolver.resolve_google_cli", lambda: Nonediff --git a/tests/unit/test_grok_build_auth.py b/tests/unit/test_grok_build_auth.pynew file mode 100644index 0000000000..467d17271e--- /dev/null+++ b/tests/unit/test_grok_build_auth.py@@ -0,0 +1,116 @@+"""Grok Build auth service — status / login parsing, isolated worker home."""+from __future__ import annotations++import json+from pathlib import Path++from jarvis.grok_build_auth import (+ GrokBuildAuthService,+ GrokBuildAuthStatus,+ _derive_auth,+ _email_from_auth,+ grok_build_install_command,+ grok_build_login_in,+ grok_build_provider_ready,+ prepare_worker_home,+)+++def test_derive_auth_subscription_tokens() -> None:+ connected, mode = _derive_auth(+ {"tokens": {"access_token": "tok", "refresh_token": "ref"}}+ )+ assert connected is True+ assert mode == "subscription"+++def test_derive_auth_api_key_field() -> None:+ connected, mode = _derive_auth({"XAI_API_KEY": "xai-test"})+ assert connected is True+ assert mode == "api_key"+++def test_derive_auth_empty() -> None:+ assert _derive_auth({}) == (False, "unknown")+ assert _derive_auth(None) == (False, "unknown")+++def test_email_from_user_object() -> None:+ assert _email_from_auth({"user": {"email": "[email protected]"}}) == "[email protected]"+++def test_login_in_reads_one_home(tmp_path: Path) -> None:+ (tmp_path / "auth.json").write_text(+ json.dumps({"tokens": {"access_token": "tok"}, "user": {"email": "[email protected]"}}),+ encoding="utf-8",+ )+ connected, mode, email = grok_build_login_in(tmp_path)+ assert connected is True+ assert mode == "subscription"+ assert email == "[email protected]"+++def test_login_in_missing_file(tmp_path: Path) -> None:+ assert grok_build_login_in(tmp_path) == (False, "unknown", None)+++def test_provider_ready_requires_installed_subscription() -> None:+ assert grok_build_provider_ready(GrokBuildAuthStatus()) is False+ assert (+ grok_build_provider_ready(+ GrokBuildAuthStatus(installed=True, connected=True, mode="api_key")+ )+ is False+ )+ assert (+ grok_build_provider_ready(+ GrokBuildAuthStatus(installed=True, connected=True, mode="subscription")+ )+ is True+ )+++def test_install_command_is_os_specific() -> None:+ assert "install.ps1" in grok_build_install_command("win32")+ assert "install.sh" in grok_build_install_command("linux")+++def test_prepare_worker_home_copies_auth_not_hooks(tmp_path: Path) -> None:+ src = tmp_path / "src"+ dest = tmp_path / "dest"+ src.mkdir()+ (src / "auth.json").write_text(+ json.dumps({"tokens": {"access_token": "tok"}}),+ encoding="utf-8",+ )+ (src / "hooks").mkdir()+ (src / "hooks" / "evil.json").write_text("{}", encoding="utf-8")+ isolated = prepare_worker_home(src_home=src, dest_root=dest)+ assert isolated == dest+ assert (dest / "auth.json").is_file()+ assert not (dest / "hooks").exists()+ assert "[cli]" in (dest / "config.toml").read_text(encoding="utf-8")+++def test_status_not_installed(monkeypatch, tmp_path: Path) -> None:+ service = GrokBuildAuthService(binary_path="grok-missing-binary", grok_home_dir=tmp_path)+ monkeypatch.setattr(service, "_resolve_binary", lambda: None)+ status = service.status()+ assert status.installed is False+ assert status.connected is False+ assert "not found" in status.message.lower() or "Install" in status.message+++def test_status_connected_from_auth_file(monkeypatch, tmp_path: Path) -> None:+ (tmp_path / "auth.json").write_text(+ json.dumps({"tokens": {"access_token": "tok"}, "user": {"email": "[email protected]"}}),+ encoding="utf-8",+ )+ service = GrokBuildAuthService(binary_path="grok", grok_home_dir=tmp_path)+ monkeypatch.setattr(service, "_resolve_binary", lambda: str(tmp_path / "grok"))+ monkeypatch.setattr(service, "_probe_version", lambda _binary: "grok 0.2.0")+ status = service.status()+ assert status.installed is True+ assert status.connected is True+ assert status.mode == "subscription"+ assert status.user_email == "[email protected]"diff --git a/tests/unit/test_grok_build_jarvis_agent_parity.py b/tests/unit/test_grok_build_jarvis_agent_parity.pynew file mode 100644index 0000000000..c7e6276f62--- /dev/null+++ b/tests/unit/test_grok_build_jarvis_agent_parity.py@@ -0,0 +1,29 @@+"""Anti-drift parity: Grok Build slugs are a SINGLE source of truth."""+from __future__ import annotations++from jarvis.missions.init import _select_subagent_worker_kind+from jarvis.missions.worker_runtime.provider_map import (+ GROK_BUILD_SUBAGENT_CANONICAL,+ GROK_BUILD_SUBAGENT_SLUGS,+)+from jarvis.ui.web import provider_routes+++def test_provider_routes_reexports_the_single_source() -> None:+ assert provider_routes._GROK_BUILD_SUBAGENT_SLUGS is GROK_BUILD_SUBAGENT_SLUGS+ assert provider_routes._GROK_BUILD_SUBAGENT_CANONICAL == GROK_BUILD_SUBAGENT_CANONICAL+++def test_accepted_slugs_all_route_to_grok_build() -> None:+ for slug in GROK_BUILD_SUBAGENT_SLUGS:+ assert _select_subagent_worker_kind(slug, "") == "grok_build", slug+++def test_canonical_value_in_set_and_routes() -> None:+ assert GROK_BUILD_SUBAGENT_CANONICAL in GROK_BUILD_SUBAGENT_SLUGS+ assert _select_subagent_worker_kind(GROK_BUILD_SUBAGENT_CANONICAL, "") == "grok_build"+++def test_api_grok_slug_is_not_grok_build() -> None:+ """The xAI API-key card must stay a different worker than Grok Build."""+ assert _select_subagent_worker_kind("grok", "") != "grok_build"diff --git a/tests/unit/test_provider_spec.py b/tests/unit/test_provider_spec.pyindex 06daca382f..457334ad53 100644--- a/tests/unit/test_provider_spec.py+++ b/tests/unit/test_provider_spec.py@@ -49,6 +49,12 @@ def test_only_subscription_cli_providers_use_cli_login() -> None:elif spec.id == "claude-cli":assert spec.auth_mode == "claude_cli"assert spec.login_cli == ("claude", "/login")+ elif spec.id == "grok-build":+ assert spec.auth_mode == "grok_build"+ assert spec.login_cli == ("grok", "login")+ assert spec.secret_keys == ()+ assert provider_billing(spec) == "subscription"+ assert spec.brain_switchable is Falseelse:assert spec.login_cli is None, f"{spec.id}: unexpected login_cli"