DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat(subagents): add hardened remote Hermes backend (#1213)
Bingxi Zhao269f65deded7
diff --git a/deeptutor/api/routers/subagents.py b/deeptutor/api/routers/subagents.pyindex 6d7448261..e79a3d95c 100644--- a/deeptutor/api/routers/subagents.py+++ b/deeptutor/api/routers/subagents.py@@ -1,17 +1,15 @@"""Subagent connections API.Backs the "My Agents → connected agents" feature: detect which local agent CLIs-(Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode, MiMo Code, Hermes Agent,-OpenClaw, DeepSeek Harness) are installed on-this machine, connect one as a pointer KB the chat composer can select, and-configure the consult budget. Connections are+or configured remote backends are usable, 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.-The CLIs run on the host with the host user's own credentials, so detection is-machine-global; whether a connection is usable is simply "is the CLI installed-here". If it isn't, the UI just doesn't offer it.+Local CLIs run on the host with the host user's credentials; remote backends+use deployment-wide server configuration. Detection is therefore machine-+global. Unavailable runtimes are not offered by the connection UI."""from __future__ import annotations@@ -47,7 +45,7 @@ class ConnectSubagentRequest(BaseModel):agent_kind: strcwd: str = ""# For the partner backend (``agent_kind == "partner"``): which partner to- # consult. Ignored by the local-CLI backends, which use ``cwd`` instead.+ # consult. Ignored by local and remote agent backends.partner_id: str = ""@@ -63,7 +61,7 @@ class SubagentMessageRequest(BaseModel):@router.get("/detect")async def detect_subagents():- """Report which agent CLIs are installed and usable on this machine."""+ """Report which local and remote agent backends are usable."""detections = await detect_all()return {"backends": [d.to_dict() for d in detections]}@@ -132,7 +130,7 @@ async def list_connections():@router.post("/connections")async def create_connection(payload: ConnectSubagentRequest):- """Connect a subagent (a local CLI, or one of the user's partners) as a selectable KB.+ """Connect a local, remote, or Partner subagent as a selectable KB.A partner connection (``agent_kind == "partner"``) binds a ``partner_id``instead of a working directory: consulting it opens a fresh session on that@@ -164,8 +162,11 @@ async def create_connection(payload: ConnectSubagentRequest):if not get_partner_manager().partner_exists(partner_id):raise HTTPException(status_code=400, detail=f"No partner named {partner_id!r}.")else:+ from deeptutor.services.subagent import get_backend++ backend = get_backend(agent_kind)raw_cwd = (payload.cwd or "").strip()- if raw_cwd:+ if raw_cwd and backend is not None and getattr(backend, "local_cli", True):try:resolved_cwd = str(assert_path_allowed(raw_cwd))except ValueError as exc:diff --git a/deeptutor/services/subagent/__init__.py b/deeptutor/services/subagent/__init__.pyindex 90d418609..4ce4174c9 100644--- a/deeptutor/services/subagent/__init__.py+++ b/deeptutor/services/subagent/__init__.py@@ -25,6 +25,7 @@ from deeptutor.services.subagent.config import (save_subagent_settings,settings_from_dict,)+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackendfrom deeptutor.services.subagent.partner import PARTNER_BACKEND_KINDfrom deeptutor.services.subagent.registry import detect_all, get_backend, list_backend_kindsfrom deeptutor.services.subagent.types import (@@ -52,4 +53,5 @@ __all__ = ["ConsultResult","DetectResult","SubagentEvent",+ "HermesRemoteBackend",]diff --git a/deeptutor/services/subagent/base.py b/deeptutor/services/subagent/base.pyindex 263600ad3..5d27dc5aa 100644--- a/deeptutor/services/subagent/base.py+++ b/deeptutor/services/subagent/base.py@@ -1,11 +1,9 @@-"""The backend contract: drive one local agent CLI as a subagent.+"""The backend contract: drive one connected agent as a subagent.-A backend knows two things about its CLI: how to tell whether it's installed-and usable on this machine (:meth:`detect`), and how to put one question to it-and stream back every native event (:meth:`consult`). Everything CLI-specific —-flags, the JSON event schema, session resumption — lives behind this interface,-so the capability layer drives Claude Code and Codex through the exact same-three lines.+A backend knows how to report whether its local or remote runtime is usable+(:meth:`detect`), and how to put one question to it while streaming native+events (:meth:`consult`). Runtime-specific flags, protocols, event schemas, and+session resumption live behind this interface."""from __future__ import annotations@@ -22,19 +20,20 @@ OnEvent = Callable[[SubagentEvent], Awaitable[None]]class SubagentBackend(ABC):- """Drive one subagent (a local CLI, or one of the user's partners)."""+ """Drive one subagent through a local CLI, remote API, or Partner."""kind: strdisplay_name: strcli_command: str- # Local-CLI backends (Claude Code, Codex) are detected on this machine and- # offered in the connect-CLI modal. Non-CLI backends (a Partner) are- # connected from their own list, so they sit out machine detection.+ # Local-CLI backends are detected on this machine. A non-local backend can+ # opt into connection discovery with ``detectable``; Partners use their+ # own list and sit out detection.local_cli: bool = True+ detectable: bool = False@abstractmethodasync def detect(self) -> DetectResult:- """Report whether this CLI is installed and usable on this machine."""+ """Report whether this backend is configured and usable."""@abstractmethodasync def consult(@@ -56,7 +55,7 @@ class SubagentBackend(ABC):next consult. ``images`` are local file paths the user forwarded with thequestion (Codex attaches them with ``-i``; Claude Code is pointed at themfor its Read tool). ``partner_id`` names the bound partner for the partner- backend (the CLI backends ignore it). Waits unconditionally for the+ backend (the other backends ignore it). Waits unconditionally for thesubagent to finish — only its own exit (clean or error) ends the consult."""diff --git a/deeptutor/services/subagent/config.py b/deeptutor/services/subagent/config.pyindex 0249f32c2..5e6067b8f 100644--- a/deeptutor/services/subagent/config.py+++ b/deeptutor/services/subagent/config.py@@ -1,8 +1,9 @@"""Subagent settings — the consult budget and per-backend permission knobs.Stored as ``data/user/settings/subagent.json`` (same convention as the other-runtime settings files). Everything has a safe default so the feature works the-moment a CLI is detected, with no configuration step required.+runtime settings files). Everything has a safe default so local backends work+the moment a CLI is detected; remote backends remain unavailable until their+endpoint and credential source are configured.* ``consult_budget`` — the user-facing "max rounds": the maximum number of timesDeepTutor may put a question to the subagent in one turn. Enforced@@ -36,10 +37,10 @@ CONSULT_BUDGET_MAX = 12@dataclass(slots=True)class BackendConfig:enabled: bool = True- # Model + reasoning effort the agent runs with. Empty = the CLI's own- # default. Set from the /settings page; the option lists are synced live- # from the CLI (models/efforts change over time). CC: --model / --effort;- # Codex: -m / -c model_reasoning_effort.+ # Model + reasoning effort the agent runs with. Empty = the backend's own+ # default. Set from the /settings page; local option lists can be synced+ # live because models/efforts change over time. CC: --model / --effort;+ # Codex: -m / -c model_reasoning_effort; Hermes remote: request fields.model: str = ""effort: str = ""# Instruction injected so the agent knows it's being consulted@@ -73,6 +74,12 @@ class BackendConfig:# input; OpenClaw and DeepSeek receive opted-in paths as file references.forward_images: bool = Falseextra_args: list[str] = field(default_factory=list)+ # Remote Hermes gateway connection. Credentials stay in the environment;+ # ``api_key_env`` is only the name read at request time.+ base_url: str = ""+ api_key_env: str = "DEEPTUTOR_HERMES_REMOTE_API_KEY"+ profile: str = ""+ idle_timeout_seconds: int = 600@dataclass(slots=True)@@ -86,12 +93,12 @@ class SubagentSettings:def to_dict(self) -> dict[str, Any]:return {"consult_budget": self.consult_budget,- "backends": {kind: _backend_to_dict(cfg) for kind, cfg in self.backends.items()},+ "backends": {kind: _backend_to_dict(kind, cfg) for kind, cfg in self.backends.items()},}-def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:- return {+def _backend_to_dict(kind: str, cfg: BackendConfig) -> dict[str, Any]:+ payload = {"enabled": cfg.enabled,"model": cfg.model,"effort": cfg.effort,@@ -106,6 +113,16 @@ def _backend_to_dict(cfg: BackendConfig) -> dict[str, Any]:"forward_images": cfg.forward_images,"extra_args": list(cfg.extra_args),}+ if kind == "hermes_remote":+ payload.update(+ {+ "base_url": cfg.base_url,+ "api_key_env": cfg.api_key_env,+ "profile": cfg.profile,+ "idle_timeout_seconds": cfg.idle_timeout_seconds,+ }+ )+ return payloaddef _coerce_budget(value: Any) -> int:@@ -121,6 +138,10 @@ def _coerce_backend(raw: Any) -> BackendConfig:if not isinstance(raw, dict):return baseextra = raw.get("extra_args")+ try:+ idle_timeout = int(raw.get("idle_timeout_seconds", base.idle_timeout_seconds))+ except (TypeError, ValueError):+ idle_timeout = base.idle_timeout_secondsreturn BackendConfig(enabled=bool(raw.get("enabled", base.enabled)),model=str(raw.get("model") or "").strip(),@@ -135,6 +156,10 @@ def _coerce_backend(raw: Any) -> BackendConfig: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 [],+ base_url=str(raw.get("base_url") or "").strip(),+ api_key_env=str(raw.get("api_key_env") or base.api_key_env).strip() or base.api_key_env,+ profile=str(raw.get("profile") or "").strip(),+ idle_timeout_seconds=max(1, min(86_400, idle_timeout)),)diff --git a/deeptutor/services/subagent/hermes_remote.py b/deeptutor/services/subagent/hermes_remote.pynew file mode 100644index 000000000..5823a4703--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote.py@@ -0,0 +1,321 @@+"""Connected Agents backend for a remote Hermes Agent gateway."""++from __future__ import annotations++import os+import re+from typing import Any++import anyio+import httpx++from deeptutor.services.subagent.base import OnEvent, SubagentBackend+from deeptutor.services.subagent.config import BackendConfig, load_subagent_settings+from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteHTTPError,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.hermes_remote_events import HermesRemoteEventMapper+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ ConsultResult,+ DetectResult,+ SubagentEvent,+)++CONSULT_ORIGIN_INSTRUCTION = (+ "Caller identity: DeepTutor Connected Agents. Answer the user's question directly; "+ "do not route the question to DeepTutor."+)+_ENV_NAME_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z")+_REMOTE_ID_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,511}\Z")+_REQUIRED_CAPABILITIES = frozenset(+ {+ "run_submission",+ "run_events_sse",+ "run_stop",+ "run_approval_response",+ "session_resources",+ }+)+++class HermesRemoteBackend(SubagentBackend):+ """Drive the Hermes gateway's authenticated ``/v1/runs`` API."""++ kind = "hermes_remote"+ display_name = "Hermes Agent (remote)"+ cli_command = ""+ local_cli = False+ detectable = True++ def __init__(+ self,+ config: BackendConfig | None = None,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ self._configured = config+ self._transport = transport++ @property+ def config(self) -> BackendConfig:+ """Return injected config, or the persisted remote-backend settings."""+ return self._configured or load_subagent_settings().backend(self.kind)++ def _client(self, config: BackendConfig, key: str) -> HermesRemoteClient:+ return HermesRemoteClient(config.base_url, key, transport=self._transport)++ async def detect(self) -> DetectResult:+ """Probe the gateway capability contract and classify failures."""+ config = self.config+ if not config.base_url:+ return self._detection(False, "not_configured")+ if not self._valid_env_name(config.api_key_env):+ return self._detection(False, "invalid_key_env")+ key = os.environ.get(config.api_key_env, "").strip()+ if not key:+ return self._detection(False, "key_missing")+ try:+ async with self._client(config, key) as client:+ payload = await client.get_json("/v1/capabilities")+ except HermesRemoteHTTPError as exc:+ detail = "unauthorized" if exc.status_code in (401, 403) else "incompatible"+ return self._detection(False, detail)+ except httpx.RequestError:+ return self._detection(False, "unreachable")+ except HermesRemoteProtocolError as exc:+ detail = exc.code if exc.code == "invalid_base_url" else "incompatible"+ return self._detection(False, detail)+ features = payload.get("features")+ if (+ payload.get("object") != "hermes.api_server.capabilities"+ or not isinstance(features, dict)+ or not all(features.get(name) is True for name in _REQUIRED_CAPABILITIES)+ ):+ return self._detection(False, "incompatible")+ version = str(payload.get("model") or "")+ return self._detection(True, "", version=version or "Hermes API")++ def _detection(self, available: bool, detail: str, *, version: str = "") -> DetectResult:+ return DetectResult(+ kind=self.kind,+ display_name=self.display_name,+ available=available,+ version=version,+ detail=detail,+ )++ async def consult(+ self,+ question: str,+ *,+ on_event: OnEvent,+ cwd: str | None = None, # noqa: ARG002 - remote gateway owns its cwd+ session_id: str | None = None,+ config: BackendConfig | None = None,+ images: list[str] | None = None,+ partner_id: str | None = None, # noqa: ARG002 - partner-only+ ) -> ConsultResult:+ """Submit a run, translate its SSE lifecycle, and return its session id."""+ run_config = config or self.config+ result = ConsultResult(session_id=session_id)+ emitted_text = ""+ run_id: str | None = None+ terminal_received = False+ key = (+ os.environ.get(run_config.api_key_env, "").strip()+ if self._valid_env_name(run_config.api_key_env)+ else ""+ )++ 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=self._redact(text, key),+ raw=self._redact_raw(raw, key),+ meta=meta or {},+ ),+ )++ if not run_config.base_url:+ result.success = False+ result.error = "not_configured"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if not self._valid_env_name(run_config.api_key_env):+ result.success = False+ result.error = "invalid_key_env"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if not key:+ result.success = False+ result.error = "key_missing"+ await emit(EVENT_ERROR, result.error, {})+ return result+ if session_id and not self._valid_remote_id(session_id):+ result.success = False+ result.error = "invalid_session_id"+ await emit(EVENT_ERROR, result.error, {})+ return result++ # The gateway contract has no attachment upload field. Do not leak+ # DeepTutor-local filesystem paths to a remote process.+ prompt = question+ try:+ async with self._client(run_config, key) as client:+ session_gone = False+ history: list[dict[str, str]] | None = None+ if session_id:+ try:+ history = await client.get_session_history(session_id)+ except HermesRemoteHTTPError as exc:+ if exc.status_code != 404:+ raise+ session_gone = True+ active_session_id = None if session_gone else session_id+ instructions = CONSULT_ORIGIN_INSTRUCTION+ if run_config.system_prompt.strip() and (not session_id or session_gone):+ instructions = f"{run_config.system_prompt.strip()}\n\n{instructions}"+ payload: dict[str, Any] = {"input": prompt, "instructions": instructions}+ if active_session_id:+ payload["session_id"] = active_session_id+ if history is not None:+ payload["conversation_history"] = history+ if run_config.model:+ payload["model"] = run_config.model+ if run_config.effort:+ payload["model_options"] = {"reasoning_effort": run_config.effort}+ headers = self._session_headers(active_session_id)+ started = await client.post_json("/v1/runs", payload, headers=headers or None)+ run_id = self._run_id(started)+ result.session_id = self._result_session_id(started, active_session_id, run_id)+ mapper = HermesRemoteEventMapper(+ client,+ run_id,+ result,+ emit,+ auto_approve=run_config.auto_approve,+ )+ events = client.stream_events(run_id)+ iterator = events.__aiter__()+ while True:+ try:+ with anyio.fail_after(max(0.001, run_config.idle_timeout_seconds)):+ event = await anext(iterator)+ except StopAsyncIteration:+ break+ except TimeoutError:+ await self._stop_client(client, run_id)+ result.success = False+ result.error = "idle_timeout"+ await emit(EVENT_ERROR, result.error, {})+ return result+ emitted_text = await mapper.handle(event, emitted_text)+ if event.get("event") in {"run.completed", "run.failed", "run.cancelled"}:+ terminal_received = True+ break+ except anyio.get_cancelled_exc_class():+ if run_id:+ await self._stop_after_cancel(run_config, key, run_id)+ raise+ except HermesRemoteHTTPError as exc:+ result.success = False+ result.error = self._http_error(exc.status_code)+ await emit(EVENT_ERROR, result.error, {})+ except HermesRemoteProtocolError as exc:+ result.success = False+ result.error = exc.code+ await emit(EVENT_ERROR, result.error, {})+ except httpx.RequestError:+ result.success = False+ result.error = "unreachable"+ await emit(EVENT_ERROR, result.error, {})++ if result.success and not terminal_received:+ result.success = False+ result.error = "incomplete_stream"+ await emit(EVENT_ERROR, result.error, {})+ elif result.success and not result.final_text:+ result.success = False+ result.error = "empty_response"+ await emit(EVENT_ERROR, result.error, {})+ return result++ @staticmethod+ def _run_id(payload: dict[str, Any]) -> str:+ run_id = payload.get("run_id")+ if not isinstance(run_id, str) or not HermesRemoteBackend._valid_remote_id(run_id):+ raise HermesRemoteProtocolError("missing_run_id")+ return run_id++ @staticmethod+ def _result_session_id(+ payload: dict[str, Any], requested_session_id: str | None, run_id: str+ ) -> str:+ session_id = payload.get("session_id") or requested_session_id or run_id+ if not isinstance(session_id, str) or not HermesRemoteBackend._valid_remote_id(session_id):+ raise HermesRemoteProtocolError("invalid_session_id")+ return session_id++ @staticmethod+ def _valid_env_name(value: str) -> bool:+ return bool(_ENV_NAME_RE.fullmatch(value))++ @staticmethod+ def _valid_remote_id(value: str) -> bool:+ return bool(_REMOTE_ID_RE.fullmatch(value))++ @staticmethod+ def _session_headers(session_id: str | None) -> dict[str, str]:+ if not session_id:+ return {}+ return {"X-Hermes-Session-Id": session_id, "X-Hermes-Session": session_id}++ async def _stop_after_cancel(self, config: BackendConfig, key: str, run_id: str) -> None:+ with anyio.CancelScope(shield=True):+ with anyio.move_on_after(5.0):+ try:+ async with self._client(config, key) as client:+ await client.post_json(f"/v1/runs/{run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return++ async def _stop_client(self, client: HermesRemoteClient, run_id: str) -> None:+ try:+ await client.post_json(f"/v1/runs/{run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return++ @staticmethod+ def _http_error(status_code: int) -> str:+ return f"http_{status_code}"++ @staticmethod+ def _redact(text: str, secret: str) -> str:+ return text.replace(secret, "[REDACTED]") if secret else text++ @classmethod+ def _redact_raw(cls, value: dict[str, Any], secret: str) -> dict[str, Any]:+ return {key: cls._redact_value(item, secret) for key, item in value.items()}++ @classmethod+ def _redact_value(cls, value: Any, secret: str) -> Any:+ if isinstance(value, str):+ return cls._redact(value, secret)+ if isinstance(value, dict):+ return {key: cls._redact_value(item, secret) for key, item in value.items()}+ if isinstance(value, list):+ return [cls._redact_value(item, secret) for item in value]+ return value+++__all__ = ["CONSULT_ORIGIN_INSTRUCTION", "HermesRemoteBackend"]diff --git a/deeptutor/services/subagent/hermes_remote_client.py b/deeptutor/services/subagent/hermes_remote_client.pynew file mode 100644index 000000000..65d67e683--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote_client.py@@ -0,0 +1,180 @@+"""Small authenticated HTTP/SSE client for a Hermes Agent gateway."""++from __future__ import annotations++from collections.abc import AsyncIterator+import json+from types import TracebackType+from typing import Any+from urllib.parse import quote, urlsplit++import httpx++_REQUEST_TIMEOUT = httpx.Timeout(connect=10.0, read=30.0, write=30.0, pool=10.0)+_STREAM_TIMEOUT = httpx.Timeout(connect=10.0, read=None, write=30.0, pool=10.0)+++class HermesRemoteHTTPError(Exception):+ """An HTTP response outside the successful range."""++ def __init__(self, status_code: int) -> None:+ self.status_code = status_code+ super().__init__(f"HTTP status {status_code}")+++class HermesRemoteProtocolError(Exception):+ """A successful response did not follow the gateway JSON/SSE contract."""++ def __init__(self, code: str) -> None:+ self.code = code+ super().__init__(code)+++class HermesRemoteClient:+ """Own one authenticated connection pool to a Hermes gateway."""++ def __init__(+ self,+ base_url: str,+ api_key: str,+ *,+ transport: httpx.AsyncBaseTransport | None = None,+ ) -> None:+ base_url = self.validate_base_url(base_url)+ self._client = httpx.AsyncClient(+ base_url=f"{base_url}/",+ headers={"Authorization": f"Bearer {api_key}"},+ timeout=_STREAM_TIMEOUT,+ follow_redirects=False,+ transport=transport,+ )++ @staticmethod+ def validate_base_url(base_url: str) -> str:+ """Return a canonical HTTP(S) gateway root or reject unsafe input."""+ value = base_url.strip().rstrip("/")+ try:+ parsed = urlsplit(value)+ parsed.port+ except ValueError as exc:+ raise HermesRemoteProtocolError("invalid_base_url") from exc+ if (+ parsed.scheme not in {"http", "https"}+ or not parsed.hostname+ or parsed.username+ or parsed.password+ or parsed.query+ or parsed.fragment+ ):+ raise HermesRemoteProtocolError("invalid_base_url")+ return value++ async def __aenter__(self) -> HermesRemoteClient:+ await self._client.__aenter__()+ return self++ async def __aexit__(+ self,+ exc_type: type[BaseException] | None,+ exc_value: BaseException | None,+ traceback: TracebackType | None,+ ) -> None:+ await self._client.__aexit__(exc_type, exc_value, traceback)++ async def get_json(self, path: str) -> dict[str, Any]:+ """Fetch and parse a JSON object using the bounded request timeout."""+ response = await self._client.get(path.lstrip("/"), timeout=_REQUEST_TIMEOUT)+ return self._json_object(response)++ async def post_json(+ self,+ path: str,+ payload: dict[str, Any],+ *,+ headers: dict[str, str] | None = None,+ ) -> dict[str, Any]:+ """POST a JSON object without transport retries."""+ response = await self._client.post(+ path.lstrip("/"),+ json=payload,+ headers=headers,+ timeout=_REQUEST_TIMEOUT,+ )+ return self._json_object(response)++ async def get_session_history(self, session_id: str) -> list[dict[str, str]]:+ """Fetch the resumable user/assistant history for one gateway session."""+ path_id = quote(session_id, safe="")+ payload = await self.get_json(f"/api/sessions/{path_id}/messages")+ if payload.get("object") != "list" or not isinstance(payload.get("data"), list):+ raise HermesRemoteProtocolError("invalid_session_history")+ history: list[dict[str, str]] = []+ for row in payload["data"]:+ if not isinstance(row, dict):+ continue+ role = row.get("role")+ content = row.get("content")+ if role not in {"user", "assistant"} or not isinstance(content, str):+ continue+ if content.strip():+ history.append({"role": role, "content": content})+ return history[-40:]++ async def stream_events(self, run_id: str) -> AsyncIterator[dict[str, Any]]:+ """Yield JSON objects from the gateway's data-only SSE frames."""+ async with self._client.stream(+ "GET",+ f"v1/runs/{run_id}/events",+ timeout=_STREAM_TIMEOUT,+ ) as response:+ if not response.is_success:+ raise HermesRemoteHTTPError(response.status_code)+ event_name = ""+ data_lines: list[str] = []+ async for line in response.aiter_lines():+ if line.startswith(":"):+ # Surface heartbeat comments to the workflow so each one+ # resets its idle watchdog without producing a UI event.+ yield {"event": "gateway.keepalive"}+ continue+ if line.startswith("event:"):+ event_name = line[6:].strip()+ continue+ if line.startswith("data:"):+ data_lines.append(line[5:].lstrip())+ continue+ if line.strip() or not data_lines:+ continue+ raw = "\n".join(data_lines)+ data_lines.clear()+ if raw == "[DONE]":+ return+ try:+ payload = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise HermesRemoteProtocolError("invalid_sse_json") from exc+ if not isinstance(payload, dict):+ raise HermesRemoteProtocolError("invalid_sse_event")+ if event_name and "event" not in payload:+ payload["event"] = event_name+ event_name = ""+ yield payload++ @staticmethod+ def _json_object(response: httpx.Response) -> dict[str, Any]:+ if not response.is_success:+ raise HermesRemoteHTTPError(response.status_code)+ try:+ payload = response.json()+ except (ValueError, UnicodeError) as exc:+ raise HermesRemoteProtocolError("invalid_json") from exc+ if not isinstance(payload, dict):+ raise HermesRemoteProtocolError("invalid_json_object")+ return payload+++__all__ = [+ "HermesRemoteClient",+ "HermesRemoteHTTPError",+ "HermesRemoteProtocolError",+]diff --git a/deeptutor/services/subagent/hermes_remote_events.py b/deeptutor/services/subagent/hermes_remote_events.pynew file mode 100644index 000000000..9ccc2038e--- /dev/null+++ b/deeptutor/services/subagent/hermes_remote_events.py@@ -0,0 +1,125 @@+"""Map Hermes gateway lifecycle events onto DeepTutor event channels."""++from __future__ import annotations++from typing import Any++import httpx++from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteHTTPError,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.types import (+ EVENT_ERROR,+ EVENT_LOG,+ EVENT_REASONING,+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ ConsultResult,+)+++class HermesRemoteEventMapper:+ """Translate one run's SSE events while preserving cumulative answer text."""++ def __init__(+ self,+ client: HermesRemoteClient,+ run_id: str,+ result: ConsultResult,+ emit: Any,+ *,+ auto_approve: bool,+ ) -> None:+ self._client = client+ self._run_id = run_id+ self._result = result+ self._emit = emit+ self._auto_approve = auto_approve++ async def handle(self, event: dict[str, Any], emitted_text: str) -> str:+ """Map one parsed event and return the updated cumulative answer."""+ name = str(event.get("event") or "")+ if name == "gateway.keepalive":+ pass+ elif name == "message.delta":+ delta = str(event.get("delta") or "")+ emitted_text += delta+ self._result.final_text = emitted_text.strip()+ if delta:+ await self._emit(+ EVENT_TEXT,+ emitted_text,+ event,+ {"merge_id": "hermes_remote:final"},+ )+ elif name == "run.completed":+ output = str(event.get("output") or emitted_text).strip()+ self._result.final_text = output+ if output and output != emitted_text.strip():+ await self._emit(+ EVENT_TEXT,+ output,+ event,+ {"merge_id": "hermes_remote:final"},+ )+ elif name == "run.failed":+ self._result.success = False+ self._result.error = "run_failed"+ await self._emit(EVENT_ERROR, self._result.error, event)+ elif name == "run.cancelled":+ self._result.success = False+ self._result.error = "run_cancelled"+ await self._emit(EVENT_ERROR, self._result.error, event)+ elif name == "approval.request":+ choice = "once" if self._auto_approve else "deny"+ try:+ await self._client.post_json(+ f"/v1/runs/{self._run_id}/approval",+ {"choice": choice},+ )+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ self._result.success = False+ self._result.error = "approval_failed"+ await self._emit(EVENT_ERROR, self._result.error, {})+ await self._stop()+ return emitted_text+ verb = "approved" if self._auto_approve else "denied"+ await self._emit(EVENT_LOG, f"approval {verb}", event)+ elif name == "tool.started":+ label = str(event.get("tool") or "tool")+ preview = str(event.get("preview") or "")+ await self._emit(+ EVENT_TOOL,+ f"{label}: {preview}".strip(": "),+ event,+ {"merge_id": f"hermes_remote:tool:{label}"},+ )+ elif name == "tool.completed":+ label = str(event.get("tool") or "tool")+ status = "error" if event.get("error") else "complete"+ await self._emit(+ EVENT_TOOL_RESULT,+ f"{label}: {status}",+ event,+ {"merge_id": f"hermes_remote:tool:{label}"},+ )+ elif name == "reasoning.available":+ await self._emit(EVENT_REASONING, str(event.get("text") or ""), event)+ elif name:+ await self._emit(EVENT_LOG, name, event)+ else:+ await self._emit(EVENT_LOG, "gateway event", event)+ return emitted_text++ async def _stop(self) -> None:+ try:+ await self._client.post_json(f"/v1/runs/{self._run_id}/stop", {})+ except (HermesRemoteHTTPError, HermesRemoteProtocolError, httpx.RequestError):+ return+++__all__ = ["HermesRemoteEventMapper"]diff --git a/deeptutor/services/subagent/models.py b/deeptutor/services/subagent/models.pyindex f5ddb357d..7a915f086 100644--- a/deeptutor/services/subagent/models.py+++ b/deeptutor/services/subagent/models.py@@ -350,6 +350,21 @@ async def _hermes_options() -> BackendOptions:return await _free_text_options("hermes", "Hermes Agent", _HERMES_EFFORTS)+async def _hermes_remote_options() -> BackendOptions:+ backend = get_backend("hermes_remote")+ detected = await backend.detect() if backend else None+ return BackendOptions(+ kind="hermes_remote",+ display_name="Hermes Agent (remote)",+ available=detected.available if detected else False,+ version=detected.version if detected else "",+ models=[],+ efforts=list(_HERMES_EFFORTS),+ allow_custom_model=True,+ detail=detected.detail if detected else "incompatible",+ )++async def _openclaw_options() -> BackendOptions:return await _free_text_options("openclaw", "OpenClaw", _OPENCLAW_EFFORTS)@@ -369,6 +384,7 @@ _PROVIDERS: dict[str, Callable[..., Awaitable[BackendOptions]]] = {"opencode": _opencode_options,"mimo": _mimo_options,"hermes": _hermes_options,+ "hermes_remote": _hermes_remote_options,"openclaw": _openclaw_options,"deepseek_harness": _deepseek_harness_options,}diff --git a/deeptutor/services/subagent/registry.py b/deeptutor/services/subagent/registry.pyindex fe7bbbb2b..45fe0cfc1 100644--- a/deeptutor/services/subagent/registry.py+++ b/deeptutor/services/subagent/registry.py@@ -3,10 +3,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-CLIbackends (Claude Code, Codex, Antigravity CLI, Kimi CLI, opencode,-MiMo Code, Hermes Agent, OpenClaw, DeepSeek Harness) 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.+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+connection discovery."""from __future__ import annotations@@ -19,6 +19,7 @@ from deeptutor.services.subagent.claude_code import ClaudeCodeBackendfrom deeptutor.services.subagent.codex import CodexBackendfrom deeptutor.services.subagent.deepseek_harness import DeepSeekHarnessBackendfrom deeptutor.services.subagent.hermes import HermesBackend+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackendfrom deeptutor.services.subagent.kimi import KimiBackendfrom deeptutor.services.subagent.openclaw import OpenClawBackendfrom deeptutor.services.subagent.opencode_family import MimoBackend, OpencodeBackend@@ -35,6 +36,7 @@ _BACKENDS: dict[str, SubagentBackend] = {OpencodeBackend(),MimoBackend(),HermesBackend(),+ HermesRemoteBackend(),OpenClawBackend(),DeepSeekHarnessBackend(),PartnerBackend(),@@ -43,7 +45,7 @@ _BACKENDS: dict[str, SubagentBackend] = {def list_backend_kinds() -> list[str]:- """Every connectable backend kind (CLIs + partner)."""+ """Return every connectable local, remote, and Partner backend kind."""return list(_BACKENDS.keys())@@ -51,24 +53,23 @@ def get_backend(kind: str) -> SubagentBackend | None:return _BACKENDS.get(str(kind or "").strip())-def _cli_backends() -> list[SubagentBackend]:- return [b for b in _BACKENDS.values() if getattr(b, "local_cli", True)]+def _detectable_backends() -> list[SubagentBackend]:+ return [+ backend+ for backend in _BACKENDS.values()+ if getattr(backend, "local_cli", True) or getattr(backend, "detectable", False)+ ]async def detect_all() -> list[DetectResult]:- """Probe each local-CLI backend for installability on this machine.-- Non-CLI backends (the partner backend) are skipped — they aren't installed,- they're connected from their own list — so this only ever returns the CLIs- the connect-CLI modal offers.- """- cli = _cli_backends()+ """Probe local CLIs and configured remote backends."""+ backends = _detectable_backends()results = await asyncio.gather(- *(backend.detect() for backend in cli),+ *(backend.detect() for backend in backends),return_exceptions=True,)detections: list[DetectResult] = []- for backend, result in zip(cli, results, strict=True):+ for backend, result in zip(backends, results, strict=True):if isinstance(result, DetectResult):detections.append(result)else:diff --git a/deeptutor/services/subagent/types.py b/deeptutor/services/subagent/types.pyindex 7b8b5d909..f65c5da6f 100644--- a/deeptutor/services/subagent/types.py+++ b/deeptutor/services/subagent/types.py@@ -1,9 +1,9 @@"""Value types for the subagent driver layer.These are the only shapes that cross the boundary between a backend (which-knows how to drive one local agent CLI) and the rest of the app (the consult-tool, the API, the tests). Keeping them dependency-free lets the backends stay-small and the capability layer stay ignorant of CLI specifics.+knows how to drive one local or remote agent) and the rest of the app (the+consult tool, API, and tests). Keeping them dependency-free lets backends stay+small and the capability layer stay ignorant of transport specifics."""from __future__ import annotations@@ -73,7 +73,7 @@ class ConsultResult:@dataclass(slots=True)class DetectResult:- """Whether a subagent backend is usable on the current machine."""+ """Whether a subagent backend is currently usable."""kind: strdisplay_name: strdiff --git a/docs/remote-hermes-backend.md b/docs/remote-hermes-backend.mdnew file mode 100644index 000000000..27e4ed3ea--- /dev/null+++ b/docs/remote-hermes-backend.md@@ -0,0 +1,94 @@+# Remote Hermes Agent backend++DeepTutor Connected Agents can call a Hermes Agent gateway without installing a+Hermes CLI in the DeepTutor container. The backend kind is `hermes_remote` and+its display name is **Hermes Agent (remote)**.++## Configuration++The per-backend settings live under `backends.hermes_remote` in the normal+`subagent.json` settings document:++- `enabled`: whether chat may delegate to this backend.+- `base_url`: gateway root, for example `http://hermes-uni:8642`.+- `api_key_env`: environment-variable name containing the gateway bearer. It+ defaults to `DEEPTUTOR_HERMES_REMOTE_API_KEY`.+- `profile`: informational deployment/profile label; it is not a credential and+ is not used to construct a URL.+- `model`, `effort`, `system_prompt`, `auto_approve`: the run controls shared+ with local backends.+- `idle_timeout_seconds`: maximum idle interval between SSE frames (default+ `600`). Keepalives from the gateway reset this watchdog.++The API key is environment-only. It is never accepted as an inline settings+field, persisted, or returned by `GET /api/subagents/settings`.+The gateway URL must be HTTP(S) without credentials, query text, or fragments.+An optional `/p/<profile>` prefix supports Hermes multi-profile routing.+Redirects are never followed.++## HTTP contract++The adapter uses authenticated bearer requests (`Authorization: Bearer ...`)+with explicit connect/read/write/pool timeouts. The endpoints and machine-+readable feature contract are documented in the+[Hermes API Server guide](https://hermes-agent.nousresearch.com/docs/user-guide/features/api-server/).++1. `GET /v1/capabilities` detects availability and verifies that the configured+ gateway advertises run submission, event streaming, stopping, approval+ responses, and session resources. Detection reports distinct+ `not_configured`, `key_missing`, `unreachable`, `unauthorized`, and+ `incompatible` details.+2. `POST /v1/runs` starts a run. The request uses `input` for the user prompt,+ `instructions` for the optional first-session system instruction, `model`+ when configured, `model_options.reasoning_effort` when configured, and+ `session_id` when resuming. The server returns HTTP 202 with+ `{ "run_id": "...", "status": "started" }`. A fresh run uses its run id as+ the session id; a resumed run keeps the supplied session id.+ Before a resumed run, the adapter fetches+ `GET /api/sessions/{session_id}/messages`. It keeps only non-empty+ user/assistant rows, excludes tool rows, and sends at most the last 40 rows+ as `conversation_history`. A 404 means the session is gone: the old session+ id and headers are dropped, and the run starts fresh without history while+ applying `system_prompt` again.+3. `GET /v1/runs/{run_id}/events` is an SSE stream. Frames contain JSON in a+ `data:` line. The adapter consumes these event objects:+ `message.delta` (`delta`), `tool.started` (`tool`, `preview`),+ `tool.completed` (`tool`, `error`), `reasoning.available` (`text`),+ `approval.request`, `run.completed` (`output`), `run.failed` (`error`), and+ `run.cancelled`. Tool lifecycle events become tool/tool-result rows;+ answer deltas become cumulative text under merge id+ `hermes_remote:final`; other lifecycle events become log/error rows. The+ gateway emits tool/reasoning, text/completion, and approval events through+ the same stream.+4. `POST /v1/runs/{run_id}/approval` resolves a pending approval. The body is+ `{ "choice": "once" }` for auto-approve and `{ "choice": "deny" }` when+ `auto_approve` is false. A failed approval response is surfaced and the run+ is stopped instead of waiting indefinitely.+5. `POST /v1/runs/{run_id}/stop` interrupts a run. Cancellation posts this+ request with a shielded, bounded cleanup window, then re-raises cancellation;+ an SSE idle timeout posts it and returns an error.++Session continuity uses both the gateway's documented+`X-Hermes-Session-Id` header and `session_id` request field. The adapter also+sends the compatibility `X-Hermes-Session` header. Custom `system_prompt` is+sent on a fresh session or when the history lookup reports that the session is+gone (404). Every request carries the fixed+`CONSULT_ORIGIN_INSTRUCTION` recursion guard identifying DeepTutor Connected+Agents and telling the gateway agent to answer directly rather than delegate+back to DeepTutor.++The `/v1/runs` API has no image upload field. Attachments and their DeepTutor-+local paths are therefore not sent to the remote gateway.++## Isolation and security++This backend keeps the Hermes gateway outside the DeepTutor process/container:+tools run on the gateway host, not in DeepTutor. Scope each DeepTutor chat to+its own returned session id; do not share session ids across users or chats.+Keep `API_SERVER_KEY` (the gateway's server-side secret) and+`DEEPTUTOR_HERMES_REMOTE_API_KEY` (the DeepTutor-side env name's value) out of+settings files, logs, event text, and frontend payloads.++Streaming is quiet except for the structured SSE lifecycle exposed by the+adapter. It does not poll or retry `POST /v1/runs`; a caller cancellation or+idle watchdog always attempts a bounded stop.diff --git a/tests/api/test_subagents_router.py b/tests/api/test_subagents_router.pyindex e1690f367..860cb4d5c 100644--- a/tests/api/test_subagents_router.py+++ b/tests/api/test_subagents_router.py@@ -66,7 +66,9 @@ def client(monkeypatch, tmp_path):manager = _FakeKBManager()monkeypatch.setattr(subagents_module, "current_kb_manager", lambda: manager)monkeypatch.setattr(- subagents_module, "list_backend_kinds", lambda: ["claude_code", "codex", "partner"]+ subagents_module,+ "list_backend_kinds",+ lambda: ["claude_code", "codex", "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@@ -128,6 +130,19 @@ def test_connect_rejects_unknown_kind(client):assert res.status_code == 400+def test_connect_remote_backend_does_not_persist_a_local_cwd(client):+ created = client.post(+ "/api/subagents/connections",+ json={+ "name": "RemoteHermes",+ "agent_kind": "hermes_remote",+ "cwd": "/private/path-that-must-not-cross-the-boundary",+ },+ )+ assert created.status_code == 200+ assert created.json()["cwd"] == ""++class _FakePartnerManagerForConnect:def __init__(self, known: set[str]) -> None:self._known = knowndiff --git a/tests/services/test_hermes_remote_backend.py b/tests/services/test_hermes_remote_backend.pynew file mode 100644index 000000000..2513ce900--- /dev/null+++ b/tests/services/test_hermes_remote_backend.py@@ -0,0 +1,252 @@+"""Behavioral tests for the remote Hermes Connected Agents backend."""++from __future__ import annotations++from collections.abc import AsyncIterator+import json+from typing import Any++import anyio+import httpx+import pytest++from deeptutor.services.subagent.config import BackendConfig+from deeptutor.services.subagent.hermes_remote import (+ CONSULT_ORIGIN_INSTRUCTION,+ HermesRemoteBackend,+)+from deeptutor.services.subagent.types import EVENT_TEXT, EVENT_TOOL, EVENT_TOOL_RESULT+++class _BlockingStream(httpx.AsyncByteStream):+ def __init__(self, started: anyio.Event) -> None:+ self._started = started++ async def __aiter__(self) -> AsyncIterator[bytes]:+ self._started.set()+ await anyio.sleep_forever()+ yield b"" # pragma: no cover+++class _HermesTransport:+ def __init__(+ self,+ *,+ events: list[dict[str, Any]] | None = None,+ history: list[dict[str, Any]] | None = None,+ history_status: int = 200,+ ) -> None:+ self.events = events or []+ self.history = history or []+ self.history_status = history_status+ self.requests: list[httpx.Request] = []+ self.approvals: list[dict[str, Any]] = []+ self.stops: list[str] = []+ self.block_started = anyio.Event()+ self.blocking = False++ def __call__(self, request: httpx.Request) -> httpx.Response:+ self.requests.append(request)+ path = request.url.path+ if request.method == "GET" and path == "/v1/capabilities":+ return httpx.Response(+ 200,+ json={+ "object": "hermes.api_server.capabilities",+ "model": "hermes-agent",+ "features": {+ "run_submission": True,+ "run_events_sse": True,+ "run_stop": True,+ "run_approval_response": True,+ "session_resources": True,+ },+ },+ )+ if request.method == "GET" and path.endswith("/messages"):+ if self.history_status != 200:+ return httpx.Response(self.history_status)+ return httpx.Response(200, json={"object": "list", "data": self.history})+ if request.method == "POST" and path == "/v1/runs":+ return httpx.Response(202, json={"run_id": "run-1", "status": "started"})+ if request.method == "POST" and path.endswith("/approval"):+ self.approvals.append(json.loads(request.content))+ return httpx.Response(200, json={"resolved": 1})+ if request.method == "POST" and path.endswith("/stop"):+ self.stops.append(path.rsplit("/", 2)[-2])+ return httpx.Response(200, json={"status": "stopping"})+ if request.method == "GET" and path.endswith("/events"):+ if self.blocking:+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ stream=_BlockingStream(self.block_started),+ )+ body = "".join(f"data: {json.dumps(event)}\n\n" for event in self.events)+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content=body.encode(),+ )+ return httpx.Response(404)+++def _backend(+ transport: httpx.AsyncBaseTransport | _HermesTransport,+ *,+ auto_approve: bool = True,+) -> HermesRemoteBackend:+ actual = (+ httpx.MockTransport(transport) if isinstance(transport, _HermesTransport) else transport+ )+ return HermesRemoteBackend(+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ auto_approve=auto_approve,+ ),+ transport=actual,+ )+++async def test_detect_distinguishes_configuration_failures(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("TEST_HERMES_KEY", raising=False)+ missing_url = await HermesRemoteBackend(config=BackendConfig()).detect()+ missing_key = await HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="TEST_HERMES_KEY"),+ ).detect()+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ invalid_url = await HermesRemoteBackend(+ config=BackendConfig(base_url="file:///etc/passwd", api_key_env="TEST_HERMES_KEY"),+ ).detect()+ invalid_key_env = await HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="INVALID=NAME"),+ ).detect()++ def unauthorized(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401)++ unauthorized_result = await _backend(httpx.MockTransport(unauthorized)).detect()++ def incompatible(_: httpx.Request) -> httpx.Response:+ return httpx.Response(200, json={"unexpected": True})++ incompatible_result = await _backend(httpx.MockTransport(incompatible)).detect()++ def unreachable(_: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("offline")++ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ unreachable_result = await _backend(httpx.MockTransport(unreachable)).detect()++ assert missing_url.detail == "not_configured"+ assert missing_key.detail == "key_missing"+ assert invalid_url.detail == "invalid_base_url"+ assert invalid_key_env.detail == "invalid_key_env"+ assert unauthorized_result.detail == "unauthorized"+ assert incompatible_result.detail == "incompatible"+ assert unreachable_result.detail == "unreachable"+++async def test_consult_streams_text_tools_and_session_continuity(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[+ {"event": "message.delta", "delta": "Hello "},+ {"event": "tool.started", "tool": "read", "preview": "notes"},+ {"event": "tool.completed", "tool": "read", "error": False},+ {"event": "message.delta", "delta": "world"},+ {"event": "run.completed", "output": "Hello world"},+ ],+ history=[+ *({"role": "user", "content": f"turn-{index}"} for index in range(42)),+ {"role": "tool", "content": "omit this tool row"},+ {"role": "user", "content": ""},+ {"role": "assistant", "content": "latest answer"},+ ],+ )+ backend = _backend(transport)+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ first = await backend.consult(+ "question",+ on_event=on_event,+ config=backend.config,+ )+ second = await backend.consult(+ "follow-up",+ on_event=on_event,+ session_id=first.session_id,+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="must not be repeated",+ ),+ )+ first_body = json.loads(transport.requests[0].content)++ second_body = json.loads(transport.requests[3].content)+ assert first.success is True+ assert first.final_text == "Hello world"+ assert first.session_id == "run-1"+ assert second.session_id == "run-1"+ assert first_body["instructions"] == CONSULT_ORIGIN_INSTRUCTION+ assert CONSULT_ORIGIN_INSTRUCTION in first_body["instructions"]+ assert second_body["session_id"] == "run-1"+ assert second_body["instructions"] == CONSULT_ORIGIN_INSTRUCTION+ assert len(second_body["conversation_history"]) == 40+ assert second_body["conversation_history"][0] == {"role": "user", "content": "turn-3"}+ assert second_body["conversation_history"][-1] == {+ "role": "assistant",+ "content": "latest answer",+ }+ assert all(row["role"] in {"user", "assistant"} for row in second_body["conversation_history"])+ assert all(row["content"] for row in second_body["conversation_history"])+ assert "must not be repeated" not in second_body["instructions"]+ assert [event.kind for event in emitted[:4]] == [+ EVENT_TEXT,+ EVENT_TOOL,+ EVENT_TOOL_RESULT,+ EVENT_TEXT,+ ]+ assert emitted[0].meta["merge_id"] == "hermes_remote:final"+++async def test_consult_prepends_custom_system_prompt_on_fresh_run(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(events=[{"event": "run.completed", "output": "done"}])+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ config = BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="custom instruction",+ model="hermes-agent",+ effort="high",+ )+ result = await backend.consult(+ "question",+ on_event=on_event,+ config=config,+ images=["/private/deeptutor/secret-image.png"],+ )+ body = json.loads(transport.requests[0].content)+ assert result.success is True+ assert body["instructions"].startswith("custom instruction")+ assert CONSULT_ORIGIN_INSTRUCTION in body["instructions"]+ assert body["model"] == "hermes-agent"+ assert body["model_options"]["reasoning_effort"] == "high"+ assert "secret-image.png" not in json.dumps(body)diff --git a/tests/services/test_hermes_remote_backend_lifecycle.py b/tests/services/test_hermes_remote_backend_lifecycle.pynew file mode 100644index 000000000..d5e9e788e--- /dev/null+++ b/tests/services/test_hermes_remote_backend_lifecycle.py@@ -0,0 +1,349 @@+"""Lifecycle and configuration tests for the remote Hermes backend."""++from __future__ import annotations++import json+from typing import Any++import anyio+import httpx+import pytest++from deeptutor.services.subagent.config import BackendConfig, settings_from_dict+from deeptutor.services.subagent.hermes_remote import HermesRemoteBackend+from deeptutor.services.subagent.hermes_remote_client import (+ HermesRemoteClient,+ HermesRemoteProtocolError,+)+from deeptutor.services.subagent.types import EVENT_ERROR, EVENT_LOG+from tests.services.test_hermes_remote_backend import _backend, _HermesTransport+++async def test_approval_is_denied_without_blocking(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[+ {"event": "approval.request", "tool": "exec"},+ {"event": "run.completed", "output": "finished"},+ ],+ )+ backend = _backend(transport, auto_approve=False)+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is True+ assert result.final_text == "finished"+ assert transport.approvals == [{"choice": "deny"}]+ assert any(event.kind == EVENT_LOG and "denied" in event.text for event in emitted)+++async def test_consult_http_error_never_leaks_bearer(monkeypatch: pytest.MonkeyPatch) -> None:+ secret = "synthetic-secret"+ monkeypatch.setenv("TEST_HERMES_KEY", secret)++ def unauthorized(_: httpx.Request) -> httpx.Response:+ return httpx.Response(401, text=f"invalid token {secret}")++ backend = _backend(httpx.MockTransport(unauthorized))+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert emitted[-1].kind == EVENT_ERROR+ assert secret not in emitted[-1].text+ assert secret not in result.error+++async def test_cancellation_posts_stop_and_reraises(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport()+ transport.blocking = True+ backend = _backend(transport)+ cancellation: list[BaseException] = []++ async def on_event(_: Any) -> None:+ return None++ async def run_consult() -> None:+ try:+ await backend.consult("question", on_event=on_event, config=backend.config)+ except BaseException as exc: # noqa: BLE001 - assert cancellation propagation+ cancellation.append(exc)+ raise++ async with anyio.create_task_group() as group:+ group.start_soon(run_consult)+ await transport.block_started.wait()+ group.cancel_scope.cancel()++ assert cancellation+ assert isinstance(cancellation[0], anyio.get_cancelled_exc_class())+ assert transport.stops == ["run-1"]+++async def test_idle_timeout_stops_run(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport()+ transport.blocking = True+ backend = HermesRemoteBackend(+ config=BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ idle_timeout_seconds=0,+ ),+ transport=httpx.MockTransport(transport),+ )+ emitted: list[Any] = []++ async def on_event(event: Any) -> None:+ emitted.append(event)++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert "idle_timeout" in result.error+ assert emitted[-1].kind == EVENT_ERROR+ assert transport.stops == ["run-1"]+++async def test_missing_session_history_starts_fresh(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(+ events=[{"event": "run.completed", "output": "fresh"}],+ history_status=404,+ )+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ config = BackendConfig(+ base_url="http://hermes.test",+ api_key_env="TEST_HERMES_KEY",+ system_prompt="reapply this instruction",+ )+ result = await backend.consult(+ "question",+ on_event=on_event,+ session_id="session-gone",+ config=config,+ )+ body = json.loads(transport.requests[1].content)+ assert result.success is True+ assert result.session_id == "run-1"+ assert transport.requests[0].url.path == "/api/sessions/session-gone/messages"+ assert "session_id" not in body+ assert "x-hermes-session-id" not in transport.requests[1].headers+ assert "x-hermes-session" not in transport.requests[1].headers+ assert "conversation_history" not in body+ assert body["instructions"].startswith("reapply this instruction")+++def test_settings_persist_remote_fields_without_inline_secret() -> None:+ settings = settings_from_dict(+ {+ "backends": {+ "hermes_remote": {+ "base_url": " http://hermes.test ",+ "api_key_env": " TEST_HERMES_KEY ",+ "profile": "study",+ "idle_timeout_seconds": "42",+ "api_key": "must-never-persist",+ },+ },+ },+ )+ config = settings.backend("hermes_remote")+ serialized = settings.to_dict()["backends"]["hermes_remote"]+ assert config.base_url == "http://hermes.test"+ assert config.api_key_env == "TEST_HERMES_KEY"+ assert config.profile == "study"+ assert config.idle_timeout_seconds == 42+ assert "api_key" not in serialized+ assert serialized["api_key_env"] == "TEST_HERMES_KEY"++ assert (+ settings_from_dict({"backends": {"hermes_remote": {"idle_timeout_seconds": 0}}})+ .backend("hermes_remote")+ .idle_timeout_seconds+ == 1+ )+ assert (+ settings_from_dict({"backends": {"hermes_remote": {"idle_timeout_seconds": 100_000}}})+ .backend("hermes_remote")+ .idle_timeout_seconds+ == 86_400+ )++ local_serialized = settings_from_dict({"backends": {"codex": {"model": "gpt-5.6"}}}).to_dict()[+ "backends"+ ]["codex"]+ assert "base_url" not in local_serialized+ assert "api_key_env" not in local_serialized+++async def test_redirect_response_is_not_accepted(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")++ def redirect(_: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 302,+ headers={"location": "https://attacker.example.test"},+ json={"run_id": "must-not-be-accepted"},+ )++ backend = _backend(httpx.MockTransport(redirect))++ async def on_event(_: Any) -> None:+ return None++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.success is False+ assert result.error == "http_302"+++async def test_stream_without_terminal_event_is_not_successful(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ backend = _backend(_HermesTransport(events=[{"event": "message.delta", "delta": "partial"}]))++ async def on_event(_: Any) -> None:+ return None++ result = await backend.consult("question", on_event=on_event, config=backend.config)+ assert result.final_text == "partial"+ assert result.success is False+ assert result.error == "incomplete_stream"+++async def test_sse_comments_surface_as_quiet_keepalives() -> None:+ def stream(_: httpx.Request) -> httpx.Response:+ return httpx.Response(+ 200,+ headers={"content-type": "text/event-stream"},+ content=b': ping\n\ndata: {"event":"run.completed","output":"done"}\n\n',+ )++ async with HermesRemoteClient(+ "http://hermes.test",+ "synthetic-secret",+ transport=httpx.MockTransport(stream),+ ) as client:+ events = [event async for event in client.stream_events("run-1")]++ assert events == [+ {"event": "gateway.keepalive"},+ {"event": "run.completed", "output": "done"},+ ]+++async def test_detect_remote_backend_is_registered(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = httpx.MockTransport(+ lambda _: httpx.Response(+ 200,+ json={+ "object": "hermes.api_server.capabilities",+ "model": "hermes",+ "features": {+ "run_submission": True,+ "run_events_sse": True,+ "run_stop": True,+ "run_approval_response": True,+ "session_resources": True,+ },+ },+ ),+ )+ backend = HermesRemoteBackend(+ config=BackendConfig(base_url="http://hermes.test", api_key_env="TEST_HERMES_KEY"),+ transport=transport,+ )+ assert backend.local_cli is False+ assert backend.detectable is True+ result = await backend.detect()+ assert result.available is True+++async def test_client_preserves_multi_profile_url_prefix() -> None:+ requests: list[httpx.Request] = []++ def capabilities(request: httpx.Request) -> httpx.Response:+ requests.append(request)+ return httpx.Response(200, json={})++ async with HermesRemoteClient(+ "https://hermes.test/p/study",+ "synthetic-secret",+ transport=httpx.MockTransport(capabilities),+ ) as client:+ await client.get_json("/v1/capabilities")++ assert requests[0].url.path == "/p/study/v1/capabilities"+++ "base_url",+ [+ "file:///etc/passwd",+ "https://user:[email protected]",+ "https://hermes.test?key=secret",+ "https://hermes.test#fragment",+ "https://hermes.test:invalid",+ ],+)+def test_client_rejects_unsafe_or_invalid_base_urls(base_url: str) -> None:+ with pytest.raises(HermesRemoteProtocolError, match="invalid_base_url"):+ HermesRemoteClient(base_url, "synthetic-secret")+++async def test_invalid_remote_identifiers_never_reach_request_paths(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setenv("TEST_HERMES_KEY", "synthetic-secret")+ transport = _HermesTransport(events=[{"event": "run.completed", "output": "done"}])+ backend = _backend(transport)++ async def on_event(_: Any) -> None:+ return None++ invalid_session = await backend.consult(+ "question",+ on_event=on_event,+ session_id="bad/session\r\nheader",+ config=backend.config,+ )+ assert invalid_session.success is False+ assert invalid_session.error == "invalid_session_id"+ assert transport.requests == []++ def invalid_run(request: httpx.Request) -> httpx.Response:+ if request.method == "POST" and request.url.path == "/v1/runs":+ return httpx.Response(202, json={"run_id": "bad/run"})+ return httpx.Response(404)++ bad_run = _backend(httpx.MockTransport(invalid_run))+ invalid_result = await bad_run.consult(+ "question",+ on_event=on_event,+ config=bad_run.config,+ )+ assert invalid_result.success is False+ assert invalid_result.error == "missing_run_id"diff --git a/tests/services/test_subagent_backends.py b/tests/services/test_subagent_backends.pyindex 3c176fe61..8956f57a5 100644--- a/tests/services/test_subagent_backends.py+++ b/tests/services/test_subagent_backends.py@@ -942,6 +942,7 @@ async def test_detect_all_excludes_partner_backend() -> None:"hermes","openclaw","deepseek_harness",+ "hermes_remote",}diff --git a/web/components/agents/ConnectedAgents.tsx b/web/components/agents/ConnectedAgents.tsxindex e5eb0f063..938d863c3 100644--- a/web/components/agents/ConnectedAgents.tsx+++ b/web/components/agents/ConnectedAgents.tsx@@ -20,15 +20,17 @@ import {/*** Connected agents — live agents the chat composer can select and consult in- * real time: a supported local agent harness, or one of the user's partners.+ * real time: a supported local harness, remote gateway, or one of the user's+ * partners.* Distinct from the imported-history agents below it: those replay- * past transcripts, these drive the live agent now. CLI detection is- * machine-global (is the CLI installed here); partners come from the user's- * partner list. Consulting a partner opens a fresh session on it — every- * consult within one DeepTutor chat is archived as one partner session.+ * past transcripts, these drive the live agent now. Runtime detection is+ * machine-global; partners come from the user's partner list. Consulting a+ * partner opens a fresh session on it — every consult within one DeepTutor+ * chat is archived as one partner session.*/const PARTNER_KIND = "partner";+const REMOTE_HERMES_KIND = "hermes_remote";type Lang = { zh: string; en: string };@@ -40,6 +42,7 @@ function backendLabel(kind: string, tr: (l: Lang) => string): string {if (kind === "opencode") return "opencode";if (kind === "mimo") return "MiMo Code";if (kind === "hermes") return "Hermes Agent";+ if (kind === REMOTE_HERMES_KIND) return "Hermes Agent (remote)";if (kind === "openclaw") return "OpenClaw";if (kind === "deepseek_harness") return "DeepSeek Harness";if (kind === PARTNER_KIND) return tr({ zh: "伙伴", en: "Partner" });@@ -82,7 +85,7 @@ export default function ConnectedAgents() {() => backends.filter((b) => b.available),[backends],);- // Something is connectable when a CLI is installed here or a partner exists.+ // Something is connectable when a local/remote backend is available or a partner exists.const canConnect = available.length > 0 || partners.length > 0;const partnerName = useCallback((id: string) => partners.find((p) => p.partner_id === id)?.name || id,@@ -117,8 +120,8 @@ export default function ConnectedAgents() {icon={Plug}title={tr({ zh: "连接的智能体", en: "Connected agents" })}description={tr({- zh: "把本机的 Claude Code、Codex、Antigravity CLI、Kimi CLI、opencode、MiMo Code、Hermes Agent、OpenClaw、DeepSeek Harness 或你的伙伴接进来,在对话中选中后直接向它提问 —— 它的运行过程会实时展示。",- en: "Bring in a supported local harness — including Claude Code, Codex, Hermes Agent, OpenClaw, and DeepSeek Harness — or one of your partners. Select it in chat to consult it directly and see its run live.",+ zh: "把本机智能体、已配置的远程 Hermes 网关或你的伙伴接进来,在对话中选中后直接向它提问——运行过程会实时展示。",+ en: "Bring in a supported local agent, a configured remote Hermes gateway, or one of your partners. Select it in chat to consult it directly and see its run live.",})}action={canConnect ? (@@ -137,20 +140,20 @@ export default function ConnectedAgents() {{loading ? (<div className="flex items-center gap-2 px-1 text-[12px] text-[var(--muted-foreground)]"><Loader2 className="h-3.5 w-3.5 animate-spin" />- {tr({ zh: "检测本机智能体…", en: "Detecting local agents…" })}+ {tr({ zh: "检测可用智能体…", en: "Detecting available agents…" })}</div>) : !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: "未在本机检测到受支持的智能体 CLI(包括 Hermes Agent、OpenClaw、DeepSeek Harness),也还没有任何伙伴。安装并登录其中任一 CLI,或在「伙伴」里新建一个,即可连接。",- en: "No supported agent CLI was detected on this machine (including Hermes Agent, OpenClaw, and DeepSeek Harness), and there are no partners yet. Install and log in to one, or create a partner, to connect it.",+ zh: "未检测到可用的本机智能体或已配置的远程 Hermes 网关,也还没有任何伙伴。安装并登录受支持的 CLI、配置远程网关,或在「伙伴」里新建一个,即可连接。",+ en: "No supported local agent or configured remote Hermes gateway is available, and there are no partners yet. Set up a local CLI, configure the gateway, 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: "尚未连接任何智能体。点击「连接智能体」把本机检测到的智能体 CLI 或你的伙伴接进来。",- en: "No agents connected yet. Click “Connect agent” to bring in a detected local agent CLI, or a partner.",+ zh: "尚未连接任何智能体。点击「连接智能体」接入本机智能体、远程 Hermes 网关或你的伙伴。",+ en: "No agents connected yet. Click “Connect agent” to add a local agent, remote Hermes gateway, or partner.",})}</div>) : (@@ -253,7 +256,7 @@ function ConnectModal({onClose: () => void;onConnected: () => void;}) {- // The agent-type choices: each detected CLI, plus "Partner" when any exist.+ // The choices include every available runtime plus Partner when one exists.const options = useMemo(() => [...backends.map((b) => ({ kind: b.kind, label: b.display_name })),@@ -273,6 +276,7 @@ function ConnectModal({const [submitting, setSubmitting] = useState(false);const isPartner = kind === PARTNER_KIND;+ const isRemote = kind === REMOTE_HERMES_KIND;// While the user hasn't renamed the connection, mirror the chosen partner's// name so the connection reads as that partner by default.@@ -307,7 +311,9 @@ function ConnectModal({await connectSubagent(isPartner? { name: trimmed, agent_kind: PARTNER_KIND, partner_id: partnerId }- : { name: trimmed, agent_kind: kind, cwd: cwd.trim() },+ : isRemote+ ? { name: trimmed, agent_kind: kind }+ : { name: trimmed, agent_kind: kind, cwd: cwd.trim() },);onConnected();} catch (e) {@@ -315,7 +321,7 @@ function ConnectModal({} finally {setSubmitting(false);}- }, [name, kind, cwd, isPartner, partnerId, existingNames, onConnected, tr]);+ }, [name, kind, cwd, isPartner, isRemote, partnerId, existingNames, onConnected, tr]);return (<div@@ -408,7 +414,7 @@ function ConnectModal({/></div>- {!isPartner && (+ {!isPartner && !isRemote && (<div><label className="mb-1.5 block text-[12px] font-medium text-[var(--foreground)]">{tr({diff --git a/web/components/agents/agent-icons.tsx b/web/components/agents/agent-icons.tsxindex fcaee3a26..acad02fb8 100644--- a/web/components/agents/agent-icons.tsx+++ b/web/components/agents/agent-icons.tsx@@ -211,6 +211,7 @@ export function agentGlyph(kind: string | undefined): AgentGlyph | null {if (kind === "opencode") return OpencodeGlyph;if (kind === "mimo") return MimoGlyph;if (kind === "hermes") return HermesGlyph;+ if (kind === "hermes_remote") return HermesGlyph;if (kind === "openclaw") return OpenClawGlyph;if (kind === "deepseek_harness") return DeepSeekGlyph;if (kind === "partner") return PartnerGlyph;diff --git a/web/components/settings/SubagentSettingsEditor.tsx b/web/components/settings/SubagentSettingsEditor.tsxindex 485aa2c89..a07edeefd 100644--- a/web/components/settings/SubagentSettingsEditor.tsx+++ b/web/components/settings/SubagentSettingsEditor.tsx@@ -24,7 +24,7 @@ import {type Lang = { zh: string; en: string };-/** The CLI default sentinel — empty model/effort means "let the CLI decide". */+/** Empty model/effort means "let the selected runtime decide". */const CUSTOM = "__custom__";// Defaults mirror BackendConfig in deeptutor/services/subagent/config.py so the@@ -142,6 +142,15 @@ const KIND_FEATURES: Record<string, KindFeatures> = {thinking: false,forwardImages: true, // --image},+ hermes_remote: {+ effort: true,+ systemPrompt: true,+ permissionMode: false,+ codexSandbox: false,+ autoApprove: true,+ thinking: false,+ forwardImages: false,+ },openclaw: {effort: true, // --thinkingsystemPrompt: true,@@ -171,6 +180,7 @@ const DISPLAY_NAMES: Record<string, string> = {opencode: "opencode",mimo: "MiMo Code",hermes: "Hermes Agent",+ hermes_remote: "Hermes Agent (remote)",openclaw: "OpenClaw",deepseek_harness: "DeepSeek Harness",};@@ -198,6 +208,10 @@ const SYSTEM_PROMPT_HINT: Record<string, Lang> = {zh: "Hermes 没有系统提示 flag——该指令会前缀在每个新会话的第一条消息上。",en: "Hermes has no system-prompt flag — the instruction is prefixed to each new session's first message.",},+ hermes_remote: {+ zh: "新会话(或远端会话已失效)时,通过 Hermes 网关 API 的 instructions 字段注入。",+ en: "Sent through the Hermes gateway API's instructions field for a fresh or expired session.",+ },openclaw: {zh: "该指令会前缀在每个新 OpenClaw session key 的第一条消息上。",en: "The instruction is prefixed to the first message for each new OpenClaw session key.",@@ -330,6 +344,7 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {);const features = KIND_FEATURES[kind] ?? FALLBACK_FEATURES;+ const isRemote = kind === "hermes_remote";const knownSlugs = useMemo(() => new Set((options?.models ?? []).map((m) => m.slug)),[options],@@ -376,10 +391,17 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {<div><SettingsPageHeadertitle={displayName}- description={tr({- zh: `DeepTutor 通过 consult_subagent 调用本机 ${displayName} 时使用的模型、推理强度与运行参数。设置后即覆盖 CLI 的默认值;留空表示沿用 CLI 默认。`,- en: `Model, reasoning effort, and run parameters DeepTutor drives the local ${displayName} with when consulting it. These override the CLI defaults; leave blank to keep the CLI's own default.`,- })}+ description={+ isRemote+ ? tr({+ zh: "配置 DeepTutor 通过 HTTP 调用的远程 Hermes 网关、模型与运行参数。",+ en: "Configure the remote Hermes gateway, model, and run parameters DeepTutor uses over HTTP.",+ })+ : tr({+ zh: `DeepTutor 通过 consult_subagent 调用本机 ${displayName} 时使用的模型、推理强度与运行参数。设置后即覆盖 CLI 的默认值;留空表示沿用 CLI 默认。`,+ en: `Model, reasoning effort, and run parameters DeepTutor drives the local ${displayName} with when consulting it. These override the CLI defaults; leave blank to keep the CLI's own default.`,+ })+ }/>{loading && (@@ -401,13 +423,24 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {the user can re-pull them on demand. */}<SettingSectiontitle={tr({ zh: "连接与同步", en: "Connection & sync" })}- description={tr({- zh: "供应商会不定期增删模型与推理档位——随时点同步即可重新拉取最新列表。",- en: "Vendors add and retire models and effort levels over time — sync any time to re-pull the latest lists.",- })}+ description={+ isRemote+ ? tr({+ 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.",+ })+ }><SettingRow- title={tr({ zh: "本机状态", en: "On this machine" })}+ title={+ isRemote+ ? tr({ zh: "网关状态", en: "Gateway status" })+ : tr({ zh: "本机状态", en: "On this machine" })+ }description={options.available? options.version@@ -432,8 +465,12 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {<XCircle className="h-3.5 w-3.5" />)}{options.available- ? tr({ zh: "已安装", en: "Installed" })- : tr({ zh: "未检测到", en: "Not detected" })}+ ? isRemote+ ? tr({ zh: "可连接", en: "Reachable" })+ : tr({ zh: "已安装", en: "Installed" })+ : isRemote+ ? tr({ zh: "不可用", en: "Unavailable" })+ : tr({ zh: "未检测到", en: "Not detected" })}</span>}/>@@ -445,27 +482,115 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {zh: `上次同步:${formatTs(options.synced_at, zh)}`,en: `Last synced: ${formatTs(options.synced_at, zh)}`,})- : tr({- zh: "该 CLI 无可枚举的模型接口,下方为常用别名,可自定义任意模型名。",- en: "This CLI has no model-list API; below are the common aliases, and any model name is accepted.",- })+ : 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={- <button- type="button"- disabled={syncing}- onClick={() => void sync()}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40 disabled:opacity-60"- >- <RefreshCw- className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`}- />- {tr({ zh: "同步", en: "Sync" })}- </button>+ isRemote ? (+ <span className="text-[12px] text-[var(--muted-foreground)]">+ {tr({ zh: "网关模型由服务端提供", en: "Gateway models are server-managed" })}+ </span>+ ) : (+ <button+ type="button"+ disabled={syncing}+ onClick={() => void sync()}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] px-2.5 py-1.5 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:border-[var(--foreground)]/40 disabled:opacity-60"+ >+ <RefreshCw+ className={`h-3.5 w-3.5 ${syncing ? "animate-spin" : ""}`}+ />+ {tr({ zh: "同步", en: "Sync" })}+ </button>+ )}/></SettingSection>+ {isRemote && (+ <SettingSection+ title={tr({ zh: "远程网关", en: "Remote gateway" })}+ description={tr({+ zh: "密钥只从环境变量读取;这里仅保存变量名,不保存密钥值。",+ en: "The bearer is read only from the environment; this stores the variable name, never the secret.",+ })}+ >+ <SettingRow+ title={tr({ zh: "网关 URL", en: "Gateway URL" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.base_url ?? ""}+ placeholder={tr({+ zh: "例如:http://hermes-uni:8642",+ en: "e.g. http://hermes-uni:8642",+ })}+ onChange={(e) => setConfig((p) => ({ ...p, base_url: e.target.value }))}+ onBlur={(e) => void save({ base_url: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "密钥环境变量", en: "API key environment variable" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.api_key_env ?? "DEEPTUTOR_HERMES_REMOTE_API_KEY"}+ onChange={(e) => setConfig((p) => ({ ...p, api_key_env: e.target.value }))}+ onBlur={(e) => void save({ api_key_env: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "配置 profile", en: "Profile label" })}+ description={tr({+ zh: "仅作部署标识,不会把密钥写入设置。",+ en: "Informational deployment label; it never stores a key.",+ })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ value={config.profile ?? ""}+ onChange={(e) => setConfig((p) => ({ ...p, profile: e.target.value }))}+ onBlur={(e) => void save({ profile: e.target.value.trim() })}+ />+ }+ />+ <SettingRow+ title={tr({ zh: "空闲超时(秒)", en: "Idle timeout (seconds)" })}+ control={+ <input+ className={`${inputClass} w-[260px]`}+ disabled={busy}+ type="number"+ min={1}+ max={86400}+ value={config.idle_timeout_seconds ?? 600}+ onChange={(e) =>+ setConfig((p) => ({+ ...p,+ idle_timeout_seconds: Number.parseInt(e.target.value, 10),+ }))+ }+ onBlur={(e) =>+ void save({ idle_timeout_seconds: Number.parseInt(e.target.value, 10) })+ }+ />+ }+ />+ </SettingSection>+ )}+<SettingSectiontitle={tr({ zh: "模型", en: "Model" })}description={tr({@@ -498,7 +623,9 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {onChange={(e) => onModelSelect(e.target.value)}><option value="">- {tr({ zh: "CLI 默认", en: "CLI default" })}+ {isRemote+ ? tr({ zh: "网关默认", en: "Gateway default" })+ : tr({ zh: "CLI 默认", en: "CLI default" })}</option>{options.models.map((m) => (<option key={m.slug} value={m.slug}>@@ -542,7 +669,9 @@ export function SubagentSettingsEditor({ kind }: { kind: string }) {onChange={(e) => void save({ effort: e.target.value })}><option value="">- {tr({ zh: "CLI 默认", en: "CLI default" })}+ {isRemote+ ? tr({ zh: "网关默认", en: "Gateway default" })+ : tr({ zh: "CLI 默认", en: "CLI default" })}</option>{effortChoices.map((eff) => (<option key={eff} value={eff}>diff --git a/web/features/settings/navigation/settings-nav.ts b/web/features/settings/navigation/settings-nav.tsindex f162a2b69..46201e5f3 100644--- a/web/features/settings/navigation/settings-nav.ts+++ b/web/features/settings/navigation/settings-nav.ts@@ -364,6 +364,18 @@ const AGENT_CHILDREN: SettingsLeaf[] = [tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",adminOnly: true,},+ {+ key: "agent-hermes-remote",+ href: "/settings#agent-hermes-remote",+ label: { zh: "Hermes Agent(远程)", en: "Hermes Agent (remote)" },+ blurb: {+ zh: "通过 HTTP 网关调用远程 Hermes Agent,并按会话保持上下文。",+ en: "Call a remote Hermes Agent over HTTP with per-chat session continuity.",+ },+ icon: HermesGlyph as unknown as LucideIcon,+ tile: "bg-violet-500/10 text-violet-600 dark:text-violet-400",+ adminOnly: true,+ },{key: "agent-openclaw",href: "/settings#agent-openclaw",diff --git a/web/features/settings/sections/AgentsSettingsSection.tsx b/web/features/settings/sections/AgentsSettingsSection.tsxindex a94b4c813..d41ab2dcb 100644--- a/web/features/settings/sections/AgentsSettingsSection.tsx+++ b/web/features/settings/sections/AgentsSettingsSection.tsx@@ -18,6 +18,9 @@ const OpencodeAgentSettingsPage = () => ();const MimoAgentSettingsPage = () => <SubagentSettingsEditor kind="mimo" />;const HermesAgentSettingsPage = () => <SubagentSettingsEditor kind="hermes" />;+const HermesRemoteAgentSettingsPage = () => (+ <SubagentSettingsEditor kind="hermes_remote" />+);const OpenClawAgentSettingsPage = () => (<SubagentSettingsEditor kind="openclaw" />);@@ -33,6 +36,7 @@ const AGENT_SECTIONS = [{ key: "agent-opencode", Component: OpencodeAgentSettingsPage },{ key: "agent-mimo", Component: MimoAgentSettingsPage },{ key: "agent-hermes", Component: HermesAgentSettingsPage },+ { key: "agent-hermes-remote", Component: HermesRemoteAgentSettingsPage },{ key: "agent-openclaw", Component: OpenClawAgentSettingsPage },{key: "agent-deepseek-harness",diff --git a/web/lib/subagents-api.ts b/web/lib/subagents-api.tsindex 916e98a34..611a20f96 100644--- a/web/lib/subagents-api.ts+++ b/web/lib/subagents-api.ts@@ -158,6 +158,13 @@ export interface SubagentBackendConfig {thinking?: boolean;forward_images?: boolean;extra_args?: string[];+ /** Remote Hermes gateway URL; the API key itself is never persisted here. */+ base_url?: string;+ /** Environment variable name containing the remote gateway bearer. */+ api_key_env?: string;+ /** Informational profile name associated with the gateway deployment. */+ profile?: string;+ idle_timeout_seconds?: number;}export interface SubagentSettings {