Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

feat: add Grok CLI subagent connector

fetw6b428934fc2c
diff --git a/AGENTS.md b/AGENTS.md
index 95a57c424..fe380125f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -106,6 +106,7 @@ deeptutor start # backend + frontend together
| `deeptutor/runtime/registry/` | Tool + Capability registries |
| `deeptutor/runtime/bootstrap/builtin_capabilities.py` | Built-in capability class paths |
| `deeptutor/services/config/runtime_settings.py` | JSON settings + process-env overrides |
+| `deeptutor/services/subagent/` | Local/remote agent connectors; register each backend in `registry.py` and its model options in `models.py` (Grok CLI uses native `streaming-json`) |
| `deeptutor/core/stream.py`, `stream_bus.py` | StreamEvent protocol + async fan-out |
| `deeptutor/core/tool_protocol.py` | `BaseTool` + `ToolDefinition` |
| `deeptutor/core/capability_protocol.py` | `BaseCapability` + `CapabilityManifest` |
diff --git a/README.md b/README.md
index 37bcf130b..95c7b44dd 100644
--- a/README.md
+++ b/README.md
@@ -225,7 +225,7 @@ DeepTutor is an agent-native learning workspace that connects tutoring, problem
- **One runtime for every mode** — Chat, Ask Questions, Quiz, Research, Visualize, Solve, Course Study, Mastery Path, Immersive Reading, and Immersive Watching share one capability runtime and session context while keeping purpose-built loops and pipelines.
- **Connected learning context** — Knowledge bases, books, Co-Writer drafts, notebooks, question banks, personas, and Memory can be reused across the workflows that support them, subject to account grants and learning policies.
- **Immersive video learning** — paste a YouTube link for privacy-enhanced native playback, synchronized captions, timestamp-grounded tutoring, and resumable progress; administrators can switch playback to a self-hosted Invidious instance without rebuilding materials.
-- **Subagents and Partners** — from Chat, consult a live agent harness (Claude Code, Codex, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw, or DeepSeek) or a Partner, import past conversations, and run persistent IM companions on the same brain.
+- **Subagents and Partners** — from Chat, consult a live agent harness (Claude Code, Codex, Grok CLI, Antigravity, Kimi, opencode, MiMo, Hermes, OpenClaw, or DeepSeek) or a Partner, import past conversations, and run persistent IM companions on the same brain.
- **Multi-engine knowledge** — versioned RAG libraries across LlamaIndex, PageIndex, GraphRAG, LightRAG, a remote LightRAG Server, a self-hosted WeKnora knowledge base, a Tencent IMA or MarginNote 4 library, or a linked Obsidian vault, with pluggable document parsing.
- **Extensible tools and skills** — built-in tools, MCP servers, CLI apps, image / video / voice generation models, and installable community skills from EduHub.
- **Inspectable memory** — L1 traces, L2 surface summaries, and L3 synthesis make personalization visible and editable; the Memory Graph links L2 facts to L1 evidence and L3 synthesis to contributing surfaces.
@@ -683,7 +683,32 @@ For faster setup, the Partner channel page can create a Feishu/Lark app or WeCom
<img src="assets/figs/web-1.4.6+/myagents/00-overview.png" alt="DeepTutor My Agents workspace" width="900">
</div>
-My Agents turns other agents into context for DeepTutor, and does two distinct things. **Connect a live agent** — Claude Code, Codex, Antigravity, Kimi, opencode, MiMo Code, Hermes Agent, OpenClaw, or DeepSeek Harness on your machine, or one of your Partners — and consult it from inside a chat turn: DeepTutor actually *runs* the other agent and streams its work into the Activity panel via the `consult_subagent` tool. Select it and its round limit with the Agent chip, or filter the same connected-agent list with `@`; the choice stays attached to the session.
+My Agents turns other agents into context for DeepTutor, and does two distinct things. **Connect a live agent** — Claude Code, Codex, Grok CLI, Antigravity, Kimi, opencode, MiMo Code, Hermes Agent, OpenClaw, or DeepSeek Harness on your machine, or one of your Partners — and consult it from inside a chat turn: DeepTutor actually *runs* the other agent and streams its work into the Activity panel via the `consult_subagent` tool. Select it and its round limit with the Agent chip, or filter the same connected-agent list with `@`; the choice stays attached to the session.
+
+**Connect Grok CLI.** Install xAI's Grok CLI on the machine running the DeepTutor
+backend, run `grok login` there, and verify that `grok --help` lists
+`--output-format streaming-json`. Then open **My Agents → Connect**, select
+**Grok CLI**, and choose a working directory. Detection checks the executable's
+protocol support; it does not verify login or model access. The connector has
+been exercised with Grok CLI 1.0.3; unrelated third-party commands also named
+`grok` are not supported.
+
+In **Settings → Partners & Agents → Grok CLI**, leave model and reasoning effort
+empty to use the CLI defaults, or enter values supported by your account's
+`grok models` output. System instructions are passed through `--rules`. The
+default permission mode is `dontAsk`: Grok uses its existing rules and built-in
+read-only handling, and denies operations that need approval. This is a CLI
+permission policy, not a filesystem sandbox. Broader modes can be selected
+explicitly in settings; advanced CLI flags remain available through
+`backends.grok.extra_args` in the subagent settings API.
+
+Grok uses its own authentication and session storage; DeepTutor does not copy
+its credentials. Follow-up consults resume the connection's session in the same
+working directory. Text and tool activity stream live; private thought payloads
+are omitted. Cross-session Grok memory is disabled by default. This connector
+supports text questions and CLI tools, not image forwarding or importing past
+Grok conversations. In Docker, install and authenticate Grok inside the backend
+container; a CLI installed only on the browser's computer is not reachable.
<div align="center">
<img src="assets/figs/web-1.4.6+/home/08-subagent%20demo%20with%20claude%20code.png" alt="Consulting a Claude Code subagent live" width="900">
diff --git a/deeptutor/capabilities/subagent/tools.py b/deeptutor/capabilities/subagent/tools.py
index aeede5195..2873612c2 100644
--- a/deeptutor/capabilities/subagent/tools.py
+++ b/deeptutor/capabilities/subagent/tools.py
@@ -47,7 +47,7 @@ class ConsultSubagentTool(BaseTool):
name="consult_subagent",
description=(
"Ask the connected external agent (a local agent CLI on the user's "
- "machine — Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode, "
+ "machine — Claude Code, Codex, Grok CLI, Antigravity CLI, Kimi CLI, opencode, "
"MiMo Code, Hermes Agent, OpenClaw, or DeepSeek Harness — or one of "
"their partners) a focused question and get its "
"answer. A local agent runs on the user's machine with access to their "
diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.py
index 4ce4174c9..21c6a6905 100644
--- a/deeptutor/services/subagent/__init__.py
+++ b/deeptutor/services/subagent/__init__.py
@@ -1,7 +1,7 @@
"""Subagent driver layer — drive a user's local agent CLI as a subagent.
DeepTutor runs on the same machine as the user's configured agent CLIs — Claude
-Code, Codex, Antigravity CLI, Kimi CLI, opencode, MiMo Code, Hermes Agent,
+Code, Codex, Grok CLI, Antigravity CLI, Kimi CLI, opencode, MiMo Code, Hermes Agent,
OpenClaw, DeepSeek Harness — so the backend can
drive them directly (spawned in print mode, or via a managed local server for
the opencode family) and stream back every native event. This package is the
diff --git a/deeptutor/services/subagent/config.py b/deeptutor/services/subagent/config.py
index 5e6067b8f..921ebc3ee 100644
--- a/deeptutor/services/subagent/config.py
+++ b/deeptutor/services/subagent/config.py
@@ -47,7 +47,8 @@ class BackendConfig:
# programmatically (be concise, self-contained, don't ask follow-ups).
# CC: --append-system-prompt. Empty = none.
system_prompt: str = ""
- # Claude Code: --permission-mode value. "bypassPermissions" never stalls and
+ # Claude Code / Grok CLI: --permission-mode. Grok defaults to "dontAsk"
+ # through default_backend_config. Claude's "bypassPermissions" never stalls and
# lets the agent act autonomously on the user's own machine (the explicit
# trust model of "connect my local CLI"). Codex ignores this field.
permission_mode: str = "bypassPermissions"
@@ -88,7 +89,7 @@ class SubagentSettings:
backends: dict[str, BackendConfig] = field(default_factory=dict)
def backend(self, kind: str) -> BackendConfig:
- return self.backends.get(kind, BackendConfig())
+ return self.backends.get(kind, default_backend_config(kind))
def to_dict(self) -> dict[str, Any]:
return {
@@ -133,8 +134,13 @@ def _coerce_budget(value: Any) -> int:
return max(CONSULT_BUDGET_MIN, min(CONSULT_BUDGET_MAX, n))
-def _coerce_backend(raw: Any) -> BackendConfig:
- base = BackendConfig()
+def default_backend_config(kind: str) -> BackendConfig:
+ """Backend-specific defaults without changing existing CLI permissions."""
+ return BackendConfig(permission_mode="dontAsk") if kind == "grok" else BackendConfig()
+
+
+def _coerce_backend(raw: Any, kind: str = "") -> BackendConfig:
+ base = default_backend_config(kind)
if not isinstance(raw, dict):
return base
extra = raw.get("extra_args")
@@ -173,7 +179,7 @@ def settings_from_dict(raw: Any) -> SubagentSettings:
backends: dict[str, BackendConfig] = {}
if isinstance(backends_raw, dict):
for kind, cfg in backends_raw.items():
- backends[str(kind)] = _coerce_backend(cfg)
+ backends[str(kind)] = _coerce_backend(cfg, str(kind))
return SubagentSettings(
consult_budget=_coerce_budget(raw.get("consult_budget") if isinstance(raw, dict) else None),
backends=backends,
@@ -205,6 +211,7 @@ def get_consult_budget() -> int:
__all__ = [
"BackendConfig",
+ "default_backend_config",
"SubagentSettings",
"DEFAULT_CONSULT_BUDGET",
"CONSULT_BUDGET_MIN",
diff --git a/deeptutor/services/subagent/grok.py b/deeptutor/services/subagent/grok.py
new file mode 100644
index 000000000..ddd4b6e84
--- /dev/null
+++ b/deeptutor/services/subagent/grok.py
@@ -0,0 +1,244 @@
+"""Drive xAI's Grok CLI using its native ``streaming-json`` headless protocol.
+
+The CLI owns authentication and session storage. DeepTutor only retains the
+``end.sessionId`` needed for ``--resume`` in the connection's working directory.
+Text and tool events stream to Activity; private ``thought`` payloads and opaque
+usage signatures are deliberately not forwarded or stored in the trace.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+import json
+import logging
+from typing import Any
+
+from deeptutor.services.subagent.base import OnEvent, SubagentBackend
+from deeptutor.services.subagent.config import BackendConfig, default_backend_config
+from deeptutor.services.subagent.process import (
+ compact_field,
+ not_found_detail,
+ probe_version,
+ stream_process_lines,
+ truncate_field,
+)
+from deeptutor.services.subagent.types import (
+ EVENT_ERROR,
+ EVENT_LOG,
+ EVENT_TEXT,
+ EVENT_TOOL,
+ EVENT_TOOL_RESULT,
+ ConsultResult,
+ DetectResult,
+ SubagentEvent,
+)
+
+logger = logging.getLogger(__name__)
+
+_NOT_FOUND_DETAIL = (
+ "Install xAI's Grok CLI on the DeepTutor server, sign in with `grok login`, "
+ "and ensure `grok` is on PATH. Requires native `--output-format streaming-json`."
+)
+
+
+@dataclass(slots=True)
+class _StreamState:
+ ended: bool = False
+ text: str = ""
+ text_index: int = 0
+ new_text_block: bool = True
+ tools: dict[str, dict[str, Any]] = field(default_factory=dict)
+
+
+class GrokBackend(SubagentBackend):
+ """Consult a locally installed, authenticated xAI Grok CLI."""
+
+ kind = "grok"
+ display_name = "Grok CLI"
+ cli_command = "grok"
+
+ async def detect(self) -> DetectResult:
+ ok, version = await probe_version([self.cli_command, "--version"])
+ detail = "" if ok else not_found_detail(version, _NOT_FOUND_DETAIL)
+ if ok:
+ # Several unrelated packages also install a binary named `grok`.
+ # Version alone cannot establish the headless protocol we consume.
+ help_ok, help_text = await probe_version([self.cli_command, "--help"])
+ ok = help_ok and all(
+ flag in help_text
+ for flag in ("streaming-json", "--single", "--resume", "--permission-mode")
+ )
+ if not ok:
+ detail = "Incompatible grok command. " + _NOT_FOUND_DETAIL
+ return DetectResult(
+ kind=self.kind,
+ display_name=self.display_name,
+ available=ok,
+ version=version if ok else "",
+ detail=detail,
+ )
+
+ def _build_command(
+ self, question: str, *, session_id: str | None, config: BackendConfig
+ ) -> list[str]:
+ cmd = [
+ self.cli_command,
+ "--output-format",
+ "streaming-json",
+ "--permission-mode",
+ config.permission_mode or "dontAsk",
+ # Keep session context, but do not mix independent DeepTutor chats
+ # through Grok's cross-session memory.
+ "--no-memory",
+ "--verbatim",
+ ]
+ if config.model:
+ cmd += ["--model", config.model]
+ if config.effort:
+ cmd += ["--reasoning-effort", config.effort]
+ if config.system_prompt:
+ cmd += ["--rules", config.system_prompt]
+ if session_id:
+ cmd += ["--resume", session_id]
+ cmd += list(config.extra_args)
+ # Equals form keeps a prompt beginning with '-' a value, not a flag.
+ cmd.append(f"--single={question}")
+ return cmd
+
+ async def consult(
+ self,
+ question: str,
+ *,
+ on_event: OnEvent,
+ cwd: str | None = None,
+ session_id: str | None = None,
+ config: BackendConfig | None = None,
+ images: list[str] | None = None,
+ partner_id: str | None = None, # noqa: ARG002 — partner-only
+ ) -> ConsultResult:
+ config = config or default_backend_config(self.kind)
+ result = ConsultResult(session_id=session_id)
+ state = _StreamState()
+
+ async def emit(
+ kind: str, text: str, raw: dict[str, Any], meta: dict[str, Any] | None = None
+ ) -> None:
+ result.event_count += 1
+ await on_event(SubagentEvent(kind=kind, text=text, raw=raw, meta=meta or {}))
+
+ async def fail(message: str) -> None:
+ if result.success:
+ result.success = False
+ result.error = message
+ await emit(EVENT_ERROR, message, {})
+
+ if images:
+ await fail("Grok CLI image forwarding is not supported by this connector.")
+ return result
+
+ cmd = self._build_command(question, session_id=session_id, config=config)
+ try:
+ async for channel, line in stream_process_lines(cmd, cwd=cwd):
+ if channel == "exit":
+ if line != "0":
+ await fail(f"grok exited with code {line}")
+ continue
+ if channel == "stderr":
+ if line.strip():
+ await emit(EVENT_LOG, truncate_field(line), {"stream": channel})
+ continue
+ try:
+ event = json.loads(line)
+ except (ValueError, TypeError):
+ if line.strip():
+ # Do not echo malformed frames: they may contain a
+ # truncated thought or other private protocol payload.
+ await fail("Grok CLI emitted invalid streaming JSON.")
+ continue
+ if not isinstance(event, dict):
+ await fail("Grok CLI emitted an invalid streaming event.")
+ continue
+ await self._handle_event(event, result, state, emit, fail)
+ except Exception as exc: # cancellation propagates to the process cleanup
+ logger.warning("grok consult failed: %s", exc)
+ await fail(str(exc))
+
+ if not state.ended:
+ await fail("Grok CLI stream ended without a completion event.")
+ elif not result.final_text.strip():
+ await fail("Grok CLI completed without an answer.")
+ return result
+
+ async def _handle_event(
+ self,
+ event: dict[str, Any],
+ result: ConsultResult,
+ state: _StreamState,
+ emit: Any,
+ fail: Any,
+ ) -> None:
+ etype = str(event.get("type") or "")
+ if etype in ("thought", "available_commands"):
+ return
+ if etype == "usage":
+ state.new_text_block = True
+ return
+ if etype == "text":
+ delta = event.get("data")
+ if not isinstance(delta, str) or not delta:
+ return
+ if state.new_text_block:
+ state.text = ""
+ state.text_index += 1
+ state.new_text_block = False
+ state.text += delta
+ result.final_text = state.text
+ await emit(
+ EVENT_TEXT,
+ state.text,
+ {"type": etype},
+ {"merge_id": f"grok-text-{state.text_index}"},
+ )
+ return
+ if etype in ("tool_call", "tool_call_update"):
+ # A preamble before a tool is not the final answer to the consult.
+ if etype == "tool_call":
+ state.new_text_block = True
+ result.final_text = ""
+ tool_id = str(event.get("toolCallId") or "")
+ # Updates are sparse, and the UI replaces a merged row in full.
+ # Retain the name and input when later frames only carry output.
+ tool = state.tools.setdefault(tool_id, {}) if tool_id else {}
+ tool.update({key: value for key, value in event.items() if value is not None})
+ name = str(tool.get("toolName") or tool.get("title") or "Tool")
+ status = str(tool.get("status") or "")
+ fields = [name]
+ if status:
+ fields.append(status)
+ for key in ("rawInput", "rawOutput", "content"):
+ if tool.get(key):
+ fields.append(compact_field(tool[key]))
+ completed = etype == "tool_call_update" and status in ("completed", "failed")
+ await emit(
+ EVENT_TOOL_RESULT if completed else EVENT_TOOL,
+ truncate_field(" · ".join(fields)),
+ {"type": etype, "toolCallId": tool_id, "status": status},
+ {"merge_id": f"grok-tool-{tool_id}"} if tool_id else None,
+ )
+ return
+ if etype == "end":
+ state.ended = True
+ sid = event.get("sessionId") or event.get("session_id")
+ if isinstance(sid, str) and sid:
+ result.session_id = sid
+ reason = event.get("stopReason") or event.get("stop_reason")
+ if reason != "end_turn":
+ await fail(f"Grok CLI stopped without completing the turn: {reason or 'unknown'}")
+ return
+ if etype == "error":
+ await fail(truncate_field(str(event.get("message") or "Grok CLI error")))
+ return
+ # New protocol events are visible by type, without exposing unknown
+ # payloads (which can include internal reasoning or opaque signatures).
+ if etype:
+ await emit(EVENT_LOG, f"Grok CLI: {etype}", {"type": etype})
diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.py
index 7a915f086..339b2c8b0 100644
--- a/deeptutor/services/subagent/models.py
+++ b/deeptutor/services/subagent/models.py
@@ -12,6 +12,8 @@ page's "sync" button just re-reads it:
(opus / sonnet / haiku) plus any full name, and ``--effort`` a fixed set — so
we offer those as suggestions and the UI also allows a free-text model.
* **Kimi CLI** has no model-list surface — free text only.
+* **Grok CLI** keeps its account-specific CLI defaults, with free-text model
+ and effort overrides (the human-readable ``grok models`` catalog is not parsed).
* **opencode / MiMo Code** enumerate ``provider/model`` slugs via their own
``<cli> models`` command (models.dev catalog); syncing re-runs it with
``--refresh``. Reasoning effort is their ``--variant`` scale.
@@ -264,6 +266,23 @@ async def _kimi_options() -> BackendOptions:
)
+async def _grok_options() -> BackendOptions:
+ backend = get_backend("grok")
+ detected = await backend.detect() if backend else None
+ return BackendOptions(
+ kind="grok",
+ display_name="Grok CLI",
+ available=detected.available if detected else False,
+ version=detected.version if detected else "",
+ # `grok models` is human-readable and account-specific. Keep the CLI
+ # default or accept a model/effort the operator has verified there.
+ models=[],
+ efforts=[],
+ allow_custom_model=True,
+ detail=detected.detail if detected else "Grok CLI backend unavailable",
+ )
+
+
async def _list_cli_models(cli_command: str, *, refresh: bool = False) -> list[ModelOption]:
"""Parse ``<cli> models`` output — one ``provider/model`` slug per line."""
cmd = [cli_command, "models"]
@@ -379,6 +398,7 @@ async def _deepseek_harness_options() -> BackendOptions:
_PROVIDERS: dict[str, Callable[..., Awaitable[BackendOptions]]] = {
"claude_code": _claude_options,
"codex": _codex_options,
+ "grok": _grok_options,
"antigravity": _antigravity_options,
"kimi": _kimi_options,
"opencode": _opencode_options,
diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.py
index 45fe0cfc1..77ac9b9c5 100644
--- a/deeptutor/services/subagent/registry.py
+++ b/deeptutor/services/subagent/registry.py
@@ -2,7 +2,7 @@
Add a new subagent by writing a :class:`SubagentBackend` and listing it here;
the capability, API and UI all discover it through these helpers. Local-CLI
-backends (Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode,
+backends (Claude Code, Codex, Grok CLI, Antigravity CLI, Kimi CLI, opencode,
MiMo Code, Hermes Agent, OpenClaw, DeepSeek Harness), configured remote
backends, and the in-process partner backend live in the same registry.
``local_cli`` and ``detectable`` control which backends participate in
@@ -18,6 +18,7 @@ from deeptutor.services.subagent.base import SubagentBackend
from deeptutor.services.subagent.claude_code import ClaudeCodeBackend
from deeptutor.services.subagent.codex import CodexBackend
from deeptutor.services.subagent.deepseek_harness import DeepSeekHarnessBackend
+from deeptutor.services.subagent.grok import GrokBackend
from deeptutor.services.subagent.hermes import HermesBackend
from deeptutor.services.subagent.hermes_remote import HermesRemoteBackend
from deeptutor.services.subagent.kimi import KimiBackend
@@ -31,6 +32,7 @@ _BACKENDS: dict[str, SubagentBackend] = {
for backend in (
ClaudeCodeBackend(),
CodexBackend(),
+ GrokBackend(),
AntigravityBackend(),
KimiBackend(),
OpencodeBackend(),
diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.py
index 860cb4d5c..58206332d 100644
--- a/tests/api/test_subagents_router.py
+++ b/tests/api/test_subagents_router.py
@@ -68,7 +68,7 @@ def client(monkeypatch, tmp_path):
monkeypatch.setattr(
subagents_module,
"list_backend_kinds",
- lambda: ["claude_code", "codex", "hermes_remote", "partner"],
+ lambda: ["claude_code", "codex", "grok", "hermes_remote", "partner"],
)
monkeypatch.setattr(subagents_module, "assert_path_allowed", lambda p: Path(p))
# Isolate settings persistence to a temp file — the PUT path otherwise
@@ -130,6 +130,26 @@ def test_connect_rejects_unknown_kind(client):
assert res.status_code == 400
+def test_grok_connection_and_settings_roundtrip(client):
+ created = client.post(
+ "/api/subagents/connections",
+ json={"name": "MyGrok", "agent_kind": "grok", "cwd": "/tmp"},
+ )
+ assert created.status_code == 200
+ assert created.json()["agent_kind"] == "grok"
+ saved = client.put(
+ "/api/subagents/settings",
+ json={"backends": {"grok": {"model": "custom-model", "effort": "high"}}},
+ )
+ assert saved.status_code == 200
+ config = client.get("/api/subagents/settings").json()["backends"]["grok"]
+ assert config["permission_mode"] == "dontAsk"
+ assert config["model"] == "custom-model" and config["effort"] == "high"
+ assert client.get("/api/subagents/connections").json()["connections"][0]["agent_kind"] == "grok"
+ assert client.delete("/api/subagents/connections/MyGrok").status_code == 200
+ assert client.get("/api/subagents/connections").json()["connections"] == []
+
+
def test_connect_remote_backend_does_not_persist_a_local_cwd(client):
created = client.post(
"/api/subagents/connections",
diff --git a/tests/services/test_grok_backend.py b/tests/services/test_grok_backend.py
new file mode 100644
index 000000000..53a766981
--- /dev/null
+++ b/tests/services/test_grok_backend.py
@@ -0,0 +1,302 @@
+"""Grok CLI's native JSONL contract, failures, and connection defaults."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+
+import pytest
+
+from deeptutor.services.subagent.config import (
+ SubagentSettings,
+ default_backend_config,
+ settings_from_dict,
+)
+from deeptutor.services.subagent.grok import GrokBackend
+
+
+async def _consult(monkeypatch, *events: Any, exit_code: str = "0", **kwargs):
+ async def stream(cmd, cwd=None): # noqa: ARG001
+ for event in events:
+ if isinstance(event, tuple):
+ yield event
+ else:
+ yield "stdout", json.dumps(event)
+ yield "exit", exit_code
+
+ monkeypatch.setattr("deeptutor.services.subagent.grok.stream_process_lines", stream)
+ seen = []
+
+ async def on_event(event):
+ seen.append(event)
+
+ result = await GrokBackend().consult("question", on_event=on_event, **kwargs)
+ return result, seen
+
+
+def test_commands_use_native_protocol_and_explicit_session_resume():
+ config = default_backend_config("grok")
+ config.model = "model-from-grok-models"
+ config.effort = "high"
+ config.system_prompt = "Ask one question at a time."
+ config.extra_args = ["--disable-web-search"]
+ backend = GrokBackend()
+ for sid in (None, "session-for-this-connection"):
+ cmd = backend._build_command("--literal prompt\n你好", session_id=sid, config=config)
+ assert cmd[0] == "grok"
+ assert cmd[cmd.index("--output-format") + 1] == "streaming-json"
+ assert cmd[cmd.index("--permission-mode") + 1] == "dontAsk"
+ assert cmd[cmd.index("--model") + 1] == config.model
+ assert cmd[cmd.index("--reasoning-effort") + 1] == "high"
+ assert cmd[cmd.index("--rules") + 1] == config.system_prompt
+ assert cmd[-1] == "--single=--literal prompt\n你好"
+ assert "--no-memory" in cmd and "--verbatim" in cmd
+ assert "--disable-web-search" in cmd
+ assert "--continue" not in cmd and "--session-id" not in cmd
+ if sid:
+ assert cmd[cmd.index("--resume") + 1] == sid
+ else:
+ assert "--resume" not in cmd
+
+
[email protected]("raw", [{}, {"backends": {"grok": {}}}, {"backends": {"grok": None}}])
+def test_missing_grok_permissions_default_to_dont_ask(raw):
+ settings = settings_from_dict(raw)
+ assert settings.backend("grok").permission_mode == "dontAsk"
+ assert SubagentSettings().backend("grok").permission_mode == "dontAsk"
+ assert settings.backend("claude_code").permission_mode == "bypassPermissions"
+
+
+def test_explicit_grok_permissions_survive_settings_roundtrip():
+ settings = settings_from_dict({"backends": {"grok": {"permission_mode": "acceptEdits"}}})
+ restored = settings_from_dict(settings.to_dict())
+ assert restored.backend("grok").permission_mode == "acceptEdits"
+
+
+async def test_streamed_answer_session_and_private_payload_filtering(monkeypatch):
+ result, seen = await _consult(
+ monkeypatch,
+ {"type": "available_commands", "tools": ["ignored"]},
+ {"type": "thought", "data": "private reasoning marker"},
+ {"type": "text", "data": "你好,"},
+ {"type": "text", "data": "world"},
+ {"type": "usage", "signature": "opaque signature marker"},
+ {"type": "end", "sessionId": "session-1", "stopReason": "end_turn"},
+ )
+ assert result.success is True
+ assert result.final_text == "你好,world"
+ assert result.session_id == "session-1"
+ assert result.event_count == len(seen) == 2
+ assert [e.text for e in seen] == ["你好,", "你好,world"]
+ assert seen[0].meta["merge_id"] == seen[1].meta["merge_id"]
+ assert "private reasoning marker" not in repr(seen)
+ assert "opaque signature marker" not in repr(seen)
+
+
+async def test_tool_events_and_final_answer_do_not_reuse_preamble(monkeypatch):
+ result, seen = await _consult(
+ monkeypatch,
+ {"type": "text", "data": "Let me read the file."},
+ {
+ "type": "tool_call",
+ "toolCallId": "t1",
+ "toolName": "read_file",
+ "status": "in_progress",
+ "rawInput": {"path": "textbook.txt"},
+ },
+ {
+ "type": "tool_call_update",
+ "toolCallId": "t1",
+ "status": "completed",
+ "rawOutput": {"text": "Chapter 1"},
+ },
+ {"type": "usage", "stopReason": "tool_use"},
+ {"type": "text", "data": "The answer is "},
+ {"type": "text", "data": "42."},
+ {"type": "end", "sessionId": "session-1", "stopReason": "end_turn"},
+ )
+ assert result.success is True
+ assert result.final_text == "The answer is 42."
+ tools = [e for e in seen if e.kind in ("tool", "tool_result")]
+ assert len(tools) == 2
+ assert "read_file" in tools[0].text and "textbook.txt" in tools[0].text
+ assert "Chapter 1" in tools[1].text
+ assert "read_file" in tools[1].text and "textbook.txt" in tools[1].text
+ assert tools[0].meta["merge_id"] == tools[1].meta["merge_id"]
+ assert seen[0].meta["merge_id"] != seen[-1].meta["merge_id"]
+
+
+async def test_late_tool_update_does_not_reset_an_answer(monkeypatch):
+ result, _ = await _consult(
+ monkeypatch,
+ {"type": "tool_call", "toolCallId": "t1", "toolName": "read_file"},
+ {"type": "text", "data": "The answer is "},
+ {"type": "tool_call_update", "toolCallId": "t1", "status": "completed"},
+ {"type": "text", "data": "42."},
+ {"type": "end", "stopReason": "end_turn"},
+ )
+ assert result.success and result.final_text == "The answer is 42."
+
+
+ "reason", ["cancelled", "max_tokens", "max_turn_requests", "refusal", "", None]
+)
+async def test_abnormal_stop_is_failure_even_with_partial_text(monkeypatch, reason):
+ result, _ = await _consult(
+ monkeypatch,
+ {"type": "text", "data": "partial"},
+ {"type": "end", "stopReason": reason},
+ )
+ assert result.success is False
+ assert "without completing" in result.error
+
+
+async def test_nonzero_exit_does_not_succeed_with_an_answer(monkeypatch):
+ result, _ = await _consult(
+ monkeypatch,
+ {"type": "text", "data": "partial answer"},
+ {"type": "end", "stopReason": "end_turn"},
+ exit_code="1",
+ )
+ assert result.success is False
+ assert "code 1" in result.error
+
+
+async def test_error_is_preserved_and_stderr_cannot_spoof_protocol(monkeypatch):
+ result, seen = await _consult(
+ monkeypatch,
+ ("stderr", '{"type":"end","stopReason":"end_turn","sessionId":"wrong"}'),
+ {"type": "error", "message": "Authentication required; run grok login"},
+ exit_code="1",
+ session_id="original",
+ )
+ assert result.success is False
+ assert "grok login" in result.error
+ assert result.session_id == "original"
+ assert seen[0].kind == "log"
+
+
+ "events,error",
+ [
+ ([], "without a completion"),
+ ([{"type": "text", "data": "partial"}], "without a completion"),
+ ([{"type": "end", "stopReason": "end_turn"}], "without an answer"),
+ ([("stdout", '{"type":"thought","data":"private truncated')], "invalid streaming JSON"),
+ ([[]], "invalid streaming event"),
+ ],
+)
+async def test_empty_truncated_or_malformed_streams_fail(monkeypatch, events, error):
+ result, seen = await _consult(monkeypatch, *events)
+ assert result.success is False
+ assert error in result.error
+ assert "private truncated" not in repr(seen)
+
+
+async def test_future_events_log_only_the_type(monkeypatch):
+ _, seen = await _consult(monkeypatch, {"type": "future_event", "data": "private marker"})
+ assert seen[0].text == "Grok CLI: future_event"
+ assert "private marker" not in repr(seen)
+
+
+async def test_images_fail_explicitly_without_starting_cli(monkeypatch):
+ async def stream(*args, **kwargs):
+ pytest.fail("unsupported images must not start Grok")
+ yield
+
+ monkeypatch.setattr("deeptutor.services.subagent.grok.stream_process_lines", stream)
+ seen = []
+
+ async def on_event(event):
+ seen.append(event)
+
+ result = await GrokBackend().consult("describe", on_event=on_event, images=["/tmp/a.png"])
+ assert result.success is False
+ assert "image forwarding" in result.error
+ assert len(seen) == 1
+
+
+async def test_cancellation_propagates_and_closes_process_stream(monkeypatch):
+ closed = False
+
+ async def stream(*args, **kwargs):
+ nonlocal closed
+ try:
+ raise asyncio.CancelledError
+ yield
+ finally:
+ closed = True
+
+ monkeypatch.setattr("deeptutor.services.subagent.grok.stream_process_lines", stream)
+
+ async def on_event(event):
+ pytest.fail("cancellation must not become an error result")
+
+ with pytest.raises(asyncio.CancelledError):
+ await GrokBackend().consult("question", on_event=on_event)
+ assert closed
+
+
+async def test_consult_passes_cwd_and_resume_to_the_process(monkeypatch):
+ captured = {}
+
+ async def stream(cmd, cwd=None):
+ captured.update(cmd=cmd, cwd=cwd)
+ yield "stdout", '{"type":"text","data":"ok"}'
+ yield "stdout", '{"type":"end","stopReason":"end_turn"}'
+ yield "exit", "0"
+
+ monkeypatch.setattr("deeptutor.services.subagent.grok.stream_process_lines", stream)
+
+ async def on_event(event):
+ pass
+
+ result = await GrokBackend().consult(
+ "follow up",
+ on_event=on_event,
+ cwd="/project",
+ session_id="saved-session",
+ )
+ assert result.success and result.session_id == "saved-session"
+ assert captured["cwd"] == "/project"
+ assert captured["cmd"][captured["cmd"].index("--resume") + 1] == "saved-session"
+ assert captured["cmd"][captured["cmd"].index("--permission-mode") + 1] == "dontAsk"
+
+
[email protected]("installed,compatible", [(True, True), (True, False), (False, False)])
+async def test_registry_detection_and_options_use_grok_protocol(monkeypatch, installed, compatible):
+ from deeptutor.services.subagent.models import sync_backend_options
+ from deeptutor.services.subagent.registry import get_backend, list_backend_kinds
+
+ async def probe(cmd):
+ assert cmd[0] == "grok"
+ if cmd[-1] == "--version":
+ return installed, "grok 1.0.3" if installed else "not installed"
+ return (
+ True,
+ "--single --resume --permission-mode streaming-json" if compatible else "other CLI",
+ )
+
+ monkeypatch.setattr("deeptutor.services.subagent.grok.probe_version", probe)
+ assert "grok" in list_backend_kinds()
+ assert get_backend("grok").local_cli is True
+ detected = await get_backend("grok").detect()
+ options = await sync_backend_options("grok")
+ assert detected.available is options.available is (installed and compatible)
+ assert options.kind == "grok"
+ assert options.allow_custom_model and options.models == [] and options.efforts == []
+ if not options.available:
+ assert "xAI" in options.detail and "grok login" in options.detail
diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.py
index 8956f57a5..fe69df337 100644
--- a/tests/services/test_subagent_backends.py
+++ b/tests/services/test_subagent_backends.py
@@ -935,6 +935,7 @@ async def test_detect_all_excludes_partner_backend() -> None:
assert kinds <= {
"claude_code",
"codex",
+ "grok",
"antigravity",
"kimi",
"opencode",
diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsx
index 938d863c3..9e3e6af84 100644
--- a/web/components/agents/ConnectedAgents.tsx
+++ b/web/components/agents/ConnectedAgents.tsx
@@ -37,6 +37,7 @@ type Lang = { zh: string; en: string };
function backendLabel(kind: string, tr: (l: Lang) => string): string {
if (kind === "claude_code") return "Claude Code";
if (kind === "codex") return "Codex";
+ if (kind === "grok") return "Grok CLI";
if (kind === "antigravity") return "Antigravity CLI";
if (kind === "kimi") return "Kimi CLI";
if (kind === "opencode") return "opencode";
diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsx
index acad02fb8..6db1a7928 100644
--- a/web/components/agents/agent-icons.tsx
+++ b/web/components/agents/agent-icons.tsx
@@ -72,6 +72,28 @@ export function CodexGlyph({ size = 16, ...props }: GlyphProps) {
);
}
+// A neutral terminal glyph for Grok CLI, not an unofficial reproduction of a
+// brand mark. It stays readable in both light and dark agent menus.
+export function GrokGlyph({ size = 16, ...props }: GlyphProps) {
+ return (
+ <svg
+ width={size}
+ height={size}
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.8"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ {...props}
+ >
+ <rect x="2" y="3" width="20" height="18" rx="4" />
+ <path d="m7 8 4 4-4 4m7 0h3" />
+ </svg>
+ );
+}
+
// Gemini's four-point spark, in the brand blue→violet gradient.
export function GeminiGlyph({ size = 16, ...props }: GlyphProps) {
const gradientId = useId();
@@ -205,6 +227,7 @@ export type AgentGlyph = ComponentType<GlyphProps>;
export function agentGlyph(kind: string | undefined): AgentGlyph | null {
if (kind === "claude_code") return ClaudeGlyph;
if (kind === "codex") return CodexGlyph;
+ if (kind === "grok") return GrokGlyph;
// Antigravity uses Google's Gemini mark, but Gemini CLI itself is retired.
if (kind === "antigravity") return GeminiGlyph;
if (kind === "kimi") return KimiGlyph;
diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsx
index a07edeefd..3e67e0637 100644
--- a/web/components/settings/SubagentSettingsEditor.tsx
+++ b/web/components/settings/SubagentSettingsEditor.tsx
@@ -63,7 +63,7 @@ const DEFAULTS: Required<
/**
* Which knobs each backend kind actually honors — the editor renders from this
* table instead of per-kind branches. Mirrors what the Python backend reads:
- * e.g. only Claude Code / Antigravity use `permission_mode`, only Codex has its
+ * e.g. Claude Code / Antigravity / Grok use `permission_mode`, only Codex has its
* sandbox family, kimi/hermes/opencode/mimo take the `auto_approve` switch.
*/
type KindFeatures = {
@@ -95,6 +95,15 @@ const KIND_FEATURES: Record<string, KindFeatures> = {
thinking: false,
forwardImages: true,
},
+ grok: {
+ effort: true,
+ systemPrompt: true,
+ permissionMode: true,
+ codexSandbox: false,
+ autoApprove: false,
+ thinking: false,
+ forwardImages: false,
+ },
antigravity: {
effort: true, // --effort low|medium|high
systemPrompt: true,
@@ -176,6 +185,7 @@ const FALLBACK_FEATURES: KindFeatures = KIND_FEATURES.claude_code;
const DISPLAY_NAMES: Record<string, string> = {
claude_code: "Claude Code",
codex: "Codex",
+ grok: "Grok CLI",
kimi: "Kimi CLI",
opencode: "opencode",
mimo: "MiMo Code",
@@ -188,6 +198,10 @@ const DISPLAY_NAMES: Record<string, string> = {
// Per-kind flavor for the system-prompt section: how the instruction reaches
// the agent (a real flag, a native prompt field, or a first-message prefix).
const SYSTEM_PROMPT_HINT: Record<string, Lang> = {
+ grok: {
+ zh: "通过 Grok CLI 的 rules 参数传入额外教学或委派指令。",
+ en: "Additional teaching or delegation instructions are passed through Grok CLI's rules option.",
+ },
claude_code: {
zh: "追加到该智能体的系统提示(--append-system-prompt)。",
en: "Appended to the agent's system prompt (--append-system-prompt).",
@@ -244,6 +258,42 @@ const PERMISSION_MODES: { value: string; label: Lang }[] = [
},
];
+const GROK_PERMISSION_MODES: { value: string; label: Lang }[] = [
+ {
+ value: "dontAsk",
+ label: {
+ zh: "不询问 · 拒绝需审批操作(默认)",
+ en: "Don't ask · deny approval requests (default)",
+ },
+ },
+ {
+ value: "plan",
+ label: { zh: "Plan(兼容模式)", en: "Plan (compatibility mode)" },
+ },
+ {
+ value: "default",
+ label: { zh: "默认权限", en: "Default permissions" },
+ },
+ {
+ value: "acceptEdits",
+ label: { zh: "自动接受编辑", en: "Accept edits automatically" },
+ },
+ {
+ value: "auto",
+ label: { zh: "自动评估权限", en: "Automatically evaluate permissions" },
+ },
+ {
+ value: "bypassPermissions",
+ label: { zh: "绕过权限", en: "Bypass permissions" },
+ },
+];
+
+function defaultsForKind(kind: string): typeof DEFAULTS {
+ return kind === "grok"
+ ? { ...DEFAULTS, permission_mode: "dontAsk" }
+ : DEFAULTS;
+}
+
const SANDBOXES: { value: string; label: Lang }[] = [
{ value: "read-only", label: { zh: "只读", en: "Read-only" } },
{
@@ -276,7 +326,9 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
const tr = useCallback((l: Lang) => (zh ? l.zh : l.en), [zh]);
const [options, setOptions] = useState<SubagentBackendOptions | null>(null);
- const [config, setConfig] = useState<SubagentBackendConfig>({ ...DEFAULTS });
+ const [config, setConfig] = useState<SubagentBackendConfig>({
+ ...defaultsForKind(kind),
+ });
const [customModel, setCustomModel] = useState(false);
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
@@ -300,7 +352,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
]);
setOptions(opts);
const stored = settings.backends?.[kind] ?? {};
- setConfig({ ...DEFAULTS, ...stored });
+ setConfig({ ...defaultsForKind(kind), ...stored });
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
@@ -345,6 +397,8 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
const features = KIND_FEATURES[kind] ?? FALLBACK_FEATURES;
const isRemote = kind === "hermes_remote";
+ const isGrok = kind === "grok";
+ const permissionModes = isGrok ? GROK_PERMISSION_MODES : PERMISSION_MODES;
const knownSlugs = useMemo(
() => new Set((options?.models ?? []).map((m) => m.slug)),
[options],
@@ -429,10 +483,15 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
zh: "检查已配置网关的连通性与认证状态。",
en: "Check connectivity and authentication for the configured gateway.",
})
- : tr({
- zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",
- en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",
- })
+ : isGrok
+ ? tr({
+ zh: "检测后端环境中的 Grok CLI。模型和推理强度可留空使用 CLI 默认值,或手动填写。",
+ en: "Detect Grok CLI in the backend environment. Leave model and reasoning effort blank for CLI defaults, or enter them manually.",
+ })
+ : tr({
+ zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",
+ en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",
+ })
}
>
<SettingRow
@@ -477,20 +536,25 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
<SettingRow
title={tr({ zh: "模型列表", en: "Model list" })}
description={
- options.synced_at
+ isGrok
? tr({
- zh: `上次同步:${formatTs(options.synced_at, zh)}`,
- en: `Last synced: ${formatTs(options.synced_at, zh)}`,
+ zh: "不预设模型列表;请填写当前 Grok CLI 支持的模型名。同步仅重新检测 CLI。",
+ en: "No model catalog is assumed. Enter a model supported by your Grok CLI; sync only detects the CLI again.",
})
- : isRemote
+ : options.synced_at
? tr({
- zh: "远程网关当前不提供模型枚举;可以留空使用网关默认值,或手动填写模型名。",
- en: "The remote gateway does not currently enumerate models here; use its default or enter a model name manually.",
- })
- : tr({
- zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",
- en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",
+ zh: `上次同步:${formatTs(options.synced_at, zh)}`,
+ en: `Last synced: ${formatTs(options.synced_at, zh)}`,
})
+ : isRemote
+ ? tr({
+ zh: "远程网关当前不提供模型枚举;可以留空使用网关默认值,或手动填写模型名。",
+ en: "The remote gateway does not currently enumerate models here; use its default or enter a model name manually.",
+ })
+ : tr({
+ zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",
+ en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",
+ })
}
control={
isRemote ? (
@@ -617,6 +681,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
control={
<div className="flex w-[260px] flex-col items-end gap-2">
<select
+ aria-label={tr({ zh: "模型", en: "Model" })}
className={selectClass}
disabled={busy}
value={showCustomModel ? CUSTOM : (config.model ?? "")}
@@ -640,6 +705,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
</select>
{showCustomModel && (
<input
+ aria-label={tr({ zh: "自定义模型", en: "Custom model" })}
className={inputClass}
disabled={busy}
placeholder={tr({
@@ -662,23 +728,45 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
<SettingRow
title={tr({ zh: "推理强度", en: "Reasoning effort" })}
control={
- <select
- className={`${selectClass} w-[260px]`}
- disabled={busy || effortChoices.length === 0}
- value={config.effort ?? ""}
- onChange={(e) => void save({ effort: e.target.value })}
- >
- <option value="">
- {isRemote
- ? tr({ zh: "网关默认", en: "Gateway default" })
- : tr({ zh: "CLI 默认", en: "CLI default" })}
- </option>
- {effortChoices.map((eff) => (
- <option key={eff} value={eff}>
- {eff}
+ isGrok ? (
+ <input
+ aria-label={tr({
+ zh: "推理强度",
+ en: "Reasoning effort",
+ })}
+ className={`${inputClass} w-[260px]`}
+ disabled={busy}
+ placeholder={tr({
+ zh: "留空使用 CLI 默认值",
+ en: "Blank uses CLI default",
+ })}
+ value={config.effort ?? ""}
+ onChange={(e) =>
+ setConfig((p) => ({ ...p, effort: e.target.value }))
+ }
+ onBlur={(e) =>
+ void save({ effort: e.target.value.trim() })
+ }
+ />
+ ) : (
+ <select
+ className={`${selectClass} w-[260px]`}
+ disabled={busy || effortChoices.length === 0}
+ value={config.effort ?? ""}
+ onChange={(e) => void save({ effort: e.target.value })}
+ >
+ <option value="">
+ {isRemote
+ ? tr({ zh: "网关默认", en: "Gateway default" })
+ : tr({ zh: "CLI 默认", en: "CLI default" })}
</option>
- ))}
- </select>
+ {effortChoices.map((eff) => (
+ <option key={eff} value={eff}>
+ {eff}
+ </option>
+ ))}
+ </select>
+ )
}
/>
)}
@@ -696,6 +784,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
>
<div className="py-4">
<textarea
+ aria-label={tr({ zh: "系统提示", en: "System prompt" })}
className={`${inputClass} min-h-[96px] resize-y leading-relaxed`}
disabled={busy}
placeholder={tr({
@@ -722,20 +811,31 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {
{features.permissionMode && (
<SettingRow
title={tr({ zh: "权限模式", en: "Permission mode" })}
- description={tr({
- zh: "非「绕过权限」的模式可能让无人值守的运行卡住等待确认。",
- en: "Modes other than bypass may stall an unattended run waiting for a prompt.",
- })}
+ description={
+ isGrok
+ ? tr({
+ zh: "默认 dontAsk 会拒绝需审批的操作。其它模式遵循 Grok CLI 权限规则;无人值守运行无法回答交互审批。",
+ en: "The default dontAsk mode denies operations that need approval. Other modes follow Grok CLI permissions; unattended runs cannot answer interactive prompts.",
+ })
+ : tr({
+ zh: "非「绕过权限」的模式可能让无人值守的运行卡住等待确认。",
+ en: "Modes other than bypass may stall an unattended run waiting for a prompt.",
+ })
+ }
control={
<select
+ aria-label={tr({ zh: "权限模式", en: "Permission mode" })}
className={`${selectClass} w-[260px]`}
disabled={busy}
- value={config.permission_mode ?? DEFAULTS.permission_mode}
+ value={
+ config.permission_mode ??
+ defaultsForKind(kind).permission_mode
+ }
onChange={(e) =>
void save({ permission_mode: e.target.value })
}
>
- {PERMISSION_MODES.map((o) => (
+ {permissionModes.map((o) => (
<option key={o.value} value={o.value}>
{tr(o.label)}
</option>
diff --git a/web/features/settings/navigation/settings-nav.ts b/web/features/settings/navigation/settings-nav.ts
index 96aa66b96..adbccc3a2 100644
--- a/web/features/settings/navigation/settings-nav.ts
+++ b/web/features/settings/navigation/settings-nav.ts
@@ -34,6 +34,7 @@ import {
CodexGlyph,
DeepSeekGlyph,
GeminiGlyph,
+ GrokGlyph,
HermesGlyph,
KimiGlyph,
MimoGlyph,
@@ -304,6 +305,18 @@ const AGENT_CHILDREN: SettingsLeaf[] = [
tile: "bg-blue-500/10 text-blue-600 dark:text-blue-400",
adminOnly: true,
},
+ {
+ key: "agent-grok",
+ href: "/settings#agent-grok",
+ label: { zh: "Grok CLI", en: "Grok CLI" },
+ blurb: {
+ zh: "DeepTutor 调用本机 Grok CLI 时的模型、推理强度与权限模式。",
+ en: "Model, reasoning effort, and permission mode for the local Grok CLI.",
+ },
+ icon: GrokGlyph as unknown as LucideIcon,
+ tile: "bg-zinc-500/10 text-zinc-700 dark:text-zinc-300",
+ adminOnly: true,
+ },
{
// Gemini CLI's supported replacement.
key: "agent-antigravity",
@@ -563,6 +576,7 @@ const STORAGE_PATHS: Record<string, string> = {
capabilities: "data/user/settings/main.yaml · agents.yaml",
"agent-claude-code": "data/user/settings/subagent.json",
"agent-codex": "data/user/settings/subagent.json",
+ "agent-grok": "data/user/settings/subagent.json",
"agent-antigravity": "data/user/settings/subagent.json",
"agent-kimi": "data/user/settings/subagent.json",
"agent-opencode": "data/user/settings/subagent.json",
diff --git a/web/features/settings/sections/AgentsSettingsSection.tsx b/web/features/settings/sections/AgentsSettingsSection.tsx
index d41ab2dcb..99ff6c942 100644
--- a/web/features/settings/sections/AgentsSettingsSection.tsx
+++ b/web/features/settings/sections/AgentsSettingsSection.tsx
@@ -9,6 +9,7 @@ const ClaudeCodeAgentSettingsPage = () => (
<SubagentSettingsEditor kind="claude_code" />
);
const CodexAgentSettingsPage = () => <SubagentSettingsEditor kind="codex" />;
+const GrokAgentSettingsPage = () => <SubagentSettingsEditor kind="grok" />;
const AntigravityAgentSettingsPage = () => (
<SubagentSettingsEditor kind="antigravity" />
);
@@ -31,6 +32,7 @@ const DeepSeekHarnessAgentSettingsPage = () => (
const AGENT_SECTIONS = [
{ key: "agent-claude-code", Component: ClaudeCodeAgentSettingsPage },
{ key: "agent-codex", Component: CodexAgentSettingsPage },
+ { key: "agent-grok", Component: GrokAgentSettingsPage },
{ key: "agent-antigravity", Component: AntigravityAgentSettingsPage },
{ key: "agent-kimi", Component: KimiAgentSettingsPage },
{ key: "agent-opencode", Component: OpencodeAgentSettingsPage },
diff --git a/web/tests/subagent-grok-settings.spec.tsx b/web/tests/subagent-grok-settings.spec.tsx
new file mode 100644
index 000000000..ac2cf6161
--- /dev/null
+++ b/web/tests/subagent-grok-settings.spec.tsx
@@ -0,0 +1,136 @@
+import {
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";
+import {
+ getBackendOptions,
+ getSubagentSettings,
+ updateSubagentSettings,
+} from "@/lib/subagents-api";
+
+vi.mock("react-i18next", () => ({
+ useTranslation: () => ({ i18n: { language: "en" } }),
+}));
+
+vi.mock("@/lib/subagents-api", () => ({
+ getBackendOptions: vi.fn(),
+ getSubagentSettings: vi.fn(),
+ updateSubagentSettings: vi.fn(),
+ syncBackendOptions: vi.fn(),
+}));
+
+beforeEach(() => {
+ vi.mocked(getBackendOptions).mockResolvedValue([
+ {
+ kind: "grok",
+ display_name: "Grok CLI",
+ available: true,
+ version: "installed",
+ default_model: "",
+ models: [],
+ efforts: [],
+ allow_custom_model: true,
+ synced_at: "",
+ detail: "",
+ },
+ ]);
+ vi.mocked(getSubagentSettings).mockResolvedValue({
+ consult_budget: 5,
+ backends: {},
+ });
+ vi.mocked(updateSubagentSettings).mockResolvedValue({
+ consult_budget: 5,
+ backends: {},
+ });
+});
+
+describe("Grok CLI settings", () => {
+ it("defaults to dontAsk and exposes only supported permission and input controls", async () => {
+ render(<SubagentSettingsEditor kind="grok" />);
+
+ const permissions = await screen.findByRole("combobox", {
+ name: "Permission mode",
+ });
+ expect(permissions).toHaveValue("dontAsk");
+ expect(
+ within(permissions)
+ .getAllByRole("option")
+ .map((option) => (option as HTMLOptionElement).value),
+ ).toEqual([
+ "dontAsk",
+ "plan",
+ "default",
+ "acceptEdits",
+ "auto",
+ "bypassPermissions",
+ ]);
+ expect(
+ screen.getByRole("textbox", { name: "Reasoning effort" }),
+ ).toBeEnabled();
+ expect(screen.queryByText("Forward images")).not.toBeInTheDocument();
+ expect(screen.queryByText("Auto-approve")).not.toBeInTheDocument();
+ expect(updateSubagentSettings).not.toHaveBeenCalled();
+
+ fireEvent.change(permissions, { target: { value: "plan" } });
+ await waitFor(() =>
+ expect(updateSubagentSettings).toHaveBeenCalledWith({
+ backends: { grok: { permission_mode: "plan" } },
+ }),
+ );
+ });
+
+ it("saves a manually entered model, effort, and rules without overwriting permissions", async () => {
+ vi.mocked(getSubagentSettings).mockResolvedValue({
+ consult_budget: 5,
+ backends: { grok: { permission_mode: "plan" } },
+ });
+ render(<SubagentSettingsEditor kind="grok" />);
+
+ const modelSelector = await screen.findByRole("combobox", {
+ name: "Model",
+ });
+ expect(within(modelSelector).getAllByRole("option")).toHaveLength(2);
+ fireEvent.change(modelSelector, { target: { value: "__custom__" } });
+ const model = screen.getByRole("textbox", { name: "Custom model" });
+ fireEvent.change(model, { target: { value: " user-model " } });
+ fireEvent.blur(model);
+ await waitFor(() =>
+ expect(updateSubagentSettings).toHaveBeenCalledWith({
+ backends: { grok: { model: "user-model" } },
+ }),
+ );
+
+ const effort = screen.getByRole("textbox", { name: "Reasoning effort" });
+ await waitFor(() => expect(effort).toBeEnabled());
+ fireEvent.change(effort, { target: { value: " high " } });
+ fireEvent.blur(effort);
+ await waitFor(() =>
+ expect(updateSubagentSettings).toHaveBeenCalledWith({
+ backends: { grok: { effort: "high" } },
+ }),
+ );
+
+ const rules = screen.getByRole("textbox", { name: "System prompt" });
+ await waitFor(() => expect(rules).toBeEnabled());
+ fireEvent.change(rules, {
+ target: { value: "Check the textbook before explaining." },
+ });
+ fireEvent.blur(rules);
+ await waitFor(() =>
+ expect(updateSubagentSettings).toHaveBeenCalledWith({
+ backends: {
+ grok: { system_prompt: "Check the textbook before explaining." },
+ },
+ }),
+ );
+ expect(
+ screen.getByRole("combobox", { name: "Permission mode" }),
+ ).toHaveValue("plan");
+ });
+});
diff --git a/web/tests/subagent-harnesses.test.ts b/web/tests/subagent-harnesses.test.ts
index 0e66b1281..abbe148bd 100644
--- a/web/tests/subagent-harnesses.test.ts
+++ b/web/tests/subagent-harnesses.test.ts
@@ -7,6 +7,7 @@ const readWebFile = (...parts: string[]) =>
readFileSync(path.join(process.cwd(), ...parts), "utf8");
const HARNESSES = [
+ { kind: "grok", route: "grok", label: "Grok CLI" },
{ kind: "hermes", route: "hermes", label: "Hermes Agent" },
{ kind: "openclaw", route: "openclaw", label: "OpenClaw" },
{