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(gateway): add AgentOS Router extension

yechenzhenb65b3258d5ab
diff --git a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
index 20f5920a3a..0542d4071c 100644
--- a/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
+++ b/deploy/yuanrong/conf/gateway-config-yuanrong.template.yaml
@@ -473,9 +473,9 @@ gateway:
session_map_scope: <<GATEWAY_SESSION_MAP_SCOPE>>
# AgentClient 配置 - Gateway 连接到 AgentServer 的方式
- # type: websocket(默认,WebSocket 连接) | yuanrong(openYuanRong 函数调用)
+ # type: websocket(默认) | yuanrong(直接函数调用) | agentos_router(AgentOS 扩展)
agent_client:
- type: yuanrong # websocket | yuanrong
+ type: yuanrong # websocket | yuanrong | agentos_router
# yuanrong 函数模式配置下面参数
frontend_endpoint: http://<<MASTER_NODE_IP>>:<<FRONTEND_PORT>>
function_version_urn: <<FUNCTION_ID>>
diff --git a/jiuwenswarm/extensions/agentos/__init__.py b/jiuwenswarm/extensions/agentos/__init__.py
new file mode 100644
index 0000000000..c2f6146ba3
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/__init__.py
@@ -0,0 +1,25 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from jiuwenswarm.extensions.agentos.agentos_router import (
+ AgentCreatingTimeout,
+ AgentInfo,
+ AgentManager,
+ AgentOSRouter,
+ AgentOSRouterClient,
+ AgentRuntime,
+ AgentStatus,
+ ImageInfo,
+ RegistryClient,
+)
+
+__all__ = [
+ "AgentCreatingTimeout",
+ "AgentInfo",
+ "AgentManager",
+ "AgentOSRouter",
+ "AgentOSRouterClient",
+ "AgentRuntime",
+ "AgentStatus",
+ "ImageInfo",
+ "RegistryClient",
+]
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/__init__.py b/jiuwenswarm/extensions/agentos/agentos_router/__init__.py
new file mode 100644
index 0000000000..1ff4b7b421
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/__init__.py
@@ -0,0 +1,32 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (
+ AgentCreatingTimeout,
+ AgentDeleted,
+ AgentManager,
+ AgentRuntime,
+ SUPPORTED_AGENT_TYPES,
+ normalize_agent_key_fields,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.extension import AgentOSRouter
+from jiuwenswarm.extensions.agentos.agentos_router.models import (
+ AgentInfo,
+ AgentStatus,
+ ImageInfo,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryClient
+from jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSRouterClient
+
+__all__ = [
+ "AgentCreatingTimeout",
+ "AgentInfo",
+ "AgentManager",
+ "AgentOSRouter",
+ "AgentOSRouterClient",
+ "AgentRuntime",
+ "AgentStatus",
+ "ImageInfo",
+ "RegistryClient",
+ "SUPPORTED_AGENT_TYPES",
+ "normalize_agent_key_fields",
+]
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/agent_manager.py b/jiuwenswarm/extensions/agentos/agentos_router/agent_manager.py
new file mode 100644
index 0000000000..8fde450807
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/agent_manager.py
@@ -0,0 +1,381 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+import asyncio
+import time
+from collections.abc import Awaitable, Callable, Mapping, Sequence
+from dataclasses import dataclass, field
+from typing import Any
+
+from jiuwenswarm.common.e2a.models import E2AEnvelope
+from jiuwenswarm.extensions.agentos.agentos_router.models import AgentInfo, AgentStatus
+
+
+AgentCreator = Callable[[AgentInfo], Awaitable[AgentInfo | None]]
+AgentKey = tuple[str, ...]
+SUPPORTED_AGENT_TYPES = frozenset({"jiuwenswarm", "opencode", "claude"})
+SUPPORTED_AGENT_KEY_FIELDS = frozenset({"user_id", "agent_type", "session_id"})
+DEFAULT_AGENT_KEY_FIELDS = ("user_id", "agent_type")
+
+
+def normalize_agent_key_fields(raw: Any = None) -> tuple[str, ...]:
+ """Normalize configured agent key fields.
+
+ Default is ``user_id + agent_type``. Supported fields:
+ ``user_id``, ``agent_type``, ``session_id``. Both ``user_id`` and
+ ``agent_type`` are always required.
+ """
+
+ if raw is None:
+ fields = list(DEFAULT_AGENT_KEY_FIELDS)
+ elif isinstance(raw, str):
+ text = raw.strip().lower().replace("+", ",").replace("|", ",")
+ fields = [part.strip() for part in text.split(",") if part.strip()]
+ elif isinstance(raw, Sequence) and not isinstance(raw, (bytes, bytearray)):
+ fields = [str(part).strip().lower() for part in raw if str(part).strip()]
+ else:
+ raise ValueError(
+ "agent_key_fields must be a string or list, "
+ f"got {type(raw).__name__}"
+ )
+
+ if not fields:
+ fields = list(DEFAULT_AGENT_KEY_FIELDS)
+
+ unique: list[str] = []
+ seen: set[str] = set()
+ for name in fields:
+ if name not in SUPPORTED_AGENT_KEY_FIELDS:
+ raise ValueError(f"unsupported agent_key_field: {name}")
+ if name not in seen:
+ seen.add(name)
+ unique.append(name)
+
+ if "user_id" not in seen or "agent_type" not in seen:
+ raise ValueError("agent_key_fields must include user_id and agent_type")
+ return tuple(unique)
+
+
+class AgentCreatingTimeout(TimeoutError):
+ """Timed out while waiting for another request to create an Agent."""
+
+
+class AgentDeleted(RuntimeError):
+ """Agent was deleted while creation was in flight."""
+
+
+@dataclass
+class AgentRuntime:
+ """In-process agent record: business info plus create-wait signaling."""
+
+ info: AgentInfo
+ key: AgentKey
+ creating_event: asyncio.Event = field(default_factory=asyncio.Event)
+
+ def is_ready(self) -> bool:
+ return self.info.status is AgentStatus.READY
+
+ def is_creating(self) -> bool:
+ return self.info.status is AgentStatus.CREATING
+
+ def is_failed(self) -> bool:
+ return self.info.status is AgentStatus.FAILED
+
+ def is_deleted(self) -> bool:
+ return self.info.status is AgentStatus.DELETED
+
+ def snapshot(self) -> AgentRuntime:
+ """Return a detached runtime view for callers (info only)."""
+ return AgentRuntime(info=self.info.copy(), key=self.key)
+
+ def attach_to_envelope(self, envelope: E2AEnvelope) -> None:
+ envelope.channel_context["agent_id"] = self.info.agent_id
+ envelope.channel_context["agent_type"] = self.info.agent_type
+ if self.info.sandbox_id:
+ envelope.channel_context["sandbox_id"] = self.info.sandbox_id
+
+ def reset_for_retry(self) -> None:
+ self.info.status = AgentStatus.CREATING
+ self.info.error = None
+ self.info.updated_at = time.time()
+ self.creating_event = asyncio.Event()
+
+ @staticmethod
+ def apply_creator_result(created: AgentInfo | None, *, base: AgentInfo) -> AgentInfo:
+ resolved = created.copy() if created is not None else base.copy()
+ resolved.agent_id = base.agent_id
+ resolved.user_id = base.user_id
+ resolved.agent_type = base.agent_type
+ resolved.status = AgentStatus.READY
+ resolved.error = None
+ resolved.updated_at = time.time()
+ return resolved
+
+ def mark_ready(self, resolved: AgentInfo) -> None:
+ self.info = resolved
+ self.creating_event.set()
+
+ def mark_failed(self, exc: BaseException) -> None:
+ failed = self.info.copy()
+ failed.status = AgentStatus.FAILED
+ failed.error = str(exc)
+ failed.updated_at = time.time()
+ self.info = failed
+ self.creating_event.set()
+
+ def mark_deleted(self) -> None:
+ deleted = self.info.copy()
+ deleted.status = AgentStatus.DELETED
+ deleted.error = "agent deleted"
+ deleted.updated_at = time.time()
+ self.info = deleted
+ self.creating_event.set()
+
+ async def wait_until_settled(self, timeout: float) -> None:
+ await asyncio.wait_for(self.creating_event.wait(), timeout=timeout)
+
+ @staticmethod
+ def normalize_agent_type(raw: Any) -> str:
+ agent_type = str(raw or "jiuwenswarm").strip().lower()
+ if agent_type not in SUPPORTED_AGENT_TYPES:
+ raise ValueError(f"unsupported agent_type: {agent_type}")
+ return agent_type
+
+ @staticmethod
+ def normalize_session_id(raw: Any) -> str:
+ session_id = str(raw or "").strip()
+ if not session_id:
+ raise ValueError("session_id is required by agent_key_fields")
+ return session_id
+
+ @staticmethod
+ def normalize_key_value(field_name: str, raw: Any) -> str:
+ if field_name == "user_id":
+ value = str(raw or "").strip()
+ if not value:
+ raise ValueError("user_id is required")
+ return value
+ if field_name == "agent_type":
+ return AgentRuntime.normalize_agent_type(raw)
+ if field_name == "session_id":
+ return AgentRuntime.normalize_session_id(raw)
+ value = str(raw or "").strip()
+ if not value:
+ raise ValueError(f"{field_name} is required by agent_key_fields")
+ return value
+
+ @staticmethod
+ def format_key(key: AgentKey, key_fields: Sequence[str]) -> str:
+ parts = [
+ f"{field_name}={value}"
+ for field_name, value in zip(key_fields, key, strict=False)
+ ]
+ return " ".join(parts)
+
+ @classmethod
+ def build_key(
+ cls,
+ key_fields: Sequence[str],
+ *,
+ user_id: str,
+ agent_type: str,
+ key_values: Mapping[str, Any] | None = None,
+ ) -> AgentKey:
+ values: dict[str, Any] = {
+ "user_id": user_id,
+ "agent_type": agent_type,
+ **dict(key_values or {}),
+ }
+ return tuple(
+ cls.normalize_key_value(name, values.get(name)) for name in key_fields
+ )
+
+ @classmethod
+ def for_key(
+ cls,
+ key: AgentKey,
+ *,
+ user_id: str,
+ agent_type: str,
+ metadata: dict[str, Any] | None = None,
+ ) -> AgentRuntime:
+ return cls(
+ key=key,
+ info=AgentInfo(
+ user_id=user_id,
+ agent_type=agent_type,
+ metadata=dict(metadata or {}),
+ ),
+ )
+
+
+class AgentManager:
+ """In-memory Agent store with configurable key fields and single-flight creation."""
+
+ def __init__(
+ self,
+ *,
+ creating_timeout_seconds: float = 60.0,
+ key_fields: Sequence[str] | str | None = None,
+ ) -> None:
+ self._key_fields = normalize_agent_key_fields(key_fields)
+ self._runtimes: dict[AgentKey, AgentRuntime] = {}
+ self._runtimes_lock = asyncio.Lock()
+ self._creating_timeout_seconds = max(0.1, float(creating_timeout_seconds))
+
+ @property
+ def key_fields(self) -> tuple[str, ...]:
+ return self._key_fields
+
+ def _make_key(
+ self,
+ user_id: str,
+ agent_type: str,
+ *,
+ key_values: Mapping[str, Any] | None = None,
+ ) -> AgentKey:
+ return AgentRuntime.build_key(
+ self._key_fields,
+ user_id=user_id,
+ agent_type=agent_type,
+ key_values=key_values,
+ )
+
+ def _identity_from_key(self, key: AgentKey) -> tuple[str, str]:
+ values = dict(zip(self._key_fields, key, strict=False))
+ return values["user_id"], values["agent_type"]
+
+ async def get_or_create_agent(
+ self,
+ user_id: str,
+ agent_type: str,
+ *,
+ key_values: Mapping[str, Any] | None = None,
+ creator: AgentCreator | None = None,
+ timeout_seconds: float | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> AgentRuntime:
+ """Get a READY Agent runtime or create one, waiting for in-flight creation."""
+
+ key = self._make_key(user_id, agent_type, key_values=key_values)
+ key_user_id, key_agent_type = self._identity_from_key(key)
+ wait_timeout = (
+ self._creating_timeout_seconds
+ if timeout_seconds is None
+ else max(0.1, float(timeout_seconds))
+ )
+ key_desc = AgentRuntime.format_key(key, self._key_fields)
+
+ while True:
+ owner = False
+ async with self._runtimes_lock:
+ existing = self._runtimes.get(key)
+ if existing is not None and existing.is_ready():
+ return existing.snapshot()
+
+ if existing is None:
+ runtime = AgentRuntime.for_key(
+ key,
+ user_id=key_user_id,
+ agent_type=key_agent_type,
+ metadata=metadata,
+ )
+ self._runtimes[key] = runtime
+ owner = True
+ else:
+ runtime = existing
+ if runtime.is_failed():
+ runtime.reset_for_retry()
+ owner = True
+ creator_base = runtime.info.copy()
+
+ if owner:
+ return await self._run_creator(
+ key, creator_base, creator, owner_runtime=runtime
+ )
+
+ try:
+ await runtime.wait_until_settled(wait_timeout)
+ except asyncio.TimeoutError as exc:
+ raise AgentCreatingTimeout(
+ f"AGENT_CREATING_TIMEOUT: {key_desc}"
+ ) from exc
+ if runtime.is_deleted():
+ raise AgentDeleted(f"AGENT_DELETED: {key_desc}")
+
+ async def get_agent(
+ self,
+ user_id: str,
+ agent_type: str,
+ *,
+ key_values: Mapping[str, Any] | None = None,
+ ) -> AgentRuntime | None:
+ key = self._make_key(user_id, agent_type, key_values=key_values)
+ async with self._runtimes_lock:
+ runtime = self._runtimes.get(key)
+ return runtime.snapshot() if runtime is not None else None
+
+ async def delete_agent(
+ self,
+ user_id: str,
+ agent_type: str,
+ *,
+ key_values: Mapping[str, Any] | None = None,
+ ) -> None:
+ key = self._make_key(user_id, agent_type, key_values=key_values)
+ async with self._runtimes_lock:
+ runtime = self._runtimes.pop(key, None)
+ if runtime is not None:
+ runtime.mark_deleted()
+
+ async def list_user_agents(self, user_id: str) -> list[AgentRuntime]:
+ normalized_user_id = str(user_id or "").strip()
+ async with self._runtimes_lock:
+ return [
+ runtime.snapshot()
+ for runtime in self._runtimes.values()
+ if runtime.info.user_id == normalized_user_id
+ ]
+
+ async def _mark_creator_failed(
+ self,
+ key: AgentKey,
+ exc: BaseException,
+ *,
+ owner_runtime: AgentRuntime,
+ ) -> None:
+ async with self._runtimes_lock:
+ if self._runtimes.get(key) is not owner_runtime:
+ return
+ owner_runtime.mark_failed(exc)
+
+ async def _run_creator(
+ self,
+ key: AgentKey,
+ agent: AgentInfo,
+ creator: AgentCreator | None,
+ *,
+ owner_runtime: AgentRuntime,
+ ) -> AgentRuntime:
+ key_desc = AgentRuntime.format_key(key, self._key_fields)
+ try:
+ created = await creator(agent.copy()) if creator is not None else agent
+ resolved = AgentRuntime.apply_creator_result(created, base=agent)
+ async with self._runtimes_lock:
+ if self._runtimes.get(key) is not owner_runtime:
+ raise AgentDeleted(f"AGENT_DELETED: {key_desc}")
+ owner_runtime.mark_ready(resolved)
+ return owner_runtime.snapshot()
+ except asyncio.CancelledError as exc:
+ await self._mark_creator_failed(
+ key, exc, owner_runtime=owner_runtime
+ )
+ raise
+ except AgentDeleted:
+ raise
+ except Exception as exc:
+ await self._mark_creator_failed(
+ key, exc, owner_runtime=owner_runtime
+ )
+ raise
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/config.py b/jiuwenswarm/extensions/agentos/agentos_router/config.py
new file mode 100644
index 0000000000..8655a8ec2f
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/config.py
@@ -0,0 +1,78 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (
+ DEFAULT_AGENT_KEY_FIELDS,
+ normalize_agent_key_fields,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryConfig
+
+
+@dataclass(frozen=True)
+class RouterConfig:
+ frontend_endpoint: str
+ function_version_urn: str
+ concurrency: int
+ invoke_timeout_s: float
+ registry: RegistryConfig
+ creating_timeout_seconds: float = 60.0
+ agent_key_fields: tuple[str, ...] = DEFAULT_AGENT_KEY_FIELDS
+
+
+def agentos_router_selected(config: dict[str, Any]) -> bool:
+ gateway = config.get("gateway") if isinstance(config, dict) else {}
+ if not isinstance(gateway, dict):
+ return False
+ agent_client = gateway.get("agent_client")
+ if not isinstance(agent_client, dict):
+ agent_client = {}
+ return (
+ str(agent_client.get("type") or "websocket").strip().lower()
+ == "agentos_router"
+ )
+
+
+def load_router_config(config: dict[str, Any]) -> RouterConfig:
+ gateway = config.get("gateway") if isinstance(config, dict) else {}
+ if not isinstance(gateway, dict):
+ gateway = {}
+ agent_client = gateway.get("agent_client")
+ if not isinstance(agent_client, dict):
+ agent_client = {}
+ agentos = gateway.get("agentos")
+ if not isinstance(agentos, dict):
+ agentos = {}
+ registry = agentos.get("registry")
+ if not isinstance(registry, dict):
+ registry = {}
+
+ frontend_endpoint = str(agent_client.get("frontend_endpoint") or "").strip()
+ function_version_urn = str(
+ agent_client.get("function_version_urn") or ""
+ ).strip()
+ if not frontend_endpoint or not function_version_urn:
+ raise ValueError(
+ "gateway.agent_client.frontend_endpoint and function_version_urn "
+ "are required in agentos_router mode"
+ )
+
+ return RouterConfig(
+ frontend_endpoint=frontend_endpoint,
+ function_version_urn=function_version_urn,
+ concurrency=int(agent_client.get("concurrency") or 1),
+ invoke_timeout_s=float(agent_client.get("invoke_timeout_s") or 60.0),
+ registry=RegistryConfig(
+ endpoint=str(registry.get("endpoint") or "").strip(),
+ request_timeout_s=float(registry.get("request_timeout_s") or 10.0),
+ ),
+ creating_timeout_seconds=float(
+ agentos.get("creating_timeout_seconds") or 60.0
+ ),
+ agent_key_fields=normalize_agent_key_fields(
+ agentos.get("agent_key_fields")
+ ),
+ )
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/extension.py b/jiuwenswarm/extensions/agentos/agentos_router/extension.py
new file mode 100644
index 0000000000..98762edfe7
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/extension.py
@@ -0,0 +1,65 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+from jiuwenswarm.common.config import get_config
+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import AgentManager
+from jiuwenswarm.extensions.agentos.agentos_router.config import (
+ RouterConfig,
+ agentos_router_selected,
+ load_router_config,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryClient
+from jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSRouterClient
+from jiuwenswarm.extensions.sdk.agent_server_client import (
+ AgentServerClientExtension,
+)
+from jiuwenswarm.extensions.yuanrong_frontend_client import (
+ YuanrongFrontendAgentClient,
+)
+from jiuwenswarm.gateway.routing.agent_client import AgentServerClient
+
+
+class AgentOSRouter(AgentServerClientExtension):
+ """AgentOS southbound Router extension."""
+
+ def __init__(self, config: RouterConfig) -> None:
+ self._config = config
+ self._yuanrong_client = YuanrongFrontendAgentClient(
+ frontend_endpoint=config.frontend_endpoint,
+ function_version_urn=config.function_version_urn,
+ concurrency=config.concurrency,
+ invoke_timeout_s=config.invoke_timeout_s,
+ )
+ self._registry_client = RegistryClient(config.registry)
+ self._agent_manager = AgentManager(
+ creating_timeout_seconds=config.creating_timeout_seconds,
+ key_fields=config.agent_key_fields,
+ )
+ self._router_client = AgentOSRouterClient(
+ self._yuanrong_client,
+ self._registry_client,
+ self._agent_manager,
+ )
+ self._closed = False
+
+ async def initialize(self, config) -> None:
+ del config
+
+ def get_client(self) -> AgentServerClient:
+ return self._router_client
+
+ async def shutdown(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ await self._router_client.shutdown()
+
+
+async def register_extensions(registry):
+ config = get_config()
+ if not agentos_router_selected(config):
+ return []
+ extension = AgentOSRouter(load_router_config(config))
+ registry.register_agent_server_client(extension)
+ return [extension]
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/models.py b/jiuwenswarm/extensions/agentos/agentos_router/models.py
new file mode 100644
index 0000000000..099f3ef8fd
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/models.py
@@ -0,0 +1,40 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+import time
+import uuid
+from dataclasses import dataclass, field, replace
+from enum import Enum
+from typing import Any
+
+
+class AgentStatus(str, Enum):
+ CREATING = "creating"
+ READY = "ready"
+ FAILED = "failed"
+ DELETED = "deleted"
+
+
+@dataclass
+class ImageInfo:
+ image_name: str
+ image_uri: str | None = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class AgentInfo:
+ user_id: str
+ agent_type: str
+ agent_id: str = field(default_factory=lambda: uuid.uuid4().hex)
+ status: AgentStatus = AgentStatus.CREATING
+ sandbox_id: str | None = None
+ public_key: str | None = None
+ created_at: float = field(default_factory=time.time)
+ updated_at: float = field(default_factory=time.time)
+ metadata: dict[str, Any] = field(default_factory=dict)
+ error: str | None = None
+
+ def copy(self) -> AgentInfo:
+ return replace(self, metadata=dict(self.metadata))
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/registry_client.py b/jiuwenswarm/extensions/agentos/agentos_router/registry_client.py
new file mode 100644
index 0000000000..114af71bed
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/registry_client.py
@@ -0,0 +1,39 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from jiuwenswarm.extensions.agentos.agentos_router.models import AgentInfo, ImageInfo
+
+
+@dataclass(frozen=True)
+class RegistryConfig:
+ endpoint: str = ""
+ request_timeout_s: float = 10.0
+
+
+class RegistryClient:
+ """Registry facade reserved for AgentOS phase two integration."""
+
+ def __init__(self, config: RegistryConfig) -> None:
+ self._config = config
+ self._registered_agents: dict[str, AgentInfo] = {}
+
+ async def register_agent(self, agent_info: AgentInfo) -> None:
+ self._registered_agents[agent_info.agent_id] = agent_info.copy()
+
+ async def unregister_agent(self, agent_id: str) -> None:
+ self._registered_agents.pop(str(agent_id or "").strip(), None)
+
+ async def report_heartbeat(self, agent_id: str) -> None:
+ del agent_id
+
+ async def get_image_info(self, image_name: str) -> ImageInfo:
+ return ImageInfo(
+ image_name=str(image_name or "").strip(),
+ metadata={"source": "phase_one_default"},
+ )
+
+ async def close(self) -> None:
+ self._registered_agents.clear()
diff --git a/jiuwenswarm/extensions/agentos/agentos_router/router_client.py b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
new file mode 100644
index 0000000000..e8643867f7
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/agentos_router/router_client.py
@@ -0,0 +1,241 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import AsyncIterator, Awaitable, Callable
+from typing import Any
+
+from jiuwenswarm.common.e2a.models import E2AEnvelope
+from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk
+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (
+ AgentCreatingTimeout,
+ AgentManager,
+ AgentRuntime,
+ SUPPORTED_AGENT_TYPES,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.models import AgentInfo, AgentStatus
+from jiuwenswarm.extensions.agentos.agentos_router.registry_client import RegistryClient
+from jiuwenswarm.extensions.yuanrong_frontend_client import (
+ YuanrongFrontendAgentClient,
+)
+from jiuwenswarm.gateway.routing.agent_client import AgentServerClient
+
+
+logger = logging.getLogger(__name__)
+
+
+class UnsupportedAgentType(ValueError):
+ pass
+
+
+class AgentOSRouterClient(AgentServerClient):
+ """AgentServerClient implementation backed by YuanRong and AgentManager."""
+
+ def __init__(
+ self,
+ yuanrong: YuanrongFrontendAgentClient,
+ registry: RegistryClient,
+ agent_manager: AgentManager,
+ ) -> None:
+ self._yuanrong = yuanrong
+ self._registry = registry
+ self._agent_manager = agent_manager
+ self._server_ready = False
+ self._background_tasks: set[asyncio.Task[Any]] = set()
+ self._closed = False
+
+ @property
+ def server_ready(self) -> bool:
+ return self._server_ready and self._yuanrong.server_ready
+
+ async def connect(self, uri: str) -> None:
+ await self._yuanrong.connect(uri)
+ self._closed = False
+ self._server_ready = True
+
+ async def disconnect(self) -> None:
+ if self._closed:
+ return
+ self._closed = True
+ self._server_ready = False
+ await self._drain_background_tasks()
+ try:
+ await self._yuanrong.disconnect()
+ finally:
+ await self._registry.close()
+
+ def set_or_update_server_config(
+ self,
+ *,
+ config: dict[str, Any],
+ env: dict[str, str] | None = None,
+ ) -> None:
+ self._yuanrong.set_or_update_server_config(config=config, env=env)
+
+ def set_server_push_handler(
+ self,
+ handler: Callable[[dict[str, Any]], Awaitable[None]] | None,
+ ) -> None:
+ setter = getattr(self._yuanrong, "set_server_push_handler", None)
+ if callable(setter):
+ setter(handler)
+
+ async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:
+ try:
+ runtime = await self._resolve_agent(envelope)
+ except (ValueError, AgentCreatingTimeout) as exc:
+ return self._routing_error_response(envelope, str(exc))
+ runtime.attach_to_envelope(envelope)
+ return await self._yuanrong.send_request(envelope)
+
+ async def send_request_stream(
+ self, envelope: E2AEnvelope
+ ) -> AsyncIterator[AgentResponseChunk]:
+ try:
+ runtime = await self._resolve_agent(envelope)
+ except (ValueError, AgentCreatingTimeout) as exc:
+ yield self._routing_error_chunk(envelope, str(exc))
+ return
+ runtime.attach_to_envelope(envelope)
+ async for chunk in self._yuanrong.send_request_stream(envelope):
+ yield chunk
+
+ async def shutdown(self) -> None:
+ await self.disconnect()
+
+ async def _drain_background_tasks(self) -> None:
+ if self._background_tasks:
+ await asyncio.gather(*self._background_tasks, return_exceptions=True)
+ self._background_tasks.clear()
+
+ async def _resolve_agent(self, envelope: E2AEnvelope) -> AgentRuntime:
+ user_id = self._extract_user_id(envelope)
+ agent_type = self._extract_agent_type(envelope)
+ return await self._agent_manager.get_or_create_agent(
+ user_id,
+ agent_type,
+ key_values={"session_id": envelope.session_id},
+ creator=self._create_agent,
+ metadata={"session_id": envelope.session_id},
+ )
+
+ async def _create_agent(self, agent_info: AgentInfo) -> AgentInfo:
+ if agent_info.agent_type not in SUPPORTED_AGENT_TYPES:
+ raise UnsupportedAgentType(
+ f"unsupported agent_type: {agent_info.agent_type}"
+ )
+
+ image_info = await self._registry.get_image_info(agent_info.agent_type)
+ sandbox = await self._yuanrong.create_sandbox(
+ user_id=agent_info.user_id,
+ agent_type=agent_info.agent_type,
+ agent_id=agent_info.agent_id,
+ image_name=image_info.image_name,
+ metadata={
+ "session_id": agent_info.metadata.get("session_id"),
+ "image_info": dict(image_info.metadata),
+ },
+ )
+ agent_info.sandbox_id = sandbox.sandbox_id
+ agent_info.metadata.update(
+ {
+ "image": image_info.image_name,
+ "image_info": dict(image_info.metadata),
+ "sandbox": dict(sandbox.metadata),
+ }
+ )
+ agent_info.status = AgentStatus.READY
+
+ task = asyncio.create_task(
+ self._register_agent(agent_info.copy()),
+ name=f"agentos-register-{agent_info.agent_id[:12]}",
+ )
+ self._background_tasks.add(task)
+ task.add_done_callback(self._background_tasks.discard)
+ return agent_info
+
+ async def delete_agent(
+ self,
+ user_id: str,
+ agent_type: str,
+ *,
+ key_values: dict[str, Any] | None = None,
+ ) -> None:
+ """Delete agent mapping and release its YuanRong sandbox."""
+ resolved_key_values = dict(key_values or {})
+ runtime = await self._agent_manager.get_agent(
+ user_id, agent_type, key_values=resolved_key_values or None
+ )
+ if runtime is None:
+ return
+ agent_info = runtime.info
+ if (
+ "session_id" not in resolved_key_values
+ and agent_info.metadata.get("session_id")
+ ):
+ resolved_key_values["session_id"] = agent_info.metadata.get(
+ "session_id"
+ )
+ if agent_info.sandbox_id:
+ await self._yuanrong.delete_sandbox(
+ agent_info.sandbox_id,
+ user_id=agent_info.user_id,
+ agent_type=agent_info.agent_type,
+ )
+ await self._agent_manager.delete_agent(
+ agent_info.user_id,
+ agent_info.agent_type,
+ key_values=resolved_key_values or None,
+ )
+
+ async def _register_agent(self, agent_info: AgentInfo) -> None:
+ try:
+ await self._registry.register_agent(agent_info)
+ except Exception:
+ logger.exception(
+ "[AgentOSRouter] async registry registration failed: agent_id=%s",
+ agent_info.agent_id,
+ )
+
+ @staticmethod
+ def _extract_user_id(envelope: E2AEnvelope) -> str:
+ user_id = str(envelope.user_id or "").strip()
+ if not user_id:
+ raise ValueError("user_id is required for AgentOS routing")
+ return user_id
+
+ @staticmethod
+ def _extract_agent_type(envelope: E2AEnvelope) -> str:
+ raw = envelope.params.get("agent_type")
+ if raw is None:
+ raw = envelope.channel_context.get("agent_type")
+ try:
+ return AgentRuntime.normalize_agent_type(raw)
+ except ValueError as exc:
+ raise UnsupportedAgentType(str(exc)) from exc
+
+ @staticmethod
+ def _routing_error_response(
+ envelope: E2AEnvelope,
+ message: str,
+ ) -> AgentResponse:
+ return AgentResponse(
+ request_id=str(envelope.request_id or ""),
+ channel_id=str(envelope.channel or ""),
+ ok=False,
+ payload={"error": message},
+ )
+
+ @staticmethod
+ def _routing_error_chunk(
+ envelope: E2AEnvelope,
+ message: str,
+ ) -> AgentResponseChunk:
+ return AgentResponseChunk(
+ request_id=str(envelope.request_id or ""),
+ channel_id=str(envelope.channel or ""),
+ payload={"error": message},
+ is_complete=True,
+ )
diff --git a/jiuwenswarm/extensions/agentos/extension.py b/jiuwenswarm/extensions/agentos/extension.py
new file mode 100644
index 0000000000..dba24a4e2f
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/extension.py
@@ -0,0 +1,10 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""AgentOS extension entry (discovered by ExtensionLoader)."""
+
+from jiuwenswarm.extensions.agentos.agentos_router.extension import (
+ AgentOSRouter,
+ register_extensions,
+)
+
+__all__ = ["AgentOSRouter", "register_extensions"]
diff --git a/jiuwenswarm/extensions/agentos/extension.yaml b/jiuwenswarm/extensions/agentos/extension.yaml
new file mode 100644
index 0000000000..13c66df3d7
--- /dev/null
+++ b/jiuwenswarm/extensions/agentos/extension.yaml
@@ -0,0 +1,9 @@
+id: agentos_router
+name: AgentOS Router
+version: 0.1.0
+description: Route AgentOS requests through YuanRong and the Agent registry
+author: jiuwenswarm
+min_jiuwenswarm_version: "0.2.3"
+dependencies: {}
+config_schema:
+ type: object
diff --git a/jiuwenswarm/extensions/yuanrong_frontend_client.py b/jiuwenswarm/extensions/yuanrong_frontend_client.py
index 9c1db3f689..fd26adf960 100644
--- a/jiuwenswarm/extensions/yuanrong_frontend_client.py
+++ b/jiuwenswarm/extensions/yuanrong_frontend_client.py
@@ -11,9 +11,11 @@ from __future__ import annotations
import asyncio
import json
import logging
+import uuid
import urllib.error
import urllib.parse
import urllib.request
+from dataclasses import dataclass, field
from typing import Any, AsyncIterator
from jiuwenswarm.common.e2a.agent_compat import e2a_to_agent_request
@@ -25,11 +27,23 @@ from jiuwenswarm.common.schema.agent import AgentResponse, AgentResponseChunk, A
logger = logging.getLogger(__name__)
+@dataclass
+class SandboxInfo:
+ """YuanRong sandbox lifecycle record (placeholder until real APIs land)."""
+
+ sandbox_id: str
+ user_id: str
+ agent_type: str
+ status: str = "ready"
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+
class YuanrongFrontendAgentClient(AgentServerClient):
"""openYuanRong Frontend HTTP 客户端.
通过 HTTP POST 调用 openYuanRong frontend 的函数 invocation 接口。
使用 session_id 进行并发控制,不使用 service_id/agent_id。
+ 另提供 create_sandbox / delete_sandbox 生命周期占位,供 AgentOS Router 使用。
"""
def __init__(
@@ -79,6 +93,75 @@ class YuanrongFrontendAgentClient(AgentServerClient):
self._server_ready = False
logger.info("[YuanrongFrontendAgentClient] disconnected")
+ async def create_sandbox(
+ self,
+ *,
+ user_id: str,
+ agent_type: str,
+ agent_id: str | None = None,
+ image_name: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> SandboxInfo:
+ """Create a sandbox via YuanRong (placeholder).
+
+ Both ``swarm`` / ``jiuwenswarm`` and ``3rd`` agent types are expected to
+ provision sandboxes through this API. Real Frontend create calls will
+ replace the local stub below.
+ """
+ self._ensure_connected()
+ normalized_user_id = str(user_id or "").strip()
+ normalized_agent_type = str(agent_type or "").strip().lower()
+ if not normalized_user_id:
+ raise ValueError("user_id is required to create sandbox")
+ if not normalized_agent_type:
+ raise ValueError("agent_type is required to create sandbox")
+
+ sandbox_id = f"sbx_{uuid.uuid4().hex}"
+ info = SandboxInfo(
+ sandbox_id=sandbox_id,
+ user_id=normalized_user_id,
+ agent_type=normalized_agent_type,
+ status="ready",
+ metadata={
+ **dict(metadata or {}),
+ "agent_id": agent_id,
+ "image_name": image_name,
+ "provisioning": "yuanrong_create_sandbox_stub",
+ },
+ )
+ logger.info(
+ "[YuanrongFrontendAgentClient] create_sandbox stub: "
+ "sandbox_id=%s user_id=%s agent_type=%s agent_id=%s",
+ sandbox_id,
+ normalized_user_id,
+ normalized_agent_type,
+ agent_id,
+ )
+ return info
+
+ async def delete_sandbox(
+ self,
+ sandbox_id: str,
+ *,
+ user_id: str | None = None,
+ agent_type: str | None = None,
+ ) -> None:
+ """Delete a sandbox via YuanRong (placeholder).
+
+ Applies to both ``swarm`` / ``jiuwenswarm`` and ``3rd`` sandboxes.
+ """
+ self._ensure_connected()
+ normalized_sandbox_id = str(sandbox_id or "").strip()
+ if not normalized_sandbox_id:
+ raise ValueError("sandbox_id is required to delete sandbox")
+ logger.info(
+ "[YuanrongFrontendAgentClient] delete_sandbox stub: "
+ "sandbox_id=%s user_id=%s agent_type=%s",
+ normalized_sandbox_id,
+ user_id,
+ agent_type,
+ )
+
def _ensure_connected(self) -> None:
if not self._connected:
raise RuntimeError("client not connected")
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index b001e22571..6a52ce12c0 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -553,15 +553,28 @@ gateway:
session_map_scope: per_chat_bot
# AgentClient 配置 - Gateway 连接到 AgentServer 的方式
- # type: websocket(默认,WebSocket 连接) | yuanrong(openYuanRong 函数调用)
+ # type: websocket(默认) | yuanrong(直接函数调用) | agentos_router(AgentOS 扩展)
agent_client:
- type: websocket # websocket | yuanrong
+ type: websocket # websocket | yuanrong | agentos_router
# yuanrong 函数模式配置下面参数
frontend_endpoint:
function_version_urn:
concurrency: 1
invoke_timeout_s: 60
+ # AgentOS Router Extension 配置;agent_client.type=agentos_router 时生效。
+ agentos:
+ creating_timeout_seconds: 60
+ # Agent 复用 key 字段,默认 user_id + agent_type。
+ # 可选字段:user_id、agent_type、session_id(必须包含前两项)。
+ # 示例:加入 session_id 后同一用户每个会话独立 Agent。
+ agent_key_fields:
+ - user_id
+ - agent_type
+ registry:
+ endpoint:
+ request_timeout_s: 10
+
heartbeat:
# 心跳间隔(秒),默认 3600
every: 3600
diff --git a/tests/unit_tests/extensions/test_agentos_agent_manager.py b/tests/unit_tests/extensions/test_agentos_agent_manager.py
new file mode 100644
index 0000000000..728fde8dae
--- /dev/null
+++ b/tests/unit_tests/extensions/test_agentos_agent_manager.py
@@ -0,0 +1,227 @@
+from __future__ import annotations
+
+import asyncio
+
+import pytest
+
+from jiuwenswarm.extensions.agentos.agentos_router.agent_manager import (
+ AgentCreatingTimeout,
+ AgentDeleted,
+ AgentManager,
+ normalize_agent_key_fields,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.models import AgentInfo, AgentStatus
+
+
+async def test_get_or_create_agent_is_single_flight() -> None:
+ agent_manager = AgentManager()
+ creator_started = asyncio.Event()
+ allow_creator = asyncio.Event()
+ create_calls = 0
+
+ async def creator(agent: AgentInfo) -> AgentInfo:
+ nonlocal create_calls
+ create_calls += 1
+ creator_started.set()
+ await allow_creator.wait()
+ agent.sandbox_id = "sandbox-1"
+ return agent
+
+ first = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await creator_started.wait()
+ second = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+
+ creating = await agent_manager.list_user_agents("u1")
+ assert len(creating) == 1
+ assert creating[0].info.status is AgentStatus.CREATING
+
+ allow_creator.set()
+ first_agent, second_agent = await asyncio.gather(first, second)
+ assert create_calls == 1
+ assert first_agent.info.agent_id == second_agent.info.agent_id
+ assert first_agent.info.status is AgentStatus.READY
+ assert first_agent.info.sandbox_id == "sandbox-1"
+
+
+async def test_waiting_for_creation_times_out() -> None:
+ agent_manager = AgentManager(creating_timeout_seconds=0.1)
+ creator_started = asyncio.Event()
+ never = asyncio.Event()
+
+ async def creator(agent: AgentInfo) -> AgentInfo:
+ creator_started.set()
+ await never.wait()
+ return agent
+
+ owner = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await creator_started.wait()
+
+ with pytest.raises(AgentCreatingTimeout, match="AGENT_CREATING_TIMEOUT"):
+ await agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+
+ owner.cancel()
+ await asyncio.gather(owner, return_exceptions=True)
+ failed = await agent_manager.list_user_agents("u1")
+ assert failed[0].info.status is AgentStatus.FAILED
+
+
+async def test_agent_manager_get_delete_and_list() -> None:
+ agent_manager = AgentManager()
+ created = await agent_manager.get_or_create_agent("u1", "jiuwenswarm")
+
+ fetched = await agent_manager.get_agent("u1", "jiuwenswarm")
+ assert fetched is not None
+ assert fetched.info == created.info
+ assert [
+ item.info.agent_id for item in await agent_manager.list_user_agents("u1")
+ ] == [created.info.agent_id]
+
+ await agent_manager.delete_agent("u1", "jiuwenswarm")
+ assert await agent_manager.get_agent("u1", "jiuwenswarm") is None
+ assert await agent_manager.list_user_agents("u1") == []
+
+
+async def test_delete_during_creation_wakes_waiter() -> None:
+ agent_manager = AgentManager(creating_timeout_seconds=5.0)
+ creator_started = asyncio.Event()
+ allow_creator = asyncio.Event()
+ create_calls = 0
+
+ async def creator(agent: AgentInfo) -> AgentInfo:
+ nonlocal create_calls
+ create_calls += 1
+ creator_started.set()
+ await allow_creator.wait()
+ agent.sandbox_id = "sandbox-1"
+ return agent
+
+ owner = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await creator_started.wait()
+ waiter = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await asyncio.sleep(0.05)
+
+ await agent_manager.delete_agent("u1", "jiuwenswarm")
+
+ with pytest.raises(AgentDeleted, match="AGENT_DELETED"):
+ await waiter
+
+ allow_creator.set()
+ with pytest.raises(AgentDeleted, match="AGENT_DELETED"):
+ await owner
+
+ assert await agent_manager.get_agent("u1", "jiuwenswarm") is None
+ assert create_calls == 1
+
+
+async def test_get_or_create_after_delete_during_creation_can_retry() -> None:
+ agent_manager = AgentManager()
+ creator_started = asyncio.Event()
+ allow_creator = asyncio.Event()
+ create_calls = 0
+
+ async def creator(agent: AgentInfo) -> AgentInfo:
+ nonlocal create_calls
+ create_calls += 1
+ creator_started.set()
+ await allow_creator.wait()
+ agent.sandbox_id = f"sandbox-{create_calls}"
+ return agent
+
+ owner = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await creator_started.wait()
+ waiter = asyncio.create_task(
+ agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ )
+ await asyncio.sleep(0.05)
+
+ await agent_manager.delete_agent("u1", "jiuwenswarm")
+
+ allow_creator.set()
+ results = await asyncio.gather(waiter, owner, return_exceptions=True)
+ assert all(isinstance(result, AgentDeleted) for result in results)
+
+ recreated = await agent_manager.get_or_create_agent("u1", "jiuwenswarm", creator=creator)
+ assert recreated.info.status is AgentStatus.READY
+ assert recreated.info.sandbox_id == "sandbox-2"
+ assert create_calls == 2
+
+
+def test_normalize_agent_key_fields_defaults_and_aliases() -> None:
+ assert normalize_agent_key_fields(None) == ("user_id", "agent_type")
+ assert normalize_agent_key_fields("user_id+agent_type") == (
+ "user_id",
+ "agent_type",
+ )
+ assert normalize_agent_key_fields(
+ ["user_id", "agent_type", "session_id"]
+ ) == ("user_id", "agent_type", "session_id")
+ with pytest.raises(ValueError, match="unsupported agent_key_field"):
+ normalize_agent_key_fields(["user_id", "channel"])
+ with pytest.raises(ValueError, match="must include user_id and agent_type"):
+ normalize_agent_key_fields(["user_id"])
+
+
+async def test_session_scoped_key_creates_independent_agents() -> None:
+ agent_manager = AgentManager(
+ key_fields=["user_id", "agent_type", "session_id"]
+ )
+ create_calls = 0
+
+ async def creator(agent: AgentInfo) -> AgentInfo:
+ nonlocal create_calls
+ create_calls += 1
+ agent.sandbox_id = f"sandbox-{create_calls}"
+ return agent
+
+ first = await agent_manager.get_or_create_agent(
+ "u1",
+ "jiuwenswarm",
+ key_values={"session_id": "sess-1"},
+ creator=creator,
+ )
+ second = await agent_manager.get_or_create_agent(
+ "u1",
+ "jiuwenswarm",
+ key_values={"session_id": "sess-2"},
+ creator=creator,
+ )
+ reused = await agent_manager.get_or_create_agent(
+ "u1",
+ "jiuwenswarm",
+ key_values={"session_id": "sess-1"},
+ creator=creator,
+ )
+
+ assert create_calls == 2
+ assert first.info.agent_id != second.info.agent_id
+ assert reused.info.agent_id == first.info.agent_id
+ assert first.key == ("u1", "jiuwenswarm", "sess-1")
+ assert second.key == ("u1", "jiuwenswarm", "sess-2")
+
+ await agent_manager.delete_agent(
+ "u1", "jiuwenswarm", key_values={"session_id": "sess-1"}
+ )
+ assert await agent_manager.get_agent(
+ "u1", "jiuwenswarm", key_values={"session_id": "sess-1"}
+ ) is None
+ assert await agent_manager.get_agent(
+ "u1", "jiuwenswarm", key_values={"session_id": "sess-2"}
+ ) is not None
diff --git a/tests/unit_tests/extensions/test_agentos_router.py b/tests/unit_tests/extensions/test_agentos_router.py
new file mode 100644
index 0000000000..1acee44f0e
--- /dev/null
+++ b/tests/unit_tests/extensions/test_agentos_router.py
@@ -0,0 +1,292 @@
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+from typing import Any
+
+import pytest
+
+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 (
+ agentos_router_selected,
+ load_router_config,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.extension import AgentOSRouter
+from jiuwenswarm.extensions.agentos.agentos_router.models import (
+ AgentInfo,
+ AgentStatus,
+ ImageInfo,
+)
+from jiuwenswarm.extensions.agentos.agentos_router.router_client import AgentOSRouterClient
+from jiuwenswarm.extensions.yuanrong_frontend_client import SandboxInfo
+
+
+class FakeYuanRongClient:
+ def __init__(self) -> None:
+ self.server_ready = True
+ self.send_calls = 0
+ self.create_calls = 0
+ self.delete_calls: list[str] = []
+ self.config: dict[str, Any] = {}
+ self.push_handler = None
+
+ async def connect(self, uri: str) -> None:
+ del uri
+ return None
+
+ async def disconnect(self) -> None:
+ return None
+
+ async def create_sandbox(
+ self,
+ *,
+ user_id: str,
+ agent_type: str,
+ agent_id: str | None = None,
+ image_name: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> SandboxInfo:
+ self.create_calls += 1
+ return SandboxInfo(
+ sandbox_id=f"sbx-{self.create_calls}",
+ user_id=user_id,
+ agent_type=agent_type,
+ metadata={
+ **dict(metadata or {}),
+ "agent_id": agent_id,
+ "image_name": image_name,
+ },
+ )
+
+ async def delete_sandbox(
+ self,
+ sandbox_id: str,
+ *,
+ user_id: str | None = None,
+ agent_type: str | None = None,
+ ) -> None:
+ del user_id, agent_type
+ self.delete_calls.append(sandbox_id)
+
+ async def send_request(self, envelope: E2AEnvelope) -> AgentResponse:
+ self.send_calls += 1
+ return AgentResponse(
+ request_id=str(envelope.request_id or ""),
+ channel_id=str(envelope.channel or ""),
+ )
+
+ async def send_request_stream(
+ self, envelope: E2AEnvelope
+ ) -> AsyncIterator[AgentResponseChunk]:
+ self.send_calls += 1
+ yield AgentResponseChunk(
+ request_id=str(envelope.request_id or ""),
+ channel_id=str(envelope.channel or ""),
+ is_complete=True,
+ )
+
+ def set_or_update_server_config(
+ self,
+ *,
+ config: dict[str, Any],
+ env: dict[str, str] | None = None,
+ ) -> None:
+ del env
+ self.config = config
+
+ def set_server_push_handler(self, handler) -> None:
+ self.push_handler = handler
+
+
+class FakeRegistryClient:
+ def __init__(self) -> None:
+ self.registered: list[AgentInfo] = []
+ self.image_lookups = 0
+
+ async def get_image_info(self, image_name: str) -> ImageInfo:
+ self.image_lookups += 1
+ return ImageInfo(image_name=image_name)
+
+ async def register_agent(self, agent_info: AgentInfo) -> None:
+ self.registered.append(agent_info)
+
+ async def close(self) -> None:
+ return None
+
+
+def _envelope(*, agent_type: str | None = None) -> E2AEnvelope:
+ params = {"query": "hello"}
+ if agent_type is not None:
+ params["agent_type"] = agent_type
+ return E2AEnvelope(
+ request_id="req-1",
+ channel="web",
+ user_id="u1",
+ session_id="sess-1",
+ params=params,
+ )
+
+
+async def test_swarm_request_creates_mapping_then_forwards() -> None:
+ yuanrong = FakeYuanRongClient()
+ registry = FakeRegistryClient()
+ agent_manager = AgentManager()
+ client = AgentOSRouterClient(yuanrong, registry, agent_manager)
+ envelope = _envelope()
+
+ response = await client.send_request(envelope)
+ await client.shutdown()
+
+ assert response.ok
+ assert registry.image_lookups == 1
+ assert yuanrong.create_calls == 1
+ assert yuanrong.send_calls == 1
+ agents = await agent_manager.list_user_agents("u1")
+ assert len(agents) == 1
+ assert agents[0].info.status is AgentStatus.READY
+ assert agents[0].info.sandbox_id == "sbx-1"
+ assert envelope.channel_context["agent_id"] == agents[0].info.agent_id
+ assert envelope.channel_context["agent_type"] == "jiuwenswarm"
+ assert envelope.channel_context["sandbox_id"] == "sbx-1"
+ assert [item.agent_id for item in registry.registered] == [agents[0].info.agent_id]
+
+
+async def test_existing_swarm_agent_is_reused() -> None:
+ yuanrong = FakeYuanRongClient()
+ registry = FakeRegistryClient()
+ client = AgentOSRouterClient(yuanrong, registry, AgentManager())
+
+ await client.send_request(_envelope())
+ await client.send_request(_envelope())
+ await client.shutdown()
+
+ assert registry.image_lookups == 1
+ assert yuanrong.create_calls == 1
+ assert yuanrong.send_calls == 2
+
+
+async def test_third_party_type_creates_via_yuanrong() -> None:
+ yuanrong = FakeYuanRongClient()
+ agent_manager = AgentManager()
+ client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+
+ response = await client.send_request(_envelope(agent_type="opencode"))
+
+ assert response.ok
+ assert yuanrong.create_calls == 1
+ assert yuanrong.send_calls == 1
+ agents = await agent_manager.list_user_agents("u1")
+ assert agents[0].info.agent_type == "opencode"
+ assert agents[0].info.status is AgentStatus.READY
+ assert agents[0].info.sandbox_id == "sbx-1"
+
+
+async def test_delete_agent_releases_yuanrong_sandbox() -> None:
+ yuanrong = FakeYuanRongClient()
+ agent_manager = AgentManager()
+ client = AgentOSRouterClient(yuanrong, FakeRegistryClient(), agent_manager)
+
+ await client.send_request(_envelope())
+ agents = await agent_manager.list_user_agents("u1")
+ assert agents[0].info.sandbox_id == "sbx-1"
+
+ await client.delete_agent("u1", "jiuwenswarm")
+
+ assert yuanrong.delete_calls == ["sbx-1"]
+ assert await agent_manager.list_user_agents("u1") == []
+
+
+def test_agentos_selected_by_agent_client_type() -> None:
+ assert agentos_router_selected(
+ {
+ "gateway": {
+ "agent_client": {"type": "agentos_router"},
+ }
+ }
+ )
+ assert not agentos_router_selected(
+ {
+ "gateway": {
+ "agent_client": {"type": "websocket"},
+ }
+ }
+ )
+ assert not agentos_router_selected(
+ {
+ "gateway": {
+ "agent_client": {"type": "yuanrong"},
+ }
+ }
+ )
+
+
+def test_load_router_config_agent_key_fields() -> None:
+ config = {
+ "gateway": {
+ "agent_client": {
+ "type": "agentos_router",
+ "frontend_endpoint": "http://yuanrong.test",
+ "function_version_urn": "urn:test",
+ },
+ "agentos": {
+ "agent_key_fields": ["user_id", "agent_type", "session_id"],
+ },
+ }
+ }
+ loaded = load_router_config(config)
+ assert loaded.agent_key_fields == ("user_id", "agent_type", "session_id")
+
+ default_loaded = load_router_config(
+ {
+ "gateway": {
+ "agent_client": {
+ "frontend_endpoint": "http://yuanrong.test",
+ "function_version_urn": "urn:test",
+ }
+ }
+ }
+ )
+ assert default_loaded.agent_key_fields == ("user_id", "agent_type")
+
+
+async def test_agentos_extension_is_selected_independently(
+ monkeypatch,
+) -> None:
+ from jiuwenswarm.extensions.agent_client import extension as plain_extension
+ from jiuwenswarm.extensions.agentos import extension as agentos_extension
+ from jiuwenswarm.extensions.agentos.agentos_router import (
+ extension as agentos_router_impl,
+ )
+
+ config = {
+ "gateway": {
+ "agent_client": {
+ "type": "agentos_router",
+ "frontend_endpoint": "http://yuanrong.test",
+ "function_version_urn": "urn:test",
+ },
+ }
+ }
+ monkeypatch.setattr(agentos_router_impl, "get_config", lambda: config)
+ monkeypatch.setattr(plain_extension, "get_config", lambda: config)
+
+ class Registry:
+ registered = None
+
+ def register_agent_server_client(self, extension) -> None:
+ self.registered = extension
+
+ registry = Registry()
+ assert await plain_extension.register_extensions(registry) == []
+ registered = await agentos_extension.register_extensions(registry)
+
+ assert len(registered) == 1
+ assert isinstance(registered[0], AgentOSRouter)
+ assert registry.registered is registered[0]
+ await registered[0].shutdown()
diff --git a/tests/unit_tests/extensions/test_yuanrong_frontend_client.py b/tests/unit_tests/extensions/test_yuanrong_frontend_client.py
index 096dadd8f9..a45e9c4574 100644
--- a/tests/unit_tests/extensions/test_yuanrong_frontend_client.py
+++ b/tests/unit_tests/extensions/test_yuanrong_frontend_client.py
@@ -115,3 +115,33 @@ async def test_send_request_omits_session_context_without_user_id(client: Yuanro
await client.send_request(envelope)
assert "X-session-context" not in {k.lower() for k in captured}
+
+
+async def test_create_and_delete_sandbox_placeholders(client: YuanrongFrontendAgentClientProbe):
+ await client.connect("http://127.0.0.1:8080")
+
+ sandbox = await client.create_sandbox(
+ user_id="alice",
+ agent_type="swarm",
+ agent_id="agent-1",
+ image_name="jiuwenswarm:latest",
+ )
+
+ assert sandbox.sandbox_id.startswith("sbx_")
+ assert sandbox.user_id == "alice"
+ assert sandbox.agent_type == "swarm"
+ assert sandbox.status == "ready"
+ assert sandbox.metadata["provisioning"] == "yuanrong_create_sandbox_stub"
+
+ await client.delete_sandbox(
+ sandbox.sandbox_id,
+ user_id="alice",
+ agent_type="3rd",
+ )
+
+
+async def test_create_sandbox_requires_connection(client: YuanrongFrontendAgentClientProbe):
+ with pytest.raises(RuntimeError, match="client not connected"):
+ await client.create_sandbox(user_id="alice", agent_type="swarm")