Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(workspace): add K8sWorkspace with Pod/PVC lifecycle, tar-stream backend and MCP gateway support (#1933)
XiuShenAl81538d356803
diff --git a/.github/workflows/k8s-workspace.yml b/.github/workflows/k8s-workspace.ymlnew file mode 100644index 000000000..ec091a585--- /dev/null+++ b/.github/workflows/k8s-workspace.yml@@ -0,0 +1,81 @@+name: K8s Workspace Integration Tests++# Runs the K8sWorkspace integration suite against a kind cluster.+# The regular `unittest.yml` job also imports this test file, but every+# test inside is guarded by `skipUnless(_KIND_AVAILABLE, ...)`, so it is+# a no-op there. This workflow is where the tests actually execute.++on:+ push:+ paths:+ - "src/agentscope/workspace/**"+ - "tests/workspace_k8s_test.py"+ - "tests/docker/k8s_workspace_test.Dockerfile"+ - ".github/workflows/k8s-workspace.yml"+ pull_request:+ paths:+ - "src/agentscope/workspace/**"+ - "tests/workspace_k8s_test.py"+ - "tests/docker/k8s_workspace_test.Dockerfile"+ - ".github/workflows/k8s-workspace.yml"++jobs:+ k8s-workspace-tests:+ if: false == contains(github.event.pull_request.title, 'WIP')+ # Ubuntu only: kind requires linux + docker; the test module's+ # skipUnless would skip everything on Windows/macOS anyway.+ runs-on: ubuntu-latest+ timeout-minutes: 25+ steps:+ - uses: actions/checkout@v4++ - name: Install uv+ uses: astral-sh/setup-uv@v5+ with:+ python-version: '3.11'++ - name: Create kind cluster+ uses: helm/kind-action@v1+ with:+ cluster_name: agentscope-test+ wait: 120s++ - name: Build K8s workspace test image+ run: |+ docker build \+ -f tests/docker/k8s_workspace_test.Dockerfile \+ -t agentscope-k8s-test:ci .++ - name: Load image into kind+ run: kind load docker-image agentscope-k8s-test:ci --name agentscope-test++ - name: Create test namespace+ run: kubectl create namespace agentscope++ - name: Install project+ run: |+ uv pip install -q -e .[dev]+ uv pip install pytest++ - name: Run K8s workspace tests+ env:+ K8S_TEST_IMAGE: agentscope-k8s-test:ci+ K8S_TEST_NAMESPACE: agentscope+ run: pytest tests/workspace_k8s_test.py -v++ - name: Dump cluster diagnostics on failure+ if: failure()+ run: |+ echo "── pods ──"+ kubectl get pods -A -o wide || true+ echo "── pvcs ──"+ kubectl get pvc -A || true+ echo "── events ──"+ kubectl get events -A --sort-by=.lastTimestamp | tail -n 50 || true+ echo "── describe agentscope pods ──"+ for p in $(kubectl -n agentscope get pods -o name 2>/dev/null); do+ echo "── $p ──"+ kubectl -n agentscope describe "$p" || true+ kubectl -n agentscope logs "$p" --all-containers=true --tail=200 || true+ done+diff --git a/docs/NEWS.md b/docs/NEWS.mdindex 6742ba63c..27c3ff582 100644--- a/docs/NEWS.md+++ b/docs/NEWS.md@@ -2,6 +2,7 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-07] `INTE`:** K8s-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)- **[2026-07] `INTE`:** ReMe long-term memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)- **[2026-06] `FEAT`:** Agentic Memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.mdindex d8a1326e6..ed4050587 100644--- a/docs/NEWS_zh.md+++ b/docs/NEWS_zh.md@@ -2,6 +2,7 @@<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. --><!-- To update news in READMEs, modify this file and push to trigger the workflow. -->+- **[2026-07] `集成`:** 集成 K8s 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)- **[2026-07] `集成`:** 集成 ReMe 长期记忆。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)- **[2026-06] `功能`:** 支持 Agentic Memory。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)diff --git a/pyproject.toml b/pyproject.tomlindex fc6a72391..81158f37b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -68,9 +68,11 @@ storage = ["redis",]# ------------ Workspace -----------+k8s = ["kubernetes-asyncio"]workspace = ["aiodocker","e2b",+ "agentscope[k8s]",]# ------------ Tools ------------tools = [diff --git a/src/agentscope/app/_router/_schema/_session.py b/src/agentscope/app/_router/_schema/_session.pyindex e9832102d..5a84f72e5 100644--- a/src/agentscope/app/_router/_schema/_session.py+++ b/src/agentscope/app/_router/_schema/_session.py@@ -60,7 +60,14 @@ class CreateSessionRequest(BaseModel):agent_id: str = Field(description="Agent this session belongs to.")workspace_id: str | None = Field(default=None,- description="Workspace this session belongs to.",+ description=(+ "Optional explicit workspace binding. When omitted the "+ "server calls "+ "``WorkspaceManagerBase.assign_workspace_id`` under the "+ "configured isolation policy. Set only to force a "+ "specific binding (e.g. share workspace with another "+ "existing session)."+ ),)name: str | None = Field(default=None,diff --git a/src/agentscope/app/_router/_session.py b/src/agentscope/app/_router/_session.pyindex ef5e0dbdc..54c678950 100644--- a/src/agentscope/app/_router/_session.py+++ b/src/agentscope/app/_router/_session.py@@ -14,6 +14,7 @@ from ..deps import (get_message_bus,get_session_service,get_storage,+ get_workspace_manager,)from ._schema import (CreateSessionRequest,@@ -47,6 +48,7 @@ from ..storage import (from ...message import ToolCallStatefrom ..storage._utils import _ensure_team_membersfrom ...event import CustomEvent+from ..workspace_manager import WorkspaceManagerBaseasync def _build_team_detail(@@ -247,6 +249,7 @@ async def create_session(body: CreateSessionRequest,user_id: str = Depends(get_current_user_id),storage: StorageBase = Depends(get_storage),+ workspace_manager: WorkspaceManagerBase = Depends(get_workspace_manager),) -> CreateSessionResponse:"""Create (or resume) a session for a given agent and workspace.@@ -258,6 +261,10 @@ async def create_session(body (`CreateSessionRequest`): Agent, workspace, and model config.user_id (`str`): Injected authenticated user ID.storage (`StorageBase`): Injected storage backend.+ workspace_manager (`WorkspaceManagerBase`): Injected workspace+ manager; consulted via+ :meth:`WorkspaceManagerBase.assign_workspace_id` to fill in+ ``workspace_id`` when the request body omits it.Returns:`CreateSessionResponse`: The session identifier.@@ -286,11 +293,23 @@ async def create_session(body.knowledge_config,)+ # Resolve the workspace binding for this session. Explicit+ # ``body.workspace_id`` always wins (used by team invite / borrow+ # flows to force sharing); otherwise defer to the manager's+ # isolation policy — see ``WorkspaceManagerBase.assign_workspace_id``.+ resolved_workspace_id = body.workspace_id or (+ workspace_manager.assign_workspace_id(+ user_id=user_id,+ agent_id=body.agent_id,+ session_id=_generate_id(),+ )+ )+session_record = await storage.upsert_session(user_id=user_id,agent_id=body.agent_id,config=SessionConfig(- workspace_id=body.workspace_id or _generate_id(),+ workspace_id=resolved_workspace_id,chat_model_config=body.chat_model_config,fallback_chat_model_config=body.fallback_chat_model_config,tts_model_config=body.tts_model_config,diff --git a/src/agentscope/app/_service/_chat.py b/src/agentscope/app/_service/_chat.pyindex 6ef52cefc..da5e97587 100644--- a/src/agentscope/app/_service/_chat.py+++ b/src/agentscope/app/_service/_chat.py@@ -421,6 +421,7 @@ class ChatService:toolkit = await get_toolkit(storage=self._storage,workspace=workspace,+ workspace_manager=self._workspace_manager,scheduler_manager=self._scheduler_manager,background_task_manager=self._background_task_manager,message_bus=self._message_bus,diff --git a/src/agentscope/app/_service/_toolkit.py b/src/agentscope/app/_service/_toolkit.pyindex a518be9e4..a614dc1be 100644--- a/src/agentscope/app/_service/_toolkit.py+++ b/src/agentscope/app/_service/_toolkit.py@@ -19,6 +19,7 @@ from .._tool import ()from .._types import AgentToolFactory, SubAgentTemplatefrom ..storage import AgentRecord, SessionRecord, StorageBase+from ..workspace_manager import WorkspaceManagerBasefrom ...middleware import MiddlewareBasefrom ...tool import (TaskCreate,@@ -35,6 +36,7 @@ async def get_toolkit(*,storage: StorageBase,workspace: WorkspaceBase,+ workspace_manager: WorkspaceManagerBase,scheduler_manager: SchedulerManager,background_task_manager: BackgroundTaskManager,message_bus: MessageBus,@@ -173,6 +175,7 @@ time or interval"team_tool_kwargs: dict[str, Any] = {"storage": storage,"message_bus": message_bus,+ "workspace_manager": workspace_manager,"user_id": user_id,"session_id": session_record.id,"agent_id": agent_record.id,diff --git a/src/agentscope/app/_tool/_agent_create.py b/src/agentscope/app/_tool/_agent_create.pyindex 144416b1b..1973e0c0a 100644--- a/src/agentscope/app/_tool/_agent_create.py+++ b/src/agentscope/app/_tool/_agent_create.py@@ -22,6 +22,7 @@ from ...tool import ToolChunk, ParamsBaseif TYPE_CHECKING:from ..message_bus import MessageBusfrom ..storage import StorageBase+ from ..workspace_manager import WorkspaceManagerBase_DEFAULT_SYSTEM_PROMPT_TEMPLATE = (@@ -178,6 +179,7 @@ overall communication topology unnecessarily complex.self,storage: "StorageBase",message_bus: "MessageBus",+ workspace_manager: "WorkspaceManagerBase",user_id: str,session_id: str,agent_id: str,@@ -185,34 +187,37 @@ overall communication topology unnecessarily complex.) -> None:"""Bind request-scoped identifiers plus sub-agent templates.- Extends :meth:`_TeamToolBase.__init__` with an optional+ Extends :meth:`_TeamToolBase.__init__` with the optionaltemplate registry. The built-in ``"default"`` template is- always present as a fallback; developers can override it by- registering their own template with ``type="default"``.-- When more than one template type is available (i.e. custom- templates were registered), the tool's ``input_schema`` is- dynamically extended with a ``subagent_type`` enum field so- the leader agent can choose which type to create.+ always injected; extra templates unlock a ``subagent_type``+ enum in the tool's input schema.Args:storage (`StorageBase`):Application storage backend.message_bus (`MessageBus`):- Application message bus for inter-session delivery.+ Application message bus.+ workspace_manager (`WorkspaceManagerBase`):+ Workspace manager (forwarded to base for uniform+ team-tool wiring; currently unused here).user_id (`str`):- The owner user id of the calling agent.+ The owner user id.session_id (`str`):- The current session id of the calling agent.+ The calling session id.agent_id (`str`):- The id of the agent invoking the tool.+ The calling agent id.sub_agent_templates (`dict[str, SubAgentTemplate] | None`, \optional):- Template registry keyed by template type. The- built-in ``"default"`` template is injected- automatically if not already present.+ Template registry keyed by type."""- super().__init__(storage, message_bus, user_id, session_id, agent_id)+ super().__init__(+ storage,+ message_bus,+ workspace_manager,+ user_id,+ session_id,+ agent_id,+ )self._sub_agent_templates: dict[str, SubAgentTemplate] = dict(sub_agent_templates or {},diff --git a/src/agentscope/app/_tool/_agent_invite.py b/src/agentscope/app/_tool/_agent_invite.pyindex bdb6d4267..1116a05ec 100644--- a/src/agentscope/app/_tool/_agent_invite.py+++ b/src/agentscope/app/_tool/_agent_invite.py@@ -36,6 +36,7 @@ from ..._utils._common import _generate_idif TYPE_CHECKING:from ..message_bus import MessageBusfrom ..storage import AgentRecord, StorageBase+ from ..workspace_manager import WorkspaceManagerBasedef _display_handle(agent_id: str) -> str:@@ -163,6 +164,7 @@ class AgentInvite(_TeamToolBase):self,storage: "StorageBase",message_bus: "MessageBus",+ workspace_manager: "WorkspaceManagerBase",user_id: str,session_id: str,agent_id: str,@@ -174,20 +176,28 @@ class AgentInvite(_TeamToolBase):storage (`StorageBase`):Application storage backend.message_bus (`MessageBus`):- Application message bus for inter-session delivery.+ Application message bus.+ workspace_manager (`WorkspaceManagerBase`):+ Used to mint the workspace id for freshly-invited+ agents (see :meth:`__call__`).user_id (`str`):- The owner user id of the calling agent.+ The owner user id.session_id (`str`):- The current session id of the calling agent.+ The calling session id.agent_id (`str`):- The id of the agent invoking the tool.+ The calling agent id.invitable_pool (`list[AgentRecord]`):- Snapshot of the user's currently-invitable agents,- resolved at toolkit assembly time. Non-empty — the- caller is responsible for skipping construction when- there is nothing to invite.+ Snapshot of currently-invitable agents. Must be+ non-empty — the caller skips construction otherwise."""- super().__init__(storage, message_bus, user_id, session_id, agent_id)+ super().__init__(+ storage,+ message_bus,+ workspace_manager,+ user_id,+ session_id,+ agent_id,+ )self._pool_by_id: dict[str, "AgentRecord"] = {a.id: a for a in invitable_pool@@ -359,7 +369,13 @@ class AgentInvite(_TeamToolBase):or leader_session.config.fallback_chat_model_config)else:- borrowed_workspace_id = _generate_id()+ borrowed_workspace_id = (+ self._workspace_manager.assign_workspace_id(+ user_id=self._user_id,+ agent_id=invited.id,+ session_id=_generate_id(),+ )+ )borrowed_chat_model = leader_session.config.chat_model_configborrowed_fallback_model = (leader_session.config.fallback_chat_model_configdiff --git a/src/agentscope/app/_tool/_team_tool_base.py b/src/agentscope/app/_tool/_team_tool_base.pyindex 734e74e5f..04100bc04 100644--- a/src/agentscope/app/_tool/_team_tool_base.py+++ b/src/agentscope/app/_tool/_team_tool_base.py@@ -12,6 +12,7 @@ from ...tool import ToolBaseif TYPE_CHECKING:from ..message_bus import MessageBusfrom ..storage import StorageBase+ from ..workspace_manager import WorkspaceManagerBaseclass _TeamToolBase(ToolBase):@@ -20,8 +21,9 @@ class _TeamToolBase(ToolBase):All team tools are constructed at agent assembly time (in:func:`get_toolkit`) with the request-scoped ``user_id``,``session_id``, and ``agent_id`` plus ``storage`` + ``message_bus``- references. Each tool's ``__call__`` does its work directly via- those two dependencies — there is no intermediate service layer.+ + ``workspace_manager`` references. Each tool's ``__call__`` does+ its work directly via those dependencies — there is no intermediate+ service layer.Permissions: all team tools allow themselves unconditionally — theagent's authority to call them is already gated by the@@ -43,6 +45,7 @@ class _TeamToolBase(ToolBase):self,storage: "StorageBase",message_bus: "MessageBus",+ workspace_manager: "WorkspaceManagerBase",user_id: str,session_id: str,agent_id: str,@@ -51,17 +54,13 @@ class _TeamToolBase(ToolBase):Args:storage (`StorageBase`):- Application storage. Each tool reads the current- session / team records at ``__call__`` time to do- runtime precondition checks (am I in a team? am I the- leader?) — this is what lets all four team tools be- attached unconditionally to ``source='user'`` agents- without depending on a stale snapshot of ``team_id``- taken at agent assembly time.+ Application storage.message_bus (`MessageBus`):- Application message bus. Tools that deliver- inter-session messages (``AgentCreate``, ``TeamSay``)- push HintBlocks + wakeups through it.+ Application message bus for inter-session delivery.+ workspace_manager (`WorkspaceManagerBase`):+ Workspace manager, consulted by tools that provision+ brand-new sessions (e.g. ``AgentInvite``) to honour+ the deployment's isolation policy.user_id (`str`):The owner user id of the calling agent.session_id (`str`):@@ -71,6 +70,7 @@ class _TeamToolBase(ToolBase):"""self._storage = storageself._message_bus = message_bus+ self._workspace_manager = workspace_managerself._user_id = user_idself._session_id = session_idself._agent_id = agent_iddiff --git a/src/agentscope/app/storage/_model/_session.py b/src/agentscope/app/storage/_model/_session.pyindex bf83b9991..af30db18d 100644--- a/src/agentscope/app/storage/_model/_session.py+++ b/src/agentscope/app/storage/_model/_session.py@@ -114,7 +114,15 @@ class SessionConfig(BaseModel):"""Session configuration — set at creation, updatable via PATCH."""workspace_id: str- """The workspace id this session is bound to."""+ """Authoritative workspace binding for the session.++ Populated at session creation — either from an explicit+ ``workspace_id`` on ``CreateSessionRequest`` (used by team+ invite/borrow flows) or from+ :meth:`WorkspaceManagerBase.assign_workspace_id` under the+ manager's isolation policy. Consumed verbatim by chat,+ ``list_mcps``, and team tools; also the cache key for+ :meth:`WorkspaceManagerBase.get_workspace`."""name: str = Field(default_factory=lambda: datetime.now().strftime("%Y-%m-%d %H:%M:%S"),diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.pyindex d60a97472..f46430059 100644--- a/src/agentscope/app/workspace_manager/__init__.py+++ b/src/agentscope/app/workspace_manager/__init__.py@@ -2,14 +2,17 @@"""The workspace manager classes, responsible for managing the resourcesand their lifecycles, and filesystem isolation."""-from ._base import WorkspaceManagerBase+from ._base import IsolationPolicy, WorkspaceManagerBasefrom ._local_workspace_manager import LocalWorkspaceManagerfrom ._docker_workspace_manager import DockerWorkspaceManagerfrom ._e2b_workspace_manager import E2BWorkspaceManager+from ._k8s_workspace_manager import K8sWorkspaceManager__all__ = [+ "IsolationPolicy","WorkspaceManagerBase","LocalWorkspaceManager","DockerWorkspaceManager","E2BWorkspaceManager",+ "K8sWorkspaceManager",]diff --git a/src/agentscope/app/workspace_manager/_base.py b/src/agentscope/app/workspace_manager/_base.pyindex dc6a933b5..2a6ba1eef 100644--- a/src/agentscope/app/workspace_manager/_base.py+++ b/src/agentscope/app/workspace_manager/_base.py@@ -1,12 +1,25 @@# -*- coding: utf-8 -*-"""Workspace manager implementations."""+import hashlibfrom abc import ABC, abstractmethod+from enum import StrEnumfrom typing import Self+from ..._utils._common import _generate_idfrom ...workspace import WorkspaceBase+class IsolationPolicy(StrEnum):+ """Workspace isolation grain for+ :meth:`WorkspaceManagerBase.assign_workspace_id`.+ """++ PER_SESSION = "per_session"+ PER_AGENT = "per_agent"+ PER_USER = "per_user"++class WorkspaceManagerBase(ABC):"""Abstract base for workspace managers.@@ -21,35 +34,87 @@ class WorkspaceManagerBase(ABC):both."""- @abstractmethod- async def get_workspace(+ def __init__(+ self,+ *,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,+ ) -> None:+ """Bind the isolation policy for :meth:`assign_workspace_id`.++ Subclasses MUST forward ``isolation`` here via+ ``super().__init__(isolation=isolation)``.++ Args:+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for the manager.+ """+ self._isolation: IsolationPolicy = isolation++ def assign_workspace_id(self,+ *,user_id: str,agent_id: str,session_id: str,- workspace_id: str,- ) -> WorkspaceBase:- """Return an initialized workspace.+ ) -> str:+ """Mint a workspace id under :attr:`_isolation`.++ Pure function — no I/O, no storage access. Called by the+ session-creation flow when the caller did not supply an+ explicit ``workspace_id``.++ * ``PER_SESSION`` → fresh UUID.+ * ``PER_AGENT`` → deterministic BLAKE2b of ``user::agent``.+ * ``PER_USER`` → deterministic BLAKE2b of ``user::``.Args:user_id (`str`):- The user id.+ The owning user id.agent_id (`str`):- The agent id.+ The agent the session belongs to.session_id (`str`):- The session id.- workspace_id (`str`):- The workspace id (reconnection credential).+ The session id being provisioned (only used by the+ per-session grain to underline its randomness).++ Returns:+ `str`:+ A workspace id."""+ del session_id+ if self._isolation is IsolationPolicy.PER_AGENT:+ return hashlib.blake2b(+ f"{user_id}::{agent_id}".encode("utf-8"),+ digest_size=8,+ ).hexdigest()+ if self._isolation is IsolationPolicy.PER_USER:+ return hashlib.blake2b(+ f"user::{user_id}".encode("utf-8"),+ digest_size=8,+ ).hexdigest()+ return _generate_id()@abstractmethod- async def create_workspace(+ async def get_workspace(self,user_id: str,agent_id: str,session_id: str,+ workspace_id: str | None = None,) -> WorkspaceBase:- """Create a new workspace and return it."""+ """Return an initialized workspace.++ Args:+ user_id (`str`):+ The user id.+ agent_id (`str`):+ The agent id.+ session_id (`str`):+ The session id.+ workspace_id (`str | None`, optional):+ Explicit workspace binding. ``None`` triggers+ :meth:`assign_workspace_id` fallback — expected only+ for callers without a persisted binding.+ """@abstractmethodasync def close(self, workspace_id: str) -> None:diff --git a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py b/src/agentscope/app/workspace_manager/_docker_workspace_manager.pyindex 63ac56301..ca7e144d3 100644--- a/src/agentscope/app/workspace_manager/_docker_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_docker_workspace_manager.py@@ -30,14 +30,16 @@ import osimport timefrom typing import Self-from agentscope._logging import logger-from agentscope.mcp import MCPClient-from agentscope.workspace._docker import DockerWorkspace-from agentscope.workspace._docker._make_dockerfile import (+from typing_extensions import deprecated++from ..._logging import logger+from ...mcp import MCPClient+from ...workspace import DockerWorkspace+from ...workspace._docker._make_dockerfile import (DEFAULT_BASE_IMAGE,DEFAULT_GATEWAY_PORT,)-from ._base import WorkspaceManagerBase+from ._base import WorkspaceManagerBase, IsolationPolicyDEFAULT_SWEEP_INTERVAL = 300.0@@ -59,6 +61,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):self,basedir: str,*,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,base_image: str = DEFAULT_BASE_IMAGE,node_version: str = "20",extra_pip: list[str] | None = None,@@ -77,6 +80,13 @@ class DockerWorkspaceManager(WorkspaceManagerBase):created (``<basedir>/<user_id>/<agent_id>``). Eachworkdir is bind-mounted to ``/workspace`` inside itscontainer.+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for :meth:`assign_workspace_id`.+ ``PER_SESSION`` → fresh UUID (one workspace per+ session); ``PER_AGENT`` / ``PER_USER`` → deterministic+ hash so sessions of the same (user, agent) or same+ user share a workspace. Explicit ``workspace_id`` on+ session creation always wins over this policy.base_image (`str`, defaults to `DEFAULT_BASE_IMAGE`):Base Docker image; must provide ``python3``.node_version (`str`, defaults to `"20"`):@@ -112,6 +122,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):self._env = dict(env or {})self._default_mcps = list(default_mcps or [])self._skill_paths = list(skill_paths or [])+ super().__init__(isolation=isolation)self._ttl = ttlself._sweep_interval = sweep_interval@@ -169,7 +180,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):user_id: str,agent_id: str,session_id: str,- workspace_id: str,+ workspace_id: str | None = None,) -> DockerWorkspace:"""Return an initialised workspace, building one on cache miss.@@ -190,9 +201,12 @@ class DockerWorkspaceManager(WorkspaceManagerBase):Session identifier (unused for isolation; sessionsshare a workdir and partition under``sessions/<session_id>/``).- workspace_id (`str`):+ workspace_id (`str | None`, optional):Stable workspace identifier — used both as the cache- key and the container name suffix.+ key and the container name suffix. When ``None`` the+ manager falls back to :meth:`assign_workspace_id`;+ the session flow should pre-resolve this so container+ names stay stable across restarts.Returns:`DockerWorkspace`:@@ -200,6 +214,13 @@ class DockerWorkspaceManager(WorkspaceManagerBase):"""del session_id # accepted for interface parity; not used here+ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id=user_id,+ agent_id=agent_id,+ session_id="",+ )+async with self._lock:cached = self._cache.get(workspace_id)if cached is not None:@@ -225,6 +246,11 @@ class DockerWorkspaceManager(WorkspaceManagerBase):self._cache[workspace_id] = (ws, time.monotonic())return ws+ @deprecated(+ "DockerWorkspaceManager.create_workspace is deprecated; "+ "use get_workspace(workspace_id=None) instead.",+ category=None,+ )async def create_workspace(self,user_id: str,@@ -233,10 +259,10 @@ class DockerWorkspaceManager(WorkspaceManagerBase):) -> DockerWorkspace:"""Build a brand-new workspace and track it.- A fresh ``workspace_id`` is allocated by- :class:`DockerWorkspace` itself; the caller should persist- ``workspace.workspace_id`` for later :meth:`get_workspace`- calls.+ .. deprecated::+ Use :meth:`get_workspace` with ``workspace_id=None`` — it+ falls back to :meth:`assign_workspace_id` under the+ manager's isolation policy and reuses the cache path.Args:user_id (`str`):@@ -256,7 +282,7 @@ class DockerWorkspaceManager(WorkspaceManagerBase):workdir = self._workdir_for(user_id, agent_id)os.makedirs(workdir, exist_ok=True)ws = DockerWorkspace(- workdir=workdir,+ host_workdir=workdir,base_image=self._base_image,node_version=self._node_version,extra_pip=self._extra_pip,diff --git a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.pyindex ca0b9778e..0c641c365 100644--- a/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_e2b_workspace_manager.py@@ -36,15 +36,17 @@ import asyncioimport timefrom typing import Self-from agentscope._logging import logger-from agentscope.mcp import MCPClient-from agentscope.workspace import E2BWorkspace-from agentscope.workspace._e2b._bootstrap import (+from typing_extensions import deprecated++from ..._logging import logger+from ...mcp import MCPClient+from ...workspace import E2BWorkspace+from ...workspace._e2b._constants import (DEFAULT_GATEWAY_PORT,DEFAULT_TEMPLATE,DEFAULT_TIMEOUT,)-from ._base import WorkspaceManagerBase+from ._base import WorkspaceManagerBase, IsolationPolicyDEFAULT_SWEEP_INTERVAL = 300.0@@ -60,6 +62,7 @@ class E2BWorkspaceManager(WorkspaceManagerBase):def __init__(self,*,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,template: str = DEFAULT_TEMPLATE,api_key: str = "",domain: str = "",@@ -76,6 +79,9 @@ class E2BWorkspaceManager(WorkspaceManagerBase):"""Initialize the E2B workspace manager.Args:+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for :meth:`assign_workspace_id`. See+ :class:`DockerWorkspaceManager` for semantics.template (`str`, defaults to `DEFAULT_TEMPLATE`):E2B template id passed to every workspace thismanager produces. Defaults to ``"base"``.@@ -125,6 +131,7 @@ class E2BWorkspaceManager(WorkspaceManagerBase):self._skill_paths = list(skill_paths or [])self._ttl = ttlself._sweep_interval = sweep_interval+ super().__init__(isolation=isolation)# workspace_id → (workspace, last_access_monotonic)self._cache: dict[str, tuple[E2BWorkspace, float]] = {}@@ -189,7 +196,7 @@ class E2BWorkspaceManager(WorkspaceManagerBase):user_id: str,agent_id: str,session_id: str,- workspace_id: str,+ workspace_id: str | None = None,) -> E2BWorkspace:"""Return an initialised workspace, reattaching on cache miss.@@ -213,10 +220,12 @@ class E2BWorkspaceManager(WorkspaceManagerBase):Session identifier (unused; sandboxes areper-workspace, sessions partition under``sessions/<session_id>/``).- workspace_id (`str`):+ workspace_id (`str | None`, optional):Stable workspace identifier — the cache key and thevalue stored in the sandbox's- ``agentscope.workspace.id`` metadata.+ ``agentscope.workspace.id`` metadata. When ``None``+ the manager falls back to+ :meth:`assign_workspace_id`.Returns:`E2BWorkspace`:@@ -224,6 +233,13 @@ class E2BWorkspaceManager(WorkspaceManagerBase):"""del session_id # accepted for interface parity; not used here+ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id=user_id,+ agent_id=agent_id,+ session_id="",+ )+async with self._lock:cached = self._cache.get(workspace_id)if cached is not None:@@ -249,6 +265,11 @@ class E2BWorkspaceManager(WorkspaceManagerBase):self._cache[workspace_id] = (ws, time.monotonic())return ws+ @deprecated(+ "E2BWorkspaceManager.create_workspace is deprecated; "+ "use get_workspace(workspace_id=None) instead.",+ category=None,+ )async def create_workspace(self,user_id: str,@@ -257,10 +278,10 @@ class E2BWorkspaceManager(WorkspaceManagerBase):) -> E2BWorkspace:"""Build a brand-new workspace and track it.- A fresh ``workspace_id`` is allocated by- :class:`WorkspaceBase`; the caller should persist- ``workspace.workspace_id`` for later :meth:`get_workspace`- calls.+ .. deprecated::+ Use :meth:`get_workspace` with ``workspace_id=None`` — it+ falls back to :meth:`assign_workspace_id` under the+ manager's isolation policy and reuses the cache path.Args:user_id (`str`):diff --git a/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.pynew file mode 100644index 000000000..ffdb49f56--- /dev/null+++ b/src/agentscope/app/workspace_manager/_k8s_workspace_manager.py@@ -0,0 +1,354 @@+# -*- coding: utf-8 -*-+"""K8sWorkspaceManager — lifecycle manager for :class:`K8sWorkspace`.++Mirrors :class:`E2BWorkspaceManager` 1:1 in its public surface+(``get_workspace`` / ``create_workspace`` / ``close`` / ``close_all``)+so callers do not branch on backend.++Differences from the E2B manager:++* Reattachment uses a deterministic Pod/PVC name derived from+ ``workspace_id`` (via ``_k8s_safe_name``).+ :meth:`K8sWorkspace.initialize` handles rediscovery.+* ``close()`` deletes the Pod; PVC deletion is governed by the+ workspace's ``_delete_pvc_on_close`` attribute.+* Idle workspaces are evicted by a dedicated background sweeper task.+"""++import asyncio+import time+from typing import Any, Self++from typing_extensions import deprecated++from ..._logging import logger+from ...mcp import MCPClient+from ...workspace import K8sWorkspace+from ...workspace._k8s._constants import (+ DEFAULT_GATEWAY_PORT,+ DEFAULT_IMAGE,+)+from ._base import WorkspaceManagerBase, IsolationPolicy++DEFAULT_SWEEP_INTERVAL = 300.0+++class K8sWorkspaceManager(WorkspaceManagerBase):+ """Manages :class:`K8sWorkspace` instances with TTL-based caching.++ Use as an ``async with`` context manager: entering starts the TTL+ sweeper, exiting stops it and closes every cached workspace.+ """++ def __init__(+ self,+ *,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,+ namespace: str = "agentscope",+ kubeconfig: str | None = None,+ image: str = DEFAULT_IMAGE,+ image_pull_policy: str = "IfNotPresent",+ image_pull_secrets: list[str] | None = None,+ resources: dict[str, Any] | None = None,+ node_selector: dict[str, str] | None = None,+ tolerations: list[dict[str, Any]] | None = None,+ service_account: str | None = None,+ gateway_port: int = DEFAULT_GATEWAY_PORT,+ extra_pip: list[str] | None = None,+ storage_class: str | None = None,+ storage_size: str = "1Gi",+ env: dict[str, str] | None = None,+ default_mcps: list[MCPClient] | None = None,+ skill_paths: list[str] | None = None,+ ttl: float = 3600.0,+ sweep_interval: float = DEFAULT_SWEEP_INTERVAL,+ delete_pvc_on_close: bool = False,+ ) -> None:+ """Initialize the K8s workspace manager.++ Args:+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for :meth:`assign_workspace_id`. See+ :class:`DockerWorkspaceManager` for semantics.+ namespace (`str`, defaults to ``"agentscope"``):+ K8s namespace for workspace Pods and PVCs.+ kubeconfig (`str | None`, optional):+ Path to kubeconfig file. ``None`` uses in-cluster+ config.+ image (`str`, defaults to ``"python:3.11-slim"``):+ Container image for workspace Pods.+ image_pull_policy (`str`, defaults to ``"IfNotPresent"``):+ K8s imagePullPolicy.+ image_pull_secrets (`list[str] | None`, optional):+ Names of K8s image pull secrets.+ resources (`dict[str, Any] | None`, optional):+ K8s ResourceRequirements dict.+ node_selector (`dict[str, str] | None`, optional):+ K8s nodeSelector.+ tolerations (`list[dict[str, Any]] | None`, optional):+ K8s tolerations list.+ service_account (`str | None`, optional):+ K8s serviceAccountName.+ gateway_port (`int`, defaults to `5600`):+ Port the gateway listens on inside the Pod.+ extra_pip (`list[str] | None`, optional):+ Extra packages for the gateway venv.+ storage_class (`str | None`, optional):+ K8s StorageClass name.+ storage_size (`str`, defaults to ``"1Gi"``):+ PVC size.+ env (`dict[str, str] | None`, optional):+ Environment variables for workspace containers.+ default_mcps (`list[MCPClient] | None`, optional):+ MCPs seeded into new workspaces.+ skill_paths (`list[str] | None`, optional):+ Skill directories seeded into new workspaces.+ ttl (`float`, defaults to `3600.0`):+ Seconds before an idle workspace is evicted.+ sweep_interval (`float`, defaults to `300.0`):+ How often the sweeper runs.+ delete_pvc_on_close (`bool`, defaults to ``False``):+ Default ``delete_pvc_on_close`` value for newly+ created workspaces.+ """+ self._namespace = namespace+ self._kubeconfig = kubeconfig+ self._image = image+ self._image_pull_policy = image_pull_policy+ self._image_pull_secrets = list(image_pull_secrets or [])+ self._resources = resources+ self._node_selector = node_selector+ self._tolerations = tolerations+ self._service_account = service_account+ self._gateway_port = gateway_port+ self._extra_pip = list(extra_pip or [])+ self._storage_class = storage_class+ self._storage_size = storage_size+ self._env = dict(env or {})+ self._default_mcps = list(default_mcps or [])+ self._skill_paths = list(skill_paths or [])+ self._ttl = ttl+ self._sweep_interval = sweep_interval+ self._delete_pvc_on_close = delete_pvc_on_close+ super().__init__(isolation=isolation)++ # workspace_id → (workspace, last_access_monotonic)+ self._cache: dict[str, tuple[K8sWorkspace, float]] = {}+ self._lock = asyncio.Lock()+ self._sweep_task: asyncio.Task[None] | None = None++ # ── workspace construction ────────────────────────────────────++ async def _build_and_start(+ self,+ *,+ workspace_id: str | None,+ ) -> K8sWorkspace:+ """Construct a :class:`K8sWorkspace` and run ``initialize``."""+ ws = K8sWorkspace(+ workspace_id=workspace_id,+ kubeconfig=self._kubeconfig,+ namespace=self._namespace,+ image=self._image,+ image_pull_policy=self._image_pull_policy,+ image_pull_secrets=self._image_pull_secrets,+ resources=self._resources,+ node_selector=self._node_selector,+ tolerations=self._tolerations,+ service_account=self._service_account,+ gateway_port=self._gateway_port,+ extra_pip=self._extra_pip,+ storage_class=self._storage_class,+ storage_size=self._storage_size,+ delete_pvc_on_close=self._delete_pvc_on_close,+ env=self._env,+ default_mcps=self._default_mcps,+ skill_paths=self._skill_paths,+ )+ await ws.initialize()+ return ws++ # ── public API ────────────────────────────────────────────────++ async def get_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace_id: str | None = None,+ ) -> K8sWorkspace:+ """Return an initialised workspace, reattaching on cache miss.++ Args:+ user_id (`str`):+ Owning user identifier.+ agent_id (`str`):+ Agent identifier.+ session_id (`str`):+ Session identifier (unused; Pods are per-workspace).+ workspace_id (`str | None`, optional):+ Stable workspace identifier — the cache key. When+ ``None`` the manager falls back to+ :meth:`assign_workspace_id`.++ Returns:+ `K8sWorkspace`:+ A live, initialised workspace.+ """+ del session_id++ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id=user_id,+ agent_id=agent_id,+ session_id="",+ )++ async with self._lock:+ cached = self._cache.get(workspace_id)+ if cached is not None:+ ws, _ = cached+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ async with self._lock:+ cached = self._cache.get(workspace_id)+ if cached is not None:+ ws, _ = cached+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ ws = await self._build_and_start(+ workspace_id=workspace_id,+ )+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ @deprecated(+ "K8sWorkspaceManager.create_workspace is deprecated; "+ "use get_workspace(workspace_id=None) instead.",+ category=None,+ )+ async def create_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> K8sWorkspace:+ """Build a brand-new workspace and track it.++ .. deprecated::+ Use :meth:`get_workspace` with ``workspace_id=None`` — it+ falls back to :meth:`assign_workspace_id` under the+ manager's isolation policy and reuses the cache path.++ Args:+ user_id (`str`):+ Owning user identifier.+ agent_id (`str`):+ Agent identifier.+ session_id (`str`):+ Session identifier (unused).++ Returns:+ `K8sWorkspace`:+ The newly built workspace, already initialised.+ """+ del session_id, user_id, agent_id++ ws = await self._build_and_start(workspace_id=None)+ async with self._lock:+ self._cache[ws.workspace_id] = (ws, time.monotonic())+ return ws++ async def close(self, workspace_id: str) -> None:+ """Close and evict a single workspace.++ Args:+ workspace_id (`str`):+ The workspace to close.+ """+ async with self._lock:+ entry = self._cache.pop(workspace_id, None)+ if entry is None:+ return+ ws, _ = entry+ await self._safe_close(ws)++ async def close_all(self) -> None:+ """Close every cached workspace in parallel."""+ async with self._lock:+ entries = list(self._cache.values())+ self._cache.clear()+ if not entries:+ return+ await asyncio.gather(+ *(self._safe_close(ws) for ws, _ in entries),+ return_exceptions=True,+ )++ # ── async context manager ─────────────────────────────────────++ async def __aenter__(self) -> Self:+ """Start the TTL sweeper task."""+ if self._sweep_task is None:+ self._sweep_task = asyncio.create_task(self._sweep_loop())+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Stop the TTL sweeper, then close every cached workspace."""+ if self._sweep_task is not None:+ self._sweep_task.cancel()+ try:+ await self._sweep_task+ except (asyncio.CancelledError, Exception):+ pass+ self._sweep_task = None+ await self.close_all()++ # ── background sweeper ───────────────────────────────────────++ async def _sweep_loop(self) -> None:+ """Periodically evict idle workspaces."""+ while True:+ try:+ await asyncio.sleep(self._sweep_interval)+ except asyncio.CancelledError:+ return+ try:+ await self._sweep_once()+ except Exception:+ logger.exception("K8s workspace sweeper tick failed")++ async def _sweep_once(self) -> None:+ """One sweeper tick: evict expired entries and close them."""+ now = time.monotonic()+ async with self._lock:+ expired_ids = [+ wid+ for wid, (_, ts) in self._cache.items()+ if now - ts > self._ttl+ ]+ evicted = [self._cache.pop(wid)[0] for wid in expired_ids]+ if not evicted:+ return+ await asyncio.gather(+ *(self._safe_close(ws) for ws in evicted),+ return_exceptions=True,+ )++ @staticmethod+ async def _safe_close(ws: K8sWorkspace) -> None:+ """Close a workspace, logging any failure instead of raising.++ Args:+ ws (`K8sWorkspace`):+ The workspace to close.+ """+ try:+ await ws.close()+ except Exception:+ logger.exception(+ "Failed to close K8sWorkspace %s",+ ws.workspace_id,+ )diff --git a/src/agentscope/app/workspace_manager/_local_workspace_manager.py b/src/agentscope/app/workspace_manager/_local_workspace_manager.pyindex 7985c27f9..1a4e08a69 100644--- a/src/agentscope/app/workspace_manager/_local_workspace_manager.py+++ b/src/agentscope/app/workspace_manager/_local_workspace_manager.py@@ -5,9 +5,11 @@ import asyncioimport osimport time+from typing_extensions import deprecated+from ..._logging import loggerfrom ...workspace import LocalWorkspace-from ._base import WorkspaceManagerBase+from ._base import WorkspaceManagerBase, IsolationPolicyclass LocalWorkspaceManager(WorkspaceManagerBase):@@ -22,6 +24,8 @@ class LocalWorkspaceManager(WorkspaceManagerBase):def __init__(self,basedir: str,+ *,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,default_mcps: list | None = None,skill_paths: list[str] | None = None,ttl: float = 3600.0,@@ -32,6 +36,9 @@ class LocalWorkspaceManager(WorkspaceManagerBase):basedir (`str`):Root directory under which per-agent workdir arecreated.+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for :meth:`assign_workspace_id`. See+ :class:`DockerWorkspaceManager` for semantics.default_mcps (`list | None`, optional):MCP clients seeded into brand-new workspaces.skill_paths (`list[str] | None`, optional):@@ -46,6 +53,7 @@ class LocalWorkspaceManager(WorkspaceManagerBase):# workspace_id → (workspace, last_access_monotonic)self._cache: dict[str, tuple[LocalWorkspace, float]] = {}self._lock = asyncio.Lock()+ super().__init__(isolation=isolation)def _pop_expired(self, now: float) -> list[LocalWorkspace]:"""Pop every cache entry whose last-access exceeds ``ttl``.@@ -64,7 +72,7 @@ class LocalWorkspaceManager(WorkspaceManagerBase):user_id: str,agent_id: str,session_id: str,- workspace_id: str,+ workspace_id: str | None = None,) -> LocalWorkspace:"""Return an initialized workspace, reconstructing fromdisk on cache miss.@@ -79,6 +87,13 @@ class LocalWorkspaceManager(WorkspaceManagerBase):"""del user_id # accepted for interface parity; not used here+ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id="",+ agent_id=agent_id,+ session_id="",+ )+# Phase 1: cache hit + collect expired.async with self._lock:now = time.monotonic()@@ -124,13 +139,24 @@ class LocalWorkspaceManager(WorkspaceManagerBase):self._cache[workspace_id] = (ws, time.monotonic())return ws+ @deprecated(+ "LocalWorkspaceManager.create_workspace is deprecated; "+ "use get_workspace(workspace_id=None) instead.",+ category=None,+ )async def create_workspace(self,user_id: str,agent_id: str,session_id: str,) -> LocalWorkspace:- """Create a new workspace for the given agent and return it."""+ """Create a new workspace for the given agent and return it.++ .. deprecated::+ Use :meth:`get_workspace` with ``workspace_id=None`` — it+ falls back to :meth:`assign_workspace_id` under the+ manager's isolation policy and reuses the cache path.+ """del user_id, session_id # accepted for interface parityworkdir = os.path.join(self._basedir, agent_id)diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.pyindex 37531571f..a3cdd459e 100644--- a/src/agentscope/workspace/__init__.py+++ b/src/agentscope/workspace/__init__.py@@ -7,6 +7,7 @@ from ._local_workspace import LocalWorkspacefrom ._offload_protocol import Offloaderfrom ._docker import DockerBackend, DockerWorkspacefrom ._e2b import E2BWorkspace, E2BBackend+from ._k8s import K8sBackend, K8sWorkspace__all__ = [@@ -16,5 +17,7 @@ __all__ = ["DockerWorkspace","E2BBackend","E2BWorkspace",+ "K8sBackend",+ "K8sWorkspace","Offloader",]diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.pyindex f828270f6..991f93ba1 100644--- a/src/agentscope/workspace/_base.py+++ b/src/agentscope/workspace/_base.py@@ -71,6 +71,12 @@ from ..message import ()from ..skill import Skillfrom ..tool import BackendBase, ToolBase+from ._utils import (+ DEFAULT_DATA_DIR,+ DEFAULT_MCP_FILE,+ DEFAULT_SESSIONS_DIR,+ DEFAULT_SKILLS_DIR,+)_EXTRACT_TAR_SHIM = ("import tarfile, sys, os\n"@@ -129,10 +135,10 @@ class WorkspaceBase:_mcps: list[MCPClient]"""Currently registered MCP clients (in-memory authoritative copy).- For sandbox-gateway subclasses this list mirrors the spec the- gateway was registered with (live handles hang off- :class:`SandboxedWorkspaceBase._gateway_clients`); for- :class:`LocalWorkspace` it *is* the live handle list.+ :class:`LocalWorkspace` stores the local live handles directly;+ :class:`SandboxedWorkspaceBase` stores gateway-side+ :class:`GatewayMCPClient` wrappers (also ``MCPClient`` instances)+ so ``list_mcps`` / persistence work uniformly across both."""_mcp_lock: asyncio.Lock@@ -141,15 +147,6 @@ class WorkspaceBase:_skill_lock: asyncio.Lock"""Guards mutation of the ``skills/`` directory."""- _glob_helper_path: str | None = None- """Optional path (backend-side) to the ``Glob`` helper script.-- ``None`` means the :class:`Glob` builtin tool falls back to its- default behaviour (suitable for :class:`LocalBackend`). Remote- backends override this with a sandbox-/container-side script path- so :class:`Glob` can run efficiently inside the workspace.- """-def __init__(self,*,@@ -192,22 +189,28 @@ class WorkspaceBase:@propertydef _data_dir(self) -> str:"""``${workdir}/data`` — offloaded multimodal payloads."""- return self.get_backend().join_path(self.workdir, "data")+ return self.get_backend().join_path(self.workdir, DEFAULT_DATA_DIR)@propertydef _skills_dir(self) -> str:"""``${workdir}/skills`` — skill subdirectories."""- return self.get_backend().join_path(self.workdir, "skills")+ return self.get_backend().join_path(+ self.workdir,+ DEFAULT_SKILLS_DIR,+ )@propertydef _sessions_dir(self) -> str:"""``${workdir}/sessions`` — per-session offload files."""- return self.get_backend().join_path(self.workdir, "sessions")+ return self.get_backend().join_path(+ self.workdir,+ DEFAULT_SESSIONS_DIR,+ )@propertydef _mcp_file(self) -> str:"""``${workdir}/.mcp`` — persisted MCP registrations."""- return self.get_backend().join_path(self.workdir, ".mcp")+ return self.get_backend().join_path(self.workdir, DEFAULT_MCP_FILE)@propertydef is_persistent(self) -> bool:@@ -390,53 +393,6 @@ class WorkspaceBase:e,)- async def _restore_or_seed_mcps(self) -> list[MCPClient]:- """Read ``${workdir}/.mcp`` if present, else return ``default_mcps``.-- Decoding / validation failures are downgraded to warnings and- treated as a missing file — :attr:`default_mcps` is returned so- a corrupted persistence file cannot block startup.- """- if not self.is_persistent:- return list(self.default_mcps)- backend = self._backend- if backend is None:- return list(self.default_mcps)- try:- if not await backend.file_exists(self._mcp_file):- return list(self.default_mcps)- raw = await backend.read_file(self._mcp_file)- except (FileNotFoundError, OSError) as e:- logger.warning(- "Failed to read MCP file at %s, falling back to "- "default_mcps: %s",- self._mcp_file,- e,- )- return list(self.default_mcps)- try:- data = json.loads(raw.decode("utf-8"))- except Exception as e:- logger.warning(- "Failed to parse MCP file at %s, falling back to "- "default_mcps: %s",- self._mcp_file,- e,- )- return list(self.default_mcps)- result: list[MCPClient] = []- for m in data:- try:- result.append(MCPClient.model_validate(m))- except Exception as e:- name = m.get("name", "?") if isinstance(m, dict) else "?"- logger.warning(- "Skipping invalid MCP entry %r: %s",- name,- e,- )- return result-# ── for Agent: offload (shared) ────────────────────────────────async def offload_context(@@ -745,7 +701,7 @@ class WorkspaceBase:await backend.delete_path(target_dir)logger.info("Removed skill %r at %s", name, target_dir)- async def _seed_skills(self) -> None:+ async def _setup_skills(self) -> None:"""Copy :attr:`skill_paths` into ``${workdir}/skills`` once.Skips seeding when:diff --git a/src/agentscope/workspace/_docker/Dockerfile.install_pypi.template b/src/agentscope/workspace/_docker/Dockerfile.install_pypi.templatedeleted file mode 100644index 1ab608035..000000000--- a/src/agentscope/workspace/_docker/Dockerfile.install_pypi.template+++ /dev/null@@ -1,5 +0,0 @@-# ``--no-deps``: see Dockerfile.install_src.template for the rationale.-# Gateway only needs ``agentscope.mcp.MCPClient`` and its lightweight-# transitive imports (mcp, pydantic, httpx, fastapi), all of which are-# pulled in by requirements.txt above.-RUN uv pip install --no-deps "agentscope=={agentscope_version}"diff --git a/src/agentscope/workspace/_docker/Dockerfile.install_src.template b/src/agentscope/workspace/_docker/Dockerfile.install_src.templatedeleted file mode 100644index 15a8fe959..000000000--- a/src/agentscope/workspace/_docker/Dockerfile.install_src.template+++ /dev/null@@ -1,12 +0,0 @@-# TODO(release): when agentscope is on PyPI, drop this whole block and use-# Dockerfile.install_pypi.template instead. Copying the source tree is a-# transitional dev-only path so the in-container gateway can `import agentscope`.-COPY agentscope_src /tmp/agentscope_src-# ``--no-deps``: the gateway only imports ``agentscope.mcp.MCPClient``,-# whose transitive needs (mcp, pydantic, httpx, fastapi) are already-# installed via requirements.txt above. Skipping agentscope's full-# dependency tree avoids dragging in heavy/Rust-built packages-# (ripgrep, tree_sitter, opentelemetry, anthropic/openai SDKs, …)-# which would otherwise require a C/Rust toolchain in the slim image.-RUN uv pip install --no-deps /tmp/agentscope_src \- && rm -rf /tmp/agentscope_srcdiff --git a/src/agentscope/workspace/_docker/Dockerfile.template b/src/agentscope/workspace/_docker/Dockerfile.templateindex 22bb6a843..7a56a0a73 100644--- a/src/agentscope/workspace/_docker/Dockerfile.template+++ b/src/agentscope/workspace/_docker/Dockerfile.template@@ -1,4 +1,8 @@# syntax=docker/dockerfile:1.6+# The filenames `.venv`, `_mcp_gateway_app.py`, `_glob_helper.py`,+# `gateway.log` below MUST stay in sync with the DEFAULT_GATEWAY_*+# constants in ``agentscope.workspace._utils`` — the base class derives+# runtime paths from those and joins them under ``_gateway_home``.{node_from_block}FROM {base_image}# Install uv via Astral's official shell installer.diff --git a/src/agentscope/workspace/_docker/_docker_workspace.py b/src/agentscope/workspace/_docker/_docker_workspace.pyindex 152213fe4..36a5c7061 100644--- a/src/agentscope/workspace/_docker/_docker_workspace.py+++ b/src/agentscope/workspace/_docker/_docker_workspace.py@@ -1,28 +1,19 @@# -*- coding: utf-8 -*-"""DockerWorkspace — sandboxed workspace backed by a Docker container.-Architecture--------------* Container lifecycle (build + run + stop) via **aiodocker**.-* MCP servers run *inside* the container behind a FastAPI gateway- (see :mod:`agentscope.workspace._mcp_gateway`); the host talks to it- over HTTP via :class:`GatewayClient` / :class:`GatewayMCPClient`.+* MCP servers run inside the container behind a FastAPI gateway+ (see :mod:`agentscope.workspace._mcp_gateway`); the host reaches it+ through :class:`GatewayClient` via ``backend.exec_shell``.* Optional bind-mounted host ``workdir`` makes the workspace- persistent — ``.mcp`` (registered MCPs), ``skills/``, ``sessions/``- and ``data/`` survive restarts. Without ``workdir`` the container- is ephemeral.+ persistent — ``.mcp``, ``skills/``, ``sessions/``, ``data/`` survive+ restarts. Without ``workdir`` the container is ephemeral.* Image is content-hashed by Dockerfile + COPY payloads(see :mod:`._make_dockerfile`); a cache hit skips the build.-Persistence model mirrors :class:`agentscope.workspace.LocalWorkspace`:-on each :meth:`initialize`, MCPs are restored from ``<workdir>/.mcp``-if it exists (otherwise ``default_mcps`` are used and persisted).-Every :meth:`add_mcp` / :meth:`remove_mcp` rewrites the file.--The gateway bearer token is freshly generated on each ``initialize``-and shipped into the container via the gateway config file — it is-*not* persisted.+On each :meth:`initialize`, MCPs are restored from ``<workdir>/.mcp``+(or seeded from ``default_mcps``); ``add_mcp`` / ``remove_mcp`` rewrite+the file. The gateway reads ``.mcp`` directly as its config."""import io@@ -40,12 +31,7 @@ from ._make_dockerfile import (CONTAINER_WORKDIR,DEFAULT_BASE_IMAGE,DEFAULT_GATEWAY_PORT,- GATEWAY_CONFIG,GATEWAY_HOME,- GATEWAY_LOG,- GATEWAY_SCRIPT,- GATEWAY_VENV,- GLOB_HELPER_SCRIPT,prepare_build_context,)@@ -77,12 +63,7 @@ class DockerWorkspace(SandboxedWorkspaceBase):not retained as instance state past :meth:`initialize`."""- _glob_helper_path = GLOB_HELPER_SCRIPT_gateway_home = GATEWAY_HOME- _gateway_config = GATEWAY_CONFIG- _gateway_log = GATEWAY_LOG- _gateway_script = GATEWAY_SCRIPT- _gateway_python = f"{GATEWAY_VENV}/bin/python"def __init__(self,@@ -308,6 +289,7 @@ class DockerWorkspace(SandboxedWorkspaceBase):f"{log}",)finally:+ logger.info("DockerWorkspace: finish building image %r", tag)shutil.rmtree(ctx_dir, ignore_errors=True)# ── internals: container lifecycle ──────────────────────────@@ -350,15 +332,3 @@ class DockerWorkspace(SandboxedWorkspaceBase):# Create the backend now that the container is running. All# subsequent container I/O in this workspace goes through it.self._backend = DockerBackend(self._container, CONTAINER_WORKDIR)-- # Pre-create the persistence directories (also shapes a newly- # bind-mounted host workdir on first use).- await self._backend.exec_shell(- [- "mkdir",- "-p",- self._data_dir,- self._skills_dir,- self._sessions_dir,- ],- )diff --git a/src/agentscope/workspace/_docker/_make_dockerfile.py b/src/agentscope/workspace/_docker/_make_dockerfile.pyindex 332c2eb9b..651e8ef59 100644--- a/src/agentscope/workspace/_docker/_make_dockerfile.py+++ b/src/agentscope/workspace/_docker/_make_dockerfile.py@@ -5,16 +5,8 @@ The image is keyed by content hash of the Dockerfile text plus allfiles COPYed into it. If the tag already exists locally the build isskipped; otherwise the caller builds with the prepared context.-Two install modes are supported, picked automatically from the host's-``agentscope`` install:--* **released** — when ``agentscope`` is in site-packages, the container- installs the same version from PyPI.-* **dev** — when running from a source checkout, the project tree is- copied into the build context and installed via ``uv pip install- /tmp/agentscope_src``. This is a transitional path used until- agentscope is published; it is marked with TODOs in the templates so- it is easy to delete later.+The container installs the same ``agentscope`` version as the host via+``uv pip install --no-deps`` inside the gateway venv.Public functions:@@ -23,22 +15,17 @@ Public functions:* :func:`compute_image_tag` — sha256 of Dockerfile + COPY files;returns ``agentscope-workspace:<12hex>``.* :func:`prepare_build_context` — assemble a temp directory holding- the Dockerfile, ``requirements.txt``, and (in dev mode) the- agentscope source tree. Returns ``(ctx_dir, tag, copy_files)``.+ the Dockerfile, ``requirements.txt``, and helper scripts. Returns+ ``(ctx_dir, tag, copy_files)``."""import hashlibimport importlib.resources as _res-import shutilimport tempfilefrom pathlib import Pathfrom .._utils import (_GATEWAY_BASE_REQUIREMENTS,- _agentscope_source_root,- _agentscope_version,- _is_released_install,- _is_source_ignored,_read_gateway_script_bytes,_read_glob_helper_bytes,)@@ -49,23 +36,8 @@ DEFAULT_BASE_IMAGE = "python:3.11-slim"DEFAULT_GATEWAY_PORT = 5600CONTAINER_WORKDIR = "/workspace"-CONTAINER_DATA_DIR = f"{CONTAINER_WORKDIR}/data"-CONTAINER_SKILLS_DIR = f"{CONTAINER_WORKDIR}/skills"-CONTAINER_SESSIONS_DIR = f"{CONTAINER_WORKDIR}/sessions"-CONTAINER_MCP_FILE = f"{CONTAINER_WORKDIR}/.mcp"GATEWAY_HOME = "/root/.agentscope"-GATEWAY_VENV = f"{GATEWAY_HOME}/.venv"-GATEWAY_CONFIG = f"{GATEWAY_HOME}/gateway.config.json"-GATEWAY_LOG = f"{GATEWAY_HOME}/gateway.log"-# Standalone gateway script copied into the image. We invoke this-# directly rather than via ``python -m agentscope.workspace._mcp_gateway``-# so Python does not auto-import ``agentscope.workspace.__init__`` (which-# pulls in skill/tool/local_workspace/docker_workspace and their heavy-# transitive dependencies).-GATEWAY_SCRIPT = f"{GATEWAY_HOME}/_mcp_gateway_app.py"-# Standalone glob helper script used by the Glob builtin tool.-GLOB_HELPER_SCRIPT = f"{GATEWAY_HOME}/_glob_helper.py"IMAGE_REPO = "agentscope-workspace"@@ -75,8 +47,6 @@ _TEMPLATE_PKG = "agentscope.workspace._docker"_DOCKERFILE_TEMPLATE = "Dockerfile.template"_DOCKERFILE_NODE_FROM_TEMPLATE = "Dockerfile.node_from.template"_DOCKERFILE_NODE_COPY_TEMPLATE = "Dockerfile.node_copy.template"-_DOCKERFILE_INSTALL_PYPI_TEMPLATE = "Dockerfile.install_pypi.template"-_DOCKERFILE_INSTALL_SRC_TEMPLATE = "Dockerfile.install_src.template"def _read_template(name: str) -> str:@@ -84,29 +54,6 @@ def _read_template(name: str) -> str:return _res.files(_TEMPLATE_PKG).joinpath(name).read_text(encoding="utf-8")-# ── source-tree packaging (dev mode) ───────────────────────────────---def _source_ignore(_dir: str, names: list[str]) -> list[str]:- """``shutil.copytree`` ignore filter — defers- to :func:`_is_source_ignored`."""- return [n for n in names if _is_source_ignored(n)]---def _hash_directory(root: Path) -> bytes:- """Hash a directory tree's contents in a stable order."""- h = hashlib.sha256()- for p in sorted(root.rglob("*")):- if not p.is_file():- continue- rel = p.relative_to(root).as_posix().encode("utf-8")- h.update(b"\x00")- h.update(rel)- h.update(b"\x00")- h.update(p.read_bytes())- return h.digest()--# ── public API ─────────────────────────────────────────────────────@@ -132,8 +79,7 @@ def render_dockerfile(image. ``None`` skips Node installation.install_agentscope_block: Pre-rendered block (no surroundingblank lines) that installs ``agentscope`` into the gateway- venv. Built by :func:`prepare_build_context` from one of- ``Dockerfile.install_{pypi,src}.template``.+ venv. Built by :func:`prepare_build_context`.Returns:The full Dockerfile text.@@ -177,10 +123,7 @@ def compute_image_tag(Args:dockerfile_text: Full Dockerfile text.copy_files: Mapping of context-relative filename → bytes for- every file referenced by a ``COPY`` instruction. Directory- payloads (e.g. the agentscope source tree in dev mode) are- represented as a single synthetic key whose value is the- tree's content hash.+ every file referenced by a ``COPY`` instruction.Returns:Tag of the form ``agentscope-workspace:<12 hex chars>``.@@ -206,10 +149,9 @@ def prepare_build_context() -> tuple[Path, str, dict[str, bytes]]:"""Assemble a temporary build context directory.- Writes Dockerfile, ``requirements.txt`` and the agentscope payload- (source tree in dev mode, nothing extra in released mode) into a- fresh temp dir. The caller is responsible for removing the- directory after the build completes.+ Writes Dockerfile, ``requirements.txt`` and helper scripts into a+ fresh temp dir. The caller is responsible for removing the directory+ after the build completes.Returns:``(ctx_dir, tag, copy_files)`` — ``ctx_dir`` holds the@@ -219,20 +161,7 @@ def prepare_build_context("""extra_pip_list = list(extra_pip or [])- released = _is_released_install()- if released:- version = _agentscope_version()- install_block = _read_template(- _DOCKERFILE_INSTALL_PYPI_TEMPLATE,- ).format(agentscope_version=version)- source_root: Path | None = None- else:- # TODO(release): drop this branch once agentscope is on PyPI; the- # released path above subsumes it. The dev branch copies the project- # tree into the build context so the in-container venv can install- # the same code the host is running.- install_block = _read_template(_DOCKERFILE_INSTALL_SRC_TEMPLATE)- source_root = _agentscope_source_root()+ install_block = 'RUN uv pip install "agentscope"'dockerfile_text = render_dockerfile(base_image=base_image,@@ -254,12 +183,6 @@ def prepare_build_context("_mcp_gateway_app.py": gateway_script_bytes,"_glob_helper.py": glob_helper_bytes,}- if source_root is not None:- # Synthetic entry: the directory tree is too large to inline, so we- # hash it once and stash the digest under a stable key. Image-tag- # determinism depends only on this digest, not on the temp path.- copy_files["agentscope_src/"] = _hash_directory(source_root)-tag = compute_image_tag(dockerfile_text, copy_files)ctx_dir = Path(tempfile.mkdtemp(prefix="as-ws-build-"))@@ -269,12 +192,5 @@ def prepare_build_context()(ctx_dir / "_mcp_gateway_app.py").write_bytes(gateway_script_bytes)(ctx_dir / "_glob_helper.py").write_bytes(glob_helper_bytes)- if source_root is not None:- shutil.copytree(- source_root,- ctx_dir / "agentscope_src",- ignore=_source_ignore,- symlinks=False,- )return ctx_dir, tag, copy_filesdiff --git a/src/agentscope/workspace/_e2b/_bootstrap.py b/src/agentscope/workspace/_e2b/_bootstrap.pydeleted file mode 100644index 84405d776..000000000--- a/src/agentscope/workspace/_e2b/_bootstrap.py+++ /dev/null@@ -1,204 +0,0 @@-# -*- coding: utf-8 -*--"""Bootstrap helpers for :class:`E2BWorkspace` first-time provisioning.--Unlike :class:`DockerWorkspace`, E2B has no image-build phase: it-attaches to a pre-built template (``base`` by default). The first-time we create a sandbox for a given ``workspace_id``, we run a-sequence of shell commands to install ``uv``, the gateway venv, the-gateway base requirements, and the ``agentscope`` package. After this-the gateway script is uploaded into the sandbox.--These artefacts persist across ``sandbox.pause()`` / ``resume`` so-the bootstrap cost is paid exactly once per sandbox lifetime.--Two install modes mirror Docker:--* **released** — ``agentscope`` is in site-packages on the host;- install the same version from PyPI inside the sandbox.-* **dev** — running from a source checkout; tar the project tree on- the host, upload it as a single blob, untar inside the sandbox, and- ``uv pip install --no-deps`` it.--``--no-deps`` is mandatory: the gateway only imports-``agentscope.mcp.MCPClient`` whose transitive needs are-``mcp / pydantic / httpx`` (already installed via the gateway base-requirements). Pulling agentscope's full dep tree drags in heavy /-Rust-built packages (ripgrep, tree_sitter, opentelemetry, openai,-anthropic, dashscope) for which the sandbox base image typically has-no compiler, exactly the same trap we hit on Docker.-"""--import io-import tarfile--from ..._logging import logger-from .._utils import (- _GATEWAY_BASE_REQUIREMENTS,- _agentscope_source_root,- _is_source_ignored,-)--# ── shared constants ───────────────────────────────────────────────--#: Default E2B template. Matches the SDK's ``base`` template — has-#: Ubuntu + python3 + curl out of the box, which is everything the-#: bootstrap needs.-DEFAULT_TEMPLATE = "base"--#: Default keep-alive timeout in seconds for newly-created sandboxes.-DEFAULT_TIMEOUT = 300--#: Default port the in-sandbox gateway listens on.-DEFAULT_GATEWAY_PORT = 5600--#: Sandbox-side runtime user (E2B base image runs as ``user``, not-#: ``root``). All the per-workspace paths sit under its ``$HOME``.-SANDBOX_USER_HOME = "/home/user"--# Workspace-side persistent layout — mirrors the DockerWorkspace one.-SANDBOX_WORKDIR = f"{SANDBOX_USER_HOME}/workspace"-SANDBOX_DATA_DIR = f"{SANDBOX_WORKDIR}/data"-SANDBOX_SKILLS_DIR = f"{SANDBOX_WORKDIR}/skills"-SANDBOX_SESSIONS_DIR = f"{SANDBOX_WORKDIR}/sessions"-SANDBOX_MCP_FILE = f"{SANDBOX_WORKDIR}/.mcp"--# Gateway home — venv, script, config, logs.-GATEWAY_HOME = f"{SANDBOX_USER_HOME}/.agentscope"-GATEWAY_VENV = f"{GATEWAY_HOME}/.venv"-GATEWAY_VENV_PY = f"{GATEWAY_VENV}/bin/python"-GATEWAY_SCRIPT = f"{GATEWAY_HOME}/_mcp_gateway_app.py"-# Standalone glob helper script used by the builtin Glob tool.-GLOB_HELPER_SCRIPT = f"{GATEWAY_HOME}/_glob_helper.py"-GATEWAY_CONFIG = f"{GATEWAY_HOME}/gateway.config.json"-GATEWAY_LOG = f"{GATEWAY_HOME}/gateway.log"--# uv binary lives under the user's local bin since we cannot write to-# /usr/local/bin without sudo on the default E2B image.-UV_BIN = f"{SANDBOX_USER_HOME}/.local/bin/uv"--#: Sandbox metadata key used to map workspace_id → sandbox_id. The-#: manager filters ``list_sandboxes`` by this key on cache miss to-#: locate (and resume) an existing sandbox.-METADATA_WORKSPACE_ID_KEY = "agentscope.workspace.id"--#: Tarball drop point for dev-mode ``agentscope`` source uploads.-#: Lives under ``GATEWAY_HOME`` (user-owned) instead of ``/tmp``-#: because the E2B ``files.write`` API runs as ``user`` and ``/tmp``-#: can have restrictive permissions after a sandbox pause/resume cycle.-DEV_SRC_TAR = f"{GATEWAY_HOME}/agentscope_src.tar"-DEV_SRC_DIR = f"{GATEWAY_HOME}/agentscope_src"--# ── source tarball (dev mode only) ─────────────────────────────────---def _tar_filter(info: tarfile.TarInfo) -> tarfile.TarInfo | None:- """``tarfile.add`` filter — skip caches, hidden files and heavy dirs.-- Returning ``None`` for an entry tells :meth:`tarfile.add` to also- *stop recursing* into it, so the root archive entry (``arcname="."``)- must be passed through unchanged — otherwise the entire tree is- excluded and the resulting tarball is effectively empty.- """- if info.name == ".":- return info- name = info.name.split("/")[-1]- if _is_source_ignored(name):- return None- return info---def build_source_tarball() -> bytes:- """Tar up the agentscope source tree for dev-mode upload.-- Returns the tar bytes (uncompressed); the sandbox will untar with- ``tar -xf`` (no ``-z``).- """- root = _agentscope_source_root()- buf = io.BytesIO()- with tarfile.open(fileobj=buf, mode="w") as tf:- tf.add(str(root), arcname=".", filter=_tar_filter)- return buf.getvalue()---# ── bootstrap command sequence ─────────────────────────────────────---def bootstrap_commands(- *,- extra_pip: list[str] | None = None,- install_agentscope_cmd: str,-) -> list[str]:- """Return the shell commands to provision a fresh E2B sandbox.-- Args:- extra_pip: Extra Python packages to install into the gateway- venv alongside the base requirements.- install_agentscope_cmd: Shell command that installs- ``agentscope`` into the gateway venv. Built per install- mode by :func:`render_install_agentscope_cmd` (released)- or :func:`render_install_agentscope_cmd_dev` (dev).-- Returns:- A list of shell command strings, to be executed in order.- Each must exit 0; a non-zero exit aborts the bootstrap.- """- pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(extra_pip or [])- pip_args = " ".join(pip_pkgs)-- return [- # 1. Persistent layout. mkdir -p is cheap on resume too — keeps- # the command idempotent in case bootstrap is re-run.- f"mkdir -p {SANDBOX_DATA_DIR} {SANDBOX_SKILLS_DIR} "- f"{SANDBOX_SESSIONS_DIR} {GATEWAY_HOME}",- # 2. Install ripgrep for the Grep builtin tool. The base E2B- # image runs as non-root, so we use sudo. ``apt-get update``- # + install is idempotent — safe to re-run on resume.- "sudo apt-get update -qq "- "&& sudo apt-get install -y --no-install-recommends ripgrep "- "&& sudo rm -rf /var/lib/apt/lists/*",- # 3. Astral uv — same shell installer as Docker. The base E2B- # image already ships ``curl``; we land uv at- # ``$HOME/.local/bin`` since the sandbox user has no sudo by- # default. ``INSTALLER_NO_MODIFY_PATH=1`` suppresses shell- # rc edits — we always invoke uv by full path here anyway.- f"curl -LsSf https://astral.sh/uv/install.sh "- f"| env UV_INSTALL_DIR={SANDBOX_USER_HOME}/.local/bin "- f"INSTALLER_NO_MODIFY_PATH=1 sh",- # 4. Gateway venv + base requirements.- f"{UV_BIN} venv {GATEWAY_VENV}",- f"{UV_BIN} pip install --python {GATEWAY_VENV_PY} {pip_args}",- # 5. agentscope itself (mode-dependent).- install_agentscope_cmd,- ]---def render_install_agentscope_cmd_released(version: str) -> str:- """Released-mode install: pin the same version as the host."""- return (- f"{UV_BIN} pip install --python {GATEWAY_VENV_PY} "- f"--no-deps 'agentscope=={version}'"- )---def render_install_agentscope_cmd_dev() -> str:- """Dev-mode install: untar the uploaded tarball and ``pip install``.-- Caller is responsible for uploading the source tarball to- :data:`DEV_SRC_TAR` before running this command.- """- return (- f"mkdir -p {DEV_SRC_DIR} && "- f"tar -xf {DEV_SRC_TAR} -C {DEV_SRC_DIR} && "- f"{UV_BIN} pip install --python {GATEWAY_VENV_PY} "- f"--no-deps {DEV_SRC_DIR} && "- f"rm -rf {DEV_SRC_TAR} {DEV_SRC_DIR}"- )---def log_bootstrap_attempt(workspace_id: str, mode: str) -> None:- """Single info-level log so first-time bootstraps are easy to spot."""- logger.info(- "E2BWorkspace: bootstrapping sandbox for workspace_id=%r (mode=%s)",- workspace_id,- mode,- )diff --git a/src/agentscope/workspace/_e2b/_constants.py b/src/agentscope/workspace/_e2b/_constants.pynew file mode 100644index 000000000..251367449--- /dev/null+++ b/src/agentscope/workspace/_e2b/_constants.py@@ -0,0 +1,28 @@+# -*- coding: utf-8 -*-+"""E2B-specific constants for :class:`E2BWorkspace`.++Path layout (venv, script, log, helper) is derived on the base class+from ``_gateway_home``. This module only carries defaults that cannot+be derived: template, timeouts, port, sandbox user, metadata key.+"""++#: Default E2B template. Matches the SDK's ``base`` template — has+#: Ubuntu + python3 + curl out of the box.+DEFAULT_TEMPLATE = "base"++#: Default keep-alive timeout in seconds for newly-created sandboxes.+DEFAULT_TIMEOUT = 300++#: Default port the in-sandbox gateway listens on.+DEFAULT_GATEWAY_PORT = 5600++#: Sandbox-side runtime user (E2B ``base`` runs as ``user``, not root).+SANDBOX_USER_HOME = "/home/user"++#: Sandbox-side workdir and gateway home — derived once here so the+#: E2B workspace and any hypothetical siblings share the layout.+SANDBOX_WORKDIR = f"{SANDBOX_USER_HOME}/workspace"+GATEWAY_HOME = f"{SANDBOX_USER_HOME}/.agentscope"++#: Sandbox metadata key used to map workspace_id → sandbox_id.+METADATA_WORKSPACE_ID_KEY = "agentscope.workspace.id"diff --git a/src/agentscope/workspace/_e2b/_e2b_workspace.py b/src/agentscope/workspace/_e2b/_e2b_workspace.pyindex 34450a305..530b7a3e7 100644--- a/src/agentscope/workspace/_e2b/_e2b_workspace.py+++ b/src/agentscope/workspace/_e2b/_e2b_workspace.py@@ -18,10 +18,11 @@ Docker engine for the E2B SDK (``e2b.AsyncSandbox``):there is no host-side ``workdir`` parameter. Pausing keeps the disk;resuming brings it back wholesale.* **Bootstrap.** First-time provisioning installs uv + a gateway venv- + agentscope (``--no-deps``) and uploads the gateway script. We- detect whether bootstrap has already happened via a single- ``files.exists(GATEWAY_SCRIPT)`` probe so the cost is paid exactly- once per sandbox lifetime.+ + agentscope (``--no-deps``) and uploads the gateway script. The+ probe + install loop lives on :class:`SandboxedWorkspaceBase`; this+ subclass only supplies the sandbox-specific shell commands via+ :meth:`_bootstrap_commands`. Bootstrap runs at most once per sandbox+ lifetime (the presence of the gateway script on disk is the marker).* **MCP gateway.** Identical to Docker: a FastAPI process inside thesandbox. All host-side calls drive the gateway through:class:`GatewayClient`, which runs an in-sandbox ``python3 -c`` shim@@ -37,35 +38,20 @@ manager handles cache, TTL eviction and metadata-based reattachment."""import asyncio+import shlexfrom typing import Anyfrom ..._logging import loggerfrom ...mcp import MCPClientfrom .._sandboxed_base import SandboxedWorkspaceBase-from .._utils import (- _agentscope_version,- _is_released_install,- _read_gateway_script_bytes,- _read_glob_helper_bytes,-)-from ._bootstrap import (+from .._utils import _GATEWAY_BASE_REQUIREMENTS+from ._constants import (DEFAULT_GATEWAY_PORT,DEFAULT_TEMPLATE,DEFAULT_TIMEOUT,- DEV_SRC_TAR,- GATEWAY_CONFIG,GATEWAY_HOME,- GATEWAY_LOG,- GATEWAY_SCRIPT,- GATEWAY_VENV_PY,- GLOB_HELPER_SCRIPT,METADATA_WORKSPACE_ID_KEY,SANDBOX_WORKDIR,- bootstrap_commands,- build_source_tarball,- log_bootstrap_attempt,- render_install_agentscope_cmd_dev,- render_install_agentscope_cmd_released,)from ._e2b_backend import E2BBackend@@ -97,12 +83,11 @@ class E2BWorkspace(SandboxedWorkspaceBase):not retained as instance state past :meth:`initialize`."""- _glob_helper_path = GLOB_HELPER_SCRIPT_gateway_home = GATEWAY_HOME- _gateway_config = GATEWAY_CONFIG- _gateway_log = GATEWAY_LOG- _gateway_script = GATEWAY_SCRIPT- _gateway_python = GATEWAY_VENV_PY+ # E2B ``base`` template already ships Python + curl, so every+ # bootstrap step is expected to complete inside 10 minutes even on+ # the slowest CI runners.+ _bootstrap_cmd_timeout = 600.0def __init__(self,@@ -186,28 +171,15 @@ class E2BWorkspace(SandboxedWorkspaceBase):async def _provision_backend(self) -> None:"""Reattach or create the sandbox and bind the backend.- First-time provisioning also runs bootstrap (uv → gateway- venv → agentscope → gateway script upload). Bootstrap is- detected by ``files.exists(GATEWAY_SCRIPT)`` and every step- is idempotent so an interrupted bootstrap re-runs cleanly.+ First-time bootstrap (uv → gateway venv → agentscope → gateway+ script upload) is driven by+ :meth:`SandboxedWorkspaceBase._ensure_bootstrapped` once+ ``initialize`` has bound the backend; every step is idempotent+ so an interrupted bootstrap re-runs cleanly."""await self._attach_or_create_sandbox()self._backend = E2BBackend(self._sandbox, workdir=SANDBOX_WORKDIR)- # If the gateway script is missing, the sandbox is fresh (or a- # prior bootstrap was interrupted). Every bootstrap step is- # idempotent so re-running is safe.- if not await self._sandbox.files.exists(GATEWAY_SCRIPT):- # The backend pins ``cwd=SANDBOX_WORKDIR`` so the very- # first bootstrap command (a ``mkdir -p``) would fail- # before it ran when the dir does not yet exist. Use- # ``cwd="/"`` to break the chicken-and-egg.- await self._backend.exec_shell(- ["mkdir", "-p", SANDBOX_WORKDIR],- cwd="/",- )- await self._run_bootstrap()-async def _teardown_backend(self) -> None:"""Pause the sandbox (keep filesystem) and drop the handle.@@ -366,51 +338,39 @@ class E2BWorkspace(SandboxedWorkspaceBase):# ── internals: bootstrap ────────────────────────────────────- async def _run_bootstrap(self) -> None:- """Provision a fresh sandbox: uv → venv → agentscope → script.+ def _bootstrap_commands(self) -> list[str]:+ """Shell commands that provision this E2B sandbox once.- Each command runs through :meth:`_exec`; a non-zero exit- raises :class:`RuntimeError` with the captured stderr so- startup failures are visible in logs (mirroring the docker- build-tail strategy).- """- if _is_released_install():- log_bootstrap_attempt(self.workspace_id, "released")- install_cmd = render_install_agentscope_cmd_released(- _agentscope_version(),- )- else:- log_bootstrap_attempt(self.workspace_id, "dev")- tar_bytes = build_source_tarball()- await self._backend.write_file(DEV_SRC_TAR, tar_bytes)- install_cmd = render_install_agentscope_cmd_dev()-- commands = bootstrap_commands(- extra_pip=self.extra_pip,- install_agentscope_cmd=install_cmd,- )- for cmd in commands:- r = await self._backend.exec_shell(- ["sh", "-c", cmd],- timeout=600.0,- )- if not r.ok():- raise RuntimeError(- f"E2BWorkspace bootstrap failed (exit {r.exit_code}) "- f"for: {cmd!r}\n"- f"stderr: {r.stderr.decode(errors='replace')}\n"- f"stdout: {r.stdout.decode(errors='replace')}",- )-- # Upload helper scripts used by builtin tools.- await self._backend.write_file(- GLOB_HELPER_SCRIPT,- _read_glob_helper_bytes(),- )+ Only runs when the gateway script is missing (fresh sandbox or+ a prior bootstrap that was interrupted). Every step is+ idempotent so a resumed sandbox can re-run cleanly.- # Upload the gateway script last so its presence is the- # idempotency marker we probe in :meth:`initialize`.- await self._backend.write_file(- GATEWAY_SCRIPT,- _read_gateway_script_bytes(),- )+ ``--no-deps`` on agentscope is mandatory: the gateway only+ imports :class:`agentscope.mcp.MCPClient` whose transitive+ needs (``mcp / pydantic / httpx``) are already installed via+ the gateway base requirements. Pulling the full dep tree+ drags in heavy / Rust-built packages the E2B image cannot+ compile.+ """+ pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)+ # Quote every requirement string so entries with spaces or+ # shell metacharacters cannot break the ``sh -c`` command or+ # become a command-injection vector inside the sandbox.+ pip_args = " ".join(shlex.quote(p) for p in pip_pkgs)++ return [+ # 1. System deps + uv installer, both via sudo so uv lands+ # at /usr/local/bin (on PATH — no absolute-path plumbing+ # needed downstream).+ "sudo apt-get update -qq "+ "&& sudo apt-get install -y --no-install-recommends ripgrep "+ "&& sudo rm -rf /var/lib/apt/lists/*",+ "curl -LsSf https://astral.sh/uv/install.sh "+ "| sudo env UV_INSTALL_DIR=/usr/local/bin "+ "INSTALLER_NO_MODIFY_PATH=1 sh",+ # 2. Gateway venv + base requirements + agentscope.+ f"uv venv {self._gateway_venv}",+ f"uv pip install --python {self._gateway_python} {pip_args}",+ f"uv pip install --python {self._gateway_python} "+ f"--no-deps 'agentscope'",+ ]diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.pyindex 59de89f34..6749c6f2e 100644--- a/src/agentscope/workspace/_gateway_client.py+++ b/src/agentscope/workspace/_gateway_client.py@@ -2,44 +2,23 @@"""Host-side client for the in-sandbox MCP gateway, driven through``backend.exec_shell``.-Three classes live here:--* :class:`GatewayClient` — workspace-side facade over the gateway's- ``/health`` and ``/mcps`` endpoints. Used by :class:`DockerWorkspace`- and :class:`E2BWorkspace` for top-level operations.+Three classes:+* :class:`GatewayClient` — workspace-side facade over ``/health`` and+ ``/mcps``. Used by the sandboxed workspaces for top-level operations.* :class:`GatewayMCPClient` — an :class:`MCPClient` subclass whose- protocol behaviour is replaced by gateway-relayed calls. The field- surface is identical to ``MCPClient`` (instances are built from- ``MCPClient.model_dump()`` data the gateway returns), so callers- that ``model_dump()`` it round-trip cleanly. Local stdio/HTTP- session machinery is bypassed: ``model_post_init`` is a no-op,- ``connect`` registers via ``POST /mcps``, ``close`` deregisters via- ``DELETE /mcps/{name}``, and ``list_raw_tools`` / ``get_tool`` fetch- / wrap upstream tools.--* :class:`GatewayMCPTool` — :class:`ToolBase` subclass whose- ``__call__`` invokes the upstream tool via- ``POST /mcps/{name}/tools/{tool}`` and reconstructs the returned- ``ToolChunk``.--Transport------------Unlike a normal HTTP client, **every** request runs **inside the-sandbox**. The host serialises the request body (if any) to a tempfile-via :meth:`BackendBase.write_file`, then spawns a tiny Python script-through :meth:`BackendBase.exec_shell` (see-:mod:`agentscope.workspace._gateway_shim`) which performs the actual-``urllib.request`` call against the gateway's loopback port, writes a-JSON envelope to stdout, and exits 0. The host parses the envelope and-reconstructs status code + response bytes (base64-decoded inline, or-read back from a sandbox tempfile for large payloads).--This removes the host→sandbox network reachability requirement-(previously satisfied by Docker port mapping or the E2B HTTPS proxy);-the gateway listens on a fixed loopback port inside the sandbox and is-no longer reachable from the host at all.+ protocol behaviour is replaced by gateway-relayed calls. Local+ stdio/HTTP machinery is bypassed; ``model_post_init`` is a no-op;+ ``connect`` / ``close`` / ``list_raw_tools`` / ``get_tool`` all+ round-trip through ``/mcps``.+* :class:`GatewayMCPTool` — :class:`ToolBase` whose ``__call__``+ invokes the upstream tool via ``POST /mcps/{name}/tools/{tool}``.++Every request runs inside the sandbox: the host writes an optional+body to a sandbox tempfile, spawns a small Python shim via+:meth:`BackendBase.exec_shell` (see :mod:`._gateway_shim`), and parses+the JSON envelope the shim prints on stdout. No host→sandbox network+reachability is required — the gateway only binds sandbox loopback."""from __future__ import annotations@@ -52,6 +31,7 @@ from typing import TYPE_CHECKING, Anyimport mcp.typesfrom pydantic import PrivateAttr+from .._logging import loggerfrom ..mcp import MCPClientfrom ..message import ToolResultStatefrom ..permission import (@@ -92,27 +72,20 @@ class GatewayMCPTool(ToolBase):) -> None:"""Build a gateway-backed MCP tool.- The instance mirrors the field surface of- :class:`agentscope.tool.MCPTool` (``name``, ``description``,- ``input_schema``, ``is_read_only``, …) so the host-side toolkit- cannot tell the difference between a local MCP tool and one- that forwards through the in-sandbox gateway.+ Mirrors the field surface of :class:`agentscope.tool.MCPTool`+ so the toolkit cannot tell the difference.Args:mcp_name (`str`):- Name of the upstream MCP server this tool belongs to.- Used both for the visible ``mcp__{mcp}__{tool}`` name- and for the gateway URL path.+ Upstream MCP server name; drives the visible+ ``mcp__{mcp}__{tool}`` name and the URL path.tool (`mcp.types.Tool`):Raw upstream tool descriptor as returned by the gateway.- Its ``name`` is the upstream-side identifier (no- ``mcp__`` prefix), ``inputSchema`` is forwarded verbatim,- and ``annotations.readOnlyHint`` drives the permission+ ``inputSchema`` is forwarded verbatim;+ ``annotations.readOnlyHint`` drives the permissionpolicy.gateway (`GatewayClient`):- The workspace-side gateway facade that owns the- backend handle, gateway port, and bearer token. All- tool invocations are dispatched through its+ Facade dispatching every call through:meth:`GatewayClient.exec_request`."""self.mcp_name = mcp_name@@ -140,10 +113,8 @@ class GatewayMCPTool(ToolBase):*_args: Any,**_kwargs: Any,) -> PermissionDecision:- """Default policy: read-only tools auto-allow, everything else- defers to the user via ``ASK``. Mirrors- :class:`agentscope.tool.MCPTool.check_permissions` so toolkit- callers see identical behaviour through the gateway.+ """Read-only tools auto-allow; everything else defers via+ ``ASK``. Mirrors :meth:`MCPTool.check_permissions`."""if self.is_read_only:return PermissionDecision(@@ -156,27 +127,12 @@ class GatewayMCPTool(ToolBase):)async def __call__(self, **kwargs: Any) -> ToolChunk:- """Invoke the upstream tool by relaying- ``POST /mcps/{mcp}/tools/{tool}`` to the gateway via the- sandbox shim.-- Args:- **kwargs:- Tool arguments forwarded as the JSON body's- ``arguments`` field; the gateway re-dispatches them to- the upstream MCP session.-- Returns:- `ToolChunk`:- The reconstructed chunk returned by the upstream tool.- 4xx / 5xx responses are surfaced as a- ``ToolChunk(state=ERROR)`` so the agent loop can reason- about the failure instead of crashing.+ """Relay ``POST /mcps/{mcp}/tools/{tool}`` to the gateway.- Raises:- `RuntimeError`:- If the gateway returns 2xx but no ``chunk`` payload- (protocol violation on the gateway side).+ 4xx / 5xx responses come back as ``ToolChunk(state=ERROR)`` so+ the agent loop can reason about failure. Raises+ :class:`RuntimeError` only if the gateway returns 2xx with no+ ``chunk`` payload (protocol violation)."""status, body = await self._gateway.exec_request("POST",@@ -218,14 +174,8 @@ class GatewayMCPClient(MCPClient):_gateway: "GatewayClient | None" = PrivateAttr(default=None)def model_post_init(self, __context: Any) -> None:- """Skip the parent's stdio/HTTP client preparation.-- For a real :class:`MCPClient`, ``model_post_init`` builds the- local stdio context manager (or wires up an HTTP client) so- the in-process session can be opened. For- :class:`GatewayMCPClient` all MCP-side work happens inside the- gateway sandbox; the host-side proxy needs no local session- machinery, so this override is a no-op.+ """No-op — the parent builds local stdio/HTTP transport, which+ the gateway-relayed client does not need."""return@@ -239,30 +189,19 @@ class GatewayMCPClient(MCPClient):) -> None:"""Wire this client to a gateway facade.- :class:`GatewayMCPClient` is normally produced by- ``model_validate(spec)`` over a dict returned by the gateway's- ``GET /mcps`` endpoint — that step recovers the public field- surface but leaves all transport-related private attributes- empty. ``attach`` injects them in a single call so subsequent- :meth:`connect`, :meth:`close`, :meth:`list_raw_tools`, and- :meth:`get_tool` can talk to the gateway. It is the only- supported way to populate the transport state from outside the- class — encapsulating the writes here keeps callers free of- ``protected-access`` warnings.+ Instances come out of ``model_validate(spec)`` with the public+ field surface set but no transport wiring. ``attach`` injects+ it so :meth:`connect` / :meth:`close` / :meth:`list_raw_tools`+ can talk to the gateway.Args:gateway (`GatewayClient`):- The workspace-side gateway facade that owns the- sandbox backend handle, gateway port, and bearer- token. All subsequent calls are dispatched through its+ Facade dispatching calls through:meth:`GatewayClient.exec_request`.connected (`bool`, defaults to `False`):When ``True``, mark this client as already connected- (i.e. the gateway is already maintaining the upstream- session). Used by :meth:`GatewayClient.list_mcps` for- clients that came back from the gateway as registered.- Leave ``False`` when the caller will call- :meth:`connect` themselves.+ (used by :meth:`GatewayClient.list_mcps` for entries+ the gateway is already serving)."""self._gateway = gatewayif connected:@@ -272,15 +211,12 @@ class GatewayMCPClient(MCPClient):"""Register this MCP on the gateway via ``POST /mcps``.All MCPs (stateless and stateful) must be registered so that- ``/mcps/{name}/tools/{tool}`` can locate the client. For- stateful MCPs the gateway additionally opens the upstream- session before responding.+ ``/mcps/{name}/tools/{tool}`` can locate the client.Raises:`RuntimeError`:- If the client is already connected, the gateway is- unreachable, or the gateway returns a 4xx/5xx- response.+ Already connected, gateway unreachable, or gateway+ returned 4xx/5xx."""if self._is_connected:raise RuntimeError(@@ -302,21 +238,12 @@ class GatewayMCPClient(MCPClient):self._is_connected = Trueasync def close(self, ignore_errors: bool = True) -> None:- """Deregister this MCP from the gateway via- ``DELETE /mcps/{name}``.-- All MCPs are deregistered from the gateway registry; the- gateway additionally closes the upstream session for stateful- clients before responding.+ """Deregister this MCP via ``DELETE /mcps/{name}``.Args:ignore_errors (`bool`, defaults to `True`):- When ``True`` (the default), suppress both "not- connected" precondition failures and gateway-side- 4xx/5xx responses; when ``False`` such conditions- raise :class:`RuntimeError`. Mirrors- :meth:`MCPClient.close` so callers can use the same- shutdown idiom regardless of transport.+ Suppress "not connected" precondition and gateway+ 4xx/5xx. Mirrors :meth:`MCPClient.close`."""if not self._is_connected:if ignore_errors:@@ -343,24 +270,17 @@ class GatewayMCPClient(MCPClient):# ── tool discovery ────────────────────────────────────────────async def list_raw_tools(self) -> list[mcp.types.Tool]:- """Fetch the upstream tool list via ``GET /mcps/{name}/tools``.+ """Fetch upstream tools via ``GET /mcps/{name}/tools``.- Returns the raw :class:`mcp.types.Tool` descriptors the gateway- forwarded — i.e. with their **upstream** names (no ``mcp__``- prefix) so the inherited :meth:`list_tools` / :meth:`get_tool`- path can re-wrap them through :meth:`_wrap_tool` exactly as a- local :class:`MCPClient` would. The full unfiltered list is- cached on ``_cached_tools`` first; the returned list then has- ``enable_tools`` / ``disable_tools`` filtering applied- identically to :meth:`MCPClient.list_raw_tools`.-- Returns:- `list[mcp.types.Tool]`:- The upstream-named, post-filter tool descriptors.+ Returns raw :class:`mcp.types.Tool` descriptors (upstream names,+ no ``mcp__`` prefix) so the inherited :meth:`get_tool` can+ re-wrap them like a local :class:`MCPClient`. The unfiltered+ list is cached; the returned list has ``enable_tools`` /+ ``disable_tools`` applied.Raises:`RuntimeError`:- If the gateway returns a non-2xx response.+ Gateway returned non-2xx."""assert self._gateway is not Nonestatus, body = await self._gateway.exec_request(@@ -377,8 +297,8 @@ class GatewayMCPClient(MCPClient):raw_tools = [mcp.types.Tool.model_validate(d) for d in data]self._cached_tools = raw_tools- # Honour the same enable/disable filtering MCPClient does- # locally — gateway returns the unfiltered upstream view.+ # Gateway returns the unfiltered upstream view; honour the same+ # enable/disable filtering ``MCPClient`` applies locally.if self.enable_tools is not None:raw_tools = [t for t in raw_tools if t.name in self.enable_tools]if self.disable_tools is not None:@@ -394,26 +314,13 @@ class GatewayMCPClient(MCPClient):"""Look up a single tool by upstream name and wrap it.Falls back to :meth:`list_raw_tools` on cache miss, then- searches ``_cached_tools`` (which holds the **unfiltered**- upstream view) so tools that ``enable_tools`` /+ searches the unfiltered cache so tools that ``enable_tools`` /``disable_tools`` would have hidden are still resolvable —- matching :meth:`MCPClient.get_tool`'s behaviour.-- Args:- name (`str`):- Upstream tool name (no ``mcp__`` prefix). The returned- :class:`GatewayMCPTool` exposes the prefixed form via- its own ``name`` attribute.-- Returns:- `GatewayMCPTool`:- A fresh wrapper around the upstream descriptor, ready- to be ``await``-ed or registered with a toolkit.+ matching :meth:`MCPClient.get_tool`.Raises:`ValueError`:- If no tool with that upstream name exists on the- gateway side.+ No tool with that upstream name exists on the gateway."""if self._cached_tools is None:await self.list_raw_tools()@@ -429,16 +336,6 @@ class GatewayMCPClient(MCPClient):def _wrap_tool(self, tool: mcp.types.Tool) -> GatewayMCPTool:"""Build a :class:`GatewayMCPTool` bound to this client'sgateway facade.-- Args:- tool (`mcp.types.Tool`):- Raw upstream tool descriptor (typically pulled out of- ``_cached_tools``).-- Returns:- `GatewayMCPTool`:- The host-side wrapper that will relay every call- through the gateway facade."""assert self._gateway is not Nonereturn GatewayMCPTool(@@ -464,64 +361,61 @@ class GatewayClient:self,backend: "BackendBase",gateway_port: int,- token: str,*,timeout: float | None = None,inline_limit: int = BODY_INLINE_LIMIT,tmp_dir: str = SANDBOX_TMP_DIR,+ gateway_log_path: str | None = None,) -> None:"""Build a workspace-side gateway facade.Args:backend (`BackendBase`):- The workspace's backend handle. Every gateway request- runs as ``backend.exec_shell([...])`` inside the- sandbox (Docker container or E2B sandbox).+ Workspace backend; every request runs as+ ``backend.exec_shell([...])`` inside the sandbox.gateway_port (`int`):TCP port the gateway listens on inside the sandbox.- The URL dialed by the shim is always- ``http://127.0.0.1:<gateway_port>``.- token (`str`):- Bearer token shared with the gateway via its config- file. Sent as ``Authorization: Bearer …`` on every- request. Pass an empty string to skip auth (useful- only in tests).+ The shim dials ``http://127.0.0.1:<gateway_port>``.timeout (`float | None`, defaults to `None`):- Per-request timeout in seconds, passed straight through- to :meth:`BackendBase.exec_shell`. The shim itself- does not apply an HTTP-level timeout — long-running- MCP tools are limited only by the backend exec- timeout. ``None`` waits indefinitely.+ Per-request timeout forwarded to+ :meth:`BackendBase.exec_shell`; ``None`` waits+ indefinitely.inline_limit (`int`, defaults to `BODY_INLINE_LIMIT`):- Threshold (in bytes) below which response bodies ride- inline through stdout as base64. Larger bodies are- spilled to a sandbox tempfile and fetched via- :meth:`BackendBase.read_file` to avoid loading multi-MB- payloads through the exec stdout channel.+ Response bodies above this size spill through a sandbox+ tempfile rather than base64-inline through stdout.tmp_dir (`str`, defaults to `SANDBOX_TMP_DIR`):- Sandbox-side directory used for both request body- tempfiles (host → sandbox) and oversized response- spills (sandbox → host). Must be writable by the- gateway process; ``/tmp`` works on every supported- image.+ Sandbox directory for request/response tempfiles. Must+ be writable by the gateway process.+ gateway_log_path (`str | None`, defaults to `None`):+ Sandbox-side path of the gateway's stdout/stderr log+ file. When set, :meth:`exec_request` failures trigger+ a ``/health`` probe and — if the gateway is+ unreachable — a tail of this log is emitted at+ ``ERROR`` level to help diagnose crashes."""self.backend = backendself.gateway_port = gateway_port- self.token = tokenself.timeout = timeoutself.inline_limit = inline_limitself.tmp_dir = tmp_dir+ self.gateway_log_path = gateway_log_path+ # Health-probe timeout is kept short so the diagnostic path adds+ # little latency to the failing request. It only runs on the+ # error path, never on the hot path.+ self._health_probe_timeout: float = 5.0+ # Number of bytes of the gateway log to tail into the error+ # log on unreachable-gateway diagnosis.+ self._log_tail_bytes: int = 4000async def health(self) -> bool:- """Probe ``/health`` — used by the workspace to wait for- readiness.-- Returns:- `bool`:- ``True`` iff the gateway answered ``200``. Any other- outcome (shim transport failure, non-200 status)- returns ``False``; callers are expected to retry until- this flips.+ """Probe ``/health``. ``True`` iff the gateway answered 200;+ any other outcome (shim transport failure, non-200) → ``False``.+ Callers retry until this flips.++ The ``/health`` path is treated specially by+ :meth:`exec_request` — it never triggers the failure+ diagnostic, so a dead gateway does not recursively probe+ itself."""try:status, _ = await self.exec_request("GET", "/health")@@ -530,23 +424,15 @@ class GatewayClient:return status == 200async def list_mcps(self) -> list[GatewayMCPClient]:- """Fetch every MCP currently registered on the gateway.-- The returned clients are marked as already connected (via- :meth:`GatewayMCPClient.attach`'s ``connected=True``) because- the gateway is already maintaining their upstream sessions —- the host should not invoke :meth:`GatewayMCPClient.connect`- again.+ """Fetch every MCP the gateway is currently serving.- Returns:- `list[GatewayMCPClient]`:- One transport-wired client per registered MCP. The- workspace's :meth:`list_mcps` implementation surfaces- this list straight to its consumer.+ Returned clients are marked already-connected (via+ :meth:`GatewayMCPClient.attach`) — the gateway is already+ maintaining their upstream sessions.Raises:`RuntimeError`:- If the gateway returns a non-2xx response.+ Gateway returned non-2xx."""status, body = await self.exec_request("GET", "/mcps")if status >= 400:@@ -564,45 +450,22 @@ class GatewayClient:) -> GatewayMCPClient:"""Build a :class:`GatewayMCPClient` wired to this gateway.- Reconstructs the public field surface from ``spec`` via- :meth:`MCPClient.model_validate`, then hands the transport- handle to the new client through- :meth:`GatewayMCPClient.attach`. Doing the wiring through- ``attach`` keeps the writes inside the target class and avoids- ``protected-access`` warnings on every assignment.-Args:spec (`dict[str, Any]`):- A dict produced by ``MCPClient.model_dump(mode="json")``- — typically the body returned by the gateway's- ``GET /mcps`` endpoint, or built from user input by- ``DockerWorkspace.add_mcp``.+ ``MCPClient.model_dump(mode="json")`` payload — either+ from ``GET /mcps`` or from user input via ``add_mcp``.connected (`bool`, defaults to `False`):- When ``True``, mark the new client as already connected- so :meth:`GatewayMCPClient.connect` need not run again.- Set by :meth:`list_mcps` for clients that came back- from the gateway already registered. Leave ``False``- for fresh clients the caller will explicitly- ``await client.connect()`` on (the ``add_mcp`` path).-- Returns:- `GatewayMCPClient`:- A pydantic-valid client whose transport state is fully- populated. Stateful clients still require an explicit- ``await client.connect()`` unless ``connected=True``.+ Mark the client as already-connected. Set by+ :meth:`list_mcps`; leave ``False`` when the caller will+ ``await client.connect()`` itself."""client = GatewayMCPClient.model_validate(spec)client.attach(self, connected=connected)return clientasync def aclose(self) -> None:- """No-op kept for API parity with the previous httpx-based- client.-- The new transport holds no host-side resources (every call is- a one-shot ``exec_shell``), so there is nothing to close. The- method stays so callers can keep their existing shutdown- idiom.+ """No-op kept for API parity — the transport holds no host-side+ resources, but callers keep their shutdown idiom."""return@@ -617,48 +480,38 @@ class GatewayClient:) -> tuple[int, bytes]:"""Relay one HTTP request through the sandbox.- Mechanics:-- 1. If ``body`` is given, JSON-encode it and write it to- ``${tmp_dir}/<uuid>.json`` inside the sandbox via- :meth:`BackendBase.write_file`.- 2. Run ``python3 -c <SHIM_SCRIPT> <method> <url> <token>- <body_file_or_""> <inline_limit> <tmp_dir>`` via- :meth:`BackendBase.exec_shell`. The shim performs the- ``urllib.request`` call against the gateway's loopback port- and prints a JSON envelope to stdout.- 3. Parse the envelope. Inline bodies are base64-decoded;- oversized bodies are pulled back from- ``envelope["body_file"]`` via :meth:`BackendBase.read_file`- and then deleted.-- Both the request and response temp files are best-effort- cleaned up so a crash does not leak files into the sandbox's- ``${tmp_dir}``.+ Writes ``body`` (if any) to a sandbox tempfile, runs+ ``python3 -c <SHIM_SCRIPT> ...`` inside the sandbox via+ :meth:`BackendBase.exec_shell`, and parses the JSON envelope+ the shim prints on stdout. Inline bodies are base64-decoded;+ oversized bodies are pulled back through ``body_file``. Request+ and response tempfiles are best-effort cleaned up.++ On any failure — shim non-zero exit, non-JSON stdout, or+ ``status == -1`` transport error — a self-diagnostic step+ probes ``/health`` and, if the gateway is unreachable, tails+ :attr:`gateway_log_path` at ``ERROR`` level so the real crash+ cause reaches the host log stream. The original exception is+ always re-raised so the caller's error contract is unchanged.+ The ``/health`` path itself skips diagnosis to avoid recursing+ on a dead gateway.Args:method (`str`):HTTP verb (``GET`` / ``POST`` / ``DELETE``).path (`str`):- Path-only URL relative to the gateway root, e.g.- ``/mcps`` or ``/mcps/<name>/tools/<tool>``. Always- starts with ``/``.+ Path-only URL, e.g. ``/mcps/<name>/tools/<tool>``.body (`Any`, optional):- JSON-serializable request body. ``None`` (the default)- means no body — typical for ``GET`` / ``DELETE``.+ JSON-serializable request body; ``None`` for no body.Returns:`tuple[int, bytes]`:- The HTTP status code returned by the gateway, paired- with the raw response body bytes (always decoded;- callers ``json.loads`` it themselves when needed).+ Status code + raw response bytes (callers decode).Raises:`RuntimeError`:- If the shim crashed (non-zero exit code, non-JSON- stdout) or reported a transport failure- (``status == -1`` — gateway unreachable, urllib- error, …).+ Shim crash (non-zero exit / non-JSON stdout) or+ transport failure (``status == -1``)."""body_file = ""wrote_body_file: str | None = None@@ -671,80 +524,139 @@ class GatewayClient:)try:- result: "ExecResult" = await self.backend.exec_shell(- [- "python3",- "-c",- SHIM_SCRIPT,- method,- f"http://127.0.0.1:{self.gateway_port}{path}",- self.token or "",- body_file,- str(self.inline_limit),- self.tmp_dir,- ],- timeout=self.timeout,- )- finally:- if wrote_body_file is not None:+ try:+ result: "ExecResult" = await self.backend.exec_shell(+ [+ "python3",+ "-c",+ SHIM_SCRIPT,+ method,+ f"http://127.0.0.1:{self.gateway_port}{path}",+ body_file,+ str(self.inline_limit),+ self.tmp_dir,+ ],+ timeout=self.timeout,+ )+ finally:+ if wrote_body_file is not None:+ try:+ await self.backend.delete_path(wrote_body_file)+ except Exception:+ pass++ if result.exit_code != 0:+ raise RuntimeError(+ f"gateway shim exited with {result.exit_code}: "+ f"{result.stderr.decode(errors='replace')[:500]}",+ )++ try:+ env = json.loads(result.stdout)+ except Exception as e:+ raise RuntimeError(+ "gateway shim produced non-JSON stdout: "+ f"{result.stdout[:200]!r}",+ ) from e++ status = int(env["status"])+ if status == -1:+ raise RuntimeError(+ "gateway request failed: "+ f"{env.get('error', 'unknown error')}",+ )++ if "body_file" in env:+ spilled = env["body_file"]+ body_bytes = await self.backend.read_file(spilled)try:- await self.backend.delete_path(wrote_body_file)+ await self.backend.delete_path(spilled)except Exception:pass+ else:+ body_bytes = base64.b64decode(env.get("body", ""))++ return status, body_bytes+ except Exception as exc:+ # ``/health`` never triggers diagnosis — otherwise a dead+ # gateway would recursively probe itself.+ if path != "/health":+ await self._diagnose_failure(method, path, exc)+ raise++ async def _diagnose_failure(+ self,+ method: str,+ path: str,+ exc: BaseException,+ ) -> None:+ """Best-effort post-failure diagnostic invoked by+ :meth:`exec_request` on any request failure.- if result.exit_code != 0:- raise RuntimeError(- f"gateway shim exited with {result.exit_code}: "- f"{result.stderr.decode(errors='replace')[:500]}",- )+ Probes ``/health`` (via :meth:`health`, which short-circuits+ the diagnostic path); if the gateway does not answer, emits+ the tail of :attr:`gateway_log_path` at ``ERROR`` level so the+ real crash cause reaches the host log stream. Every step is+ guarded — diagnosis must never raise, so the caller's original+ exception is always the one that surfaces.+ Args:+ method (`str`):+ HTTP verb of the failed request (for log context).+ path (`str`):+ Path of the failed request (for log context).+ exc (`BaseException`):+ Original exception raised by the shim call (for log+ context; not re-raised here).+ """try:- env = json.loads(result.stdout)- except Exception as e:- raise RuntimeError(- "gateway shim produced non-JSON stdout: "- f"{result.stdout[:200]!r}",- ) from e-- status = int(env["status"])- if status == -1:- raise RuntimeError(- "gateway request failed: "- f"{env.get('error', 'unknown error')}",- )+ healthy = await self.health()+ except Exception: # pragma: no cover — defensive+ healthy = False++ if healthy:+ # Gateway is up — the failure came from the request itself+ # (bad payload, upstream MCP error, etc.). Original error+ # is enough context.+ return++ logger.error(+ "Gateway unreachable during %s %s: %s. Probing /health failed. "+ "Attempting to tail gateway log at %r ...",+ method,+ path,+ exc,+ self.gateway_log_path,+ )- if "body_file" in env:- spilled = env["body_file"]- body_bytes = await self.backend.read_file(spilled)- try:- await self.backend.delete_path(spilled)- except Exception:- pass- else:- body_bytes = base64.b64decode(env.get("body", ""))+ if self.gateway_log_path is None:+ return- return status, body_bytes+ try:+ log_bytes = await self.backend.read_file(self.gateway_log_path)+ except Exception as read_exc: # noqa: BLE001+ logger.error(+ "Failed to read gateway log at %r: %s",+ self.gateway_log_path,+ read_exc,+ )+ return++ tail = log_bytes[-self._log_tail_bytes :].decode(errors="replace")+ logger.error(+ "Gateway log tail (last %d bytes of %r):\n%s",+ len(tail),+ self.gateway_log_path,+ tail,+ )# ── module-private utilities ───────────────────────────────────────def _safe_detail(status: int, body: bytes) -> str:- """Best-effort extraction of an HTTPException-style detail from a- gateway response body.-- Args:- status (`int`):- HTTP status code returned by the gateway.- body (`bytes`):- Raw response body bytes — typically a JSON object from- FastAPI's ``HTTPException``, but tolerate anything.-- Returns:- `str`:- A human-readable diagnostic that always starts with- ``HTTP <status>:`` so it slots into the same exception /- ``ToolChunk`` messages as the previous httpx-based code.+ """Best-effort ``HTTP <status>: <detail>`` string from a gateway+ error response — tolerates non-JSON, missing ``detail``, etc."""try:data = json.loads(body)diff --git a/src/agentscope/workspace/_gateway_shim.py b/src/agentscope/workspace/_gateway_shim.pyindex 31d49d479..5ac4052a3 100644--- a/src/agentscope/workspace/_gateway_shim.py+++ b/src/agentscope/workspace/_gateway_shim.py@@ -1,103 +1,58 @@# -*- coding: utf-8 -*--"""Tiny Python script that runs **inside the sandbox** to relay a single-HTTP request to the gateway, plus the host-side helpers that drive it-through :class:`agentscope.tool.BackendBase.exec_shell`.+"""Tiny Python script that runs inside the sandbox to relay a single+HTTP request to the gateway, plus the host-side constants that drive it+through :meth:`BackendBase.exec_shell`.-Architectural shift----------------------Previously the workspace reached its in-sandbox MCP gateway through a-host-visible URL — DockerWorkspace mapped the gateway TCP port to a-random host port and dialed ``http://127.0.0.1:<host_port>``;-E2BWorkspace used ``sandbox.get_host(port)`` + ``X-Access-Token`` to-ride E2B's HTTPS proxy. Both flows require host → sandbox network-reachability.--The new flow is: **every request runs inside the sandbox**. The host-spawns a short Python script there via ``backend.exec_shell`` which-makes the call against the gateway's loopback port using nothing but-the standard library (``urllib.request``), serialises the response into-a self-describing JSON envelope, and prints it to stdout. The host-reads stdout back as an ``ExecResult`` and reconstructs the status-code and body bytes (response headers are not transmitted — callers-consume JSON bodies directly).--Why ``python3 -c`` (and not ``curl``)----------------------------------------* ``python3`` is guaranteed by every backend we support — the gateway- itself is a Python process, and our Dockerfile sets up a venv. We- cannot make the same guarantee for ``curl`` on third-party E2B- templates.-* No new dependency: ``urllib.request`` is stdlib.-* argv stays free of shell-special characters; the whole script is one- argv element delivered to ``python3 -c`` via the backend's argv-based- ``exec_shell`` (Docker passes ``cmd=`` directly; E2B's ``shlex.quote``- POSIX-quotes the element). No interpolation, no escape bugs.--Wire format--------------Stdout always carries a single JSON object — even on transport failure-the shim exits 0 and reports the error in the envelope, so callers-need only one parse path::+Flow: host spawns ``python3 -c <SHIM_SCRIPT> ...`` via ``exec_shell``;+the shim calls the gateway's loopback port using ``urllib.request`` and+emits one JSON envelope on stdout::{"status": <int>, # HTTP status, or -1 on error- "body": "<base64-of-bytes>", # only when status >= 0 and small- "body_file": "<sandbox-path>", # only when body is large+ "body": "<base64-of-bytes>", # inline when small+ "body_file": "<sandbox-path>", # spilled when > inline_limit"error": "<short message>" # only when status == -1}-For typical MCP tool calls (≤ 1 MiB) the body rides inline as base64.-For exceptional payloads (> ``BODY_INLINE_LIMIT`` bytes) the shim-spills to ``/tmp/<uuid>.bin`` and returns the path; the caller reads-that file via ``backend.read_file`` and deletes it. This avoids loading-multi-megabyte responses through stdout, which both ``aiodocker`` and-``e2b`` accumulate in host RAM.+The gateway listens only on the sandbox's loopback; the host has no+network reachability to it. The shim relies on ``python3`` (which the+gateway venv already needs) rather than ``curl`` because we cannot+assume ``curl`` on every backend image."""from __future__ import annotations-# Request bodies larger than this go through a temp file rather than-# riding through stdout. 4 MiB comfortably covers any real MCP tool-# result without paying the disk-roundtrip cost on the common path.+# Bodies larger than this spill to a tempfile so we don't accumulate+# multi-MB payloads in the exec stdout channel.BODY_INLINE_LIMIT = 4 * 1024 * 1024-# Where the shim spills oversized payloads. ``/tmp`` is writable on-# every backend image (Docker python:3.11-slim, E2B default templates).+# ``/tmp`` is writable on every backend image we support.SANDBOX_TMP_DIR = "/tmp"-# The shim itself. Embedded as a string so it ships with this module —-# the host always knows the exact source the sandbox is executing.-#-# Conventions kept tight on purpose:-# * stdlib-only;-# * no shebang (we always invoke as ``python3 -c``);-# * exit code is always 0 — failures land in the envelope;-# * stderr is intentionally untouched so a Python traceback (e.g.-# syntax error after a botched edit) is visible to the caller.+# The shim itself, embedded as a string so it ships with this module.+# Conventions: stdlib-only; no shebang (always via ``python3 -c``);+# exit code is always 0 — failures land in the envelope; stderr is+# untouched so a Python traceback (e.g. syntax error after a botched+# edit) surfaces to the caller.## ``sys.argv`` layout when run via ``python3 -c``::## argv[0] = "-c" (Python convention)# argv[1] = method (e.g. "GET" / "POST" / "DELETE")# argv[2] = url (e.g. "http://127.0.0.1:5600/health")-# argv[3] = token (bearer; empty string for none)-# argv[4] = body_file or "" (path readable on the sandbox)-# argv[5] = inline_limit (bytes; int as str)-# argv[6] = tmp_dir (where to spill oversized responses)+# argv[3] = body_file or "" (path readable on the sandbox)+# argv[4] = inline_limit (bytes; int as str)+# argv[5] = tmp_dir (where to spill oversized responses)SHIM_SCRIPT = r"""import sys, json, base64, uuid, osimport urllib.request, urllib.errormethod = sys.argv[1]url = sys.argv[2]-token = sys.argv[3]-body_file = sys.argv[4]-inline_limit = int(sys.argv[5])-tmp_dir = sys.argv[6]+body_file = sys.argv[3]+inline_limit = int(sys.argv[4])+tmp_dir = sys.argv[5]body = Noneif body_file:@@ -105,8 +60,6 @@ if body_file:body = f.read()req = urllib.request.Request(url, data=body, method=method)-if token:- req.add_header("Authorization", "Bearer " + token)if body is not None:req.add_header("Content-Type", "application/json")diff --git a/src/agentscope/workspace/_k8s/__init__.py b/src/agentscope/workspace/_k8s/__init__.pynew file mode 100644index 000000000..68ce0b74a--- /dev/null+++ b/src/agentscope/workspace/_k8s/__init__.py@@ -0,0 +1,12 @@+# -*- coding: utf-8 -*-+"""Kubernetes-backed workspace package.++Re-exports :class:`K8sWorkspace` and :class:`K8sBackend` so callers+can write ``from agentscope.workspace._k8s import K8sWorkspace``+without having to poke at the underlying module layout.+"""++from ._k8s_workspace import K8sWorkspace+from ._k8s_backend import K8sBackend++__all__ = ["K8sWorkspace", "K8sBackend"]diff --git a/src/agentscope/workspace/_k8s/_constants.py b/src/agentscope/workspace/_k8s/_constants.pynew file mode 100644index 000000000..800782890--- /dev/null+++ b/src/agentscope/workspace/_k8s/_constants.py@@ -0,0 +1,42 @@+# -*- coding: utf-8 -*-+"""K8s-specific constants for :class:`K8sWorkspace`.++Path layout (venv, script, log, helper) is derived on the base class+from ``_gateway_home``. This module only carries defaults that cannot+be derived: image, port, apt deps, workdir/gateway_home, and the+K8s-name sanitiser.+"""++import re++#: Default base image. Debian-slim with Python 3.11 — provides+#: ``sh`` (dash), ``tar``, ``base64`` (coreutils) out of the box.+#: Missing ``curl`` and ``ca-certificates`` — installed in bootstrap.+DEFAULT_IMAGE = "python:3.11-slim"++#: Default port the in-Pod gateway listens on.+DEFAULT_GATEWAY_PORT = 5600++#: apt packages the bootstrap installs before uv.+#: ``curl`` + ``ca-certificates`` are needed for the uv installer;+#: ``ripgrep`` is needed by the builtin Grep tool.+SYSTEM_DEPS = ("curl", "ca-certificates", "ripgrep")++#: Pod-side persistent layout — matches Docker/E2B semantics.+POD_WORKDIR = "/workspace"+GATEWAY_HOME = "/root/.agentscope"+++# ── K8s name sanitisation ─────────────────────────────────────────++_K8S_UNSAFE_RE = re.compile(r"[^a-z0-9-]")+++def _k8s_safe_name(workspace_id: str, prefix: str = "as-ws-") -> str:+ """Produce an RFC-1123 compliant K8s resource name.++ Rules: lowercase alphanumeric + hyphens, max 63 characters,+ must not end with a hyphen.+ """+ name = prefix + _K8S_UNSAFE_RE.sub("-", workspace_id.lower())+ return name[:63].rstrip("-")diff --git a/src/agentscope/workspace/_k8s/_k8s_backend.py b/src/agentscope/workspace/_k8s/_k8s_backend.pynew file mode 100644index 000000000..aba775522--- /dev/null+++ b/src/agentscope/workspace/_k8s/_k8s_backend.py@@ -0,0 +1,358 @@+# -*- coding: utf-8 -*-+"""Kubernetes Pod :class:`BackendBase` implementation.++Wraps the ``kubernetes_asyncio`` exec API and tar-stream file transfer+into the three backend primitives (``exec_shell``, ``read_file``,+``write_file``) so that builtin tools (Bash, Read, Write, Edit, Grep,+Glob) can operate inside a K8s Pod transparently.++File I/O uses **tar streams** piped through ``exec`` — the same+mechanism ``kubectl cp`` uses under the hood. This mirrors+:class:`DockerBackend`'s ``get_archive`` / ``put_archive`` approach+and avoids the known reliability issues with raw stdin binary writes+over the ``kubernetes_asyncio`` WebSocket channel+(cf. kubernetes-client/python#1866).+"""++from __future__ import annotations++import asyncio+import io+import posixpath+import shlex+import tarfile+from typing import Any++from ...tool import BackendBase, ExecResult+++class K8sBackend(BackendBase):+ """Backend that delegates to a running Kubernetes Pod.++ Only the three abstract primitives (``exec_shell``, ``read_file``,+ ``write_file``) are implemented here; the derived filesystem helpers+ are inherited from :class:`BackendBase`.++ Args:+ api_client (`Any`):+ A ``kubernetes_asyncio.client.ApiClient`` instance used+ to build ``CoreV1Api`` for exec calls.+ namespace (`str`):+ Kubernetes namespace the Pod lives in.+ pod_name (`str`):+ Name of the target Pod.+ container_name (`str`):+ Container name within the Pod.+ workdir (`str`):+ Default working directory for ``exec_shell`` calls.+ """++ def __init__(+ self,+ api_client: Any,+ namespace: str,+ pod_name: str,+ container_name: str,+ workdir: str,+ ) -> None:+ """Initialize the K8s backend.++ Args:+ api_client (`Any`):+ A ``kubernetes_asyncio.client.ApiClient`` instance.+ namespace (`str`):+ Kubernetes namespace the Pod lives in.+ pod_name (`str`):+ Name of the target Pod.+ container_name (`str`):+ Container name within the Pod.+ workdir (`str`):+ Default working directory for ``exec_shell`` calls.+ """+ self._api_client = api_client+ self._namespace = namespace+ self._pod_name = pod_name+ self._container_name = container_name+ self._workdir = workdir++ # ── exec ───────────────────────────────────────────────────────++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Run a program inside the Pod via WebSocket ``exec``.++ Opens a multiplexed WebSocket channel with+ ``_preload_content=False`` and reads channel-tagged frames to+ separate stdout (channel 1), stderr (channel 2) and the exit+ status (channel 3). ``cwd`` is emulated by wrapping the+ command in ``sh -c 'cd <cwd> && exec "$@"' -- <cmd...>``.++ Args:+ command (`list[str]`):+ Executable path/name followed by its arguments.+ cwd (`str | None`, optional):+ Working directory inside the Pod. When ``None`` the+ backend's default ``workdir`` is used.+ timeout (`float | None`, optional):+ Maximum number of seconds to wait. ``None`` waits+ indefinitely.++ Returns:+ `ExecResult`:+ The captured exit code, stdout, and stderr.+ """+ from kubernetes_asyncio import client as k8s_client+ from kubernetes_asyncio.stream import WsApiClient++ effective_cwd = cwd or self._workdir+ wrapped = [+ "sh",+ "-c",+ f'cd {shlex.quote(effective_cwd)} && exec "$@"',+ "--",+ *command,+ ]++ async def _run() -> ExecResult:+ async with WsApiClient(+ self._api_client.configuration,+ ) as ws_api:+ v1_ws = k8s_client.CoreV1Api(api_client=ws_api)+ ws = await v1_ws.connect_get_namespaced_pod_exec(+ self._pod_name,+ self._namespace,+ command=wrapped,+ container=self._container_name,+ stderr=True,+ stdin=False,+ stdout=True,+ tty=False,+ _preload_content=False,+ )+ stdout_parts: list[bytes] = []+ stderr_parts: list[bytes] = []+ exit_code = 0++ async with ws as sock:+ async for msg in sock:+ if msg.type in (+ 1, # WSMsgType.TEXT+ 2, # WSMsgType.BINARY+ ):+ data = (+ msg.data+ if isinstance(msg.data, bytes)+ else msg.data.encode("utf-8")+ )+ if not data:+ continue+ channel = data[0]+ payload = data[1:]+ if channel == 1: # stdout+ stdout_parts.append(payload)+ elif channel == 2: # stderr+ stderr_parts.append(payload)+ elif channel == 3: # error/status+ import json++ try:+ status = json.loads(+ payload.decode("utf-8"),+ )+ if status.get("status") != "Success":+ exit_code = int(+ status.get(+ "details",+ {},+ )+ .get("causes", [{}])[0]+ .get("message", "1"),+ )+ except (+ json.JSONDecodeError,+ ValueError,+ IndexError,+ KeyError,+ ):+ exit_code = 1+ else:+ break++ return ExecResult(+ exit_code=exit_code,+ stdout=b"".join(stdout_parts),+ stderr=b"".join(stderr_parts),+ )++ if timeout is None:+ return await _run()+ try:+ return await asyncio.wait_for(_run(), timeout=timeout)+ except asyncio.TimeoutError:+ return ExecResult(+ exit_code=-1,+ stdout=b"",+ stderr=b"timed out",+ )++ # ── file I/O (tar-stream, mirroring DockerBackend) ─────────────++ async def read_file(self, path: str) -> bytes:+ """Read a file from the Pod via tar stream extraction.++ Runs ``tar cf - -C <dir> <basename>`` inside the Pod, collects+ the tar bytes from stdout, and extracts the file content. This+ handles binary files correctly — identical to DockerBackend's+ ``get_archive`` approach.++ Args:+ path (`str`):+ Path to the file inside the Pod.++ Returns:+ `bytes`:+ The raw file contents.++ Raises:+ `FileNotFoundError`:+ If the path does not exist inside the Pod.+ """+ dirname = posixpath.dirname(path) or "/"+ basename = posixpath.basename(path)++ result = await self.exec_shell(+ ["tar", "cf", "-", "-C", dirname, basename],+ cwd="/",+ )+ if not result.ok():+ stderr_text = result.stderr.decode(errors="replace")+ if "No such file" in stderr_text or "not found" in stderr_text:+ raise FileNotFoundError(+ f"not found in Pod: {path}",+ )+ raise FileNotFoundError(+ f"not found in Pod: {path} (tar stderr: {stderr_text})",+ )++ try:+ tar = tarfile.open(fileobj=io.BytesIO(result.stdout), mode="r")+ except tarfile.ReadError as exc:+ raise FileNotFoundError(+ f"not found in Pod: {path}",+ ) from exc++ try:+ for member in tar.getmembers():+ if member.isfile():+ f = tar.extractfile(member)+ if f:+ return f.read()+ finally:+ tar.close()++ raise FileNotFoundError(f"not found in Pod: {path}")++ async def write_file(self, path: str, data: bytes) -> None:+ """Write raw bytes to a file inside the Pod via tar stream.++ Creates the parent directory first, then constructs an in-memory+ tar archive containing the file and pipes it to+ ``tar xf - -C <parent>`` inside the Pod. This mirrors+ DockerBackend's ``put_archive`` approach and the mechanism+ ``kubectl cp`` uses internally.++ After sending the tar data, this method reads back the exec+ stream to capture any ``tar`` stderr and exit status. A+ non-zero exit raises ``RuntimeError``.++ Args:+ path (`str`):+ Destination path inside the Pod.+ data (`bytes`):+ The raw bytes to write.++ Raises:+ `RuntimeError`:+ If ``tar xf`` exits non-zero inside the Pod.+ """+ parent = posixpath.dirname(path) or "/"+ name = posixpath.basename(path)++ await self.exec_shell(["mkdir", "-p", parent])++ buf = io.BytesIO()+ with tarfile.open(fileobj=buf, mode="w") as tf:+ info = tarfile.TarInfo(name=name)+ info.size = len(data)+ tf.addfile(info, io.BytesIO(data))+ tar_bytes = buf.getvalue()++ from kubernetes_asyncio import client as k8s_client+ from kubernetes_asyncio.stream import WsApiClient++ async with WsApiClient(+ self._api_client.configuration,+ ) as ws_api:+ v1_ws = k8s_client.CoreV1Api(api_client=ws_api)+ ws = await v1_ws.connect_get_namespaced_pod_exec(+ self._pod_name,+ self._namespace,+ command=["tar", "xf", "-", "-C", parent],+ container=self._container_name,+ stderr=True,+ stdin=True,+ stdout=True,+ tty=False,+ _preload_content=False,+ )+ stderr_parts: list[bytes] = []+ exit_code = 0++ async with ws as sock:+ await sock.send_bytes(+ bytes([0]) + tar_bytes,+ )+ await sock.send_bytes(bytes([0]))++ async for msg in sock:+ if msg.type not in (1, 2):+ break+ raw = (+ msg.data+ if isinstance(msg.data, bytes)+ else msg.data.encode("utf-8")+ )+ if not raw:+ continue+ channel = raw[0]+ payload = raw[1:]+ if channel == 2:+ stderr_parts.append(payload)+ elif channel == 3:+ import json++ try:+ status = json.loads(+ payload.decode("utf-8"),+ )+ if status.get("status") != "Success":+ exit_code = 1+ except (+ json.JSONDecodeError,+ ValueError,+ ):+ exit_code = 1++ if exit_code != 0:+ stderr_text = b"".join(stderr_parts).decode(+ errors="replace",+ )+ raise RuntimeError(+ f"write_file to {path!r} failed: "+ f"tar xf exited {exit_code}: {stderr_text}",+ )diff --git a/src/agentscope/workspace/_k8s/_k8s_workspace.py b/src/agentscope/workspace/_k8s/_k8s_workspace.pynew file mode 100644index 000000000..443b5c5c4--- /dev/null+++ b/src/agentscope/workspace/_k8s/_k8s_workspace.py@@ -0,0 +1,629 @@+# -*- coding: utf-8 -*-+"""K8sWorkspace — sandboxed workspace backed by a Kubernetes Pod.++Architecture+------------++Mirrors :class:`agentscope.workspace.DockerWorkspace` but swaps the+Docker engine for the Kubernetes API (``kubernetes_asyncio``):++* **Lifecycle.** ``initialize()`` looks up an existing Pod by label,+ reuses it if Running, deletes-and-recreates if Failed/Unknown, or+ creates a new one. PVCs survive Pod deletion for data persistence.+ ``close()`` deletes the Pod but keeps the PVC (unless+ ``delete_pvc_on_close=True`` was passed at construction).+* **Persistence.** A PVC (``as-ws-{workspace_id}``) mounted at+ ``/workspace`` provides cross-Pod-restart persistence. Skills,+ ``.mcp``, sessions, and data survive restarts.+* **Bootstrap.** First-time provisioning installs system deps ++ uv + gateway venv + agentscope and uploads the gateway script.+ The probe + install loop lives on :class:`SandboxedWorkspaceBase`;+ this subclass only supplies Pod-specific shell commands via+ :meth:`_bootstrap_commands`.+* **MCP gateway.** Identical to Docker/E2B: a FastAPI process inside+ the Pod, host talks to it via :class:`GatewayClient` through the+ gateway shim (``exec_shell``-based transport, no host-to-Pod+ network required).+"""++import asyncio+import shlex+from typing import Any++from ..._logging import logger+from ...mcp import MCPClient+from .._sandboxed_base import SandboxedWorkspaceBase+from .._utils import _GATEWAY_BASE_REQUIREMENTS+from ._k8s_backend import K8sBackend+from ._constants import (+ DEFAULT_GATEWAY_PORT,+ DEFAULT_IMAGE,+ GATEWAY_HOME,+ POD_WORKDIR,+ SYSTEM_DEPS,+ _k8s_safe_name,+)++_DEFAULT_INSTRUCTIONS = """<workspace>+You have a Kubernetes-based workspace. All tool calls execute **inside+the Pod** at ``{workdir}``.++Layout:++```+{workdir}+├── data/ # offloaded multimodal files+├── skills/ # reusable skills+└── sessions/ # session context and tool results+```++Use the MCP-provided tools to interact with the Pod's filesystem+and processes.+</workspace>"""+++# ── the workspace ──────────────────────────────────────────────────+++class K8sWorkspace(SandboxedWorkspaceBase):+ """Workspace backed by a Kubernetes Pod with PVC persistence.++ ``default_mcps`` and ``skill_paths`` are seed-time inputs and are+ not retained as instance state past :meth:`initialize`.+ """++ _gateway_home = GATEWAY_HOME++ def __init__(+ self,+ *,+ workspace_id: str | None = None,+ # ── K8s connection ──+ kubeconfig: str | None = None,+ namespace: str = "agentscope",+ # ── Pod construction ──+ image: str = DEFAULT_IMAGE,+ image_pull_policy: str = "IfNotPresent",+ image_pull_secrets: list[str] | None = None,+ resources: dict[str, Any] | None = None,+ node_selector: dict[str, str] | None = None,+ tolerations: list[dict[str, Any]] | None = None,+ service_account: str | None = None,+ # ── Gateway ──+ gateway_port: int = DEFAULT_GATEWAY_PORT,+ extra_pip: list[str] | None = None,+ # ── Persistence ──+ storage_class: str | None = None,+ storage_size: str = "1Gi",+ delete_pvc_on_close: bool = False,+ # ── Environment ──+ env: dict[str, str] | None = None,+ instructions: str = _DEFAULT_INSTRUCTIONS,+ # ── Seed ──+ default_mcps: list[MCPClient] | None = None,+ skill_paths: list[str] | None = None,+ ) -> None:+ """Construct a :class:`K8sWorkspace`.++ The Pod is *not* started here; call :meth:`initialize`+ (or use the workspace as an ``async`` context manager).++ Args:+ workspace_id (`str | None`, optional):+ Stable identifier. ``None`` generates a fresh UUID.+ kubeconfig (`str | None`, optional):+ Path to kubeconfig file. ``None`` uses in-cluster+ config.+ namespace (`str`, defaults to ``"agentscope"``):+ K8s namespace for the Pod and PVC.+ image (`str`, defaults to ``"python:3.11-slim"``):+ Container image.+ image_pull_policy (`str`, defaults to ``"IfNotPresent"``):+ K8s imagePullPolicy.+ image_pull_secrets (`list[str] | None`, optional):+ Names of K8s image pull secrets.+ resources (`dict[str, Any] | None`, optional):+ K8s ResourceRequirements dict.+ node_selector (`dict[str, str] | None`, optional):+ K8s nodeSelector.+ tolerations (`list[dict[str, Any]] | None`, optional):+ K8s tolerations list.+ service_account (`str | None`, optional):+ K8s serviceAccountName.+ gateway_port (`int`, defaults to `5600`):+ Port the gateway listens on inside the Pod.+ extra_pip (`list[str] | None`, optional):+ Extra packages for the gateway venv.+ storage_class (`str | None`, optional):+ K8s StorageClass name. ``None`` uses cluster default.+ storage_size (`str`, defaults to ``"1Gi"``):+ PVC size.+ delete_pvc_on_close (`bool`, defaults to ``False``):+ When ``True``, :meth:`close` also deletes the PVC.+ env (`dict[str, str] | None`, optional):+ Environment variables for the container.+ instructions (`str`):+ System-prompt fragment template.+ default_mcps (`list[MCPClient] | None`, optional):+ MCPs seeded on first init.+ skill_paths (`list[str] | None`, optional):+ Skill directories seeded on first init.+ """+ super().__init__(+ workspace_id=workspace_id,+ default_mcps=default_mcps,+ skill_paths=skill_paths,+ )++ # ── serializable config ─────────────────────────────────+ self.workdir = POD_WORKDIR+ self._kubeconfig = kubeconfig+ self._namespace = namespace+ self._image = image+ self._image_pull_policy = image_pull_policy+ self._image_pull_secrets = list(image_pull_secrets or [])+ self._resources = resources+ self._node_selector = node_selector+ self._tolerations = tolerations+ self._service_account = service_account+ self.gateway_port = gateway_port+ self.extra_pip: list[str] = list(extra_pip or [])+ self._storage_class = storage_class+ self._storage_size = storage_size+ self._delete_pvc_on_close = delete_pvc_on_close+ self.env: dict[str, str] = dict(env or {})+ self.instructions = instructions++ # ── runtime state (K8s-only) ────────────────────────────+ self._api_client: Any = None+ self._v1: Any = None # CoreV1Api+ self._pod_name: str = ""++ # ── lifecycle hooks ─────────────────────────────────────────++ async def _provision_backend(self) -> None:+ """Create or reattach to the K8s Pod, bootstrap if needed."""+ from kubernetes_asyncio import client as k8s_client+ from kubernetes_asyncio import config as k8s_config++ if self._kubeconfig:+ await k8s_config.load_kube_config(+ config_file=self._kubeconfig,+ )+ else:+ try:+ k8s_config.load_incluster_config()+ except k8s_config.ConfigException:+ await k8s_config.load_kube_config()++ self._api_client = k8s_client.ApiClient()+ self._v1 = k8s_client.CoreV1Api(self._api_client)++ self._pod_name = _k8s_safe_name(self.workspace_id)++ await self._ensure_namespace()+ await self._ensure_pvc()+ await self._ensure_pod()+ await self._wait_pod_running()++ self._backend = K8sBackend(+ api_client=self._api_client,+ namespace=self._namespace,+ pod_name=self._pod_name,+ container_name="workspace",+ workdir=POD_WORKDIR,+ )++ async def _teardown_backend(self) -> None:+ """Delete the Pod (and optionally the PVC), release the API+ client. Errors are swallowed so teardown is always safe.+ """+ if self._v1 is not None and self._pod_name:+ try:+ await self._v1.delete_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ except Exception as e:+ logger.warning("K8sWorkspace: Pod delete failed: %s", e)++ if self._delete_pvc_on_close:+ try:+ await self._v1.delete_namespaced_persistent_volume_claim(+ self._pod_name,+ self._namespace,+ )+ except Exception as e:+ logger.warning(+ "K8sWorkspace: PVC delete failed: %s",+ e,+ )++ if self._api_client is not None:+ try:+ await self._api_client.close()+ except Exception:+ pass+ self._api_client = None+ self._v1 = None++ # ── instructions ────────────────────────────────────────────++ async def get_instructions(self) -> str:+ """Return the system-prompt fragment for this workspace."""+ return self.instructions.format(workdir=POD_WORKDIR)++ # ── internals: K8s resource management ─────────────────────++ async def _ensure_namespace(self) -> None:+ """Create the namespace if it doesn't exist."""+ from kubernetes_asyncio.client.rest import ApiException++ try:+ await self._v1.read_namespace(self._namespace)+ except ApiException as e:+ if e.status == 404:+ from kubernetes_asyncio import client as k8s_client++ ns = k8s_client.V1Namespace(+ metadata=k8s_client.V1ObjectMeta(+ name=self._namespace,+ ),+ )+ await self._v1.create_namespace(ns)+ else:+ raise++ async def _ensure_pvc(self) -> None:+ """Create or reuse the PVC for workspace persistence.++ Deletion-in-progress is detected via+ ``metadata.deletion_timestamp`` (K8s sets this field when a+ ``DELETE`` has been accepted but finalizers have not yet+ completed). ``status.phase`` does not have a+ ``"Terminating"`` value in upstream Kubernetes.+ """+ from kubernetes_asyncio.client.rest import ApiException++ pvc_name = self._pod_name+ try:+ pvc = await self._v1.read_namespaced_persistent_volume_claim(+ pvc_name,+ self._namespace,+ )+ if pvc.metadata and pvc.metadata.deletion_timestamp is not None:+ logger.info(+ "K8sWorkspace: PVC %r is being deleted, waiting...",+ pvc_name,+ )+ await self._wait_pvc_deleted(pvc_name)+ await self._create_pvc(pvc_name)+ except ApiException as e:+ if e.status == 404:+ await self._create_pvc(pvc_name)+ else:+ raise++ async def _create_pvc(self, pvc_name: str) -> None:+ """Create a new PVC."""+ from kubernetes_asyncio import client as k8s_client++ spec_kwargs: dict[str, Any] = {+ "access_modes": ["ReadWriteOnce"],+ "resources": k8s_client.V1VolumeResourceRequirements(+ requests={"storage": self._storage_size},+ ),+ }+ if self._storage_class is not None:+ spec_kwargs["storage_class_name"] = self._storage_class++ pvc = k8s_client.V1PersistentVolumeClaim(+ metadata=k8s_client.V1ObjectMeta(+ name=pvc_name,+ namespace=self._namespace,+ labels={+ "app.kubernetes.io/managed-by": "agentscope",+ "agentscope.workspace.id": self.workspace_id,+ },+ ),+ spec=k8s_client.V1PersistentVolumeClaimSpec(**spec_kwargs),+ )+ await self._v1.create_namespaced_persistent_volume_claim(+ self._namespace,+ pvc,+ )++ async def _wait_pvc_deleted(+ self,+ pvc_name: str,+ timeout: float = 60.0,+ ) -> None:+ """Poll until the PVC is fully deleted."""+ from kubernetes_asyncio.client.rest import ApiException++ deadline = asyncio.get_event_loop().time() + timeout+ while asyncio.get_event_loop().time() < deadline:+ try:+ await self._v1.read_namespaced_persistent_volume_claim(+ pvc_name,+ self._namespace,+ )+ except ApiException as e:+ if e.status == 404:+ return+ raise+ await asyncio.sleep(1.0)+ raise RuntimeError(+ f"PVC {pvc_name!r} did not finish deleting " f"within {timeout}s",+ )++ async def _ensure_pod(self) -> None:+ """Create or reuse the workspace Pod.++ Only terminal phases (``Failed``, ``Unknown``, ``Succeeded``)+ trigger a delete-and-recreate cycle. ``Pending`` Pods are left+ for :meth:`_wait_pod_running` which inspects container statuses+ for early failure detection.++ A Pod whose ``metadata.deletion_timestamp`` is set is already+ being deleted (by a previous ``close()`` or an external actor)+ — attaching to it would race the terminator, so we wait for it+ to disappear and then create a fresh one.+ """+ from kubernetes_asyncio.client.rest import ApiException++ _REBUILD_PHASES = frozenset({"Failed", "Unknown", "Succeeded"})++ try:+ pod = await self._v1.read_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ phase = pod.status.phase if pod.status else None+ deletion_ts = (+ pod.metadata.deletion_timestamp+ if pod.metadata is not None+ else None+ )+ if deletion_ts is not None:+ logger.info(+ "K8sWorkspace: Pod %r is being deleted, "+ "waiting to recreate",+ self._pod_name,+ )+ await self._wait_pod_deleted()+ await self._create_pod()+ return+ if phase in {"Running", "Pending"}:+ return+ if phase in _REBUILD_PHASES:+ logger.info(+ "K8sWorkspace: Pod %r is %s, deleting and recreating",+ self._pod_name,+ phase,+ )+ try:+ await self._v1.delete_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ except ApiException:+ pass+ await self._wait_pod_deleted()+ await self._create_pod()+ else:+ logger.warning(+ "K8sWorkspace: Pod %r has unexpected phase %r, "+ "deleting and recreating",+ self._pod_name,+ phase,+ )+ try:+ await self._v1.delete_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ except ApiException:+ pass+ await self._wait_pod_deleted()+ await self._create_pod()+ except ApiException as e:+ if e.status == 404:+ await self._create_pod()+ else:+ raise++ async def _create_pod(self) -> None:+ """Create the workspace Pod."""+ from kubernetes_asyncio import client as k8s_client++ container_env = None+ if self.env:+ container_env = [+ k8s_client.V1EnvVar(name=k, value=v)+ for k, v in self.env.items()+ ]++ container = k8s_client.V1Container(+ name="workspace",+ image=self._image,+ image_pull_policy=self._image_pull_policy,+ command=["sleep", "infinity"],+ working_dir=POD_WORKDIR,+ ports=[+ k8s_client.V1ContainerPort(+ container_port=self.gateway_port,+ ),+ ],+ resources=(+ k8s_client.V1ResourceRequirements(**self._resources)+ if self._resources+ else None+ ),+ volume_mounts=[+ k8s_client.V1VolumeMount(+ name="workspace-data",+ mount_path=POD_WORKDIR,+ ),+ ],+ env=container_env,+ )++ volumes = [+ k8s_client.V1Volume(+ name="workspace-data",+ persistent_volume_claim=(+ k8s_client.V1PersistentVolumeClaimVolumeSource(+ claim_name=self._pod_name,+ )+ ),+ ),+ ]++ spec_kwargs: dict[str, Any] = {+ "restart_policy": "OnFailure",+ "containers": [container],+ "volumes": volumes,+ }+ if self._node_selector:+ spec_kwargs["node_selector"] = self._node_selector+ if self._tolerations:+ spec_kwargs["tolerations"] = [+ k8s_client.V1Toleration(**t) for t in self._tolerations+ ]+ if self._service_account:+ spec_kwargs["service_account_name"] = self._service_account+ if self._image_pull_secrets:+ spec_kwargs["image_pull_secrets"] = [+ k8s_client.V1LocalObjectReference(name=s)+ for s in self._image_pull_secrets+ ]++ pod = k8s_client.V1Pod(+ metadata=k8s_client.V1ObjectMeta(+ name=self._pod_name,+ namespace=self._namespace,+ labels={+ "app.kubernetes.io/managed-by": "agentscope",+ "agentscope.workspace": "true",+ "agentscope.workspace.id": self.workspace_id,+ },+ ),+ spec=k8s_client.V1PodSpec(**spec_kwargs),+ )+ await self._v1.create_namespaced_pod(self._namespace, pod)++ async def _wait_pod_running(self, timeout: float = 120.0) -> None:+ """Poll until the Pod phase is Running.++ Also inspects container statuses during the Pending phase to+ detect unrecoverable conditions (``ImagePullBackOff``,+ ``ErrImagePull``, ``InvalidImageName``) early instead of+ waiting for the full timeout.+ """+ _TERMINAL_WAITING_REASONS = frozenset(+ {+ "ImagePullBackOff",+ "ErrImagePull",+ "InvalidImageName",+ "CrashLoopBackOff",+ },+ )+ _UNSCHEDULABLE_TYPES = frozenset(+ {"PodScheduled"},+ )++ deadline = asyncio.get_event_loop().time() + timeout+ delay = 0.5+ while asyncio.get_event_loop().time() < deadline:+ pod = await self._v1.read_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ phase = pod.status.phase if pod.status else None+ if phase == "Running":+ return+ if phase in ("Failed", "Unknown"):+ raise RuntimeError(+ f"Pod {self._pod_name!r} entered {phase} state",+ )++ if phase == "Pending" and pod.status:+ for cs in pod.status.container_statuses or []:+ if cs.state and cs.state.waiting:+ reason = cs.state.waiting.reason or ""+ if reason in _TERMINAL_WAITING_REASONS:+ msg = cs.state.waiting.message or reason+ raise RuntimeError(+ f"Pod {self._pod_name!r} container "+ f"is stuck: {msg}",+ )+ for cond in pod.status.conditions or []:+ if (+ cond.type in _UNSCHEDULABLE_TYPES+ and cond.status == "False"+ and cond.reason == "Unschedulable"+ ):+ raise RuntimeError(+ f"Pod {self._pod_name!r} is "+ f"unschedulable: {cond.message}",+ )++ await asyncio.sleep(delay)+ delay = min(delay * 1.5, 3.0)+ raise RuntimeError(+ f"Pod {self._pod_name!r} did not become Running "+ f"within {timeout}s",+ )++ async def _wait_pod_deleted(self, timeout: float = 30.0) -> None:+ """Poll until the Pod is gone."""+ from kubernetes_asyncio.client.rest import ApiException++ deadline = asyncio.get_event_loop().time() + timeout+ while asyncio.get_event_loop().time() < deadline:+ try:+ await self._v1.read_namespaced_pod(+ self._pod_name,+ self._namespace,+ )+ except ApiException as e:+ if e.status == 404:+ return+ raise+ await asyncio.sleep(1.0)+ raise RuntimeError(+ f"Pod {self._pod_name!r} did not finish deleting "+ f"within {timeout}s",+ )++ # ── internals: bootstrap ────────────────────────────────────++ def _bootstrap_commands(self) -> list[str]:+ """Shell commands that provision this Pod once.++ Only runs when the gateway script is missing (fresh PVC, or a+ Pod that died before the script was written). Slim base image+ runs as root, so no ``sudo`` needed — uv lands at+ ``/usr/local/bin/uv`` which is on the default PATH.+ """+ pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)+ # Quote every requirement string so entries containing spaces+ # or shell metacharacters (e.g. version specifiers wrapped in+ # brackets, direct-URL installs) cannot break the ``sh -c``+ # command or become an injection vector.+ pip_args = " ".join(shlex.quote(p) for p in pip_pkgs)+ sys_deps = " ".join(shlex.quote(d) for d in SYSTEM_DEPS)++ return [+ f"apt-get update -qq "+ f"&& apt-get install -y --no-install-recommends {sys_deps} "+ f"&& rm -rf /var/lib/apt/lists/*",+ "curl -LsSf https://astral.sh/uv/install.sh "+ "| env UV_INSTALL_DIR=/usr/local/bin "+ "INSTALLER_NO_MODIFY_PATH=1 sh",+ f"uv venv {self._gateway_venv}",+ f"uv pip install --python {self._gateway_python} {pip_args}",+ f"uv pip install --python {self._gateway_python} "+ f"--no-deps 'agentscope'",+ ]diff --git a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.pyindex 58b690bb7..8c8ed16e2 100644--- a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py+++ b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py@@ -1,37 +1,24 @@# -*- coding: utf-8 -*-"""In-workspace MCP gateway — FastAPI router over agentscope MCPClients.-Runs *inside* the workspace environment as a standalone script-(``python /path/to/_mcp_gateway_app.py``). Reads ``--config`` JSON,-instantiates one :class:`agentscope.mcp.MCPClient` per configured server,-and exposes per-server HTTP endpoints. Each call is forwarded to the-underlying ``MCPClient`` (which owns the upstream session).--The script uses an absolute import for ``agentscope.mcp`` (rather than-a package-relative import) so it can be invoked directly without-loading ``agentscope.workspace.__init__`` — the latter eagerly imports-heavy modules (skill, tool, …) that are unnecessary for the gateway-and would force their dependencies into the in-container venv.--Endpoints------------ GET /health # liveness, no auth- GET /mcps # [{name, tools}, ...]+Runs inside the workspace environment as a standalone script. Reads+``--config`` — a JSON list of ``MCPClient.model_dump()`` dicts (same+format as the workspace's ``.mcp`` file) — instantiates one client per+entry, and exposes per-server HTTP endpoints. No auth: the gateway is+only reachable via ``backend.exec_shell`` from inside the sandbox.++Endpoints::++ GET /health+ GET /mcps # [MCPClient.model_dump(), ...]POST /mcps # body: MCPClient.model_dump()DELETE /mcps/{name}- GET /mcps/{name}/tools # upstream tool schemas+ GET /mcps/{name}/toolsPOST /mcps/{name}/tools/{tool} # body: {arguments: {...}}-Auth: every endpoint except ``/health`` requires-``Authorization: Bearer <token>`` when a token is configured.--Config schema::-- {- "token": "bearer-token",- "servers": [<MCPClient.model_dump()>, ...]- }+The absolute import for ``agentscope.mcp`` avoids loading+``agentscope.workspace.__init__`` (which pulls in skill/tool trees the+gateway does not need)."""import argparse@@ -39,75 +26,44 @@ import asyncioimport jsonfrom typing import Any-from fastapi import Depends, FastAPI, HTTPException, Request+from fastapi import FastAPI, HTTPException, Requestfrom fastapi.responses import PlainTextResponsefrom agentscope.mcp import MCPClient-# ── gateway state ──────────────────────────────────────────────────--class _State:"""Mutable runtime state shared by FastAPI routes."""def __init__(self) -> None:self.clients: dict[str, MCPClient] = {}- self.token: str = ""self.lock = asyncio.Lock()-def _make_auth_dep(state: _State) -> Any:- """Build a Bearer-token auth dependency closed over the state.-- No-op when ``state.token`` is empty.- """-- async def _auth(request: Request) -> None:- if not state.token:- return- header = request.headers.get("authorization", "")- if header != f"Bearer {state.token}":- raise HTTPException(status_code=401, detail="unauthorized")-- return _auth---# ── client construction ───────────────────────────────────────────--async def _build_client(spec: dict[str, Any]) -> MCPClient:- """Validate a config / request body into an :class:`MCPClient`,- then connect if stateful so subsequent ``list_raw_tools`` /- ``get_tool`` work without re-spawning the upstream session.+ """Validate a spec into an ``MCPClient``, connect if stateful,+ and prime its tool cache."""client = MCPClient.model_validate(spec)if client.is_stateful:await client.connect()- # Prime the tool cache so /mcps/{name}/tools is cheap and stable.await client.list_raw_tools()return client-# ── FastAPI app ────────────────────────────────────────────────────--def _build_app(state: _State) -> FastAPI:"""Build the FastAPI app with all routes wired against ``state``."""app = FastAPI(title="agentscope-workspace-mcp-gateway")- auth = Depends(_make_auth_dep(state))@app.get("/health")async def _health() -> PlainTextResponse:return PlainTextResponse("ok")- @app.get("/mcps", dependencies=[auth])+ @app.get("/mcps")async def _list_mcps() -> list[dict[str, Any]]:- # Dump the full MCPClient field set so the host can rebuild- # `GatewayMCPClient.model_validate(spec)` losslessly.return [c.model_dump(mode="json") for c in state.clients.values()]- @app.post("/mcps", dependencies=[auth])+ @app.post("/mcps")async def _add_mcp(request: Request) -> dict[str, Any]:body = await request.json()name = body.get("name", "")@@ -121,14 +77,11 @@ def _build_app(state: _State) -> FastAPI:except HTTPException:raiseexcept Exception as e: # noqa: BLE001- raise HTTPException(- 500,- f"connect failed: {e}",- ) from e+ raise HTTPException(500, f"connect failed: {e}") from estate.clients[name] = clientreturn {"ok": True}- @app.delete("/mcps/{name}", dependencies=[auth])+ @app.delete("/mcps/{name}")async def _remove_mcp(name: str) -> dict[str, Any]:async with state.lock:client = state.clients.pop(name, None)@@ -138,18 +91,15 @@ def _build_app(state: _State) -> FastAPI:await client.close()return {"ok": True}- @app.get("/mcps/{name}/tools", dependencies=[auth])+ @app.get("/mcps/{name}/tools")async def _list_tools(name: str) -> list[dict[str, Any]]:client = state.clients.get(name)if client is None:raise HTTPException(404, f"{name!r} not found")- # Send raw mcp.types.Tool over the wire so the host-side- # GatewayMCPClient can re-wrap them via the standard MCPClient- # path (preserves inputSchema, annotations.readOnlyHint, ...).raw = await client.list_raw_tools()return [t.model_dump(mode="json") for t in raw]- @app.post("/mcps/{name}/tools/{tool}", dependencies=[auth])+ @app.post("/mcps/{name}/tools/{tool}")async def _call_tool(name: str,tool: str,@@ -167,20 +117,16 @@ def _build_app(state: _State) -> FastAPI:raise HTTPException(404, str(e)) from eexcept Exception as e: # noqa: BLE001raise HTTPException(500, str(e)) from e- # ToolChunk is a pydantic model — let host reconstruct it.return {"chunk": chunk.model_dump(mode="json")}return app-# ── lifecycle ──────────────────────────────────────────────────────--async def _connect_initial(state: _State,server_cfgs: list[dict[str, Any]],) -> None:- """Connect every server listed in the static config file."""+ """Connect every server listed in the config file."""for cfg in server_cfgs:client = await _build_client(cfg)if client.name in state.clients:@@ -196,11 +142,15 @@ async def _connect_initial(async def _run(config_path: str, port: int) -> None:"""Read config, connect upstreams, start uvicorn, clean up on exit."""with open(config_path, encoding="utf-8") as f:- config = json.load(f)+ servers = json.load(f)+ if not isinstance(servers, list):+ raise ValueError(+ f"config file must be a JSON list of MCPClient specs, "+ f"got {type(servers).__name__}",+ )state = _State()- state.token = config.get("token", "") or ""- await _connect_initial(state, config.get("servers", []) or [])+ await _connect_initial(state, servers)app = _build_app(state)print(@@ -212,9 +162,9 @@ async def _run(config_path: str, port: int) -> None:uvi_cfg = uvicorn.Config(app,- host="0.0.0.0", # noqa: S104 — gateway listens inside container+ host="127.0.0.1",port=port,- log_level="warning",+ log_level="info",)server = uvicorn.Server(uvi_cfg)try:@@ -226,9 +176,7 @@ async def _run(config_path: str, port: int) -> None:def main() -> None:- """CLI entry point — invoked via- ``python -m agentscope.workspace._mcp_gateway``.- """+ """CLI entry point."""parser = argparse.ArgumentParser(description="In-workspace MCP gateway (FastAPI)",)diff --git a/src/agentscope/workspace/_sandboxed_base.py b/src/agentscope/workspace/_sandboxed_base.pyindex 09c0e43a3..279c10ca1 100644--- a/src/agentscope/workspace/_sandboxed_base.py+++ b/src/agentscope/workspace/_sandboxed_base.py@@ -1,81 +1,112 @@# -*- coding: utf-8 -*-"""SandboxedWorkspaceBase — shared implementation for gateway-backed-sandbox workspaces (Docker, E2B, and future K8s / Daytona etc.).--Extends :class:`WorkspaceBase` with a full template-method lifecycle-around an in-sandbox MCP gateway. Concrete subclasses only need to-provide:--- :meth:`_provision_backend` — create / attach the sandbox and bind- ``self._backend`` (a :class:`BackendBase` implementation).-- :meth:`_teardown_backend` — destroy / pause the sandbox and release- backend-specific resources.-- five gateway-path class attributes (see below) pinned to whatever- paths the subclass's bootstrap places files at.--Every gateway concern — writing config, launching the process,-polling ``/health``, dispatching :meth:`add_mcp` / :meth:`remove_mcp`-through :class:`GatewayClient`, restoring / persisting the ``.mcp``-file, wiping state on :meth:`reset` — lives here so it is written-exactly once.+sandbox workspaces (Docker, E2B, K8s, …).++Extends :class:`WorkspaceBase` with a template-method lifecycle around+an in-sandbox MCP gateway. Subclasses only need to provide:++- :meth:`_provision_backend` — attach/create the sandbox, bind+ ``self._backend``.+- :meth:`_teardown_backend` — destroy/pause the sandbox.+- :meth:`_bootstrap_commands` — shell commands to install the gateway+ venv on first use (Docker skips this — the image already has it).+- gateway-path class attributes (see below).++Everything gateway-related — bootstrap, launch, health poll, MCP+add/remove routing, ``.mcp`` persistence, reset — lives here."""import asyncioimport jsonimport shlex-import uuidfrom abc import abstractmethod-from typing import TYPE_CHECKINGfrom .._logging import loggerfrom ..mcp import MCPClientfrom ._base import WorkspaceBasefrom ._gateway_client import GatewayClient--if TYPE_CHECKING:- from ._gateway_client import GatewayMCPClient+from ._utils import (+ DEFAULT_GATEWAY_LOG,+ DEFAULT_GATEWAY_SCRIPT,+ DEFAULT_GATEWAY_VENV,+ DEFAULT_GLOB_HELPER_SCRIPT,+ _read_gateway_script_bytes,+ _read_glob_helper_bytes,+)class SandboxedWorkspaceBase(WorkspaceBase):"""Base class for workspaces backed by an in-sandbox MCP gateway.- Subclasses set the following class attributes (usually to module- constants defined by the backend's bootstrap):+ Subclasses only need to set:+ - :attr:`workdir` — agent-visible root inside the sandbox.+ - :attr:`_gateway_home` — directory holding the venv, script, log.- :attr:`gateway_port` — TCP port the gateway listens on.- - :attr:`_gateway_home` — directory that holds gateway files.- - :attr:`_gateway_config` — path to ``gateway.config.json``.- - :attr:`_gateway_log` — path to the gateway log.- - :attr:`_gateway_script` — path to the gateway entry script.- - :attr:`_gateway_python` — path to the gateway venv's python.++ Every other gateway path (venv, python, script, log, glob helper)+ is derived from :attr:`_gateway_home` via+ :meth:`BackendBase.join_path`."""+ workdir: str+ """Agent-visible root directory for workspace file operations."""+gateway_port: int"""TCP port the in-sandbox gateway listens on."""_gateway_home: str- """Sandbox-side directory holding the gateway config and log."""+ """Sandbox-side directory holding the gateway venv, script, log."""- _gateway_config: str- """Sandbox-side path of ``gateway.config.json``."""+ _gateway: GatewayClient | None+ """Workspace-side gateway facade. ``None`` before init / after close."""- _gateway_log: str- """Sandbox-side path of the gateway stdout/stderr log."""+ _bootstrap_cmd_timeout: float = 1800.0+ """Per-command timeout applied to every :meth:`_setup_mcp_gateway`+ bootstrap step. Subclasses lower this for lighter base images+ (E2B uses 600 s; K8s inherits the wider default for apt-get).+ """- _gateway_script: str- """Sandbox-side path of the gateway entry script."""+ @property+ def _gateway_venv(self) -> str:+ """Sandbox-side path of the gateway venv root."""+ return self.get_backend().join_path(+ self._gateway_home,+ DEFAULT_GATEWAY_VENV,+ )- _gateway_python: str- """Sandbox-side path of the gateway venv python interpreter."""+ @property+ def _gateway_python(self) -> str:+ """Sandbox-side path of the gateway venv python interpreter."""+ return self.get_backend().join_path(+ self._gateway_venv,+ "bin",+ "python",+ )- _gateway: GatewayClient | None- """Workspace-side gateway facade. ``None`` before init / after close."""+ @property+ def _gateway_script(self) -> str:+ """Sandbox-side path of the gateway entry script."""+ return self.get_backend().join_path(+ self._gateway_home,+ DEFAULT_GATEWAY_SCRIPT,+ )- _gateway_clients: "dict[str, GatewayMCPClient]"- """Gateway-wrapped MCP handles keyed by ``MCPClient.name``."""+ @property+ def _gateway_log(self) -> str:+ """Sandbox-side path of the gateway stdout/stderr log."""+ return self.get_backend().join_path(+ self._gateway_home,+ DEFAULT_GATEWAY_LOG,+ )- _gateway_token: str- """Bearer token minted per :meth:`initialize`; never persisted."""+ @property+ def _glob_helper_path(self) -> str:+ """Standalone glob helper script used by the builtin Glob tool."""+ return self.get_backend().join_path(+ self._gateway_home,+ DEFAULT_GLOB_HELPER_SCRIPT,+ )def __init__(self,@@ -100,8 +131,6 @@ class SandboxedWorkspaceBase(WorkspaceBase):skill_paths=skill_paths,)self._gateway = None- self._gateway_clients = {}- self._gateway_token = ""# ── subclass hooks ────────────────────────────────────────────@@ -109,22 +138,28 @@ class SandboxedWorkspaceBase(WorkspaceBase):async def _provision_backend(self) -> None:"""Provision the sandbox and bind ``self._backend``.- Called once per :meth:`initialize`. Implementations must- leave ``self._backend`` as a live :class:`BackendBase`- instance ready to accept ``exec_shell`` / ``write_file`` /- ``read_file`` calls. Any first-time bootstrap (installing the- gateway venv, uploading scripts) should happen here.+ Called once per :meth:`initialize`. Must leave ``self._backend``+ as a live :class:`BackendBase` ready for+ ``exec_shell`` / ``write_file`` / ``read_file``."""@abstractmethodasync def _teardown_backend(self) -> None:- """Destroy or pause the sandbox and release resources.+ """Destroy or pause the sandbox.- Called once per :meth:`close`, *after* the gateway facade has- been closed. Implementations should be idempotent and swallow- exceptions so ``close`` never raises.+ Called once per :meth:`close`, after the gateway facade has+ been closed. Must be idempotent and swallow exceptions."""+ def _bootstrap_commands(self) -> list[str]:+ """Shell commands that provision the gateway venv on first use.++ Runs only when :attr:`_gateway_script` is missing. Subclasses+ whose image already ships the venv (e.g. Docker) leave this+ empty; the base's fast-path skips the whole bootstrap block.+ """+ return []+# ── lifecycle template methods ────────────────────────────────async def initialize(self) -> None:@@ -132,48 +167,38 @@ class SandboxedWorkspaceBase(WorkspaceBase):Idempotent — a no-op when already alive."""+ logger.info(+ "Initialize workspace (id=%s) from %s ...",+ self.workspace_id,+ self.__class__.__name__,+ )+if self.is_alive:return+ # Set up the backend connectionawait self._provision_backend()assert (self._backend is not None), "_provision_backend must set self._backend before returning"- self._mcps = await self._restore_or_seed_mcps()- self._gateway_token = uuid.uuid4().hex+ # Set up the workspace layout+ await self._ensure_workspace_layout()- # Kill any leftover gateway from a previous resume. Each init- # mints a fresh bearer token, so a stale gateway would accept- # old-token requests but reject new ones. Idempotent (``|| true``).- await self._backend.exec_shell(- ["sh", "-c", "pkill -f _mcp_gateway_app.py || true"],- )+ # Set up the MCP gateway server+ await self._setup_mcp_gateway()- await self._write_gateway_config()- await self._start_gateway_process()-- self._gateway = GatewayClient(- backend=self._backend,- gateway_port=self.gateway_port,- token=self._gateway_token,- timeout=30.0,- )- await self._wait_for_gateway()-- # The gateway loaded the same set we just wrote — name-for-name.- self._gateway_clients = {- c.name: c for c in await self._gateway.list_mcps()- }-- # ``_save_mcp_file`` is a persistence-gated no-op when the- # workspace is ephemeral; ``_seed_skills`` short-circuits when- # ``skills/`` already has entries.- await self._save_mcp_file()- await self._seed_skills()+ # Set up the skills if not exists+ await self._setup_skills()self.is_alive = True+ logger.info(+ "Finished initializing workspace (id=%s) from %s.",+ self.workspace_id,+ self.__class__.__name__,+ )+async def close(self) -> None:"""Close the gateway facade, then tear down the sandbox.@@ -186,7 +211,6 @@ class SandboxedWorkspaceBase(WorkspaceBase):except Exception:passself._gateway = None- self._gateway_clients.clear()try:await self._teardown_backend()@@ -203,16 +227,15 @@ class SandboxedWorkspaceBase(WorkspaceBase):"""backend = self.get_backend()async with self._mcp_lock, self._skill_lock:- for gw_client in list(self._gateway_clients.values()):+ for mcp in list(self._mcps):try:- await gw_client.close()+ await mcp.close()except Exception as e:logger.warning("MCP %r close failed during reset: %s",- gw_client.name,+ mcp.name,e,)- self._gateway_clients.clear()self._mcps = []for path in (@@ -229,7 +252,7 @@ class SandboxedWorkspaceBase(WorkspaceBase):async def list_mcps(self) -> list[MCPClient]:"""Gateway-wrapped MCP handles, one per registered MCP."""- return list(self._gateway_clients.values())+ return list(self._mcps)async def add_mcp(self, mcp_client: MCPClient) -> None:"""Register a new MCP server through the in-sandbox gateway.@@ -248,15 +271,14 @@ class SandboxedWorkspaceBase(WorkspaceBase):if self._gateway is None:raise RuntimeError("Workspace has no MCP gateway attached.")async with self._mcp_lock:- if mcp_client.name in self._gateway_clients:+ if any(m.name == mcp_client.name for m in self._mcps):raise ValueError(f"MCP {mcp_client.name!r} already exists in workspace.",)spec = mcp_client.model_dump(mode="json")gw_client = self._gateway.make_client(spec)await gw_client.connect()- self._mcps.append(mcp_client)- self._gateway_clients[gw_client.name] = gw_client+ self._mcps.append(gw_client)await self._save_mcp_file()async def remove_mcp(self, name: str) -> None:@@ -274,77 +296,159 @@ class SandboxedWorkspaceBase(WorkspaceBase):if self._gateway is None:raise RuntimeError("Workspace has no MCP gateway attached.")async with self._mcp_lock:- gw_client = self._gateway_clients.pop(name, None)- if gw_client is None:- logger.warning("MCP %r not found in workspace", name)- return+ for i, mcp in enumerate(self._mcps):+ if mcp.name == name:+ self._mcps.pop(i)+ try:+ await mcp.close()+ except Exception as e:+ logger.warning("MCP %r close failed: %s", name, e)+ await self._save_mcp_file()+ return+ logger.warning("MCP %r not found in workspace", name)++ # ── workspace layout helpers ──────────────────────────────────++ async def _ensure_workspace_layout(self) -> None:+ """Create the standard workspace directories inside the sandbox."""+ backend = self.get_backend()+ await backend.exec_shell(+ [+ "mkdir",+ "-p",+ self.workdir,+ self._data_dir,+ self._skills_dir,+ self._sessions_dir,+ self._gateway_home,+ ],+ cwd="/",+ )++ # Seed ``.mcp`` on first use. If a persisted file already+ # exists we validate it: a partial/corrupted write (crash mid+ # ``_save_mcp_file``) would otherwise brick the gateway on the+ # next startup because it expects a JSON list. When the+ # payload is unusable we log and reseed the defaults instead+ # of failing initialization.+ payload = json.dumps(+ [m.model_dump(mode="json") for m in self.default_mcps],+ indent=2,+ ensure_ascii=False,+ ).encode("utf-8")++ if await backend.file_exists(self._mcp_file):try:- await gw_client.close()- except Exception as e:- logger.warning("MCP %r close failed: %s", name, e)- self._mcps = [m for m in self._mcps if m.name != name]- await self._save_mcp_file()+ existing = await backend.read_file(self._mcp_file)+ parsed = json.loads(existing.decode("utf-8"))+ except (UnicodeDecodeError, json.JSONDecodeError) as e:+ logger.warning(+ "%s: %s is corrupted (%s); reseeding defaults",+ type(self).__name__,+ self._mcp_file,+ e,+ )+ else:+ if isinstance(parsed, list):+ return+ logger.warning(+ "%s: %s does not contain a JSON list "+ "(got %s); reseeding defaults",+ type(self).__name__,+ self._mcp_file,+ type(parsed).__name__,+ )+ await backend.write_file(self._mcp_file, payload)# ── gateway lifecycle helpers ─────────────────────────────────- async def _write_gateway_config(self) -> None:- """Drop ``gateway.config.json`` into the sandbox.+ async def _setup_mcp_gateway(self) -> None:+ """Bootstrap (once) and launch the in-sandbox gateway.++ Steps:- Carries the freshly minted bearer token plus the MCP server- specs the gateway should bring up at startup.+ 1. Bootstrap the venv + script if :attr:`_gateway_script` is+ missing (Docker's image already has it → fast-path).+ 2. Kill any leftover gateway from a previous resume.+ 3. Launch a fresh gateway pointed at ``.mcp``.+ 4. Bind :attr:`_gateway` and poll ``/health``."""backend = self.get_backend()- cfg = {- "token": self._gateway_token,- "servers": [m.model_dump(mode="json") for m in self._mcps],- }- await backend.exec_shell(["mkdir", "-p", self._gateway_home])- await backend.write_file(- self._gateway_config,- json.dumps(cfg, indent=2, ensure_ascii=False).encode("utf-8"),- )- async def _start_gateway_process(self) -> None:- """Launch the gateway inside the sandbox as a detached process."""- backend = self.get_backend()- cmd = (+ # Provision the venv + script on first use. Fast-path skips+ # when the script already exists (Docker image build, E2B+ # resume, K8s PVC remount).+ if not await backend.file_exists(self._gateway_script):+ logger.info(+ "%s: bootstrapping workspace_id=%r",+ type(self).__name__,+ self.workspace_id,+ )+ for cmd in self._bootstrap_commands():+ r = await backend.exec_shell(+ ["sh", "-c", cmd],+ timeout=self._bootstrap_cmd_timeout,+ )+ if not r.ok():+ raise RuntimeError(+ f"{type(self).__name__} bootstrap failed "+ f"(exit {r.exit_code}) for: {cmd!r}\n"+ f"stderr: {r.stderr.decode(errors='replace')}\n"+ f"stdout: {r.stdout.decode(errors='replace')}",+ )+ # Glob helper first, gateway script last — a partial+ # bootstrap leaves _gateway_script absent so the next+ # initialize retries cleanly.+ if self._glob_helper_path is not None:+ await backend.write_file(+ self._glob_helper_path,+ _read_glob_helper_bytes(),+ )+ await backend.write_file(+ self._gateway_script,+ _read_gateway_script_bytes(),+ )++ # Launch. ``pkill`` clears any gateway left running by a+ # previous resume so the new one can bind the port cleanly.+ # The gateway reads ``.mcp`` directly — no separate config file.+ launch_cmd = (+ "pkill -f _mcp_gateway_app.py || true; "f"nohup {shlex.quote(self._gateway_python)} -u "f"{shlex.quote(self._gateway_script)} "- f"--config {shlex.quote(self._gateway_config)} "+ f"--config {shlex.quote(self._mcp_file)} "f"--port {self.gateway_port} "f"> {shlex.quote(self._gateway_log)} 2>&1 &")- await backend.exec_shell(["sh", "-c", cmd])+ await backend.exec_shell(["sh", "-c", launch_cmd])- async def _wait_for_gateway(self, timeout: float = 30.0) -> None:- """Block until the gateway answers ``/health`` with 200.-- On timeout, dump the tail of the gateway log so startup- failures are visible in the raised error.-- Args:- timeout (`float`, defaults to 30.0):- Maximum seconds to wait for readiness.-- Raises:- RuntimeError: If the gateway does not become healthy- before the deadline.- """- assert self._gateway is not None- backend = self.get_backend()- deadline = asyncio.get_event_loop().time() + timeout+ # Wait for ``/health``; on timeout, tail the gateway log.+ self._gateway = GatewayClient(+ backend=backend,+ gateway_port=self.gateway_port,+ timeout=30.0,+ gateway_log_path=self._gateway_log,+ )+ health_timeout = 30.0+ deadline = asyncio.get_event_loop().time() + health_timeoutdelay = 0.1while asyncio.get_event_loop().time() < deadline:if await self._gateway.health():- return+ breakawait asyncio.sleep(delay)delay = min(delay * 1.5, 1.0)- try:- log = await backend.read_file(self._gateway_log)- tail = log[-2000:].decode(errors="replace")- except Exception:- tail = "<no gateway log available>"- raise RuntimeError(- f"gateway did not become healthy within {timeout}s. "- f"Tail of {self._gateway_log}:\n{tail}",- )+ else:+ try:+ log = await backend.read_file(self._gateway_log)+ tail = log[-2000:].decode(errors="replace")+ except Exception:+ tail = "<no gateway log available>"+ raise RuntimeError(+ f"gateway did not become healthy within {health_timeout}s. "+ f"Tail of {self._gateway_log}:\n{tail}",+ )++ # Replace the seed specs with the gateway-side wrappers — same+ # set, name-for-name — so subsequent list_mcps / add / remove+ # operate on the live proxies.+ self._mcps = list(await self._gateway.list_mcps())diff --git a/src/agentscope/workspace/_utils.py b/src/agentscope/workspace/_utils.pyindex 2266c382f..848ea37a7 100644--- a/src/agentscope/workspace/_utils.py+++ b/src/agentscope/workspace/_utils.py@@ -1,23 +1,36 @@# -*- coding: utf-8 -*--"""Host-side helpers shared by Docker + E2B backends.--Pure functions for detecting the local ``agentscope`` install (released-vs dev), iterating the source tree with a stable ignore set, and-reading the gateway script bundled with the package. No Docker / E2B-SDK dependency lives here — both backends import the same helpers so-their install logic stays byte-for-byte in sync.--All names in this module are package-private (leading underscore).-External code should not import from here directly; the two backends-that consume these helpers live next to it under-``agentscope.workspace``.+"""Host-side helpers shared by workspace implementations.++Constants for the standard workspace layout, plus pure functions for+detecting the local ``agentscope`` version and reading scripts bundled+with the package. No Docker / E2B SDK dependency lives here.++This module is internal to ``agentscope.workspace``. Public-sounding+constants are shared within the package, not exported as user-facing+API."""import importlib.resources as _res-from pathlib import Path# ── shared constants ───────────────────────────────────────────────+#: Standard workspace-relative directory for offloaded multimodal data.+DEFAULT_DATA_DIR = "data"++#: Standard workspace-relative directory for reusable skills.+DEFAULT_SKILLS_DIR = "skills"++#: Standard workspace-relative directory for session context and results.+DEFAULT_SESSIONS_DIR = "sessions"++#: Standard workspace-relative file for persisted MCP registrations.+DEFAULT_MCP_FILE = ".mcp"++DEFAULT_GATEWAY_VENV = ".venv"+DEFAULT_GATEWAY_LOG = "gateway.log"+DEFAULT_GATEWAY_SCRIPT = "_mcp_gateway_app.py"+DEFAULT_GLOB_HELPER_SCRIPT = "_glob_helper.py"+#: Minimum Python packages the gateway script needs at runtime.#: Both Docker (image build) and E2B (sandbox bootstrap) install this#: same tuple into the gateway venv before adding ``agentscope`` itself.@@ -27,121 +40,6 @@ _GATEWAY_BASE_REQUIREMENTS: tuple[str, ...] = ("fastapi",)-#: Basename set excluded when packaging the agentscope source tree-#: into a build / bootstrap context (dev-mode only — released installs-#: pull from PyPI and never copy the tree).-_SOURCE_IGNORE_NAMES: frozenset[str] = frozenset(- {- "__pycache__",- "node_modules",- "build",- "dist",- "venv",- "workdir",- "examples",- "tests",- "docs",- "assets",- "scripts",- "dump.rdb",- "uv.lock",- },-)---def _is_source_ignored(name: str) -> bool:- """Whether a single basename should be excluded from the source payload.-- Args:- name (`str`):- Basename to check (e.g. ``"__pycache__"``, ``".git"``,- ``"foo.pyc"``).-- Returns:- `bool`:- ``True`` if the name matches the ignore set / hidden-file- rule / cache-extension rule; ``False`` otherwise.- """- if name.startswith("."):- return True- if name in _SOURCE_IGNORE_NAMES:- return True- return name.endswith(".pyc") or name.endswith(".egg-info")---# ── agentscope install detection ───────────────────────────────────---def _agentscope_module_path() -> Path:- """Return the filesystem path of the imported ``agentscope`` package.-- Returns:- `Path`:- The directory containing ``agentscope/__init__.py``.- """- import agentscope # local import — keeps module import cheap-- file = getattr(agentscope, "__file__", None)- if not file:- raise RuntimeError(- "agentscope has no __file__ attribute; cannot locate package",- )- return Path(file).resolve().parent---def _is_released_install() -> bool:- """Return ``True`` if the imported ``agentscope`` lives in site-packages.-- Used to pick between PyPI install (released) and source-tree- upload (dev) when provisioning the gateway venv inside a- container or sandbox.- """- parts = _agentscope_module_path().parts- return "site-packages" in parts or "dist-packages" in parts---def _agentscope_version() -> str:- """Return the installed ``agentscope`` version string.-- Falls back to :func:`importlib.metadata.version` when the package- has no ``__version__`` attribute.- """- import agentscope-- version = getattr(agentscope, "__version__", None)- if not version:- try:- from importlib.metadata import version as _v-- version = _v("agentscope")- except Exception as e: # noqa: BLE001- raise RuntimeError(- "cannot determine agentscope version",- ) from e- return version---def _agentscope_source_root() -> Path:- """Locate the project root containing ``pyproject.toml`` + ``src/``.-- Only valid in dev mode. Walks up from the package directory until- a ``pyproject.toml`` is found alongside a ``src/`` (or- ``agentscope/``) directory.-- Returns:- `Path`:- The project root path.- """- pkg = _agentscope_module_path()- for parent in [pkg, *pkg.parents]:- if (parent / "pyproject.toml").is_file() and (- (parent / "src").is_dir() or (parent / "agentscope").is_dir()- ):- return parent- raise RuntimeError(- f"cannot locate agentscope project root from {pkg}",- )-# ── gateway script ─────────────────────────────────────────────────diff --git a/tests/app_lifespan_dedicated_test.py b/tests/app_lifespan_dedicated_test.pyindex 05d33ce2c..df3cf0394 100644--- a/tests/app_lifespan_dedicated_test.py+++ b/tests/app_lifespan_dedicated_test.py@@ -158,15 +158,15 @@ class _NoopWorkspaceManager(WorkspaceManagerBase):"""Workspace manager that does nothing."""async def get_workspace(self, *args: Any, **kwargs: Any) -> Any:- raise NotImplementedError-- async def create_workspace(self, *args: Any, **kwargs: Any) -> Any:+ """Fake implementation."""raise NotImplementedErrorasync def close(self, workspace_id: str) -> None:+ """Fake implementation."""return Noneasync def close_all(self) -> None:+ """Fake implementation."""return Nonediff --git a/tests/backend_e2b_test.py b/tests/backend_e2b_test.pyindex 532c4e269..3a4388284 100644--- a/tests/backend_e2b_test.py+++ b/tests/backend_e2b_test.py@@ -23,7 +23,7 @@ from unittest.async_case import IsolatedAsyncioTestCasefrom agentscope.tool import ExecResultfrom agentscope.workspace import E2BWorkspacefrom agentscope.workspace import E2BBackend-from agentscope.workspace._e2b._bootstrap import SANDBOX_WORKDIR+from agentscope.workspace._e2b._constants import SANDBOX_WORKDIR# ── E2B availability check ─────────────────────────────────────────diff --git a/tests/docker/k8s_workspace_test.Dockerfile b/tests/docker/k8s_workspace_test.Dockerfilenew file mode 100644index 000000000..d5067bae0--- /dev/null+++ b/tests/docker/k8s_workspace_test.Dockerfile@@ -0,0 +1,67 @@+# syntax=docker/dockerfile:1.6+# ---------------------------------------------------------------------------+# Pre-baked image for K8sWorkspace integration tests.+#+# Rationale+# ---------+# K8sWorkspace's ``_setup_mcp_gateway`` skips the bootstrap phase when the+# gateway script already exists inside the sandbox (see+# ``SandboxedWorkspaceBase._setup_mcp_gateway`` — fast-path skip).+# By pre-installing every dependency the bootstrap would install and by+# copying the gateway/glob-helper scripts to ``GATEWAY_HOME`` at build time,+# ``initialize()`` skips ``apt-get`` + ``uv install`` + ``pip install`` and+# starts in ~10 s instead of ~5 min.+#+# Build context MUST be the repository root:+# docker build \+# -f tests/docker/k8s_workspace_test.Dockerfile \+# -t agentscope-k8s-test:ci .+#+# In CI the image is loaded into the kind cluster with:+# kind load docker-image agentscope-k8s-test:ci --name <cluster>+# ---------------------------------------------------------------------------++FROM python:3.11-slim++# Keep in sync with agentscope.workspace._k8s._k8s_bootstrap.SYSTEM_DEPS+RUN apt-get update -qq \+ && apt-get install -y --no-install-recommends \+ curl ca-certificates ripgrep \+ && rm -rf /var/lib/apt/lists/*++# uv — matches the bootstrap command exactly.+RUN curl -LsSf https://astral.sh/uv/install.sh \+ | env UV_INSTALL_DIR=/usr/local/bin INSTALLER_NO_MODIFY_PATH=1 sh++# Keep in sync with agentscope.workspace._k8s._k8s_bootstrap.GATEWAY_HOME+ENV GATEWAY_HOME=/root/.agentscope++# Gateway venv + base runtime requirements+# (mirrors ``_GATEWAY_BASE_REQUIREMENTS`` in _sandboxed_base.py)+RUN mkdir -p "${GATEWAY_HOME}" \+ && uv venv "${GATEWAY_HOME}/.venv" \+ && uv pip install --python "${GATEWAY_HOME}/.venv/bin/python" \+ mcp uvicorn fastapi++# Install agentscope itself from the local checkout.+# Build context is repo root, so pyproject.toml + src/ are visible at /src.+COPY pyproject.toml README.md /src/+COPY src /src/src+RUN uv pip install --python "${GATEWAY_HOME}/.venv/bin/python" \+ --no-deps /src++# Copy the gateway script + glob helper into GATEWAY_HOME so that+# ``_setup_mcp_gateway`` sees ``_gateway_script`` on disk and skips bootstrap.+COPY src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py \+ "${GATEWAY_HOME}/_mcp_gateway_app.py"+COPY src/agentscope/tool/_builtin/_scripts/_glob_helper.py \+ "${GATEWAY_HOME}/_glob_helper.py"++# The workdir is created lazily by ``_provision_sandbox``; leaving it here+# just makes ad-hoc `docker run` debugging friendlier.+WORKDIR /workspace++# Container has nothing to run by itself — K8s Pod spec will override CMD+# with the sleep loop from ``_build_pod_spec``.+CMD ["sleep", "infinity"]+diff --git a/tests/service_knowledge_base_upload_test.py b/tests/service_knowledge_base_upload_test.pyindex 195735e65..44a410fb7 100644--- a/tests/service_knowledge_base_upload_test.py+++ b/tests/service_knowledge_base_upload_test.py@@ -261,15 +261,15 @@ class _NoopWorkspaceManager(WorkspaceManagerBase):touches it, but ``create_app`` requires one to be wired in."""async def get_workspace(self, *args: Any, **kwargs: Any) -> Any:- raise NotImplementedError-- async def create_workspace(self, *args: Any, **kwargs: Any) -> Any:+ """Fake implementation."""raise NotImplementedErrorasync def close(self, workspace_id: str) -> None:+ """Fake implementation."""return Noneasync def close_all(self) -> None:+ """Fake implementation."""return Nonediff --git a/tests/service_team_tools_test.py b/tests/service_team_tools_test.pyindex e69a46971..d4c21f95b 100644--- a/tests/service_team_tools_test.py+++ b/tests/service_team_tools_test.py@@ -19,7 +19,7 @@ from unittest import IsolatedAsyncioTestCaseimport fakeredis.aioredis-from utils import AnyString+from utils import AnyString, FakeWorkspaceManagerfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._tool import (@@ -116,6 +116,7 @@ class _TeamToolsTestBase(IsolatedAsyncioTestCase):_make_storage(self.fr),)self.bus = await self._stack.enter_async_context(_make_bus(self.fr))+ self.workspace_manager = FakeWorkspaceManager()# Leader agent + its session.self.leader_agent = _make_agent_record(self.user_id, "leader")@@ -141,6 +142,7 @@ class TestTeamCreate(_TeamToolsTestBase):tool = TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -186,6 +188,7 @@ class TestTeamCreate(_TeamToolsTestBase):tool = TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -216,6 +219,7 @@ class TestAgentCreate(_TeamToolsTestBase):await TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -229,6 +233,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -324,6 +329,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -555,6 +561,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=loner_session.id,agent_id=self.leader_agent.id,@@ -582,6 +589,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -611,6 +619,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -645,6 +654,7 @@ class TestAgentCreate(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -686,6 +696,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):await TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -699,6 +710,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -714,6 +726,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -731,6 +744,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -749,6 +763,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -785,6 +800,7 @@ class TestAgentCreateTemplates(_TeamToolsTestBase):tool = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -836,6 +852,7 @@ class TestTeamSay(_TeamToolsTestBase):await TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -844,6 +861,7 @@ class TestTeamSay(_TeamToolsTestBase):agent_create = AgentCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -882,6 +900,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -946,6 +965,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -992,6 +1012,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=loner_session.id,agent_id=self.leader_agent.id,@@ -1017,6 +1038,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1042,6 +1064,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1072,6 +1095,7 @@ class TestTeamSay(_TeamToolsTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=worker_sid,agent_id=worker_aid,@@ -1116,6 +1140,7 @@ class TestTeamDelete(_TeamToolsTestBase):await TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1127,6 +1152,7 @@ class TestTeamDelete(_TeamToolsTestBase):tool = TeamDelete(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1163,6 +1189,7 @@ class TestTeamDelete(_TeamToolsTestBase):tool = TeamDelete(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=loner_session.id,agent_id=self.leader_agent.id,@@ -1245,6 +1272,7 @@ class _AgentInviteTestBase(_TeamToolsTestBase):await TeamCreate(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1288,6 +1316,7 @@ class TestAgentInviteSuccess(_AgentInviteTestBase):tool = AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1376,6 +1405,7 @@ class TestAgentInviteRejections(_AgentInviteTestBase):return AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1420,6 +1450,7 @@ class TestAgentInviteRejections(_AgentInviteTestBase):tool = AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=loner.id,agent_id=self.leader_agent.id,@@ -1455,6 +1486,7 @@ class TestTeamSayInvitedRouting(_AgentInviteTestBase):await AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1482,6 +1514,7 @@ class TestTeamSayInvitedRouting(_AgentInviteTestBase):tool = TeamSay(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1513,6 +1546,7 @@ class TestTeamDeletePreservesInvited(_AgentInviteTestBase):await AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1532,6 +1566,7 @@ class TestTeamDeletePreservesInvited(_AgentInviteTestBase):await TeamDelete(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,@@ -1573,6 +1608,7 @@ class TestDeleteInvitedAgentReverseCascade(_AgentInviteTestBase):await AgentInvite(storage=self.storage,message_bus=self.bus,+ workspace_manager=self.workspace_manager,user_id=self.user_id,session_id=self.leader_session.id,agent_id=self.leader_agent.id,diff --git a/tests/service_toolkit_test.py b/tests/service_toolkit_test.pyindex 15b8b9966..553af19f9 100644--- a/tests/service_toolkit_test.py+++ b/tests/service_toolkit_test.py@@ -19,6 +19,7 @@ Verifies the assembly rules:from typing import Anyfrom unittest import IsolatedAsyncioTestCase+from utils import FakeWorkspaceManagerfrom agentscope.agent import ContextConfig, ReActConfigfrom agentscope.app._manager import (BackgroundTaskManager,@@ -204,6 +205,7 @@ class TestGetToolkitBaseAssembly(IsolatedAsyncioTestCase):toolkit = await get_toolkit(storage=_NoOpStorage(), # type: ignore[arg-type]workspace=workspace, # type: ignore[arg-type]+ workspace_manager=FakeWorkspaceManager(),scheduler_manager=SchedulerManager(storage=_NoOpStorage(), # type: ignore[arg-type]message_bus=_NullBus(), # type: ignore[arg-type]@@ -273,6 +275,7 @@ class TestGetToolkitWorkerVariant(IsolatedAsyncioTestCase):team_id_map={"t1": team},), # type: ignore[arg-type]workspace=_FakeWorkspace(), # type: ignore[arg-type]+ workspace_manager=FakeWorkspaceManager(),scheduler_manager=SchedulerManager(storage=_NoOpStorage(), # type: ignore[arg-type]message_bus=_NullBus(), # type: ignore[arg-type]@@ -315,6 +318,7 @@ class TestGetToolkitSchedulingGuard(IsolatedAsyncioTestCase):toolkit = await get_toolkit(storage=_NoOpStorage(), # type: ignore[arg-type]workspace=_FakeWorkspace(), # type: ignore[arg-type]+ workspace_manager=FakeWorkspaceManager(),scheduler_manager=SchedulerManager(storage=_NoOpStorage(), # type: ignore[arg-type]message_bus=_NullBus(), # type: ignore[arg-type]@@ -371,6 +375,7 @@ class TestGetToolkitExtraFactory(IsolatedAsyncioTestCase):toolkit = await get_toolkit(storage=_NoOpStorage(), # type: ignore[arg-type]workspace=_FakeWorkspace(), # type: ignore[arg-type]+ workspace_manager=FakeWorkspaceManager(),scheduler_manager=SchedulerManager(storage=_NoOpStorage(), # type: ignore[arg-type]message_bus=_NullBus(), # type: ignore[arg-type]diff --git a/tests/utils.py b/tests/utils.pyindex ac9cdf110..9eba25cc0 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -5,9 +5,11 @@ from typing import Any, AsyncGenerator, Typefrom pydantic import BaseModel+from agentscope.app.workspace_manager import WorkspaceManagerBasefrom agentscope.credential import CredentialBasefrom agentscope.message import Msgfrom agentscope.model import ChatModelBase, ChatResponse, StructuredResponse+from agentscope.workspace import WorkspaceBaseclass AnyString(str):@@ -149,3 +151,37 @@ def compare_by_printing(a: Any, b: Any) -> None:"""Compare the expected output with the actual output by printing them."""print(json.dumps(a, indent=4))print(json.dumps(b, indent=4))+++class FakeWorkspaceManager(WorkspaceManagerBase):+ """Minimal :class:`WorkspaceManagerBase` for tests.++ Inherits the real :meth:`assign_workspace_id` (drives the+ isolation policy under test) and stubs the abstract async+ methods with no-ops. Not backed by any real workspace.+ """++ async def get_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace_id: str | None = None,+ ) -> WorkspaceBase:+ """Not implemented — team-tool tests never touch this."""+ raise NotImplementedError++ async def create_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ ) -> WorkspaceBase:+ """Not implemented — team-tool tests never touch this."""+ raise NotImplementedError++ async def close(self, workspace_id: str) -> None:+ """No-op."""++ async def close_all(self) -> None:+ """No-op."""diff --git a/tests/workspace_docker_test.py b/tests/workspace_docker_test.pyindex 96c278002..016f3e42b 100644--- a/tests/workspace_docker_test.py+++ b/tests/workspace_docker_test.py@@ -54,10 +54,10 @@ from agentscope.message import (from agentscope.permission import PermissionBehavior, PermissionDecisionfrom agentscope.tool import ToolBase, ToolChunkfrom agentscope.workspace import DockerWorkspace-from agentscope.workspace._docker._make_dockerfile import (- CONTAINER_SESSIONS_DIR,- CONTAINER_SKILLS_DIR,-)+from agentscope.workspace._docker._make_dockerfile import CONTAINER_WORKDIR++CONTAINER_SKILLS_DIR = f"{CONTAINER_WORKDIR}/skills"+CONTAINER_SESSIONS_DIR = f"{CONTAINER_WORKDIR}/sessions"# ── docker daemon detection ────────────────────────────────────────diff --git a/tests/workspace_e2b_test.py b/tests/workspace_e2b_test.pyindex 384c9f6cd..2a5a8a7e3 100644--- a/tests/workspace_e2b_test.py+++ b/tests/workspace_e2b_test.py@@ -26,7 +26,7 @@ class TestE2BWorkspaceLifecycle(IsolatedAsyncioTestCase):"""Test cases for E2BWorkspace lifecycle and MCP integration.Each test creates a real E2B cloud sandbox and tears it down- (``pause``) afterwards. The suite is skipped entirely when+ (``pause``) afterward. The suite is skipped entirely when``E2B_API_KEY`` is absent so that CI runs without E2B credentialsare unaffected."""diff --git a/tests/workspace_k8s_test.py b/tests/workspace_k8s_test.pynew file mode 100644index 000000000..8dac2ca64--- /dev/null+++ b/tests/workspace_k8s_test.py@@ -0,0 +1,420 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+"""Integration tests for :class:`K8sWorkspace`.++These tests exercise a real Kubernetes cluster (kind is used in CI).+The whole module is skipped when either:++* the current platform is not Linux, or+* ``K8S_TEST_IMAGE`` is not set (the pre-baked test image name), or+* ``kubectl`` is not on ``PATH`` (kind cluster not provisioned).++Each test uses a fresh ``workspace_id`` so PVCs/Pods never collide, and+``delete_pvc_on_close=True`` so no residue is left in the cluster.++The pre-baked image (see ``tests/docker/k8s_workspace_test.Dockerfile``)+ships the gateway script at ``GATEWAY_HOME``, so ``initialize()`` skips+bootstrap and each test finishes in ~15 s.+"""+import os+import shutil+import sys+import tempfile+import unittest+import uuid+from unittest.async_case import IsolatedAsyncioTestCase++from agentscope.mcp import MCPClient, StdioMCPConfig+from agentscope.workspace import K8sWorkspace+from agentscope.workspace._k8s._constants import (+ GATEWAY_HOME,+ POD_WORKDIR,+)++# ── cluster availability check ────────────────────────────────────++_TEST_IMAGE = os.getenv("K8S_TEST_IMAGE", "")+_TEST_NAMESPACE = os.getenv("K8S_TEST_NAMESPACE", "agentscope")+_KIND_AVAILABLE = (+ sys.platform.startswith("linux")+ and bool(_TEST_IMAGE)+ and shutil.which("kubectl") is not None+)+_SKIP_REASON = (+ "requires linux + K8S_TEST_IMAGE + kubectl (kind cluster). "+ "See tests/docker/k8s_workspace_test.Dockerfile and the "+ "``k8s-workspace-tests`` CI job."+)+++def _new_workspace(**overrides: object) -> K8sWorkspace:+ """Construct a K8sWorkspace pinned to the pre-baked test image.++ Args:+ **overrides:+ Additional/replacement kwargs forwarded to+ :class:`K8sWorkspace`.++ Returns:+ `K8sWorkspace`:+ A workspace with a unique ``workspace_id``, tiny PVC, and+ ``delete_pvc_on_close=True`` so tests never leak state.+ """+ kwargs: dict[str, object] = {+ "workspace_id": f"test-{uuid.uuid4().hex[:8]}",+ "image": _TEST_IMAGE,+ "image_pull_policy": "Never", # image is `kind load`-ed+ "namespace": _TEST_NAMESPACE,+ "storage_size": "100Mi",+ "delete_pvc_on_close": True,+ }+ kwargs.update(overrides)+ return K8sWorkspace(**kwargs) # type: ignore[arg-type]+++def _write_skill_dir(root: str, name: str, description: str) -> str:+ """Create a minimal, valid skill directory on the host.++ Args:+ root (`str`):+ Parent directory for the new skill.+ name (`str`):+ Skill name; also used as directory basename and written+ into the ``SKILL.md`` front matter.+ description (`str`):+ Skill description for the front matter.++ Returns:+ `str`:+ Absolute path to the created skill directory.+ """+ skill_dir = os.path.join(root, name)+ os.makedirs(skill_dir, exist_ok=True)+ with open(+ os.path.join(skill_dir, "SKILL.md"),+ "w",+ encoding="utf-8",+ ) as f:+ f.write(+ f"---\nname: {name}\ndescription: {description}\n---\n\n"+ f"# {name}\n\n{description}\n",+ )+ return skill_dir+++# ── happy-path: bootstrap + skills + mcps + backend all share ────+# a single Pod to minimise total CI time. Each section below cleans+# up whatever it added so subsequent sections start from a known+# state. Destructive scenarios (reset, close) get their own class /+# workspace further down.++[email protected](_KIND_AVAILABLE, _SKIP_REASON)+class TestK8sWorkspaceHappyPath(IsolatedAsyncioTestCase):+ """Scenarios 1 + 2 + 3 + 7 exercised against a single Pod.++ Every section restores the workspace to a clean state before the+ next section runs, so ordering is not fragile — but ``unittest``+ runs test methods alphabetically anyway and there is only one+ test method here on purpose.+ """++ async def asyncSetUp(self) -> None:+ """Start a single workspace + host-side scratch dir."""+ # pylint: disable=consider-using-with+ self._skills_src = tempfile.TemporaryDirectory()+ self._ws = _new_workspace()+ await self._ws.initialize()+ self._backend = self._ws.get_backend()++ async def asyncTearDown(self) -> None:+ """Tear the workspace down and drop the scratch dir."""+ try:+ await self._ws.close()+ finally:+ self._skills_src.cleanup()++ async def test_workspace_end_to_end(self) -> None:+ """Cover bootstrap artefacts, skills CRUD, MCP CRUD + call, and+ every public backend API against one Pod.++ Sections:++ 1. **Bootstrap** — verify every workdir / gateway artefact.+ 2. **Skills** — ``add_skill`` → ``list_skills`` → ``remove_skill``.+ 3. **MCPs** — register a pure-Python MCP (``uvx+ mcp-server-time``), list it, call ``list_raw_tools`` on+ it, deregister.+ 4. **Backend** — exec_shell (success / nonzero / cwd),+ write_file + read_file roundtrip (binary, nested path),+ file_exists, delete_path, join_path.+ """+ backend = self._backend+ ws = self._ws++ # ── 1. Bootstrap artefacts ───────────────────────────────+ artefact_paths = [+ f"{POD_WORKDIR}/data",+ f"{POD_WORKDIR}/skills",+ f"{POD_WORKDIR}/sessions",+ f"{POD_WORKDIR}/.mcp",+ f"{GATEWAY_HOME}/_mcp_gateway_app.py",+ f"{GATEWAY_HOME}/_glob_helper.py",+ f"{GATEWAY_HOME}/.venv/bin/python",+ ]+ artefact_state = {+ p: await backend.file_exists(p) for p in artefact_paths+ }+ self.assertDictEqual(+ artefact_state,+ {p: True for p in artefact_paths},+ )++ # ── 2. Skills CRUD ───────────────────────────────────────+ skill_path = _write_skill_dir(+ self._skills_src.name,+ "greeter",+ "Says hi.",+ )+ self.assertListEqual(await ws.list_skills(), [])++ await ws.add_skill(skill_path)+ skills = await ws.list_skills()+ self.assertEqual(len(skills), 1)+ self.assertEqual(+ (skills[0].name, skills[0].description, skills[0].dir),+ ("greeter", "Says hi.", f"{POD_WORKDIR}/skills/greeter"),+ )++ await ws.remove_skill("greeter")+ self.assertListEqual(await ws.list_skills(), [])++ # ── 3. MCP CRUD + call (pure Python stdio MCP) ──────────+ mcp_client = MCPClient(+ name="time",+ is_stateful=True,+ mcp_config=StdioMCPConfig(+ command="uvx",+ args=["mcp-server-time"],+ ),+ )+ self.assertListEqual(await ws.list_mcps(), [])++ await ws.add_mcp(mcp_client)+ mcps = await ws.list_mcps()+ self.assertEqual(len(mcps), 1)+ self.assertEqual(mcps[0].name, "time")++ tools = await mcps[0].list_raw_tools()+ self.assertGreater(len(tools), 0)++ await ws.remove_mcp("time")+ self.assertListEqual(await ws.list_mcps(), [])++ # ── 4. Backend public API ───────────────────────────────+ # 4a. exec_shell success+ r_ok = await backend.exec_shell(["echo", "hello"])+ self.assertEqual(+ (r_ok.exit_code, r_ok.stdout.strip(), r_ok.ok()),+ (0, b"hello", True),+ )++ # 4b. exec_shell non-zero exit + stderr+ r_bad = await backend.exec_shell(+ ["sh", "-c", "echo boom >&2; exit 3"],+ )+ self.assertEqual(+ (r_bad.exit_code, r_bad.ok(), b"boom" in r_bad.stderr),+ (3, False, True),+ )++ # 4c. exec_shell honours cwd+ r_cwd = await backend.exec_shell(["pwd"], cwd=POD_WORKDIR)+ self.assertEqual(+ (r_cwd.exit_code, r_cwd.stdout.strip()),+ (0, POD_WORKDIR.encode()),+ )++ # 4d. write_file → read_file roundtrip, binary safe+ blob_path = f"{POD_WORKDIR}/data/blob.bin"+ blob = bytes(range(256)) * 16 # 4 KiB, all byte values+ await backend.write_file(blob_path, blob)+ self.assertEqual(await backend.read_file(blob_path), blob)++ # 4e. write_file mkdir -p+ nested = f"{POD_WORKDIR}/data/nested/deeper/note.txt"+ await backend.write_file(nested, b"nested")+ self.assertEqual(await backend.read_file(nested), b"nested")++ # 4f. read_file on missing path+ with self.assertRaises(FileNotFoundError):+ await backend.read_file(f"{POD_WORKDIR}/does_not_exist")++ # 4g. file_exists reflects delete_path (files + directories)+ tree_dir = f"{POD_WORKDIR}/data/tree"+ tree_child = f"{tree_dir}/child.txt"+ await backend.write_file(tree_child, b"child")+ await backend.delete_path(blob_path)+ await backend.delete_path(tree_dir)+ self.assertDictEqual(+ {+ blob_path: await backend.file_exists(blob_path),+ tree_dir: await backend.file_exists(tree_dir),+ },+ {blob_path: False, tree_dir: False},+ )++ # 4h. join_path is a pure string op+ self.assertEqual(+ backend.join_path("/workspace", "data", "x.txt"),+ "/workspace/data/x.txt",+ )+++# ── destructive: reset ───────────────────────────────────────────++[email protected](_KIND_AVAILABLE, _SKIP_REASON)+class TestK8sWorkspaceReset(IsolatedAsyncioTestCase):+ """Scenario 5: ``reset`` wipes workspace state without killing the+ Pod or the gateway. Isolated because it is destructive."""++ async def asyncSetUp(self) -> None:+ """Host-side temp dir for a seed skill."""+ # pylint: disable=consider-using-with+ self._skills_src = tempfile.TemporaryDirectory()++ async def asyncTearDown(self) -> None:+ """Drop the staging dir."""+ self._skills_src.cleanup()++ async def test_reset_clears_dirs_mcps_skills_but_keeps_gateway(+ self,+ ) -> None:+ """After ``reset``: dirs empty, MCPs gone, skills gone,+ gateway still alive.++ Verifies:++ 1. Seed a skill file under ``skills/`` and a file under+ ``sessions/``.+ 2. After ``reset``:+ - ``list_skills`` and ``list_mcps`` return empty lists,+ - ``sessions/`` and ``data/`` directories no longer exist,+ - the gateway script under ``GATEWAY_HOME`` is untouched+ (proves the Pod / gateway are still alive).+ """+ skill_path = _write_skill_dir(+ self._skills_src.name,+ "sample",+ "sample skill",+ )+ ws = _new_workspace()+ try:+ await ws.initialize()+ backend = ws.get_backend()++ # Seed state.+ await ws.add_skill(skill_path)+ await backend.write_file(+ f"{POD_WORKDIR}/sessions/s1/context.jsonl",+ b'{"msg": "hi"}\n',+ )+ self.assertEqual(len(await ws.list_skills()), 1)++ await ws.reset()++ state_after = {+ "skills": await ws.list_skills(),+ "mcps": await ws.list_mcps(),+ "sessions_exists": await backend.file_exists(+ f"{POD_WORKDIR}/sessions",+ ),+ "data_exists": await backend.file_exists(+ f"{POD_WORKDIR}/data",+ ),+ "gateway_alive": await backend.file_exists(+ f"{GATEWAY_HOME}/_mcp_gateway_app.py",+ ),+ }+ self.assertDictEqual(+ state_after,+ {+ "skills": [],+ "mcps": [],+ "sessions_exists": False,+ "data_exists": False,+ "gateway_alive": True,+ },+ )+ finally:+ await ws.close()+++# ── destructive: close ───────────────────────────────────────────++[email protected](_KIND_AVAILABLE, _SKIP_REASON)+class TestK8sWorkspaceClose(IsolatedAsyncioTestCase):+ """Scenario 4: ``close`` tears down cleanly and is idempotent.+ Isolated because it terminates the workspace."""++ async def test_close_is_idempotent_and_releases_backend(self) -> None:+ """Two consecutive ``close`` calls succeed; backend is released.++ Verifies:++ 1. After initialize, ``get_backend`` returns a backend.+ 2. First ``close`` succeeds.+ 3. Second ``close`` on the same workspace is a no-op (no+ exception raised) — matches the docstring contract+ "errors are swallowed so close is always safe to call".+ """+ ws = _new_workspace()+ await ws.initialize()+ self.assertIsNotNone(ws.get_backend())++ await ws.close()+ # Second close must not raise.+ await ws.close()+++# ── local-only: get_instructions text ─────────────────────────────+++class TestK8sWorkspaceInstructions(IsolatedAsyncioTestCase):+ """Scenario 6: ``get_instructions`` renders the workspace prompt.++ Pure local check — no cluster needed, so *not* skip-guarded.+ """++ async def test_get_instructions_substitutes_workdir_in_template(+ self,+ ) -> None:+ """Custom ``instructions`` template has ``{workdir}`` filled in."""+ ws = K8sWorkspace(+ workspace_id="prompt-only",+ instructions="Workdir is {workdir}; nothing else.",+ )+ self.assertEqual(+ await ws.get_instructions(),+ f"Workdir is {POD_WORKDIR}; nothing else.",+ )++ async def test_get_instructions_default_template_mentions_workdir(+ self,+ ) -> None:+ """Default template renders and mentions the Pod workdir."""+ ws = K8sWorkspace(workspace_id="prompt-default")+ text = await ws.get_instructions()+ # Assert on the full rendered string as a golden of the default+ # template — reviewers see intent at a glance.+ self.assertIn(POD_WORKDIR, text)+ self.assertIn("Kubernetes-based workspace", text)+ self.assertIn("data/", text)+ self.assertIn("skills/", text)+ self.assertIn("sessions/", text)+++if __name__ == "__main__":+ unittest.main()