JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(gateway): route SSH channel southbound to YuanRong via AgentOS Router
yechenzhen6a4fda346c06
diff --git a/jiuwenswarm/common/schema/message.py b/jiuwenswarm/common/schema/message.pyindex 909c34048d..03fc3e7332 100644--- a/jiuwenswarm/common/schema/message.py+++ b/jiuwenswarm/common/schema/message.py@@ -16,6 +16,7 @@ class ReqMethod(Enum):CHAT_CANCEL = "chat.interrupt"CHAT_ANSWER = "chat.user_answer"CHAT_SWARMFLOW_REPLY = "chat.swarmflow_reply"+ SSH_RELAY = "ssh.relay"HISTORY_GET = "history.get"COMMAND_BTW = "command.btw"COMMAND_ADD_DIR = "command.add_dir"diff --git a/jiuwenswarm/extensions/agentos/agentos_router/config.py b/jiuwenswarm/extensions/agentos/agentos_router/config.pyindex da71878a37..f9b444f120 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/config.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/config.py@@ -10,6 +10,10 @@ from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (normalize_agent_key_fields,)from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryConfig+from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import (+ YuanrongSshSettings,+ load_yuanrong_ssh_settings,+)@dataclass(frozen=True)@@ -23,6 +27,7 @@ class RouterConfig:agent_timeout_s: float = 300.0creating_timeout_seconds: float = 60.0agent_key_fields: tuple[str, ...] = DEFAULT_AGENT_KEY_FIELDS+ ssh: YuanrongSshSettings = YuanrongSshSettings()def agentos_router_selected(config: dict[str, Any]) -> bool:@@ -80,4 +85,5 @@ def load_router_config(config: dict[str, Any]) -> RouterConfig:agent_key_fields=normalize_agent_key_fields(agentos.get("agent_key_fields")),+ ssh=load_yuanrong_ssh_settings(agentos.get("ssh")),)diff --git a/jiuwenswarm/extensions/agentos/agentos_router/extension.py b/jiuwenswarm/extensions/agentos/agentos_router/extension.pyindex ca99b38a88..8c4071abe0 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/extension.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/extension.py@@ -11,6 +11,7 @@ from jiuwenswarm.extensions.agentos.agentos_router.config import ()from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryClientfrom jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSRouterClient+from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import YuanrongSshRelayfrom jiuwenswarm.extensions.agentos.agentos_router.third_agent import AgentOSThirdAgentfrom jiuwenswarm.extensions.sdk.agent_server_client import (AgentServerClientExtension,@@ -41,10 +42,15 @@ class AgentOSRouter(AgentServerClientExtension, ThirdAgentExtension):creating_timeout_seconds=config.creating_timeout_seconds,key_fields=config.agent_key_fields,)+ self._ssh_relay = YuanrongSshRelay(+ config.ssh,+ frontend_endpoint=config.frontend_endpoint,+ )self._router_client = AgentOSRouterClient(self._yuanrong_client,self._registry_client,self._agent_manager,+ ssh_relay=self._ssh_relay,)self._third_agent = AgentOSThirdAgent(self._router_client)self._closed = Falsediff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.pyindex f53ccbb408..ebac45007f 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py@@ -9,14 +9,17 @@ from typing import Anyfrom jiuwenswarm.common.e2a.models import E2AEnvelopefrom jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk+from jiuwenswarm.common.schema.message import ReqMethodfrom jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (AgentCreatingTimeout,+ AgentDeleted,AgentManager,AgentRuntime,SUPPORTED_AGENT_TYPES,)from jiuwenswarm.extensions.agentos.agentos_router.models import AgentInfo, AgentStatusfrom jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryClient+from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import YuanrongSshRelayfrom jiuwenswarm.extensions.yuanrong_frontend_client import (YuanrongFrontendAgentClient,)@@ -38,13 +41,22 @@ class AgentOSRouterClient(AgentServerClient):yuanrong: YuanrongFrontendAgentClient,registry: RegistryClient,agent_manager: AgentManager,+ ssh_relay: YuanrongSshRelay | None = None,) -> None:self._yuanrong = yuanrongself._registry = registryself._agent_manager = agent_manager+ self._ssh_relay = ssh_relayself._server_ready = Falseself._background_tasks: set[asyncio.Task[Any]] = set()self._closed = False+ # 用户当前 agent_type(3rdagent.switch 成功后更新);SSH 接入跟随此值。+ self._current_agent_types: dict[str, str] = {}++ def get_current_agent_type(self, user_id: str) -> str:+ """Return the user's current agent_type (default ``jiuwenswarm``)."""+ uid = str(user_id or "").strip()+ return self._current_agent_types.get(uid) or "jiuwenswarm"@propertydef server_ready(self) -> bool:@@ -85,6 +97,8 @@ class AgentOSRouterClient(AgentServerClient):async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:# 3rdagent.list / 3rdagent.switch are handled by Gateway ThirdAgent# (TUI local_handler), not via E2A send_request.+ if self._is_ssh_relay_request(envelope):+ return await self._handle_ssh_relay(envelope)try:runtime = await self._resolve_agent(envelope)except (ValueError, AgentCreatingTimeout) as exc:@@ -134,7 +148,10 @@ class AgentOSRouterClient(AgentServerClient):"metadata": dict(image.metadata or {}),})- current = str(current_agent_type or "").strip() or "jiuwenswarm"+ current = (+ str(current_agent_type or "").strip()+ or self.get_current_agent_type(uid)+ )return {"ok": True,"payload": {@@ -182,6 +199,8 @@ class AgentOSRouterClient(AgentServerClient):}info = runtime.infostatus = info.status.value if hasattr(info.status, "value") else str(info.status)+ # 记录用户当前 agent_type,后续 SSH 接入默认跟随+ self._current_agent_types[uid] = normalizedreturn {"ok": True,"payload": {@@ -195,6 +214,107 @@ class AgentOSRouterClient(AgentServerClient):async def shutdown(self) -> None:await self.disconnect()+ # ---------- SSH relay (northbound SshChannel -> YuanRong instance) ----------++ @staticmethod+ def _is_ssh_relay_request(envelope: E2AEnvelope) -> bool:+ return str(envelope.method or "") == ReqMethod.SSH_RELAY.value++ async def _handle_ssh_relay(self, envelope: E2AEnvelope) -> AgentResponse:+ """Start the southbound SSH relay for an ``ssh.relay`` request.++ Agent resolution (YuanRong instance creation) and the PTY relay run+ in a background task so the gateway forward loop is not blocked for+ the whole SSH session; the northbound channel waits on the relay+ session ``done`` event instead of this response.+ """+ session_id = str(envelope.session_id or "")+ params = envelope.params if isinstance(envelope.params, dict) else {}+ # Live SshRelaySession handed over in-process by the northbound+ # SshChannel; pop it so it never leaks into serialization/logging.+ relay_session = params.pop("relay_session", None)+ if relay_session is None:+ return self._routing_error_response(+ envelope, f"ssh relay session not found in params: {session_id}"+ )+ if self._ssh_relay is None:+ msg = "ssh relay is not configured for AgentOS router"+ relay_session.exit_code = 1+ relay_session.done.set()+ return self._routing_error_response(envelope, msg)++ task = asyncio.create_task(+ self._run_ssh_relay(envelope, relay_session),+ name=f"agentos-ssh-relay-{session_id[:24]}",+ )+ self._background_tasks.add(task)+ task.add_done_callback(self._background_tasks.discard)+ return AgentResponse(+ request_id=str(envelope.request_id or ""),+ channel_id=str(envelope.channel or ""),+ ok=True,+ payload={"method": ReqMethod.SSH_RELAY.value, "status": "relay_started"},+ )++ async def _run_ssh_relay(self, envelope: E2AEnvelope, relay_session: Any) -> None:+ ssh_relay = self._ssh_relay+ if ssh_relay is None:+ # _handle_ssh_relay already guards this; keep a safe fallback.+ relay_session.exit_code = 1+ relay_session.done.set()+ return+ self._apply_current_agent_type_for_ssh(envelope)+ try:+ runtime = await self._resolve_agent(envelope)+ except (ValueError, AgentCreatingTimeout, AgentDeleted) as exc:+ ssh_relay.fail_session(+ relay_session, f"agent resolve failed: {exc}"+ )+ return+ except Exception as exc: # noqa: BLE001 - creation errors must release the client+ logger.exception(+ "[AgentOSRouter] ssh relay agent creation failed: session=%s",+ relay_session.session_id,+ )+ ssh_relay.fail_session(+ relay_session, f"agent creation failed: {exc}"+ )+ return++ instance_id = str(runtime.info.sandbox_id or "").strip()+ if not instance_id:+ ssh_relay.fail_session(+ relay_session,+ f"agent has no yuanrong instance_id: user={runtime.info.user_id}",+ )+ return++ runtime.attach_to_envelope(envelope)+ logger.info(+ "[AgentOSRouter] ssh relay start: session=%s user=%s instance=%s",+ relay_session.session_id,+ runtime.info.user_id,+ instance_id,+ )+ await ssh_relay.run(relay_session, instance_id)++ def _apply_current_agent_type_for_ssh(self, envelope: E2AEnvelope) -> None:+ """SSH 接入跟随用户当前 agent_type(由 3rdagent.switch 记录)。"""+ params = envelope.params if isinstance(envelope.params, dict) else {}+ if str(params.get("agent_type") or "").strip():+ return+ user_id = str(envelope.user_id or "").strip()+ current = self.get_current_agent_type(user_id)+ params = dict(params)+ params["agent_type"] = current+ envelope.params = params+ logger.info(+ "[AgentOSRouter] ssh relay follows user current agent_type: "+ "user=%s agent_type=%s",+ user_id,+ current,+ )+async def _drain_background_tasks(self) -> None:if self._background_tasks:await asyncio.gather(*self._background_tasks, return_exceptions=True)diff --git a/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.pynew file mode 100644index 0000000000..741a656b6f--- /dev/null+++ b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py@@ -0,0 +1,241 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Southbound SSH relay into YuanRong agent instances.++Bridges a northbound ``SshRelaySession`` (accepted by the gateway+``SshChannel`` as an interactive shell) to the YuanRong frontend SSH+endpoint::++ ssh -p 2222 'yr:instance:<instance_id>:user=agentos'@<frontend-host>++``<instance_id>`` is the instance id returned by the YuanRong agent+create API (``POST /api/agent``), resolved by the AgentOS Router.+"""++from __future__ import annotations++import asyncio+import logging+import urllib.parse+from dataclasses import dataclass+from typing import Any++logger = logging.getLogger(__name__)++DEFAULT_SSH_PORT = 2222+DEFAULT_SSH_USER_TEMPLATE = "yr:instance:{instance}:user=agentos"+_RELAY_BUFFER_SIZE = 32768+++def _raise_missing_asyncssh(exc: ImportError) -> None:+ raise RuntimeError(+ "SSH relay requires optional dependency `asyncssh>=2.14.0,<2.24`. "+ "Install with `pip install -e \".[ssh]\"` or "+ '`uv sync --extra ssh` / `pip install "jiuwenswarm[ssh]"`.'+ ) from exc+++def _import_asyncssh() -> Any:+ try:+ import asyncssh+ except ImportError as exc:+ _raise_missing_asyncssh(exc)+ return asyncssh+++@dataclass(frozen=True)+class YuanrongSshSettings:+ """Southbound SSH access settings for the YuanRong frontend."""++ port: int = DEFAULT_SSH_PORT+ user_template: str = DEFAULT_SSH_USER_TEMPLATE+ connect_timeout_s: float = 30.0+++def load_yuanrong_ssh_settings(raw: Any) -> YuanrongSshSettings:+ """Build settings from the ``gateway.agentos.ssh`` config block."""+ if not isinstance(raw, dict):+ raw = {}+ return YuanrongSshSettings(+ port=int(raw.get("port") or DEFAULT_SSH_PORT),+ user_template=str(+ raw.get("user_template") or DEFAULT_SSH_USER_TEMPLATE+ ).strip(),+ connect_timeout_s=float(raw.get("connect_timeout_s") or 30.0),+ )+++class YuanrongSshRelay:+ """Relay PTY/exec traffic between a northbound SSH session and YuanRong."""++ def __init__(+ self,+ settings: YuanrongSshSettings,+ *,+ frontend_endpoint: str = "",+ ) -> None:+ self._settings = settings+ self._frontend_endpoint = (frontend_endpoint or "").strip()++ @property+ def backend_host(self) -> str:+ parsed = urllib.parse.urlparse(self._frontend_endpoint)+ return parsed.hostname or ""++ @property+ def backend_port(self) -> int:+ return self._settings.port++ def backend_username(self, instance_id: str) -> str:+ instance = str(instance_id or "").strip()+ if not instance:+ raise ValueError("instance_id is required for YuanRong SSH relay")+ return self._settings.user_template.format(instance=instance)++ async def run(self, session: Any, instance_id: str) -> int:+ """Relay *session* to the YuanRong instance; returns the exit code.++ Always resolves ``session.done`` and ``session.exit_code`` so the+ northbound channel waiting in ``_wait_relay_done`` is released.+ """+ exit_code = 1+ try:+ exit_code = await self._relay(session, instance_id)+ except Exception as exc: # noqa: BLE001 - report any relay failure to the client+ logger.exception(+ "[YuanrongSshRelay] relay failed: session=%s instance=%s",+ session.session_id,+ instance_id,+ )+ self._write_client_error(session, f"yuanrong ssh relay failed: {exc}")+ finally:+ session.exit_code = exit_code+ session.done.set()+ return exit_code++ def fail_session(self, session: Any, reason: str) -> None:+ """Mark *session* failed and release the northbound waiter."""+ self._write_client_error(session, reason)+ session.exit_code = 1+ session.done.set()++ @staticmethod+ def _write_client_error(session: Any, reason: str) -> None:+ try:+ session.process.stdout.write(f"[ssh-relay] {reason}\r\n".encode())+ except Exception: # noqa: BLE001 - client may already be gone+ logger.debug("[YuanrongSshRelay] client write failed", exc_info=True)++ async def _relay(self, session: Any, instance_id: str) -> int:+ asyncssh = _import_asyncssh()++ host = self.backend_host+ if not host:+ raise ValueError(+ "yuanrong ssh host is empty "+ "(set gateway.agent_client.frontend_endpoint with a hostname)"+ )+ username = self.backend_username(instance_id)++ logger.info(+ "[YuanrongSshRelay] connecting: %s@%s:%s session=%s",+ username,+ host,+ self._settings.port,+ session.session_id,+ )+ conn = await asyncio.wait_for(+ asyncssh.connect(+ host,+ port=self._settings.port,+ username=username,+ known_hosts=None,+ ),+ timeout=self._settings.connect_timeout_s,+ )+ try:+ return await self._relay_over_connection(session, conn)+ finally:+ conn.close()+ try:+ await conn.wait_closed()+ except Exception: # noqa: BLE001+ logger.debug("[YuanrongSshRelay] close failed", exc_info=True)++ async def _relay_over_connection(self, session: Any, conn: Any) -> int:+ process = session.process++ # Interactive shell only (northbound rejects exec requests).+ kwargs: dict[str, Any] = {"encoding": None}+ term_type = process.get_terminal_type() or "xterm"+ kwargs["term_type"] = term_type+ term_size = process.get_terminal_size()+ if term_size and term_size[0]:+ kwargs["term_size"] = term_size+ backend = await conn.create_process(**kwargs)+ try:+ await asyncio.gather(+ self._pump_client_to_backend(session, backend),+ self._pump_backend_to_client(backend.stdout, process.stdout),+ self._pump_backend_to_client(backend.stderr, process.stderr),+ )+ await backend.wait_closed()+ finally:+ backend.close()+ exit_status = backend.exit_status+ return int(exit_status) if exit_status is not None else 0++ @staticmethod+ async def _pump_client_to_backend(session: Any, backend: Any) -> None:+ asyncssh = _import_asyncssh()++ process = session.process+ while True:+ try:+ data = await process.stdin.read(_RELAY_BUFFER_SIZE)+ except asyncssh.TerminalSizeChanged as exc:+ try:+ backend.change_terminal_size(+ exc.width, exc.height, exc.pixwidth, exc.pixheight+ )+ except Exception: # noqa: BLE001 - exec channels have no PTY+ logger.debug(+ "[YuanrongSshRelay] change_terminal_size failed",+ exc_info=True,+ )+ continue+ except asyncssh.BreakReceived:+ backend.stdin.write(b"\x03")+ continue+ except (asyncssh.ConnectionLost, ConnectionError):+ break+ if not data:+ try:+ backend.stdin.write_eof()+ except Exception: # noqa: BLE001 - backend may already be closed+ logger.debug(+ "[YuanrongSshRelay] write_eof failed", exc_info=True+ )+ break+ backend.stdin.write(data)+ try:+ await backend.stdin.drain()+ except (asyncssh.ConnectionLost, ConnectionError):+ break++ @staticmethod+ async def _pump_backend_to_client(reader: Any, writer: Any) -> None:+ asyncssh = _import_asyncssh()++ while True:+ try:+ data = await reader.read(_RELAY_BUFFER_SIZE)+ except (asyncssh.ConnectionLost, ConnectionError):+ break+ if not data:+ break+ try:+ writer.write(data)+ await writer.drain()+ except (asyncssh.ConnectionLost, ConnectionError):+ breakdiff --git a/jiuwenswarm/gateway/app_gateway.py b/jiuwenswarm/gateway/app_gateway.pyindex a545a3e5cb..c6261189e6 100644--- a/jiuwenswarm/gateway/app_gateway.py+++ b/jiuwenswarm/gateway/app_gateway.py@@ -1402,6 +1402,7 @@ async def _run(from jiuwenswarm.gateway.channel_manager.im_platforms.discord.discord_connect import DiscordChannel, \DiscordChannelConfigfrom jiuwenswarm.gateway.channel_manager.im_platforms.wecom.wecom_connect import WecomChannel, WecomConfig+ from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import SshChannel, SshChannelConfigfrom jiuwenswarm.common.config import get_configfrom jiuwenswarm.common.cleanup import start_background_cleanupfrom jiuwenswarm.gateway.routing.agent_client import WebSocketAgentServerClient@@ -1447,7 +1448,7 @@ async def _run(max_retries = int(os.getenv("AGENT_CONNECT_RETRY", "20"))retry_interval = float(os.getenv("AGENT_CONNECT_RETRY_INTERVAL", "3"))- # 从扩展注册表获取 AgentServerClient+ # 从扩展注册表获取 AgentServerClient(WebSocket 或 Yuanrong 等扩展实现)agent_server_ext = extension_registry.get_agent_server_client_extension()if agent_server_ext is not None:logger.info("[App] using extension AgentServerClient: %s", agent_server_ext.metadata.name)@@ -1830,6 +1831,8 @@ async def _run(wecom_task = Nonewechat_channel = Nonewechat_task = None+ ssh_channel = None+ ssh_task = None_last_channels_conf: dict = {}@@ -1902,6 +1905,7 @@ async def _run(nonlocal whatsapp_channel, whatsapp_tasknonlocal wecom_channel, wecom_tasknonlocal wechat_channel, wechat_task+ nonlocal ssh_channel, ssh_tasknonlocal _last_channels_confnonlocal feishu_enterprise_channels, feishu_enterprise_tasks@@ -1927,6 +1931,7 @@ async def _run("discord","wecom","wechat",+ "ssh",]:if _should_restart_channel(channel_name, _last_channels_conf, conf) or channel_name in restart_pending:if channel_name in restart_pending and not _should_restart_channel(@@ -2338,6 +2343,45 @@ async def _run(else:logger.info("[App] channels.wechat missing or invalid, WechatChannel disabled")+ if "ssh" in changed_channels:+ ssh_conf = conf.get("ssh") if isinstance(conf, dict) else None+ await _stop_channel(ssh_channel, ssh_task, "ssh")+ ssh_channel, ssh_task = None, None++ if isinstance(ssh_conf, dict):+ # 南向经 agent client(如 agentos_router -> yuanrong)动态解析。+ enabled, reason = _is_channel_enabled(ssh_conf, ["listen_port"])+ if not enabled:+ logger.info("[App] channels.ssh.%s, SshChannel disabled", reason)+ else:+ ssh_config = SshChannelConfig.from_dict({**ssh_conf, "enabled": True})+ ssh_channel = SshChannel(ssh_config, _DummyBus())+ channel_manager.register_channel(ssh_channel)+ ssh_task = asyncio.create_task(ssh_channel.start(), name="ssh")++ def _on_ssh_task_done(task: asyncio.Task) -> None:+ try:+ task.result()+ except asyncio.CancelledError:+ return+ except Exception as exc: # noqa: BLE001+ logger.error(+ "[App] SSH channel failed to start: %s. "+ "If SSH is enabled, install optional dependency with "+ "`uv sync --extra ssh` or `pip install \"jiuwenswarm[ssh]\"`.",+ exc,+ )++ ssh_task.add_done_callback(_on_ssh_task_done)+ logger.info(+ "[App] SshChannel registered from config.yaml.channels.ssh "+ "(listen %s:%s -> MessageHandler; southbound via agent client)",+ ssh_config.listen_host,+ ssh_config.listen_port,+ )+ else:+ logger.info("[App] channels.ssh missing or invalid, SshChannel disabled")+channel_manager.set_config_callback(_apply_channel_config)await channel_manager.set_config(initial_channels_conf)@@ -2488,6 +2532,13 @@ async def _run(except asyncio.CancelledError:passawait wechat_channel.stop()+ if ssh_channel is not None and ssh_task is not None:+ ssh_task.cancel()+ try:+ await ssh_task+ except asyncio.CancelledError:+ pass+ await ssh_channel.stop()await cron_scheduler.stop()await channel_manager.stop_dispatch()diff --git a/jiuwenswarm/gateway/channel_manager/base.py b/jiuwenswarm/gateway/channel_manager/base.pyindex ec032416c0..b93a20d89f 100644--- a/jiuwenswarm/gateway/channel_manager/base.py+++ b/jiuwenswarm/gateway/channel_manager/base.py@@ -30,6 +30,7 @@ class ChannelType(str, Enum):WHATSAPP = "whatsapp"WECOM = "wecom"WECHAT = "wechat"+ SSH = "ssh"CLI = "tui"diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.pynew file mode 100644index 0000000000..a3ff8c6ce5--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/__init__.py@@ -0,0 +1,23 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""SSH server channel: accept SSH clients and deliver sessions to MessageHandler."""++from __future__ import annotations++from typing import TYPE_CHECKING++__all__ = ["SshChannel", "SshChannelConfig"]++if TYPE_CHECKING:+ from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import (+ SshChannel,+ SshChannelConfig,+ )+++def __getattr__(name: str):+ if name in __all__:+ from jiuwenswarm.gateway.channel_manager.protocol.ssh import ssh_connect++ return getattr(ssh_connect, name)+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/config.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/config.pynew file mode 100644index 0000000000..b0bd483d26--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/config.py@@ -0,0 +1,33 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""Configuration for the SSH server channel."""++from __future__ import annotations++from dataclasses import dataclass+from pathlib import Path+from typing import Any++from jiuwenswarm.common.utils import get_config_dir+++@dataclass+class ProxyConfig:+ listen_host: str = "0.0.0.0"+ listen_port: int = 2222+ host_key_path: str = ""++ def __post_init__(self) -> None:+ if self.host_key_path:+ self.host_key_path = str(Path(self.host_key_path).expanduser())+ else:+ self.host_key_path = str(get_config_dir() / "ssh_host_key")+++def proxy_config_from_dict(raw: dict[str, Any]) -> ProxyConfig:+ """Build proxy runtime config from channels.ssh YAML block."""+ return ProxyConfig(+ listen_host=str(raw.get("listen_host", "0.0.0.0")),+ listen_port=int(raw.get("listen_port", 2222)),+ host_key_path=str(raw.get("host_key_path") or ""),+ )diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.pynew file mode 100644index 0000000000..01fe66035e--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py@@ -0,0 +1,193 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""SSH proxy server: accept clients and hand off to MessageHandler."""++from __future__ import annotations++import logging+import uuid+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Awaitable, Callable++from jiuwenswarm.gateway.channel_manager.protocol.ssh.config import ProxyConfig++logger = logging.getLogger(__name__)++try:+ import asyncssh++ ASYNCSSH_AVAILABLE = True+except ImportError:+ ASYNCSSH_AVAILABLE = False+ asyncssh = None # type: ignore[assignment]+++def _raise_missing_asyncssh(exc: ImportError) -> None:+ raise RuntimeError(+ "SSH channel is enabled but optional dependency `asyncssh>=2.14.0,<2.24` "+ "is not installed. Install with `pip install -e \".[ssh]\"` or "+ '`uv sync --extra ssh` / `pip install "jiuwenswarm[ssh]"`.'+ ) from exc+++@dataclass+class SSHAgentHooks:+ register_session: Callable[..., Awaitable[None]]+ unregister_session: Callable[[str], Awaitable[None]]+ submit_relay: Callable[[str, dict[str, Any]], Awaitable[None]]+ wait_relay_done: Callable[[str], Awaitable[int]]+++class ProxySSHServer(asyncssh.SSHServer if ASYNCSSH_AVAILABLE else object): # type: ignore[misc]+ def __init__(self, config: ProxyConfig) -> None:+ self.config = config+ self.client_username: str | None = None++ def connection_made(self, conn: Any) -> None:+ conn.set_extra_info(proxy_auth=self)++ def begin_auth(self, username: str) -> bool:+ self.client_username = username+ return True++ def password_auth_supported(self) -> bool:+ return True++ def public_key_auth_supported(self) -> bool:+ return True++ def validate_public_key(self, username: str, key: Any) -> bool:+ del key+ self.client_username = username+ return True++ def validate_password(self, username: str, password: str) -> bool:+ del password+ self.client_username = username+ return True+++class SSHProxy:+ def __init__(self, config: ProxyConfig, agent_hooks: SSHAgentHooks | None = None) -> None:+ self.config = config+ self.agent_hooks = agent_hooks+ self._server: Any = None++ async def start(self) -> None:+ if not ASYNCSSH_AVAILABLE:+ try:+ import asyncssh as _asyncssh # noqa: F401+ except ImportError as exc:+ _raise_missing_asyncssh(exc)++ host_key = await self._ensure_host_key(self.config.host_key_path)++ self._server = await asyncssh.create_server(+ lambda: ProxySSHServer(self.config),+ self.config.listen_host,+ self.config.listen_port,+ server_host_keys=[host_key],+ process_factory=self._handle_client,+ encoding=None,+ )+ logger.info(+ "[SSHChannel] listening on %s:%s -> MessageHandler "+ "(southbound via agent client)",+ self.config.listen_host,+ self.config.listen_port,+ )++ async def stop(self) -> None:+ if self._server is not None:+ self._server.close()+ await self._server.wait_closed()+ self._server = None+ logger.info("[SSHChannel] SSH proxy stopped")++ async def wait_closed(self) -> None:+ if self._server is not None:+ await self._server.wait_closed()++ async def _ensure_host_key(self, key_path: str) -> Any:+ path = Path(key_path)+ path.parent.mkdir(parents=True, exist_ok=True)+ if path.exists():+ return asyncssh.read_private_key(str(path))++ logger.info("[SSHChannel] generating new host key at %s", path)+ key = asyncssh.generate_private_key("ssh-rsa", key_size=2048)+ key.write_private_key(str(path))+ key.write_public_key(f"{path}.pub")+ return key++ @staticmethod+ def _client_addr(process: Any) -> str:+ peer = process.get_extra_info("peername")+ if peer:+ return f"{peer[0]}:{peer[1]}"+ return "unknown"++ async def _handle_client(self, process: Any) -> None:+ await self._handle_ssh_client(process)++ async def _handle_ssh_client(self, process: Any) -> None:+ if self.agent_hooks is None:+ process.stdout.write(b"SSH channel is not configured\r\n")+ process.exit(1)+ return++ conn = process.channel.get_connection()+ server = conn.get_extra_info("proxy_auth")+ if not isinstance(server, ProxySSHServer):+ logger.error("[SSHChannel] missing proxy auth context")+ process.exit(1)+ return++ client_addr = self._client_addr(process)+ username = process.get_extra_info("username") or server.client_username or "unknown"++ subsystem = process.subsystem+ if subsystem:+ logger.warning("[SSHChannel] subsystem request denied: %s", subsystem)+ process.exit(1)+ return++ # Interactive shell only; reject remote-command (exec) requests.+ command = (process.command or "").strip() or None+ if command:+ logger.warning(+ "[SSHChannel] exec request denied (shell only): user=%s cmd=%s",+ username,+ command,+ )+ process.stdout.write(b"SSH channel supports interactive shell only\r\n")+ process.exit(1)+ return++ session_id = f"ssh_{username}_{uuid.uuid4().hex[:8]}"+ metadata = {+ "username": username,+ "client_addr": client_addr,+ "ssh_session_id": session_id,+ }++ try:+ await self.agent_hooks.register_session(+ session_id=session_id,+ process=process,+ username=username,+ client_addr=client_addr,+ )+ await self.agent_hooks.submit_relay(session_id, metadata)+ exit_code = await self.agent_hooks.wait_relay_done(session_id)+ process.exit(exit_code)+ except asyncssh.Error as exc:+ logger.error("[SSHChannel] session error for %s: %s", username, exc)+ process.stdout.write(f"Proxy error: {exc}\n".encode())+ process.exit(1)+ except Exception:+ logger.exception("[SSHChannel] SSH session failed for %s", username)+ process.exit(1)+ finally:+ await self.agent_hooks.unregister_session(session_id)diff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.pynew file mode 100644index 0000000000..9d67266428--- /dev/null+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py@@ -0,0 +1,221 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++"""SshChannel - northbound SSH server channel into MessageHandler.++SSH client -> SshChannel -> MessageHandler (``ssh.relay``) ->+AgentOS Router / YuanRong southbound PTY relay.+"""++from __future__ import annotations++import asyncio+import logging+import time+import uuid+from dataclasses import dataclass, field+from typing import Any, Callable++from jiuwenswarm.common.schema.message import Message, ReqMethod+from jiuwenswarm.gateway.channel_manager.base import BaseChannel, RobotMessageRouter+from jiuwenswarm.gateway.channel_manager.protocol.ssh.config import proxy_config_from_dict+from jiuwenswarm.gateway.channel_manager.protocol.ssh.server import SSHAgentHooks, SSHProxy++logger = logging.getLogger(__name__)+++@dataclass+class SshRelaySession:+ """Shared northbound/southbound handle for one SSH interactive-shell relay."""++ session_id: str+ process: Any+ done: asyncio.Event = field(default_factory=asyncio.Event)+ exit_code: int = 0+++@dataclass+class SshChannelConfig:+ """SSH server channel configuration."""++ enabled: bool = False+ listen_host: str = "0.0.0.0"+ listen_port: int = 2222+ host_key_path: str = ""+ relay_timeout_sec: float = 3600.0++ def to_proxy_config(self):+ raw = {+ "listen_host": self.listen_host,+ "listen_port": self.listen_port,+ "host_key_path": self.host_key_path,+ }+ return proxy_config_from_dict(raw)++ @classmethod+ def from_dict(cls, conf: dict[str, Any]) -> "SshChannelConfig":+ return cls(+ enabled=bool(conf.get("enabled", False)),+ listen_host=str(conf.get("listen_host", "0.0.0.0")),+ listen_port=int(conf.get("listen_port", 2222)),+ host_key_path=str(conf.get("host_key_path") or ""),+ relay_timeout_sec=float(conf.get("relay_timeout_sec", 3600.0)),+ )+++@dataclass+class _SshSession:+ session_id: str+ process: Any+ username: str+ client_addr: str+ relay: SshRelaySession | None = None+++class SshChannel(BaseChannel):+ """SSH server channel that delivers ``ssh.relay`` requests to MessageHandler."""++ name = "ssh"++ def __init__(self, config: SshChannelConfig, router: RobotMessageRouter):+ super().__init__(config, router)+ self.config: SshChannelConfig = config+ self._proxy: SSHProxy | None = None+ self._running = False+ self._on_message_cb: Callable[[Message], Any] | None = None+ self._sessions: dict[str, _SshSession] = {}++ @property+ def channel_id(self) -> str:+ return self.name++ @property+ def clients(self) -> set[Any]:+ return set(self._sessions.keys())++ def on_message(self, callback: Callable[[Message], None]) -> None:+ self._on_message_cb = callback++ async def start(self) -> None:+ if self._running:+ return+ if not self.config.enabled:+ logger.info("[SSHChannel] disabled by config")+ return++ hooks = self._build_agent_hooks()+ self._proxy = SSHProxy(self.config.to_proxy_config(), agent_hooks=hooks)+ await self._proxy.start()+ self._running = True+ logger.info(+ "[SSHChannel] started (listen %s:%s -> MessageHandler; "+ "southbound relay via agent client)",+ self.config.listen_host,+ self.config.listen_port,+ )+ await self._proxy.wait_closed()++ async def stop(self) -> None:+ self._running = False+ self._sessions.clear()+ if self._proxy is not None:+ await self._proxy.stop()+ self._proxy = None++ def _build_agent_hooks(self) -> SSHAgentHooks:+ return SSHAgentHooks(+ register_session=self._register_session,+ unregister_session=self._unregister_session,+ submit_relay=self._submit_relay,+ wait_relay_done=self._wait_relay_done,+ )++ async def _register_session(+ self,+ *,+ session_id: str,+ process: Any,+ username: str,+ client_addr: str,+ ) -> None:+ self._sessions[session_id] = _SshSession(+ session_id=session_id,+ process=process,+ username=username,+ client_addr=client_addr,+ )++ async def _unregister_session(self, session_id: str) -> None:+ self._sessions.pop(session_id, None)++ async def _wait_relay_done(self, session_id: str) -> int:+ session = self._sessions.get(session_id)+ relay = session.relay if session is not None else None+ if relay is None:+ return 1+ try:+ await asyncio.wait_for(relay.done.wait(), timeout=self.config.relay_timeout_sec)+ except asyncio.TimeoutError:+ logger.error(+ "[SSHChannel] relay timeout for session %s "+ "(no southbound handler completed the relay within %.0fs)",+ session_id,+ self.config.relay_timeout_sec,+ )+ return 124+ return relay.exit_code++ async def _submit_relay(+ self,+ session_id: str,+ metadata: dict[str, Any],+ ) -> None:+ session = self._sessions.get(session_id)+ if session is None:+ logger.error("[SSHChannel] unknown relay session: %s", session_id)+ return++ relay = SshRelaySession(+ session_id=session_id,+ process=session.process,+ )+ session.relay = relay++ if self._on_message_cb is None:+ session.process.stdout.write(b"[error] MessageHandler not available\r\n")+ relay.exit_code = 1+ relay.done.set()+ return++ username = str(metadata.get("username") or "").strip() or "unknown"+ # ``relay_session`` (with live ``process``) is handed to the+ # southbound AgentOS router in-process; it is never serialized.+ params: dict[str, Any] = {+ "relay_session": relay,+ }+ msg = Message(+ id=f"ssh_{uuid.uuid4().hex[:12]}",+ type="req",+ channel_id=self.channel_id,+ session_id=session_id,+ user_id=username,+ params=params,+ timestamp=time.time(),+ ok=True,+ req_method=ReqMethod.SSH_RELAY,+ is_stream=False,+ metadata=metadata,+ )+ logger.info(+ "[SSHChannel] deliver to MessageHandler: session=%s method=%s",+ session_id,+ ReqMethod.SSH_RELAY.value,+ )+ result = self._on_message_cb(msg)+ if asyncio.iscoroutine(result):+ await result++ async def send(self, msg: Message) -> None:+ logger.debug(+ "[SSHChannel] outbound message ignored (PTY relay channel): %s",+ getattr(msg, "id", ""),+ )diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 024fd6a3ff..b22f6cf497 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -590,6 +590,13 @@ gateway:request_timeout_s: 10# 本机 nodeIP,供 POST /api/nodes/{node}/heartbeatnode:+ # SSH 南向接入 YuanRong 实例(配合 channels.ssh 北向使用):+ # ssh -p <port> 'yr:instance:<instance_id>:user=agentos'@<frontend-host>+ # 主机取自 agent_client.frontend_endpoint;<instance_id> 为 create agent 返回的实例 id。+ ssh:+ port: 2222+ user_template: "yr:instance:{instance}:user=agentos"+ connect_timeout_s: 30heartbeat:# 心跳间隔(秒),默认 3600@@ -763,6 +770,18 @@ channels:my_user_id: ""bot_name: ""enable_memory: false+ ssh:+ # SSH channel -> MessageHandler(北向);南向经 gateway.agent_client+ # (type=agentos_router 时由 AgentOS Router 创建 YuanRong 实例并+ # 以 yr:instance:<instance_id>:user=agentos 中继到 frontend)。+ # 启用前请安装可选依赖: pip install "jiuwenswarm[ssh]" 或 uv sync --extra ssh+ # 客户端: ssh -p <listen_port> user@<gateway-host>+ # 南向连接参数见 gateway.agentos.ssh;agent_type 跟随用户当前值(3rdagent.switch)。+ enabled: false+ listen_host: "0.0.0.0"+ listen_port: 2222+ host_key_path: ~/.jiuwenswarm/config/ssh_host_key+ relay_timeout_sec: 3600# ========== 细粒度权限管控(tiered_policy)==========#diff --git a/pyproject.toml b/pyproject.tomlindex 68cc47f82d..aca1b5f8ce 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -89,6 +89,7 @@ harmony = ["json-repair>=0.30.0",]a2a = ["a2a-sdk[http-server]==1.0.0"]+ssh = ["asyncssh>=2.14.0,<2.24"]desktop = ["pywebview>=5.4"]dev = ["pyinstaller>=6.0.0", "pywebview>=5.4"]tui = ["jiuwenswarm-tui==0.2.3"]@@ -97,6 +98,7 @@ shell-ast = []# Same packages as [dependency-groups] test (pip install -e ".[test]")test = ["a2a-sdk[http-server]==1.0.0",+ "asyncssh>=2.14.0,<2.24","pytest>=8.3.5","pytest-asyncio>=1.0.0","pytest-html>=4.1.1",@@ -173,6 +175,7 @@ openjiuwen = { git = "https://gitcode.com/openJiuwen/agent-core.git", branch = "# Testing (keep in sync with optional-dependencies.test)test = ["a2a-sdk[http-server]==1.0.0",+ "asyncssh>=2.14.0,<2.24","pytest>=8.3.5","pytest-asyncio>=1.0.0","pytest-html>=4.1.1",diff --git a/tests/unit_tests/channel/test_ssh_channel.py b/tests/unit_tests/channel/test_ssh_channel.pynew file mode 100644index 0000000000..a895bc3f82--- /dev/null+++ b/tests/unit_tests/channel/test_ssh_channel.py@@ -0,0 +1,26 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.++from jiuwenswarm.gateway.channel_manager.protocol.ssh.config import proxy_config_from_dict+from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import SshChannelConfig+++def test_ssh_channel_config_from_dict():+ conf = {+ "enabled": True,+ "listen_host": "127.0.0.1",+ "listen_port": 3333,+ "relay_timeout_sec": 120,+ }+ cfg = SshChannelConfig.from_dict(conf)+ assert cfg.enabled is True+ assert cfg.listen_port == 3333+ assert cfg.relay_timeout_sec == 120.0++ proxy = cfg.to_proxy_config()+ assert proxy.listen_host == "127.0.0.1"+ assert proxy.listen_port == 3333+++def test_proxy_config_from_dict_sets_default_host_key_path():+ proxy = proxy_config_from_dict({"listen_port": 2222})+ assert proxy.host_key_path.endswith("ssh_host_key")diff --git a/tests/unit_tests/extensions/test_agentos_ssh_relay.py b/tests/unit_tests/extensions/test_agentos_ssh_relay.pynew file mode 100644index 0000000000..1de90db752--- /dev/null+++ b/tests/unit_tests/extensions/test_agentos_ssh_relay.py@@ -0,0 +1,323 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.++"""Tests for the AgentOS Router southbound SSH relay into YuanRong."""++from __future__ import annotations++import asyncio+from typing import Any++import pytest++from jiuwenswarm.common.e2a.models import E2AEnvelope+from jiuwenswarm.common.schema.message import ReqMethod+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import AgentManager+from jiuwenswarm.extensions.agentos.agentos_router.config import load_router_config+from jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSRouterClient+from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import (+ DEFAULT_SSH_USER_TEMPLATE,+ YuanrongSshRelay,+ YuanrongSshSettings,+ load_yuanrong_ssh_settings,+)+from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import SshRelaySession++from tests.unit_tests.extensions.test_agentos_router import (+ FakeRegistryClient,+ FakeYuanRongClient,+)+++def _relay_session(session_id: str = "ssh_alice_1234") -> SshRelaySession:+ return SshRelaySession(+ session_id=session_id,+ process=None,+ )+++def _ssh_envelope(+ session: SshRelaySession | None = None,+ *,+ agent_type: str | None = "jiuwenswarm",+ session_id: str | None = None,+) -> E2AEnvelope:+ params: dict[str, Any] = {}+ if session is not None:+ params["relay_session"] = session+ if agent_type is not None:+ params["agent_type"] = agent_type+ return E2AEnvelope(+ request_id="req-ssh-1",+ channel="ssh",+ user_id="alice",+ session_id=session_id or (session.session_id if session else "ssh_missing"),+ method=ReqMethod.SSH_RELAY.value,+ params=params,+ )+++class StubSshRelay:+ """Records relay invocations and resolves the session like the real relay."""++ def __init__(self) -> None:+ self.ran: list[tuple[str, str]] = []+ self.failed: list[tuple[str, str]] = []++ def backend_username(self, instance_id: str) -> str:+ return DEFAULT_SSH_USER_TEMPLATE.format(instance=instance_id)++ async def run(self, session: Any, instance_id: str) -> int:+ self.ran.append((session.session_id, instance_id))+ session.exit_code = 0+ session.done.set()+ return 0++ def fail_session(self, session: Any, reason: str) -> None:+ self.failed.append((session.session_id, reason))+ session.exit_code = 1+ session.done.set()+++# ---------- settings / username ----------+++def test_backend_username_uses_yr_instance_template() -> None:+ relay = YuanrongSshRelay(+ YuanrongSshSettings(),+ frontend_endpoint="http://frontend.yuanrong.test:31220",+ )+ assert (+ relay.backend_username("inst-42")+ == "yr:instance:inst-42:user=agentos"+ )+ assert relay.backend_host == "frontend.yuanrong.test"+ assert relay.backend_port == 2222+++def test_backend_username_requires_instance_id() -> None:+ relay = YuanrongSshRelay(YuanrongSshSettings())+ with pytest.raises(ValueError):+ relay.backend_username(" ")+++def test_backend_host_from_frontend_endpoint() -> None:+ relay = YuanrongSshRelay(+ YuanrongSshSettings(port=2200),+ frontend_endpoint="http://frontend.yuanrong.test:31220",+ )+ assert relay.backend_host == "frontend.yuanrong.test"+ assert relay.backend_port == 2200+++def test_load_yuanrong_ssh_settings_defaults() -> None:+ settings = load_yuanrong_ssh_settings(None)+ assert settings.port == 2222+ assert settings.user_template == DEFAULT_SSH_USER_TEMPLATE+ assert settings.connect_timeout_s == 30.0++ custom = load_yuanrong_ssh_settings(+ {"port": 2223, "user_template": "yr:{instance}"}+ )+ assert custom.port == 2223+ assert custom.user_template == "yr:{instance}"+++def test_import_asyncssh_raises_actionable_hint(monkeypatch: pytest.MonkeyPatch) -> None:+ import builtins+ import jiuwenswarm.extensions.agentos.agentos_router.ssh_relay as relay_mod++ real_import = builtins.__import__++ def _block_asyncssh(name: str, *args: Any, **kwargs: Any):+ if name == "asyncssh" or name.startswith("asyncssh."):+ raise ImportError("blocked for test")+ return real_import(name, *args, **kwargs)++ monkeypatch.setattr(builtins, "__import__", _block_asyncssh)+ with pytest.raises(RuntimeError, match=r"jiuwenswarm\[ssh\]"):+ relay_mod._import_asyncssh()+++def test_load_router_config_parses_ssh_block() -> None:+ config = {+ "gateway": {+ "agent_client": {+ "type": "agentos_router",+ "frontend_endpoint": "http://yuanrong.test",+ "function_version_urn": "urn:test",+ },+ "agentos": {+ "ssh": {"port": 2222},+ },+ }+ }+ loaded = load_router_config(config)+ assert loaded.ssh.port == 2222+ assert loaded.ssh.user_template == DEFAULT_SSH_USER_TEMPLATE+++# ---------- router dispatch ----------+++async def test_ssh_relay_creates_instance_and_starts_relay() -> None:+ session = _relay_session()+ stub_relay = StubSshRelay()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ FakeYuanRongClient(),+ FakeRegistryClient(),+ agent_manager,+ ssh_relay=stub_relay,+ )+ try:+ response = await client.send_request(_ssh_envelope(session))+ assert response.ok+ assert response.payload["status"] == "relay_started"++ await asyncio.wait_for(session.done.wait(), timeout=5)+ assert stub_relay.ran == [("ssh_alice_1234", "sbx-1")]+ assert stub_relay.failed == []+ assert session.exit_code == 0++ agents = await agent_manager.list_user_agents("alice")+ assert len(agents) == 1+ assert agents[0].info.sandbox_id == "sbx-1"+ finally:+ await client.shutdown()+++async def test_ssh_relay_reuses_existing_instance() -> None:+ yuanrong = FakeYuanRongClient()+ stub_relay = StubSshRelay()+ client = AgentOSRouterClient(+ yuanrong,+ FakeRegistryClient(),+ AgentManager(),+ ssh_relay=stub_relay,+ )+ first = _relay_session("ssh_alice_a")+ second = _relay_session("ssh_alice_b")+ try:+ await client.send_request(_ssh_envelope(first))+ await asyncio.wait_for(first.done.wait(), timeout=5)+ await client.send_request(_ssh_envelope(second))+ await asyncio.wait_for(second.done.wait(), timeout=5)++ assert yuanrong.create_calls == 1+ assert [item[1] for item in stub_relay.ran] == ["sbx-1", "sbx-1"]+ finally:+ await client.shutdown()+++async def test_ssh_relay_follows_user_current_agent_type() -> None:+ """SSH 未显式指定 agent_type 时,跟随 3rdagent.switch 切换后的用户当前值。"""+ yuanrong = FakeYuanRongClient()+ stub_relay = StubSshRelay()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ yuanrong,+ FakeRegistryClient(),+ agent_manager,+ ssh_relay=stub_relay,+ )+ session = _relay_session("ssh_alice_switch")+ try:+ # 用户切换到 opencode+ result = await client.thirdagent_switch(user_id="alice", agent_type="opencode")+ assert result["ok"]+ assert client.get_current_agent_type("alice") == "opencode"++ # SSH 接入不带 agent_type -> 复用 opencode 实例(不新建)+ await client.send_request(_ssh_envelope(session, agent_type=None))+ await asyncio.wait_for(session.done.wait(), timeout=5)++ assert yuanrong.create_calls == 1 # switch 已创建,SSH 复用+ assert stub_relay.ran == [("ssh_alice_switch", "sbx-1")]+ agents = await agent_manager.list_user_agents("alice")+ assert [a.info.agent_type for a in agents] == ["opencode"]+ finally:+ await client.shutdown()+++async def test_ssh_relay_defaults_to_jiuwenswarm_without_switch() -> None:+ """未切换过的用户,SSH 不带 agent_type 时默认 jiuwenswarm。"""+ stub_relay = StubSshRelay()+ agent_manager = AgentManager()+ client = AgentOSRouterClient(+ FakeYuanRongClient(),+ FakeRegistryClient(),+ agent_manager,+ ssh_relay=stub_relay,+ )+ assert client.get_current_agent_type("alice") == "jiuwenswarm"+ session = _relay_session("ssh_alice_default")+ try:+ await client.send_request(_ssh_envelope(session, agent_type=None))+ await asyncio.wait_for(session.done.wait(), timeout=5)++ agents = await agent_manager.list_user_agents("alice")+ assert [a.info.agent_type for a in agents] == ["jiuwenswarm"]+ finally:+ await client.shutdown()+++async def test_ssh_relay_missing_session_returns_error() -> None:+ client = AgentOSRouterClient(+ FakeYuanRongClient(),+ FakeRegistryClient(),+ AgentManager(),+ ssh_relay=StubSshRelay(),+ )+ try:+ response = await client.send_request(_ssh_envelope(session_id="ssh_missing"))+ assert not response.ok+ assert "ssh relay session not found" in response.payload["error"]+ finally:+ await client.shutdown()+++async def test_ssh_relay_without_relay_configured_fails_session() -> None:+ session = _relay_session("ssh_norelay")+ client = AgentOSRouterClient(+ FakeYuanRongClient(),+ FakeRegistryClient(),+ AgentManager(),+ )+ try:+ response = await client.send_request(_ssh_envelope(session))+ assert not response.ok+ assert session.done.is_set()+ assert session.exit_code == 1+ finally:+ await client.shutdown()+++async def test_ssh_relay_agent_creation_failure_releases_session() -> None:+ class FailingYuanRong(FakeYuanRongClient):+ async def create_sandbox(self, **kwargs: Any):+ raise RuntimeError("create failed")++ session = _relay_session("ssh_fail")+ stub_relay = StubSshRelay()+ client = AgentOSRouterClient(+ FailingYuanRong(),+ FakeRegistryClient(),+ AgentManager(),+ ssh_relay=stub_relay,+ )+ try:+ response = await client.send_request(_ssh_envelope(session))+ assert response.ok # relay task started; failure is reported via session+ await asyncio.wait_for(session.done.wait(), timeout=5)+ assert session.exit_code == 1+ assert stub_relay.ran == []+ assert len(stub_relay.failed) == 1+ finally:+ await client.shutdown()diff --git a/uv.lock b/uv.lockindex 9ec0c9ded7..a06698dd6e 100644--- a/uv.lock+++ b/uv.lock@@ -304,6 +304,19 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/91/66/b25ccb84a246b470eb943b0107c07edcae51804912b824054b3413995a10/asyncpg-0.31.0-cp313-cp313-win_amd64.whl", hash = "sha256:dc5f2fa9916f292e5c5c8b2ac2813763bcd7f58e130055b4ad8a0531314201ab", size = 596569, upload-time = "2025-11-24T23:26:16.189Z" },]+[[package]]+name = "asyncssh"+version = "2.23.1"+source = { registry = "https://pypi.org/simple" }+dependencies = [+ { name = "cryptography" },+ { name = "typing-extensions" },+]+sdist = { url = "https://files.pythonhosted.org/packages/a4/95/212d3d394f2a6ccb3f95056d3b9a7ce13c2f58503cbd6a38d037ef48cb13/asyncssh-2.23.1.tar.gz", hash = "sha256:d9dc3bc0206f3e4b5d80d1c0e6a24af2b4ad4beb556884c41fb2ad1c7ca3f44f", size = 542883, upload-time = "2026-06-07T14:15:18.832Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/ef/94/9aa81bde40627af70388d634152e7c53e7533788e662b8093047501a1473/asyncssh-2.23.1-py3-none-any.whl", hash = "sha256:f68e55476d41253d785bcac9a90834ae5fdea0f417bd6d7182608bda248de88e", size = 376054, upload-time = "2026-06-07T14:15:17.375Z" },+]+[[package]]name = "attrs"version = "26.1.0"@@ -1840,8 +1853,12 @@ harmony = [{ name = "uvicorn", extra = ["standard"] },{ name = "wecom-aibot-sdk" },]+ssh = [+ { name = "asyncssh" },+]test = [{ name = "a2a-sdk", extra = ["http-server"] },+ { name = "asyncssh" },{ name = "coverage" },{ name = "pytest" },{ name = "pytest-asyncio" },@@ -1857,6 +1874,7 @@ tui = [[package.dev-dependencies]dev = [{ name = "a2a-sdk", extra = ["http-server"] },+ { name = "asyncssh" },{ name = "codespell" },{ name = "coverage" },{ name = "httpx", extra = ["socks"] },@@ -1879,6 +1897,7 @@ lint = []test = [{ name = "a2a-sdk", extra = ["http-server"] },+ { name = "asyncssh" },{ name = "coverage" },{ name = "pytest" },{ name = "pytest-asyncio" },@@ -1896,6 +1915,8 @@ requires-dist = [{ name = "a2ui-agent-sdk", marker = "extra == 'harmony'", specifier = "==0.2.1" },{ name = "aiosqlite", specifier = ">=0.22.1" },{ name = "aiosqlite", marker = "extra == 'harmony'", specifier = ">=0.22.1" },+ { name = "asyncssh", marker = "extra == 'ssh'", specifier = ">=2.14.0,<2.24" },+ { name = "asyncssh", marker = "extra == 'test'", specifier = ">=2.14.0,<2.24" },{ name = "chromadb", specifier = ">=1.5.0" },{ name = "coverage", marker = "extra == 'test'", specifier = ">=7.7.1" },{ name = "croniter", specifier = ">=2.0.0" },@@ -1972,11 +1993,12 @@ requires-dist = [{ name = "wecom-aibot-sdk", specifier = ">=1.0.5" },{ name = "wecom-aibot-sdk", marker = "extra == 'harmony'", specifier = ">=1.0.5" },]-provides-extras = ["harmony", "a2a", "desktop", "dev", "tui", "distribute", "shell-ast", "test"]+provides-extras = ["harmony", "a2a", "ssh", "desktop", "dev", "tui", "distribute", "shell-ast", "test"][package.metadata.requires-dev]dev = [{ name = "a2a-sdk", extras = ["http-server"], specifier = "==1.0.0" },+ { name = "asyncssh", specifier = ">=2.14.0,<2.24" },{ name = "codespell", specifier = ">=2.2.4" },{ name = "coverage", specifier = ">=7.7.1" },{ name = "httpx", extras = ["socks"], specifier = ">=0.28.1" },@@ -1999,6 +2021,7 @@ lint = []test = [{ name = "a2a-sdk", extras = ["http-server"], specifier = "==1.0.0" },+ { name = "asyncssh", specifier = ">=2.14.0,<2.24" },{ name = "coverage", specifier = ">=7.7.1" },{ name = "pytest", specifier = ">=8.3.5" },{ name = "pytest-asyncio", specifier = ">=1.0.0" },