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

feat(agentos): return channels.ssh listen endpoint from 3rdagent.switch

yechenzhen646e9857757b
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/config.py b/jiuwenswarm/extensions/agentos/agentos_router/config.py
index f9b444f120..01414681dc 100644
--- a/jiuwenswarm/extensions/agentos/agentos_router/config.py
+++ b/jiuwenswarm/extensions/agentos/agentos_router/config.py
@@ -16,6 +16,14 @@ from jiuwenswarm.extensions.agentos.agentos_router.ssh_relay import (
)
+@dataclass(frozen=True)
+class SshChannelEndpoint:
+ """Northbound ``channels.ssh`` listen address for ``3rdagent.switch``."""
+
+ ip: str = ""
+ port: int = 0
+
+
@dataclass(frozen=True)
class RouterConfig:
frontend_endpoint: str
@@ -28,6 +36,7 @@ class RouterConfig:
creating_timeout_seconds: float = 60.0
agent_key_fields: tuple[str, ...] = DEFAULT_AGENT_KEY_FIELDS
ssh: YuanrongSshSettings = YuanrongSshSettings()
+ ssh_channel: SshChannelEndpoint | None = None
def agentos_router_selected(config: dict[str, Any]) -> bool:
@@ -43,6 +52,29 @@ def agentos_router_selected(config: dict[str, Any]) -> bool:
)
+def load_ssh_channel_endpoint(config: dict[str, Any]) -> SshChannelEndpoint | None:
+ """Load northbound SSH listen ip/port from ``channels.ssh``.
+
+ Returns ``None`` when the channel is disabled or listen address is incomplete.
+ """
+ channels = config.get("channels") if isinstance(config, dict) else None
+ if not isinstance(channels, dict):
+ return None
+ ssh = channels.get("ssh")
+ if not isinstance(ssh, dict):
+ return None
+ if not bool(ssh.get("enabled", False)):
+ return None
+ ip = str(ssh.get("listen_host") or "").strip()
+ try:
+ port = int(ssh.get("listen_port") or 0)
+ except (TypeError, ValueError):
+ return None
+ if not ip or port <= 0:
+ return None
+ return SshChannelEndpoint(ip=ip, port=port)
+
+
def load_router_config(config: dict[str, Any]) -> RouterConfig:
gateway = config.get("gateway") if isinstance(config, dict) else {}
if not isinstance(gateway, dict):
@@ -86,4 +118,5 @@ def load_router_config(config: dict[str, Any]) -> RouterConfig:
agentos.get("agent_key_fields")
),
ssh=load_yuanrong_ssh_settings(agentos.get("ssh")),
+ ssh_channel=load_ssh_channel_endpoint(config),
)
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/extension.py b/jiuwenswarm/extensions/agentos/agentos_router/extension.py
index 8c4071abe0..c5ab8f6f53 100644
--- a/jiuwenswarm/extensions/agentos/agentos_router/extension.py
+++ b/jiuwenswarm/extensions/agentos/agentos_router/extension.py
@@ -51,6 +51,7 @@ class AgentOSRouter(AgentServerClientExtension, ThirdAgentExtension):
self._registry_client,
self._agent_manager,
ssh_relay=self._ssh_relay,
+ ssh_channel_endpoint=config.ssh_channel,
)
self._third_agent = AgentOSThirdAgent(self._router_client)
self._closed = False
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
index 8e34de6322..0c8f7407e5 100644
--- a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
@@ -20,6 +20,7 @@ from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (
AgentRuntime,
THIRD_PARTY_AGENT_TYPES,
)
+from jiuwenswarm.extensions.agentos.agentos_router.config import SshChannelEndpoint
from jiuwenswarm.extensions.agentos.agentos_router.models import (
AgentInfo,
AgentStatus,
@@ -90,11 +91,13 @@ class AgentOSRouterClient(AgentServerClient):
registry: RegistryClient,
agent_manager: AgentManager,
ssh_relay: YuanrongSshRelay | None = None,
+ ssh_channel_endpoint: SshChannelEndpoint | None = None,
) -> None:
self._yuanrong = yuanrong
self._registry = registry
self._agent_manager = agent_manager
self._ssh_relay = ssh_relay
+ self._ssh_channel_endpoint = ssh_channel_endpoint
self._server_ready = False
self._background_tasks: set[asyncio.Task[Any]] = set()
self._closed = False
@@ -223,6 +226,28 @@ class AgentOSRouterClient(AgentServerClient):
},
}
+ def _ssh_endpoint_fields(self) -> dict[str, Any] | None:
+ """Northbound ``channels.ssh`` listen ip/port, or None if unavailable."""
+ endpoint = self._ssh_channel_endpoint
+ if endpoint is None:
+ return None
+ ip = str(endpoint.ip or "").strip()
+ port = int(endpoint.port or 0)
+ if not ip or port <= 0:
+ return None
+ return {"ssh_ip": ip, "ssh_port": port}
+
+ @staticmethod
+ def _missing_ssh_endpoint_error() -> dict[str, Any]:
+ return {
+ "ok": False,
+ "error": (
+ "ssh channel endpoint is unavailable: enable channels.ssh "
+ "and set listen_host / listen_port"
+ ),
+ "code": "SSH_ENDPOINT_UNAVAILABLE",
+ }
+
async def thirdagent_switch(
self,
*,
@@ -230,7 +255,11 @@ class AgentOSRouterClient(AgentServerClient):
agent_type: str,
session_id: str = "",
) -> dict[str, Any]:
- """Handle ``3rdagent.switch``: ensure agent exists without forwarding chat."""
+ """Handle ``3rdagent.switch``: ensure agent exists without forwarding chat.
+
+ Success payload includes northbound SSH channel ``ssh_ip``/``ssh_port``
+ (``channels.ssh.listen_host`` / ``listen_port``). Missing values fail.
+ """
uid = str(user_id or "").strip()
if not uid:
return {
@@ -246,6 +275,10 @@ class AgentOSRouterClient(AgentServerClient):
"error": str(exc),
"code": "UNSUPPORTED_AGENT_TYPE",
}
+ # Fail fast before create when northbound SSH channel is not configured.
+ ssh_fields = self._ssh_endpoint_fields()
+ if ssh_fields is None:
+ return self._missing_ssh_endpoint_error()
# Builtin swarm: no registry / create_sandbox; mark current type only.
if self._uses_direct_yuanrong(normalized):
self._current_agent_types[uid] = normalized
@@ -256,6 +289,7 @@ class AgentOSRouterClient(AgentServerClient):
"agent_type": normalized,
"sandbox_id": "",
"status": AgentStatus.READY.value,
+ **ssh_fields,
},
}
try:
@@ -283,6 +317,7 @@ class AgentOSRouterClient(AgentServerClient):
"agent_type": info.agent_type,
"sandbox_id": info.sandbox_id,
"status": status,
+ **ssh_fields,
},
}
diff --git a/tests/unit_tests/extensions/test_agentos_router.py b/tests/unit_tests/extensions/test_agentos_router.py
index bcbfb2b57c..3ec0d47cf2 100644
--- a/tests/unit_tests/extensions/test_agentos_router.py
+++ b/tests/unit_tests/extensions/test_agentos_router.py
@@ -9,6 +9,7 @@ from jiuwenswarm.common.e2a.models import E2AEnvelope
from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import AgentManager
from jiuwenswarm.extensions.agentos.agentos_router.config import (
+ SshChannelEndpoint,
agentos_router_selected,
load_router_config,
)
@@ -22,6 +23,14 @@ from jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSR
from jiuwenswarm.extensions.yuanrong_frontend_client import SandboxInfo
+def _ssh_channel(
+ *,
+ ip: str = "0.0.0.0",
+ port: int = 2222,
+) -> SshChannelEndpoint:
+ return SshChannelEndpoint(ip=ip, port=port)
+
+
class FakeYuanRongClient:
def __init__(self) -> None:
self.server_ready = True
@@ -223,7 +232,9 @@ async def test_third_party_type_creates_via_yuanrong() -> None:
async def test_agent_switch_creates_without_forwarding_chat() -> None:
yuanrong = FakeYuanRongClient()
agent_manager = AgentManager()
- client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+ client = AgentOSRouterClient(
+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()
+ )
response = await client.thirdagent_switch(
user_id="u1",
@@ -237,11 +248,32 @@ async def test_agent_switch_creates_without_forwarding_chat() -> None:
assert yuanrong.send_calls == 0
assert response["payload"]["agent_type"] == "claude"
assert response["payload"]["sandbox_id"] == "sbx-1"
+ assert response["payload"]["ssh_ip"] == "0.0.0.0"
+ assert response["payload"]["ssh_port"] == 2222
agents = await agent_manager.list_user_agents("u1")
assert len(agents) == 1
assert agents[0].info.agent_type == "claude"
+async def test_agent_switch_fails_without_ssh_endpoint() -> None:
+ yuanrong = FakeYuanRongClient()
+ agent_manager = AgentManager()
+ client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+
+ response = await client.thirdagent_switch(
+ user_id="u1",
+ agent_type="claude",
+ session_id="sess-1",
+ )
+ await client.shutdown()
+
+ assert response["ok"] is False
+ assert response["code"] == "SSH_ENDPOINT_UNAVAILABLE"
+ assert "ssh" in response["error"].lower()
+ assert yuanrong.create_calls == 0
+
+
@pytest.mark.asyncio
async def test_agent_list_returns_registry_images_without_creating() -> None:
yuanrong = FakeYuanRongClient()
@@ -272,7 +304,9 @@ async def test_agent_list_returns_registry_images_without_creating() -> None:
async def test_agent_switch_reuses_existing_agent() -> None:
yuanrong = FakeYuanRongClient()
agent_manager = AgentManager()
- client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+ client = AgentOSRouterClient(
+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()
+ )
first = await client.thirdagent_switch(
user_id="u1",
@@ -290,13 +324,17 @@ async def test_agent_switch_reuses_existing_agent() -> None:
assert yuanrong.create_calls == 1
assert yuanrong.send_calls == 0
assert first["payload"]["agent_id"] == second["payload"]["agent_id"]
+ assert first["payload"]["ssh_ip"] == second["payload"]["ssh_ip"]
+ assert first["payload"]["ssh_port"] == second["payload"]["ssh_port"]
@pytest.mark.asyncio
async def test_chat_after_switch_reuses_agent() -> None:
yuanrong = FakeYuanRongClient()
agent_manager = AgentManager()
- client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+ client = AgentOSRouterClient(
+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()
+ )
switch_resp = await client.thirdagent_switch(
user_id="u1",
@@ -318,7 +356,9 @@ async def test_chat_after_switch_reuses_agent() -> None:
async def test_switch_to_jiuwenswarm_is_direct_without_create() -> None:
yuanrong = FakeYuanRongClient()
agent_manager = AgentManager()
- client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+ client = AgentOSRouterClient(
+ yuanrong, FakeRegistryClient(), agent_manager, ssh_channel_endpoint=_ssh_channel()
+ )
response = await client.thirdagent_switch(
user_id="u1",
@@ -332,6 +372,8 @@ async def test_switch_to_jiuwenswarm_is_direct_without_create() -> None:
assert yuanrong.send_calls == 0
assert response["payload"]["agent_type"] == "jiuwenswarm"
assert response["payload"]["sandbox_id"] == ""
+ assert response["payload"]["ssh_ip"] == "0.0.0.0"
+ assert response["payload"]["ssh_port"] == 2222
assert client.get_current_agent_type("u1") == "jiuwenswarm"
assert await agent_manager.list_user_agents("u1") == []
@@ -377,7 +419,9 @@ async def test_agentos_third_agent_list_and_switch() -> None:
yuanrong = FakeYuanRongClient()
registry = FakeRegistryClient()
agent_manager = AgentManager()
- client = AgentOSRouterClient(yuanrong, registry, agent_manager)
+ client = AgentOSRouterClient(
+ yuanrong, registry, agent_manager, ssh_channel_endpoint=_ssh_channel(port=2223)
+ )
third = AgentOSThirdAgent(client)
listed = await third.thirdagent_list(user_id="u1", current_agent_type="jiuwenswarm")
@@ -393,6 +437,8 @@ async def test_agentos_third_agent_list_and_switch() -> None:
]
assert switched["ok"] is True
assert switched["payload"]["agent_type"] == "claude"
+ assert switched["payload"]["ssh_ip"] == "0.0.0.0"
+ assert switched["payload"]["ssh_port"] == 2223
assert yuanrong.create_calls == 1
assert yuanrong.send_calls == 0
diff --git a/tests/unit_tests/extensions/test_agentos_ssh_relay.py b/tests/unit_tests/extensions/test_agentos_ssh_relay.py
index 3adcd2f420..73f4b14856 100644
--- a/tests/unit_tests/extensions/test_agentos_ssh_relay.py
+++ b/tests/unit_tests/extensions/test_agentos_ssh_relay.py
@@ -12,7 +12,10 @@ 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.config import (
+ SshChannelEndpoint,
+ 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,
@@ -59,9 +62,16 @@ def _ssh_envelope(
class StubSshRelay:
"""Records relay invocations and resolves the session like the real relay."""
- def __init__(self) -> None:
+ def __init__(
+ self,
+ *,
+ backend_host: str = "frontend.yuanrong.test",
+ backend_port: int = 2222,
+ ) -> None:
self.ran: list[tuple[str, str]] = []
self.failed: list[tuple[str, str]] = []
+ self.backend_host = backend_host
+ self.backend_port = backend_port
def backend_username(self, instance_id: str) -> str:
return DEFAULT_SSH_USER_TEMPLATE.format(instance=instance_id)
@@ -149,11 +159,40 @@ def test_load_router_config_parses_ssh_block() -> None:
"agentos": {
"ssh": {"port": 2222},
},
- }
+ },
+ "channels": {
+ "ssh": {
+ "enabled": True,
+ "listen_host": "192.168.1.10",
+ "listen_port": 2222,
+ }
+ },
}
loaded = load_router_config(config)
assert loaded.ssh.port == 2222
assert loaded.ssh.user_template == DEFAULT_SSH_USER_TEMPLATE
+ assert loaded.ssh_channel == SshChannelEndpoint(ip="192.168.1.10", port=2222)
+
+
+def test_load_router_config_ssh_channel_requires_enabled() -> None:
+ config = {
+ "gateway": {
+ "agent_client": {
+ "type": "agentos_router",
+ "frontend_endpoint": "http://yuanrong.test",
+ "function_version_urn": "urn:test",
+ },
+ },
+ "channels": {
+ "ssh": {
+ "enabled": False,
+ "listen_host": "0.0.0.0",
+ "listen_port": 2222,
+ }
+ },
+ }
+ loaded = load_router_config(config)
+ assert loaded.ssh_channel is None
# ---------- router dispatch ----------
@@ -225,12 +264,16 @@ async def test_ssh_relay_follows_user_current_agent_type() -> None:
FakeRegistryClient(),
agent_manager,
ssh_relay=stub_relay,
+ ssh_channel_endpoint=SshChannelEndpoint(ip="0.0.0.0", port=2222),
)
session = _relay_session("ssh_alice_switch")
try:
# 用户切换到 opencode
result = await client.thirdagent_switch(user_id="alice", agent_type="opencode")
assert result["ok"]
+ assert result["payload"]["ssh_ip"] == "0.0.0.0"
+ assert result["payload"]["ssh_port"] == 2222
+ assert "ssh_user" not in result["payload"]
assert client.get_current_agent_type("alice") == "opencode"
# SSH 接入不带 agent_type -> 复用 opencode 实例(不新建)