Skip to content

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

fix(agentos): 3rdagent.switch 等 sandbox sshd 就绪再返回

yechenzhena0afdbcb0b3e
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
index 99dfb097b2..7ddff7807e 100644
--- a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
@@ -717,6 +717,31 @@ class AgentOSRouterClient(AgentServerClient):
}
info = runtime.info
status = info.status.value if hasattr(info.status, "value") else str(info.status)
+ instance_id = str(info.sandbox_id or "").strip()
+ ssh_relay = self._ssh_relay
+ if ssh_relay is not None:
+ if not instance_id:
+ return {
+ "ok": False,
+ "error": f"agent has no yuanrong instance_id: user={uid}",
+ "code": "INTERNAL_ERROR",
+ }
+ try:
+ # create 返回不代表 sshd 已听端口;等南向 SSH 通了再让客户端连。
+ await ssh_relay.wait_until_ready(instance_id, user_id=uid)
+ except Exception as exc:
+ logger.warning(
+ "[AgentOSRouter] 3rdagent.switch sshd not ready: "
+ "user=%s instance=%s error=%s",
+ uid,
+ instance_id,
+ exc,
+ )
+ return {
+ "ok": False,
+ "error": f"sandbox sshd not ready: {exc}",
+ "code": "SSH_NOT_READY",
+ }
# 记录用户当前 agent_type,后续 SSH 接入默认跟随
self._current_agent_types[uid] = normalized
payload = {
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py
index 201d77dc16..32fe7a4f83 100644
--- a/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py
+++ b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py
@@ -43,6 +43,27 @@ _DEFAULT_CLIENT_KEY_NAMES = (
"id_ed448",
"agent_key",
)
+# create_sandbox 返回后 frontend bastion / 实例 sshd 可能尚未就绪,对端会
+# 立刻掐连接(asyncssh: "SSH connection closed")。对齐 chat WS 冷启动重试。
+_SSH_CONNECT_READY_TIMEOUT_SECONDS = 60.0
+_SSH_CONNECT_RETRY_INTERVAL_SECONDS = 1.0
+_SSH_CONNECT_RETRYABLE_TEXT_TOKENS = (
+ "ssh connection closed",
+ "connection closed",
+ "connection reset",
+ "connection refused",
+ "temporarily unavailable",
+ "connect call failed",
+ "timeout",
+)
+
+
+def _is_ssh_connect_retryable(exc: BaseException) -> bool:
+ """冷启动期间 frontend/sshd 未就绪的可重试错误."""
+ if isinstance(exc, (ConnectionError, TimeoutError, asyncio.TimeoutError, OSError)):
+ return True
+ text = str(exc).lower()
+ return any(token in text for token in _SSH_CONNECT_RETRYABLE_TEXT_TOKENS)
def _raise_missing_asyncssh(exc: ImportError) -> None:
@@ -202,13 +223,31 @@ class YuanrongSshRelay:
)
return key_paths
- async def _relay(
+ async def wait_until_ready(
self,
- session: Any,
instance_id: str,
*,
user_id: str = "",
- ) -> int:
+ ) -> None:
+ """Probe southbound SSH until sshd accepts, then close the probe.
+
+ Used by ``3rdagent.switch`` after create so the client does not SSH
+ before the YuanRong instance is reachable.
+ """
+ conn = await self._connect_until_ready(instance_id, user_id=user_id)
+ conn.close()
+ try:
+ await conn.wait_closed()
+ except Exception: # noqa: BLE001
+ logger.debug("[YuanrongSshRelay] probe close failed", exc_info=True)
+
+ async def _connect_until_ready(
+ self,
+ instance_id: str,
+ *,
+ user_id: str = "",
+ session_id: str = "",
+ ) -> Any:
asyncssh = _import_asyncssh()
host = self.backend_host
@@ -219,26 +258,73 @@ class YuanrongSshRelay:
)
username = self.backend_username(instance_id)
client_keys = self._resolve_client_keys(user_id)
-
- logger.info(
- "[YuanrongSshRelay] connecting: %s@%s:%s session=%s keys_dir=%s keys=%s",
- username,
- host,
- self._settings.port,
- session.session_id,
- resolve_client_keys_dir(self._settings.client_keys_dir, user_id),
- len(client_keys),
+ keys_dir = resolve_client_keys_dir(self._settings.client_keys_dir, user_id)
+ deadline = (
+ asyncio.get_running_loop().time() + _SSH_CONNECT_READY_TIMEOUT_SECONDS
)
- conn = await asyncio.wait_for(
- asyncssh.connect(
+ attempt = 0
+ while True:
+ attempt += 1
+ logger.info(
+ "[YuanrongSshRelay] connecting: %s@%s:%s session=%s "
+ "attempt=%s keys_dir=%s keys=%s",
+ username,
host,
- port=self._settings.port,
- username=username,
- client_keys=client_keys,
- agent_path=None,
- known_hosts=None,
- ),
- timeout=self._settings.connect_timeout_s,
+ self._settings.port,
+ session_id or "-",
+ attempt,
+ keys_dir,
+ len(client_keys),
+ )
+ try:
+ conn = await asyncio.wait_for(
+ asyncssh.connect(
+ host,
+ port=self._settings.port,
+ username=username,
+ client_keys=client_keys,
+ agent_path=None,
+ known_hosts=None,
+ ),
+ timeout=self._settings.connect_timeout_s,
+ )
+ except Exception as exc:
+ remaining = deadline - asyncio.get_running_loop().time()
+ if remaining <= 0 or not _is_ssh_connect_retryable(exc):
+ raise
+ sleep_for = min(_SSH_CONNECT_RETRY_INTERVAL_SECONDS, remaining)
+ logger.warning(
+ "[YuanrongSshRelay] ssh not ready, retrying: "
+ "session=%s instance=%s attempt=%s sleep=%.1fs error=%s",
+ session_id or "-",
+ instance_id,
+ attempt,
+ sleep_for,
+ exc,
+ )
+ await asyncio.sleep(sleep_for)
+ continue
+ if attempt > 1:
+ logger.info(
+ "[YuanrongSshRelay] ssh ready after retry: "
+ "session=%s instance=%s attempts=%s",
+ session_id or "-",
+ instance_id,
+ attempt,
+ )
+ return conn
+
+ async def _relay(
+ self,
+ session: Any,
+ instance_id: str,
+ *,
+ user_id: str = "",
+ ) -> int:
+ conn = await self._connect_until_ready(
+ instance_id,
+ user_id=user_id,
+ session_id=str(getattr(session, "session_id", "") or ""),
)
try:
return await self._relay_over_connection(session, conn)
diff --git a/tests/unit_tests/extensions/test_agentos_ssh_relay.py b/tests/unit_tests/extensions/test_agentos_ssh_relay.py
index 4005bea94e..79d68bcea3 100644
--- a/tests/unit_tests/extensions/test_agentos_ssh_relay.py
+++ b/tests/unit_tests/extensions/test_agentos_ssh_relay.py
@@ -23,6 +23,7 @@ from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import (
DEFAULT_SSH_USER_TEMPLATE,
YuanrongSshRelay,
YuanrongSshSettings,
+ _is_ssh_connect_retryable,
list_client_key_paths,
load_yuanrong_ssh_settings,
resolve_client_keys_dir,
@@ -102,6 +103,9 @@ class StubSshRelay:
session.exit_code = 1
session.done.set()
+ async def wait_until_ready(self, instance_id: str, *, user_id: str = "") -> None:
+ del instance_id, user_id
+
# ---------- settings / username ----------
@@ -187,6 +191,115 @@ def test_resolve_client_keys_requires_private_key(tmp_path: Path) -> None:
assert relay._resolve_client_keys("alice") == [str(key_dir / "id_ed25519")]
+def test_is_ssh_connect_retryable_for_cold_start_errors() -> None:
+ assert _is_ssh_connect_retryable(ConnectionRefusedError())
+ assert _is_ssh_connect_retryable(TimeoutError("timeout"))
+ assert _is_ssh_connect_retryable(RuntimeError("SSH connection closed"))
+ assert not _is_ssh_connect_retryable(ValueError("no SSH private keys found"))
+
+
+async def test_wait_until_ready_retries_closed_then_succeeds(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ import jiuwenswarm.extensions.agentos.agentos_router.ssh_relay as relay_mod
+
+ monkeypatch.setattr(relay_mod, "_SSH_CONNECT_RETRY_INTERVAL_SECONDS", 0.01)
+ monkeypatch.setattr(relay_mod, "_SSH_CONNECT_READY_TIMEOUT_SECONDS", 2.0)
+
+ key_dir = tmp_path / "alice"
+ key_dir.mkdir()
+ (key_dir / "id_ed25519").write_text("k", encoding="utf-8")
+
+ class _Conn:
+ def __init__(self) -> None:
+ self.closed = False
+
+ def close(self) -> None:
+ self.closed = True
+
+ async def wait_closed(self) -> None:
+ return None
+
+ attempts = {"n": 0}
+
+ class _FakeAsyncssh:
+ async def connect(self, *args: Any, **kwargs: Any) -> _Conn:
+ del args, kwargs
+ attempts["n"] += 1
+ if attempts["n"] < 3:
+ raise ConnectionRefusedError("SSH connection closed")
+ return _Conn()
+
+ monkeypatch.setattr(relay_mod, "_import_asyncssh", lambda: _FakeAsyncssh())
+ relay = YuanrongSshRelay(
+ YuanrongSshSettings(client_keys_dir=str(tmp_path / "{user_id}")),
+ frontend_endpoint="http://frontend.test:8888",
+ )
+ await relay.wait_until_ready("inst-1", user_id="alice")
+ assert attempts["n"] == 3
+
+
+async def test_thirdagent_switch_waits_for_sshd_after_create() -> None:
+ class _WaitRelay(StubSshRelay):
+ def __init__(self) -> None:
+ super().__init__()
+ self.ready_calls: list[tuple[str, str]] = []
+
+ async def wait_until_ready(self, instance_id: str, *, user_id: str = "") -> None:
+ self.ready_calls.append((instance_id, user_id))
+
+ relay = _WaitRelay()
+ yuanrong = FakeYuanRongClient()
+ client = AgentOSRouterClient(
+ yuanrong,
+ FakeRegistryClient(),
+ AgentManager(),
+ ssh_relay=relay,
+ ssh_channel_endpoint=SshChannelEndpoint(ip="0.0.0.0", port=2222),
+ )
+ try:
+ response = await client.thirdagent_switch(
+ user_id="alice",
+ agent_type="opencode",
+ session_id="sess-1",
+ )
+ finally:
+ await client.shutdown()
+
+ assert response["ok"] is True
+ assert yuanrong.create_calls == 1
+ assert relay.ready_calls == [("sbx-1", "alice")]
+
+
+async def test_thirdagent_switch_sshd_not_ready_fails() -> None:
+ class _WaitRelay(StubSshRelay):
+ async def wait_until_ready(self, instance_id: str, *, user_id: str = "") -> None:
+ raise ConnectionRefusedError("SSH connection closed")
+
+ client = AgentOSRouterClient(
+ FakeYuanRongClient(),
+ FakeRegistryClient(),
+ AgentManager(),
+ ssh_relay=_WaitRelay(),
+ ssh_channel_endpoint=SshChannelEndpoint(ip="0.0.0.0", port=2222),
+ )
+ try:
+ response = await client.thirdagent_switch(
+ user_id="alice",
+ agent_type="opencode",
+ session_id="sess-1",
+ )
+ finally:
+ await client.shutdown()
+
+ assert response["ok"] is False
+ assert response["code"] == "SSH_NOT_READY"
+ assert "sshd not ready" in response["error"]
+
+
def test_import_asyncssh_raises_actionable_hint(monkeypatch: pytest.MonkeyPatch) -> None:
import builtins
import jiuwenswarm.extensions.agentos.agentos_router.ssh_relay as relay_mod