DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
myagent update - mimo code, gemini cli, opencode, kimi cli
Bingxi Zhao (Frank)2fcc8b18f9cf
diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.pyindex 2174cf2bb..910d584e7 100644--- a/deeptutor/api/routers/subagents.py+++ b/deeptutor/api/routers/subagents.py@@ -1,8 +1,9 @@"""Subagent connections API.Backs the "My Agents → connected agents" feature: detect which local agent CLIs-(Claude Code / Codex) are installed on this machine, connect one as a pointer KB-the chat composer can select, and configure the consult budget. Connections are+(Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code) are installed on+this machine, connect one as a pointer KB the chat composer can select, and+configure the consult budget. Connections arestored as ``type: subagent`` knowledge bases (per-user, via the KB manager), sothey ride the same selection/persistence path as the other connected KB types —the subagent capability drives them live, nothing is indexed.diff --git a/deeptutor/capabilities/subagent/tools.py b/deeptutor/capabilities/subagent/tools.pyindex 930a2a146..7d76b2b38 100644--- a/deeptutor/capabilities/subagent/tools.py+++ b/deeptutor/capabilities/subagent/tools.py@@ -46,8 +46,9 @@ class ConsultSubagentTool(BaseTool):return ToolDefinition(name="consult_subagent",description=(- "Ask the connected external agent (the user's local Claude Code / "- "Codex, or one of their partners) a focused question and get its "+ "Ask the connected external agent (a local agent CLI on the user's "+ "machine — Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo "+ "Code — 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 ""files and tools; a partner answers with its own persona, library and ""skills. Either way its full step-by-step run is shown to the user "diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.pyindex c64705739..bbc61898b 100644--- a/deeptutor/services/subagent/__init__.py+++ b/deeptutor/services/subagent/__init__.py@@ -1,11 +1,13 @@"""Subagent driver layer — drive a user's local agent CLI as a subagent.-DeepTutor runs on the same machine as the user's configured Claude Code / Codex,-so the backend can spawn those CLIs directly and stream back every native event.-This package is the decoupled core of that: backends that know one CLI each, a-shared streaming-subprocess primitive, and the value types that cross into the-chat capability. It knows nothing about the chat loop, KBs, or HTTP — those wire-in through the consult tool and the API.+DeepTutor runs on the same machine as the user's configured agent CLIs — Claude+Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code — 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+decoupled core of that: backends that know one CLI each, a shared+streaming-subprocess primitive, and the value types that cross into the chat+capability. It knows nothing about the chat loop, KBs, or HTTP — those wire in+through the consult tool and the API."""from __future__ import annotationsdiff --git a/deeptutor/services/subagent/config.py b/deeptutor/services/subagent/config.pyindex 50b02102d..5a4db2a33 100644--- a/deeptutor/services/subagent/config.py+++ b/deeptutor/services/subagent/config.py@@ -59,8 +59,16 @@ class BackendConfig:network_access: bool = False# Codex: --ephemeral — don't persist the session under ~/.codex/sessions.ephemeral: bool = False+ # Kimi / opencode / MiMo: answer the CLI's permission asks affirmatively so+ # a headless run never stalls (kimi --yolo; the opencode family's+ # permission.asked replies). Same trust model as CC's bypassPermissions.+ auto_approve: bool = True+ # Kimi: stream the model's thinking (--thinking / --no-thinking). The+ # opencode family always streams reasoning over its event bus.+ thinking: bool = True# Forward image attachments from the chat turn to the agent (CC image input- # / Codex -i). Off by default — the user opts in per backend.+ # / Codex -i / Gemini @path / opencode-family file parts). Off by default —+ # the user opts in per backend. Kimi has no headless image input.forward_images: bool = Falseextra_args: list[str] = field(default_factory=list)@@ -91,6 +99,8 @@ def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:"approval": cfg.approval,"network_access": cfg.network_access,"ephemeral": cfg.ephemeral,+ "auto_approve": cfg.auto_approve,+ "thinking": cfg.thinking,"forward_images": cfg.forward_images,"extra_args": list(cfg.extra_args),}@@ -119,6 +129,8 @@ def _coerce_backend(raw: Any) -> BackendConfig:approval=str(raw.get("approval") or base.approval),network_access=bool(raw.get("network_access", base.network_access)),ephemeral=bool(raw.get("ephemeral", base.ephemeral)),+ auto_approve=bool(raw.get("auto_approve", base.auto_approve)),+ thinking=bool(raw.get("thinking", base.thinking)),forward_images=bool(raw.get("forward_images", base.forward_images)),extra_args=[str(a) for a in extra] if isinstance(extra, list) else [],)diff --git a/deeptutor/services/subagent/gemini.py b/deeptutor/services/subagent/gemini.pynew file mode 100644index 000000000..b01154f6d--- /dev/null+++ b/deeptutor/services/subagent/gemini.py@@ -0,0 +1,301 @@+"""Gemini CLI backend — drive the local ``gemini`` CLI in headless print mode.++Uses ``gemini -p <question> --output-format stream-json`` (stream-json exists+since v0.11.0): a newline-delimited JSON event stream with a small, fixed event+vocabulary — ``init`` (session id + model), ``message`` (assistant text arrives+as incremental ``delta`` chunks; there is no final aggregated message event),+``tool_use`` / ``tool_result`` (paired by ``tool_id``), ``error`` and a closing+``result``. We accumulate the deltas per text block so the answer types out+live in the sidebar, exactly like Claude Code's partial messages.++Two headless quirks worth knowing: thought summaries are dropped by the CLI's+non-interactive loop (so no reasoning channel), and the policy engine treats+``ask_user`` as deny — mutating tools only run under ``--approval-mode=yolo``+or ``auto_edit``, which is why the config's permission mode maps onto those.++Auth and config are inherited automatically: the spawned ``gemini`` reads the+user's existing ``~/.gemini`` credentials (or ``GEMINI_API_KEY``-style env+vars), so no token is ever handled here. Sessions are project-scoped on disk,+so resuming requires the same working directory — a connection's fixed ``cwd``+satisfies that by construction.+"""++from __future__ import annotations++import json+import logging+import os+from typing import Any++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.process import probe_version, stream_process_lines+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_MAX_FIELD_CHARS = 4000+_TOOL_HEADER_CHARS = 160++# The stored permission mode uses Claude Code's spellings as the canonical+# vocabulary (the two CLIs' modes are semantically parallel); translate to+# Gemini's ``--approval-mode`` values here. Unknown values fall back to yolo —+# a headless run that blocks on approval would hang the turn forever.+_APPROVAL_MODES = {+ "bypassPermissions": "yolo",+ "acceptEdits": "auto_edit",+ "default": "default",+ "plan": "plan",+}++# The salient argument to surface in a tool header (same idea as Claude Code's+# renderer): show ``Shell(cmd …)`` / ``ReadFile(path)`` instead of raw JSON.+_TOOL_PRIMARY_ARGS = (+ "command",+ "file_path",+ "path",+ "pattern",+ "query",+ "url",+ "prompt",+ "description",+)+++class GeminiBackend(SubagentBackend):+ kind = "gemini"+ display_name = "Gemini CLI"+ cli_command = "gemini"++ async def detect(self) -> DetectResult:+ ok, text = await probe_version([self.cli_command, "--version"])+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else (text or "gemini CLI not found on PATH"),+ )++ def _build_command(+ self,+ question: str,+ *,+ session_id: str | None,+ config: BackendConfig,+ images: list[str] | None = None,+ ) -> list[str]:+ prompt = question+ # No system-prompt flag exists, so the delegate instruction is prepended+ # once, on the session-creating consult; resumed sessions already have it.+ if config.system_prompt.strip() and not session_id:+ prompt = f"{config.system_prompt.strip()}\n\n{question}"+ # Images attach via the @path syntax (routed through read_many_files into+ # inline parts); --include-directories admits the staging dir, which is+ # outside the working dir.+ if images:+ listing = " ".join(f"@{path}" for path in images)+ prompt = f"{prompt}\n\n{listing}"+ cmd = [+ self.cli_command,+ "-p",+ prompt,+ "--output-format",+ "stream-json",+ "--approval-mode",+ _APPROVAL_MODES.get(config.permission_mode, "yolo"),+ ]+ if images:+ cmd += ["--include-directories", os.path.dirname(images[0])]+ if session_id:+ cmd += ["--resume", session_id]+ if config.model:+ cmd += ["--model", config.model]+ cmd += list(config.extra_args)+ 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; ignored here+ ) -> ConsultResult:+ config = config or BackendConfig()+ cmd = self._build_command(question, session_id=session_id, config=config, images=images)+ result = ConsultResult(session_id=session_id)+ # Delta accumulator: assistant text arrives as chunks with no final+ # aggregate, so we grow per-block running text; a tool_use closes the+ # current block so post-tool text streams as a new row.+ stream: dict[str, Any] = {"blocks": [], "open": False}++ 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 {}))++ try:+ async for channel, line in stream_process_lines(cmd, cwd=cwd):+ if channel == "exit":+ if line != "0" and result.success and not result.final_text:+ result.success = False+ result.error = f"gemini exited with code {line}"+ await emit(EVENT_ERROR, result.error, {"returncode": line})+ continue+ if channel == "stderr":+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stderr"})+ continue+ event = _parse_json(line)+ if event is None:+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stdout"})+ continue+ await self._handle_event(event, result, stream, emit)+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn+ logger.warning("gemini consult failed: %s", exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})++ if not result.final_text:+ result.final_text = "\n\n".join(b for b in stream["blocks"] if b.strip()).strip()+ return result++ async def _handle_event(+ self,+ event: dict[str, Any],+ result: ConsultResult,+ stream: dict[str, Any],+ emit: Any,+ ) -> None:+ etype = str(event.get("type") or "")++ if etype == "init":+ sid = str(event.get("session_id") or "")+ if sid:+ result.session_id = sid+ model = str(event.get("model") or "")+ await emit(EVENT_LOG, f"Session started{f' · {model}' if model else ''}", event)+ return++ if etype == "message":+ if str(event.get("role") or "") != "assistant":+ return # the echoed user prompt; the consult tool already heads the round+ content = str(event.get("content") or "")+ if not content:+ return+ blocks: list[str] = stream["blocks"]+ if event.get("delta") and stream["open"] and blocks:+ blocks[-1] += content+ else:+ blocks.append(content)+ stream["open"] = True+ await emit(+ EVENT_TEXT,+ blocks[-1].strip(),+ event,+ {"merge_id": f"txt:{len(blocks) - 1}"},+ )+ return++ if etype == "tool_use":+ stream["open"] = False # post-tool text starts a fresh block/row+ await emit(EVENT_TOOL, _render_tool_use(event), event)+ return++ if etype == "tool_result":+ await emit(EVENT_TOOL_RESULT, _render_tool_result(event), event)+ return++ if etype == "error":+ message = str(event.get("message") or "gemini reported an error")+ if str(event.get("severity") or "") == "warning":+ await emit(EVENT_LOG, message, event)+ else:+ result.error = message+ await emit(EVENT_ERROR, message, event)+ return++ if etype == "result":+ if str(event.get("status") or "") == "error":+ result.success = False+ error = event.get("error")+ if isinstance(error, dict) and error.get("message"):+ result.error = str(error["message"])+ return++ # Unknown event type — keep it visible as a log rather than dropping it.+ await emit(EVENT_LOG, _compact(event), event)+++def _parse_json(line: str) -> dict[str, Any] | None:+ line = line.strip()+ if not line or line[0] not in "{[":+ return None+ try:+ parsed = json.loads(line)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _render_tool_use(event: dict[str, Any]) -> str:+ name = str(event.get("tool_name") or "tool")+ params = event.get("parameters")+ if not isinstance(params, dict) or not params:+ return name+ for key in _TOOL_PRIMARY_ARGS:+ value = params.get(key)+ if isinstance(value, str) and value.strip():+ return f"{name}({_inline(value)})"+ return f"{name}({_inline(_compact(params))})"+++def _render_tool_result(event: dict[str, Any]) -> str:+ if str(event.get("status") or "") == "error":+ error = event.get("error")+ message = error.get("message") if isinstance(error, dict) else None+ return _truncate(str(message or "tool failed"))+ # ``output`` is present only when the tool's display result is a plain+ # string; other display shapes arrive as no output at all.+ return _truncate(str(event.get("output") or "")) or "(no output)"+++def _inline(text: str) -> str:+ one_line = " ".join(text.split())+ if len(one_line) > _TOOL_HEADER_CHARS:+ return one_line[:_TOOL_HEADER_CHARS].rstrip() + " …"+ return one_line+++def _compact(obj: Any) -> str:+ try:+ text = json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(obj)+ return _truncate(text)+++def _truncate(text: str) -> str:+ text = text.strip()+ if len(text) > _MAX_FIELD_CHARS:+ return text[:_MAX_FIELD_CHARS].rstrip() + " …"+ return text+++__all__ = ["GeminiBackend"]diff --git a/deeptutor/services/subagent/kimi.py b/deeptutor/services/subagent/kimi.pynew file mode 100644index 000000000..0cbc8ee60--- /dev/null+++ b/deeptutor/services/subagent/kimi.py@@ -0,0 +1,277 @@+"""Kimi CLI backend — drive the local ``kimi`` CLI in headless print mode.++Uses ``kimi --print --output-format stream-json``: a JSONL stream of chat-shaped+messages, one object per line, flushed live at step boundaries. Lines are+discriminated by their ``role`` key — ``assistant`` (text / ``think`` parts /+``tool_calls``), ``tool`` (a tool result), and role-less service lines+(notifications, plan displays). Streaming is message-granular: the CLI merges+its internal token deltas before printing, so the answer lands per step rather+than typing out.++Deliberately restricted to the flag subset shared by both generations of the+CLI — the original ``kimi-cli`` (PyPI) and its successor ``kimi-code`` (npm)+install the same ``kimi`` binary and agree on ``--print`` / ``-p`` /+``--output-format stream-json`` / ``--session`` / ``--yolo`` / ``--thinking``,+so one backend drives whichever the user has (the generations only diverge on+short flags we don't use).++Session continuity uses a trick both generations support: ``--session <uuid>``+with a nonexistent id *creates* the session under that exact id — so we mint+the id ourselves and never parse it from output (it isn't in stdout anyway).+Sessions are keyed by working directory, which a connection pins by design.++Auth and config are inherited automatically from the user's ``~/.kimi`` — no+token is ever handled here. Headless image input is not supported by the CLI.+"""++from __future__ import annotations++import json+import logging+from typing import Any+import uuid++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.process import probe_version, stream_process_lines+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_MAX_FIELD_CHARS = 4000+_TOOL_HEADER_CHARS = 160++# Exit code the CLI uses for retryable provider failures (429/5xx/timeouts).+_RETRYABLE_EXIT = "75"++_TOOL_PRIMARY_ARGS = (+ "command",+ "file_path",+ "path",+ "pattern",+ "query",+ "url",+ "prompt",+ "description",+)+++class KimiBackend(SubagentBackend):+ kind = "kimi"+ display_name = "Kimi CLI"+ cli_command = "kimi"++ async def detect(self) -> DetectResult:+ ok, text = await probe_version([self.cli_command, "--version"])+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else (text or "kimi CLI not found on PATH"),+ )++ def _build_command(+ self,+ question: str,+ *,+ session_id: str,+ fresh_session: bool,+ config: BackendConfig,+ ) -> list[str]:+ prompt = question+ # No system-prompt flag exists, so the delegate instruction is prepended+ # once, on the session-creating consult; resumed sessions already have it.+ if config.system_prompt.strip() and fresh_session:+ prompt = f"{config.system_prompt.strip()}\n\n{question}"+ cmd = [+ self.cli_command,+ "--print",+ "--output-format",+ "stream-json",+ "--session",+ session_id,+ ]+ if config.auto_approve:+ # Auto-approve tool runs; --print already implies --afk (never wait+ # for interactive input), so a headless run cannot stall either way.+ cmd.append("--yolo")+ cmd.append("--thinking" if config.thinking else "--no-thinking")+ if config.model:+ cmd += ["--model", config.model]+ cmd += list(config.extra_args)+ cmd += ["--prompt", prompt]+ 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, # noqa: ARG002 — no headless image input+ partner_id: str | None = None, # noqa: ARG002 — partner-only; ignored here+ ) -> ConsultResult:+ config = config or BackendConfig()+ # Mint the session id ourselves (a nonexistent --session id creates the+ # session under that id), so continuity never depends on parsing output.+ fresh_session = not session_id+ sid = session_id or str(uuid.uuid4())+ cmd = self._build_command(+ question, session_id=sid, fresh_session=fresh_session, config=config+ )+ result = ConsultResult(session_id=sid)++ 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 {}))++ try:+ async for channel, line in stream_process_lines(cmd, cwd=cwd):+ if channel == "exit":+ if line != "0" and result.success and not result.final_text:+ result.success = False+ suffix = " (transient provider error)" if line == _RETRYABLE_EXIT else ""+ result.error = f"kimi exited with code {line}{suffix}"+ await emit(EVENT_ERROR, result.error, {"returncode": line})+ continue+ if channel == "stderr":+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stderr"})+ continue+ event = _parse_json(line)+ if event is None:+ if line.strip():+ await emit(EVENT_LOG, line, {"stream": "stdout"})+ continue+ await self._handle_event(event, result, emit)+ except Exception as exc: # pragma: no cover - defensive: surface, don't crash the turn+ logger.warning("kimi consult failed: %s", exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})++ return result++ async def _handle_event(self, event: dict[str, Any], result: ConsultResult, emit: Any) -> None:+ role = str(event.get("role") or "")++ if role == "assistant":+ for part in _content_parts(event.get("content")):+ ptype = str(part.get("type") or "")+ if ptype == "text":+ text = str(part.get("text") or "").strip()+ if text:+ # Message-granular stream: the latest assistant text is+ # the freshest candidate for the final answer.+ result.final_text = text+ await emit(EVENT_TEXT, text, event)+ elif ptype == "think":+ text = str(part.get("think") or "").strip()+ if text:+ await emit(EVENT_REASONING, text, event)+ for call in event.get("tool_calls") or []:+ if isinstance(call, dict):+ await emit(EVENT_TOOL, _render_tool_call(call), call)+ return++ if role == "tool":+ text = "\n".join(+ str(p.get("text") or "") for p in _content_parts(event.get("content"))+ ).strip()+ await emit(EVENT_TOOL_RESULT, _truncate(text) or "(empty result)", event)+ return++ if role:+ return # an echoed user/system message — nothing to surface++ # Role-less service lines: notifications and plan displays.+ if event.get("category") or event.get("severity"):+ title = str(event.get("title") or "").strip()+ body = str(event.get("body") or "").strip()+ text = " · ".join(p for p in (title, body) if p)+ if text:+ await emit(EVENT_LOG, _truncate(text), event)+ return+ if event.get("file_path") and event.get("content"):+ await emit(EVENT_LOG, f"plan · {event.get('file_path')}", event)+ return+ await emit(EVENT_LOG, _compact(event), event)+++def _content_parts(content: Any) -> list[dict[str, Any]]:+ """Normalize the polymorphic ``content`` — a plain string or a part list."""+ if isinstance(content, str):+ return [{"type": "text", "text": content}] if content else []+ if isinstance(content, list):+ return [p for p in content if isinstance(p, dict)]+ return []+++def _render_tool_call(call: dict[str, Any]) -> str:+ function = call.get("function") if isinstance(call.get("function"), dict) else {}+ name = str(function.get("name") or "tool")+ raw_args = function.get("arguments")+ args: Any = raw_args+ if isinstance(raw_args, str): # arguments arrive JSON-encoded+ try:+ args = json.loads(raw_args)+ except (ValueError, TypeError):+ args = raw_args+ if isinstance(args, dict) and args:+ for key in _TOOL_PRIMARY_ARGS:+ value = args.get(key)+ if isinstance(value, str) and value.strip():+ return f"{name}({_inline(value)})"+ return f"{name}({_inline(_compact(args))})"+ return name+++def _parse_json(line: str) -> dict[str, Any] | None:+ line = line.strip()+ if not line or line[0] not in "{[":+ return None+ try:+ parsed = json.loads(line)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _inline(text: str) -> str:+ one_line = " ".join(text.split())+ if len(one_line) > _TOOL_HEADER_CHARS:+ return one_line[:_TOOL_HEADER_CHARS].rstrip() + " …"+ return one_line+++def _compact(obj: Any) -> str:+ try:+ text = json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(obj)+ return _truncate(text)+++def _truncate(text: str) -> str:+ text = text.strip()+ if len(text) > _MAX_FIELD_CHARS:+ return text[:_MAX_FIELD_CHARS].rstrip() + " …"+ return text+++__all__ = ["KimiBackend"]diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.pyindex 4f2b23b89..62e654a1d 100644--- a/deeptutor/services/subagent/models.py+++ b/deeptutor/services/subagent/models.py@@ -11,10 +11,20 @@ page's "sync" button just re-reads it:* **Claude Code** has no model-list CLI; its ``--model`` takes stable aliases(opus / sonnet / haiku) plus any full name, and ``--effort`` a fixed set — sowe offer those as suggestions and the UI also allows a free-text model.+* **Gemini CLI** models are stable aliases (auto / pro / flash / flash-lite)+ plus any concrete name — curated suggestions, free text allowed.+* **Kimi CLI** has no model-list surface — free text only.+* **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.++Each backend kind maps to one options provider in ``_PROVIDERS`` — adding a+backend means adding a provider here, nothing else changes."""from __future__ import annotations+import asynciofrom dataclasses import dataclass, fieldimport jsonimport logging@@ -39,6 +49,18 @@ _CLAUDE_MODELS = ()_CLAUDE_EFFORTS = ("low", "medium", "high", "xhigh", "max")+# Gemini CLI: ``--model`` takes stable aliases plus any concrete model name.+# There is no reasoning-effort flag (thinking is a settings.json concern).+_GEMINI_MODELS = (+ ("auto", "Auto (recommended)"),+ ("pro", "Gemini Pro"),+ ("flash", "Gemini Flash"),+ ("flash-lite", "Gemini Flash-Lite"),+)++# opencode family: ``--variant`` — provider-relative reasoning effort.+_OPENCODE_EFFORTS = ("minimal", "high", "max")+@dataclass(slots=True)class ModelOption:@@ -178,9 +200,113 @@ async def _codex_options() -> BackendOptions:)+async def _probe(kind: str) -> tuple[bool, str]:+ backend = get_backend(kind)+ if backend is None:+ return False, ""+ return await probe_version([backend.cli_command, "--version"])+++async def _gemini_options() -> BackendOptions:+ ok, version = await _probe("gemini")+ return BackendOptions(+ kind="gemini",+ display_name="Gemini CLI",+ available=ok,+ version=version if ok else "",+ models=[ModelOption(slug=slug, display_name=name) for slug, name in _GEMINI_MODELS],+ efforts=[], # no reasoning-effort flag+ allow_custom_model=True,+ detail="" if ok else (version or "gemini CLI not found on PATH"),+ )+++async def _kimi_options() -> BackendOptions:+ ok, version = await _probe("kimi")+ return BackendOptions(+ kind="kimi",+ display_name="Kimi CLI",+ available=ok,+ version=version if ok else "",+ models=[], # no model-list surface; free text only+ efforts=[],+ allow_custom_model=True,+ detail="" if ok else (version or "kimi CLI not found on PATH"),+ )+++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"]+ if refresh:+ cmd.append("--refresh")+ try:+ process = await asyncio.create_subprocess_exec(+ *cmd,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.DEVNULL,+ )+ out, _ = await asyncio.wait_for(process.communicate(), timeout=60.0 if refresh else 20.0)+ except FileNotFoundError:+ return []+ except (TimeoutError, asyncio.TimeoutError):+ return []+ except Exception: # pragma: no cover - defensive+ logger.warning("failed to enumerate %s models", cli_command, exc_info=True)+ return []+ models: list[ModelOption] = []+ for raw in (out or b"").decode("utf-8", "replace").splitlines():+ slug = raw.strip()+ # Slugs are provider/model tokens; anything with spaces is decoration.+ if not slug or "/" not in slug or " " in slug:+ continue+ models.append(ModelOption(slug=slug, display_name=slug, efforts=list(_OPENCODE_EFFORTS)))+ return models+++async def _opencode_family_options(+ kind: str, display_name: str, *, refresh: bool = False+) -> BackendOptions:+ backend = get_backend(kind)+ cli = backend.cli_command if backend else kind+ ok, version = await _probe(kind)+ models = await _list_cli_models(cli, refresh=refresh) if ok else []+ return BackendOptions(+ kind=kind,+ display_name=display_name,+ available=ok,+ version=version if ok else "",+ models=models,+ efforts=list(_OPENCODE_EFFORTS),+ allow_custom_model=True,+ detail="" if ok else (version or f"{cli} CLI not found on PATH"),+ )+++async def _opencode_options(*, refresh: bool = False) -> BackendOptions:+ return await _opencode_family_options("opencode", "opencode", refresh=refresh)+++async def _mimo_options(*, refresh: bool = False) -> BackendOptions:+ return await _opencode_family_options("mimo", "MiMo Code", refresh=refresh)+++# One provider per backend kind — the discovery order is the settings order.+_PROVIDERS = {+ "claude_code": _claude_options,+ "codex": _codex_options,+ "gemini": _gemini_options,+ "kimi": _kimi_options,+ "opencode": _opencode_options,+ "mimo": _mimo_options,+}++async def list_backend_options() -> list[BackendOptions]:"""Synced model/effort options for every backend (the /settings sync source)."""- return [await _claude_options(), await _codex_options()]+ results = await asyncio.gather(*(provider() for provider in _PROVIDERS.values()))+ return list(results)async def sync_backend_options(kind: str) -> BackendOptions:@@ -188,14 +314,18 @@ async def sync_backend_options(kind: str) -> BackendOptions:Claude Code has no machine-readable catalog, so we actively scrape its``/model`` TUI and cache the result. Codex's cache is maintained by its own- CLI, so syncing is just a fresh read.+ CLI (a fresh read suffices), and the opencode family re-runs ``models+ --refresh``. The rest have nothing external to refresh."""if kind == "claude_code":from deeptutor.services.subagent.claude_models import sync_claude_modelsawait sync_claude_models() # writes the cache that _claude_options readsreturn await _claude_options()- return await _codex_options()+ if kind in ("opencode", "mimo"):+ return await _PROVIDERS[kind](refresh=True)+ provider = _PROVIDERS.get(kind, _codex_options)+ return await provider()__all__ = [diff --git a/deeptutor/services/subagent/opencode_family.py b/deeptutor/services/subagent/opencode_family.pynew file mode 100644index 000000000..4326bc057--- /dev/null+++ b/deeptutor/services/subagent/opencode_family.py@@ -0,0 +1,510 @@+"""opencode-family backends — opencode and its fork MiMo-Code, over serve+SSE.++Both CLIs share one integration because MiMo-Code is a source-level fork of+opencode: same server API, same bus events, same session model. Instead of the+part-granular ``run --format json`` subprocess mode, we drive the CLI's local+HTTP server (managed by :mod:`deeptutor.services.subagent.opencode_server`),+which exposes the full event bus over SSE — **token-level**+``message.part.delta`` chunks, every tool-state transition, and interactive+permission asks we answer programmatically. That makes these the richest+streams of the CLI backends: the answer types out live and tools surface the+moment they start running.++One consult = attach to ``GET /event`` (filtered by session), then a blocking+``POST /session/{id}/message`` whose return *is* the end of the turn and whose+response carries the authoritative final answer parts. Sessions are created via+``POST /session`` and live on the CLI's own disk storage keyed by the workdir,+so they survive server respawns.++Auth/config are inherited from the user's own CLI setup (``auth.json`` under+its data dir) — no token is ever handled here. Images ride as first-class+``file`` parts with a real mime type on the prompt body, which sidesteps the+CLI flag's mime-sniffing limitations.+"""++from __future__ import annotations++import asyncio+import base64+import json+import logging+import mimetypes+import os+from pathlib import Path+from typing import Any++import httpx++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.opencode_server import acquire_server+from deeptutor.services.subagent.process import probe_version+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++logger = logging.getLogger(__name__)++_MAX_FIELD_CHARS = 4000+_TOOL_HEADER_CHARS = 160+# MiMo's first run performs a local DB migration, so give the version probe+# more headroom than the default.+_PROBE_TIMEOUT_SECONDS = 15.0+_ATTACH_TIMEOUT_SECONDS = 15.0++# No read timeout: per the product contract we wait unconditionally for the+# agent's own logic to finish — only the run ending closes the request/stream.+_HTTP_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=60.0, pool=10.0)++_TOOL_PRIMARY_ARGS = (+ "command",+ "filePath",+ "file_path",+ "path",+ "pattern",+ "query",+ "url",+ "prompt",+ "description",+)+++class OpencodeFamilyBackend(SubagentBackend):+ """Shared driver for the opencode lineage; subclasses name the CLI."""++ # The CLI's server env-var family (`<PREFIX>_SERVER_PASSWORD` / `_USERNAME`)+ # and the basic-auth user it expects.+ env_prefix: str+ basic_auth_user: str++ async def detect(self) -> DetectResult:+ ok, text = await probe_version(+ [self.cli_command, "--version"], timeout=_PROBE_TIMEOUT_SECONDS+ )+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=ok,+ version=text if ok else "",+ detail="" if ok else (text or f"{self.cli_command} CLI not found on PATH"),+ )++ 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; ignored here+ ) -> ConsultResult:+ config = config or BackendConfig()+ result = ConsultResult(session_id=session_id)+ # Per-consult stream state: cumulative text per part id, each part's+ # channel (text vs reasoning), and any session error seen on the bus.+ state: dict[str, Any] = {"parts": {}, "kinds": {}, "error": ""}++ 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 {}))++ try:+ handle = await acquire_server(+ self.cli_command,+ cwd=cwd or "",+ env_prefix=self.env_prefix,+ username=self.basic_auth_user,+ )+ except Exception as exc:+ logger.warning("%s server failed to start: %s", self.kind, exc, exc_info=True)+ result.success = False+ result.error = f"failed to start {self.display_name} server: {exc}"+ await emit(EVENT_ERROR, result.error, {})+ return result++ listener: asyncio.Task | None = None+ try:+ async with httpx.AsyncClient(+ base_url=handle.base_url, auth=handle.auth, timeout=_HTTP_TIMEOUT+ ) as client:+ fresh_session = not session_id+ sid = session_id or await self._create_session(client)+ result.session_id = sid++ attached = asyncio.Event()+ listener = asyncio.create_task(+ self._listen(client, sid, state, emit, attached, config)+ )+ await _wait_attached(listener, attached)++ body = self._prompt_body(+ question, config=config, images=images, fresh_session=fresh_session+ )+ try:+ response = await client.post(f"/session/{sid}/message", json=body)+ response.raise_for_status()+ except asyncio.CancelledError:+ # The user aborted the turn — best-effort stop the run so+ # the agent doesn't keep working into a dead session.+ with_abort = client.post(f"/session/{sid}/abort", timeout=5.0)+ await asyncio.shield(_swallow(with_abort))+ raise+ result.final_text = _text_from_parts(_response_parts(response))+ except asyncio.CancelledError:+ raise+ except Exception as exc:+ logger.warning("%s consult failed: %s", self.kind, exc, exc_info=True)+ result.success = False+ result.error = str(exc)+ await emit(EVENT_ERROR, str(exc), {})+ finally:+ if listener is not None:+ listener.cancel()+ await asyncio.gather(listener, return_exceptions=True)+ handle.touch()++ if not result.final_text:+ # Fallback: the cumulative text parts streamed over the bus.+ texts = [+ text+ for pid, text in state["parts"].items()+ if state["kinds"].get(pid) == "text" and str(text).strip()+ ]+ result.final_text = "\n\n".join(texts).strip()+ if state["error"] and not result.final_text:+ result.success = False+ result.error = result.error or state["error"]+ return result++ async def _create_session(self, client: httpx.AsyncClient) -> str:+ response = await client.post("/session", json={"title": "DeepTutor consult"})+ response.raise_for_status()+ data = response.json()+ sid = str(data.get("id") or "") if isinstance(data, dict) else ""+ if not sid:+ raise RuntimeError("server created a session without an id")+ return sid++ def _prompt_body(+ self,+ question: str,+ *,+ config: BackendConfig,+ images: list[str] | None,+ fresh_session: bool,+ ) -> dict[str, Any]:+ parts: list[dict[str, Any]] = [{"type": "text", "text": question}]+ for path in images or []:+ part = _image_part(path)+ if part is not None:+ parts.append(part)+ body: dict[str, Any] = {"parts": parts}+ model = (config.model or "").strip()+ if "/" in model:+ provider, model_id = model.split("/", 1)+ body["model"] = {"providerID": provider, "modelID": model_id}+ if config.effort:+ body["variant"] = config.effort+ # The delegate instruction rides the session-creating prompt as the+ # native system field; resumed sessions already have it.+ if fresh_session and config.system_prompt.strip():+ body["system"] = config.system_prompt.strip()+ return body++ async def _listen(+ self,+ client: httpx.AsyncClient,+ sid: str,+ state: dict[str, Any],+ emit: Any,+ attached: asyncio.Event,+ config: BackendConfig,+ ) -> None:+ """Consume the SSE bus, mapping this session's events onto the trace."""+ async with client.stream("GET", "/event") as response:+ response.raise_for_status()+ attached.set()+ async for line in response.aiter_lines():+ if not line.startswith("data:"):+ continue+ event = _parse_json(line[5:])+ if event is None:+ continue+ await self._handle_bus_event(event, sid, state, emit, client, config)++ async def _handle_bus_event(+ self,+ event: dict[str, Any],+ sid: str,+ state: dict[str, Any],+ emit: Any,+ client: httpx.AsyncClient | None,+ config: BackendConfig,+ ) -> None:+ etype = str(event.get("type") or "")+ props = event.get("properties") if isinstance(event.get("properties"), dict) else {}++ if etype == "message.part.updated":+ part = props.get("part") if isinstance(props.get("part"), dict) else {}+ if str(part.get("sessionID") or "") != sid:+ return+ await self._handle_part(part, state, emit)+ return++ if etype == "message.part.delta":+ if str(props.get("sessionID") or "") != sid:+ return+ if str(props.get("field") or "text") != "text":+ return+ pid = str(props.get("partID") or "")+ if not pid:+ return+ acc = str(state["parts"].get(pid, "")) + str(props.get("delta") or "")+ state["parts"][pid] = acc+ kind = state["kinds"].setdefault(pid, "text")+ channel = EVENT_REASONING if kind == "reasoning" else EVENT_TEXT+ prefix = "rsn" if kind == "reasoning" else "txt"+ await emit(channel, acc.strip(), event, {"merge_id": f"{prefix}:{pid}"})+ return++ if etype == "permission.asked":+ if str(props.get("sessionID") or "") != sid:+ return+ await self._reply_permission(props, sid, emit, client, config)+ return++ if etype == "session.error":+ if str(props.get("sessionID") or sid) != sid:+ return+ message = _error_message(props)+ state["error"] = message+ await emit(EVENT_ERROR, message, event)+ return++ # message.updated / session.status / heartbeats — lifecycle noise here;+ # the blocking POST is our end-of-turn signal.++ async def _handle_part(self, part: dict[str, Any], state: dict[str, Any], emit: Any) -> None:+ ptype = str(part.get("type") or "")+ pid = str(part.get("id") or "")++ if ptype in ("text", "reasoning"):+ if not pid:+ return+ state["kinds"][pid] = ptype+ text = str(part.get("text") or "")+ if not text.strip():+ return+ # The updated part carries the authoritative cumulative text —+ # replaces whatever the deltas accumulated (same merge row).+ state["parts"][pid] = text+ prefix, channel = (+ ("rsn", EVENT_REASONING) if ptype == "reasoning" else ("txt", EVENT_TEXT)+ )+ await emit(channel, text.strip(), part, {"merge_id": f"{prefix}:{pid}"})+ return++ if ptype == "tool":+ tool_state = part.get("state") if isinstance(part.get("state"), dict) else {}+ status = str(tool_state.get("status") or "")+ if status == "running":+ await emit(EVENT_TOOL, _render_tool_header(part, tool_state), part,+ {"merge_id": f"tool:{pid}"} if pid else None)+ elif status == "completed":+ await emit(EVENT_TOOL, _render_tool_header(part, tool_state), part,+ {"merge_id": f"tool:{pid}"} if pid else None)+ output = _truncate(str(tool_state.get("output") or ""))+ await emit(EVENT_TOOL_RESULT, output or "(empty result)", part)+ elif status == "error":+ error = _truncate(str(tool_state.get("error") or "tool failed"))+ await emit(EVENT_TOOL_RESULT, error, part)+ return++ # step-start / step-finish / file / agent parts — no transcript row.++ async def _reply_permission(+ self,+ props: dict[str, Any],+ sid: str,+ emit: Any,+ client: httpx.AsyncClient | None,+ config: BackendConfig,+ ) -> None:+ permission_id = str(props.get("id") or "")+ reply = "once" if config.auto_approve else "reject"+ label = _permission_label(props)+ if client is not None and permission_id:+ try:+ await client.post(+ f"/session/{sid}/permissions/{permission_id}",+ json={"response": reply},+ timeout=10.0,+ )+ except httpx.HTTPError as exc: # pragma: no cover - defensive+ logger.warning("permission reply failed: %s", exc)+ note = "auto-approved" if reply == "once" else "rejected (auto-approval is off)"+ await emit(EVENT_LOG, f"permission {note}{f' · {label}' if label else ''}", props)+++class OpencodeBackend(OpencodeFamilyBackend):+ kind = "opencode"+ display_name = "opencode"+ cli_command = "opencode"+ env_prefix = "OPENCODE"+ basic_auth_user = "opencode"+++class MimoBackend(OpencodeFamilyBackend):+ kind = "mimo"+ display_name = "MiMo Code"+ cli_command = "mimo"+ env_prefix = "MIMOCODE"+ basic_auth_user = "mimocode"+++async def _wait_attached(listener: asyncio.Task, attached: asyncio.Event) -> None:+ """Block until the SSE stream is attached (or surface the listener's error)."""+ waiter = asyncio.create_task(attached.wait())+ done, _ = await asyncio.wait(+ {listener, waiter},+ timeout=_ATTACH_TIMEOUT_SECONDS,+ return_when=asyncio.FIRST_COMPLETED,+ )+ if waiter in done:+ return+ waiter.cancel()+ if listener in done:+ exc = listener.exception()+ raise exc if exc else RuntimeError("event stream closed before attaching")+ raise RuntimeError("timed out attaching to the event stream")+++async def _swallow(awaitable) -> None:+ try:+ await awaitable+ except Exception: # pragma: no cover - best-effort abort+ pass+++def _response_parts(response: httpx.Response) -> list[dict[str, Any]]:+ try:+ data = response.json()+ except ValueError:+ return []+ if not isinstance(data, dict):+ return []+ parts = data.get("parts")+ if not isinstance(parts, list):+ return []+ return [p for p in parts if isinstance(p, dict)]+++def _text_from_parts(parts: list[dict[str, Any]]) -> str:+ texts = [+ str(p.get("text") or "").strip()+ for p in parts+ if str(p.get("type") or "") == "text" and not p.get("synthetic")+ ]+ return "\n\n".join(t for t in texts if t).strip()+++def _image_part(path: str) -> dict[str, Any] | None:+ mime = mimetypes.guess_type(path)[0] or "image/png"+ try:+ data = Path(path).read_bytes()+ except OSError:+ return None+ return {+ "type": "file",+ "mime": mime,+ "filename": os.path.basename(path),+ "url": f"data:{mime};base64,{base64.b64encode(data).decode('ascii')}",+ }+++def _render_tool_header(part: dict[str, Any], tool_state: dict[str, Any]) -> str:+ name = str(tool_state.get("title") or part.get("tool") or "tool")+ args = tool_state.get("input")+ if not isinstance(args, dict) or not args:+ return name+ for key in _TOOL_PRIMARY_ARGS:+ value = args.get(key)+ if isinstance(value, str) and value.strip():+ return f"{name}({_inline(value)})"+ return f"{name}({_inline(_compact(args))})"+++def _permission_label(props: dict[str, Any]) -> str:+ """A short human label for a permission ask (title, or the permission name)."""+ title = props.get("title")+ if isinstance(title, str) and title.strip():+ return title.strip()+ permission = props.get("permission")+ if isinstance(permission, dict):+ inner = permission.get("title") or permission.get("id")+ if isinstance(inner, str) and inner.strip():+ return inner.strip()+ elif isinstance(permission, str) and permission.strip():+ return permission.strip()+ return ""+++def _error_message(props: dict[str, Any]) -> str:+ error = props.get("error")+ if isinstance(error, dict):+ data = error.get("data")+ if isinstance(data, dict) and data.get("message"):+ return str(data["message"])+ if error.get("message"):+ return str(error["message"])+ if error.get("name"):+ return str(error["name"])+ return "the agent reported a session error"+++def _parse_json(text: str) -> dict[str, Any] | None:+ text = text.strip()+ if not text or text[0] not in "{[":+ return None+ try:+ parsed = json.loads(text)+ except (ValueError, TypeError):+ return None+ return parsed if isinstance(parsed, dict) else None+++def _inline(text: str) -> str:+ one_line = " ".join(text.split())+ if len(one_line) > _TOOL_HEADER_CHARS:+ return one_line[:_TOOL_HEADER_CHARS].rstrip() + " …"+ return one_line+++def _compact(obj: Any) -> str:+ try:+ text = json.dumps(obj, ensure_ascii=False)+ except (TypeError, ValueError):+ text = str(obj)+ return _truncate(text)+++def _truncate(text: str) -> str:+ text = text.strip()+ if len(text) > _MAX_FIELD_CHARS:+ return text[:_MAX_FIELD_CHARS].rstrip() + " …"+ return text+++__all__ = ["OpencodeFamilyBackend", "OpencodeBackend", "MimoBackend"]diff --git a/deeptutor/services/subagent/opencode_server.py b/deeptutor/services/subagent/opencode_server.pynew file mode 100644index 000000000..54389d144--- /dev/null+++ b/deeptutor/services/subagent/opencode_server.py@@ -0,0 +1,203 @@+"""Managed ``opencode serve`` instances — one live server per (CLI, workdir).++The opencode family (opencode and its fork MiMo-Code) exposes its best+streaming through a local HTTP server: ``<cli> serve`` + an SSE ``/event``+firehose with true token-level ``message.part.delta`` events — richer than the+part-granular ``run --format json`` subprocess mode. This module owns those+server processes so the backend can treat "a reachable server" as a primitive:++* One server per (CLI command, working directory), spawned lazily on first+ consult and **reused across consults and turns** — resumed sessions hit a+ warm server instead of paying a cold start each question.+* Loopback only, with a random per-spawn password passed via the CLI's server+ env vars, so another local user can't drive the agent through our port.+* Reaped after an idle TTL (checked on each acquire), terminated atexit, and+ respawned transparently if the process died in between.++Sessions live on the CLI's own disk storage (keyed by the workdir), so a+respawned server still resumes them — the server is a stateless doorway.+"""++from __future__ import annotations++import asyncio+import atexit+from dataclasses import dataclass, field+import logging+import os+import secrets+import socket+import time++import httpx++logger = logging.getLogger(__name__)++# How long a server may sit unused before the next acquire() reaps it.+_IDLE_TTL_SECONDS = 15 * 60+# How long we wait for a fresh spawn to start answering HTTP.+_READY_TIMEOUT_SECONDS = 30.0+_READY_POLL_SECONDS = 0.3+_TERMINATE_GRACE_SECONDS = 5.0+++@dataclass(slots=True)+class ServerHandle:+ """One live ``<cli> serve`` process and how to talk to it."""++ base_url: str+ username: str+ password: str+ process: asyncio.subprocess.Process+ last_used: float = field(default_factory=time.monotonic)++ @property+ def alive(self) -> bool:+ return self.process.returncode is None++ def touch(self) -> None:+ self.last_used = time.monotonic()++ @property+ def auth(self) -> tuple[str, str]:+ return (self.username, self.password)+++_servers: dict[tuple[str, str], ServerHandle] = {}+_lock = asyncio.Lock()+++async def acquire_server(+ cli_command: str,+ *,+ cwd: str,+ env_prefix: str,+ username: str,+) -> ServerHandle:+ """A reachable server for this CLI + workdir — reused, or spawned fresh.++ ``env_prefix`` names the CLI's server env-var family (``OPENCODE`` /+ ``MIMOCODE``); ``username`` is the basic-auth user the CLI expects.+ """+ key = (cli_command, cwd or "")+ async with _lock:+ _reap_stale(except_key=key)+ handle = _servers.get(key)+ if handle is not None and handle.alive:+ handle.touch()+ return handle+ if handle is not None: # died in between — clean up before respawn+ _terminate_sync(handle)+ _servers.pop(key, None)+ handle = await _spawn(cli_command, cwd=cwd, env_prefix=env_prefix, username=username)+ _servers[key] = handle+ return handle+++async def _spawn(+ cli_command: str, *, cwd: str, env_prefix: str, username: str+) -> ServerHandle:+ port = _free_port()+ password = secrets.token_urlsafe(16)+ env = {+ **os.environ,+ f"{env_prefix}_SERVER_PASSWORD": password,+ f"{env_prefix}_SERVER_USERNAME": username,+ }+ process = await asyncio.create_subprocess_exec(+ cli_command,+ "serve",+ "--port",+ str(port),+ "--hostname",+ "127.0.0.1",+ cwd=cwd or None,+ env=env,+ stdin=asyncio.subprocess.DEVNULL,+ stdout=asyncio.subprocess.DEVNULL,+ stderr=asyncio.subprocess.DEVNULL,+ )+ handle = ServerHandle(+ base_url=f"http://127.0.0.1:{port}",+ username=username,+ password=password,+ process=process,+ )+ try:+ await _wait_ready(handle)+ except Exception:+ _terminate_sync(handle)+ raise+ logger.info("%s serve started on %s (cwd=%s)", cli_command, handle.base_url, cwd or ".")+ return handle+++async def _wait_ready(handle: ServerHandle) -> None:+ """Poll until the server answers HTTP (any status means it's listening)."""+ deadline = time.monotonic() + _READY_TIMEOUT_SECONDS+ async with httpx.AsyncClient(base_url=handle.base_url, auth=handle.auth) as client:+ while True:+ if not handle.alive:+ raise RuntimeError(+ f"server exited during startup (code {handle.process.returncode})"+ )+ try:+ await client.get("/doc", timeout=2.0)+ return+ except httpx.HTTPError:+ if time.monotonic() >= deadline:+ raise RuntimeError("server did not become ready in time") from None+ await asyncio.sleep(_READY_POLL_SECONDS)+++def _free_port() -> int:+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return sock.getsockname()[1]+++def _reap_stale(*, except_key: tuple[str, str] | None = None) -> None:+ """Terminate servers idle past the TTL (called under the lock)."""+ now = time.monotonic()+ for key, handle in list(_servers.items()):+ if key == except_key:+ continue+ if not handle.alive or now - handle.last_used > _IDLE_TTL_SECONDS:+ _terminate_sync(handle)+ _servers.pop(key, None)+++def _terminate_sync(handle: ServerHandle) -> None:+ if not handle.alive:+ return+ try:+ handle.process.terminate()+ except ProcessLookupError:+ pass+++async def shutdown_servers() -> None:+ """Terminate every managed server and wait briefly (tests, app shutdown)."""+ async with _lock:+ handles = list(_servers.values())+ _servers.clear()+ for handle in handles:+ _terminate_sync(handle)+ for handle in handles:+ try:+ await asyncio.wait_for(handle.process.wait(), timeout=_TERMINATE_GRACE_SECONDS)+ except (TimeoutError, asyncio.TimeoutError):+ try:+ handle.process.kill()+ except ProcessLookupError:+ pass+++def _atexit_cleanup() -> None: # pragma: no cover - process teardown+ for handle in _servers.values():+ _terminate_sync(handle)+ _servers.clear()+++__all__ = ["ServerHandle", "acquire_server", "shutdown_servers"]diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.pyindex 3640c7ea0..42decad81 100644--- a/deeptutor/services/subagent/registry.py+++ b/deeptutor/services/subagent/registry.py@@ -2,9 +2,10 @@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) and the in-process partner backend live in the-same registry but are told apart by ``local_cli`` — only CLIs are detected on-the machine and offered in the connect-CLI modal.+backends (Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code) and+the in-process partner backend live in the same registry but are told apart by+``local_cli`` — only CLIs are detected on the machine and offered in the+connect-CLI modal."""from __future__ import annotations@@ -14,11 +15,23 @@ import asynciofrom deeptutor.services.subagent.base import SubagentBackendfrom deeptutor.services.subagent.claude_code import ClaudeCodeBackendfrom deeptutor.services.subagent.codex import CodexBackend+from deeptutor.services.subagent.gemini import GeminiBackend+from deeptutor.services.subagent.kimi import KimiBackend+from deeptutor.services.subagent.opencode_family import MimoBackend, OpencodeBackendfrom deeptutor.services.subagent.partner import PartnerBackendfrom deeptutor.services.subagent.types import DetectResult_BACKENDS: dict[str, SubagentBackend] = {- backend.kind: backend for backend in (ClaudeCodeBackend(), CodexBackend(), PartnerBackend())+ backend.kind: backend+ for backend in (+ ClaudeCodeBackend(),+ CodexBackend(),+ GeminiBackend(),+ KimiBackend(),+ OpencodeBackend(),+ MimoBackend(),+ PartnerBackend(),+ )}diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.pyindex 8d5b1ae0d..64830f0a2 100644--- a/tests/services/test_subagent_backends.py+++ b/tests/services/test_subagent_backends.py@@ -636,7 +636,7 @@ async def test_detect_all_excludes_partner_backend() -> None:kinds = {d.kind for d in await detect_all()}assert "partner" not in kinds- assert kinds <= {"claude_code", "codex"}+ assert kinds <= {"claude_code", "codex", "gemini", "kimi", "opencode", "mimo"}# ---- partner backend: drive a partner as a subagent --------------------------@@ -898,3 +898,424 @@ def test_partner_content_accumulates_cumulatively() -> None:)assert a[0].text == "The " and b[0].text == "The answer"assert a[0].meta["merge_id"] == b[0].meta["merge_id"] == "text:f1"+++# ---- Gemini CLI: command building + event parsing -----------------------------+++def test_gemini_command_build_fresh_resume_and_approval_mapping() -> None:+ from deeptutor.services.subagent.gemini import GeminiBackend++ backend = GeminiBackend()+ fresh = backend._build_command(+ "hi", session_id=None, config=BackendConfig(system_prompt="be brief")+ )+ assert fresh[:3] == ["gemini", "-p", "be brief\n\nhi"] # instruction only on fresh+ assert "--output-format" in fresh and "stream-json" in fresh+ # Canonical CC spelling maps onto gemini's approval modes (default → yolo).+ assert fresh[fresh.index("--approval-mode") + 1] == "yolo"+ assert "--resume" not in fresh++ resumed = backend._build_command(+ "again",+ session_id="s1",+ config=BackendConfig(system_prompt="be brief", permission_mode="acceptEdits", model="flash"),+ )+ assert resumed[1:3] == ["-p", "again"] # no instruction prefix on resume+ assert resumed[resumed.index("--approval-mode") + 1] == "auto_edit"+ assert "--resume" in resumed and "s1" in resumed+ assert resumed[resumed.index("--model") + 1] == "flash"+++def test_gemini_command_attaches_images_via_at_syntax() -> None:+ from deeptutor.services.subagent.gemini import GeminiBackend++ backend = GeminiBackend()+ cmd = backend._build_command(+ "look", session_id=None, config=BackendConfig(), images=["/tmp/stage/a.png"]+ )+ assert "@/tmp/stage/a.png" in cmd[2] # rides inside the prompt text+ assert cmd[cmd.index("--include-directories") + 1] == "/tmp/stage"+++async def _drive_gemini(events):+ from deeptutor.services.subagent.gemini import GeminiBackend++ backend = GeminiBackend()+ result = ConsultResult()+ stream: dict = {"blocks": [], "open": False}+ emitted: list[tuple[str, str, dict]] = []++ async def emit(kind, text, raw, meta=None):+ emitted.append((kind, text, meta or {}))++ for ev in events:+ await backend._handle_event(ev, result, stream, emit)+ if not result.final_text:+ result.final_text = "\n\n".join(b for b in stream["blocks"] if b.strip()).strip()+ return result, emitted+++async def test_gemini_deltas_accumulate_and_tools_split_blocks() -> None:+ events = [+ {"type": "init", "timestamp": "t", "session_id": "g1", "model": "gemini-pro"},+ {"type": "message", "role": "user", "content": "the echoed prompt"},+ {"type": "message", "role": "assistant", "content": "Let me ", "delta": True},+ {"type": "message", "role": "assistant", "content": "check.", "delta": True},+ {"type": "tool_use", "tool_name": "Shell", "tool_id": "c1", "parameters": {"command": "ls"}},+ {"type": "tool_result", "tool_id": "c1", "status": "success", "output": "a.py"},+ {"type": "message", "role": "assistant", "content": "Found it.", "delta": True},+ {"type": "result", "timestamp": "t", "status": "success"},+ ]+ result, emitted = await _drive_gemini(events)++ assert result.session_id == "g1"+ # The user echo is dropped; deltas grow one row per block.+ texts = [(t, m.get("merge_id")) for k, t, m in emitted if k == "text"]+ assert texts == [+ ("Let me", "txt:0"),+ ("Let me check.", "txt:0"),+ ("Found it.", "txt:1"), # the tool_use closed block 0+ ]+ assert ("tool", "Shell(ls)") in [(k, t) for k, t, _ in emitted]+ assert ("tool_result", "a.py") in [(k, t) for k, t, _ in emitted]+ # No aggregated message event exists — the final answer is the joined blocks.+ assert result.final_text == "Let me check.\n\nFound it."+ assert result.success is True+++async def test_gemini_warning_is_log_and_error_result_fails() -> None:+ events = [+ {"type": "error", "severity": "warning", "message": "slow network"},+ {"type": "error", "severity": "error", "message": "quota exhausted"},+ {"type": "result", "status": "error", "error": {"type": "x", "message": "quota exhausted"}},+ ]+ result, emitted = await _drive_gemini(events)+ kinds = [k for k, _, _ in emitted]+ assert kinds == ["log", "error"]+ assert result.success is False+ assert "quota" in result.error+++# ---- Kimi CLI: command building + line parsing --------------------------------+++def test_kimi_command_build_session_yolo_and_thinking() -> None:+ from deeptutor.services.subagent.kimi import KimiBackend++ backend = KimiBackend()+ cmd = backend._build_command(+ "hi",+ session_id="u-1",+ fresh_session=True,+ config=BackendConfig(system_prompt="sp", model="kimi-k2", thinking=False),+ )+ assert cmd[:4] == ["kimi", "--print", "--output-format", "stream-json"]+ assert cmd[cmd.index("--session") + 1] == "u-1"+ assert "--yolo" in cmd and "--no-thinking" in cmd+ assert cmd[cmd.index("--model") + 1] == "kimi-k2"+ assert cmd[-2:] == ["--prompt", "sp\n\nhi"] # instruction prefixed on fresh session++ resumed = backend._build_command(+ "again",+ session_id="u-1",+ fresh_session=False,+ config=BackendConfig(system_prompt="sp", auto_approve=False),+ )+ assert resumed[-1] == "again" and "--yolo" not in resumed+ assert "--thinking" in resumed+++async def test_kimi_consult_mints_session_id_upfront() -> None:+ """A fresh consult pre-generates the session id (never parsed from output)."""+ import uuid as uuid_mod++ from deeptutor.services.subagent.kimi import KimiBackend++ backend = KimiBackend()++ captured: dict = {}++ def fake_build(question, *, session_id, fresh_session, config):+ captured["sid"] = session_id+ captured["fresh"] = fresh_session+ return [sys.executable, "-c", "pass"] # exits 0 with no output++ backend._build_command = fake_build # type: ignore[method-assign]++ async def on_event(event):+ pass++ result = await backend.consult("q", on_event=on_event)+ assert captured["fresh"] is True+ assert result.session_id == captured["sid"]+ assert uuid_mod.UUID(result.session_id) # a well-formed UUID+++async def test_kimi_line_parsing_roles_parts_and_tools() -> None:+ from deeptutor.services.subagent.kimi import KimiBackend++ backend = KimiBackend()+ events = [+ # content as a plain string (single text part shorthand)+ {"role": "assistant", "content": "Working on it."},+ # content as a part array with thinking + a tool call+ {+ "role": "assistant",+ "content": [{"type": "think", "think": "planning"}],+ "tool_calls": [+ {+ "type": "function",+ "id": "t1",+ "function": {"name": "shell", "arguments": '{"command": "ls -la"}'},+ }+ ],+ },+ {"role": "tool", "content": "<system>OK</system>", "tool_call_id": "t1"},+ {"role": "assistant", "content": [{"type": "text", "text": "The answer."}]},+ # role-less service lines+ {"id": "n1", "category": "task", "title": "background", "body": "done", "severity": "info"},+ {"content": "# plan", "file_path": "/tmp/plan.md"},+ ]+ result, emitted = await _drive(backend, events)++ kinds = [k for k, _ in emitted]+ assert kinds == ["text", "reasoning", "tool", "tool_result", "text", "log", "log"]+ assert ("tool", "shell(ls -la)") in emitted # JSON-string arguments are decoded+ assert result.final_text == "The answer." # the latest assistant text wins+++async def test_kimi_echoed_user_lines_are_dropped() -> None:+ from deeptutor.services.subagent.kimi import KimiBackend++ _, emitted = await _drive(KimiBackend(), [{"role": "user", "content": "echo"}])+ assert emitted == []+++# ---- opencode family: bus event mapping + prompt body -------------------------+++async def _drive_opencode(events, *, auto_approve=True):+ from deeptutor.services.subagent.opencode_family import OpencodeBackend++ backend = OpencodeBackend()+ state: dict = {"parts": {}, "kinds": {}, "error": ""}+ emitted: list[tuple[str, str, dict]] = []++ async def emit(kind, text, raw, meta=None):+ emitted.append((kind, text, meta or {}))++ config = BackendConfig(auto_approve=auto_approve)+ for ev in events:+ await backend._handle_bus_event(ev, "ses_1", state, emit, None, config)+ return state, emitted+++async def test_opencode_deltas_type_out_and_updated_finalizes() -> None:+ events = [+ # the part is created empty, then token deltas grow it+ {+ "type": "message.part.updated",+ "properties": {"part": {"id": "p1", "sessionID": "ses_1", "type": "text", "text": ""}},+ },+ {+ "type": "message.part.delta",+ "properties": {"sessionID": "ses_1", "messageID": "m1", "partID": "p1", "field": "text", "delta": "Hel"},+ },+ {+ "type": "message.part.delta",+ "properties": {"sessionID": "ses_1", "messageID": "m1", "partID": "p1", "field": "text", "delta": "lo."},+ },+ # the completed part carries the authoritative cumulative text+ {+ "type": "message.part.updated",+ "properties": {+ "part": {"id": "p1", "sessionID": "ses_1", "type": "text", "text": "Hello.", "time": {"start": 1, "end": 2}},+ },+ },+ ]+ state, emitted = await _drive_opencode(events)+ texts = [(t, m.get("merge_id")) for k, t, m in emitted if k == "text"]+ assert texts == [("Hel", "txt:p1"), ("Hello.", "txt:p1"), ("Hello.", "txt:p1")]+ assert state["parts"]["p1"] == "Hello."+++async def test_opencode_reasoning_deltas_use_reasoning_channel() -> None:+ events = [+ {+ "type": "message.part.updated",+ "properties": {"part": {"id": "r1", "sessionID": "ses_1", "type": "reasoning", "text": ""}},+ },+ {+ "type": "message.part.delta",+ "properties": {"sessionID": "ses_1", "messageID": "m1", "partID": "r1", "field": "text", "delta": "hmm"},+ },+ ]+ _, emitted = await _drive_opencode(events)+ assert [(k, t, m.get("merge_id")) for k, t, m in emitted] == [("reasoning", "hmm", "rsn:r1")]+++async def test_opencode_tool_lifecycle_running_completed_error() -> None:+ def tool_event(status, **extra):+ return {+ "type": "message.part.updated",+ "properties": {+ "part": {+ "id": "tp1",+ "sessionID": "ses_1",+ "type": "tool",+ "callID": "c1",+ "tool": "bash",+ "state": {"status": status, **extra},+ }+ },+ }++ _, emitted = await _drive_opencode(+ [+ tool_event("pending", input={"command": "ls"}),+ tool_event("running", input={"command": "ls"}),+ tool_event("completed", input={"command": "ls"}, output="a.py", title="List files"),+ tool_event("error", input={"command": "rm"}, error="denied"),+ ]+ )+ assert [(k, t) for k, t, _ in emitted] == [+ ("tool", "bash(ls)"), # pending is silent; running opens the row+ ("tool", "List files(ls)"), # completion finalizes the same row (same merge id)+ ("tool_result", "a.py"),+ ("tool_result", "denied"),+ ]+ tool_merges = [m.get("merge_id") for k, _, m in emitted if k == "tool"]+ assert tool_merges == ["tool:tp1", "tool:tp1"]+++async def test_opencode_permission_asked_is_answered_and_logged() -> None:+ ask = {+ "type": "permission.asked",+ "properties": {"id": "perm1", "sessionID": "ses_1", "title": "Run bash"},+ }+ _, approved = await _drive_opencode([ask], auto_approve=True)+ assert approved[0][0] == "log" and "auto-approved" in approved[0][1]++ _, rejected = await _drive_opencode([ask], auto_approve=False)+ assert "rejected" in rejected[0][1]+++async def test_opencode_session_error_and_foreign_session_filtering() -> None:+ events = [+ # another session's traffic must not leak into this consult's trace+ {+ "type": "message.part.updated",+ "properties": {"part": {"id": "x", "sessionID": "ses_OTHER", "type": "text", "text": "hi"}},+ },+ {+ "type": "session.error",+ "properties": {"sessionID": "ses_1", "error": {"name": "ProviderError", "data": {"message": "boom"}}},+ },+ ]+ state, emitted = await _drive_opencode(events)+ assert [(k, t) for k, t, _ in emitted] == [("error", "boom")]+ assert state["error"] == "boom"+++def test_opencode_prompt_body_model_variant_system_and_images(tmp_path) -> None:+ from deeptutor.services.subagent.opencode_family import OpencodeBackend++ img = tmp_path / "shot.png"+ img.write_bytes(b"\x89PNG fake")+ backend = OpencodeBackend()+ body = backend._prompt_body(+ "q",+ config=BackendConfig(model="anthropic/claude-x", effort="high", system_prompt="sys"),+ images=[str(img)],+ fresh_session=True,+ )+ assert body["model"] == {"providerID": "anthropic", "modelID": "claude-x"}+ assert body["variant"] == "high"+ assert body["system"] == "sys"+ assert body["parts"][0] == {"type": "text", "text": "q"}+ file_part = body["parts"][1]+ assert file_part["type"] == "file" and file_part["mime"] == "image/png"+ assert file_part["url"].startswith("data:image/png;base64,")++ resumed = backend._prompt_body(+ "q2", config=BackendConfig(system_prompt="sys"), images=None, fresh_session=False+ )+ assert "system" not in resumed and "model" not in resumed+++def test_opencode_final_text_skips_synthetic_parts() -> None:+ from deeptutor.services.subagent.opencode_family import _text_from_parts++ parts = [+ {"type": "text", "text": "real answer"},+ {"type": "text", "text": "injected", "synthetic": True},+ {"type": "tool", "text": "not text"},+ ]+ assert _text_from_parts(parts) == "real answer"+++# ---- opencode family: managed server registry ---------------------------------+++class _FakeServerProc:+ def __init__(self):+ self.returncode: int | None = None+ self.terminated = False++ def terminate(self):+ self.terminated = True+ self.returncode = -15++ def kill(self):+ self.returncode = -9++ async def wait(self):+ return self.returncode+++def test_server_registry_reaps_idle_and_dead_handles() -> None:+ from deeptutor.services.subagent import opencode_server as srv++ fresh_proc, stale_proc, dead_proc = _FakeServerProc(), _FakeServerProc(), _FakeServerProc()+ dead_proc.returncode = 1+ fresh = srv.ServerHandle(base_url="http://x", username="u", password="p", process=fresh_proc)+ stale = srv.ServerHandle(base_url="http://y", username="u", password="p", process=stale_proc)+ stale.last_used -= srv._IDLE_TTL_SECONDS + 1+ dead = srv.ServerHandle(base_url="http://z", username="u", password="p", process=dead_proc)++ srv._servers.clear()+ srv._servers[("cli", "a")] = fresh+ srv._servers[("cli", "b")] = stale+ srv._servers[("cli", "c")] = dead+ try:+ srv._reap_stale()+ assert set(srv._servers) == {("cli", "a")}+ assert stale_proc.terminated is True+ assert fresh_proc.terminated is False+ finally:+ srv._servers.clear()+++async def test_server_registry_shutdown_terminates_everything() -> None:+ from deeptutor.services.subagent import opencode_server as srv++ proc = _FakeServerProc()+ srv._servers.clear()+ srv._servers[("cli", "a")] = srv.ServerHandle(+ base_url="http://x", username="u", password="p", process=proc+ )+ await srv.shutdown_servers()+ assert srv._servers == {}+ assert proc.terminated is Truediff --git a/web/app/(utility)/settings/agents/gemini/page.tsx b/web/app/(utility)/settings/agents/gemini/page.tsxnew file mode 100644index 000000000..34d8d1858--- /dev/null+++ b/web/app/(utility)/settings/agents/gemini/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function GeminiAgentSettingsPage() {+ return <SubagentSettingsEditor kind="gemini" />;+}diff --git a/web/app/(utility)/settings/agents/kimi/page.tsx b/web/app/(utility)/settings/agents/kimi/page.tsxnew file mode 100644index 000000000..d00eb1a67--- /dev/null+++ b/web/app/(utility)/settings/agents/kimi/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function KimiAgentSettingsPage() {+ return <SubagentSettingsEditor kind="kimi" />;+}diff --git a/web/app/(utility)/settings/agents/mimo/page.tsx b/web/app/(utility)/settings/agents/mimo/page.tsxnew file mode 100644index 000000000..0d1c0e428--- /dev/null+++ b/web/app/(utility)/settings/agents/mimo/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function MimoAgentSettingsPage() {+ return <SubagentSettingsEditor kind="mimo" />;+}diff --git a/web/app/(utility)/settings/agents/opencode/page.tsx b/web/app/(utility)/settings/agents/opencode/page.tsxnew file mode 100644index 000000000..c63dedb33--- /dev/null+++ b/web/app/(utility)/settings/agents/opencode/page.tsx@@ -0,0 +1,7 @@+"use client";++import { SubagentSettingsEditor } from "@/components/settings/SubagentSettingsEditor";++export default function OpencodeAgentSettingsPage() {+ return <SubagentSettingsEditor kind="opencode" />;+}diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsxindex 6e7ea335b..975293ea1 100644--- a/web/components/agents/ConnectedAgents.tsx+++ b/web/components/agents/ConnectedAgents.tsx@@ -35,6 +35,10 @@ 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 === "gemini") return "Gemini CLI";+ if (kind === "kimi") return "Kimi CLI";+ if (kind === "opencode") return "opencode";+ if (kind === "mimo") return "MiMo Code";if (kind === PARTNER_KIND) return tr({ zh: "伙伴", en: "Partner" });return kind;}@@ -110,8 +114,8 @@ export default function ConnectedAgents() {icon={Plug}title={tr({ zh: "连接的智能体", en: "Connected agents" })}description={tr({- zh: "把本机的 Claude Code / Codex 或你的伙伴接进来,在对话中选中后直接向它提问 —— 它的完整运行过程会实时展示。",- en: "Bring in the Claude Code / Codex on this machine, or one of your partners — select one in chat to consult it directly, with its full run shown live.",+ zh: "把本机的 Claude Code、Codex、Gemini CLI、Kimi CLI、opencode、MiMo Code 或你的伙伴接进来,在对话中选中后直接向它提问 —— 它的完整运行过程会实时展示。",+ en: "Bring in the Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, or MiMo Code on this machine, or one of your partners — select one in chat to consult it directly, with its full run shown live.",})}action={canConnect ? (@@ -135,15 +139,15 @@ export default function ConnectedAgents() {) : !canConnect ? (<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{tr({- zh: "未在本机检测到 Claude Code 或 Codex,也还没有任何伙伴。安装并登录其中任一 CLI,或在「伙伴」里新建一个,即可连接。",- en: "No Claude Code or Codex detected on this machine, and no partners yet. Install and log in to either CLI, or create a partner, to connect one.",+ zh: "未在本机检测到可用的智能体 CLI(Claude Code、Codex、Gemini CLI、Kimi CLI、opencode、MiMo Code),也还没有任何伙伴。安装并登录其中任一 CLI,或在「伙伴」里新建一个,即可连接。",+ en: "No agent CLI detected on this machine (Claude Code, Codex, Gemini CLI, Kimi CLI, opencode, MiMo Code), and no partners yet. Install and log in to any of them, or create a partner, to connect one.",})}</div>) : connections.length === 0 ? (<div className="rounded-xl border border-dashed border-[var(--border)] bg-[var(--card)]/40 px-4 py-5 text-[12.5px] leading-relaxed text-[var(--muted-foreground)]">{tr({- zh: "尚未连接任何智能体。点击「连接智能体」把本机的 Claude Code / Codex 或你的伙伴接进来。",- en: "No agents connected yet. Click “Connect agent” to bring in your local Claude Code / Codex, or a partner.",+ zh: "尚未连接任何智能体。点击「连接智能体」把本机检测到的智能体 CLI 或你的伙伴接进来。",+ en: "No agents connected yet. Click “Connect agent” to bring in a detected local agent CLI, or a partner.",})}</div>) : (@@ -338,7 +342,8 @@ function ConnectModal({<label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">{tr({ zh: "智能体", en: "Agent" })}</label>- <div className="flex gap-2">+ {/* Two per row — up to six CLIs plus Partner can be on offer. */}+ <div className="grid grid-cols-2 gap-2">{options.map((opt) => {const Glyph = agentGlyph(opt.kind);return (@@ -346,7 +351,7 @@ function ConnectModal({key={opt.kind}type="button"onClick={() => setKind(opt.kind)}- className={`flex flex-1 items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-[12.5px] font-medium transition-colors ${+ className={`flex items-center justify-center gap-1.5 rounded-lg border px-3 py-2 text-[12.5px] font-medium transition-colors ${kind === opt.kind? "border-[var(--primary)] bg-[var(--primary)]/[0.07] text-[var(--foreground)]": "border-[var(--border)] text-[var(--muted-foreground)] hover:border-[var(--border)] hover:text-[var(--foreground)]"diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsxindex 82b45f523..a56ad4a98 100644--- a/web/components/agents/agent-icons.tsx+++ b/web/components/agents/agent-icons.tsx@@ -72,6 +72,108 @@ export function CodexGlyph({ size = 16, ...props }: GlyphProps) {);}+// Gemini's four-point spark, in the brand blue→violet gradient.+export function GeminiGlyph({ size = 16, ...props }: GlyphProps) {+ const gradientId = useId();+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden+ {...props}+ >+ <path+ d="M12 24A14.3 14.3 0 0 0 0 12 14.3 14.3 0 0 0 12 0a14.3 14.3 0 0 0 12 12 14.3 14.3 0 0 0-12 12z"+ fill={`url(#${gradientId})`}+ />+ <defs>+ <linearGradient+ gradientUnits="userSpaceOnUse"+ id={gradientId}+ x1="0"+ x2="24"+ y1="24"+ y2="0"+ >+ <stop stopColor="#217BFE" />+ <stop offset="1" stopColor="#AC87EB" />+ </linearGradient>+ </defs>+ </svg>+ );+}++// Kimi (Moonshot AI): dark tile with a white K.+export function KimiGlyph({ size = 16, ...props }: GlyphProps) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden+ {...props}+ >+ <rect width="24" height="24" rx="5.4" fill="#16161D" />+ <path+ d="M8 5.6h2.6v5.1l4.5-5.1h3.3l-5 5.6 5.2 7.2h-3.2l-3.7-5.3-1.1 1.2v4.1H8z"+ fill="#fff"+ />+ </svg>+ );+}++// opencode: dark terminal tile with a prompt chevron + cursor underscore.+export function OpencodeGlyph({ size = 16, ...props }: GlyphProps) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden+ {...props}+ >+ <rect width="24" height="24" rx="5.4" fill="#0A0A0A" />+ <path+ d="M7.2 8.4 11 11.9l-3.8 3.5"+ stroke="#fff"+ strokeWidth="1.9"+ strokeLinecap="round"+ strokeLinejoin="round"+ />+ <path+ d="M12.9 15.6h4.3"+ stroke="#fff"+ strokeWidth="1.9"+ strokeLinecap="round"+ />+ </svg>+ );+}++// MiMo Code (Xiaomi): the brand-orange tile with a white M.+export function MimoGlyph({ size = 16, ...props }: GlyphProps) {+ return (+ <svg+ width={size}+ height={size}+ viewBox="0 0 24 24"+ fill="none"+ aria-hidden+ {...props}+ >+ <rect width="24" height="24" rx="5.4" fill="#FF6900" />+ <path+ d="M6.4 17.2V6.8h2.5l3.1 5.4 3.1-5.4h2.5v10.4h-2.4v-6l-2.6 4.4h-1.2l-2.6-4.4v6z"+ fill="#fff"+ />+ </svg>+ );+}+// A connected partner: a filled heart in the Partners accent, so a consulted// partner reads as a companion (not a CLI) everywhere a connected agent appears.export function PartnerGlyph({ size = 16, ...props }: GlyphProps) {@@ -94,6 +196,10 @@ 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 === "gemini") return GeminiGlyph;+ if (kind === "kimi") return KimiGlyph;+ if (kind === "opencode") return OpencodeGlyph;+ if (kind === "mimo") return MimoGlyph;if (kind === "partner") return PartnerGlyph;return null;}diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsxindex 17d934edc..490867a56 100644--- a/web/components/settings/SubagentSettingsEditor.tsx+++ b/web/components/settings/SubagentSettingsEditor.tsx@@ -41,6 +41,8 @@ const DEFAULTS: Required<| "approval"| "network_access"| "ephemeral"+ | "auto_approve"+ | "thinking"| "forward_images">> = {@@ -53,9 +55,120 @@ const DEFAULTS: Required<approval: "never",network_access: false,ephemeral: false,+ auto_approve: true,+ thinking: true,forward_images: false,};+/**+ * 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 / Gemini use `permission_mode`, only Codex has its+ * sandbox family, kimi/opencode/mimo take the `auto_approve` reply switch.+ */+type KindFeatures = {+ effort: boolean;+ systemPrompt: boolean;+ permissionMode: boolean;+ codexSandbox: boolean;+ autoApprove: boolean;+ thinking: boolean;+ forwardImages: boolean;+};++const KIND_FEATURES: Record<string, KindFeatures> = {+ claude_code: {+ effort: true,+ systemPrompt: true,+ permissionMode: true,+ codexSandbox: false,+ autoApprove: false,+ thinking: false,+ forwardImages: true,+ },+ codex: {+ effort: true,+ systemPrompt: false,+ permissionMode: false,+ codexSandbox: true,+ autoApprove: false,+ thinking: false,+ forwardImages: true,+ },+ gemini: {+ effort: false, // no reasoning-effort flag+ systemPrompt: true,+ permissionMode: true, // canonical values map onto --approval-mode+ codexSandbox: false,+ autoApprove: false,+ thinking: false,+ forwardImages: true, // @path syntax+ },+ kimi: {+ effort: false,+ systemPrompt: true,+ permissionMode: false,+ codexSandbox: false,+ autoApprove: true, // --yolo+ thinking: true, // --thinking / --no-thinking+ forwardImages: false, // no headless image input+ },+ opencode: {+ effort: true, // --variant+ systemPrompt: true,+ permissionMode: false,+ codexSandbox: false,+ autoApprove: true, // permission.asked replies+ thinking: false, // the event bus always streams reasoning+ forwardImages: true, // file parts on the server API+ },+ mimo: {+ effort: true,+ systemPrompt: true,+ permissionMode: false,+ codexSandbox: false,+ autoApprove: true,+ thinking: false,+ forwardImages: true,+ },+};++const FALLBACK_FEATURES: KindFeatures = KIND_FEATURES.claude_code;++const DISPLAY_NAMES: Record<string, string> = {+ claude_code: "Claude Code",+ codex: "Codex",+ gemini: "Gemini CLI",+ kimi: "Kimi CLI",+ opencode: "opencode",+ mimo: "MiMo Code",+};++// 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> = {+ claude_code: {+ zh: "追加到该智能体的系统提示(--append-system-prompt)。",+ en: "Appended to the agent's system prompt (--append-system-prompt).",+ },+ gemini: {+ zh: "Gemini CLI 没有系统提示 flag——该指令会前缀在每个新会话的第一条消息上。",+ en: "Gemini CLI has no system-prompt flag — the instruction is prefixed to each new session's first message.",+ },+ kimi: {+ zh: "Kimi CLI 没有系统提示 flag——该指令会前缀在每个新会话的第一条消息上。",+ en: "Kimi CLI has no system-prompt flag — the instruction is prefixed to each new session's first message.",+ },+ opencode: {+ zh: "通过服务器 API 的 system 字段注入到每个新会话。",+ en: "Injected into each new session via the server API's system field.",+ },+ mimo: {+ zh: "通过服务器 API 的 system 字段注入到每个新会话。",+ en: "Injected into each new session via the server API's system field.",+ },+};+const PERMISSION_MODES: { value: string; label: Lang }[] = [{value: "bypassPermissions",@@ -104,6 +217,33 @@ const APPROVALS: { value: string; label: Lang }[] = [},];+// Gemini stores the same canonical permission values (the two CLIs' modes are+// semantically parallel); the labels name its native --approval-mode spellings.+const GEMINI_PERMISSION_MODES: { value: string; label: Lang }[] = [+ {+ value: "bypassPermissions",+ label: {+ zh: "YOLO · 全自主(推荐)",+ en: "YOLO · autonomous (recommended)",+ },+ },+ {+ value: "acceptEdits",+ label: { zh: "自动接受编辑(auto_edit)", en: "Auto-accept edits (auto_edit)" },+ },+ {+ value: "default",+ label: {+ zh: "默认 · 无人值守下改动会被拒绝",+ en: "Default · mutating tools are denied headless",+ },+ },+ {+ value: "plan",+ label: { zh: "计划模式 · 只读", en: "Plan mode · read-only" },+ },+];+export function SubagentSettingsEditor({ kind }: { kind: string }) {const { i18n } = useTranslation();const zh = i18n.language?.toLowerCase().startsWith("zh");@@ -176,7 +316,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {[kind],);- const isCodex = kind === "codex";+ const features = KIND_FEATURES[kind] ?? FALLBACK_FEATURES;const knownSlugs = useMemo(() => new Set((options?.models ?? []).map((m) => m.slug)),[options],@@ -184,16 +324,16 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {const showCustomModel =customModel || (config.model !== "" && !knownSlugs.has(config.model ?? ""));- // Effort choices: per-model for Codex (its cache carries each model's levels),- // global for Claude Code. Falls back to the backend's union when the chosen- // model isn't a known slug (custom / default).+ // Effort choices: per-model when the catalog carries each model's levels+ // (Codex, opencode family), else the backend's union (Claude Code). Falls+ // back to the union when the chosen model isn't a known slug.const effortChoices = useMemo(() => {- if (isCodex && config.model && knownSlugs.has(config.model)) {+ if (config.model && knownSlugs.has(config.model)) {const m = options?.models.find((x) => x.slug === config.model);if (m?.efforts?.length) return m.efforts;}return options?.efforts ?? [];- }, [isCodex, config.model, knownSlugs, options]);+ }, [config.model, knownSlugs, options]);const onModelSelect = useCallback((value: string) => {@@ -202,11 +342,10 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {return;}setCustomModel(false);- // Reset an effort the newly chosen model doesn't support (Codex).+ // Reset an effort the newly chosen model doesn't support.const m = options?.models.find((x) => x.slug === value);const patch: Partial<SubagentBackendConfig> = { model: value };if (- isCodex &&config.effort &&m?.efforts?.length &&!m.efforts.includes(config.effort)@@ -215,11 +354,11 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {}void save(patch);},- [options, isCodex, config.effort, save],+ [options, config.effort, save],);const displayName =- options?.display_name ?? (isCodex ? "Codex" : "Claude Code");+ options?.display_name ?? DISPLAY_NAMES[kind] ?? kind;return (<div>@@ -380,35 +519,39 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {</div>}/>- <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="">- {tr({ zh: "CLI 默认", en: "CLI default" })}- </option>- {effortChoices.map((eff) => (- <option key={eff} value={eff}>- {eff}+ {features.effort && (+ <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="">+ {tr({ zh: "CLI 默认", en: "CLI default" })}</option>- ))}- </select>- }- />+ {effortChoices.map((eff) => (+ <option key={eff} value={eff}>+ {eff}+ </option>+ ))}+ </select>+ }+ />+ )}</SettingSection>- {!isCodex && (+ {features.systemPrompt && (<SettingSectiontitle={tr({ zh: "系统提示", en: "System prompt" })}- description={tr({- zh: "追加到该智能体的系统提示(--append-system-prompt)。留空则使用 DeepTutor 的默认委派提示。",- en: "Appended to the agent's system prompt (--append-system-prompt). Blank uses DeepTutor's default delegate instruction.",- })}+ description={`${tr(+ SYSTEM_PROMPT_HINT[kind] ?? SYSTEM_PROMPT_HINT.claude_code,+ )} ${tr({+ zh: "留空则使用 DeepTutor 的默认委派提示。",+ en: "Blank uses DeepTutor's default delegate instruction.",+ })}`}><div className="py-4"><textarea@@ -435,7 +578,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {en: "DeepTutor drives the agent unattended — the defaults ensure it never stalls waiting for an approval prompt.",})}>- {!isCodex && (+ {features.permissionMode && (<SettingRowtitle={tr({ zh: "权限模式", en: "Permission mode" })}description={tr({@@ -451,7 +594,10 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {void save({ permission_mode: e.target.value })}>- {PERMISSION_MODES.map((o) => (+ {(kind === "gemini"+ ? GEMINI_PERMISSION_MODES+ : PERMISSION_MODES+ ).map((o) => (<option key={o.value} value={o.value}>{tr(o.label)}</option>@@ -461,7 +607,41 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {/>)}- {isCodex && (+ {features.autoApprove && (+ <SettingRow+ title={tr({ zh: "自动批准", en: "Auto-approve" })}+ description={tr({+ zh: "自动批准该智能体的权限请求。关闭后请求将被拒绝——无人值守运行无法交互确认。",+ en: "Approve the agent's permission asks automatically. When off they are rejected — an unattended run can't confirm interactively.",+ })}+ control={+ <Toggle+ checked={config.auto_approve !== false}+ disabled={busy}+ onChange={(v) => void save({ auto_approve: v })}+ />+ }+ />+ )}++ {features.thinking && (+ <SettingRow+ title={tr({ zh: "思考过程", en: "Thinking" })}+ description={tr({+ zh: "流式展示模型的思考过程(--thinking)。",+ en: "Stream the model's thinking (--thinking).",+ })}+ control={+ <Toggle+ checked={config.thinking !== false}+ disabled={busy}+ onChange={(v) => void save({ thinking: v })}+ />+ }+ />+ )}++ {features.codexSandbox && (<><SettingRowtitle={tr({ zh: "沙箱", en: "Sandbox" })}@@ -532,20 +712,22 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {</>)}- <SettingRow- title={tr({ zh: "转发图片", en: "Forward images" })}- description={tr({- zh: "允许 DeepTutor 把本轮对话中的图片附件转发给该智能体。",- en: "Let DeepTutor forward image attachments from the chat turn to this agent.",- })}- control={- <Toggle- checked={Boolean(config.forward_images)}- disabled={busy}- onChange={(v) => void save({ forward_images: v })}- />- }- />+ {features.forwardImages && (+ <SettingRow+ title={tr({ zh: "转发图片", en: "Forward images" })}+ description={tr({+ zh: "允许 DeepTutor 把本轮对话中的图片附件转发给该智能体。",+ en: "Let DeepTutor forward image attachments from the chat turn to this agent.",+ })}+ control={+ <Toggle+ checked={Boolean(config.forward_images)}+ disabled={busy}+ onChange={(v) => void save({ forward_images: v })}+ />+ }+ />+ )}</SettingSection></>)}diff --git a/web/lib/knowledge-helpers.ts b/web/lib/knowledge-helpers.tsindex 939ec1905..ba3f3ae90 100644--- a/web/lib/knowledge-helpers.ts+++ b/web/lib/knowledge-helpers.ts@@ -56,7 +56,7 @@ export interface KnowledgeBase {type?: string;/** Absolute path of a connected Obsidian vault (when type === "obsidian"). */vault_path?: string;- /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "partner". */+ /** Backend of a connected subagent (when type === "subagent"): "claude_code" | "codex" | "gemini" | "kimi" | "opencode" | "mimo" | "partner". */agent_kind?: string;/** Bound partner id when agent_kind === "partner". */partner_id?: string;diff --git a/web/lib/settings-nav.ts b/web/lib/settings-nav.tsindex b1a464255..df7b6dd57 100644--- a/web/lib/settings-nav.ts+++ b/web/lib/settings-nav.ts@@ -23,7 +23,14 @@ import {type LucideIcon,} from "lucide-react";-import { ClaudeGlyph, CodexGlyph } from "@/components/agents/agent-icons";+import {+ ClaudeGlyph,+ CodexGlyph,+ GeminiGlyph,+ KimiGlyph,+ MimoGlyph,+ OpencodeGlyph,+} from "@/components/agents/agent-icons";import type { ServiceName } from "@/components/settings/SettingsContext";/**@@ -227,6 +234,54 @@ const AGENT_CHILDREN: SettingsLeaf[] = [tile: "bg-blue-500/10 text-blue-600 dark:text-blue-400",adminOnly: true,},+ {+ key: "agent-gemini",+ href: "/settings/agents/gemini",+ label: { zh: "Gemini CLI", en: "Gemini CLI" },+ blurb: {+ zh: "DeepTutor 调用本机 Gemini CLI 时的模型与运行参数。",+ en: "Model and run params for the local Gemini CLI.",+ },+ icon: GeminiGlyph as unknown as LucideIcon,+ tile: "bg-sky-500/10 text-sky-600 dark:text-sky-400",+ adminOnly: true,+ },+ {+ key: "agent-kimi",+ href: "/settings/agents/kimi",+ label: { zh: "Kimi CLI", en: "Kimi CLI" },+ blurb: {+ zh: "DeepTutor 调用本机 Kimi CLI 时的模型与运行参数。",+ en: "Model and run params for the local Kimi CLI.",+ },+ icon: KimiGlyph as unknown as LucideIcon,+ tile: "bg-zinc-500/10 text-zinc-700 dark:text-zinc-300",+ adminOnly: true,+ },+ {+ key: "agent-opencode",+ href: "/settings/agents/opencode",+ label: { zh: "opencode", en: "opencode" },+ blurb: {+ zh: "DeepTutor 调用本机 opencode 时的模型、推理强度与运行参数。",+ en: "Model, reasoning effort, and run params for the local opencode.",+ },+ icon: OpencodeGlyph as unknown as LucideIcon,+ tile: "bg-neutral-500/10 text-neutral-700 dark:text-neutral-300",+ adminOnly: true,+ },+ {+ key: "agent-mimo",+ href: "/settings/agents/mimo",+ label: { zh: "MiMo Code", en: "MiMo Code" },+ blurb: {+ zh: "DeepTutor 调用本机 MiMo Code 时的模型、推理强度与运行参数。",+ en: "Model, reasoning effort, and run params for the local MiMo Code.",+ },+ icon: MimoGlyph as unknown as LucideIcon,+ tile: "bg-orange-500/10 text-orange-600 dark:text-orange-400",+ adminOnly: true,+ },];export const SETTINGS_CATEGORIES: SettingsCategory[] = [@@ -333,6 +388,10 @@ const STORAGE_PATHS: Record<string, string> = {"/settings/memory": "data/user/settings/main.yaml","/settings/agents/claude-code": "data/user/settings/subagent.json","/settings/agents/codex": "data/user/settings/subagent.json",+ "/settings/agents/gemini": "data/user/settings/subagent.json",+ "/settings/agents/kimi": "data/user/settings/subagent.json",+ "/settings/agents/opencode": "data/user/settings/subagent.json",+ "/settings/agents/mimo": "data/user/settings/subagent.json",};export function storagePathFor(pathname: string): string | null {diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.tsindex 46bcbdaf8..5ba3bcfa5 100644--- a/web/lib/subagents-api.ts+++ b/web/lib/subagents-api.ts@@ -149,6 +149,10 @@ export interface SubagentBackendConfig {approval?: string;network_access?: boolean;ephemeral?: boolean;+ /** Kimi / opencode / MiMo: answer permission asks affirmatively. */+ auto_approve?: boolean;+ /** Kimi: stream the model's thinking (--thinking / --no-thinking). */+ thinking?: boolean;forward_images?: boolean;extra_args?: string[];}