Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(workspace): add bubblewrap workspace backend (#2051)
Trefoil7af58b119bdd
diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.ymlindex 3b9fd773a..04670f51d 100644--- a/.github/workflows/unittest.yml+++ b/.github/workflows/unittest.yml@@ -18,6 +18,11 @@ jobs:uses: astral-sh/setup-uv@v5with:python-version: ${{ matrix.python-version }}+ - name: Install Bubblewrap (Linux only)+ if: runner.os == 'Linux'+ run: |+ sudo apt-get update+ sudo apt-get install -y bubblewrap- name: Install Dev Dependenciesrun: |uv pip install -q -e .[dev]@@ -29,4 +34,4 @@ jobs:coverage run -m pytest tests- name: Generate coverage reportrun: |- coverage report -m\ No newline at end of file+ coverage report -mdiff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.pyindex 745967157..fd7a0016c 100644--- a/src/agentscope/app/workspace_manager/__init__.py+++ b/src/agentscope/app/workspace_manager/__init__.py@@ -9,11 +9,13 @@ from ._e2b_workspace_manager import E2BWorkspaceManagerfrom ._daytona_workspace_manager import DaytonaWorkspaceManagerfrom ._k8s_workspace_manager import K8sWorkspaceManagerfrom ._opensandbox_workspace_manager import OpenSandboxWorkspaceManager+from ._bubblewrap_workspace_manager import BubblewrapWorkspaceManager__all__ = ["IsolationPolicy","WorkspaceManagerBase","LocalWorkspaceManager",+ "BubblewrapWorkspaceManager","DockerWorkspaceManager","E2BWorkspaceManager","DaytonaWorkspaceManager",diff --git a/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.pynew file mode 100644index 000000000..86dccbffc--- /dev/null+++ b/src/agentscope/app/workspace_manager/_bubblewrap_workspace_manager.py@@ -0,0 +1,272 @@+# -*- coding: utf-8 -*-+"""BubblewrapWorkspaceManager -- lifecycle manager for Bubblewrap."""++from __future__ import annotations++import asyncio+import hashlib+import os+import time+from typing import Self++from typing_extensions import deprecated++from ..._logging import logger+from ..._utils._common import _generate_id+from ...mcp import MCPClient+from ...workspace import BubblewrapWorkspace+from ...workspace._bubblewrap._constants import DEFAULT_GATEWAY_PORT+from ._base import IsolationPolicy, WorkspaceManagerBase++DEFAULT_SWEEP_INTERVAL = 300.0+++def _safe_component(value: str) -> str:+ """Hash an external identifier into a filesystem-safe component."""+ return hashlib.blake2b(+ value.encode("utf-8"),+ digest_size=16,+ ).hexdigest()+++class BubblewrapWorkspaceManager(WorkspaceManagerBase):+ """Manage Bubblewrap workspaces with TTL caching.++ Explicit ``workspace_id`` values must be globally unique across users;+ the cache is keyed by workspace id while the host path also includes the+ user id.+ """++ def __init__(+ self,+ basedir: str,+ *,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,+ gateway_port: int | None = DEFAULT_GATEWAY_PORT,+ share_net: bool = True,+ env: dict[str, str] | None = None,+ extra_pip: list[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,+ ) -> None:+ """Initialize the Bubblewrap workspace manager.++ Args:+ basedir (`str`):+ Host root for per-user/per-workspace workdirs.+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for assigned workspace ids.+ gateway_port (`int | None`, optional):+ In-sandbox MCP gateway port. ``None`` lets each workspace+ allocate an available loopback port during initialization.+ share_net (`bool`, defaults to `True`):+ Must be ``True`` for the current Bubblewrap workspace TCP+ gateway design.+ env (`dict[str, str] | None`, optional):+ Extra environment variables for every workspace.+ extra_pip (`list[str] | None`, optional):+ Extra gateway venv requirements.+ default_mcps (`list[MCPClient] | None`, optional):+ MCPs seeded into new workspaces.+ skill_paths (`list[str] | None`, optional):+ Skill dirs seeded into new workspaces.+ ttl (`float`, defaults to `3600.0`):+ Seconds before an idle workspace is evicted.+ sweep_interval (`float`, defaults to `300.0`):+ Seconds between sweeper ticks.+ """+ if not basedir.strip():+ raise ValueError("basedir must not be empty.")+ BubblewrapWorkspace._validate_gateway_port(gateway_port)+ if not share_net:+ raise ValueError(+ "BubblewrapWorkspaceManager currently requires "+ "share_net=True because BubblewrapWorkspace uses a TCP MCP "+ "gateway across separate bwrap executions.",+ )++ self._basedir = os.path.abspath(basedir)+ self._gateway_port = gateway_port+ self._share_net = share_net+ self._env = dict(env or {})+ self._extra_pip = list(extra_pip or [])+ self._default_mcps = list(default_mcps or [])+ self._skill_paths = list(skill_paths or [])+ self._ttl = ttl+ self._sweep_interval = sweep_interval+ super().__init__(isolation=isolation)++ self._cache: dict[str, tuple[BubblewrapWorkspace, float]] = {}+ self._lock = asyncio.Lock()+ self._sweep_task: asyncio.Task[None] | None = None++ def _workdir_for(self, user_id: str, workspace_id: str) -> str:+ """Resolve the host workdir for ``(user_id, workspace_id)``."""+ path = os.path.join(+ self._basedir,+ _safe_component(user_id),+ _safe_component(workspace_id),+ )+ basedir = os.path.realpath(self._basedir)+ real_path = os.path.realpath(path)+ if os.path.commonpath([basedir, real_path]) != basedir:+ raise PermissionError("Bubblewrap workdir escapes basedir.")+ return path++ async def _build_and_start(+ self,+ *,+ workspace_id: str,+ user_id: str,+ agent_id: str,+ ) -> BubblewrapWorkspace:+ """Construct and initialize a Bubblewrap workspace."""+ del agent_id+ workdir = self._workdir_for(user_id, workspace_id)+ os.makedirs(workdir, mode=0o700, exist_ok=True)+ os.chmod(workdir, 0o700)+ ws = BubblewrapWorkspace(+ workspace_id=workspace_id,+ host_workdir=workdir,+ gateway_port=self._gateway_port,+ share_net=self._share_net,+ env=self._env,+ extra_pip=self._extra_pip,+ default_mcps=self._default_mcps,+ skill_paths=self._skill_paths,+ )+ await ws.initialize()+ return ws++ async def get_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace_id: str | None = None,+ ) -> BubblewrapWorkspace:+ """Return an initialized workspace, creating it on cache miss."""+ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id=user_id,+ agent_id=agent_id,+ session_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++ ws = await self._build_and_start(+ workspace_id=workspace_id,+ user_id=user_id,+ agent_id=agent_id,+ )+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ @deprecated(+ "BubblewrapWorkspaceManager.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,+ ) -> BubblewrapWorkspace:+ """Build a brand-new workspace and track it."""+ del session_id+ workspace_id = _generate_id()+ ws = await self._build_and_start(+ workspace_id=workspace_id,+ user_id=user_id,+ agent_id=agent_id,+ )+ 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."""+ 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 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 sweeper, then close cached workspaces."""+ 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()++ 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("Bubblewrap workspace sweeper tick failed")++ async def _sweep_once(self) -> None:+ """One sweeper tick: evict expired entries."""+ 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: BubblewrapWorkspace) -> None:+ """Close a workspace, logging failures instead of raising."""+ try:+ await ws.close()+ except Exception:+ logger.exception(+ "Failed to close BubblewrapWorkspace %s",+ ws.workspace_id,+ )diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.pyindex 700359af1..db7bce710 100644--- a/src/agentscope/workspace/__init__.py+++ b/src/agentscope/workspace/__init__.py@@ -10,11 +10,14 @@ from ._e2b import E2BWorkspace, E2BBackendfrom ._daytona import DaytonaBackend, DaytonaWorkspacefrom ._k8s import K8sBackend, K8sWorkspacefrom ._opensandbox import OpenSandboxBackend, OpenSandboxWorkspace+from ._bubblewrap import BubblewrapBackend, BubblewrapWorkspace__all__ = ["WorkspaceBase","LocalWorkspace",+ "BubblewrapBackend",+ "BubblewrapWorkspace","DockerBackend","DockerWorkspace","E2BBackend",diff --git a/src/agentscope/workspace/_bubblewrap/__init__.py b/src/agentscope/workspace/_bubblewrap/__init__.pynew file mode 100644index 000000000..dd1a487a8--- /dev/null+++ b/src/agentscope/workspace/_bubblewrap/__init__.py@@ -0,0 +1,7 @@+# -*- coding: utf-8 -*-+"""Bubblewrap-backed workspace."""++from ._bubblewrap_backend import BubblewrapBackend+from ._bubblewrap_workspace import BubblewrapWorkspace++__all__ = ["BubblewrapBackend", "BubblewrapWorkspace"]diff --git a/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py b/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.pynew file mode 100644index 000000000..27bfe878c--- /dev/null+++ b/src/agentscope/workspace/_bubblewrap/_bubblewrap_backend.py@@ -0,0 +1,567 @@+# -*- coding: utf-8 -*-+"""Bubblewrap :class:`BackendBase` implementation.++The backend launches each command through ``bwrap`` with a stable host+directory mounted at ``/workspace`` and a stable host temp directory+mounted at ``/tmp``. Those two writable mounts are enough for the shared+workspace implementation, gateway request shims, skills, and offload data.+"""++from __future__ import annotations++import asyncio+import os+import posixpath+import signal+from pathlib import PurePosixPath+from typing import Any++from ...tool import BackendBase, ExecResult+from ._constants import SANDBOX_CACHE_DIR, SANDBOX_TMPDIR, SANDBOX_WORKDIR+++class BubblewrapBackend(BackendBase):+ """Backend that executes commands inside Bubblewrap sandboxes.++ Args:+ host_workdir (`str`):+ Host directory mounted read-write at ``/workspace``.+ host_tmpdir (`str`):+ Host directory mounted read-write at ``/tmp``.+ host_cache_dir (`str | None`, optional):+ Host directory mounted at ``/tmp/.agentscope-cache`` for package+ manager caches. Isolation depends on whether callers provide a+ workspace-private or shared host directory. It must not overlap+ ``host_workdir`` or ``host_tmpdir``, or resolve through a+ symbolic-link root.+ workdir (`str`, optional):+ Default sandbox working directory.+ share_net (`bool`, optional):+ Keep host networking visible inside the sandbox. When+ ``False``, the network namespace created by ``--unshare-all``+ remains isolated.+ env (`dict[str, str] | None`, optional):+ Extra environment variables for sandboxed processes.+ """++ def __init__(+ self,+ *,+ host_workdir: str,+ host_tmpdir: str,+ host_cache_dir: str | None = None,+ workdir: str = SANDBOX_WORKDIR,+ share_net: bool = True,+ env: dict[str, str] | None = None,+ ) -> None:+ if not host_workdir.strip():+ raise ValueError("host_workdir must not be empty.")+ if not host_tmpdir.strip():+ raise ValueError("host_tmpdir must not be empty.")+ if host_cache_dir is not None and not host_cache_dir.strip():+ raise ValueError("host_cache_dir must not be empty.")+ host_workdir_path = os.path.abspath(host_workdir)+ host_tmpdir_path = os.path.abspath(host_tmpdir)+ workdir_created = not os.path.lexists(host_workdir_path)+ tmpdir_created = not os.path.lexists(host_tmpdir_path)+ os.makedirs(host_workdir_path, mode=0o700, exist_ok=True)+ os.makedirs(host_tmpdir_path, mode=0o700, exist_ok=True)+ if workdir_created:+ os.chmod(host_workdir_path, 0o700)+ if tmpdir_created:+ os.chmod(host_tmpdir_path, 0o700)+ self._host_workdir = os.path.realpath(host_workdir_path)+ self._host_tmpdir = os.path.realpath(host_tmpdir_path)+ self._host_workdir_identity = self._directory_identity(+ self._host_workdir,+ label="host_workdir",+ )+ self._host_tmpdir_identity = self._directory_identity(+ self._host_tmpdir,+ label="host_tmpdir",+ )+ mount_sources: list[tuple[str, str]] = [+ ("host_workdir", self._host_workdir),+ ("host_tmpdir", self._host_tmpdir),+ ]+ self._host_cache_dir: str | None = None+ self._host_cache_identity: tuple[int, int] | None = None+ cache_dir: str | None = None+ if host_cache_dir is not None:+ cache_dir = os.path.abspath(host_cache_dir)+ if os.path.lexists(cache_dir) and os.path.islink(cache_dir):+ raise ValueError("host_cache_dir must not be a symbolic link.")+ cache_realpath = os.path.realpath(cache_dir)+ self._host_cache_dir = cache_realpath+ mount_sources.append(("host_cache_dir", cache_realpath))+ for index, (left_name, left_path) in enumerate(mount_sources):+ for right_name, right_path in mount_sources[index + 1 :]:+ if self._paths_overlap(left_path, right_path):+ raise ValueError(+ f"{left_name} must not overlap {right_name}.",+ )+ if cache_dir is not None:+ cache_created = not os.path.lexists(cache_dir)+ os.makedirs(cache_dir, mode=0o700, exist_ok=True)+ if cache_created:+ os.chmod(cache_dir, 0o700)+ if not os.path.isdir(cache_dir):+ raise ValueError("host_cache_dir must be a directory.")+ assert self._host_cache_dir is not None+ self._host_cache_identity = self._directory_identity(+ self._host_cache_dir,+ label="host_cache_dir",+ )+ self._workdir = workdir+ self._share_net = share_net+ self._env = dict(env or {})++ async def getcwd(self) -> str:+ """Return the backend's default working directory."""+ return self._workdir++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Run an argv list inside a fresh Bubblewrap process."""+ if not command:+ return ExecResult(+ exit_code=127,+ stdout=b"",+ stderr=b"empty command",+ )++ try:+ process = await self.start_process(+ command,+ cwd=cwd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ except (FileNotFoundError, NotADirectoryError, OSError) as exc:+ return ExecResult(+ exit_code=127,+ stdout=b"",+ stderr=str(exc).encode("utf-8"),+ )++ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(),+ timeout=timeout,+ )+ except asyncio.TimeoutError:+ await self._terminate_process_tree(process, grace=1.0)+ return ExecResult(exit_code=-1, stdout=b"", stderr=b"timed out")+ except BaseException:+ await asyncio.shield(+ self._terminate_process_tree(process, grace=1.0),+ )+ raise++ return ExecResult(+ exit_code=process.returncode or 0,+ stdout=stdout,+ stderr=stderr,+ )++ async def start_process(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ stdin: Any = asyncio.subprocess.DEVNULL,+ stdout: Any = asyncio.subprocess.DEVNULL,+ stderr: Any = asyncio.subprocess.DEVNULL,+ ) -> asyncio.subprocess.Process:+ """Start a long-running command inside Bubblewrap.++ Used by :class:`BubblewrapWorkspace` to keep the MCP gateway as a+ tracked subprocess instead of daemonizing it inside the sandbox.+ """+ argv = self._bwrap_argv(command, cwd=cwd)+ kwargs: dict[str, Any] = {}+ if os.name != "nt":+ kwargs["start_new_session"] = True+ return await asyncio.create_subprocess_exec(+ *argv,+ stdin=stdin,+ stdout=stdout,+ stderr=stderr,+ **kwargs,+ )++ @staticmethod+ async def _terminate_process_tree(+ process: asyncio.subprocess.Process,+ *,+ grace: float,+ ) -> None:+ """Terminate a process group, falling back to the process itself."""+ if process.returncode is not None:+ return++ if os.name != "nt":+ try:+ os.killpg(process.pid, signal.SIGTERM)+ except ProcessLookupError:+ try:+ process.terminate()+ except ProcessLookupError:+ return+ try:+ await asyncio.wait_for(process.wait(), timeout=grace)+ return+ except asyncio.TimeoutError:+ try:+ os.killpg(process.pid, signal.SIGKILL)+ except ProcessLookupError:+ try:+ process.kill()+ except ProcessLookupError:+ return+ await process.wait()+ return++ try:+ process.terminate()+ await asyncio.wait_for(process.wait(), timeout=grace)+ except asyncio.TimeoutError:+ try:+ process.kill()+ except ProcessLookupError:+ return+ await process.wait()+ except ProcessLookupError:+ return++ async def read_file(self, path: str) -> bytes:+ """Read a sandbox file as raw bytes.++ Files under ``/workspace`` and ``/tmp`` are read by a command running+ inside Bubblewrap. The in-sandbox check resolves the target and+ rejects anything outside the writable mounts, which stops a symlink+ from redirecting reads to a read-only system mount or another device.+ This is a best-effort check inside the sandbox, not a guard against a+ target swapped between the resolve and the read.+ """+ sandbox_path = self._sandbox_path_for(path)+ result = await self.exec_shell(+ [+ "sh",+ "-c",+ (+ 'resolved=$(realpath -e -- "$1") || exit 66; '+ 'case "$resolved" in '+ "/workspace|/workspace/*|/tmp|/tmp/*) "+ 'cat -- "$resolved" ;; '+ "*) exit 65 ;; "+ "esac"+ ),+ "sh",+ sandbox_path,+ ],+ )+ if result.exit_code == 66:+ raise FileNotFoundError(f"not found in Bubblewrap sandbox: {path}")+ if result.exit_code == 65:+ raise PermissionError(+ f"path escapes writable Bubblewrap mounts: {path}",+ )+ if not result.ok():+ raise RuntimeError(+ "Bubblewrap read_file failed "+ f"(exit {result.exit_code}): "+ f"{result.stderr.decode(errors='replace')}",+ )+ return result.stdout++ async def write_file(self, path: str, data: bytes) -> None:+ """Write raw bytes, refusing every symbolic-link final component."""+ sandbox_path = self._sandbox_path_for(path)+ result = await self._exec_with_input(+ [+ "sh",+ "-c",+ (+ 'parent=$(dirname -- "$1") && '+ 'resolved_parent=$(realpath -m -- "$parent") || exit 65; '+ 'case "$resolved_parent" in '+ "/workspace|/workspace/*|/tmp|/tmp/*) ;; "+ "*) exit 65 ;; "+ "esac; "+ 'mkdir -p -- "$resolved_parent" && '+ 'target="$resolved_parent/$(basename -- "$1")" && '+ '[ ! -L "$target" ] || exit 65; '+ 'cat > "$target"'+ ),+ "sh",+ sandbox_path,+ ],+ data,+ )+ if result.exit_code == 65:+ raise PermissionError(+ f"path escapes writable Bubblewrap mounts: {path}",+ )+ if not result.ok():+ raise RuntimeError(+ "Bubblewrap write_file failed "+ f"(exit {result.exit_code}): "+ f"{result.stderr.decode(errors='replace')}",+ )++ async def _exec_with_input(+ self,+ command: list[str],+ data: bytes,+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Run a sandbox command with ``data`` piped to stdin."""+ try:+ process = await self.start_process(+ command,+ cwd=cwd,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ except (FileNotFoundError, NotADirectoryError, OSError) as exc:+ return ExecResult(+ exit_code=127,+ stdout=b"",+ stderr=str(exc).encode("utf-8"),+ )++ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(data),+ timeout=timeout,+ )+ except asyncio.TimeoutError:+ await self._terminate_process_tree(process, grace=1.0)+ return ExecResult(exit_code=-1, stdout=b"", stderr=b"timed out")+ except BaseException:+ await asyncio.shield(+ self._terminate_process_tree(process, grace=1.0),+ )+ raise++ return ExecResult(+ exit_code=process.returncode or 0,+ stdout=stdout,+ stderr=stderr,+ )++ def _bwrap_argv(+ self,+ command: list[str],+ *,+ cwd: str | None,+ ) -> list[str]:+ """Build the ``bwrap`` argv for one sandboxed process."""+ self._validate_mount_sources()++ # ``--bind``/``--ro-bind``/``--tmpfs`` all create their destination+ # mount points (including parents), so an explicit ``--dir`` before a+ # same-path mount is redundant. ``--dir /var`` is kept because the+ # tmpfs below only covers ``/var/tmp``.+ args = [+ "bwrap",+ "--die-with-parent",+ "--new-session",+ "--unshare-all",+ "--proc",+ "/proc",+ "--dev",+ "/dev",+ "--bind",+ self._host_workdir,+ SANDBOX_WORKDIR,+ "--bind",+ self._host_tmpdir,+ SANDBOX_TMPDIR,+ "--tmpfs",+ "/run",+ "--dir",+ "/var",+ "--tmpfs",+ "/var/tmp",+ ]+ if self._host_cache_dir is not None:+ args.extend(+ [+ "--bind",+ self._host_cache_dir,+ SANDBOX_CACHE_DIR,+ ],+ )+ if self._share_net:+ args.append("--share-net")++ args.extend(self._readonly_system_mounts())++ sandbox_cwd = cwd or self._workdir+ env = dict(self._env)+ env.update(self._base_env())+ env["PWD"] = sandbox_cwd+ args.append("--clearenv")+ for key, value in env.items():+ args.extend(["--setenv", key, str(value)])++ args.extend(["--chdir", sandbox_cwd, "--"])+ args.extend(command)+ return args++ def _validate_mount_sources(self) -> None:+ """Ensure bind sources were not removed or replaced."""+ for label, path, expected_identity in (+ (+ "host_workdir",+ self._host_workdir,+ self._host_workdir_identity,+ ),+ (+ "host_tmpdir",+ self._host_tmpdir,+ self._host_tmpdir_identity,+ ),+ ):+ try:+ identity = self._directory_identity(path, label=label)+ except ValueError as exc:+ raise RuntimeError(+ f"{label} was removed or replaced before execution.",+ ) from exc+ if identity != expected_identity:+ raise RuntimeError(+ f"{label} was replaced before execution.",+ )++ if self._host_cache_dir is None:+ return+ try:+ identity = self._directory_identity(+ self._host_cache_dir,+ label="host_cache_dir",+ )+ except ValueError as exc:+ raise RuntimeError(+ "host_cache_dir was removed or replaced before execution.",+ ) from exc+ if identity != self._host_cache_identity:+ raise RuntimeError(+ "host_cache_dir was replaced before execution.",+ )++ @staticmethod+ def _directory_identity(+ path: str,+ *,+ label: str,+ ) -> tuple[int, int]:+ """Return a stable identity for a real directory mount source."""+ if os.path.islink(path) or not os.path.isdir(path):+ raise ValueError(f"{label} must be a real directory: {path}")+ stat_result = os.stat(path, follow_symlinks=False)+ return stat_result.st_dev, stat_result.st_ino++ @staticmethod+ def _paths_overlap(left: str, right: str) -> bool:+ """Return whether either real path contains the other."""+ left_real = os.path.realpath(left)+ right_real = os.path.realpath(right)+ try:+ common = os.path.commonpath([left_real, right_real])+ except ValueError:+ return False+ return common in (left_real, right_real)++ def _base_env(self) -> dict[str, str]:+ """Environment visible to sandboxed commands."""+ path_parts = [+ f"{SANDBOX_WORKDIR}/.agentscope/.venv/bin",+ f"{SANDBOX_WORKDIR}/.agentscope/bin",+ "/usr/local/sbin",+ "/usr/local/bin",+ "/usr/sbin",+ "/usr/bin",+ "/sbin",+ "/bin",+ ]+ return {+ "HOME": SANDBOX_WORKDIR,+ "TMPDIR": SANDBOX_TMPDIR,+ "UV_CACHE_DIR": f"{SANDBOX_CACHE_DIR}/uv",+ "XDG_CACHE_HOME": f"{SANDBOX_CACHE_DIR}/xdg",+ "PIP_CACHE_DIR": f"{SANDBOX_CACHE_DIR}/pip",+ "PATH": ":".join(path_parts),+ "LANG": "C.UTF-8",+ "LC_ALL": "C.UTF-8",+ "PYTHONUNBUFFERED": "1",+ }++ def _readonly_system_mounts(self) -> list[str]:+ """Mount host system directories read-only inside the sandbox."""+ args: list[str] = []+ for path in ("/usr",):+ if os.path.exists(path):+ args.extend(["--ro-bind", path, path])+ args.extend(self._readonly_etc_mounts())++ for path in ("/bin", "/sbin", "/lib", "/lib64"):+ if not os.path.exists(path):+ continue+ if os.path.islink(path):+ args.extend(["--symlink", os.readlink(path), path])+ else:+ args.extend(["--ro-bind", path, path])+ return args++ @staticmethod+ def _readonly_etc_mounts() -> list[str]:+ """Mount only host ``/etc`` entries needed for networking/runtime."""+ args = ["--dir", "/etc"]+ for path in (+ "/etc/resolv.conf",+ "/etc/hosts",+ "/etc/nsswitch.conf",+ "/etc/passwd",+ "/etc/group",+ ):+ if os.path.exists(path):+ args.extend(["--ro-bind", path, path])+ for path in (+ "/etc/alternatives",+ "/etc/ssl",+ "/etc/pki",+ "/etc/ca-certificates",+ ):+ if os.path.exists(path):+ args.extend(["--ro-bind", path, path])+ return args++ def _sandbox_path_for(self, path: str) -> str:+ """Validate and normalize a writable sandbox path."""+ sandbox_path = PurePosixPath(path)+ if not sandbox_path.is_absolute():+ raise ValueError(f"Sandbox path must be absolute: {path!r}")++ normalized = posixpath.normpath(path)+ for sandbox_root in (SANDBOX_WORKDIR, SANDBOX_TMPDIR):+ if normalized == sandbox_root:+ return normalized+ prefix = sandbox_root + "/"+ if normalized.startswith(prefix):+ return normalized++ raise PermissionError(+ "Bubblewrap file access is limited to "+ f"{SANDBOX_WORKDIR!r} and {SANDBOX_TMPDIR!r}: {path!r}",+ )diff --git a/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.py b/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.pynew file mode 100644index 000000000..1838f65ce--- /dev/null+++ b/src/agentscope/workspace/_bubblewrap/_bubblewrap_workspace.py@@ -0,0 +1,660 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access,consider-using-with+"""BubblewrapWorkspace -- sandboxed workspace backed by ``bwrap``."""++from __future__ import annotations++import asyncio+import hashlib+import os+import secrets+import shlex+import shutil+import socket+import sys+import tempfile+from typing import Any++from ..._logging import logger+from ...mcp import MCPClient+from .._gateway_client import GatewayClient+from .._sandboxed_base import SandboxedWorkspaceBase+from .._utils import (+ _GATEWAY_BASE_REQUIREMENTS,+ _read_gateway_script_bytes,+ _read_glob_helper_bytes,+)+from ._bubblewrap_backend import BubblewrapBackend+from ._constants import (+ BWRAP_SMOKE_PROBE_ARGV,+ DEFAULT_GATEWAY_PORT,+ GATEWAY_HOME,+ SANDBOX_CACHE_DIR,+ SANDBOX_WORKDIR,+)++_DEFAULT_INSTRUCTIONS = """<workspace>+You have a Bubblewrap-based Linux workspace. All tool calls execute+inside the sandbox at ``{workdir}``.++Layout:++```+{workdir}/+|-- data/ # offloaded multimodal files+|-- skills/ # reusable skills+`-- sessions/ # session context and tool results+```+</workspace>"""+++class BubblewrapWorkspace(SandboxedWorkspaceBase):+ """Workspace backed by Linux Bubblewrap.++ .. warning::+ This is **not** a network sandbox. The current TCP MCP gateway+ requires ``share_net=True`` so gateway requests from later ``bwrap``+ executions can reach the long-lived gateway process over host+ loopback. Sandboxed code therefore shares the host network namespace+ and can reach any service the host can — other loopback services,+ internal endpoints, and cloud metadata (e.g. ``169.254.169.254``).+ The gateway bearer token only guards the gateway itself, not the rest+ of the host network. Bubblewrap still isolates other namespaces and+ the mounted filesystem; only the network namespace is shared.++ ``host_workdir`` is mounted read-write at ``/workspace``. When it is+ omitted, an ephemeral temp directory is created and removed on close.+ Bootstrap caches are stored outside ``host_workdir`` by default, and the+ backend detects mount-source replacement before launching Bubblewrap. An+ explicit ``host_cache_dir`` must not overlap ``host_workdir`` or the+ backend's temporary directory; sharing one cache between mutually trusted+ workspaces is an opt-in tradeoff.+ """++ _gateway_home = GATEWAY_HOME+ _bootstrap_cmd_timeout = 1800.0++ def __init__(+ self,+ *,+ workspace_id: str | None = None,+ host_workdir: str | None = None,+ host_cache_dir: str | None = None,+ gateway_port: int | None = DEFAULT_GATEWAY_PORT,+ share_net: bool = True,+ env: dict[str, str] | None = None,+ extra_pip: list[str] | None = None,+ instructions: str = _DEFAULT_INSTRUCTIONS,+ default_mcps: list[MCPClient] | None = None,+ skill_paths: list[str] | None = None,+ ) -> None:+ """Construct a :class:`BubblewrapWorkspace`.++ Args:+ workspace_id (`str | None`, optional):+ Stable workspace identifier.+ host_workdir (`str | None`, optional):+ Host directory mounted at ``/workspace``. Omit for an+ ephemeral workspace.+ host_cache_dir (`str | None`, optional):+ Host directory mounted at ``/tmp/.agentscope-cache`` for+ package caches. Omit to use a workspace-private cache outside+ ``host_workdir``. An explicit path must not overlap the+ workspace or its temporary directory. Supplying a shared+ directory weakens cross-workspace isolation and should only be+ used for mutually trusted workspaces.+ gateway_port (`int | None`, optional):+ TCP port used by the in-sandbox gateway. ``None`` allocates+ an available loopback port during initialization.+ share_net (`bool`, defaults to `True`):+ Must be ``True`` for this workspace because the TCP MCP+ gateway is reached across separate ``bwrap`` executions.+ env (`dict[str, str] | None`, optional):+ Extra environment variables for sandboxed commands.+ extra_pip (`list[str] | None`, optional):+ Extra Python requirements installed into the gateway venv.+ For a persistent ``host_workdir``, keep this list stable+ across workspace instances; changing it does not currently+ invalidate an existing Bootstrap environment.+ instructions (`str`, optional):+ System-prompt fragment template.+ default_mcps (`list[MCPClient] | None`, optional):+ MCPs seeded on first initialization.+ skill_paths (`list[str] | None`, optional):+ Local skill directories seeded on first initialization.+ """+ self._validate_gateway_port(gateway_port)+ if not share_net:+ raise ValueError(+ "BubblewrapWorkspace currently requires share_net=True "+ "because its TCP MCP gateway must be reachable across "+ "separate bwrap executions.",+ )+ if host_workdir is not None and not host_workdir.strip():+ raise ValueError("host_workdir must not be empty.")+ if host_cache_dir is not None and not host_cache_dir.strip():+ raise ValueError("host_cache_dir must not be empty.")++ super().__init__(+ workspace_id=workspace_id,+ default_mcps=default_mcps,+ skill_paths=skill_paths,+ )++ self.workdir = SANDBOX_WORKDIR+ self.gateway_port = gateway_port+ self._gateway_port_input = gateway_port+ self._gateway_token = ""+ self._gateway_nonce = ""+ self._rotate_gateway_credentials()+ self.share_net = share_net+ self.env = dict(env or {})+ self.extra_pip = list(extra_pip or [])+ self.instructions = instructions++ self._host_workdir_input = host_workdir+ self._host_cache_dir_input = (+ os.path.abspath(host_cache_dir) if host_cache_dir else None+ )+ self._owned_workdir: tempfile.TemporaryDirectory[str] | None = None+ self._owned_cache_dir: tempfile.TemporaryDirectory[str] | None = None+ self.host_workdir = (+ os.path.abspath(host_workdir) if host_workdir else ""+ )+ self._tmpdir: tempfile.TemporaryDirectory[str] | None = None+ self._host_cache_dir = (+ os.path.abspath(host_cache_dir) if host_cache_dir else ""+ )+ self._backend: BubblewrapBackend | None = None+ self._gateway_process: asyncio.subprocess.Process | None = None++ @staticmethod+ def _validate_gateway_port(gateway_port: int | None) -> None:+ """Validate the configured TCP port before provisioning."""+ if gateway_port is None:+ return+ if (+ isinstance(gateway_port, bool)+ or not isinstance(gateway_port, int)+ or not 1 <= gateway_port <= 65535+ ):+ raise ValueError(+ "gateway_port must be None or an integer from 1 to 65535.",+ )++ @property+ def is_persistent(self) -> bool:+ """Whether the workspace files survive ``close``."""+ return self._host_workdir_input is not None++ async def _provision_backend(self) -> None:+ """Validate Bubblewrap availability and bind the backend."""+ if not sys.platform.startswith("linux"):+ raise RuntimeError("BubblewrapWorkspace requires Linux.")+ if shutil.which("bwrap") is None:+ raise RuntimeError("BubblewrapWorkspace requires 'bwrap' on PATH.")+ await self._probe_bubblewrap()+ if self._host_workdir_input is None:+ self._owned_workdir = tempfile.TemporaryDirectory()+ self.host_workdir = self._owned_workdir.name+ else:+ self.host_workdir = os.path.abspath(self._host_workdir_input)+ workdir_created = not os.path.lexists(self.host_workdir)+ os.makedirs(self.host_workdir, mode=0o700, exist_ok=True)+ if not os.path.isdir(self.host_workdir):+ raise ValueError("host_workdir must be a directory.")+ if workdir_created:+ os.chmod(self.host_workdir, 0o700)++ if (+ self._host_workdir_input is None+ and self._host_cache_dir_input is None+ ):+ self._owned_cache_dir = tempfile.TemporaryDirectory(+ prefix="agentscope-bwrap-cache-",+ )+ self._host_cache_dir = self._owned_cache_dir.name+ else:+ self._host_cache_dir = self._resolve_host_cache_dir()+ self._tmpdir = tempfile.TemporaryDirectory()+ self._backend = BubblewrapBackend(+ host_workdir=self.host_workdir,+ host_tmpdir=self._tmpdir.name,+ host_cache_dir=self._host_cache_dir,+ workdir=SANDBOX_WORKDIR,+ share_net=self.share_net,+ env=self.env,+ )++ def _resolve_host_cache_dir(self) -> str:+ """Create and return a safe external cache directory."""+ workdir = os.path.realpath(self.host_workdir)+ if self._host_cache_dir_input is not None:+ path = os.path.abspath(self._host_cache_dir_input)+ make_private = False+ else:+ key = hashlib.blake2b(+ workdir.encode("utf-8"),+ digest_size=16,+ ).hexdigest()+ cache_root = os.path.join(+ os.path.dirname(workdir),+ ".agentscope-bwrap-cache",+ )+ self._ensure_cache_directory(+ cache_root,+ make_private=True,+ )+ path = os.path.join(+ cache_root,+ key,+ )+ make_private = True++ if os.path.lexists(path) and os.path.islink(path):+ raise ValueError("host_cache_dir must not be a symbolic link.")+ cache_dir = os.path.realpath(path)+ try:+ common = os.path.commonpath([workdir, cache_dir])+ except ValueError:+ common = ""+ if common in (workdir, cache_dir):+ raise ValueError(+ "host_cache_dir must not overlap host_workdir because it "+ "is used as a Bubblewrap bind source.",+ )++ self._ensure_cache_directory(+ path,+ make_private=make_private,+ )+ return os.path.realpath(path)++ @staticmethod+ def _ensure_cache_directory(+ path: str,+ *,+ make_private: bool,+ ) -> None:+ """Create a cache directory without accepting a symlink root."""+ if os.path.lexists(path) and os.path.islink(path):+ raise ValueError("host_cache_dir must not be a symbolic link.")+ created = not os.path.lexists(path)+ os.makedirs(path, mode=0o700, exist_ok=True)+ if os.path.islink(path) or not os.path.isdir(path):+ raise ValueError("host_cache_dir must be a real directory.")+ if created or make_private:+ os.chmod(path, 0o700)++ async def initialize(self) -> None:+ """Initialize and clean up partial resources on failure."""+ try:+ await super().initialize()+ except BaseException:+ try:+ await asyncio.shield(self.close())+ except BaseException:+ logger.exception(+ "Bubblewrap cleanup after init failure failed",+ )+ raise++ async def _teardown_backend(self) -> None:+ """Terminate the gateway process and clean ephemeral directories."""+ try:+ await self._stop_gateway_process()+ except Exception as exc:+ logger.warning("Failed to stop Bubblewrap gateway: %s", exc)+ self._backend = None+ if self._tmpdir is not None:+ try:+ self._tmpdir.cleanup()+ except Exception as exc:+ logger.warning("Failed to clean Bubblewrap tmpdir: %s", exc)+ finally:+ self._tmpdir = None+ if self._owned_cache_dir is not None:+ try:+ self._owned_cache_dir.cleanup()+ except Exception as exc:+ logger.warning("Failed to clean Bubblewrap cache: %s", exc)+ finally:+ self._owned_cache_dir = None+ if self._host_cache_dir_input is None:+ self._host_cache_dir = ""+ if self._owned_workdir is not None:+ try:+ self._owned_workdir.cleanup()+ except Exception as exc:+ logger.warning("Failed to clean Bubblewrap workdir: %s", exc)+ finally:+ self._owned_workdir = None+ if self._host_workdir_input is None:+ self.host_workdir = ""++ async def get_instructions(self) -> str:+ """Return the system-prompt fragment for this workspace."""+ return self.instructions.format(workdir=SANDBOX_WORKDIR)++ async def _setup_mcp_gateway(self) -> None:+ """Bootstrap and launch a tracked Bubblewrap gateway process."""+ backend = self.get_backend()++ if not await self._bootstrap_is_ready():+ logger.info(+ "BubblewrapWorkspace: bootstrapping or repairing "+ "workspace_id=%r",+ self.workspace_id,+ )+ for cmd in self._bootstrap_commands():+ result = await backend.exec_shell(+ ["sh", "-c", cmd],+ timeout=self._bootstrap_cmd_timeout,+ )+ if not result.ok():+ raise RuntimeError(+ "BubblewrapWorkspace bootstrap failed "+ f"(exit {result.exit_code}) for: {cmd!r}\n"+ f"stderr: {result.stderr.decode(errors='replace')}\n"+ f"stdout: {result.stdout.decode(errors='replace')}",+ )++ # These scripts are part of the installed AgentScope runtime rather+ # than user state, so refresh them even when a persistent workspace's+ # bootstrap artifacts are already usable.+ await backend.write_file(+ self._glob_helper_path,+ _read_glob_helper_bytes(),+ )+ await backend.write_file(+ self._gateway_script,+ _read_gateway_script_bytes(),+ )++ max_attempts = 3 if self._gateway_port_input is None else 1+ health_timeout = 30.0+ for attempt in range(max_attempts):+ if self._gateway_port_input is None:+ self.gateway_port = self._allocate_gateway_port()+ gateway_port = self.gateway_port+ assert gateway_port is not None+ await self._stop_gateway_process()+ self._rotate_gateway_credentials()++ launch_cmd = (+ f"exec {shlex.quote(self._gateway_python)} -I -u "+ f"{shlex.quote(self._gateway_script)} "+ f"--config {shlex.quote(self._mcp_file)} "+ f"--port {gateway_port} "+ f"--auth-token {shlex.quote(self._gateway_token)} "+ f"--instance-nonce {shlex.quote(self._gateway_nonce)} "+ f"> {shlex.quote(self._gateway_log)} 2>&1"+ )+ self._gateway_process = await backend.start_process(+ ["sh", "-c", launch_cmd],+ cwd=SANDBOX_WORKDIR,+ )++ self._gateway = GatewayClient(+ backend=backend,+ gateway_port=gateway_port,+ timeout=30.0,+ gateway_log_path=self._gateway_log,+ auth_token=self._gateway_token,+ instance_nonce=self._gateway_nonce,+ )+ if await self._wait_gateway_health(health_timeout):+ break+ if attempt == max_attempts - 1:+ await self._raise_gateway_timeout(health_timeout)+ await self._stop_gateway_process()+ else: # pragma: no cover - loop always breaks or raises+ await self._raise_gateway_timeout(health_timeout)++ self._mcps = list(await self._gateway.list_mcps())++ async def _bootstrap_is_ready(self) -> bool:+ """Check whether persisted user-space bootstrap artifacts work."""+ result = await self.get_backend().exec_shell(+ [+ "sh",+ "-c",+ (+ 'test -f "$1" && '+ 'test -x "$2" && '+ '"$2" --version >/dev/null 2>&1 && '+ "\"$2\" -I -c 'import agentscope, fastapi, uvicorn, mcp' "+ ">/dev/null 2>&1 && "+ '"$3" --version >/dev/null 2>&1 && '+ '"$4" --version >/dev/null 2>&1'+ ),+ "sh",+ self._gateway_script,+ self._gateway_python,+ f"{self._gateway_home}/bin/uv",+ f"{self._gateway_home}/bin/rg",+ ],+ timeout=30.0,+ )+ return result.ok()++ def _rotate_gateway_credentials(self) -> None:+ """Rotate per-launch gateway auth token and health nonce."""+ self._gateway_token = secrets.token_urlsafe(32)+ self._gateway_nonce = secrets.token_urlsafe(32)++ async def _wait_gateway_health(self, timeout: float) -> bool:+ """Wait for the tracked gateway process to answer health checks."""+ assert self._gateway is not None+ deadline = asyncio.get_event_loop().time() + timeout+ delay = 0.1+ while asyncio.get_event_loop().time() < deadline:+ if (+ self._gateway_process is not None+ and self._gateway_process.returncode is not None+ ):+ return False+ if await self._gateway.health():+ return True+ await asyncio.sleep(delay)+ delay = min(delay * 1.5, 1.0)+ return await self._gateway.health()++ @staticmethod+ def _allocate_gateway_port() -> int:+ """Return an available loopback TCP port for the gateway."""+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])++ @staticmethod+ async def _probe_bubblewrap() -> None:+ """Run a minimal Bubblewrap command to verify runtime support."""+ proc: asyncio.subprocess.Process | None = None+ kwargs: dict[str, Any] = {}+ if os.name != "nt":+ kwargs["start_new_session"] = True+ try:+ proc = await asyncio.create_subprocess_exec(+ *BWRAP_SMOKE_PROBE_ARGV,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ **kwargs,+ )+ stdout, stderr = await asyncio.wait_for(+ proc.communicate(),+ timeout=5.0,+ )+ except asyncio.TimeoutError as exc:+ if proc is not None:+ await BubblewrapBackend._terminate_process_tree(+ proc,+ grace=1.0,+ )+ raise RuntimeError(+ "BubblewrapWorkspace bwrap smoke probe timed out.",+ ) from exc+ except (FileNotFoundError, NotADirectoryError, OSError) as exc:+ raise RuntimeError(+ "BubblewrapWorkspace requires Linux and a working "+ "'bwrap' executable.",+ ) from exc+ except BaseException:+ if proc is not None:+ await asyncio.shield(+ BubblewrapBackend._terminate_process_tree(+ proc,+ grace=1.0,+ ),+ )+ raise++ if proc.returncode != 0:+ detail = (stderr or stdout).decode("utf-8", errors="replace")+ raise RuntimeError(+ "BubblewrapWorkspace requires Linux and a working "+ f"'bwrap' executable. Smoke probe failed: {detail}",+ )++ def _bootstrap_commands(self) -> list[str]:+ """Return user-space provisioning commands for Bubblewrap."""+ pip_pkgs = [+ *_GATEWAY_BASE_REQUIREMENTS,+ *self.extra_pip,+ ]+ pip_args = " ".join(shlex.quote(p) for p in pip_pkgs)+ bin_dir = f"{self._gateway_home}/bin"+ uv_path = shlex.quote(f"{bin_dir}/uv")+ rg_path = shlex.quote(f"{bin_dir}/rg")+ python_path = shlex.quote(self._gateway_python)+ return [+ f"mkdir -p {shlex.quote(bin_dir)}",+ f"if ! {uv_path} --version >/dev/null 2>&1; then "+ f"rm -f {uv_path}; "+ f"{self._install_uv_script(bin_dir)}; "+ "fi",+ f"if ! {python_path} --version >/dev/null 2>&1; then "+ f"rm -rf {shlex.quote(self._gateway_venv)}; "+ f"{uv_path} venv {shlex.quote(self._gateway_venv)}; "+ "fi",+ f"{uv_path} pip install --python {python_path} " f"{pip_args}",+ f"if ! {rg_path} --version >/dev/null 2>&1; then "+ f"rm -f {rg_path}; "+ f"{self._install_ripgrep_script()}; "+ "fi",+ f"{rg_path} --version",+ f"{uv_path} pip install --python {python_path} "+ "--no-deps 'agentscope'",+ ]++ @staticmethod+ def _install_uv_script(bin_dir: str) -> str:+ """Return shell code that downloads and executes the uv installer."""+ quoted_bin_dir = shlex.quote(bin_dir)+ return (+ "set -eu; "+ "tmp_installer=$(mktemp); "+ 'cleanup_installer() { rm -f "$tmp_installer"; }; '+ "trap cleanup_installer EXIT INT TERM; "+ "curl -LsSf --retry 5 --retry-delay 2 --retry-all-errors "+ "--connect-timeout 15 --max-time 60 --retry-max-time 180 "+ '-o "$tmp_installer" '+ "https://astral.sh/uv/install.sh; "+ f"env UV_INSTALL_DIR={quoted_bin_dir} "+ 'INSTALLER_NO_MODIFY_PATH=1 sh "$tmp_installer"; '+ 'rm -f "$tmp_installer"; '+ "trap - EXIT INT TERM"+ )++ def _install_ripgrep_script(self) -> str:+ """Return shell code that installs official ripgrep release assets."""+ bin_dir = shlex.quote(f"{self._gateway_home}/bin")+ cache_dir = shlex.quote(f"{SANDBOX_CACHE_DIR}/ripgrep")+ version = "14.1.0"+ base_url = (+ "https://github.com/BurntSushi/ripgrep/releases/download/"+ f"{version}"+ )+ curl_release_asset = (+ "curl -fL --retry 5 --retry-delay 2 --retry-all-errors "+ "--connect-timeout 15 --max-time 90 --retry-max-time 180"+ )+ x86_64_sha256 = (+ "f84757b07f425fe5cf11d87df6644691"+ "c644a5cd2348a2c670894272999d3ba7"+ )+ aarch64_sha256 = (+ "c8c210b99844fbf16b7a36d1c963e835"+ "1bca5ff2dd7c788f5fba4ac18ba8c60d"+ )+ return (+ "set -eu; "+ "arch=$(uname -m); "+ 'case "$arch" in '+ "x86_64|amd64) "+ f"asset=ripgrep-{version}-x86_64-unknown-linux-musl.tar.gz; "+ f"sha256={x86_64_sha256} ;; "+ "aarch64|arm64) "+ f"asset=ripgrep-{version}-aarch64-unknown-linux-gnu.tar.gz; "+ f"sha256={aarch64_sha256} ;; "+ "*) echo "+ '"unsupported ripgrep architecture: $arch" >&2; exit 1 ;; '+ "esac; "+ f"mkdir -p {cache_dir} {bin_dir}; "+ f"cd {cache_dir}; "+ 'if ! printf "%s %s\\n" "$sha256" "$asset" '+ "| sha256sum -c - >/dev/null 2>&1; then "+ 'tmp_asset=$(mktemp "${asset}.tmp.XXXXXX"); '+ 'cleanup_asset() { rm -f "$tmp_asset"; }; '+ "trap cleanup_asset EXIT INT TERM; "+ f'{curl_release_asset} -o "$tmp_asset" '+ f'{shlex.quote(base_url)}/"$asset"; '+ 'printf "%s %s\\n" "$sha256" "$tmp_asset" '+ "| sha256sum -c -; "+ 'mv -f "$tmp_asset" "$asset"; '+ "trap - EXIT INT TERM; "+ "fi; "+ "tmp=$(mktemp -d); "+ 'tar -xzf "$asset" -C "$tmp"; '+ f"tmp_rg=$(mktemp {bin_dir}/.rg.tmp.XXXXXX); "+ 'cleanup_rg() { rm -f "$tmp_rg"; }; '+ "trap cleanup_rg EXIT INT TERM; "+ 'cp "$tmp"/ripgrep-*/rg "$tmp_rg"; '+ 'chmod +x "$tmp_rg"; '+ f'mv -f "$tmp_rg" {bin_dir}/rg; '+ "trap - EXIT INT TERM; "+ 'rm -rf "$tmp"'+ )++ async def _stop_gateway_process(self) -> None:+ """Terminate any tracked gateway process."""+ proc = self._gateway_process+ if proc is None:+ return+ try:+ if proc.returncode is None:+ await BubblewrapBackend._terminate_process_tree(+ proc,+ grace=5.0,+ )+ finally:+ if proc.returncode is not None:+ self._gateway_process = None++ async def _raise_gateway_timeout(self, timeout: float) -> None:+ """Raise a gateway-start failure with the log tail included."""+ try:+ log = await self.get_backend().read_file(self._gateway_log)+ tail = log[-2000:].decode(errors="replace")+ except Exception:+ tail = "<no gateway log available>"+ code = (+ self._gateway_process.returncode+ if self._gateway_process is not None+ else None+ )+ raise RuntimeError(+ f"gateway did not become healthy within {timeout}s "+ f"(process returncode={code}). Tail of {self._gateway_log}:\n"+ f"{tail}",+ )diff --git a/src/agentscope/workspace/_bubblewrap/_constants.py b/src/agentscope/workspace/_bubblewrap/_constants.pynew file mode 100644index 000000000..702dfbbf7--- /dev/null+++ b/src/agentscope/workspace/_bubblewrap/_constants.py@@ -0,0 +1,26 @@+# -*- coding: utf-8 -*-+"""Constants for Bubblewrap-backed workspaces."""++DEFAULT_GATEWAY_PORT = None++SANDBOX_WORKDIR = "/workspace"+SANDBOX_TMPDIR = "/tmp"+SANDBOX_CACHE_DIR = f"{SANDBOX_TMPDIR}/.agentscope-cache"+GATEWAY_HOME = f"{SANDBOX_WORKDIR}/.agentscope"++BWRAP_SMOKE_PROBE_ARGV = [+ "bwrap",+ "--die-with-parent",+ "--new-session",+ "--unshare-all",+ "--share-net",+ "--ro-bind",+ "/",+ "/",+ "--proc",+ "/proc",+ "--dev",+ "/dev",+ "--",+ "true",+]diff --git a/src/agentscope/workspace/_gateway_client.py b/src/agentscope/workspace/_gateway_client.pyindex 6749c6f2e..95b3d7da8 100644--- a/src/agentscope/workspace/_gateway_client.py+++ b/src/agentscope/workspace/_gateway_client.py@@ -25,6 +25,7 @@ from __future__ import annotationsimport base64import json+import secretsimport uuidfrom typing import TYPE_CHECKING, Any@@ -366,6 +367,8 @@ class GatewayClient:inline_limit: int = BODY_INLINE_LIMIT,tmp_dir: str = SANDBOX_TMP_DIR,gateway_log_path: str | None = None,+ auth_token: str | None = None,+ instance_nonce: str | None = None,) -> None:"""Build a workspace-side gateway facade.@@ -392,6 +395,13 @@ class GatewayClient:a ``/health`` probe and — if the gateway isunreachable — a tail of this log is emitted at``ERROR`` level to help diagnose crashes.+ auth_token (`str | None`, defaults to `None`):+ Optional bearer token forwarded to the gateway by the+ in-sandbox shim.+ instance_nonce (`str | None`, defaults to `None`):+ Optional nonce expected from ``/health``. Used by shared+ network backends to make sure the probed port belongs to the+ gateway process that was just launched before sending auth."""self.backend = backendself.gateway_port = gateway_port@@ -399,6 +409,8 @@ class GatewayClient:self.inline_limit = inline_limitself.tmp_dir = tmp_dirself.gateway_log_path = gateway_log_path+ self.auth_token = auth_token+ self.instance_nonce = instance_nonce# 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.@@ -408,9 +420,13 @@ class GatewayClient:self._log_tail_bytes: int = 4000async def health(self) -> bool:- """Probe ``/health``. ``True`` iff the gateway answered 200;+ """Probe ``/health``.any other outcome (shim transport failure, non-200) → ``False``.- Callers retry until this flips.+ With no expected ``instance_nonce``, HTTP 200 means healthy. When a+ nonce is configured, the response must be a JSON object containing the+ matching ``instance_nonce``. Transport failures, non-200 responses,+ malformed JSON, non-object JSON, and nonce mismatches return+ ``False``.The ``/health`` path is treated specially by:meth:`exec_request` — it never triggers the failure@@ -418,10 +434,30 @@ class GatewayClient:itself."""try:- status, _ = await self.exec_request("GET", "/health")+ status, body = await self.exec_request(+ "GET",+ "/health",+ include_auth=False,+ )except Exception:return False- return status == 200+ if status != 200:+ return False+ if self.instance_nonce is None:+ return True+ try:+ payload = json.loads(body)+ except (json.JSONDecodeError, UnicodeDecodeError, TypeError):+ return False+ if not isinstance(payload, dict):+ return False+ nonce = payload.get("instance_nonce")+ return (+ isinstance(nonce, str)+ and nonce.isascii()+ and self.instance_nonce.isascii()+ and secrets.compare_digest(nonce, self.instance_nonce)+ )async def list_mcps(self) -> list[GatewayMCPClient]:"""Fetch every MCP the gateway is currently serving.@@ -477,6 +513,7 @@ class GatewayClient:path: str,*,body: Any = None,+ include_auth: bool = True,) -> tuple[int, bytes]:"""Relay one HTTP request through the sandbox.@@ -503,6 +540,10 @@ class GatewayClient:Path-only URL, e.g. ``/mcps/<name>/tools/<tool>``.body (`Any`, optional):JSON-serializable request body; ``None`` for no body.+ include_auth (`bool`, defaults to `True`):+ Whether to send the configured bearer token to the shim.+ Health probes set this to ``False`` so a port-race cannot+ leak the token to a process that is not the gateway.Returns:`tuple[int, bytes]`:@@ -535,6 +576,7 @@ class GatewayClient:body_file,str(self.inline_limit),self.tmp_dir,+ (self.auth_token or "") if include_auth else "",],timeout=self.timeout,)diff --git a/src/agentscope/workspace/_gateway_shim.py b/src/agentscope/workspace/_gateway_shim.pyindex 5ac4052a3..6573a86b5 100644--- a/src/agentscope/workspace/_gateway_shim.py+++ b/src/agentscope/workspace/_gateway_shim.py@@ -44,6 +44,7 @@ SANDBOX_TMP_DIR = "/tmp"# 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)+# argv[6] = auth_token or "" (optional bearer token)SHIM_SCRIPT = r"""import sys, json, base64, uuid, osimport urllib.request, urllib.error@@ -53,6 +54,7 @@ url = sys.argv[2]body_file = sys.argv[3]inline_limit = int(sys.argv[4])tmp_dir = sys.argv[5]+auth_token = sys.argv[6] if len(sys.argv) > 6 else ""body = Noneif body_file:@@ -62,6 +64,8 @@ if body_file:req = urllib.request.Request(url, data=body, method=method)if body is not None:req.add_header("Content-Type", "application/json")+if auth_token:+ req.add_header("Authorization", "Bearer " + auth_token)try:with urllib.request.urlopen(req) as resp:diff --git a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.pyindex 8c8ed16e2..47d503fcf 100644--- a/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py+++ b/src/agentscope/workspace/_mcp_gateway/_mcp_gateway_app.py@@ -4,8 +4,9 @@Runs inside the workspace environment as a standalone script. Reads``--config`` — a JSON list of ``MCPClient.model_dump()`` dicts (sameformat 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.+entry, and exposes per-server HTTP endpoints. Authentication is optional.+Sandboxes sharing a host network namespace can enable a bearer token to+prevent cross-workspace gateway access.Endpoints::@@ -24,6 +25,7 @@ gateway does not need).import argparseimport asyncioimport json+import secretsfrom typing import Anyfrom fastapi import FastAPI, HTTPException, Request@@ -51,12 +53,38 @@ async def _build_client(spec: dict[str, Any]) -> MCPClient:return client-def _build_app(state: _State) -> FastAPI:+def _build_app(+ state: _State,+ auth_token: str | None = None,+ instance_nonce: str | None = None,+) -> FastAPI:"""Build the FastAPI app with all routes wired against ``state``."""app = FastAPI(title="agentscope-workspace-mcp-gateway")- @app.get("/health")- async def _health() -> PlainTextResponse:+ if auth_token:++ @app.middleware("http")+ async def _auth_middleware(request: Request, call_next: Any) -> Any:+ if request.url.path == "/health":+ return await call_next(request)+ header = request.headers.get("authorization", "")+ expected = f"Bearer {auth_token}"+ valid = (+ header.isascii()+ and expected.isascii()+ and secrets.compare_digest(header, expected)+ )+ if not valid:+ return PlainTextResponse(+ "invalid gateway token",+ status_code=401,+ )+ return await call_next(request)++ @app.get("/health", response_model=None)+ async def _health() -> Any:+ if instance_nonce is not None:+ return {"status": "ok", "instance_nonce": instance_nonce}return PlainTextResponse("ok")@app.get("/mcps")@@ -139,7 +167,12 @@ async def _connect_initial(print(f"[gateway] connected {client.name!r}", flush=True)-async def _run(config_path: str, port: int) -> None:+async def _run(+ config_path: str,+ port: int,+ auth_token: str | None = None,+ instance_nonce: str | None = None,+) -> None:"""Read config, connect upstreams, start uvicorn, clean up on exit."""with open(config_path, encoding="utf-8") as f:servers = json.load(f)@@ -152,7 +185,11 @@ async def _run(config_path: str, port: int) -> None:state = _State()await _connect_initial(state, servers)- app = _build_app(state)+ app = _build_app(+ state,+ auth_token=auth_token,+ instance_nonce=instance_nonce,+ )print(f"[gateway] serving {len(state.clients)} MCPs on :{port}",flush=True,@@ -182,8 +219,17 @@ def main() -> None:)parser.add_argument("--config", required=True)parser.add_argument("--port", type=int, default=5600)+ parser.add_argument("--auth-token")+ parser.add_argument("--instance-nonce")args = parser.parse_args()- asyncio.run(_run(args.config, args.port))+ asyncio.run(+ _run(+ args.config,+ args.port,+ auth_token=args.auth_token,+ instance_nonce=args.instance_nonce,+ ),+ )if __name__ == "__main__":diff --git a/tests/backend_bubblewrap_test.py b/tests/backend_bubblewrap_test.pynew file mode 100644index 000000000..f99d91c73--- /dev/null+++ b/tests/backend_bubblewrap_test.py@@ -0,0 +1,572 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access,consider-using-with,too-many-public-methods+"""Test cases for :class:`BubblewrapBackend`."""++import os+import shutil+import stat+import subprocess+import sys+import tempfile+import unittest+import asyncio+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch++from agentscope.tool import ExecResult+from agentscope.workspace import BubblewrapBackend+from agentscope.workspace._bubblewrap._constants import (+ BWRAP_SMOKE_PROBE_ARGV,+ SANDBOX_CACHE_DIR,+ SANDBOX_WORKDIR,+)+++def _bubblewrap_available() -> bool:+ """Return ``True`` iff ``bwrap`` can run a trivial command."""+ if not sys.platform.startswith("linux"):+ return False+ if shutil.which("bwrap") is None:+ return False+ try:+ result = subprocess.run(+ BWRAP_SMOKE_PROBE_ARGV,+ capture_output=True,+ timeout=5,+ check=False,+ )+ return result.returncode == 0+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):+ return False+++_BWRAP_OK = _bubblewrap_available()+_SKIP_REASON = "Bubblewrap backend requires Linux with a working bwrap"+++class TestBubblewrapBackendUnit(IsolatedAsyncioTestCase):+ """Unit tests that do not invoke the real ``bwrap`` executable."""++ async def asyncSetUp(self) -> None:+ """Build a backend with host dirs only."""+ # pylint: disable=consider-using-with+ self.workdir = tempfile.TemporaryDirectory()+ self.tmpdir = tempfile.TemporaryDirectory()+ self.backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ )++ async def asyncTearDown(self) -> None:+ """Clean up host dirs."""+ self.workdir.cleanup()+ self.tmpdir.cleanup()++ async def test_bwrap_argv_uses_unshare_all_and_share_net(self) -> None:+ """Default command isolates namespaces and restores networking."""+ argv = self.backend._bwrap_argv(["true"], cwd=None)+ self.assertIn("--unshare-all", argv)+ self.assertIn("--share-net", argv)+ self.assertIn("--new-session", argv)+ self.assertIn("--die-with-parent", argv)+ self.assertIn("--clearenv", argv)++ async def test_bwrap_argv_does_not_mount_opt_by_default(self) -> None:+ """Host /opt is not exposed unless a future explicit mount adds it."""+ argv = self.backend._bwrap_argv(["true"], cwd=None)+ ro_bind_targets = [+ argv[i + 2]+ for i, item in enumerate(argv)+ if item == "--ro-bind" and i + 2 < len(argv)+ ]+ self.assertNotIn("/opt", ro_bind_targets)++ async def test_bwrap_argv_can_unshare_network(self) -> None:+ """``share_net=False`` leaves networking isolated."""+ backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ share_net=False,+ )+ argv = backend._bwrap_argv(["true"], cwd=None)+ self.assertIn("--unshare-all", argv)+ self.assertNotIn("--share-net", argv)++ async def test_bwrap_argv_can_mount_shared_cache(self) -> None:+ """An optional host cache is writable at the sandbox cache path."""+ cache_dir = tempfile.TemporaryDirectory()+ self.addCleanup(cache_dir.cleanup)+ backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ host_cache_dir=cache_dir.name,+ )++ argv = backend._bwrap_argv(["true"], cwd=None)++ self.assertIn(SANDBOX_CACHE_DIR, argv)+ bind_index = argv.index(os.path.realpath(cache_dir.name))+ self.assertEqual(argv[bind_index - 1], "--bind")+ self.assertEqual(argv[bind_index + 1], SANDBOX_CACHE_DIR)++ async def test_replaced_cache_bind_source_is_rejected(self) -> None:+ """A cache root replacement is detected before bwrap starts."""+ with tempfile.TemporaryDirectory() as parent:+ cache_dir = os.path.join(parent, "cache")+ outside_dir = os.path.join(parent, "outside")+ os.makedirs(cache_dir)+ os.makedirs(outside_dir)+ backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ host_cache_dir=cache_dir,+ )++ os.rmdir(cache_dir)+ try:+ os.symlink(outside_dir, cache_dir)+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ with self.assertRaisesRegex(RuntimeError, "removed or replaced"):+ backend._bwrap_argv(["true"], cwd=None)++ async def test_cache_bind_source_cannot_overlap_workdir(self) -> None:+ """Direct backend construction enforces the cache boundary."""+ for cache_dir in (+ os.path.join(self.workdir.name, "cache"),+ os.path.dirname(self.workdir.name),+ ):+ with self.assertRaisesRegex(ValueError, "must not overlap"):+ BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ host_cache_dir=cache_dir,+ )++ async def test_workdir_cannot_overlap_tmpdir(self) -> None:+ """Workspace and tmp bind sources must remain separate."""+ with tempfile.TemporaryDirectory() as parent:+ workdir = os.path.join(parent, "workspace")+ tmpdir = os.path.join(workdir, "tmp")+ with self.assertRaisesRegex(ValueError, "must not overlap"):+ BubblewrapBackend(+ host_workdir=workdir,+ host_tmpdir=tmpdir,+ )++ async def test_cache_cannot_overlap_tmpdir(self) -> None:+ """Cache and tmp bind sources must remain separate."""+ with tempfile.TemporaryDirectory() as parent:+ workdir = os.path.join(parent, "workspace")+ tmpdir = os.path.join(parent, "tmp")+ cache_dir = os.path.join(tmpdir, "cache")+ with self.assertRaisesRegex(ValueError, "must not overlap"):+ BubblewrapBackend(+ host_workdir=workdir,+ host_tmpdir=tmpdir,+ host_cache_dir=cache_dir,+ )++ @unittest.skipIf(os.name == "nt", "POSIX mode bits only")+ async def test_new_host_mounts_use_private_permissions(self) -> None:+ """New backend-owned mount directories use mode 0700."""+ with tempfile.TemporaryDirectory() as parent:+ workdir = os.path.join(parent, "workspace")+ tmpdir = os.path.join(parent, "tmp")+ cache_dir = os.path.join(parent, "cache")++ BubblewrapBackend(+ host_workdir=workdir,+ host_tmpdir=tmpdir,+ host_cache_dir=cache_dir,+ )++ self.assertEqual(+ stat.S_IMODE(os.stat(workdir).st_mode),+ 0o700,+ )+ self.assertEqual(+ stat.S_IMODE(os.stat(tmpdir).st_mode),+ 0o700,+ )+ self.assertEqual(+ stat.S_IMODE(os.stat(cache_dir).st_mode),+ 0o700,+ )++ async def test_rejects_empty_host_paths(self) -> None:+ """Host mount roots must be explicit non-empty paths."""+ with self.assertRaises(ValueError):+ BubblewrapBackend(host_workdir="", host_tmpdir=self.tmpdir.name)+ with self.assertRaises(ValueError):+ BubblewrapBackend(host_workdir=self.workdir.name, host_tmpdir="")+ with self.assertRaises(ValueError):+ BubblewrapBackend(host_workdir=" ", host_tmpdir=self.tmpdir.name)+ with self.assertRaises(ValueError):+ BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=" ",+ )+ with self.assertRaises(ValueError):+ BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ host_cache_dir=" ",+ )++ async def test_native_io_rejects_relative_paths(self) -> None:+ """Native file access requires absolute sandbox paths."""+ with self.assertRaises(ValueError):+ await self.backend.write_file("relative.txt", b"x")++ async def test_native_io_rejects_unmounted_paths(self) -> None:+ """Native file access is limited to ``/workspace`` and ``/tmp``."""+ with self.assertRaises(PermissionError):+ await self.backend.write_file("/etc/hosts", b"x")+ with self.assertRaises(PermissionError):+ await self.backend.read_file("/etc/hosts")++ @unittest.skipUnless(_BWRAP_OK, _SKIP_REASON)+ async def test_native_io_rejects_parent_symlink_escape(self) -> None:+ """A symlinked parent cannot redirect writes outside the sandbox."""+ try:+ os.symlink(+ "/unmounted-dir",+ os.path.join(self.workdir.name, "out"),+ )+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ with self.assertRaises(PermissionError):+ await self.backend.write_file(+ f"{SANDBOX_WORKDIR}/out/file.txt",+ b"x",+ )++ @unittest.skipUnless(_BWRAP_OK, _SKIP_REASON)+ async def test_native_io_rejects_file_symlink_escape(self) -> None:+ """A symlinked file cannot redirect reads outside the sandbox."""+ try:+ os.symlink(+ "/unmounted-secret",+ os.path.join(self.workdir.name, "secret"),+ )+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ with self.assertRaises(FileNotFoundError):+ await self.backend.read_file(f"{SANDBOX_WORKDIR}/secret")++ @unittest.skipUnless(_BWRAP_OK, _SKIP_REASON)+ async def test_native_io_rejects_dangling_file_symlink_write(+ self,+ ) -> None:+ """A dangling symlink cannot redirect writes outside the sandbox."""+ outside = tempfile.TemporaryDirectory()+ self.addCleanup(outside.cleanup)+ outside_file = os.path.join(outside.name, "created.txt")+ try:+ os.symlink(+ outside_file,+ os.path.join(self.workdir.name, "escape"),+ )+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ with self.assertRaises(PermissionError):+ await self.backend.write_file(+ f"{SANDBOX_WORKDIR}/escape",+ b"escaped",+ )+ self.assertFalse(os.path.exists(outside_file))++ @unittest.skipUnless(_BWRAP_OK, _SKIP_REASON)+ async def test_native_io_rejects_symlinks_to_mounted_paths(self) -> None:+ """File helpers cannot redirect through a writable mount boundary."""+ try:+ os.symlink(+ "/etc/hosts",+ os.path.join(self.workdir.name, "system-file"),+ )+ os.symlink(+ "/dev/null",+ os.path.join(self.workdir.name, "device-file"),+ )+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ with self.assertRaises(PermissionError):+ await self.backend.read_file(+ f"{SANDBOX_WORKDIR}/system-file",+ )+ with self.assertRaises(PermissionError):+ await self.backend.write_file(+ f"{SANDBOX_WORKDIR}/device-file",+ b"must not reach /dev/null",+ )++ await self.backend.write_file(+ f"{SANDBOX_WORKDIR}/real-file",+ b"internal target",+ )+ try:+ os.symlink(+ "real-file",+ os.path.join(self.workdir.name, "internal-link"),+ )+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")++ self.assertEqual(+ await self.backend.read_file(+ f"{SANDBOX_WORKDIR}/internal-link",+ ),+ b"internal target",+ )+ with self.assertRaises(PermissionError):+ await self.backend.write_file(+ f"{SANDBOX_WORKDIR}/internal-link",+ b"must be rejected",+ )++ async def test_base_env_cannot_be_overridden(self) -> None:+ """Critical runtime env vars are restored after user env."""+ backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ env={+ "PATH": "/custom",+ "HOME": "/custom-home",+ "TMPDIR": "/custom-tmp",+ "API_KEY": "allowed",+ },+ )+ argv = backend._bwrap_argv(["true"], cwd=None)+ env_pairs = {+ argv[i + 1]: argv[i + 2]+ for i, item in enumerate(argv)+ if item == "--setenv"+ }+ self.assertEqual(env_pairs["HOME"], SANDBOX_WORKDIR)+ self.assertEqual(env_pairs["TMPDIR"], "/tmp")+ self.assertEqual(env_pairs["UV_CACHE_DIR"], f"{SANDBOX_CACHE_DIR}/uv")+ self.assertEqual(env_pairs["PWD"], SANDBOX_WORKDIR)+ self.assertIn(+ f"{SANDBOX_WORKDIR}/.agentscope/.venv/bin",+ env_pairs["PATH"],+ )+ self.assertEqual(env_pairs["API_KEY"], "allowed")++ async def test_pwd_matches_explicit_cwd(self) -> None:+ """PWD follows the sandbox cwd instead of leaking host PWD."""+ argv = self.backend._bwrap_argv(["true"], cwd="/tmp")+ env_pairs = {+ argv[i + 1]: argv[i + 2]+ for i, item in enumerate(argv)+ if item == "--setenv"+ }+ self.assertEqual(env_pairs["PWD"], "/tmp")++ async def test_exec_shell_cancellation_terminates_process_tree(+ self,+ ) -> None:+ """Cancelling ``exec_shell`` still triggers process cleanup."""+ fake_process = AsyncMock()+ fake_process.communicate.side_effect = asyncio.CancelledError()+ fake_process.returncode = None++ with (+ patch.object(+ self.backend,+ "start_process",+ new=AsyncMock(return_value=fake_process),+ ),+ patch.object(+ BubblewrapBackend,+ "_terminate_process_tree",+ new=AsyncMock(),+ ) as terminate,+ ):+ with self.assertRaises(asyncio.CancelledError):+ await self.backend.exec_shell(["sleep", "10"])++ terminate.assert_awaited_once_with(fake_process, grace=1.0)++ async def test_start_process_uses_new_process_group_on_posix(self) -> None:+ """POSIX subprocesses are started in their own process group."""+ with patch(+ "asyncio.create_subprocess_exec",+ new=AsyncMock(return_value=object()),+ ) as create_process:+ await self.backend.start_process(["true"])++ kwargs = create_process.call_args.kwargs+ if os.name == "nt":+ self.assertNotIn("start_new_session", kwargs)+ else:+ self.assertTrue(kwargs["start_new_session"])++[email protected](_BWRAP_OK, _SKIP_REASON)+class TestBubblewrapBackend(IsolatedAsyncioTestCase):+ """Backend primitive tests against live Bubblewrap."""++ async def asyncSetUp(self) -> None:+ """Build a fresh backend and mounted host dirs."""+ # pylint: disable=consider-using-with+ self.workdir = tempfile.TemporaryDirectory()+ self.tmpdir = tempfile.TemporaryDirectory()+ self.backend = BubblewrapBackend(+ host_workdir=self.workdir.name,+ host_tmpdir=self.tmpdir.name,+ )++ async def asyncTearDown(self) -> None:+ """Drop mounted host dirs."""+ self.workdir.cleanup()+ self.tmpdir.cleanup()++ async def test_exec_returns_stdout(self) -> None:+ """A program's stdout and exit code are captured."""+ result = await self.backend.exec_shell(["echo", "hello world"])+ self.assertIsInstance(result, ExecResult)+ self.assertTrue(result.ok())+ self.assertEqual(result.stdout.decode().strip(), "hello world")++ async def test_exec_nonzero_exit(self) -> None:+ """Non-zero exits are returned as normal results."""+ result = await self.backend.exec_shell(+ ["sh", "-c", "echo oops >&2; exit 4"],+ )+ self.assertEqual(result.exit_code, 4)+ self.assertIn("oops", result.stderr.decode())++ async def test_exec_argv_not_shell_split(self) -> None:+ """Metacharacters in one argv element are passed intact."""+ tricky = "a b $(echo x) | ;"+ result = await self.backend.exec_shell(["echo", tricky])+ self.assertTrue(result.ok())+ self.assertEqual(result.stdout.decode().rstrip("\n"), tricky)++ async def test_exec_cwd_default_is_workdir(self) -> None:+ """With no explicit cwd, commands run in ``/workspace``."""+ result = await self.backend.exec_shell(["pwd"])+ self.assertTrue(result.ok())+ self.assertEqual(result.stdout.decode().strip(), SANDBOX_WORKDIR)++ async def test_exec_timeout_returns_minus_one(self) -> None:+ """Timeouts use the standard -1 sentinel."""+ result = await self.backend.exec_shell(["sleep", "10"], timeout=0.2)+ self.assertEqual(result.exit_code, -1)+ self.assertEqual(result.stderr, b"timed out")++ async def test_write_then_read_roundtrip(self) -> None:+ """Bytes written under ``/workspace`` are read back verbatim."""+ path = f"{SANDBOX_WORKDIR}/roundtrip.txt"+ payload = b"hello\nworld\n"+ await self.backend.write_file(path, payload)+ self.assertEqual(await self.backend.read_file(path), payload)++ async def test_write_creates_parent_dirs(self) -> None:+ """``write_file`` creates missing parents."""+ path = f"{SANDBOX_WORKDIR}/a/b/c/file.txt"+ await self.backend.write_file(path, b"x")+ self.assertEqual(await self.backend.read_file(path), b"x")++ async def test_write_preserves_binary(self) -> None:+ """Raw bytes survive the mounted host roundtrip."""+ path = f"{SANDBOX_WORKDIR}/bin.dat"+ payload = b"a\r\nb\x00\xffc"+ await self.backend.write_file(path, payload)+ self.assertEqual(await self.backend.read_file(path), payload)++ async def test_read_missing_file_raises(self) -> None:+ """Reading a missing file raises ``FileNotFoundError``."""+ with self.assertRaises(FileNotFoundError):+ await self.backend.read_file(f"{SANDBOX_WORKDIR}/missing.txt")++ async def test_file_exists_and_is_dir(self) -> None:+ """Inherited existence helpers reflect the sandbox filesystem."""+ path = f"{SANDBOX_WORKDIR}/f.txt"+ await self.backend.write_file(path, b"x")+ self.assertTrue(await self.backend.file_exists(path))+ self.assertTrue(await self.backend.file_exists(SANDBOX_WORKDIR))+ self.assertTrue(await self.backend.is_dir(SANDBOX_WORKDIR))+ self.assertFalse(await self.backend.is_dir(path))++ async def test_list_dir(self) -> None:+ """Non-recursive list returns immediate child base names."""+ base = f"{SANDBOX_WORKDIR}/listing"+ await self.backend.write_file(f"{base}/a.txt", b"x")+ await self.backend.write_file(f"{base}/b.txt", b"x")+ entries = await self.backend.list_dir(base)+ self.assertEqual(sorted(entries), ["a.txt", "b.txt"])++ async def test_list_dir_recursive(self) -> None:+ """Recursive list returns file paths under the root."""+ base = f"{SANDBOX_WORKDIR}/rec"+ await self.backend.write_file(f"{base}/top.txt", b"x")+ await self.backend.write_file(f"{base}/sub/nested.txt", b"x")+ entries = await self.backend.list_dir(base, recursive=True)+ basenames = sorted(e.rsplit("/", 1)[-1] for e in entries)+ self.assertEqual(basenames, ["nested.txt", "top.txt"])++ async def test_stat_mtime(self) -> None:+ """``stat_mtime`` returns a float for existing files."""+ path = f"{SANDBOX_WORKDIR}/stat.txt"+ await self.backend.write_file(path, b"x")+ self.assertIsInstance(await self.backend.stat_mtime(path), float)+ self.assertIsNone(+ await self.backend.stat_mtime(f"{SANDBOX_WORKDIR}/missing"),+ )++ async def test_delete_path(self) -> None:+ """``delete_path`` removes files and trees."""+ path = f"{SANDBOX_WORKDIR}/to_delete.txt"+ await self.backend.write_file(path, b"x")+ await self.backend.delete_path(path)+ self.assertFalse(await self.backend.file_exists(path))++ tree = f"{SANDBOX_WORKDIR}/tree"+ await self.backend.write_file(f"{tree}/deep/f.txt", b"x")+ await self.backend.delete_path(tree)+ self.assertFalse(await self.backend.file_exists(tree))++ await self.backend.delete_path(f"{SANDBOX_WORKDIR}/missing")++ async def test_cannot_read_unmounted_host_file(self) -> None:+ """Absolute host paths outside mounts are not visible in sandbox."""+ outside = tempfile.TemporaryDirectory()+ self.addCleanup(outside.cleanup)+ secret = os.path.join(outside.name, "secret.txt")+ with open(secret, "wb") as f:+ f.write(b"secret")++ result = await self.backend.exec_shell(["cat", secret])+ self.assertFalse(result.ok())++ async def test_system_directory_is_read_only(self) -> None:+ """The /usr mount is explicitly read-only."""+ result = await self.backend.exec_shell(+ [+ "sh",+ "-c",+ (+ "while IFS= read -r line; do "+ "set -- $line; "+ 'if [ "$5" = "/usr" ]; then '+ 'case ",$6," in '+ "*,ro,*) exit 0 ;; "+ "*) exit 1 ;; "+ "esac; "+ "fi; "+ "done < /proc/self/mountinfo; "+ "exit 1"+ ),+ ],+ )+ self.assertTrue(+ result.ok(),+ result.stderr.decode(errors="replace"),+ )diff --git a/tests/workspace_bubblewrap_test.py b/tests/workspace_bubblewrap_test.pynew file mode 100644index 000000000..a7e27b30b--- /dev/null+++ b/tests/workspace_bubblewrap_test.py@@ -0,0 +1,1270 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access,consider-using-with+"""Tests for Bubblewrap workspace and manager."""++from __future__ import annotations++import base64+import asyncio+import json+import os+import shutil+import stat+import subprocess+import sys+import tempfile+import time+import unittest+import uuid+from typing import Any+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch++import aiofiles+from fastapi.testclient import TestClient++from agentscope.app.workspace_manager import BubblewrapWorkspaceManager+from agentscope.mcp import MCPClient, StdioMCPConfig+from agentscope.message import Base64Source, DataBlock, UserMsg+from agentscope.tool import ExecResult+from agentscope.workspace import BubblewrapBackend, BubblewrapWorkspace+from agentscope.workspace._bubblewrap._constants import (+ BWRAP_SMOKE_PROBE_ARGV,+ SANDBOX_WORKDIR,+)+from agentscope.workspace._gateway_client import GatewayClient+from agentscope.workspace._mcp_gateway._mcp_gateway_app import (+ _State,+ _build_app,+)+++def _bubblewrap_available() -> bool:+ """Return ``True`` iff ``bwrap`` can run a trivial command."""+ if not sys.platform.startswith("linux"):+ return False+ if shutil.which("bwrap") is None:+ return False+ try:+ result = subprocess.run(+ BWRAP_SMOKE_PROBE_ARGV,+ capture_output=True,+ timeout=5,+ check=False,+ )+ return result.returncode == 0+ except (subprocess.TimeoutExpired, FileNotFoundError, OSError):+ return False+++_BWRAP_OK = _bubblewrap_available()+_SKIP_REASON = "Bubblewrap workspace requires Linux with a working bwrap"+_BWRAP_INTEGRATION_ENABLED = (+ os.getenv("AGENTSCOPE_BWRAP_INTEGRATION_TEST") == "1"+)+_INTEGRATION_SKIP_REASON = (+ _SKIP_REASON+ if _BWRAP_INTEGRATION_ENABLED+ else (+ "set AGENTSCOPE_BWRAP_INTEGRATION_TEST=1 to run Bubblewrap "+ "workspace integration tests"+ )+)+++def _write_skill_dir(root: str, name: str, description: str) -> str:+ """Create a minimal 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+++class TestBubblewrapWorkspaceInstructions(IsolatedAsyncioTestCase):+ """Pure local instruction rendering tests."""++ async def test_get_instructions_custom_template(self) -> None:+ """Custom instruction template gets the sandbox workdir."""+ ws = BubblewrapWorkspace(+ workspace_id="prompt-only",+ instructions="Workdir: {workdir}",+ )+ try:+ self.assertEqual(+ await ws.get_instructions(),+ f"Workdir: {SANDBOX_WORKDIR}",+ )+ finally:+ await ws.close()++ async def test_get_instructions_default_mentions_workdir(self) -> None:+ """Default template renders useful workspace details."""+ ws = BubblewrapWorkspace(workspace_id="prompt-default")+ try:+ text = await ws.get_instructions()+ self.assertIn("Bubblewrap-based Linux workspace", text)+ self.assertIn(SANDBOX_WORKDIR, text)+ self.assertIn("data/", text)+ self.assertIn("skills/", text)+ self.assertIn("sessions/", text)+ finally:+ await ws.close()++ async def test_gateway_port_defaults_to_dynamic(self) -> None:+ """No explicit gateway port is assigned until initialization."""+ ws1 = BubblewrapWorkspace(workspace_id="p1")+ ws2 = BubblewrapWorkspace(workspace_id="p2")+ try:+ self.assertIsNone(ws1.gateway_port)+ self.assertIsNone(ws2.gateway_port)+ port1 = ws1._allocate_gateway_port()+ port2 = ws2._allocate_gateway_port()+ self.assertIsInstance(port1, int)+ self.assertIsInstance(port2, int)+ finally:+ await ws1.close()+ await ws2.close()++ async def test_workspace_rejects_share_net_false(self) -> None:+ """Workspace-level TCP gateway currently requires shared network."""+ with self.assertRaises(ValueError):+ BubblewrapWorkspace(workspace_id="no-net", share_net=False)++ async def test_workspace_rejects_invalid_gateway_ports(self) -> None:+ """Fixed gateway ports must be valid TCP ports, not port zero."""+ for port in (0, -1, 65536, True):+ with self.assertRaises(ValueError):+ BubblewrapWorkspace(+ workspace_id="invalid-port",+ gateway_port=port, # type: ignore[arg-type]+ )++ async def test_workspace_rejects_empty_workdir(self) -> None:+ """Explicit host workdir must not collapse to cwd."""+ with self.assertRaises(ValueError):+ BubblewrapWorkspace(workspace_id="empty", host_workdir="")++ async def test_ephemeral_workspace_is_never_persistent(self) -> None:+ """Ephemeral persistence is determined by constructor config."""+ ws = BubblewrapWorkspace(workspace_id="ephemeral")+ try:+ self.assertFalse(ws.is_persistent)+ finally:+ await ws.close()++ async def test_explicit_workdir_is_persistent(self) -> None:+ """Explicit host workdirs survive workspace close."""+ with tempfile.TemporaryDirectory() as workdir:+ ws = BubblewrapWorkspace(+ workspace_id="persistent",+ host_workdir=workdir,+ )+ try:+ self.assertTrue(ws.is_persistent)+ finally:+ await ws.close()++ async def test_initialize_failure_cleans_ephemeral_dirs(self) -> None:+ """Partial initialization failures clean owned host resources."""+ paths: dict[str, str] = {}++ class _FailingWorkspace(BubblewrapWorkspace):+ async def _provision_backend(self) -> None:+ """Create owned resources, then fail provisioning."""+ # pylint: disable=attribute-defined-outside-init+ self._owned_workdir = tempfile.TemporaryDirectory()+ self.host_workdir = self._owned_workdir.name+ self._tmpdir = tempfile.TemporaryDirectory()+ paths["workdir"] = self.host_workdir+ paths["tmpdir"] = self._tmpdir.name+ self._backend = BubblewrapBackend(+ host_workdir=self.host_workdir,+ host_tmpdir=self._tmpdir.name,+ )+ raise RuntimeError("boom")++ ws = _FailingWorkspace(workspace_id="fail-cleanup")++ with self.assertRaises(RuntimeError):+ await ws.initialize()++ self.assertFalse(os.path.exists(paths["workdir"]))+ self.assertFalse(os.path.exists(paths["tmpdir"]))++ async def test_probe_timeout_terminates_process_tree(self) -> None:+ """A timed-out smoke probe terminates the spawned bwrap process."""++ class _TimeoutProcess:+ returncode = None++ async def communicate(self) -> tuple[bytes, bytes]:+ """Pretend the subprocess communicate call timed out."""+ raise asyncio.TimeoutError()++ fake_process = _TimeoutProcess()++ with (+ patch(+ "asyncio.create_subprocess_exec",+ new=AsyncMock(return_value=fake_process),+ ) as create_process,+ patch.object(+ BubblewrapBackend,+ "_terminate_process_tree",+ new=AsyncMock(),+ ) as terminate,+ ):+ with self.assertRaises(RuntimeError):+ await BubblewrapWorkspace._probe_bubblewrap()++ terminate.assert_awaited_once_with(fake_process, grace=1.0)+ kwargs = create_process.call_args.kwargs+ if os.name == "nt":+ self.assertNotIn("start_new_session", kwargs)+ else:+ self.assertTrue(kwargs["start_new_session"])++ async def test_stop_gateway_process_terminates_tracked_process(+ self,+ ) -> None:+ """Gateway teardown terminates the tracked subprocess."""+ ws = BubblewrapWorkspace(workspace_id="stop-gateway")+ fake_process = AsyncMock()+ fake_process.returncode = None+ ws._gateway_process = fake_process++ async def _mark_terminated(+ process: Any,+ *,+ grace: float,+ ) -> None:+ """Simulate the process returncode being set after termination."""+ del grace+ process.returncode = -15++ with patch.object(+ BubblewrapBackend,+ "_terminate_process_tree",+ new=AsyncMock(side_effect=_mark_terminated),+ ) as terminate:+ await ws._stop_gateway_process()++ self.assertIsNone(ws._gateway_process)+ terminate.assert_awaited_once_with(fake_process, grace=5.0)++ async def test_stop_gateway_keeps_handle_when_termination_fails(+ self,+ ) -> None:+ """A failed termination keeps the process handle for retry."""+ ws = BubblewrapWorkspace(workspace_id="stop-failure")+ fake_process = AsyncMock()+ fake_process.returncode = None+ ws._gateway_process = fake_process++ with patch.object(+ BubblewrapBackend,+ "_terminate_process_tree",+ new=AsyncMock(side_effect=OSError("cannot terminate")),+ ):+ with self.assertRaises(OSError):+ await ws._stop_gateway_process()++ self.assertIs(ws._gateway_process, fake_process)++ async def test_bootstrap_uses_official_ripgrep_release(self) -> None:+ """Bootstrap installs rg from the official release asset."""+ ws = BubblewrapWorkspace(workspace_id="bootstrap")+ workdir = tempfile.TemporaryDirectory()+ tmpdir = tempfile.TemporaryDirectory()+ try:+ ws._backend = BubblewrapBackend(+ host_workdir=workdir.name,+ host_tmpdir=tmpdir.name,+ )+ commands = ws._bootstrap_commands()+ joined = "\n".join(commands)+ pip_commands = [cmd for cmd in commands if "uv pip install" in cmd]+ self.assertNotIn("ripgrep", "\n".join(pip_commands))+ self.assertIn("github.com/BurntSushi/ripgrep", joined)+ self.assertIn("sha256sum -c", joined)+ self.assertIn("sha256=f84757b0", joined)+ self.assertIn("sha256sum -c -", joined)+ self.assertIn('mktemp "${asset}.tmp.XXXXXX"', joined)+ self.assertIn('mv -f "$tmp_asset" "$asset"', joined)+ self.assertNotIn('"$asset.sha256"', joined)+ self.assertIn("tmp_installer=$(mktemp)", joined)+ self.assertIn('sh "$tmp_installer"', joined)+ self.assertNotIn("| env UV_INSTALL_DIR", joined)+ finally:+ workdir.cleanup()+ tmpdir.cleanup()+ await ws.close()++ async def test_gateway_credentials_rotate_per_launch(self) -> None:+ """Gateway credentials can be rotated for every launch attempt."""+ ws = BubblewrapWorkspace(workspace_id="rotate")+ try:+ first_token = ws._gateway_token+ first_nonce = ws._gateway_nonce++ ws._rotate_gateway_credentials()++ self.assertNotEqual(first_token, ws._gateway_token)+ self.assertNotEqual(first_nonce, ws._gateway_nonce)+ finally:+ await ws.close()++ async def test_gateway_client_passes_auth_token_to_shim(self) -> None:+ """Gateway requests include the optional auth token."""++ class _FakeGatewayBackend:+ command: list[str] | None = None++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Capture the shim command and return a tiny response."""+ del cwd, timeout+ self.command = command+ body = base64.b64encode(b"ok").decode("ascii")+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ backend = _FakeGatewayBackend()+ client = GatewayClient(+ backend=backend, # type: ignore[arg-type]+ gateway_port=5600,+ auth_token="secret-token",+ )+ self.assertEqual(+ await client.exec_request("GET", "/health"),+ (200, b"ok"),+ )+ self.assertIsNotNone(backend.command)+ command = backend.command+ assert command is not None+ self.assertEqual(command[-1], "secret-token")++ async def test_gateway_client_without_auth_token_passes_empty_arg(+ self,+ ) -> None:+ """Gateway requests without auth use an empty shim token arg."""++ class _FakeGatewayBackend:+ command: list[str] | None = None++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Capture the shim command and return a tiny response."""+ del cwd, timeout+ self.command = command+ body = base64.b64encode(b"ok").decode("ascii")+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ backend = _FakeGatewayBackend()+ client = GatewayClient(+ backend=backend, # type: ignore[arg-type]+ gateway_port=5600,+ )+ await client.exec_request("GET", "/health")++ command = backend.command+ assert command is not None+ self.assertEqual(command[-1], "")++ async def test_gateway_health_omits_auth_token(self) -> None:+ """Health probes do not send the bearer token."""++ class _FakeGatewayBackend:+ command: list[str] | None = None++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Capture the health command and return plain ok."""+ del cwd, timeout+ self.command = command+ body = base64.b64encode(b"ok").decode("ascii")+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ backend = _FakeGatewayBackend()+ client = GatewayClient(+ backend=backend, # type: ignore[arg-type]+ gateway_port=5600,+ auth_token="secret-token",+ )++ self.assertTrue(await client.health())+ command = backend.command+ assert command is not None+ self.assertEqual(command[-1], "")++ async def test_gateway_health_requires_expected_nonce(self) -> None:+ """Health succeeds only when the gateway nonce matches."""++ class _FakeGatewayBackend:+ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Return a health body with a different nonce."""+ del command, cwd, timeout+ payload = {"status": "ok", "instance_nonce": "actual"}+ body = base64.b64encode(json.dumps(payload).encode()).decode()+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ backend = _FakeGatewayBackend()+ mismatch = GatewayClient(+ backend=backend, # type: ignore[arg-type]+ gateway_port=5600,+ instance_nonce="expected",+ )+ match = GatewayClient(+ backend=backend, # type: ignore[arg-type]+ gateway_port=5600,+ instance_nonce="actual",+ )++ self.assertFalse(await mismatch.health())+ self.assertTrue(await match.health())++ async def test_gateway_health_rejects_non_object_json(self) -> None:+ """Nonce health checks reject valid JSON that is not an object."""++ class _FakeGatewayBackend:+ def __init__(self, body: bytes) -> None:+ self.body = body++ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Return a health body controlled by the test."""+ del command, cwd, timeout+ body = base64.b64encode(self.body).decode()+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ for body in (b"[]", b'"ok"', b"123", b"null"):+ client = GatewayClient(+ backend=_FakeGatewayBackend(body), # type: ignore[arg-type]+ gateway_port=5600,+ instance_nonce="expected",+ )+ self.assertFalse(await client.health())++ async def test_gateway_health_rejects_non_ascii_nonce(self) -> None:+ """Nonce health checks reject non-ASCII response data safely."""++ class _FakeGatewayBackend:+ async def exec_shell(+ self,+ command: list[str],+ *,+ cwd: str | None = None,+ timeout: float | None = None,+ ) -> ExecResult:+ """Return a health body with a non-ASCII nonce."""+ del command, cwd, timeout+ payload = {"status": "ok", "instance_nonce": "\u00e9"}+ body = base64.b64encode(json.dumps(payload).encode()).decode()+ return ExecResult(+ 0,+ json.dumps({"status": 200, "body": body}).encode(),+ b"",+ )++ client = GatewayClient(+ backend=_FakeGatewayBackend(), # type: ignore[arg-type]+ gateway_port=5600,+ instance_nonce="expected",+ )++ self.assertFalse(await client.health())+++class TestBubblewrapWorkspaceCache(IsolatedAsyncioTestCase):+ """Pure local cache path tests."""++ async def test_workspace_rejects_empty_cache_dir(self) -> None:+ """Explicit cache dirs must not collapse to cwd."""+ with self.assertRaises(ValueError):+ BubblewrapWorkspace(workspace_id="empty-cache", host_cache_dir="")++ async def test_default_cache_dir_is_workspace_private(self) -> None:+ """Default caches are distinct and outside each workspace."""+ with tempfile.TemporaryDirectory() as parent:+ workdir1 = os.path.join(parent, "workspace-one")+ workdir2 = os.path.join(parent, "workspace-two")+ os.makedirs(workdir1)+ os.makedirs(workdir2)+ ws1 = BubblewrapWorkspace(+ workspace_id="cache-one",+ host_workdir=workdir1,+ )+ ws2 = BubblewrapWorkspace(+ workspace_id="cache-two",+ host_workdir=workdir2,+ )+ try:+ cache1 = ws1._resolve_host_cache_dir()+ cache2 = ws2._resolve_host_cache_dir()+ finally:+ await ws1.close()+ await ws2.close()++ self.assertNotEqual(cache1, cache2)+ self.assertNotEqual(+ os.path.commonpath([os.path.realpath(workdir1), cache1]),+ os.path.realpath(workdir1),+ )+ self.assertNotEqual(+ os.path.commonpath([os.path.realpath(workdir2), cache2]),+ os.path.realpath(workdir2),+ )+ self.assertEqual(+ os.path.basename(os.path.dirname(cache1)),+ ".agentscope-bwrap-cache",+ )++ async def test_explicit_cache_dir_is_opt_in_shared(self) -> None:+ """Shared writable caches only happen when requested explicitly."""+ with (+ tempfile.TemporaryDirectory() as workdir1,+ tempfile.TemporaryDirectory() as workdir2,+ tempfile.TemporaryDirectory() as cache_dir,+ ):+ ws1 = BubblewrapWorkspace(+ workspace_id="shared-cache-one",+ host_workdir=workdir1,+ host_cache_dir=cache_dir,+ )+ ws2 = BubblewrapWorkspace(+ workspace_id="shared-cache-two",+ host_workdir=workdir2,+ host_cache_dir=cache_dir,+ )+ try:+ expected_cache_dir = os.path.realpath(cache_dir)+ self.assertEqual(+ ws1._resolve_host_cache_dir(),+ expected_cache_dir,+ )+ self.assertEqual(+ ws2._resolve_host_cache_dir(),+ expected_cache_dir,+ )+ finally:+ await ws1.close()+ await ws2.close()++ async def test_cache_bind_source_cannot_overlap_workspace(self) -> None:+ """Cache bind sources cannot expose workspace paths or parents."""+ with tempfile.TemporaryDirectory() as parent:+ workdir = os.path.join(parent, "workspace")+ os.makedirs(workdir)+ for cache_dir in (+ os.path.join(workdir, "cache"),+ parent,+ ):+ ws = BubblewrapWorkspace(+ workspace_id="unsafe-cache",+ host_workdir=workdir,+ host_cache_dir=cache_dir,+ )+ try:+ with self.assertRaisesRegex(+ ValueError,+ "must not overlap",+ ):+ ws._resolve_host_cache_dir()+ finally:+ await ws.close()++ async def test_cache_bind_source_cannot_be_symlink(self) -> None:+ """Cache bind source roots must be real directories."""+ with (+ tempfile.TemporaryDirectory() as parent,+ tempfile.TemporaryDirectory() as outside,+ ):+ workdir = os.path.join(parent, "workspace")+ os.makedirs(workdir)+ cache_dir = os.path.join(parent, "cache-link")+ try:+ os.symlink(outside, cache_dir)+ except (OSError, NotImplementedError) as exc:+ self.skipTest(f"symlink unavailable: {exc}")+ ws = BubblewrapWorkspace(+ workspace_id="symlink-cache",+ host_workdir=workdir,+ host_cache_dir=cache_dir,+ )+ try:+ with self.assertRaisesRegex(ValueError, "symbolic link"):+ ws._resolve_host_cache_dir()+ finally:+ await ws.close()++ @unittest.skipUnless(+ sys.platform.startswith("linux"),+ "POSIX mode test requires Linux",+ )+ async def test_new_explicit_workdir_uses_private_permissions(self) -> None:+ """A newly created explicit workdir uses mode 0700."""+ with tempfile.TemporaryDirectory() as parent:+ workdir = os.path.join(parent, "workspace")+ ws = BubblewrapWorkspace(+ workspace_id="private-workdir",+ host_workdir=workdir,+ )+ with (+ patch.object(+ BubblewrapWorkspace,+ "_probe_bubblewrap",+ new=AsyncMock(),+ ),+ patch.object(shutil, "which", return_value="/usr/bin/bwrap"),+ ):+ await ws._provision_backend()+ try:+ mode = stat.S_IMODE(os.stat(workdir).st_mode)+ self.assertEqual(mode, 0o700)+ finally:+ await ws._teardown_backend()++ @unittest.skipUnless(+ sys.platform.startswith("linux"),+ "Ephemeral provisioning requires Linux",+ )+ async def test_ephemeral_private_cache_is_cleaned_on_close(self) -> None:+ """An owned external cache is removed with an ephemeral workspace."""+ ws = BubblewrapWorkspace(workspace_id="ephemeral-cache")+ with (+ patch.object(+ BubblewrapWorkspace,+ "_probe_bubblewrap",+ new=AsyncMock(),+ ),+ patch.object(shutil, "which", return_value="/usr/bin/bwrap"),+ ):+ await ws._provision_backend()+ cache_dir = ws._host_cache_dir+ workdir = ws.host_workdir+ self.assertTrue(os.path.isdir(cache_dir))+ self.assertNotEqual(+ os.path.commonpath([cache_dir, workdir]),+ workdir,+ )++ await ws._teardown_backend()++ self.assertFalse(os.path.exists(cache_dir))+ self.assertFalse(os.path.exists(workdir))+++class TestGatewayAuth(unittest.TestCase):+ """Pure FastAPI tests for optional gateway authentication."""++ def test_gateway_rejects_missing_token(self) -> None:+ """A protected gateway rejects missing auth."""+ client = TestClient(_build_app(_State(), auth_token="secret"))++ response = client.get("/mcps")++ self.assertEqual(response.status_code, 401)++ def test_gateway_rejects_wrong_token(self) -> None:+ """A protected gateway rejects incorrect auth."""+ client = TestClient(_build_app(_State(), auth_token="secret"))++ response = client.get(+ "/mcps",+ headers={"Authorization": "Bearer wrong"},+ )++ self.assertEqual(response.status_code, 401)++ def test_gateway_rejects_non_ascii_token(self) -> None:+ """Malformed non-ASCII auth headers return 401, not 500."""+ client = TestClient(_build_app(_State(), auth_token="secret"))++ response = client.get(+ "/mcps",+ headers=[+ (b"authorization", b"Bearer \xff"),+ ],+ )++ self.assertEqual(response.status_code, 401)++ def test_gateway_accepts_valid_token(self) -> None:+ """A protected gateway accepts the configured token."""+ client = TestClient(_build_app(_State(), auth_token="secret"))++ response = client.get(+ "/mcps",+ headers={"Authorization": "Bearer secret"},+ )++ self.assertEqual(response.status_code, 200)++ def test_gateway_auth_is_optional(self) -> None:+ """Unprotected gateway preserves existing backend behavior."""+ client = TestClient(_build_app(_State(), auth_token=None))++ response = client.get("/mcps")++ self.assertEqual(response.status_code, 200)++ def test_gateway_health_returns_nonce_without_auth(self) -> None:+ """Health exposes a nonce without requiring bearer auth."""+ client = TestClient(+ _build_app(+ _State(),+ auth_token="secret",+ instance_nonce="nonce",+ ),+ )++ response = client.get("/health")++ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.json()["instance_nonce"], "nonce")+++ _BWRAP_OK and _BWRAP_INTEGRATION_ENABLED,+ _INTEGRATION_SKIP_REASON,+)+class TestBubblewrapWorkspace(IsolatedAsyncioTestCase):+ """Integration tests against live Bubblewrap."""++ _shared_workdir: tempfile.TemporaryDirectory[str]+ _shared_cache: tempfile.TemporaryDirectory[str]++ @classmethod+ def setUpClass(cls) -> None:+ """Create one persistent workdir so bootstrap is paid once."""+ super().setUpClass()+ cls._shared_workdir = tempfile.TemporaryDirectory()+ cls._shared_cache = tempfile.TemporaryDirectory()++ @classmethod+ def tearDownClass(cls) -> None:+ """Drop the shared persistent workdir."""+ cls._shared_cache.cleanup()+ cls._shared_workdir.cleanup()+ super().tearDownClass()++ async def asyncSetUp(self) -> None:+ """Create mounted dirs and a workspace."""+ # pylint: disable=consider-using-with+ self.skills_src = tempfile.TemporaryDirectory()+ self.workspace = BubblewrapWorkspace(+ workspace_id=f"test-{uuid.uuid4().hex[:8]}",+ host_workdir=self._shared_workdir.name,+ host_cache_dir=self._shared_cache.name,+ )+ await self.workspace.initialize()+ await self.workspace.reset()++ async def asyncTearDown(self) -> None:+ """Close workspace and drop scratch dirs."""+ try:+ if self.workspace.is_alive:+ await self.workspace.reset()+ await self.workspace.close()+ finally:+ self._clear_shared_state()+ self.skills_src.cleanup()++ def _clear_shared_state(self) -> None:+ """Remove user state while preserving the bootstrapped gateway."""+ for name in ("data", "sessions", "skills", ".mcp"):+ path = os.path.join(self._shared_workdir.name, name)+ if os.path.isdir(path):+ shutil.rmtree(path)+ elif os.path.exists(path):+ os.remove(path)++ async def test_initialize_gateway_and_tools(self) -> None:+ """Initialization starts gateway and returns builtins."""+ self.assertTrue(self.workspace.is_alive)+ self.assertListEqual(await self.workspace.list_mcps(), [])+ tools = await self.workspace.list_tools()+ self.assertSetEqual(+ {tool.name for tool in tools},+ {"Bash", "Edit", "Glob", "Grep", "Read", "Write"},+ )+ for tool in tools:+ self.assertIsInstance(tool._backend, BubblewrapBackend)++ async def test_persistent_workspace_repairs_partial_bootstrap(+ self,+ ) -> None:+ """A damaged persisted venv is repaired on the next initialization."""+ workdir = tempfile.TemporaryDirectory()+ cache_dir = tempfile.TemporaryDirectory()+ first = BubblewrapWorkspace(+ workspace_id=f"repair-first-{uuid.uuid4().hex[:8]}",+ host_workdir=workdir.name,+ host_cache_dir=cache_dir.name,+ )+ second: BubblewrapWorkspace | None = None+ try:+ await first.initialize()+ await first.close()++ python_path = os.path.join(+ workdir.name,+ ".agentscope",+ ".venv",+ "bin",+ "python",+ )+ os.remove(python_path)++ second = BubblewrapWorkspace(+ workspace_id=f"repair-second-{uuid.uuid4().hex[:8]}",+ host_workdir=workdir.name,+ host_cache_dir=cache_dir.name,+ )+ await second.initialize()+ self.assertTrue(second.is_alive)+ result = await second.get_backend().exec_shell(+ ["python", "--version"],+ )+ self.assertTrue(result.ok(), result.stderr.decode())+ finally:+ if second is not None:+ await second.close()+ await first.close()+ cache_dir.cleanup()+ workdir.cleanup()++ async def test_bootstrap_tools_available(self) -> None:+ """User-space bootstrap exposes uv and rg in PATH."""+ uv = await self.workspace.get_backend().exec_shell(["uv", "--version"])+ rg = await self.workspace.get_backend().exec_shell(["rg", "--version"])+ self.assertTrue(uv.ok(), uv.stderr.decode(errors="replace"))+ self.assertTrue(rg.ok(), rg.stderr.decode(errors="replace"))++ async def test_offload_context_and_datablock(self) -> None:+ """Offload writes session JSONL and decoded data."""+ b64_data = base64.b64encode(b"hello-data").decode()+ msg = UserMsg(+ name="user",+ content=[+ DataBlock(+ source=Base64Source(+ data=b64_data,+ media_type="text/plain",+ ),+ name="note.txt",+ ),+ ],+ )+ path = await self.workspace.offload_context("s1", [msg])+ self.assertEqual(path, f"{SANDBOX_WORKDIR}/sessions/s1/context.jsonl")++ host_path = os.path.join(+ self._shared_workdir.name,+ "sessions",+ "s1",+ "context.jsonl",+ )+ async with aiofiles.open(host_path, "r") as f:+ content = await f.read()+ self.assertIn("file:///workspace/data/", content)+ self.assertTrue(+ os.path.isdir(os.path.join(self._shared_workdir.name, "data")),+ )++ async def test_skills_crud(self) -> None:+ """Skill add/list/remove works through the backend."""+ skill_path = _write_skill_dir(+ self.skills_src.name,+ "greeter",+ "Says hi.",+ )+ self.assertListEqual(await self.workspace.list_skills(), [])+ await self.workspace.add_skill(skill_path)+ skills = await self.workspace.list_skills()+ self.assertEqual(len(skills), 1)+ self.assertEqual(skills[0].name, "greeter")+ self.assertEqual(skills[0].dir, f"{SANDBOX_WORKDIR}/skills/greeter")++ await self.workspace.remove_skill("greeter")+ self.assertListEqual(await self.workspace.list_skills(), [])++ async def test_reset_clears_state_but_keeps_gateway(self) -> None:+ """Reset clears user state while keeping the gateway usable."""+ await self.workspace.offload_context(+ "reset",+ [UserMsg(name="user", content="hi")],+ )+ self.assertTrue(+ os.path.exists(+ os.path.join(self._shared_workdir.name, "sessions"),+ ),+ )++ await self.workspace.reset()+ self.assertFalse(+ os.path.exists(+ os.path.join(self._shared_workdir.name, "sessions"),+ ),+ )+ self.assertListEqual(await self.workspace.list_mcps(), [])++ async def test_close_is_idempotent(self) -> None:+ """Closing twice does not raise."""+ await self.workspace.close()+ await self.workspace.close()++ async def test_close_terminates_gateway_process(self) -> None:+ """Closing a live workspace terminates its gateway process."""+ process = self.workspace._gateway_process+ self.assertIsNotNone(process)++ await self.workspace.close()++ await asyncio.wait_for(process.wait(), timeout=5.0)+ self.assertIsNotNone(process.returncode)++ async def test_workdir_persistence_across_restart(self) -> None:+ """Same host workdir preserves state across workspace instances."""+ msg = UserMsg(name="user", content="durable")+ await self.workspace.offload_context("persist", [msg])+ await self.workspace.close()++ ws2 = BubblewrapWorkspace(+ workspace_id=f"test-{uuid.uuid4().hex[:8]}",+ host_workdir=self._shared_workdir.name,+ host_cache_dir=self._shared_cache.name,+ )+ try:+ await ws2.initialize()+ host_path = os.path.join(+ self._shared_workdir.name,+ "sessions",+ "persist",+ "context.jsonl",+ )+ async with aiofiles.open(host_path, "r") as f:+ self.assertEqual(+ (await f.read()).strip(),+ msg.model_dump_json(),+ )+ finally:+ await ws2.close()++ @unittest.skipUnless(+ os.getenv("AGENTSCOPE_BWRAP_NETWORK_TEST") == "1",+ "set AGENTSCOPE_BWRAP_NETWORK_TEST=1 to run network MCP test",+ )+ async def test_optional_network_mcp(self) -> None:+ """Register and query a pure-Python MCP via uvx."""+ mcp_client = MCPClient(+ name="time",+ is_stateful=True,+ mcp_config=StdioMCPConfig(+ command="uvx",+ args=["mcp-server-time"],+ ),+ )+ await self.workspace.add_mcp(mcp_client)+ mcps = await self.workspace.list_mcps()+ self.assertEqual(len(mcps), 1)+ tools = await mcps[0].list_raw_tools()+ self.assertGreater(len(tools), 0)+ tool = await mcps[0].get_tool("get_current_time")+ result = await tool(timezone="Asia/Tokyo")+ self.assertIsNotNone(result)+++ _BWRAP_OK and _BWRAP_INTEGRATION_ENABLED,+ _INTEGRATION_SKIP_REASON,+)+class TestBubblewrapWorkspaceConcurrency(IsolatedAsyncioTestCase):+ """Concurrency scenarios that need multiple live workspaces."""++ async def asyncSetUp(self) -> None:+ """Create a shared bootstrap cache for live concurrency tests."""+ # pylint: disable=consider-using-with+ self.cache_dir = tempfile.TemporaryDirectory()++ async def asyncTearDown(self) -> None:+ """Drop the shared bootstrap cache."""+ self.cache_dir.cleanup()++ async def test_two_workspaces_can_start_concurrently(self) -> None:+ """Dynamic gateway ports avoid shared-loopback collisions."""+ # pylint: disable=consider-using-with+ workdir1 = tempfile.TemporaryDirectory()+ workdir2 = tempfile.TemporaryDirectory()+ ws1 = BubblewrapWorkspace(+ workspace_id=f"test-{uuid.uuid4().hex[:8]}",+ host_workdir=workdir1.name,+ host_cache_dir=self.cache_dir.name,+ )+ ws2 = BubblewrapWorkspace(+ workspace_id=f"test-{uuid.uuid4().hex[:8]}",+ host_workdir=workdir2.name,+ host_cache_dir=self.cache_dir.name,+ )+ try:+ await asyncio.gather(ws1.initialize(), ws2.initialize())+ self.assertIsInstance(ws1.gateway_port, int)+ self.assertIsInstance(ws2.gateway_port, int)+ self.assertNotEqual(ws1.gateway_port, ws2.gateway_port)++ rogue = GatewayClient(+ backend=ws1.get_backend(),+ gateway_port=ws2.gateway_port,+ timeout=5.0,+ instance_nonce=ws1._gateway_nonce,+ )+ self.assertFalse(await rogue.health())+ self.assertTrue(await ws2._gateway.health())+ finally:+ await asyncio.gather(+ ws1.close(),+ ws2.close(),+ return_exceptions=True,+ )+ workdir1.cleanup()+ workdir2.cleanup()++ async def test_ephemeral_workspace_reinitialize_cleans_new_dirs(+ self,+ ) -> None:+ """An ephemeral workspace can close and initialize again cleanly."""+ ws = BubblewrapWorkspace(+ workspace_id=f"test-{uuid.uuid4().hex[:8]}",+ host_cache_dir=self.cache_dir.name,+ )+ try:+ await ws.initialize()+ first = ws.host_workdir+ await ws.close()+ self.assertFalse(os.path.exists(first))++ await ws.initialize()+ second = ws.host_workdir+ self.assertNotEqual(first, second)+ await ws.close()+ self.assertFalse(os.path.exists(second))+ finally:+ await ws.close()+++class _FakeWorkspace:+ """Tiny workspace double for manager cache tests."""++ def __init__(self, workspace_id: str) -> None:+ self.workspace_id = workspace_id+ self.closed = False++ async def close(self) -> None:+ """Mark closed."""+ self.closed = True+++class _FakeBubblewrapWorkspaceManager(BubblewrapWorkspaceManager):+ """Manager that avoids starting real Bubblewrap workspaces."""++ async def _build_and_start(+ self,+ *,+ workspace_id: str,+ user_id: str,+ agent_id: str,+ ) -> Any:+ del user_id, agent_id+ return _FakeWorkspace(workspace_id)+++class TestBubblewrapWorkspaceManager(IsolatedAsyncioTestCase):+ """Manager cache behavior tests that do not require bwrap."""++ async def asyncSetUp(self) -> None:+ """Create a manager rooted at a temp dir."""+ # pylint: disable=consider-using-with+ self.basedir = tempfile.TemporaryDirectory()+ self.manager = _FakeBubblewrapWorkspaceManager(+ self.basedir.name,+ ttl=0.01,+ sweep_interval=60.0,+ )++ async def asyncTearDown(self) -> None:+ """Close manager and scratch dir."""+ await self.manager.close_all()+ self.basedir.cleanup()++ async def test_get_workspace_reuses_explicit_id(self) -> None:+ """Same explicit workspace id returns cached object."""+ ws1 = await self.manager.get_workspace("u", "a", "s", "wid")+ ws2 = await self.manager.get_workspace("u", "a", "s", "wid")+ self.assertIs(ws1, ws2)++ async def test_close_evicts_workspace(self) -> None:+ """Closing one id evicts and closes it."""+ ws = await self.manager.get_workspace("u", "a", "s", "wid")+ await self.manager.close("wid")+ self.assertTrue(ws.closed)+ self.assertNotIn("wid", self.manager._cache)++ async def test_close_all_closes_cached_workspaces(self) -> None:+ """``close_all`` closes every cached workspace."""+ ws1 = await self.manager.get_workspace("u", "a", "s", "one")+ ws2 = await self.manager.get_workspace("u", "a", "s", "two")+ await self.manager.close_all()+ self.assertTrue(ws1.closed)+ self.assertTrue(ws2.closed)+ self.assertDictEqual(self.manager._cache, {})++ async def test_create_workspace_always_creates_new_workspace(self) -> None:+ """Deprecated create still creates a fresh workspace each call."""+ ws1 = await self.manager.create_workspace("u", "a", "s1")+ ws2 = await self.manager.create_workspace("u", "a", "s2")++ self.assertNotEqual(ws1.workspace_id, ws2.workspace_id)+ self.assertFalse(ws1.closed)+ self.assertFalse(ws2.closed)+ self.assertIn(ws1.workspace_id, self.manager._cache)+ self.assertIn(ws2.workspace_id, self.manager._cache)++ async def test_sweep_once_evicts_expired(self) -> None:+ """Sweeper evicts entries older than ttl."""+ ws = await self.manager.get_workspace("u", "a", "s", "wid")+ self.manager._cache["wid"] = (ws, time.monotonic() - 1.0)+ await self.manager._sweep_once()+ self.assertTrue(ws.closed)+ self.assertNotIn("wid", self.manager._cache)++ async def test_manager_rejects_share_net_false(self) -> None:+ """Manager mirrors workspace network limitation."""+ with self.assertRaises(ValueError):+ _FakeBubblewrapWorkspaceManager(+ self.basedir.name,+ share_net=False,+ )++ async def test_manager_rejects_invalid_gateway_port(self) -> None:+ """Manager validates gateway ports before creating workspaces."""+ with self.assertRaises(ValueError):+ _FakeBubblewrapWorkspaceManager(+ self.basedir.name,+ gateway_port=0,+ )++ async def test_manager_rejects_empty_basedir(self) -> None:+ """Manager basedir must not collapse to cwd."""+ with self.assertRaises(ValueError):+ _FakeBubblewrapWorkspaceManager("")++ @unittest.skipIf(os.name == "nt", "POSIX mode bits only")+ async def test_manager_workdir_is_private(self) -> None:+ """Manager-created workdirs use 0700 permissions."""+ manager = BubblewrapWorkspaceManager(+ self.basedir.name,+ ttl=0.01,+ sweep_interval=60.0,+ )+ try:+ with patch.object(+ BubblewrapWorkspace,+ "initialize",+ new=AsyncMock(),+ ):+ ws = await manager._build_and_start(+ workspace_id="wid",+ user_id="u",+ agent_id="a",+ )+ mode = os.stat(ws.host_workdir).st_mode & 0o777+ self.assertEqual(mode, 0o700)+ finally:+ await manager.close_all()++ async def test_workdir_tracks_workspace_id(self) -> None:+ """Different workspace ids use different host workdirs."""+ one = self.manager._workdir_for("user", "workspace-one")+ two = self.manager._workdir_for("user", "workspace-two")+ self.assertNotEqual(one, two)+ self.assertEqual(+ os.path.commonpath(+ [os.path.realpath(self.basedir.name), os.path.realpath(one)],+ ),+ os.path.realpath(self.basedir.name),+ )++ async def test_workdir_hashes_unsafe_identifiers(self) -> None:+ """External ids cannot escape the manager basedir."""+ for user_id, workspace_id in (+ ("u", "../../outside"),+ ("u", os.path.abspath(os.sep)),+ ("../outside", "wid"),+ ):+ path = self.manager._workdir_for(user_id, workspace_id)+ self.assertEqual(+ os.path.commonpath(+ [+ os.path.realpath(self.basedir.name),+ os.path.realpath(path),+ ],+ ),+ os.path.realpath(self.basedir.name),+ )+++if __name__ == "__main__":+ unittest.main()