Skip to content

Build and run agents you can see, understand and trust.

feat(workspace): add OpenSandbox-based backend, workspace and manager (#1953)

llumanman15b5243ef3c2
diff --git a/README.md b/README.md
index f49f170c9..70c0521c2 100644
--- a/README.md
+++ b/README.md
@@ -62,7 +62,7 @@ AgentScope 2.0 is a production-ready, easy-to-use agent framework with essential
- [**Event System** →](https://docs.agentscope.io/latest/en/building-blocks/message-and-event) A unified event bus to the frontend and human-in-the-loop support.
- [**Permission System** →](https://docs.agentscope.io/latest/en/building-blocks/permission-system) Fine-grained, configurable control over tools and resources.
- [**Multi-tenancy & Multi-session Service** →](https://docs.agentscope.io/latest/en/deploy/agent-service) Production-grade serving with isolation across tenants and sessions.
-- [**Workspace / Sandbox Support** →](https://docs.agentscope.io/latest/en/building-blocks/workspace) Run tools and code in isolated environments, with built-in backends for local, Docker, and E2B.
+- [**Workspace / Sandbox Support** →](https://docs.agentscope.io/latest/en/building-blocks/workspace) Run tools and code in isolated environments, with built-in backends for local, Docker, E2B, and OpenSandbox.
- [**Extensible Middleware System** →](https://docs.agentscope.io/latest/en/building-blocks/middleware) Composable hooks to customize and extend the agent's reasoning-acting loop.
We design for increasingly agentic LLMs.
diff --git a/README_zh.md b/README_zh.md
index e310fd270..766e51464 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -62,7 +62,7 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
- [**事件系统** →](https://docs.agentscope.io/latest/zh/building-blocks/message-and-event) 统一的事件总线,服务于前端智能体应用与 human-in-the-loop 协作。
- [**权限系统** →](https://docs.agentscope.io/latest/zh/building-blocks/permission-system) 对工具和资源进行细粒度、可配置的控制。
- [**多租户与多会话服务** →](https://docs.agentscope.io/latest/zh/deploy/agent-service) 提供生产级服务,在租户与会话之间实现隔离。
-- [**工作区 / 沙箱支持** →](https://docs.agentscope.io/latest/zh/building-blocks/workspace) 在隔离环境中运行工具和代码,内置支持本地文件系统、Docker 和 E2B 后端。
+- [**工作区 / 沙箱支持** →](https://docs.agentscope.io/latest/zh/building-blocks/workspace) 在隔离环境中运行工具和代码,内置支持本地文件系统、Docker、E2B 和 OpenSandbox 后端。
- [**可扩展中间件系统** →](https://docs.agentscope.io/latest/zh/building-blocks/middleware) 可组合的钩子系统,用于自定义和扩展智能体的推理-行动循环。
我们为日益自主的大语言模型而设计。
diff --git a/docs/NEWS.md b/docs/NEWS.md
index 27c3ff582..fb723153a 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,7 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
-- **[2026-07] `INTE`:** K8s-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
+- **[2026-07] `INTE`:** K8s, OpenSandbox-based workspace/sandbox supported. [Docs](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `INTE`:** ReMe long-term memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Agentic Memory supported. [Example](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [Docs](https://docs.agentscope.io/latest/en/building-blocks/long-term-memory)
- **[2026-06] `FEAT`:** Distributed & Multi-Tenancy & Multi-Session RAG service supported. [Docs](https://docs.agentscope.io/latest/en/deploy/agent-team)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index ed4050587..8ad67dcd5 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,7 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
-- **[2026-07] `集成`:** 集成 K8s 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
+- **[2026-07] `集成`:** 集成 K8s,OpenSandbox 工作区/沙箱实现。 [文档](https://docs.agentscope.io/latest/en/building-blocks/workspace)
- **[2026-07] `集成`:** 集成 ReMe 长期记忆。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/reme) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持 Agentic Memory。 [样例](https://github.com/agentscope-ai/agentscope/tree/main/examples/long_term_memory/agentic_memory) | [文档](https://docs.agentscope.io/latest/zh/building-blocks/long-term-memory)
- **[2026-06] `功能`:** 支持分布式 & 多租户 & 多会话 RAG 服务。 [文档](https://docs.agentscope.io/latest/en/deploy/agent-team)
diff --git a/pyproject.toml b/pyproject.toml
index ffd601aec..6f03f8222 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -73,6 +73,7 @@ workspace = [
"aiodocker",
"e2b",
"agentscope[k8s]",
+ "opensandbox",
]
# ------------ Tools ------------
tools = [
diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.py
index f46430059..dcd6befcc 100644
--- a/src/agentscope/app/workspace_manager/__init__.py
+++ b/src/agentscope/app/workspace_manager/__init__.py
@@ -7,6 +7,7 @@ from ._local_workspace_manager import LocalWorkspaceManager
from ._docker_workspace_manager import DockerWorkspaceManager
from ._e2b_workspace_manager import E2BWorkspaceManager
from ._k8s_workspace_manager import K8sWorkspaceManager
+from ._opensandbox_workspace_manager import OpenSandboxWorkspaceManager
__all__ = [
"IsolationPolicy",
@@ -15,4 +16,5 @@ __all__ = [
"DockerWorkspaceManager",
"E2BWorkspaceManager",
"K8sWorkspaceManager",
+ "OpenSandboxWorkspaceManager",
]
diff --git a/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py b/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py
new file mode 100644
index 000000000..c9fd286ca
--- /dev/null
+++ b/src/agentscope/app/workspace_manager/_opensandbox_workspace_manager.py
@@ -0,0 +1,356 @@
+# -*- coding: utf-8 -*-
+"""OpenSandboxWorkspaceManager -- lifecycle manager for OpenSandbox.
+
+Mirrors :class:`DockerWorkspaceManager` and :class:`E2BWorkspaceManager`
+in its public surface (``get_workspace`` / ``close`` / ``close_all``) so
+callers do not branch on backend.
+
+Differences from the Docker manager:
+
+* No ``basedir`` / host workdir layout: OpenSandbox sandboxes carry
+ their own filesystem state across pause/resume, so there is nothing
+ to bind-mount on the host.
+* No image build step: the manager passes an image name plus runtime
+ bootstrap options to :class:`OpenSandboxWorkspace`.
+* Reattachment uses OpenSandbox sandbox metadata. The workspace writes
+ ``agentscope.workspace.id`` at create time and looks it up via
+ ``SandboxManager.list_sandbox_infos`` inside
+ :meth:`OpenSandboxWorkspace.initialize`. The manager itself stays
+ metadata-blind and just forwards ``workspace_id``.
+* ``user_id`` / ``agent_id`` are surfaced as extra sandbox metadata so
+ operators can filter sandboxes in OpenSandbox. They do not
+ participate in cache key resolution; the cache is keyed strictly by
+ ``workspace_id``.
+* Idle workspaces are evicted by a background sweeper task started in
+ :meth:`__aenter__` and cancelled in :meth:`__aexit__`.
+* ``close_all`` fans calls out with :func:`asyncio.gather` because
+ ``sandbox.pause()`` is a remote round-trip per sandbox.
+"""
+
+import asyncio
+import time
+from typing import Any, Literal, Self
+
+from ..._logging import logger
+from ...mcp import MCPClient
+from ...workspace._opensandbox._constants import (
+ DEFAULT_GATEWAY_PORT,
+ DEFAULT_IMAGE,
+ DEFAULT_REQUEST_TIMEOUT,
+ DEFAULT_TIMEOUT,
+)
+from ...workspace import OpenSandboxWorkspace
+
+from ._base import IsolationPolicy, WorkspaceManagerBase
+
+DEFAULT_SWEEP_INTERVAL = 300.0
+
+
+class OpenSandboxWorkspaceManager(WorkspaceManagerBase):
+ """Manages OpenSandbox workspaces with TTL-based caching.
+
+ 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,
+ image: str = DEFAULT_IMAGE,
+ api_key: str = "",
+ domain: str = "",
+ protocol: Literal["http", "https"] = "http",
+ request_timeout_seconds: float | None = DEFAULT_REQUEST_TIMEOUT,
+ timeout_seconds: int = DEFAULT_TIMEOUT,
+ gateway_port: int = DEFAULT_GATEWAY_PORT,
+ env: dict[str, str] | None = None,
+ sandbox_metadata: dict[str, str] | None = None,
+ resource: dict[str, str] | None = None,
+ entrypoint: list[str] | None = None,
+ network_policy: Any | 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 OpenSandbox workspace manager.
+
+ Args:
+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):
+ Isolation grain for :meth:`assign_workspace_id`, used
+ when :meth:`get_workspace` is called without an explicit
+ ``workspace_id``.
+ image (`str`, defaults to `DEFAULT_IMAGE`):
+ OpenSandbox image passed to every workspace this manager
+ produces.
+ api_key (`str`, defaults to `""`):
+ OpenSandbox API key. ``""`` lets the SDK fall back to
+ its environment-based configuration.
+ domain (`str`, defaults to `""`):
+ Optional OpenSandbox domain, for local or self-hosted
+ deployments.
+ protocol (`str`, defaults to `"http"`):
+ Scheme used when OpenSandbox returns endpoint values as
+ ``host:port`` without a protocol.
+ request_timeout_seconds (`float | None`, optional):
+ HTTP request timeout forwarded through
+ ``ConnectionConfig``. Defaults to 600 seconds so the
+ SDK HTTP streaming layer is not shorter than bootstrap
+ command timeout.
+ timeout_seconds (`int`, defaults to `DEFAULT_TIMEOUT`):
+ Sandbox keep-alive / resume timeout.
+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):
+ TCP port the in-sandbox gateway listens on.
+ env (`dict[str, str] | None`, optional):
+ Environment variables applied when creating a sandbox.
+ sandbox_metadata (`dict[str, str] | None`, optional):
+ Extra metadata merged with the per-workspace
+ ``agentscope.workspace.id`` / ``agentscope.user.id`` /
+ ``agentscope.agent.id`` keys.
+ resource (`dict[str, str] | None`, optional):
+ Resource limits forwarded to OpenSandbox create.
+ entrypoint (`list[str] | None`, optional):
+ Optional sandbox entrypoint forwarded to OpenSandbox
+ create.
+ network_policy (`Any | None`, optional):
+ Creation-time OpenSandbox network policy. Runtime egress
+ patching is intentionally left for a follow-up.
+ 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. On
+ reattach, the sandbox's persisted ``.mcp`` file wins.
+ 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 sandbox paused.
+ sweep_interval (`float`, defaults to `DEFAULT_SWEEP_INTERVAL`):
+ How often the background sweeper wakes up to look for
+ idle workspaces.
+ """
+ self._image = image
+ self._api_key = api_key
+ self._domain = domain
+ self._protocol = protocol
+ self._request_timeout_seconds = request_timeout_seconds
+ self._timeout_seconds = timeout_seconds
+ self._gateway_port = gateway_port
+ self._env = dict(env or {})
+ self._sandbox_metadata = dict(sandbox_metadata or {})
+ self._resource = dict(resource or {})
+ self._entrypoint = list(entrypoint or [])
+ self._network_policy = network_policy
+ 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)
+
+ # workspace_id -> (workspace, last_access_monotonic)
+ self._cache: dict[str, tuple[OpenSandboxWorkspace, float]] = {}
+ self._lock = asyncio.Lock()
+ self._sweep_task: asyncio.Task | None = None
+
+ async def _build_and_start(
+ self,
+ *,
+ workspace_id: str,
+ user_id: str,
+ agent_id: str,
+ ) -> OpenSandboxWorkspace:
+ """Construct an OpenSandbox workspace and run full initialize.
+
+ ``workspace_id`` is always concrete here — :meth:`get_workspace`
+ resolves ``None`` via :meth:`assign_workspace_id` before calling
+ — and is forwarded so metadata-based reattachment works on the
+ next cache miss.
+ """
+ ws = OpenSandboxWorkspace(
+ workspace_id=workspace_id,
+ image=self._image,
+ api_key=self._api_key,
+ domain=self._domain,
+ protocol=self._protocol,
+ request_timeout_seconds=self._request_timeout_seconds,
+ timeout_seconds=self._timeout_seconds,
+ gateway_port=self._gateway_port,
+ env=self._env,
+ sandbox_metadata={
+ "agentscope.user.id": user_id,
+ "agentscope.agent.id": agent_id,
+ **self._sandbox_metadata,
+ },
+ resource=self._resource,
+ entrypoint=self._entrypoint,
+ network_policy=self._network_policy,
+ 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,
+ ) -> OpenSandboxWorkspace:
+ """Return an initialized workspace, reattaching on cache miss.
+
+ On miss, the manager constructs ``OpenSandboxWorkspace`` with
+ the requested ``workspace_id`` and relies on its ``initialize``
+ method to find an existing sandbox by metadata, connect or
+ resume it depending on state, or create a fresh sandbox
+ otherwise.
+
+ Idle eviction is not performed here; the background sweeper
+ started by :meth:`__aenter__` handles that.
+
+ Args:
+ user_id (`str`):
+ Owning user identifier (forwarded as sandbox metadata
+ only — not part of the cache key).
+ agent_id (`str`):
+ Agent identifier (forwarded as sandbox metadata only —
+ not part of the cache key).
+ session_id (`str`):
+ Session identifier (unused; sandboxes are per-workspace,
+ sessions partition under ``sessions/<session_id>/``).
+ workspace_id (`str | None`, optional):
+ Stable workspace identifier — the cache key and the
+ value stored in the sandbox's ``agentscope.workspace.id``
+ metadata. When ``None`` the manager falls back to
+ :meth:`assign_workspace_id` under its isolation policy.
+
+ Returns:
+ `OpenSandboxWorkspace`:
+ A live, initialized 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 to prevent two concurrent
+ # get_workspace(workspace_id=X) calls from creating two
+ # workspaces (and thus two sandboxes) for the same 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
+
+ async def close(self, workspace_id: str) -> None:
+ """Close (= pause the sandbox) 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.
+
+ ``sandbox.pause()`` is a remote round-trip per sandbox; doing
+ it sequentially on shutdown would produce unnecessary latency.
+ """
+ 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 TTL sweeper task, then close all 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 close idle workspaces.
+
+ Runs until cancelled. Each tick pops expired entries and closes
+ them outside the lock; failures are logged and swallowed so one
+ bad sandbox does not poison the sweeper.
+ """
+ while True:
+ try:
+ await asyncio.sleep(self._sweep_interval)
+ except asyncio.CancelledError:
+ return
+ try:
+ await self._sweep_once()
+ except Exception:
+ logger.exception("OpenSandbox 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: OpenSandboxWorkspace) -> None:
+ """Close a workspace, logging failures instead of raising."""
+ try:
+ await ws.close()
+ except Exception:
+ logger.exception(
+ "Failed to close OpenSandboxWorkspace %s",
+ ws.workspace_id,
+ )
diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.py
index a3cdd459e..2aa043cac 100644
--- a/src/agentscope/workspace/__init__.py
+++ b/src/agentscope/workspace/__init__.py
@@ -8,6 +8,7 @@ from ._offload_protocol import Offloader
from ._docker import DockerBackend, DockerWorkspace
from ._e2b import E2BWorkspace, E2BBackend
from ._k8s import K8sBackend, K8sWorkspace
+from ._opensandbox import OpenSandboxBackend, OpenSandboxWorkspace
__all__ = [
@@ -20,4 +21,6 @@ __all__ = [
"K8sBackend",
"K8sWorkspace",
"Offloader",
+ "OpenSandboxBackend",
+ "OpenSandboxWorkspace",
]
diff --git a/src/agentscope/workspace/_base.py b/src/agentscope/workspace/_base.py
index 991f93ba1..cb90f55ca 100644
--- a/src/agentscope/workspace/_base.py
+++ b/src/agentscope/workspace/_base.py
@@ -13,6 +13,8 @@ Three concrete implementations:
- :class:`agentscope.workspace.LocalWorkspace` — local filesystem.
- :class:`agentscope.workspace.DockerWorkspace` — Docker container.
- :class:`agentscope.workspace.E2BWorkspace` — E2B cloud sandbox.
+- :class:`agentscope.workspace.OpenSandboxWorkspace` — OpenSandbox
+ remote sandbox.
Consumers:
diff --git a/src/agentscope/workspace/_docker/_docker_workspace.py b/src/agentscope/workspace/_docker/_docker_workspace.py
index 36a5c7061..e28efa63d 100644
--- a/src/agentscope/workspace/_docker/_docker_workspace.py
+++ b/src/agentscope/workspace/_docker/_docker_workspace.py
@@ -47,9 +47,6 @@ Layout:
├── skills/ # reusable skills
└── sessions/ # session context and tool results
```
-
-Use the MCP-provided tools to interact with the container's filesystem
-and processes.
</workspace>"""
diff --git a/src/agentscope/workspace/_e2b/_e2b_workspace.py b/src/agentscope/workspace/_e2b/_e2b_workspace.py
index 530b7a3e7..f08dcc6e1 100644
--- a/src/agentscope/workspace/_e2b/_e2b_workspace.py
+++ b/src/agentscope/workspace/_e2b/_e2b_workspace.py
@@ -67,9 +67,6 @@ Layout:
├── skills/ # reusable skills
└── sessions/ # session context and tool results
```
-
-Use the MCP-provided tools to interact with the sandbox's filesystem
-and processes.
</workspace>"""
diff --git a/src/agentscope/workspace/_k8s/_k8s_workspace.py b/src/agentscope/workspace/_k8s/_k8s_workspace.py
index 443b5c5c4..61054b4ac 100644
--- a/src/agentscope/workspace/_k8s/_k8s_workspace.py
+++ b/src/agentscope/workspace/_k8s/_k8s_workspace.py
@@ -56,9 +56,6 @@ Layout:
├── skills/ # reusable skills
└── sessions/ # session context and tool results
```
-
-Use the MCP-provided tools to interact with the Pod's filesystem
-and processes.
</workspace>"""
diff --git a/src/agentscope/workspace/_opensandbox/__init__.py b/src/agentscope/workspace/_opensandbox/__init__.py
new file mode 100644
index 000000000..5ed9e0dd5
--- /dev/null
+++ b/src/agentscope/workspace/_opensandbox/__init__.py
@@ -0,0 +1,12 @@
+# -*- coding: utf-8 -*-
+"""OpenSandbox-backed workspace.
+
+OpenSandbox support follows the E2B remote-sandbox model: one sandbox
+per workspace id, filesystem persistence inside the sandbox, and MCPs
+reached through the in-sandbox gateway.
+"""
+
+from ._opensandbox_backend import OpenSandboxBackend
+from ._opensandbox_workspace import OpenSandboxWorkspace
+
+__all__ = ["OpenSandboxWorkspace", "OpenSandboxBackend"]
diff --git a/src/agentscope/workspace/_opensandbox/_constants.py b/src/agentscope/workspace/_opensandbox/_constants.py
new file mode 100644
index 000000000..5f5f1b213
--- /dev/null
+++ b/src/agentscope/workspace/_opensandbox/_constants.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+"""Constants for :class:`OpenSandboxWorkspace`, mirroring the E2B and
+K8s ``_constants`` modules.
+
+Only defaults that cannot be derived on the base class live here:
+image, timeouts, gateway port, sandbox metadata key, plus the two
+sandbox-side anchors the workspace must set (``SANDBOX_WORKDIR`` and
+``GATEWAY_HOME``). The bootstrap command sequence and every derived
+path (venv, python, script, glob helper, log) live on the workspace /
+base class, not here.
+"""
+
+#: Default OpenSandbox image. The slim Python image is small but still
+#: has enough package-manager support for installing curl, certificates,
+#: ripgrep, and procps during bootstrap.
+DEFAULT_IMAGE = "python:3.11-slim"
+
+#: Default keep-alive timeout in seconds for newly-created sandboxes.
+DEFAULT_TIMEOUT = 300
+
+#: Per-command timeout for first-time bootstrap shell commands.
+BOOTSTRAP_COMMAND_TIMEOUT = 600.0
+
+#: Default OpenSandbox SDK HTTP timeout in seconds. Bootstrap commands
+#: can legitimately stream for several minutes, so this must not be
+#: shorter than :data:`BOOTSTRAP_COMMAND_TIMEOUT`.
+DEFAULT_REQUEST_TIMEOUT = BOOTSTRAP_COMMAND_TIMEOUT
+
+#: Default port the in-sandbox gateway listens on.
+DEFAULT_GATEWAY_PORT = 5600
+
+# Workspace-side persistent layout. OpenSandbox's default Docker
+# runtime runs the image as root, so the workspace itself can live at a
+# short root-owned path. The data/skills/sessions subdirectories are
+# created by the base class from ``workdir``.
+SANDBOX_WORKDIR = "/workspace"
+
+# Gateway home — the single sandbox-side anchor the workspace must set.
+# The venv, entry script, glob helper, and log paths are all derived
+# from it by the base class.
+GATEWAY_HOME = "/root/.agentscope"
+
+#: Sandbox metadata key used to map workspace_id to sandbox id. The
+#: workspace filters ``list_sandbox_infos`` by this key on cache miss to
+#: locate and resume an existing sandbox.
+METADATA_WORKSPACE_ID_KEY = "agentscope.workspace.id"
diff --git a/src/agentscope/workspace/_opensandbox/_opensandbox_backend.py b/src/agentscope/workspace/_opensandbox/_opensandbox_backend.py
new file mode 100644
index 000000000..fb3f6bed1
--- /dev/null
+++ b/src/agentscope/workspace/_opensandbox/_opensandbox_backend.py
@@ -0,0 +1,277 @@
+# -*- coding: utf-8 -*-
+"""OpenSandbox :class:`BackendBase` implementation.
+
+Wraps the OpenSandbox SDK's ``commands.run`` and ``files.*`` APIs into
+the three backend primitives (``exec_shell``, ``read_file``,
+``write_file``) so builtin tools can operate inside an OpenSandbox
+sandbox 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 posixpath
+import shlex
+from datetime import timedelta
+from typing import TYPE_CHECKING, Any
+
+from ...tool import BackendBase, ExecResult
+
+if TYPE_CHECKING:
+ from opensandbox.sandbox import Sandbox
+
+
+class _WriteEntry:
+ """Small SDK-compatible write entry used when the SDK type is absent."""
+
+ def __init__(self, path: str, data: bytes, mode: int) -> None:
+ self.path = path
+ self.data = data
+ self.mode = mode
+
+
+class OpenSandboxBackend(BackendBase):
+ """Backend that delegates to a running OpenSandbox sandbox.
+
+ Only the three abstract primitives (``exec_shell``, ``read_file``,
+ ``write_file``) are implemented here; the derived filesystem
+ helpers are inherited from :class:`BackendBase`.
+
+ Args:
+ sandbox (`Sandbox`):
+ A started / connected ``opensandbox.sandbox.Sandbox`` object.
+ workdir (`str`):
+ Default working directory for ``exec_shell`` calls inside the
+ sandbox.
+ """
+
+ def __init__(self, sandbox: "Sandbox", workdir: str) -> None:
+ """Initialize the OpenSandbox backend.
+
+ Args:
+ sandbox (`Sandbox`):
+ A started / connected ``opensandbox.sandbox.Sandbox``
+ object.
+ workdir (`str`):
+ Default working directory for ``exec_shell`` calls inside
+ the sandbox.
+ """
+ self._sandbox = sandbox
+ self._workdir = workdir
+
+ # ---- exec ---------------------------------------------------------
+
+ async def exec_shell(
+ self,
+ command: list[str],
+ *,
+ cwd: str | None = None,
+ timeout: float | None = None,
+ ) -> ExecResult:
+ """Run a program inside the sandbox via ``commands.run``.
+
+ *command* is an argv list. The OpenSandbox ``commands.run`` API
+ expects a single shell command line, so the argv is POSIX-quoted
+ back into a string before dispatch. Callers needing shell
+ features should pass ``["sh", "-c", line]``.
+
+ Args:
+ command (`list[str]`):
+ Executable path/name followed by its arguments.
+ cwd (`str | None`, optional):
+ Working directory inside the sandbox. When ``None`` the
+ backend's default ``workdir`` is used.
+ timeout (`float | None`, optional):
+ Maximum number of seconds to wait. When ``None`` the SDK
+ default applies.
+
+ Returns:
+ `ExecResult`:
+ The captured exit code, stdout, and stderr. A non-zero
+ command exit is returned as a normal result; transport
+ errors yield an ``exit_code`` of ``-1``.
+ """
+ command_line = " ".join(shlex.quote(arg) for arg in command)
+ opts = self._make_run_opts(cwd=cwd or self._workdir, timeout=timeout)
+ try:
+ res = await self._sandbox.commands.run(command_line, opts=opts)
+ return ExecResult(
+ exit_code=int(getattr(res, "exit_code", 0) or 0),
+ stdout=self._execution_stream_bytes(res, "stdout"),
+ stderr=self._execution_stream_bytes(res, "stderr"),
+ )
+ except Exception as e: # noqa: BLE001
+ return ExecResult(
+ exit_code=-1,
+ stdout=b"",
+ stderr=str(e).encode("utf-8"),
+ )
+
+ # ---- file I/O -----------------------------------------------------
+
+ async def read_file(self, path: str) -> bytes:
+ """Read a file from the sandbox via ``files.read_bytes``.
+
+ Args:
+ path (`str`):
+ Path to the file inside the sandbox.
+
+ Returns:
+ `bytes`:
+ The raw file contents.
+
+ Raises:
+ `FileNotFoundError`:
+ If the path does not exist inside the sandbox.
+ """
+ try:
+ data = await self._sandbox.files.read_bytes(path)
+ except FileNotFoundError:
+ raise
+ except Exception as exc: # noqa: BLE001
+ # OpenSandbox surfaces missing files through the HTTP
+ # transport today (httpx.HTTPStatusError with a 404
+ # response). Keep a message fallback for SDK wrappers that
+ # do not expose the response object.
+ if self._is_not_found_error(exc):
+ raise FileNotFoundError(
+ f"not found in OpenSandbox sandbox: {path}",
+ ) from exc
+ raise
+ return data
+
+ async def write_file(self, path: str, data: bytes) -> None:
+ """Write raw bytes to a file inside the sandbox.
+
+ Creates parent directories via ``exec_shell`` first.
+
+ Args:
+ path (`str`):
+ Destination path inside the sandbox.
+ data (`bytes`):
+ The raw bytes to write.
+ """
+ parent = posixpath.dirname(path)
+ if parent:
+ await self.exec_shell(["mkdir", "-p", parent])
+
+ entry = self._make_write_entry(path, data)
+ await self._sandbox.files.write_files([entry])
+
+ @staticmethod
+ def _make_write_entry(path: str, data: bytes) -> Any:
+ """Build a binary-safe OpenSandbox write entry.
+
+ The implementation prefers the real
+ ``opensandbox.models.filesystem.WriteEntry`` type
+ when available, but falls back to a tiny local adapter to avoid
+ hard dependency on the SDK during tests.
+
+ Args:
+ path (`str`):
+ Destination path inside the sandbox.
+ data (`bytes`):
+ Raw bytes to write.
+
+ Returns:
+ `Any`:
+ A write entry object suitable for ``files.write_files``.
+ """
+ try:
+ from opensandbox.models.filesystem import WriteEntry
+
+ return WriteEntry(path=path, data=data, mode=0o644)
+ except Exception: # noqa: BLE001
+ return _WriteEntry(path=path, data=data, mode=0o644)
+
+ @staticmethod
+ def _make_run_opts(cwd: str, timeout: float | None) -> Any:
+ """Build SDK command options, falling back to a test adapter."""
+ try:
+ from opensandbox.models.execd import RunCommandOpts
+
+ return RunCommandOpts(
+ working_directory=cwd,
+ timeout=(
+ timedelta(seconds=timeout) if timeout is not None else None
+ ),
+ )
+ except Exception: # noqa: BLE001
+ return type(
+ "RunCommandOpts",
+ (),
+ {
+ "working_directory": cwd,
+ "timeout": (
+ timedelta(seconds=timeout)
+ if timeout is not None
+ else None
+ ),
+ },
+ )()
+
+ @classmethod
+ def _is_not_found_error(cls, exc: BaseException) -> bool:
+ """Return whether an SDK/transport exception means HTTP 404."""
+ if cls._status_code(exc) == 404:
+ return True
+
+ for chained in (exc.__cause__, exc.__context__):
+ if chained is not None and chained is not exc:
+ if cls._is_not_found_error(chained):
+ return True
+
+ return "not found" in str(exc).lower()
+
+ @staticmethod
+ def _status_code(exc: BaseException) -> int | None:
+ """Extract a response/status code from common SDK error shapes."""
+ response = getattr(exc, "response", None)
+ status_code = getattr(response, "status_code", None)
+ if status_code is None:
+ status_code = getattr(exc, "status_code", None)
+ if status_code is None:
+ return None
+ try:
+ return int(status_code)
+ except (TypeError, ValueError):
+ return None
+
+ @staticmethod
+ def _execution_stream_bytes(res: Any, stream: str) -> bytes:
+ """Extract stdout/stderr bytes from real or test execution shapes.
+
+ The real SDK returns an ``Execution`` with accumulated
+ ``logs.stdout`` / ``logs.stderr`` entries. Some unit tests use a
+ simpler direct ``stdout`` / ``stderr`` shape to mirror E2B-style
+ command results, so this helper normalizes both.
+ """
+ direct = getattr(res, stream, None)
+ if direct is not None:
+ if isinstance(direct, bytes):
+ return direct
+ return str(direct).encode("utf-8")
+
+ logs = getattr(res, "logs", None)
+ messages = getattr(logs, stream, []) if logs is not None else []
+ parts = [str(getattr(msg, "text", msg) or "") for msg in messages]
+ text = ""
+ for part in parts:
+ if text and part:
+ previous_is_tight = (
+ not text.endswith(
+ ("\n", "\r"),
+ )
+ and not text[-1].isspace()
+ )
+ next_is_tight = (
+ not part.startswith(
+ ("\n", "\r"),
+ )
+ and not part[0].isspace()
+ )
+ if previous_is_tight and next_is_tight:
+ text += "\n"
+ text += part
+ return text.encode("utf-8")
diff --git a/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py b/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py
new file mode 100644
index 000000000..fbb5e0622
--- /dev/null
+++ b/src/agentscope/workspace/_opensandbox/_opensandbox_workspace.py
@@ -0,0 +1,403 @@
+# -*- coding: utf-8 -*-
+"""OpenSandboxWorkspace -- sandboxed workspace backed by OpenSandbox."""
+
+from __future__ import annotations
+
+import asyncio
+from datetime import timedelta
+import shlex
+from typing import TYPE_CHECKING, Literal
+
+from ..._logging import logger
+from ...mcp import MCPClient
+from .._sandboxed_base import SandboxedWorkspaceBase
+from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from ._constants import (
+ DEFAULT_GATEWAY_PORT,
+ DEFAULT_IMAGE,
+ BOOTSTRAP_COMMAND_TIMEOUT,
+ DEFAULT_REQUEST_TIMEOUT,
+ DEFAULT_TIMEOUT,
+ GATEWAY_HOME,
+ METADATA_WORKSPACE_ID_KEY,
+ SANDBOX_WORKDIR,
+)
+from ._opensandbox_backend import OpenSandboxBackend
+
+if TYPE_CHECKING:
+ from opensandbox import Sandbox
+ from opensandbox.config.connection import ConnectionConfig
+ from opensandbox.models.sandboxes import (
+ NetworkPolicy,
+ SandboxInfo,
+ )
+
+
+_DEFAULT_INSTRUCTIONS = """<workspace>
+You have an OpenSandbox-based 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 OpenSandboxWorkspace(SandboxedWorkspaceBase):
+ """Workspace backed by an OpenSandbox sandbox.
+
+ ``default_mcps`` and ``skill_paths`` are seed-time inputs and are
+ not retained as instance state past :meth:`initialize`.
+ """
+
+ _gateway_home = GATEWAY_HOME
+ # The slim base image streams apt-get + uv + pip for several
+ # minutes on first bootstrap, so cap each bootstrap command at the
+ # same budget the SDK HTTP layer is configured for.
+ _bootstrap_cmd_timeout = BOOTSTRAP_COMMAND_TIMEOUT
+
+ def __init__(
+ self,
+ *,
+ workspace_id: str | None = None,
+ image: str = DEFAULT_IMAGE,
+ api_key: str = "",
+ domain: str = "",
+ protocol: Literal["http", "https"] = "http",
+ request_timeout_seconds: float | None = DEFAULT_REQUEST_TIMEOUT,
+ timeout_seconds: int = DEFAULT_TIMEOUT,
+ gateway_port: int = DEFAULT_GATEWAY_PORT,
+ env: dict[str, str] | None = None,
+ sandbox_metadata: dict[str, str] | None = None,
+ resource: dict[str, str] | None = None,
+ entrypoint: list[str] | None = None,
+ network_policy: NetworkPolicy | 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:`OpenSandboxWorkspace`.
+
+ The sandbox 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 stored in sandbox metadata for
+ reattachment.
+ image (`str`, defaults to `DEFAULT_IMAGE`):
+ OpenSandbox image used when creating a fresh sandbox.
+ api_key (`str`, defaults to `""`):
+ OpenSandbox API key (``""`` lets the SDK use its
+ environment fallback).
+ domain (`str`, defaults to `""`):
+ Optional OpenSandbox server domain.
+ protocol (`str`, defaults to `"http"`):
+ Protocol to use (http/https)
+ request_timeout_seconds (`float | None`, optional):
+ SDK HTTP request timeout. ``None`` leaves the SDK
+ default in effect.
+ timeout_seconds (`int`, defaults to `DEFAULT_TIMEOUT`):
+ Sandbox keep-alive and create/connect/resume timeout.
+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):
+ TCP port the in-sandbox gateway listens on.
+ env (`dict[str, str] | None`, optional):
+ Environment variables baked into newly-created sandboxes.
+ sandbox_metadata (`dict[str, str] | None`, optional):
+ Extra metadata merged with the workspace-id tag.
+ resource (`dict[str, str] | None`, optional):
+ OpenSandbox resource hints for newly-created sandboxes.
+ entrypoint (`list[str] | None`, optional):
+ Entrypoint override for newly-created sandboxes.
+ network_policy (`NetworkPolicy | None`, optional):
+ Creation-time OpenSandbox network policy. Runtime egress
+ mutation is intentionally left to a follow-up.
+ 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,
+ )
+ self.workdir = SANDBOX_WORKDIR
+ self.image = image
+ self.api_key = api_key
+ self.domain = domain
+ self.protocol = protocol
+ self.request_timeout_seconds = request_timeout_seconds
+ self.timeout_seconds = timeout_seconds
+ self.gateway_port = gateway_port
+ self.env = dict(env or {})
+ self.sandbox_metadata = dict(sandbox_metadata or {})
+ self.resource = dict(resource or {})
+ self.entrypoint = list(entrypoint or [])
+ self.network_policy = network_policy
+ self.extra_pip = list(extra_pip or [])
+ self.instructions = instructions
+
+ self._sandbox: Sandbox | None = None
+ self._backend: OpenSandboxBackend | None = None
+
+ @property
+ def sandbox_id(self) -> str | None:
+ """OpenSandbox sandbox id, or ``None`` before initialize."""
+ return self._sandbox.id if self._sandbox else None
+
+ async def _provision_backend(self) -> None:
+ """Reattach or create the sandbox and bind the backend.
+
+ First-time bootstrap (uv → gateway venv → agentscope → gateway
+ script upload) is driven by
+ :meth:`SandboxedWorkspaceBase._setup_mcp_gateway` once
+ ``initialize`` has bound the backend and created the workspace
+ layout (which lays down ``workdir`` / ``_gateway_home`` first),
+ so this hook only has to attach or create the sandbox. Every
+ bootstrap step is idempotent, so an interrupted bootstrap
+ re-runs cleanly on the next ``initialize``.
+ """
+ existing = await self._find_existing_sandbox()
+ if existing is not None:
+ self._sandbox = await self._attach_existing_sandbox(existing)
+ else:
+ self._sandbox = await self._create_sandbox()
+ await self._wait_until_running()
+
+ self._backend = OpenSandboxBackend(self._sandbox, SANDBOX_WORKDIR)
+
+ async def _teardown_backend(self) -> None:
+ """Pause the sandbox (keep filesystem) and drop the handle.
+
+ ``sandbox.pause()`` — not ``kill()`` — so the next
+ :meth:`initialize` can reattach via metadata lookup and
+ resume. Errors are swallowed.
+ """
+ if self._sandbox is not None:
+ try:
+ await self._sandbox.pause()
+ except Exception as exc:
+ logger.warning("OpenSandboxWorkspace: pause failed: %s", exc)
+ try:
+ await self._sandbox.close()
+ except Exception as exc:
+ logger.warning(
+ "OpenSandboxWorkspace: local close failed: %s",
+ exc,
+ )
+ self._sandbox = None
+
+ async def get_instructions(self) -> str:
+ """Return the system-prompt fragment for this workspace.
+
+ Substitutes ``{workdir}`` in the configured template with
+ the sandbox-side path (``/workspace``). The agent always sees
+ sandbox-internal paths.
+ """
+ return self.instructions.format(workdir=SANDBOX_WORKDIR)
+
+ def _connection_config(self) -> ConnectionConfig:
+ """Build OpenSandbox connection config on demand."""
+ from opensandbox.config.connection import ConnectionConfig
+
+ kwargs: dict = {"protocol": self.protocol}
+ if self.api_key:
+ kwargs["api_key"] = self.api_key
+ if self.domain:
+ kwargs["domain"] = self.domain
+ if self.request_timeout_seconds is not None:
+ kwargs["request_timeout"] = timedelta(
+ seconds=self.request_timeout_seconds,
+ )
+ return ConnectionConfig(**kwargs)
+
+ async def _find_existing_sandbox(self) -> SandboxInfo | None:
+ """Return the most recent sandbox matching this workspace id."""
+ from opensandbox.models.sandboxes import SandboxFilter
+ from opensandbox import SandboxManager
+
+ manager = await SandboxManager.create(
+ connection_config=self._connection_config(),
+ )
+ sandbox_filter = SandboxFilter(
+ states=["RUNNING", "PAUSED"],
+ metadata={METADATA_WORKSPACE_ID_KEY: self.workspace_id},
+ )
+ try:
+ infos = await manager.list_sandbox_infos(sandbox_filter)
+ finally:
+ try:
+ await manager.close()
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "OpenSandboxWorkspace: manager close failed: %s",
+ exc,
+ )
+ candidates = infos.sandbox_infos
+ if not candidates:
+ return None
+ if len(candidates) > 1:
+ logger.warning(
+ "OpenSandboxWorkspace: %d sandboxes match workspace_id=%r; "
+ "attaching to most recent",
+ len(candidates),
+ self.workspace_id,
+ )
+ candidates.sort(key=lambda item: item.created_at, reverse=True)
+ return candidates[0]
+
+ async def _create_sandbox(self) -> Sandbox:
+ """Create a fresh sandbox with workspace metadata applied."""
+ from opensandbox import Sandbox
+
+ kwargs: dict = {
+ "image": self.image,
+ "connection_config": self._connection_config(),
+ "metadata": {
+ **self.sandbox_metadata,
+ METADATA_WORKSPACE_ID_KEY: self.workspace_id,
+ },
+ "timeout": timedelta(seconds=self.timeout_seconds),
+ "ready_timeout": timedelta(seconds=self.timeout_seconds),
+ }
+ if self.env:
+ kwargs["env"] = self.env
+ if self.resource:
+ kwargs["resource"] = self.resource
+ if self.entrypoint:
+ kwargs["entrypoint"] = self.entrypoint
+ if self.network_policy is not None:
+ kwargs["network_policy"] = self.network_policy
+ return await Sandbox.create(**kwargs)
+
+ async def _attach_existing_sandbox(self, info: SandboxInfo) -> Sandbox:
+ """Connect or resume depending on the OpenSandbox info state."""
+ from opensandbox import Sandbox
+
+ state = info.status.state.lower()
+
+ if state == "paused":
+ return await Sandbox.resume(
+ sandbox_id=info.id,
+ connection_config=self._connection_config(),
+ resume_timeout=timedelta(seconds=self.timeout_seconds),
+ )
+
+ if state == "running":
+ return await Sandbox.connect(
+ sandbox_id=info.id,
+ connection_config=self._connection_config(),
+ connect_timeout=timedelta(seconds=self.timeout_seconds),
+ )
+
+ raise RuntimeError(
+ f"OpenSandbox sandbox {info.id!r} is not attachable "
+ f"(state={state!r})",
+ )
+
+ async def _wait_until_running(self, timeout: float = 30.0) -> None:
+ """Poll until the sandbox reports healthy.
+
+ ``Sandbox.create`` / ``Sandbox.connect`` / ``Sandbox.resume``
+ normally perform their own readiness checks, but a freshly
+ created, connected, or resumed sandbox may still briefly reject
+ command / filesystem calls while the service endpoint settles.
+ We poll the SDK health probe, treating transient SDK errors as
+ "not yet" and retrying until the timeout.
+
+ Args:
+ timeout (`float`, defaults to `30.0`):
+ Hard ceiling in seconds. Raises :class:`RuntimeError`
+ if the sandbox is still not healthy after this long.
+ """
+ if hasattr(self._sandbox, "is_running"):
+ probe = self._sandbox.is_running
+ probe_name = "is_running"
+ elif hasattr(self._sandbox, "is_healthy"):
+ probe = self._sandbox.is_healthy
+ probe_name = "is_healthy"
+ else:
+ # The real SDK create/connect/resume calls perform readiness
+ # checks before returning; older/mocked SDK shapes may not expose
+ # an extra probe.
+ return
+
+ deadline = asyncio.get_event_loop().time() + timeout
+ delay = 0.1
+ while asyncio.get_event_loop().time() < deadline:
+ try:
+ if await probe():
+ return
+ except Exception as exc:
+ logger.debug(
+ "OpenSandboxWorkspace: %s probe error (will retry): %s",
+ probe_name,
+ exc,
+ )
+ await asyncio.sleep(delay)
+ delay = min(delay * 1.5, 1.0)
+ raise RuntimeError(
+ f"OpenSandbox sandbox did not become ready within {timeout}s "
+ f"(workspace_id={self.workspace_id!r})",
+ )
+
+ def _bootstrap_commands(self) -> list[str]:
+ """Return the provisioning shell command sequence.
+
+ Called once by :meth:`SandboxedWorkspaceBase._setup_mcp_gateway`
+ when the gateway script is missing (fresh sandbox, or a prior
+ bootstrap that was interrupted before the script was written).
+ The base class runs each command with
+ :attr:`_bootstrap_cmd_timeout` and then uploads the glob helper
+ and gateway script itself, so this hook only builds the command
+ list.
+
+ The workspace layout (``data/``, ``skills/``, ``sessions/``,
+ gateway home) is created by the base class
+ :meth:`_ensure_workspace_layout` before bootstrap runs, so
+ bootstrap only installs the runtime. ``uv`` lands at
+ ``/usr/local/bin`` (on the default PATH, root needs no sudo) and
+ is invoked bare, matching K8s/E2B.
+
+ Returns:
+ A list of shell command strings, to be executed in order. Each
+ must exit 0; a non-zero exit aborts bootstrap.
+ """
+ pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)
+ # Quote every requirement so entries with spaces or shell
+ # metacharacters cannot break ``sh -c`` or inject inside the sandbox.
+ pip_args = " ".join(shlex.quote(p) for p in pip_pkgs)
+
+ return [
+ # 1. System packages used by bootstrap and builtin tools. The
+ # default image runs as root, so no sudo is needed. ``procps``
+ # backs gateway-process cleanup; ``ripgrep`` backs the Grep tool.
+ "apt-get update -qq "
+ "&& apt-get install -y --no-install-recommends curl "
+ "ca-certificates procps ripgrep "
+ "&& rm -rf /var/lib/apt/lists/*",
+ # 2. Astral uv → /usr/local/bin (on PATH). INSTALLER_NO_MODIFY_PATH
+ # suppresses shell rc edits.
+ "curl -LsSf https://astral.sh/uv/install.sh "
+ "| env UV_INSTALL_DIR=/usr/local/bin "
+ "INSTALLER_NO_MODIFY_PATH=1 sh",
+ # 3. Gateway venv + base requirements + agentscope from PyPI.
+ # ``uv venv`` creates the gateway home as a parent dir.
+ 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/tests/backend_docker_test.py b/tests/backend_docker_test.py
index 93fbc5244..62473740c 100644
--- a/tests/backend_docker_test.py
+++ b/tests/backend_docker_test.py
@@ -212,7 +212,3 @@ class TestDockerBackend(IsolatedAsyncioTestCase):
# Deleting a non-existent path must not raise.
await self.backend.delete_path(f"{CONTAINER_WORKDIR}/missing")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/backend_e2b_test.py b/tests/backend_e2b_test.py
index 3a4388284..7da141242 100644
--- a/tests/backend_e2b_test.py
+++ b/tests/backend_e2b_test.py
@@ -147,7 +147,3 @@ class TestE2BBackend(IsolatedAsyncioTestCase):
# Deleting a non-existent path must not raise.
await self.backend.delete_path(f"{SANDBOX_WORKDIR}/missing")
-
-
-if __name__ == "__main__":
- unittest.main()
diff --git a/tests/backend_opensandbox_test.py b/tests/backend_opensandbox_test.py
new file mode 100644
index 000000000..1be34dfbc
--- /dev/null
+++ b/tests/backend_opensandbox_test.py
@@ -0,0 +1,155 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Test cases for :class:`OpenSandboxBackend`.
+
+Validates that the three backend primitives (``exec_shell``,
+``read_file``, ``write_file``) and the inherited shell-based filesystem
+helpers behave correctly inside a real OpenSandbox sandbox.
+
+The whole module is skipped unless the ``OPENSANDBOX_DOMAIN`` environment
+variable is set, because every test requires a live OpenSandbox service.
+CI runs without OpenSandbox access are therefore unaffected; when a
+domain *is* present the tests exercise the real ``commands.run`` /
+``files.*`` APIs.
+
+A live sandbox is obtained by initializing an :class:`OpenSandboxWorkspace`
+and reusing its already-wired :class:`OpenSandboxBackend` (``ws._backend``),
+which avoids duplicating the sandbox bring-up logic here.
+"""
+
+import os
+import unittest
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from agentscope.tool import ExecResult
+from agentscope.workspace import OpenSandboxWorkspace
+from agentscope.workspace import OpenSandboxBackend
+from agentscope.workspace._opensandbox._constants import SANDBOX_WORKDIR
+
+
+# ── OpenSandbox availability check ─────────────────────────────────
+
+_DOMAIN = os.getenv("OPENSANDBOX_DOMAIN", "")
+_API_KEY = os.getenv("OPENSANDBOX_API_KEY", "")
+_SKIP_REASON = "OPENSANDBOX_DOMAIN environment variable is not set"
+
+
[email protected](_DOMAIN, _SKIP_REASON)
+class TestOpenSandboxBackend(IsolatedAsyncioTestCase):
+ """Test cases for ``OpenSandboxBackend`` against a live sandbox.
+
+ Each test creates a real OpenSandbox sandbox via
+ ``OpenSandboxWorkspace`` and tears it down (``close`` → sandbox
+ pause) afterwards.
+ """
+
+ async def asyncSetUp(self) -> None:
+ """Start a workspace and reuse its wired backend."""
+ self.workspace = OpenSandboxWorkspace(
+ domain=_DOMAIN,
+ api_key=_API_KEY,
+ )
+ await self.workspace.initialize()
+ self.backend = self.workspace._backend
+ self.assertIsInstance(self.backend, OpenSandboxBackend)
+
+ async def asyncTearDown(self) -> None:
+ """Pause / close the sandbox."""
+ await self.workspace.close()
+
+ # ── exec ───────────────────────────────────────────────────────
+
+ async def test_exec_returns_stdout(self) -> None:
+ """A program's stdout/exit code are captured into ``ExecResult``."""
+ 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:
+ """A non-zero command exit is reported as a normal result."""
+ 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_quoting_preserved(self) -> None:
+ """An argv element with spaces / metacharacters survives the
+ POSIX-quote round-trip the backend does for ``commands.run``."""
+ tricky = "a b c | ;"
+ 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`` the sandbox workdir is used."""
+ result = await self.backend.exec_shell(["pwd"])
+ self.assertTrue(result.ok())
+ self.assertEqual(result.stdout.decode().strip(), SANDBOX_WORKDIR)
+
+ # ── file I/O ───────────────────────────────────────────────────
+
+ async def test_write_then_read_roundtrip(self) -> None:
+ """Bytes written into the sandbox 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 parent directories."""
+ 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_read_missing_file_raises(self) -> None:
+ """Reading a non-existent file raises ``FileNotFoundError``."""
+ with self.assertRaises(FileNotFoundError):
+ await self.backend.read_file(f"{SANDBOX_WORKDIR}/nope.txt")
+
+ # ── derived filesystem helpers (shell-based) ───────────────────
+
+ async def test_file_exists_and_is_dir(self) -> None:
+ """``file_exists`` / ``is_dir`` 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.is_dir(SANDBOX_WORKDIR))
+ self.assertFalse(await self.backend.is_dir(path))
+ self.assertFalse(
+ await self.backend.file_exists(f"{SANDBOX_WORKDIR}/missing"),
+ )
+
+ async def test_list_dir(self) -> None:
+ """Non-recursive ``list_dir`` 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_stat_mtime(self) -> None:
+ """``stat_mtime`` returns a float for an existing path, None else."""
+ path = f"{SANDBOX_WORKDIR}/stat.txt"
+ await self.backend.write_file(path, b"x")
+ mtime = await self.backend.stat_mtime(path)
+ self.assertIsInstance(mtime, 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; missing is a no-op."""
+ 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))
+
+ # Deleting a non-existent path must not raise.
+ await self.backend.delete_path(f"{SANDBOX_WORKDIR}/missing")
diff --git a/tests/workspace_opensandbox_test.py b/tests/workspace_opensandbox_test.py
new file mode 100644
index 000000000..893c6dfc5
--- /dev/null
+++ b/tests/workspace_opensandbox_test.py
@@ -0,0 +1,73 @@
+# -*- coding: utf-8 -*-
+"""Test cases for OpenSandboxWorkspace.
+
+The whole module is skipped when the ``OPENSANDBOX_DOMAIN`` environment
+variable is not set, because every test requires a live OpenSandbox
+service.
+"""
+import os
+import unittest
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from agentscope.mcp import MCPClient, StdioMCPConfig
+from agentscope.workspace import OpenSandboxWorkspace
+
+
+# ── OpenSandbox availability check ─────────────────────────────────
+
+_DOMAIN = os.getenv("OPENSANDBOX_DOMAIN", "")
+_API_KEY = os.getenv("OPENSANDBOX_API_KEY", "")
+_SKIP_REASON = "OPENSANDBOX_DOMAIN environment variable is not set"
+
+
+# ── lifecycle tests ────────────────────────────────────────────────
+
+
[email protected](_DOMAIN, _SKIP_REASON)
+class TestOpenSandboxWorkspaceLifecycle(IsolatedAsyncioTestCase):
+ """Test cases for OpenSandboxWorkspace lifecycle and MCP integration.
+
+ Each test creates a real OpenSandbox sandbox and tears it down
+ (``pause``) afterward. The suite is skipped entirely when
+ ``OPENSANDBOX_DOMAIN`` is absent so that CI runs without OpenSandbox
+ access are unaffected.
+ """
+
+ async def test_initialize_and_list_mcps(self) -> None:
+ """``initialize`` starts the sandbox and ``list_mcps`` enumerates MCPs.
+
+ Verifies:
+ 1. The workspace initializes without raising.
+ 2. ``list_mcps`` returns at least the seeded MCP (browser-use).
+ 3. Each MCP exposes at least one tool via ``list_raw_tools``.
+ 4. ``close`` (sandbox pause) completes without raising.
+ """
+ workspace = OpenSandboxWorkspace(
+ domain=_DOMAIN,
+ api_key=_API_KEY,
+ default_mcps=[
+ MCPClient(
+ name="browser-use",
+ mcp_config=StdioMCPConfig(
+ command="npx",
+ args=["@playwright/mcp@latest"],
+ ),
+ is_stateful=True,
+ ),
+ ],
+ )
+
+ await workspace.initialize()
+
+ mcps = await workspace.list_mcps()
+ self.assertGreater(len(mcps), 0)
+
+ for mcp in mcps:
+ tools = await mcp.list_raw_tools()
+ self.assertGreater(len(tools), 0)
+
+ await workspace.close()
+
+
+if __name__ == "__main__":
+ unittest.main()