Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(workspace): support apple container as workspace backend (#2068)
DiegoCluv72ba25bbd2ada
diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.ymlindex 04670f51d..aa3b1fc7b 100644--- a/.github/workflows/unittest.yml+++ b/.github/workflows/unittest.yml@@ -8,12 +8,12 @@ jobs:runs-on: ${{ matrix.os }}strategy:matrix:- os: [ubuntu-latest, windows-latest, macos-15]+ os: [ubuntu-latest, windows-latest, macos-26]python-version: ['3.11']env:OS: ${{ matrix.os }}steps:- - uses: actions/checkout@master+ - uses: actions/checkout@v4- name: Install uvuses: astral-sh/setup-uv@v5with:@@ -31,7 +31,7 @@ jobs:env:GRPC_VERBOSITY: ERRORrun: |- coverage run -m pytest tests+ coverage run -m pytest tests -v- name: Generate coverage reportrun: |coverage report -mdiff --git a/examples/workspace/apple-container-workspace.md b/examples/workspace/apple-container-workspace.mdnew file mode 100644index 000000000..0134d9689--- /dev/null+++ b/examples/workspace/apple-container-workspace.md@@ -0,0 +1,80 @@+# Apple Container Workspace++AgentScope workspace backed by Apple's `container` CLI. Runs agent tool calls (Bash, Read, Write, Edit, Grep, Glob) inside an Apple Container Linux VM.++## Prerequisites++- **macOS 26+** on Apple silicon (Intel Macs are not supported by Apple Container).+- **Apple Container 1.0.0 or later** (tested on 1.0.0 and 1.1.0). Install from the [Apple Container developer site](https://developer.apple.com/container/).+- **`container system start`** must be running before creating any workspace.+- **Outbound network access from the container VM** is required during the first `initialize()` — the bootstrap installs system packages via `apt-get` and downloads `uv` via the installer script. If the container VM cannot reach the internet, initialize will fail at the bootstrap step with an apt-get or curl error.++### Network / Proxy++The container VM shares the host's network stack by default. If your host uses a proxy:++```bash+# Verify the container VM can reach external hosts before using the workspace:+container exec <container-id> curl -I https://pypi.org+```++DNS resolution inside the VM should work out of the box. If TCP connections time out while DNS resolves, check whether your host firewall is blocking traffic from the container VM.++## Supported Images++Any Debian/Ubuntu-based OCI image with `python3` pre-installed. The default is `python:3.11-slim`. Official Docker library images are recognized in both short form and canonical form:++```python+# These are equivalent:+AppleContainerWorkspace(base_image="python:3.11-slim")+AppleContainerWorkspace(base_image="docker.io/library/python:3.11-slim")+```++## Configuration++```python+from agentscope.workspace import AppleContainerWorkspace++ws = AppleContainerWorkspace(+ workspace_id="my-workspace", # optional, auto-generated if omitted+ base_image="python:3.11-slim", # default+ gateway_port=5600, # TCP port for the MCP gateway inside the container+ cpus=2, # virtual CPUs allocated to the container+ memory="2G", # memory limit (e.g. "512M", "4G")+ env={"MY_VAR": "value"}, # environment variables inside the container+ extra_pip=["requests"], # extra pip packages installed during bootstrap+)+```++| Parameter | Default | Description |+|-----------|---------|-------------|+| `workspace_id` | auto UUID | Stable identifier, also used as the container name suffix (`as_ws_<id>`). |+| `base_image` | `python:3.11-slim` | OCI image to run. Must have `python3` and be Debian/Ubuntu-based for apt-get bootstrap. |+| `gateway_port` | `5600` | TCP port the in-container MCP gateway listens on. |+| `cpus` | `2` | Virtual CPUs for the container. |+| `memory` | `"2G"` | Memory limit. |+| `env` | `{}` | Environment variables injected into the container. |+| `extra_pip` | `[]` | Additional pip packages installed in the gateway venv during bootstrap. |++## Lifecycle++```python+import asyncio+from agentscope.workspace import AppleContainerWorkspace++async def main():+ async with AppleContainerWorkspace() as ws:+ # Container is created, bootstrapped, gateway is running.+ backend = ws.get_backend()+ result = await backend.exec_shell(["echo", "hello"])+ print(result.stdout)++ # Container is stopped and removed.++asyncio.run(main())+```++- `initialize()` / `async with`: creates the container, pulls the base image if not cached, bootstraps the gateway venv (apt-get + uv + pip), and starts the MCP gateway.+- `close()`: stops and removes the container. Filesystem state is not persisted.+- Second `initialize()` on the same container name is a no-op if the container is still running.+diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.pyindex fd7a0016c..fd88ca9b6 100644--- a/src/agentscope/app/workspace_manager/__init__.py+++ b/src/agentscope/app/workspace_manager/__init__.py@@ -9,6 +9,9 @@ from ._e2b_workspace_manager import E2BWorkspaceManagerfrom ._daytona_workspace_manager import DaytonaWorkspaceManagerfrom ._k8s_workspace_manager import K8sWorkspaceManagerfrom ._opensandbox_workspace_manager import OpenSandboxWorkspaceManager+from ._applecontainer_workspace_manager import (+ AppleContainerWorkspaceManager,+)from ._bubblewrap_workspace_manager import BubblewrapWorkspaceManager__all__ = [@@ -21,4 +24,5 @@ __all__ = ["DaytonaWorkspaceManager","K8sWorkspaceManager","OpenSandboxWorkspaceManager",+ "AppleContainerWorkspaceManager",]diff --git a/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.pynew file mode 100644index 000000000..0d2af4ade--- /dev/null+++ b/src/agentscope/app/workspace_manager/_applecontainer_workspace_manager.py@@ -0,0 +1,294 @@+# -*- coding: utf-8 -*-+"""AppleContainerWorkspaceManager — lifecycle manager for+:class:`AppleContainerWorkspace`.++Mirrors :class:`DockerWorkspaceManager` 1:1 in its public surface+(``get_workspace`` / ``close`` / ``close_all``) so that callers do not+branch on backend.++Differences from the Docker manager:++* No bind-mount workdir — container filesystem is the persistence+ layer. Container names are deterministic so reattachment works+ across process restarts.+* No Dockerfile generation — images are pulled as OCI images directly.+* Idle workspaces are evicted by a dedicated background sweeper task.+* ``close_all`` shuts containers down in parallel.+"""++import asyncio+import time+from typing import Self++from ..._logging import logger+from ...mcp import MCPClient+from ...workspace import AppleContainerWorkspace+from ...workspace._applecontainer._constants import (+ DEFAULT_BASE_IMAGE,+ DEFAULT_CPUS,+ DEFAULT_GATEWAY_PORT,+ DEFAULT_MEMORY,+)+from ._base import IsolationPolicy, WorkspaceManagerBase++DEFAULT_SWEEP_INTERVAL = 300.0+++class AppleContainerWorkspaceManager(WorkspaceManagerBase):+ """Manages :class:`AppleContainerWorkspace` instances with TTL-based+ caching.++ The manager owns a single set of container parameters+ (``base_image``, ``cpus``, ``memory``) shared by every workspace+ it produces.++ Use the manager as an ``async with`` context manager: entering it+ starts the TTL sweeper task, exiting it stops the sweeper and then+ closes every cached workspace via :meth:`close_all`.+ """++ def __init__(+ self,+ *,+ isolation: IsolationPolicy = IsolationPolicy.PER_AGENT,+ base_image: str = DEFAULT_BASE_IMAGE,+ cpus: int = DEFAULT_CPUS,+ memory: str = DEFAULT_MEMORY,+ gateway_port: int = DEFAULT_GATEWAY_PORT,+ 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 Apple Container workspace manager.++ Args:+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):+ Isolation grain for :meth:`assign_workspace_id`.+ base_image (`str`, defaults to `DEFAULT_BASE_IMAGE`):+ OCI image used for every workspace.+ cpus (`int`, defaults to `DEFAULT_CPUS`):+ Number of virtual CPUs per container.+ memory (`str`, defaults to `DEFAULT_MEMORY`):+ Memory allocation per container (e.g. ``"2G"``).+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):+ TCP port the in-container gateway listens on.+ env (`dict[str, str] | None`, optional):+ Environment variables set in every workspace's+ container.+ extra_pip (`list[str] | None`, optional):+ Extra Python packages installed into the gateway venv+ during bootstrap.+ default_mcps (`list[MCPClient] | None`, optional):+ MCP clients seeded into brand-new workspaces.+ skill_paths (`list[str] | None`, optional):+ Skill directories seeded into brand-new workspaces.+ ttl (`float`, defaults to `3600.0`):+ Seconds before an idle cached workspace is evicted+ and its container torn down.+ sweep_interval (`float`, defaults to+ `DEFAULT_SWEEP_INTERVAL`):+ How often (seconds) the background sweeper wakes up.+ """+ self._base_image = base_image+ self._cpus = cpus+ self._memory = memory+ self._gateway_port = gateway_port+ 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 [])+ super().__init__(isolation=isolation)+ self._ttl = ttl+ self._sweep_interval = sweep_interval++ # workspace_id → (workspace, last_access_monotonic)+ self._cache: dict[+ str,+ tuple[AppleContainerWorkspace, float],+ ] = {}+ self._lock = asyncio.Lock()+ self._sweep_task: asyncio.Task | None = None++ # ── workspace construction ────────────────────────────────────++ async def _build_and_start(+ self,+ *,+ workspace_id: str,+ ) -> AppleContainerWorkspace:+ """Create an :class:`AppleContainerWorkspace` and run its full+ ``initialize``.++ Args:+ workspace_id (`str`):+ Stable identifier forwarded to the workspace.++ Returns:+ `AppleContainerWorkspace`:+ A live, initialized workspace.+ """+ ws = AppleContainerWorkspace(+ workspace_id=workspace_id,+ base_image=self._base_image,+ gateway_port=self._gateway_port,+ cpus=self._cpus,+ memory=self._memory,+ env=self._env,+ extra_pip=self._extra_pip,+ default_mcps=self._default_mcps,+ skill_paths=self._skill_paths,+ )+ await ws.initialize()+ return ws++ # ── public API ────────────────────────────────────────────────++ async def get_workspace(+ self,+ user_id: str,+ agent_id: str,+ session_id: str,+ workspace_id: str | None = None,+ ) -> AppleContainerWorkspace:+ """Return an initialised workspace, building one on cache miss.++ Args:+ user_id (`str`):+ Owning user identifier.+ agent_id (`str`):+ Agent identifier.+ session_id (`str`):+ Session identifier (accepted for interface parity;+ not used here).+ workspace_id (`str | None`, optional):+ Stable workspace identifier — used as the cache key+ and container name suffix. When ``None`` the manager+ falls back to :meth:`assign_workspace_id`.++ Returns:+ `AppleContainerWorkspace`:+ A live, initialised workspace.+ """+ del session_id # accepted for interface parity; not used here++ if workspace_id is None:+ workspace_id = self.assign_workspace_id(+ user_id=user_id,+ agent_id=agent_id,+ session_id="",+ )++ async with self._lock:+ cached = self._cache.get(workspace_id)+ if cached is not None:+ ws, _ = cached+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ # Cache miss: build under the lock.+ async with self._lock:+ cached = self._cache.get(workspace_id)+ if cached is not None:+ ws, _ = cached+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ ws = await self._build_and_start(+ workspace_id=workspace_id,+ )+ self._cache[workspace_id] = (ws, time.monotonic())+ return ws++ async def close(self, workspace_id: str) -> None:+ """Close and evict a single workspace from the cache.++ No-op when the workspace_id is not tracked.++ Args:+ workspace_id (`str`):+ The workspace to close.+ """+ async with self._lock:+ entry = self._cache.pop(workspace_id, None)+ if entry is None:+ return+ ws, _ = entry+ await self._safe_close(ws)++ async def close_all(self) -> None:+ """Close every cached workspace in parallel."""+ async with self._lock:+ entries = list(self._cache.values())+ self._cache.clear()+ if not entries:+ return+ await asyncio.gather(+ *(self._safe_close(ws) for ws, _ in entries),+ return_exceptions=True,+ )++ # ── async context manager ─────────────────────────────────────++ async def __aenter__(self) -> Self:+ """Start the TTL sweeper task."""+ if self._sweep_task is None:+ self._sweep_task = asyncio.create_task(self._sweep_loop())+ return self++ async def __aexit__(self, *exc: object) -> None:+ """Stop the TTL sweeper task, then close every cached workspace."""+ if self._sweep_task is not None:+ self._sweep_task.cancel()+ try:+ await self._sweep_task+ except (asyncio.CancelledError, Exception):+ pass+ self._sweep_task = None+ await self.close_all()++ # ── background sweeper ───────────────────────────────────────++ async def _sweep_loop(self) -> None:+ """Periodically evict idle workspaces."""+ while True:+ try:+ await asyncio.sleep(self._sweep_interval)+ except asyncio.CancelledError:+ return+ try:+ await self._sweep_once()+ except Exception:+ logger.exception(+ "Apple Container workspace sweeper tick failed",+ )++ async def _sweep_once(self) -> None:+ """One sweeper tick: evict expired entries and close them."""+ now = time.monotonic()+ async with self._lock:+ expired_ids = [+ wid+ for wid, (_, ts) in self._cache.items()+ if now - ts > self._ttl+ ]+ evicted = [self._cache.pop(wid)[0] for wid in expired_ids]+ if not evicted:+ return+ await asyncio.gather(+ *(self._safe_close(ws) for ws in evicted),+ return_exceptions=True,+ )++ @staticmethod+ async def _safe_close(ws: AppleContainerWorkspace) -> None:+ """Close a workspace, logging any failure instead of raising."""+ try:+ await ws.close()+ except Exception:+ logger.exception(+ "Failed to close AppleContainerWorkspace %s",+ ws.workspace_id,+ )diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.pyindex db7bce710..cca389d81 100644--- a/src/agentscope/workspace/__init__.py+++ b/src/agentscope/workspace/__init__.py@@ -10,6 +10,7 @@ from ._e2b import E2BWorkspace, E2BBackendfrom ._daytona import DaytonaBackend, DaytonaWorkspacefrom ._k8s import K8sBackend, K8sWorkspacefrom ._opensandbox import OpenSandboxBackend, OpenSandboxWorkspace+from ._applecontainer import AppleContainerBackend, AppleContainerWorkspacefrom ._bubblewrap import BubblewrapBackend, BubblewrapWorkspace@@ -29,4 +30,6 @@ __all__ = ["Offloader","OpenSandboxBackend","OpenSandboxWorkspace",+ "AppleContainerBackend",+ "AppleContainerWorkspace",]diff --git a/src/agentscope/workspace/_applecontainer/__init__.py b/src/agentscope/workspace/_applecontainer/__init__.pynew file mode 100644index 000000000..990999eea--- /dev/null+++ b/src/agentscope/workspace/_applecontainer/__init__.py@@ -0,0 +1,18 @@+# -*- coding: utf-8 -*-+"""Apple-Container-backed workspace.++Uses Apple's ``container`` CLI to run Linux containers as lightweight+VMs on macOS 26+ with Apple silicon. MCP servers run *inside* the+container behind a FastAPI gateway and are reached through+:class:`GatewayClient` via :class:`AppleContainerBackend`.++Requires:+- macOS 26+ with Apple silicon+- ``container`` CLI installed+- ``container system start`` running+"""++from ._applecontainer_backend import AppleContainerBackend+from ._applecontainer_workspace import AppleContainerWorkspace++__all__ = ["AppleContainerBackend", "AppleContainerWorkspace"]diff --git a/src/agentscope/workspace/_applecontainer/_applecontainer_backend.py b/src/agentscope/workspace/_applecontainer/_applecontainer_backend.pynew file mode 100644index 000000000..fcf96e45b--- /dev/null+++ b/src/agentscope/workspace/_applecontainer/_applecontainer_backend.py@@ -0,0 +1,215 @@+# -*- coding: utf-8 -*-+"""Apple Container :class:`BackendBase` implementation.++Wraps the ``container`` CLI (``container exec``, ``container cp``)+into the three backend primitives (``exec_shell``, ``read_file``,+``write_file``) so that builtin tools (Bash, Read, Write, Edit, Grep,+Glob) can operate inside an Apple container transparently. All derived+filesystem helpers (``file_exists``, ``is_dir``, ``list_dir``,+``stat_mtime``, ``delete_path``) are inherited from+:class:`BackendBase`, which implements them via ``exec_shell``.+"""++from __future__ import annotations++import asyncio+import os+import posixpath+import tempfile++from ...tool import BackendBase, ExecResult+++class AppleContainerBackend(BackendBase):+ """Backend that delegates to a running Apple container via the+ ``container`` CLI.++ Only the three abstract primitives (``exec_shell``, ``read_file``,+ ``write_file``) are implemented here; the derived filesystem helpers+ are inherited from :class:`BackendBase`.++ Args:+ container_id (`str`):+ The Apple container identifier (set via ``--name`` at+ creation time).+ workdir (`str`):+ Default working directory for ``exec_shell`` calls inside+ the container.+ """++ def __init__(self, container_id: str, workdir: str) -> None:+ """Initialize the Apple Container backend.++ Args:+ container_id (`str`):+ The container identifier.+ workdir (`str`):+ Default working directory for ``exec_shell`` calls+ inside the container.+ """+ self._container_id = container_id+ self._workdir = workdir++ # ── exec ───────────────────────────────────────────────────────++ async def getcwd(self) -> str:+ """Return the container's default working directory.++ Returns:+ `str`:+ The container'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 a program inside the Apple container via+ ``container exec``.++ *command* is an argv list passed directly after the container+ identifier — no ``--`` separator is used (Apple Container treats+ ``--`` as the target executable). Callers needing shell features+ pass ``["sh", "-c", line]``.++ Args:+ command (`list[str]`):+ Executable path/name followed by its arguments.+ cwd (`str | None`, optional):+ Working directory inside the container. When ``None``+ the backend's default ``workdir`` is used.+ timeout (`float | None`, optional):+ Maximum number of seconds to wait. When ``None`` the+ call waits indefinitely.++ Returns:+ `ExecResult`:+ The captured exit code, stdout, and stderr.+ """+ workdir = cwd or self._workdir+ cli_cmd = [+ "container",+ "exec",+ "--workdir",+ workdir,+ self._container_id,+ ] + list(command)++ try:+ process = await asyncio.create_subprocess_exec(+ *cli_cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ try:+ stdout, stderr = await asyncio.wait_for(+ process.communicate(),+ timeout=timeout,+ )+ except asyncio.TimeoutError:+ process.kill()+ await process.communicate()+ return ExecResult(+ exit_code=-1,+ stdout=b"",+ stderr=b"timed out",+ )+ return ExecResult(+ exit_code=process.returncode or 0,+ stdout=stdout,+ stderr=stderr,+ )+ except FileNotFoundError:+ return ExecResult(+ exit_code=127,+ stdout=b"",+ stderr=b"container CLI not found - is Apple Container "+ b"installed?",+ )+ except OSError as exc:+ return ExecResult(+ exit_code=-1,+ stdout=b"",+ stderr=str(exc).encode("utf-8"),+ )++ # ── file I/O ───────────────────────────────────────────────────++ async def read_file(self, path: str) -> bytes:+ """Read a file from the container via ``container exec cat``.++ Args:+ path (`str`):+ Path to the file inside the container.++ Returns:+ `bytes`:+ The raw file contents.++ Raises:+ `FileNotFoundError`:+ If the path does not exist inside the container.+ """+ result = await self.exec_shell(["cat", path])+ if result.exit_code != 0:+ raise FileNotFoundError(+ f"not found in container: {path}\n"+ f"stderr: {result.stderr.decode(errors='replace')}",+ )+ return result.stdout++ async def write_file(self, path: str, data: bytes) -> None:+ """Write *data* to a file inside the container via+ ``container cp``.++ Writes *data* to a host-side temp file, then copies it into the+ container.++ Args:+ path (`str`):+ Destination path inside the container.+ data (`bytes`):+ The raw bytes to write.+ """+ # Write data to a host-side temp file.+ tmp_fd, tmp_path = tempfile.mkstemp(+ prefix="as_ws_",+ suffix=".bin",+ )+ try:+ # Write all bytes, handling partial writes.+ with os.fdopen(tmp_fd, "wb") as f:+ f.write(data)++ # Create parent directory inside the container first.+ parent = posixpath.dirname(path)+ if parent and parent != "/":+ await self.exec_shell(+ ["mkdir", "-p", parent],+ )++ # Copy the temp file into the container.+ container_path = f"{self._container_id}:{path}"+ process = await asyncio.create_subprocess_exec(+ "container",+ "cp",+ tmp_path,+ container_path,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ _stdout, stderr = await process.communicate()+ if process.returncode != 0:+ raise OSError(+ f"container cp failed (exit {process.returncode}): "+ f"{stderr.decode(errors='replace')}",+ )+ finally:+ try:+ os.unlink(tmp_path)+ except OSError:+ passdiff --git a/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.py b/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.pynew file mode 100644index 000000000..fb218425b--- /dev/null+++ b/src/agentscope/workspace/_applecontainer/_applecontainer_workspace.py@@ -0,0 +1,525 @@+# -*- coding: utf-8 -*-+"""AppleContainerWorkspace — sandboxed workspace backed by Apple's+``container`` CLI.++Architecture+------------++Mirrors :class:`agentscope.workspace.E2BWorkspace` but swaps the E2B+SDK for the ``container`` CLI:++* **Lifecycle.** ``initialize()`` pulls the base image (if needed),+ creates and starts a container via ``container run -d``, then+ bootstraps the MCP gateway inside the container.+ ``close()`` calls ``container stop`` + ``container rm -f``.++* **Persistence.** Container filesystem state is the persistence+ layer — there is no host-side ``workdir`` parameter. Stopping the+ container discards state; volumes are not used by default.++* **Bootstrap.** First-time provisioning installs uv + a gateway venv+ + agentscope (``--no-deps``) and uploads the gateway script. The+ probe + install loop lives on :class:`SandboxedWorkspaceBase`; this+ subclass only supplies the container-specific shell commands via+ :meth:`_bootstrap_commands`. Bootstrap runs at most once per+ container lifetime.++* **MCP gateway.** Identical to Docker/E2B: a FastAPI process inside+ the container. All host-side calls drive the gateway through+ :class:`GatewayClient`, which runs an in-container ``python3 -c``+ shim via :meth:`AppleContainerBackend.exec_shell`.++.. note::++ Apple Container requires the system service to be running+ (``container system start``) and is available on macOS 26++ with Apple silicon only.+"""++import asyncio+import json+import shlex++from ..._logging import logger+from ...mcp import MCPClient+from .._sandboxed_base import SandboxedWorkspaceBase+from .._utils import _GATEWAY_BASE_REQUIREMENTS+from ._applecontainer_backend import AppleContainerBackend+from ._constants import (+ CONTAINER_WORKDIR,+ DEFAULT_BASE_IMAGE,+ DEFAULT_CPUS,+ DEFAULT_GATEWAY_PORT,+ DEFAULT_MEMORY,+ GATEWAY_HOME,+)++_DEFAULT_INSTRUCTIONS = """<workspace>+You have an Apple-Container-based workspace. All tool calls execute+**inside the container** at ``{workdir}``.++Layout:++```+{workdir}+├── data/ # offloaded multimodal files+├── skills/ # reusable skills+└── sessions/ # session context and tool results+```+</workspace>"""+++# ── the workspace ──────────────────────────────────────────────────+++class AppleContainerWorkspace(SandboxedWorkspaceBase):+ """Workspace backed by Apple's ``container`` CLI.++ ``default_mcps`` and ``skill_paths`` are seed-time inputs and are+ not retained as instance state past :meth:`initialize`.++ Requires:+ - macOS 26+ with Apple silicon+ - ``container`` CLI installed and ``container system start`` running+ """++ _gateway_home = GATEWAY_HOME+ _bootstrap_cmd_timeout = 600.0++ def __init__(+ self,+ *,+ workspace_id: str | None = None,+ base_image: str = DEFAULT_BASE_IMAGE,+ gateway_port: int = DEFAULT_GATEWAY_PORT,+ cpus: int = DEFAULT_CPUS,+ memory: str = DEFAULT_MEMORY,+ 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 an :class:`AppleContainerWorkspace`.++ The container is *not* started here — call :meth:`initialize`+ (or use the workspace as an ``async`` context manager).++ Args:+ workspace_id (`str | None`, optional):+ Stable identifier; also used as the container name+ suffix.+ base_image (`str`, defaults to `DEFAULT_BASE_IMAGE`):+ OCI image to run. Must provide ``python3``. Ubuntu/+ Debian-based images are preferred for apt-get+ bootstrap.+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):+ TCP port the in-container gateway listens on.+ cpus (`int`, defaults to `DEFAULT_CPUS`):+ Number of virtual CPUs allocated to the container.+ memory (`str`, defaults to `DEFAULT_MEMORY`):+ Memory allocation (e.g. ``"2G"``, ``"512M"``).+ env (`dict[str, str] | None`, optional):+ Environment variables set inside the container.+ extra_pip (`list[str] | None`, optional):+ Extra Python packages installed into the gateway venv+ during bootstrap.+ instructions (`str`, defaults to `_DEFAULT_INSTRUCTIONS`):+ System-prompt fragment template (supports ``{workdir}``).+ default_mcps (`list[MCPClient] | None`, optional):+ MCPs registered on first init when no persisted+ ``.mcp`` exists.+ skill_paths (`list[str] | None`, optional):+ Local skill dirs seeded into ``skills/`` on first init.+ """+ super().__init__(+ workspace_id=workspace_id,+ default_mcps=default_mcps,+ skill_paths=skill_paths,+ )++ # ── serializable config ─────────────────────────────────+ self.workdir = CONTAINER_WORKDIR+ self.base_image = base_image+ self.gateway_port = gateway_port+ self.cpus = cpus+ self.memory = memory+ self.env: dict[str, str] = dict(env or {})+ self.extra_pip: list[str] = list(extra_pip or [])+ self.instructions = instructions++ # ── runtime state ───────────────────────────────────────+ self._backend: AppleContainerBackend | None = None+ self._container_name: str = f"as_ws_{self.workspace_id}"++ # ── lifecycle hooks ─────────────────────────────────────────++ async def _provision_backend(self) -> None:+ """Pull the base image (if needed), create and start the+ container, and bind the backend.++ Steps:+ 1. Verify ``container`` CLI is available.+ 2. Pull the base image if not already present locally.+ 3. Create and start the container via ``container run -d``.+ 4. Bind :class:`AppleContainerBackend`.+ """+ # 1. Verify CLI availability.+ await self._check_cli()++ # 2. Pull the image if needed.+ await self._pull_image_if_needed()++ # 3. Check for an existing container with the same name.+ existing_id = await self._find_existing_container()+ if existing_id is not None:+ logger.info(+ "AppleContainerWorkspace: reattaching to existing "+ "container %r (workspace_id=%r)",+ existing_id,+ self.workspace_id,+ )+ # Ensure the container is running.+ await self._start_container_if_stopped()+ else:+ await self._create_and_start_container()++ # 4. Bind the backend.+ self._backend = AppleContainerBackend(+ container_id=self._container_name,+ workdir=CONTAINER_WORKDIR,+ )++ async def _teardown_backend(self) -> None:+ """Stop and remove the container. Errors are swallowed."""+ if self._backend is None:+ return+ try:+ process = await asyncio.create_subprocess_exec(+ "container",+ "stop",+ self._container_name,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ await process.communicate()+ except Exception as e:+ logger.warning(+ "AppleContainerWorkspace: stop failed: %s",+ e,+ )+ try:+ process = await asyncio.create_subprocess_exec(+ "container",+ "rm",+ "-f",+ self._container_name,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ await process.communicate()+ except Exception as e:+ logger.warning(+ "AppleContainerWorkspace: rm failed: %s",+ e,+ )+ self._backend = None++ # ── instructions ────────────────────────────────────────────++ async def get_instructions(self) -> str:+ """Return the system-prompt fragment, formatted with ``{workdir}``."""+ return self.instructions.format(workdir=CONTAINER_WORKDIR)++ # ── internals: CLI check ────────────────────────────────────++ async def _check_cli(self) -> None:+ """Verify the ``container`` CLI is installed and responsive.++ Runs ``container system version --format json`` and parses the+ output to confirm the CLI is available.++ Raises:+ RuntimeError: If the CLI is not installed or the system+ service is not running.+ """+ try:+ process = await asyncio.create_subprocess_exec(+ "container",+ "system",+ "version",+ "--format",+ "json",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await process.communicate()+ except FileNotFoundError as e:+ # The ``container`` binary itself is missing.+ raise RuntimeError(+ "Apple Container CLI is not installed. Install it "+ "first: https://github.com/apple/container",+ ) from e+ if process.returncode != 0:+ raise RuntimeError(+ "Apple Container CLI is not available. "+ "Ensure it is installed and running: "+ "`container system start`.\n"+ f"stderr: {stderr.decode(errors='replace')}",+ )+ logger.info(+ "AppleContainerWorkspace: CLI OK — %s",+ stdout.decode(errors="replace").strip(),+ )++ # ── internals: image management ─────────────────────────────++ @staticmethod+ def _normalize_image_ref(ref: str) -> str:+ """Normalize an OCI image reference for comparison.++ Strips the default registry (``docker.io``) and the default+ namespace (``library``) so that short references like+ ``python:3.11-slim`` match the canonical form returned by+ ``container image list``+ (``docker.io/library/python:3.11-slim``).++ Args:+ ref (`str`):+ An image reference, either short or canonical.++ Returns:+ `str`:+ The normalized form without default registry/namespace.+ """+ # Strip optional tag/digest for prefix normalization.+ parts = ref.split("/")+ if len(parts) >= 2 and parts[0] == "docker.io":+ parts = parts[1:]+ if len(parts) >= 2 and parts[0] == "library":+ parts = parts[1:]+ return "/".join(parts)++ async def _pull_image_if_needed(self) -> None:+ """Pull *base_image* if it is not already present locally.++ Uses ``container image list --format json`` to check for the+ image. Both the configured image name and the canonical name+ reported by the CLI are normalized before comparison.+ """+ target = self._normalize_image_ref(self.base_image)++ # Check if the image is already available locally.+ process = await asyncio.create_subprocess_exec(+ "container",+ "image",+ "list",+ "--format",+ "json",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, _ = await process.communicate()+ if process.returncode == 0:+ try:+ images = json.loads(stdout.decode())+ except (json.JSONDecodeError, UnicodeDecodeError):+ images = []+ for img in images:+ if isinstance(img, dict) and img.get("name"):+ if self._normalize_image_ref(img["name"]) == target:+ logger.info(+ "AppleContainerWorkspace: image %r already "+ "present (as %r)",+ self.base_image,+ img["name"],+ )+ return++ # Pull the image.+ logger.info(+ "AppleContainerWorkspace: pulling image %r ...",+ self.base_image,+ )+ process = await asyncio.create_subprocess_exec(+ "container",+ "image",+ "pull",+ self.base_image,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ _, stderr = await process.communicate()+ if process.returncode != 0:+ raise RuntimeError(+ f"Failed to pull image {self.base_image!r}: "+ f"{stderr.decode(errors='replace')}",+ )+ logger.info(+ "AppleContainerWorkspace: image %r pulled successfully",+ self.base_image,+ )++ # ── internals: container lifecycle ──────────────────────────++ async def _find_existing_container(self) -> str | None:+ """Find a container by name via ``container list --format json``.++ Returns:+ `str | None`:+ The container ID if found, ``None`` otherwise.+ """+ process = await asyncio.create_subprocess_exec(+ "container",+ "list",+ "--all",+ "--format",+ "json",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, _ = await process.communicate()+ if process.returncode != 0:+ return None+ try:+ containers = json.loads(stdout.decode())+ except (json.JSONDecodeError, UnicodeDecodeError):+ return None+ for c in containers:+ if isinstance(c, dict) and c.get("name") == self._container_name:+ return c.get("id")+ return None++ async def _start_container_if_stopped(self) -> None:+ """Start the container if it is not already running."""+ # Check if the container is already running.+ process = await asyncio.create_subprocess_exec(+ "container",+ "inspect",+ self._container_name,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, _ = await process.communicate()+ if process.returncode == 0:+ try:+ info = json.loads(stdout.decode())+ except (json.JSONDecodeError, UnicodeDecodeError):+ info = None+ # ``container inspect`` may return a bare object or a+ # single-element array (Docker-compatible shape).+ if isinstance(info, list):+ info = info[0] if info else None+ if isinstance(info, dict) and info.get(+ "status",+ "",+ ) in ("running",):+ logger.info(+ "AppleContainerWorkspace: container %r already running",+ self._container_name,+ )+ return++ # Start the container.+ logger.info(+ "AppleContainerWorkspace: starting container %r ...",+ self._container_name,+ )+ process = await asyncio.create_subprocess_exec(+ "container",+ "start",+ self._container_name,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ _, stderr = await process.communicate()+ if process.returncode != 0:+ raise RuntimeError(+ f"Failed to start container {self._container_name!r}: "+ f"{stderr.decode(errors='replace')}",+ )++ async def _create_and_start_container(self) -> None:+ """Create and start the container via ``container run -d``.++ The container runs ``sleep infinity`` to stay alive while the+ gateway is managed independently.+ """+ run_cmd: list[str] = [+ "container",+ "run",+ "-d",+ "--name",+ self._container_name,+ "--cpus",+ str(self.cpus),+ "--memory",+ self.memory,+ ]++ # Environment variables.+ for key, value in self.env.items():+ run_cmd.extend(["--env", f"{key}={value}"])++ # Image and init command.+ run_cmd.extend(+ [+ self.base_image,+ "sleep",+ "infinity",+ ],+ )++ logger.info(+ "AppleContainerWorkspace: creating container %r ...",+ self._container_name,+ )+ process = await asyncio.create_subprocess_exec(+ *run_cmd,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ stdout, stderr = await process.communicate()+ if process.returncode != 0:+ raise RuntimeError(+ f"Failed to create container {self._container_name!r}: "+ f"stderr: {stderr.decode(errors='replace')}\n"+ f"stdout: {stdout.decode(errors='replace')}",+ )+ logger.info(+ "AppleContainerWorkspace: container %r created (id=%s)",+ self._container_name,+ stdout.decode(errors="replace").strip(),+ )++ # ── internals: bootstrap ────────────────────────────────────++ def _bootstrap_commands(self) -> list[str]:+ """Shell commands that provision this container once.++ Only runs when the gateway script is missing (fresh container+ or prior interrupted bootstrap). Every step is idempotent.++ ``--no-deps`` on agentscope is mandatory: the gateway only+ imports :class:`agentscope.mcp.MCPClient` whose transitive+ needs (``mcp / pydantic / httpx``) are already installed via+ the gateway base requirements.+ """+ pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)+ pip_args = " ".join(shlex.quote(p) for p in pip_pkgs)++ return [+ # 1. System deps + uv installer.+ "apt-get update -qq "+ "&& apt-get install -y --no-install-recommends "+ "curl ripgrep "+ "&& rm -rf /var/lib/apt/lists/*",+ "curl -LsSf https://astral.sh/uv/install.sh "+ "| env UV_INSTALL_DIR=/usr/local/bin "+ "INSTALLER_NO_MODIFY_PATH=1 sh",+ # 2. Gateway venv + base requirements + agentscope.+ f"uv venv {self._gateway_venv}",+ f"uv pip install --python {self._gateway_python} {pip_args}",+ f"uv pip install --python {self._gateway_python} "+ f"--no-deps 'agentscope'",+ ]diff --git a/src/agentscope/workspace/_applecontainer/_constants.py b/src/agentscope/workspace/_applecontainer/_constants.pynew file mode 100644index 000000000..511914062--- /dev/null+++ b/src/agentscope/workspace/_applecontainer/_constants.py@@ -0,0 +1,27 @@+# -*- coding: utf-8 -*-+"""Apple-Container-specific constants for+:class:`AppleContainerWorkspace`.++Path layout (venv, script, log, helper) is derived on the base class+from ``_gateway_home``. This module only carries defaults that cannot+be derived: image, timeouts, port, container user, workdir.+"""++#: Default base image. Must provide ``python3`` and be Debian/Ubuntu+#: based for apt-get bootstrap compatibility.+DEFAULT_BASE_IMAGE = "python:3.11-slim"++#: Default gateway port inside the container (no host port mapping).+DEFAULT_GATEWAY_PORT = 5600++#: Default CPUs allocated to the container.+DEFAULT_CPUS = 2++#: Default memory allocated to the container (2 GiB).+DEFAULT_MEMORY = "2G"++#: Container-side workdir — agent-visible root.+CONTAINER_WORKDIR = "/workspace"++#: Container-side gateway home (root user, same as Docker workspace).+GATEWAY_HOME = "/root/.agentscope"diff --git a/tests/backend_applecontainer_test.py b/tests/backend_applecontainer_test.pynew file mode 100644index 000000000..fa4b078c8--- /dev/null+++ b/tests/backend_applecontainer_test.py@@ -0,0 +1,460 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+# mypy: disable-error-code="misc,no-untyped-def,attr-defined"+"""Test cases for :class:`AppleContainerBackend`.++Runs against a real Apple Container via the ``container`` CLI.+Requires ``container`` CLI installed and ``container system start``+running.+"""++import shutil+import sys+import unittest+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch+from uuid import uuid4++from agentscope.tool import ExecResult+from agentscope.workspace import AppleContainerBackend++_CONTAINER_CLI = shutil.which("container")+_RUN_REASON = "container CLI not found — install Apple Container first"++#: Patch target for the CLI spawn inside the backend module.+_EXEC_PATCH = (+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec"+)+++def _ok_proc() -> AsyncMock:+ """A mock process that exits 0 with empty stdout/stderr."""+ proc = AsyncMock()+ proc.returncode = 0+ proc.communicate.return_value = (b"", b"")+ return proc+++class TestAppleContainerBackendCommandConstruction(IsolatedAsyncioTestCase):+ """CLI argv construction tests — no container needed.++ Each test patches ``create_subprocess_exec``, drives the backend,+ and asserts on the *actual* argv the backend passes, verifying the+ ``--`` separator is never present (Apple Container treats ``--`` as+ the target executable).+ """++ WORKDIR = "/workspace"+ CONTAINER_ID = "test-container"++ def setUp(self) -> None:+ self.backend = AppleContainerBackend(+ container_id=self.CONTAINER_ID,+ workdir=self.WORKDIR,+ )++ @patch(_EXEC_PATCH)+ async def test_simple_command_argv(self, mock_exec: AsyncMock) -> None:+ """A plain command yields the exec prefix and no ``--``."""+ mock_exec.return_value = _ok_proc()+ await self.backend.exec_shell(["echo", "hello"])+ argv = list(mock_exec.call_args.args)+ self.assertEqual(+ argv,+ [+ "container",+ "exec",+ "--workdir",+ self.WORKDIR,+ self.CONTAINER_ID,+ "echo",+ "hello",+ ],+ )+ self.assertNotIn("--", argv)++ @patch(_EXEC_PATCH)+ async def test_custom_cwd_in_argv(self, mock_exec: AsyncMock) -> None:+ """Custom ``cwd`` is passed via ``--workdir``, no ``--``."""+ mock_exec.return_value = _ok_proc()+ await self.backend.exec_shell(["pwd"], cwd="/custom/dir")+ argv = list(mock_exec.call_args.args)+ self.assertEqual(argv[3], "/custom/dir")+ self.assertEqual(argv[-1], "pwd")+ self.assertNotIn("--", argv)++ @patch(_EXEC_PATCH)+ async def test_shell_command_wrapping(+ self,+ mock_exec: AsyncMock,+ ) -> None:+ """Shell features wrapped in ``sh -c`` are appended verbatim."""+ mock_exec.return_value = _ok_proc()+ await self.backend.exec_shell(+ ["sh", "-c", "echo hello && echo world"],+ )+ argv = list(mock_exec.call_args.args)+ self.assertEqual(argv[-3:], ["sh", "-c", "echo hello && echo world"])+ self.assertNotIn("--", argv)++ @patch(_EXEC_PATCH)+ async def test_multi_arg_command(self, mock_exec: AsyncMock) -> None:+ """Commands with multiple args are appended in order."""+ mock_exec.return_value = _ok_proc()+ cmd = ["find", "/", "-name", "*.py", "-type", "f"]+ await self.backend.exec_shell(cmd)+ argv = list(mock_exec.call_args.args)+ prefix = [+ "container",+ "exec",+ "--workdir",+ self.WORKDIR,+ self.CONTAINER_ID,+ ]+ self.assertEqual(argv, prefix + cmd)+ self.assertNotIn("--", argv)+++class TestAppleContainerBackendUnit(IsolatedAsyncioTestCase):+ """Unit tests for error paths — no container needed.++ These mock ``asyncio.create_subprocess_exec`` to exercise FileNotFound,+ timeout, and non-zero-exit code paths without a real container.+ """++ WORKDIR = "/workspace"+ CONTAINER_ID = "unit-test-ctr"++ def setUp(self) -> None:+ self.backend = AppleContainerBackend(+ container_id=self.CONTAINER_ID,+ workdir=self.WORKDIR,+ )++ # ── FileNotFoundError → exit_code 127 ───────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_exec_cli_not_found(self, mock_exec: AsyncMock) -> None:+ """When ``container`` CLI is missing, return exit_code 127."""+ mock_exec.side_effect = FileNotFoundError("container not found")+ result = await self.backend.exec_shell(["echo", "hello"])+ self.assertEqual(result.exit_code, 127)+ self.assertEqual(result.stdout, b"")+ self.assertIn(b"container CLI not found", result.stderr)++ # ── OSError → exit_code -1 ──────────────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_exec_oserror(self, mock_exec: AsyncMock) -> None:+ """OSError (not FileNotFound) returns exit_code -1."""+ mock_exec.side_effect = OSError("spawn failed")+ result = await self.backend.exec_shell(["echo", "hello"])+ self.assertEqual(result.exit_code, -1)+ self.assertEqual(result.stdout, b"")+ self.assertIn(b"spawn failed", result.stderr)++ # ── timeout → exit_code -1 ──────────────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_exec_timeout(self, mock_exec: AsyncMock) -> None:+ """Timeout returns exit_code -1 with 'timed out' stderr."""+ import asyncio+ from unittest.mock import MagicMock++ # Use MagicMock (not AsyncMock) so that kill() is a plain callable+ # instead of a coroutine (the real code does not await kill()).+ mock_proc = MagicMock()+ mock_proc.returncode = None+ mock_proc.kill = MagicMock()++ # communicate() must be an async callable that raises TimeoutError+ # on the first call and returns (b"", b"") on subsequent calls.+ _call_count = 0++ async def _communicate():+ nonlocal _call_count+ _call_count += 1+ if _call_count == 1:+ raise asyncio.TimeoutError+ return b"", b""++ mock_proc.communicate = _communicate+ mock_exec.return_value = mock_proc++ result = await self.backend.exec_shell(+ ["sleep", "10"],+ timeout=0.1,+ )+ self.assertEqual(result.exit_code, -1)+ self.assertIn(b"timed out", result.stderr)+ mock_proc.kill.assert_called_once()++ # ── non-zero exit ───────────────────────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_exec_nonzero_exit(self, mock_exec: AsyncMock) -> None:+ """Non-zero exit codes are captured correctly."""+ mock_proc = AsyncMock()+ mock_proc.returncode = 4+ mock_proc.communicate.return_value = (b"", b"something failed")+ mock_exec.return_value = mock_proc++ result = await self.backend.exec_shell(+ ["sh", "-c", "exit 4"],+ )+ self.assertEqual(result.exit_code, 4)+ self.assertEqual(result.stderr, b"something failed")++ # ── read_file: file not found ───────────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_read_file_not_found(self, mock_exec: AsyncMock) -> None:+ """read_file raises FileNotFoundError on non-zero exit."""+ mock_proc = AsyncMock()+ mock_proc.returncode = 1+ mock_proc.communicate.return_value = (b"", b"No such file")+ mock_exec.return_value = mock_proc++ with self.assertRaises(FileNotFoundError):+ await self.backend.read_file("/nonexistent")++ # ── write_file: container cp failure ────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_write_file_cp_failure(self, mock_exec: AsyncMock) -> None:+ """write_file raises OSError when ``container cp`` fails."""+ # First call: mkdir -p (succeeds), second: container cp (fails).+ mkdir_proc = AsyncMock()+ mkdir_proc.returncode = 0+ mkdir_proc.communicate.return_value = (b"", b"")++ cp_proc = AsyncMock()+ cp_proc.returncode = 1+ cp_proc.communicate.return_value = (b"", b"cp failed")++ mock_exec.side_effect = [mkdir_proc, cp_proc]++ with self.assertRaises(OSError):+ await self.backend.write_file("/tmp/test.txt", b"data")++ # ── read_file success path ──────────────────────────────────────++ @patch(+ "agentscope.workspace._applecontainer._applecontainer_backend."+ "asyncio.create_subprocess_exec",+ )+ async def test_read_file_success(self, mock_exec: AsyncMock) -> None:+ """read_file returns bytes on success."""+ mock_proc = AsyncMock()+ mock_proc.returncode = 0+ mock_proc.communicate.return_value = (b"hello world", b"")+ mock_exec.return_value = mock_proc++ result = await self.backend.read_file("/tmp/test.txt")+ self.assertEqual(result, b"hello world")++[email protected](_CONTAINER_CLI, _RUN_REASON)+ sys.platform == "darwin",+ "Apple Container requires macOS",+)+class TestAppleContainerBackend(IsolatedAsyncioTestCase):+ """Test cases against a real Apple Container."""++ WORKDIR = "/workspace"+ #: Unique per run so a leaked container never collides on re-run.+ container_name = f"as_test_backend_{uuid4().hex[:8]}"++ @classmethod+ def setUpClass(cls) -> None:+ """Create a test container once for all tests."""+ import asyncio++ asyncio.run(cls._setup_container())++ @classmethod+ def tearDownClass(cls) -> None:+ """Remove the test container."""+ import asyncio++ asyncio.run(cls._teardown_container())++ @classmethod+ async def _setup_container(cls) -> None:+ """Create a container for testing and its ``/workspace`` root."""+ import asyncio++ proc = await asyncio.create_subprocess_exec(+ "container",+ "run",+ "-d",+ "--name",+ cls.container_name,+ "python:3.11-slim",+ "sleep",+ "infinity",+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ _stdout, stderr = await proc.communicate()+ if proc.returncode != 0:+ raise RuntimeError(+ f"Failed to create test container: "+ f"{stderr.decode(errors='replace')}",+ )+ # The bare image has no ``/workspace``; create it so exec calls+ # using ``--workdir /workspace`` resolve to an existing dir.+ mkdir = await asyncio.create_subprocess_exec(+ "container",+ "exec",+ cls.container_name,+ "mkdir",+ "-p",+ cls.WORKDIR,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ await mkdir.communicate()++ @classmethod+ async def _teardown_container(cls) -> None:+ """Stop and remove the test container, awaiting completion."""+ import asyncio++ for args in (+ ("container", "stop", cls.container_name),+ ("container", "rm", "-f", cls.container_name),+ ):+ proc = await asyncio.create_subprocess_exec(+ *args,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ )+ await proc.communicate()++ def setUp(self) -> None:+ """Create a backend instance for each test."""+ self.backend = AppleContainerBackend(+ container_id=self.container_name,+ workdir=self.WORKDIR,+ )++ # ── getcwd ─────────────────────────────────────────────────────++ async def test_getcwd_returns_workdir(self) -> None:+ """``getcwd`` returns the cached workdir."""+ self.assertEqual(await self.backend.getcwd(), self.WORKDIR)++ # ── exec_shell ─────────────────────────────────────────────────++ async def test_exec_simple_command(self) -> None:+ """A simple command runs successfully."""+ result = await self.backend.exec_shell(["echo", "hello"])+ self.assertIsInstance(result, ExecResult)+ self.assertTrue(result.ok())+ self.assertEqual(result.stdout.strip(), b"hello")++ async def test_exec_with_custom_cwd(self) -> None:+ """Custom ``cwd`` changes the working directory."""+ result = await self.backend.exec_shell(["pwd"], cwd="/tmp")+ self.assertTrue(result.ok())+ self.assertEqual(result.stdout.strip(), b"/tmp")++ async def test_exec_nonzero_exit(self) -> None:+ """Non-zero exit code is reported normally."""+ result = await self.backend.exec_shell(+ ["sh", "-c", "exit 4"],+ )+ self.assertEqual(result.exit_code, 4)++ async def test_exec_timeout(self) -> None:+ """Timeout returns exit_code -1."""+ result = await self.backend.exec_shell(+ ["sleep", "10"],+ timeout=0.5,+ )+ self.assertEqual(result.exit_code, -1)+ self.assertIn(b"timed out", result.stderr)++ async def test_exec_stderr_captured(self) -> None:+ """Stderr is captured."""+ result = await self.backend.exec_shell(+ ["sh", "-c", "echo err >&2"],+ )+ self.assertTrue(result.ok())+ self.assertIn(b"err", result.stderr)++ # ── read_file ──────────────────────────────────────────────────++ async def test_read_write_roundtrip(self) -> None:+ """Bytes written are read back verbatim."""+ path = f"{self.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_read_file_not_found(self) -> None:+ """Reading a missing file raises ``FileNotFoundError``."""+ with self.assertRaises(FileNotFoundError):+ await self.backend.read_file(f"{self.WORKDIR}/missing.txt")++ async def test_write_creates_parent_dirs(self) -> None:+ """``write_file`` creates missing parent directories."""+ path = f"{self.WORKDIR}/a/b/c/file.txt"+ await self.backend.write_file(path, b"x")+ self.assertEqual(await self.backend.read_file(path), b"x")++ # ── derived filesystem helpers ─────────────────────────────────++ async def test_file_exists_and_is_dir(self) -> None:+ """``file_exists`` / ``is_dir`` work correctly."""+ path = f"{self.WORKDIR}/f.txt"+ await self.backend.write_file(path, b"x")+ self.assertTrue(await self.backend.file_exists(path))+ self.assertTrue(await self.backend.is_dir(self.WORKDIR))+ self.assertFalse(await self.backend.is_dir(path))+ self.assertFalse(+ await self.backend.file_exists(f"{self.WORKDIR}/missing"),+ )++ async def test_list_dir(self) -> None:+ """Non-recursive ``list_dir`` returns immediate children."""+ base = f"{self.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_delete_path(self) -> None:+ """``delete_path`` removes files and trees."""+ path = f"{self.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"{self.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))+ # Deleting a non-existent path must not raise.+ await self.backend.delete_path(f"{self.WORKDIR}/missing")diff --git a/tests/workspace_applecontainer_test.py b/tests/workspace_applecontainer_test.pynew file mode 100644index 000000000..0ed716497--- /dev/null+++ b/tests/workspace_applecontainer_test.py@@ -0,0 +1,474 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+# mypy: disable-error-code="misc,no-untyped-def,attr-defined"+"""Test cases for :class:`AppleContainerWorkspace`.++Runs against a real Apple Container via the ``container`` CLI.+Requires ``container`` CLI installed and ``container system start``+running.+"""++import os+import shutil+import sys+import unittest+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import AsyncMock, patch++from agentscope.mcp import MCPClient, StdioMCPConfig+from agentscope.workspace import AppleContainerBackend, AppleContainerWorkspace+from agentscope.workspace._applecontainer._constants import (+ CONTAINER_WORKDIR,+ DEFAULT_BASE_IMAGE,+ GATEWAY_HOME,+)+from agentscope.workspace._utils import DEFAULT_GATEWAY_VENV++_CONTAINER_CLI = shutil.which("container")+_RUN_REASON = "container CLI not found — install Apple Container first"+++class TestAppleContainerWorkspaceConstruct(unittest.TestCase):+ """Constructor and config tests — no container needed.++ These tests only exercise the constructor and string formatting;+ they do not require macOS or the ``container`` CLI.+ """++ def test_default_values(self) -> None:+ """Constructor picks up all the default constants."""+ ws = AppleContainerWorkspace()+ self.assertEqual(ws.workdir, CONTAINER_WORKDIR)+ self.assertEqual(ws.base_image, DEFAULT_BASE_IMAGE)+ self.assertEqual(ws.cpus, 2)+ self.assertEqual(ws.memory, "2G")+ self.assertFalse(ws.is_alive)++ def test_custom_values(self) -> None:+ """All config knobs are forwarded."""+ ws = AppleContainerWorkspace(+ workspace_id="my-ws",+ base_image="ubuntu:latest",+ gateway_port=9999,+ cpus=4,+ memory="8G",+ env={"FOO": "bar"},+ extra_pip=["requests"],+ )+ self.assertEqual(ws.workspace_id, "my-ws")+ self.assertEqual(ws.base_image, "ubuntu:latest")+ self.assertEqual(ws.gateway_port, 9999)+ self.assertEqual(ws.cpus, 4)+ self.assertEqual(ws.memory, "8G")+ self.assertEqual(ws.env, {"FOO": "bar"})+ self.assertEqual(ws.extra_pip, ["requests"])++ def test_instructions_substitution(self) -> None:+ """System prompt contains the container workdir."""+ import asyncio++ ws = AppleContainerWorkspace()+ text = asyncio.run(ws.get_instructions())+ self.assertIn(CONTAINER_WORKDIR, text)+++class TestImageRefNormalization(unittest.TestCase):+ """Unit tests for ``_normalize_image_ref`` — no container needed."""++ def _normalize(self, ref: str) -> str:+ """Delegate to the private static method under test."""+ return AppleContainerWorkspace._normalize_image_ref(ref)++ def test_short_ref_unchanged(self) -> None:+ """Short references pass through unchanged."""+ self.assertEqual(+ self._normalize("python:3.11-slim"),+ "python:3.11-slim",+ )+ self.assertEqual(self._normalize("ubuntu:latest"), "ubuntu:latest")++ def test_canonical_library_ref(self) -> None:+ """Canonical ``docker.io/library/...`` is shortened."""+ self.assertEqual(+ self._normalize("docker.io/library/python:3.11-slim"),+ "python:3.11-slim",+ )+ self.assertEqual(+ self._normalize("docker.io/library/ubuntu:22.04"),+ "ubuntu:22.04",+ )++ def test_canonical_non_library_ref(self) -> None:+ """Non-library images keep their namespace."""+ self.assertEqual(+ self._normalize("docker.io/bitnami/redis:7.0"),+ "bitnami/redis:7.0",+ )++ def test_registry_only_stripped(self) -> None:+ """Registry is stripped even without library namespace."""+ self.assertEqual(+ self._normalize("docker.io/myorg/myimg:v1"),+ "myorg/myimg:v1",+ )++ def test_library_only_stripped(self) -> None:+ """Library prefix without registry is also stripped."""+ self.assertEqual(+ self._normalize("library/python:3.11-slim"),+ "python:3.11-slim",+ )++ def test_other_registry_preserved(self) -> None:+ """Non-docker.io registries are left intact."""+ self.assertEqual(+ self._normalize("quay.io/prometheus/node-exporter:v1"),+ "quay.io/prometheus/node-exporter:v1",+ )++ def test_tag_and_digest_handled(self) -> None:+ """Tags and digests survive normalization."""+ self.assertEqual(+ self._normalize(+ "docker.io/library/alpine@sha256:abc123...",+ ),+ "alpine@sha256:abc123...",+ )+++#: Patch target for the CLI spawn inside the workspace module.+_WS_EXEC_PATCH = (+ "agentscope.workspace._applecontainer._applecontainer_workspace."+ "asyncio.create_subprocess_exec"+)+++def _ws_proc(+ returncode: int = 0,+ stdout: bytes = b"",+ stderr: bytes = b"",+) -> AsyncMock:+ """An awaited-process mock with the given return code and output."""+ proc = AsyncMock()+ proc.returncode = returncode+ proc.communicate.return_value = (stdout, stderr)+ return proc+++class TestAppleContainerWorkspaceInternals(IsolatedAsyncioTestCase):+ """Mocked tests for CLI check and reattach parsing — no container."""++ @patch(_WS_EXEC_PATCH, new_callable=AsyncMock)+ async def test_check_cli_missing_binary_raises_runtimeerror(+ self,+ mock_exec: AsyncMock,+ ) -> None:+ """A missing ``container`` binary surfaces as ``RuntimeError``."""+ mock_exec.side_effect = FileNotFoundError("no container binary")+ ws = AppleContainerWorkspace()+ with self.assertRaises(RuntimeError) as ctx:+ await ws._check_cli()+ self.assertIn("not installed", str(ctx.exception))++ @patch(_WS_EXEC_PATCH, new_callable=AsyncMock)+ async def test_check_cli_service_down_raises_runtimeerror(+ self,+ mock_exec: AsyncMock,+ ) -> None:+ """A non-zero exit surfaces the ``container system start`` hint."""+ mock_exec.return_value = _ws_proc(1, b"", b"service down")+ ws = AppleContainerWorkspace()+ with self.assertRaises(RuntimeError) as ctx:+ await ws._check_cli()+ self.assertIn("container system start", str(ctx.exception))++ @patch(_WS_EXEC_PATCH, new_callable=AsyncMock)+ async def test_reattach_array_running_skips_start(+ self,+ mock_exec: AsyncMock,+ ) -> None:+ """Array-shaped ``inspect`` reporting running skips ``start``."""+ calls: list = []++ def _fake(*args, **_kwargs):+ calls.append(args)+ if args[1] == "inspect":+ return _ws_proc(0, b'[{"status": "running"}]')+ return _ws_proc(0)++ mock_exec.side_effect = _fake+ ws = AppleContainerWorkspace()+ await ws._start_container_if_stopped()+ spawned = [a[1] for a in calls]+ self.assertIn("inspect", spawned)+ self.assertNotIn("start", spawned)++ @patch(_WS_EXEC_PATCH, new_callable=AsyncMock)+ async def test_reattach_array_stopped_triggers_start(+ self,+ mock_exec: AsyncMock,+ ) -> None:+ """Array-shaped ``inspect`` reporting stopped triggers ``start``."""+ calls: list = []++ def _fake(*args, **_kwargs):+ calls.append(args)+ if args[1] == "inspect":+ return _ws_proc(0, b'[{"status": "stopped"}]')+ return _ws_proc(0)++ mock_exec.side_effect = _fake+ ws = AppleContainerWorkspace()+ await ws._start_container_if_stopped()+ spawned = [a[1] for a in calls]+ self.assertIn("start", spawned)++[email protected](_CONTAINER_CLI, _RUN_REASON)+ sys.platform == "darwin",+ "Apple Container requires macOS",+)+class TestAppleContainerWorkspaceLifecycle(IsolatedAsyncioTestCase):+ """Lifecycle tests against a real Apple Container."""++ async def test_initialize_and_close(self) -> None:+ """Workspace can be initialized and closed."""+ ws = AppleContainerWorkspace()+ self.assertFalse(ws.is_alive)++ async with ws:+ self.assertTrue(ws.is_alive)+ self.assertIsNotNone(ws._backend)+ self.assertIsInstance(ws._backend, AppleContainerBackend)++ self.assertFalse(ws.is_alive)++ async def test_exec_shell_inside_workspace(self) -> None:+ """Commands run inside the container via the workspace."""+ ws = AppleContainerWorkspace()+ async with ws:+ backend = ws.get_backend()+ result = await backend.exec_shell(["echo", "hello from ws"])+ self.assertTrue(result.ok())+ self.assertEqual(+ result.stdout.strip(),+ b"hello from ws",+ )++ async def test_read_write_inside_workspace(self) -> None:+ """Files can be written and read inside the workspace container."""+ ws = AppleContainerWorkspace()+ async with ws:+ backend = ws.get_backend()+ path = f"{CONTAINER_WORKDIR}/ws_test.txt"+ await backend.write_file(path, b"workspace data")+ data = await backend.read_file(path)+ self.assertEqual(data, b"workspace data")++ async def test_list_tools(self) -> None:+ """``list_tools`` returns the 6 builtin tools bound to backend."""+ ws = AppleContainerWorkspace()+ async with ws:+ tools = await ws.list_tools()+ tool_names = [t.name for t in tools]+ for name in ("Bash", "Read", "Write", "Edit", "Glob", "Grep"):+ self.assertIn(name, tool_names)++ async def test_initialize_idempotent(self) -> None:+ """Second initialize is a no-op."""+ ws = AppleContainerWorkspace()+ await ws.initialize()+ self.assertTrue(ws.is_alive)+ backend_before = ws._backend++ # Second call should be a no-op.+ await ws.initialize()+ self.assertIs(ws._backend, backend_before)++ await ws.close()+++_APPLE_CONTAINER_LIVE = os.getenv("APPLE_CONTAINER_LIVE", "")+++#: Sandbox-side path of the gateway venv Python interpreter.+_GATEWAY_PYTHON = f"{GATEWAY_HOME}/{DEFAULT_GATEWAY_VENV}/bin/python"++#: Minimal MCP echo server script (uploaded into the container on demand).+_ECHO_MCP_SERVER_SCRIPT = '''\+# -*- coding: utf-8 -*-+"""Minimal echo MCP server for live-test verification."""+from mcp.server.fastmcp import FastMCP++mcp = FastMCP("EchoServer")+++def echo(message: str) -> str:+ """Echo back the message."""+ return f"ECHO: {message}"+++if __name__ == "__main__":+ mcp.run(transport="stdio")+'''++[email protected](_APPLE_CONTAINER_LIVE, "APPLE_CONTAINER_LIVE not set")[email protected](_CONTAINER_CLI, _RUN_REASON)+ sys.platform == "darwin",+ "Apple Container requires macOS",+)+class TestAppleContainerWorkspaceLive(IsolatedAsyncioTestCase):+ """Live integration tests — full bootstrap + gateway lifecycle.++ Set ``APPLE_CONTAINER_LIVE=1`` to run. This test pulls an image,+ bootstraps the gateway venv, installs system dependencies, and+ verifies the full chain:++ 1. Bootstrap deps (ripgrep, uv) are installed and executable.+ 2. Builtin tools are bound and functional through the backend.+ 3. MCP gateway is healthy and ``list_mcps`` responds.+ 4. A real MCP echo server is registered, listed, and called.+ 5. File read/write roundtrip works inside the container.+ """++ async def test_bootstrap_dependencies(self) -> None:+ """Bootstrap installed ``rg``, ``uv``, and ``python3``."""+ ws = AppleContainerWorkspace()+ async with ws:+ backend = ws.get_backend()++ # ripgrep — installed by apt-get during bootstrap.+ result = await backend.exec_shell(["rg", "--version"])+ self.assertTrue(+ result.ok(),+ f"ripgrep not available — bootstrap may have failed: "+ f"{result.stderr.decode(errors='replace')}",+ )++ # uv — installed by the uv installer script during bootstrap.+ result = await backend.exec_shell(["uv", "--version"])+ self.assertTrue(+ result.ok(),+ f"uv not available — bootstrap may have failed: "+ f"{result.stderr.decode(errors='replace')}",+ )++ # python3 — must be present in the base image.+ result = await backend.exec_shell(+ ["python3", "--version"],+ )+ self.assertTrue(result.ok())++ async def test_builtin_tools_bound_and_callable(self) -> None:+ """All 6 builtin tools are returned by ``list_tools`` and a+ Bash call through the tool succeeds."""+ ws = AppleContainerWorkspace()+ async with ws:+ tools = await ws.list_tools()+ tool_names = {t.name for t in tools}+ for expected in ("Bash", "Read", "Write", "Edit", "Glob", "Grep"):+ self.assertIn(+ expected,+ tool_names,+ f"Builtin tool {expected!r} missing from list_tools()",+ )++ # Call Bash tool (not raw backend) — this exercises the+ # full tool binding path.+ bash = next(t for t in tools if t.name == "Bash")+ texts: list[str] = []+ async for chunk in bash.call(command="echo tool_call_ok"):+ for block in chunk.content:+ if hasattr(block, "text") and block.text:+ texts.append(block.text)+ combined = "".join(texts)+ self.assertIn("tool_call_ok", combined)++ async def test_gateway_healthy_and_mcp_list(self) -> None:+ """Gateway is healthy and ``list_mcps`` returns a list."""+ ws = AppleContainerWorkspace()+ async with ws:+ mcps = await ws.list_mcps()+ self.assertIsInstance(mcps, list)+ # After init, mcps may be empty or seeded — both are valid.++ async def test_mcp_server_register_and_call(self) -> None:+ """Register a real MCP echo server, list its tools, call one."""+ ws = AppleContainerWorkspace()+ async with ws:+ backend = ws.get_backend()++ # Write a minimal MCP echo server into the container.+ server_path = "/tmp/echo_mcp_server.py"+ await backend.write_file(+ server_path,+ _ECHO_MCP_SERVER_SCRIPT.encode("utf-8"),+ )++ # Register it through the gateway.+ echo_mcp = MCPClient(+ name="echo",+ mcp_config=StdioMCPConfig(+ command=_GATEWAY_PYTHON,+ args=[server_path],+ ),+ is_stateful=True,+ )+ await ws.add_mcp(echo_mcp)++ # Verify the MCP appears in the gateway list.+ mcps = await ws.list_mcps()+ names = [m.name for m in mcps]+ self.assertIn("echo", names, f"MCP 'echo' not in {names}")++ # Get the gateway-managed echo client and list its tools.+ echo_client = next(m for m in mcps if m.name == "echo")+ tools = await echo_client.list_raw_tools()+ tool_names = [t.name for t in tools]+ self.assertIn("echo", tool_names)++ # Call the echo tool through the gateway.+ echo_tool = await echo_client.get_tool("echo")+ result = await echo_tool(message="hello_mcp")+ texts = []+ for block in result.content:+ if hasattr(block, "text") and block.text:+ texts.append(block.text)+ combined = "".join(texts)+ self.assertIn("ECHO: hello_mcp", combined)++ async def test_file_read_write_roundtrip(self) -> None:+ """Bytes written via backend survive a read roundtrip."""+ ws = AppleContainerWorkspace()+ async with ws:+ backend = ws.get_backend()++ path = f"{CONTAINER_WORKDIR}/e2e_test.txt"+ await backend.write_file(path, b"e2e test data")+ data = await backend.read_file(path)+ self.assertEqual(data, b"e2e test data")++ # Also test via Write/Read tools.+ tools = await ws.list_tools()+ write = next(t for t in tools if t.name == "Write")+ read = next(t for t in tools if t.name == "Read")++ tool_path = f"{CONTAINER_WORKDIR}/tool_roundtrip.txt"+ chunk = await write.call(+ file_path=tool_path,+ content="tool written data",+ )+ self.assertTrue(+ len(chunk.content) > 0,+ "Write tool returned empty content",+ )++ chunk = await read.call(file_path=tool_path)+ text = "".join(+ c.text for c in chunk.content if hasattr(c, "text") and c.text+ )+ self.assertIn("tool written data", text)diff --git a/tests/workspace_manager_applecontainer_test.py b/tests/workspace_manager_applecontainer_test.pynew file mode 100644index 000000000..e9f5cd31d--- /dev/null+++ b/tests/workspace_manager_applecontainer_test.py@@ -0,0 +1,227 @@+# -*- coding: utf-8 -*-+# pylint: disable=protected-access+# mypy: disable-error-code="misc,no-untyped-def,attr-defined"+"""Test cases for :class:`AppleContainerWorkspaceManager`."""++import asyncio+from unittest.async_case import IsolatedAsyncioTestCase+from unittest.mock import patch++from agentscope.app.workspace_manager import (+ AppleContainerWorkspaceManager,+ IsolationPolicy,+)+++class _FakeWorkspace:+ """Workspace double used by manager tests."""++ created: list["_FakeWorkspace"] = []++ def __init__(self, **kwargs: object) -> None:+ self.kwargs = kwargs+ self.workspace_id = str(kwargs.get("workspace_id") or "new-id")+ self.initialized = False+ self.closed = False+ _FakeWorkspace.created.append(self)++ async def initialize(self) -> None:+ """Mark initialized."""+ await asyncio.sleep(0)+ self.initialized = True++ async def close(self) -> None:+ """Mark closed."""+ self.closed = True+++class TestAppleContainerWorkspaceManager(IsolatedAsyncioTestCase):+ """Manager cache, config forwarding and TTL behavior.++ Uses ``_FakeWorkspace`` so no real container is needed; these tests+ can run on any platform.+ """++ async def asyncSetUp(self) -> None:+ """Patch the workspace class used by the manager."""+ _FakeWorkspace.created.clear()+ self.workspace_patch = patch(+ "agentscope.app.workspace_manager."+ "_applecontainer_workspace_manager.AppleContainerWorkspace",+ _FakeWorkspace,+ )+ self.workspace_patch.start()++ async def asyncTearDown(self) -> None:+ """Undo patches."""+ self.workspace_patch.stop()++ async def test_default_config(self) -> None:+ """Manager picks up default constants when none are given."""+ manager = AppleContainerWorkspaceManager()+ self.assertEqual(manager._base_image, "python:3.11-slim")+ self.assertEqual(manager._cpus, 2)+ self.assertEqual(manager._memory, "2G")+ self.assertEqual(manager._gateway_port, 5600)+ self.assertEqual(manager._isolation, IsolationPolicy.PER_AGENT)++ async def test_custom_config(self) -> None:+ """All config knobs are forwarded to new workspaces."""+ manager = AppleContainerWorkspaceManager(+ base_image="ubuntu:latest",+ cpus=4,+ memory="8G",+ gateway_port=9999,+ isolation=IsolationPolicy.PER_SESSION,+ )++ ws = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )+ self.assertEqual(ws.kwargs["base_image"], "ubuntu:latest")+ self.assertEqual(ws.kwargs["cpus"], 4)+ self.assertEqual(ws.kwargs["memory"], "8G")+ self.assertEqual(ws.kwargs["gateway_port"], 9999)++ async def test_get_workspace_caches(self) -> None:+ """Same workspace_id returns the cached instance."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ )++ ws1 = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="fixed-id",+ )+ ws2 = await manager.get_workspace(+ user_id="u2",+ agent_id="a2",+ session_id="s2",+ workspace_id="fixed-id",+ )+ self.assertIs(ws1, ws2)+ self.assertEqual(+ len(_FakeWorkspace.created),+ 1,+ "Only one workspace should be created on cache hit",+ )++ async def test_close_evicts(self) -> None:+ """close() pops the workspace from cache and calls its close."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ )+ ws = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="fixed-id",+ )+ self.assertTrue(ws.initialized) # type: ignore[attr-defined]++ await manager.close("fixed-id")+ self.assertTrue(ws.closed) # type: ignore[attr-defined]+ # Subsequent get_workspace with same id creates a new one.+ ws2 = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="fixed-id",+ )+ self.assertIsNot(ws, ws2)++ async def test_close_all(self) -> None:+ """close_all shuts down every cached workspace."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ )+ ws1 = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="id-1",+ )+ ws2 = await manager.get_workspace(+ user_id="u2",+ agent_id="a2",+ session_id="s2",+ workspace_id="id-2",+ )+ await manager.close_all()+ self.assertTrue(ws1.closed) # type: ignore[attr-defined]+ self.assertTrue(ws2.closed) # type: ignore[attr-defined]++ async def test_sweeper_evicts_expired(self) -> None:+ """Background sweeper closes and evicts idle workspaces."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ ttl=0.01, # expire almost immediately+ sweep_interval=0.01,+ )+ async with manager:+ ws = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="sweep-id",+ )+ # Allow the sweeper to fire.+ await asyncio.sleep(0.1)+ # Next get should create a new workspace since the old one+ # expired.+ ws2 = await manager.get_workspace(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ workspace_id="sweep-id",+ )+ self.assertIsNot(ws, ws2)+ self.assertTrue(ws.closed) # type: ignore[attr-defined]++ async def test_assign_workspace_id_per_agent(self) -> None:+ """PER_AGENT policy returns deterministic ids."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_AGENT,+ )+ id1 = manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )+ id2 = manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s2",+ )+ # Same user+agent, different session → same id.+ self.assertEqual(id1, id2)++ id3 = manager.assign_workspace_id(+ user_id="u1",+ agent_id="a2",+ session_id="s1",+ )+ # Different agent → different id.+ self.assertNotEqual(id1, id3)++ async def test_assign_workspace_id_per_session(self) -> None:+ """PER_SESSION policy returns unique ids."""+ manager = AppleContainerWorkspaceManager(+ isolation=IsolationPolicy.PER_SESSION,+ )+ id1 = manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s1",+ )+ id2 = manager.assign_workspace_id(+ user_id="u1",+ agent_id="a1",+ session_id="s2",+ )+ # Different session → different id.+ self.assertNotEqual(id1, id2)