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(gateway): tear down SSH north/south when either side disconnects
yechenzhen0305a2f56264
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.pyindex 03d98809ce..4fd47e798a 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py@@ -361,6 +361,7 @@ class AgentOSRouterClient(AgentServerClient):self._run_ssh_relay(envelope, relay_session),name=f"agentos-ssh-relay-{session_id[:24]}",)+ relay_session.relay_task = taskself._background_tasks.add(task)task.add_done_callback(self._background_tasks.discard)return AgentResponse(@@ -442,8 +443,12 @@ class AgentOSRouterClient(AgentServerClient):)async def _drain_background_tasks(self) -> None:- if self._background_tasks:- await asyncio.gather(*self._background_tasks, return_exceptions=True)+ if not self._background_tasks:+ return+ tasks = list(self._background_tasks)+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)self._background_tasks.clear()async def _resolve_agent(self, envelope: E2AEnvelope) -> AgentRuntime:diff --git a/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.pyindex 37732f49a4..043382013d 100644--- a/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py+++ b/jiuwenswarm/extensions/agentos/agentos_router/ssh_relay.py@@ -150,10 +150,20 @@ class YuanrongSshRelay:Always resolves ``session.done`` and ``session.exit_code`` so thenorthbound channel waiting in ``_wait_relay_done`` is released.+ Cancellation (northbound timeout / router disconnect) also releases+ the waiter and tears down the southbound connection."""exit_code = 1try:exit_code = await self._relay(session, instance_id, user_id=user_id)+ except asyncio.CancelledError:+ logger.info(+ "[YuanrongSshRelay] relay cancelled: session=%s instance=%s",+ session.session_id,+ instance_id,+ )+ exit_code = 130+ raiseexcept Exception as exc: # noqa: BLE001 - report any relay failure to the clientlogger.exception("[YuanrongSshRelay] relay failed: session=%s instance=%s",@@ -249,18 +259,78 @@ class YuanrongSshRelay:if term_size and term_size[0]:kwargs["term_size"] = term_sizebackend = await conn.create_process(**kwargs)- try:- await asyncio.gather(++ # Either side dying must tear down the other: wait FIRST_COMPLETED,+ # then cancel remaining pumps and close both ends.+ pumps = [+ asyncio.create_task(self._pump_client_to_backend(session, backend),+ name=f"ssh-pump-n2s-{session.session_id[:16]}",+ ),+ asyncio.create_task(self._pump_backend_to_client(backend.stdout, process.stdout),+ name=f"ssh-pump-s2n-out-{session.session_id[:16]}",+ ),+ asyncio.create_task(self._pump_backend_to_client(backend.stderr, process.stderr),+ name=f"ssh-pump-s2n-err-{session.session_id[:16]}",+ ),+ ]+ try:+ done, pending = await asyncio.wait(+ pumps, return_when=asyncio.FIRST_COMPLETED)- await backend.wait_closed()+ for task in pending:+ task.cancel()+ if pending:+ await asyncio.gather(*pending, return_exceptions=True)+ for task in done:+ exc = task.exception() if not task.cancelled() else None+ if exc is not None:+ logger.debug(+ "[YuanrongSshRelay] pump ended with error: %s",+ exc,+ exc_info=exc,+ )+ except asyncio.CancelledError:+ for task in pumps:+ task.cancel()+ await asyncio.gather(*pumps, return_exceptions=True)+ raisefinally:- backend.close()+ await self._close_backend(backend)+ self._exit_northbound(process, backend.exit_status)+exit_status = backend.exit_statusreturn int(exit_status) if exit_status is not None else 0+ @staticmethod+ async def _close_backend(backend: Any) -> None:+ try:+ backend.close()+ except Exception: # noqa: BLE001+ logger.debug("[YuanrongSshRelay] backend.close failed", exc_info=True)+ try:+ await backend.wait_closed()+ except Exception: # noqa: BLE001+ logger.debug(+ "[YuanrongSshRelay] backend.wait_closed failed", exc_info=True+ )++ @staticmethod+ def _exit_northbound(process: Any, exit_status: Any) -> None:+ """Force-close the northbound SSH process when the southbound ends."""+ if process is None:+ return+ code = int(exit_status) if exit_status is not None else 0+ try:+ process.exit(code)+ except Exception: # noqa: BLE001 - channel may already be closed+ logger.debug(+ "[YuanrongSshRelay] northbound process.exit failed",+ exc_info=True,+ )+@staticmethodasync def _pump_client_to_backend(session: Any, backend: Any) -> None:asyncssh = _import_asyncssh()@@ -281,7 +351,10 @@ class YuanrongSshRelay:)continueexcept asyncssh.BreakReceived:- backend.stdin.write(b"\x03")+ try:+ backend.stdin.write(b"\x03")+ except (asyncssh.ConnectionLost, ConnectionError):+ breakcontinueexcept (asyncssh.ConnectionLost, ConnectionError):break@@ -293,8 +366,8 @@ class YuanrongSshRelay:"[YuanrongSshRelay] write_eof failed", exc_info=True)break- backend.stdin.write(data)try:+ backend.stdin.write(data)await backend.stdin.drain()except (asyncssh.ConnectionLost, ConnectionError):breakdiff --git a/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.pyindex 01fe66035e..d725011263 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/server.py@@ -181,13 +181,29 @@ class SSHProxy:)await self.agent_hooks.submit_relay(session_id, metadata)exit_code = await self.agent_hooks.wait_relay_done(session_id)- process.exit(exit_code)+ try:+ process.exit(exit_code)+ except Exception: # noqa: BLE001 - may already be closed by southbound teardown+ logger.debug(+ "[SSHChannel] process.exit after relay done failed for %s",+ username,+ exc_info=True,+ )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)+ try:+ process.stdout.write(f"Proxy error: {exc}\n".encode())+ except Exception: # noqa: BLE001+ pass+ try:+ process.exit(1)+ except Exception: # noqa: BLE001+ passexcept Exception:logger.exception("[SSHChannel] SSH session failed for %s", username)- process.exit(1)+ try:+ process.exit(1)+ except Exception: # noqa: BLE001+ passfinally: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.pyindex 9d67266428..afe490e867 100644--- a/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py+++ b/jiuwenswarm/gateway/channel_manager/protocol/ssh/ssh_connect.py@@ -31,6 +31,18 @@ class SshRelaySession:process: Anydone: asyncio.Event = field(default_factory=asyncio.Event)exit_code: int = 0+ # Background southbound relay task (set by AgentOS Router); cancelled on+ # northbound timeout or disconnect so the YuanRong SSH connection is+ # torn down instead of lingering until relay_timeout_sec / TCP timeout.+ relay_task: asyncio.Task[Any] | None = None++ def cancel_relay(self) -> bool:+ """Cancel the southbound relay task if it is still running."""+ task = self.relay_task+ if task is None or task.done():+ return False+ task.cancel()+ return True@dataclass@@ -145,7 +157,18 @@ class SshChannel(BaseChannel):)async def _unregister_session(self, session_id: str) -> None:- self._sessions.pop(session_id, None)+ session = self._sessions.pop(session_id, None)+ relay = session.relay if session is not None else None+ # Northbound session is over (clean exit, hard disconnect, or the+ # handler task itself was cancelled by asyncssh on connection loss).+ # The southbound pumps may never notice a dead client (stdin.read can+ # block forever), so explicitly cancel the relay task here.+ if relay is not None and relay.cancel_relay():+ logger.info(+ "[SSHChannel] northbound session %s closed; "+ "cancelled southbound relay",+ session_id,+ )async def _wait_relay_done(self, session_id: str) -> int:session = self._sessions.get(session_id)@@ -157,10 +180,23 @@ class SshChannel(BaseChannel):except asyncio.TimeoutError:logger.error("[SSHChannel] relay timeout for session %s "- "(no southbound handler completed the relay within %.0fs)",+ "(no southbound handler completed the relay within %.0fs); "+ "cancelling southbound relay",session_id,self.config.relay_timeout_sec,)+ if relay.cancel_relay():+ try:+ await asyncio.wait_for(relay.done.wait(), timeout=5.0)+ except asyncio.TimeoutError:+ logger.warning(+ "[SSHChannel] southbound relay did not finish after "+ "cancel for session %s",+ session_id,+ )+ if not relay.done.is_set():+ relay.exit_code = 124+ relay.done.set()return 124return relay.exit_codediff --git a/tests/unit_tests/extensions/test_agentos_ssh_relay.py b/tests/unit_tests/extensions/test_agentos_ssh_relay.pyindex 0fc8ffd1f3..d97f2c4b3e 100644--- a/tests/unit_tests/extensions/test_agentos_ssh_relay.py+++ b/tests/unit_tests/extensions/test_agentos_ssh_relay.py@@ -427,3 +427,365 @@ async def test_ssh_relay_agent_creation_failure_releases_session() -> None:assert "create failed" in stub_relay.failed[0][1]finally:await client.shutdown()+++# ---------- bidirectional disconnect ----------+++class _FakeStream:+ """Minimal async stream used by disconnect tests."""++ def __init__(+ self,+ chunks: list[bytes] | None = None,+ *,+ raise_on_read: BaseException | None = None,+ block_read: bool = False,+ ) -> None:+ self._chunks = list(chunks or [])+ self._raise_on_read = raise_on_read+ self._block_read = block_read+ self.writes: list[bytes] = []+ self.eof_written = False+ self._read_event = asyncio.Event()++ async def read(self, _n: int) -> bytes:+ if self._raise_on_read is not None:+ raise self._raise_on_read+ if self._block_read:+ await self._read_event.wait()+ return b""+ if not self._chunks:+ return b""+ return self._chunks.pop(0)++ def write(self, data: bytes) -> None:+ self.writes.append(data)++ async def drain(self) -> None:+ return None++ def write_eof(self) -> None:+ self.eof_written = True++ def unblock(self) -> None:+ self._read_event.set()+++class _FakeProcess:+ def __init__(self, stdin: _FakeStream, stdout: _FakeStream, stderr: _FakeStream) -> None:+ self.stdin = stdin+ self.stdout = stdout+ self.stderr = stderr+ self.exit_codes: list[int] = []++ def get_terminal_type(self) -> str:+ return "xterm"++ def get_terminal_size(self) -> tuple[int, int]:+ return (80, 24)++ def exit(self, code: int) -> None:+ self.exit_codes.append(code)+++class _FakeBackend:+ def __init__(+ self,+ stdout: _FakeStream,+ stderr: _FakeStream,+ stdin: _FakeStream | None = None,+ *,+ exit_status: int | None = 0,+ ) -> None:+ self.stdout = stdout+ self.stderr = stderr+ self.stdin = stdin or _FakeStream()+ self.exit_status = exit_status+ self.closed = False+ self.wait_closed_called = False++ def close(self) -> None:+ self.closed = True+ self.stdout.unblock()+ self.stderr.unblock()+ self.stdin.unblock()++ async def wait_closed(self) -> None:+ self.wait_closed_called = True+++class _FakeConn:+ def __init__(self, backend: _FakeBackend) -> None:+ self._backend = backend+ self.create_calls = 0++ async def create_process(self, *args: Any, **kwargs: Any) -> _FakeBackend:+ del args, kwargs+ self.create_calls += 1+ return self._backend+++def _install_fake_asyncssh(modules: dict[str, Any]) -> type[BaseException]:+ from types import ModuleType++ fake_asyncssh = ModuleType("asyncssh")++ class ConnectionLost(Exception):+ pass++ class TerminalSizeChanged(Exception):+ pass++ class BreakReceived(Exception):+ pass++ fake_asyncssh.ConnectionLost = ConnectionLost # type: ignore[attr-defined]+ fake_asyncssh.TerminalSizeChanged = TerminalSizeChanged # type: ignore[attr-defined]+ fake_asyncssh.BreakReceived = BreakReceived # type: ignore[attr-defined]+ modules["asyncssh"] = fake_asyncssh+ return ConnectionLost+++async def test_southbound_eof_closes_northbound_and_cancels_pumps() -> None:+ """Southbound stdout EOF must exit the northbound process and stop other pumps."""+ import sys+ from unittest.mock import patch++ modules: dict[str, Any] = dict(sys.modules)+ _install_fake_asyncssh(modules)++ north_stdin = _FakeStream(block_read=True)+ north_stdout = _FakeStream()+ north_stderr = _FakeStream()+ process = _FakeProcess(north_stdin, north_stdout, north_stderr)++ backend_stdout = _FakeStream(chunks=[b"bye"]) # one chunk then EOF+ backend_stderr = _FakeStream(block_read=True)+ backend = _FakeBackend(backend_stdout, backend_stderr, exit_status=7)+ conn = _FakeConn(backend)++ session = _relay_session("ssh_s2n")+ session.process = process++ relay = YuanrongSshRelay(+ YuanrongSshSettings(),+ frontend_endpoint="http://127.0.0.1:31220",+ )+ with patch.dict(sys.modules, modules):+ code = await asyncio.wait_for(+ relay._relay_over_connection(session, conn),+ timeout=5,+ )++ assert code == 7+ assert backend.closed is True+ assert process.exit_codes == [7]+ assert north_stdout.writes == [b"bye"]+++async def test_northbound_disconnect_closes_southbound() -> None:+ """Northbound ConnectionLost must close the southbound backend."""+ import sys+ from unittest.mock import patch++ modules: dict[str, Any] = dict(sys.modules)+ ConnectionLost = _install_fake_asyncssh(modules)++ north_stdin = _FakeStream(raise_on_read=ConnectionLost())+ process = _FakeProcess(north_stdin, _FakeStream(), _FakeStream())++ backend_stdout = _FakeStream(block_read=True)+ backend_stderr = _FakeStream(block_read=True)+ backend = _FakeBackend(backend_stdout, backend_stderr, exit_status=None)+ conn = _FakeConn(backend)++ session = _relay_session("ssh_n2s")+ session.process = process++ relay = YuanrongSshRelay(+ YuanrongSshSettings(),+ frontend_endpoint="http://127.0.0.1:31220",+ )+ with patch.dict(sys.modules, modules):+ code = await asyncio.wait_for(+ relay._relay_over_connection(session, conn),+ timeout=5,+ )++ assert code == 0+ assert backend.closed is True+ assert process.exit_codes == [0]+++async def test_relay_run_cancelled_releases_session_done() -> None:+ """Cancelling the relay task must still set session.done for the northbound waiter."""+ session = _relay_session("ssh_cancel")+ session.process = _FakeProcess(_FakeStream(), _FakeStream(), _FakeStream())+ relay = YuanrongSshRelay(+ YuanrongSshSettings(),+ frontend_endpoint="http://127.0.0.1:31220",+ )++ async def _hang(+ _session: Any, _instance_id: str, *, user_id: str = ""+ ) -> int:+ del user_id+ await asyncio.Event().wait()+ return 0++ relay._relay = _hang # type: ignore[method-assign]+ task = asyncio.create_task(relay.run(session, "inst-1"))+ await asyncio.sleep(0)+ assert not session.done.is_set()+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task+ assert session.done.is_set()+ assert session.exit_code == 130+++async def test_router_disconnect_cancels_background_ssh_relay() -> None:+ """Router disconnect must cancel in-flight SSH relay background tasks."""+ started = asyncio.Event()+ cancelled = asyncio.Event()++ class HangingRelay(StubSshRelay):+ async def run(+ self,+ session: Any,+ instance_id: str,+ *,+ user_id: str = "",+ ) -> int:+ del instance_id, user_id+ started.set()+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancelled.set()+ session.exit_code = 130+ session.done.set()+ raise+ return 0++ session = _relay_session("ssh_drain")+ client = AgentOSRouterClient(+ FakeYuanRongClient(),+ FakeRegistryClient(),+ AgentManager(),+ ssh_relay=HangingRelay(),+ )+ try:+ await client.send_request(_ssh_envelope(session, agent_type="opencode"))+ await asyncio.wait_for(started.wait(), timeout=5)+ assert session.relay_task is not None+ assert not session.relay_task.done()+ await client.disconnect()+ await asyncio.wait_for(cancelled.wait(), timeout=5)+ assert session.done.is_set()+ finally:+ await client.shutdown()+++async def test_wait_relay_done_timeout_cancels_southbound_task() -> None:+ """Northbound relay timeout must cancel the southbound relay_task."""+ from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import (+ SshChannel,+ SshChannelConfig,+ )++ cancelled = asyncio.Event()++ async def _hanging_relay() -> None:+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancelled.set()+ session.exit_code = 130+ session.done.set()+ raise++ session = _relay_session("ssh_timeout")+ session.relay_task = asyncio.create_task(_hanging_relay())++ channel = SshChannel(+ SshChannelConfig(enabled=False, relay_timeout_sec=0.05),+ router=None, # type: ignore[arg-type]+ )+ await channel._register_session(+ session_id="ssh_timeout",+ process=object(),+ username="alice",+ client_addr="127.0.0.1:1",+ )+ channel._sessions["ssh_timeout"].relay = session+ try:+ code = await channel._wait_relay_done("ssh_timeout")+ assert code == 124+ await asyncio.wait_for(cancelled.wait(), timeout=5)+ assert session.done.is_set()+ finally:+ await channel._unregister_session("ssh_timeout")+ if session.relay_task and not session.relay_task.done():+ session.relay_task.cancel()+ try:+ await session.relay_task+ except asyncio.CancelledError:+ pass+++async def test_unregister_session_cancels_southbound_task() -> None:+ """Northbound session teardown must cancel a still-running southbound+ relay, even when the pumps never notice the dead client (stdin blocked)."""+ from jiuwenswarm.gateway.channel_manager.protocol.ssh.ssh_connect import (+ SshChannel,+ SshChannelConfig,+ )++ cancelled = asyncio.Event()++ async def _hanging_relay() -> None:+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ cancelled.set()+ session.exit_code = 130+ session.done.set()+ raise++ session = _relay_session("ssh_unreg")+ session.relay_task = asyncio.create_task(_hanging_relay())+ # Let the relay task start; cancelling a never-started task would skip+ # its CancelledError handler.+ await asyncio.sleep(0)++ channel = SshChannel(+ SshChannelConfig(enabled=False),+ router=None, # type: ignore[arg-type]+ )+ await channel._register_session(+ session_id="ssh_unreg",+ process=object(),+ username="alice",+ client_addr="127.0.0.1:1",+ )+ channel._sessions["ssh_unreg"].relay = session+ try:+ await channel._unregister_session("ssh_unreg")+ await asyncio.wait_for(cancelled.wait(), timeout=5)+ assert session.done.is_set()+ assert "ssh_unreg" not in channel._sessions+ finally:+ if session.relay_task and not session.relay_task.done():+ session.relay_task.cancel()+ try:+ await session.relay_task+ except asyncio.CancelledError:+ pass