Skip to content

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

feat(workspace): add daytona workspace backend (#1943)

B1n_dd71a37294d8
diff --git a/.github/workflows/k8s-workspace.yml b/.github/workflows/k8s-workspace.yml
index ec091a585..d8bda37f7 100644
--- a/.github/workflows/k8s-workspace.yml
+++ b/.github/workflows/k8s-workspace.yml
@@ -78,4 +78,3 @@ jobs:
kubectl -n agentscope describe "$p" || true
kubectl -n agentscope logs "$p" --all-containers=true --tail=200 || true
done
-
diff --git a/README.md b/README.md
index 5c721dc09..4415c1ced 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, E2B, and OpenSandbox.
+- [**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, OpenSandbox, and Daytona.
- [**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.
@@ -73,6 +73,7 @@ rather than constraining them with strict prompts and opinionated orchestrations
## News
<!-- BEGIN NEWS -->
+- **[2026-07] `INTE`:** Daytona-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)
diff --git a/README_zh.md b/README_zh.md
index 081cac7d8..cb8804311 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 和 OpenSandbox 后端。
+- [**工作区 / 沙箱支持** →](https://docs.agentscope.io/latest/zh/building-blocks/workspace) 在隔离环境中运行工具和代码,内置支持本地文件系统、Docker、E2B、OpenSandbox 和 Daytona 后端。
- [**可扩展中间件系统** →](https://docs.agentscope.io/latest/zh/building-blocks/middleware) 可组合的钩子系统,用于自定义和扩展智能体的推理-行动循环。
我们为日益自主的大语言模型而设计。
@@ -79,6 +79,7 @@ AgentScope 2.0 是一款面向生产、易于使用的智能体框架,提供
## 新闻
<!-- BEGIN NEWS -->
+- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](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)
diff --git a/docs/NEWS.md b/docs/NEWS.md
index fb723153a..6798954f9 100644
--- a/docs/NEWS.md
+++ b/docs/NEWS.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-07] `INTE`:** Daytona-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)
diff --git a/docs/NEWS_zh.md b/docs/NEWS_zh.md
index 8ad67dcd5..90e0f3c2c 100644
--- a/docs/NEWS_zh.md
+++ b/docs/NEWS_zh.md
@@ -2,6 +2,7 @@
<!-- The first 10 items are automatically synced to README.md and README_zh.md via GitHub Actions. -->
<!-- To update news in READMEs, modify this file and push to trigger the workflow. -->
+- **[2026-07] `集成`:** 集成 Daytona 工作区/沙箱实现。 [文档](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)
diff --git a/pyproject.toml b/pyproject.toml
index 744e971e2..8eaff2400 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -73,6 +73,7 @@ workspace = [
"aiodocker",
"e2b",
"agentscope[k8s]",
+ "daytona",
"opensandbox",
]
# ------------ Tools ------------
diff --git a/src/agentscope/app/workspace_manager/__init__.py b/src/agentscope/app/workspace_manager/__init__.py
index dcd6befcc..745967157 100644
--- a/src/agentscope/app/workspace_manager/__init__.py
+++ b/src/agentscope/app/workspace_manager/__init__.py
@@ -6,6 +6,7 @@ from ._base import IsolationPolicy, WorkspaceManagerBase
from ._local_workspace_manager import LocalWorkspaceManager
from ._docker_workspace_manager import DockerWorkspaceManager
from ._e2b_workspace_manager import E2BWorkspaceManager
+from ._daytona_workspace_manager import DaytonaWorkspaceManager
from ._k8s_workspace_manager import K8sWorkspaceManager
from ._opensandbox_workspace_manager import OpenSandboxWorkspaceManager
@@ -15,6 +16,7 @@ __all__ = [
"LocalWorkspaceManager",
"DockerWorkspaceManager",
"E2BWorkspaceManager",
+ "DaytonaWorkspaceManager",
"K8sWorkspaceManager",
"OpenSandboxWorkspaceManager",
]
diff --git a/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py
new file mode 100644
index 000000000..22860da2a
--- /dev/null
+++ b/src/agentscope/app/workspace_manager/_daytona_workspace_manager.py
@@ -0,0 +1,339 @@
+# -*- coding: utf-8 -*-
+"""DaytonaWorkspaceManager — lifecycle manager for Daytona workspaces.
+
+Mirrors :class:`E2BWorkspaceManager` and :class:`DockerWorkspaceManager`
+in its public surface (``get_workspace`` / ``close`` / ``close_all``) so
+service-layer callers do not branch on backend.
+
+Daytona-specific behavior:
+
+* Reattachment uses Daytona labels. The ``workspace_id`` is written to
+ the sandbox's ``agentscope.workspace.id`` label at create time and
+ looked up inside :meth:`DaytonaWorkspace.initialize`.
+* ``user_id`` / ``agent_id`` are forwarded as additional labels for
+ dashboard filtering. They do **not** participate in cache resolution;
+ the cache key is strictly ``workspace_id``.
+* The manager does not share an ``AsyncDaytona`` client. Each workspace
+ owns its provider client so network resources and shutdown are scoped
+ to that workspace.
+* 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
+ stopping Daytona sandboxes is a remote round-trip per workspace.
+"""
+
+import asyncio
+import time
+from typing import Self
+
+from ..._logging import logger
+from ...mcp import MCPClient
+from ...workspace import DaytonaWorkspace
+from ...workspace._daytona._constants import (
+ DEFAULT_GATEWAY_PORT,
+ DEFAULT_SWEEP_INTERVAL,
+ DEFAULT_TIMEOUT,
+)
+from ._base import IsolationPolicy, WorkspaceManagerBase
+
+
+class DaytonaWorkspaceManager(WorkspaceManagerBase):
+ """Manages :class:`DaytonaWorkspace` instances with TTL 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,
+ api_key: str = "",
+ api_url: str = "",
+ target: str = "",
+ timeout_seconds: int = DEFAULT_TIMEOUT,
+ gateway_port: int = DEFAULT_GATEWAY_PORT,
+ env: dict[str, str] | None = None,
+ sandbox_metadata: dict[str, str] | None = None,
+ extra_pip: list[str] | None = None,
+ default_mcps: list[MCPClient] | None = None,
+ skill_paths: list[str] | None = None,
+ os_user: str | None = None,
+ ttl: float = 3600.0,
+ sweep_interval: float = DEFAULT_SWEEP_INTERVAL,
+ ) -> None:
+ """Initialize the Daytona workspace manager.
+
+ Args:
+ isolation (`IsolationPolicy`, defaults to `PER_AGENT`):
+ Isolation grain for :meth:`assign_workspace_id`. See
+ :class:`DockerWorkspaceManager` for semantics.
+ api_key (`str`, defaults to `""`):
+ Daytona API key forwarded to every workspace. ``""``
+ lets the Daytona SDK read credentials from the
+ environment.
+ api_url (`str`, defaults to `""`):
+ Optional Daytona API URL for self-hosted or non-default
+ deployments.
+ target (`str`, defaults to `""`):
+ Optional Daytona target / region.
+ timeout_seconds (`int`, defaults to `DEFAULT_TIMEOUT`):
+ Timeout forwarded to workspace create/start/recover/stop
+ operations.
+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):
+ TCP port the in-sandbox gateway listens on.
+ env (`dict[str, str] | None`, optional):
+ Environment variables passed to Daytona create params.
+ sandbox_metadata (`dict[str, str] | None`, optional):
+ Extra labels merged with the per-workspace
+ ``agentscope.workspace.id`` / ``agentscope.user.id`` /
+ ``agentscope.agent.id`` labels.
+ 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. Persisted
+ ``.mcp`` state wins on reattach.
+ skill_paths (`list[str] | None`, optional):
+ Skill directories seeded into brand-new workspaces.
+ os_user (`str | None`, optional):
+ Optional Daytona OS user forwarded to workspace create
+ params. ``None`` leaves user selection to Daytona.
+ ttl (`float`, defaults to `3600.0`):
+ Seconds before an idle cached workspace is evicted and
+ its sandbox stopped.
+ sweep_interval (`float`, defaults to `DEFAULT_SWEEP_INTERVAL`):
+ How often (seconds) the background sweeper wakes up to
+ look for idle workspaces.
+ """
+ self._api_key = api_key
+ self._api_url = api_url
+ self._target = target
+ self._timeout_seconds = timeout_seconds
+ self._gateway_port = gateway_port
+ self._env = dict(env or {})
+ self._sandbox_metadata = dict(sandbox_metadata or {})
+ self._extra_pip = list(extra_pip or [])
+ self._default_mcps = list(default_mcps or [])
+ self._skill_paths = list(skill_paths or [])
+ self._os_user = os_user
+ self._ttl = ttl
+ self._sweep_interval = sweep_interval
+ super().__init__(isolation=isolation)
+
+ # workspace_id → (workspace, last_access_monotonic)
+ self._cache: dict[str, tuple[DaytonaWorkspace, float]] = {}
+ self._lock = asyncio.Lock()
+ self._sweep_task: asyncio.Task | None = None
+
+ # ── metadata helper ───────────────────────────────────────────
+
+ def _metadata_for(self, user_id: str, agent_id: str) -> dict[str, str]:
+ """Build user/agent labels for Daytona dashboard filtering.
+
+ ``DaytonaWorkspace`` always sets ``agentscope.workspace.id``;
+ this manager adds user/agent labels so provider dashboards can
+ be filtered without changing AgentScope cache semantics.
+ """
+ return {
+ "agentscope.user.id": user_id,
+ "agentscope.agent.id": agent_id,
+ **self._sandbox_metadata,
+ }
+
+ # ── workspace construction ────────────────────────────────────
+
+ async def _build_and_start(
+ self,
+ *,
+ workspace_id: str | None,
+ user_id: str,
+ agent_id: str,
+ ) -> DaytonaWorkspace:
+ """Construct a :class:`DaytonaWorkspace` and initialize it.
+
+ ``workspace_id=None`` lets :class:`WorkspaceBase` allocate a
+ fresh UUID. Otherwise the provided id is forwarded so
+ label-based reattachment works on cache miss.
+ """
+ ws = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ api_key=self._api_key,
+ api_url=self._api_url,
+ target=self._target,
+ timeout_seconds=self._timeout_seconds,
+ gateway_port=self._gateway_port,
+ env=self._env,
+ sandbox_metadata=self._metadata_for(user_id, agent_id),
+ extra_pip=self._extra_pip,
+ default_mcps=self._default_mcps,
+ skill_paths=self._skill_paths,
+ os_user=self._os_user,
+ )
+ 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,
+ ) -> DaytonaWorkspace:
+ """Return an initialized workspace, reattaching on cache miss.
+
+ On miss the manager constructs ``DaytonaWorkspace`` with the
+ requested ``workspace_id`` and lets its ``initialize`` find a
+ matching sandbox by label or create a fresh sandbox otherwise.
+
+ Args:
+ user_id (`str`):
+ Owning user identifier, forwarded as sandbox label only.
+ agent_id (`str`):
+ Agent identifier, forwarded as sandbox label only.
+ session_id (`str`):
+ Session identifier (unused; sessions partition under
+ ``sessions/<session_id>/`` inside a workspace).
+ workspace_id (`str | None`, optional):
+ Stable workspace identifier and cache key. When ``None``,
+ the manager falls back to :meth:`assign_workspace_id`.
+
+ Returns:
+ `DaytonaWorkspace`:
+ 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
+ # calls for the same workspace_id from creating two sandboxes.
+ 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 (= gracefully stop the sandbox) and evict a workspace.
+
+ 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.
+
+ ``sandbox.stop()`` is a remote round-trip per sandbox; doing it
+ sequentially on app shutdown produces a noticeable stall, so we
+ fan the calls out with :func:`asyncio.gather`.
+ """
+ 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 close idle workspaces.
+
+ Runs forever until cancelled. Each tick pops every cache entry
+ whose last-access is older than ``ttl`` and closes it outside
+ the lock; exceptions during close 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("Daytona 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: DaytonaWorkspace) -> None:
+ """Close a workspace, logging any failure instead of raising."""
+ try:
+ await ws.close()
+ except Exception:
+ logger.exception(
+ "Failed to close DaytonaWorkspace %s",
+ ws.workspace_id,
+ )
diff --git a/src/agentscope/workspace/__init__.py b/src/agentscope/workspace/__init__.py
index 2aa043cac..700359af1 100644
--- a/src/agentscope/workspace/__init__.py
+++ b/src/agentscope/workspace/__init__.py
@@ -7,6 +7,7 @@ from ._local_workspace import LocalWorkspace
from ._offload_protocol import Offloader
from ._docker import DockerBackend, DockerWorkspace
from ._e2b import E2BWorkspace, E2BBackend
+from ._daytona import DaytonaBackend, DaytonaWorkspace
from ._k8s import K8sBackend, K8sWorkspace
from ._opensandbox import OpenSandboxBackend, OpenSandboxWorkspace
@@ -18,6 +19,8 @@ __all__ = [
"DockerWorkspace",
"E2BBackend",
"E2BWorkspace",
+ "DaytonaBackend",
+ "DaytonaWorkspace",
"K8sBackend",
"K8sWorkspace",
"Offloader",
diff --git a/src/agentscope/workspace/_daytona/__init__.py b/src/agentscope/workspace/_daytona/__init__.py
new file mode 100644
index 000000000..55ec1ee80
--- /dev/null
+++ b/src/agentscope/workspace/_daytona/__init__.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+"""Daytona-backed workspace package.
+
+Re-exports :class:`DaytonaWorkspace` so callers can write
+``from agentscope.workspace._daytona import DaytonaWorkspace`` without
+having to poke at the underlying module layout.
+"""
+
+from ._daytona_backend import DaytonaBackend
+from ._daytona_workspace import DaytonaWorkspace
+
+__all__ = [
+ "DaytonaBackend",
+ "DaytonaWorkspace",
+]
diff --git a/src/agentscope/workspace/_daytona/_constants.py b/src/agentscope/workspace/_daytona/_constants.py
new file mode 100644
index 000000000..03114386c
--- /dev/null
+++ b/src/agentscope/workspace/_daytona/_constants.py
@@ -0,0 +1,32 @@
+# -*- coding: utf-8 -*-
+"""Constants for :class:`DaytonaWorkspace`, mirroring the E2B and K8s
+``_constants`` modules.
+
+Only defaults that cannot be derived on the shared sandbox base live
+here: SDK operation timeout, gateway port, sweeper interval, the
+sandbox label key used for reattachment, and the gateway home anchor
+name. Every derived path (venv, python, script, glob helper, log) and
+the bootstrap command sequence live on the workspace / base class, not
+here.
+"""
+
+# ── shared constants ───────────────────────────────────────────────
+
+#: Default Daytona SDK operation timeout, in seconds. Bootstrap runs
+#: ``apt install``, the uv installer, and Python dependency installs, so
+#: the default must be generous enough to cover a cold first start.
+DEFAULT_TIMEOUT = 300
+
+#: Default port the in-sandbox gateway listens on.
+DEFAULT_GATEWAY_PORT = 5600
+
+#: Default interval for the manager-side TTL sweeper.
+DEFAULT_SWEEP_INTERVAL = 300.0
+
+#: Sandbox label key used to map workspace_id -> Daytona sandbox.
+METADATA_WORKSPACE_ID_KEY = "agentscope.workspace.id"
+
+# Gateway runtime home under the SDK-reported user home. The shared
+# sandbox base derives venv, gateway script, log, and glob-helper paths
+# from this anchor.
+GATEWAY_HOME_NAME = ".agentscope"
diff --git a/src/agentscope/workspace/_daytona/_daytona_backend.py b/src/agentscope/workspace/_daytona/_daytona_backend.py
new file mode 100644
index 000000000..ff2019580
--- /dev/null
+++ b/src/agentscope/workspace/_daytona/_daytona_backend.py
@@ -0,0 +1,167 @@
+# -*- coding: utf-8 -*-
+"""Daytona sandbox :class:`BackendBase` implementation.
+
+Wraps Daytona SDK ``process.exec`` and ``fs.*`` APIs into the three
+backend primitives (``exec_shell``, ``read_file``, ``write_file``) so
+that builtin tools (Bash, Read, Write, Edit, Grep, Glob) can operate
+inside a Daytona 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 math
+import posixpath
+import shlex
+from typing import Any
+
+from ...tool import BackendBase, ExecResult
+
+
+class DaytonaBackend(BackendBase):
+ """Backend that delegates to a running Daytona 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 (`Any`):
+ A Daytona sandbox object (must already be started /
+ attached).
+ workdir (`str`):
+ Default working directory for ``exec_shell`` calls inside
+ the sandbox.
+ """
+
+ def __init__(self, sandbox: Any, workdir: str) -> None:
+ """Initialize the Daytona backend.
+
+ Args:
+ sandbox (`Any`):
+ A started / attached Daytona sandbox object.
+ workdir (`str`):
+ Default working directory for ``exec_shell`` calls
+ inside the sandbox.
+ """
+ self._sandbox = sandbox
+ self._workdir = workdir
+
+ # ── exec ─────────────────────────────────────────────────────
+
+ async def getcwd(self) -> str:
+ """Return the sandbox's default working directory.
+
+ Overrides the base class default (which would shell out to
+ ``pwd``) with the cached ``workdir`` supplied at construction,
+ avoiding a per-call sandbox round-trip.
+
+ Returns:
+ `str`:
+ The sandbox'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 sandbox via ``process.exec``.
+
+ *command* is an argv list. Daytona ``process.exec`` takes one
+ shell command line, so argv is POSIX-quoted back into a string
+ before dispatch. 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 sandbox. When ``None`` the
+ backend's default ``workdir`` is used.
+ timeout (`float | None`, optional):
+ Maximum number of seconds to wait. Daytona expects an
+ integer timeout, so provided values are rounded up to
+ the next integer second.
+
+ Returns:
+ `ExecResult`:
+ The captured exit code and output. Daytona's SDK exposes
+ only ``exit_code`` and ``result`` (no separate stderr
+ field), so the command is wrapped with ``2>&1`` to fold
+ stderr into ``result`` — otherwise command error output
+ would be silently dropped. ``stdout`` therefore carries
+ the merged stream and ``stderr`` stays empty for normal
+ responses. Transport errors yield an ``exit_code`` of
+ ``-1`` with the exception text in ``stderr``.
+ """
+ # Fold stderr into stdout at the shell level; the SDK lacks a
+ # dedicated stderr field, so without this error output is lost.
+ command_line = " ".join(shlex.quote(arg) for arg in command) + " 2>&1"
+ kwargs: dict[str, Any] = {"cwd": cwd or self._workdir}
+ if timeout is not None:
+ kwargs["timeout"] = math.ceil(timeout)
+
+ try:
+ res = await self._sandbox.process.exec(command_line, **kwargs)
+ return ExecResult(
+ exit_code=int(res.exit_code),
+ stdout=res.result.encode("utf-8"),
+ stderr=b"",
+ )
+ 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 ``fs.download_file``.
+
+ 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.
+ """
+ from daytona import DaytonaNotFoundError
+
+ try:
+ data = await self._sandbox.fs.download_file(path)
+ except FileNotFoundError:
+ raise
+ except DaytonaNotFoundError as exc:
+ raise FileNotFoundError(
+ f"not found in sandbox: {path}",
+ ) from exc
+ return bytes(data)
+
+ async def write_file(self, path: str, data: bytes) -> None:
+ """Write *data* 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])
+ await self._sandbox.fs.upload_file(data, path)
diff --git a/src/agentscope/workspace/_daytona/_daytona_workspace.py b/src/agentscope/workspace/_daytona/_daytona_workspace.py
new file mode 100644
index 000000000..3c08fccfc
--- /dev/null
+++ b/src/agentscope/workspace/_daytona/_daytona_workspace.py
@@ -0,0 +1,508 @@
+# -*- coding: utf-8 -*-
+"""DaytonaWorkspace — sandboxed workspace backed by Daytona.
+
+Architecture
+------------
+
+Mirrors :class:`agentscope.workspace.E2BWorkspace` and
+:class:`agentscope.workspace.DockerWorkspace` at the AgentScope
+boundary, but swaps the provider runtime for the Daytona SDK:
+
+* **Lifecycle.** ``initialize()`` is inherited from
+ :class:`SandboxedWorkspaceBase`; it calls
+ :meth:`_provision_backend` to look up a sandbox by the
+ ``agentscope.workspace.id`` label, start / recover an existing
+ candidate when possible, or create a new sandbox and run bootstrap.
+ ``close()`` calls :meth:`_teardown_backend`, which uses Daytona
+ ``stop(force=False)`` so filesystem persistence survives reattach.
+* **Persistence.** Sandbox filesystem state is the persistence layer.
+ ``.mcp``, ``skills/``, ``sessions/`` and ``data/`` are managed by
+ :class:`WorkspaceBase` under the SDK-reported workdir.
+* **Bootstrap.** First-time provisioning installs ripgrep, uv, the
+ gateway virtualenv, AgentScope itself, the gateway script and the
+ glob helper. Bootstrap is detected by probing the gateway script path
+ inside the sandbox and is safe to rerun when a previous attempt was
+ interrupted.
+* **MCP gateway.** Identical to Docker/E2B after the shared-base
+ migration: a FastAPI process runs inside the sandbox. Host-side calls
+ drive the gateway through :class:`GatewayClient`, which runs an
+ in-sandbox ``python3 -c`` shim via :meth:`DaytonaBackend.exec_shell`.
+ Daytona preview URLs are not part of the internal gateway path.
+* **SDK paths.** The real workdir and user home are read from Daytona
+ before deriving gateway paths. The implementation does not assume a
+ fixed OS user, root home, or ``/home/daytona`` layout.
+* **Service-layer index.** The host stores only ``workspace_id``; the
+ sandbox carries ``METADATA_WORKSPACE_ID_KEY = workspace_id`` in its
+ Daytona labels. Manager code asks the workspace to reattach by that
+ label on cache miss.
+
+Configuration is per-workspace. The manager handles cache and TTL
+eviction; each workspace owns its own ``AsyncDaytona`` client and
+runtime sandbox handle.
+"""
+
+from __future__ import annotations
+
+import posixpath
+import shlex
+from typing import Any
+
+from ..._logging import logger
+from ...mcp import MCPClient
+from .._sandboxed_base import SandboxedWorkspaceBase
+from .._utils import _GATEWAY_BASE_REQUIREMENTS
+from ._constants import (
+ DEFAULT_GATEWAY_PORT,
+ DEFAULT_TIMEOUT,
+ GATEWAY_HOME_NAME,
+ METADATA_WORKSPACE_ID_KEY,
+)
+from ._daytona_backend import DaytonaBackend
+
+_DEFAULT_INSTRUCTIONS = """<workspace>
+You have a Daytona-based sandbox 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
+```
+
+Use the MCP-provided tools to interact with the sandbox filesystem
+and processes.
+</workspace>"""
+
+
+# ── the workspace ──────────────────────────────────────────────────
+
+
+class DaytonaWorkspace(SandboxedWorkspaceBase):
+ """Workspace backed by a Daytona sandbox.
+
+ ``default_mcps`` and ``skill_paths`` are seed-time inputs and are
+ not interpreted until :meth:`initialize`, after the Daytona backend
+ has been provisioned and the shared sandbox lifecycle can restore
+ persisted state.
+ """
+
+ # Gateway home is derived from Daytona SDK path APIs during
+ # ``_provision_backend``; the shared base derives venv, python,
+ # script, log and glob-helper paths from this anchor.
+ _gateway_home: str
+
+ def __init__(
+ self,
+ *,
+ workspace_id: str | None = None,
+ api_key: str = "",
+ api_url: str = "",
+ target: str = "",
+ timeout_seconds: int = DEFAULT_TIMEOUT,
+ gateway_port: int = DEFAULT_GATEWAY_PORT,
+ env: dict[str, str] | None = None,
+ sandbox_metadata: 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,
+ os_user: str | None = None,
+ ) -> None:
+ """Construct a :class:`DaytonaWorkspace`.
+
+ 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 Daytona labels for
+ reattachment. ``None`` generates a fresh UUID.
+ api_key (`str`, defaults to `""`):
+ Daytona API key. ``""`` lets the SDK read credentials
+ from its normal environment.
+ api_url (`str`, defaults to `""`):
+ Optional Daytona API URL for self-hosted deployments.
+ Empty string defers to SDK defaults.
+ target (`str`, defaults to `""`):
+ Optional Daytona target / region. Empty string defers
+ to SDK defaults.
+ timeout_seconds (`int`, defaults to `DEFAULT_TIMEOUT`):
+ Timeout forwarded to Daytona create/start/recover/stop
+ calls.
+ gateway_port (`int`, defaults to `DEFAULT_GATEWAY_PORT`):
+ TCP port the in-sandbox gateway listens on.
+ env (`dict[str, str] | None`, optional):
+ Environment variables passed to Daytona create params
+ as ``env_vars``.
+ sandbox_metadata (`dict[str, str] | None`, optional):
+ Extra labels merged with the workspace-id label. Useful
+ for dashboard filtering by user / agent.
+ 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.
+ os_user (`str | None`, optional):
+ Optional Daytona OS user. ``None`` means AgentScope
+ lets Daytona and the selected snapshot decide.
+ """
+ super().__init__(
+ workspace_id=workspace_id,
+ default_mcps=default_mcps,
+ skill_paths=skill_paths,
+ )
+
+ # ── serializable config ─────────────────────────────────
+ self.workdir = ""
+ self.api_key = api_key
+ self.api_url = api_url
+ self.target = target
+ self.timeout_seconds = timeout_seconds
+ self.gateway_port = gateway_port
+ self.env: dict[str, str] = dict(env or {})
+ self.sandbox_metadata: dict[str, str] = dict(sandbox_metadata or {})
+ self.extra_pip: list[str] = list(extra_pip or [])
+ self.instructions = instructions
+ self.os_user = os_user
+
+ # ── SDK-derived paths ───────────────────────────────────
+ self._user_home: str
+ self._uv_bin: str
+
+ # ── runtime state (Daytona-only) ────────────────────────
+ self._daytona: Any = None
+ self._sandbox: Any = None
+ self._backend: DaytonaBackend | None = None
+
+ # ── lifecycle hooks ─────────────────────────────────────────
+
+ @property
+ def sandbox_id(self) -> str | None:
+ """Daytona sandbox id, or ``None`` if not started."""
+ return self._sandbox.id if self._sandbox is not None else None
+
+ async def _provision_backend(self) -> None:
+ """Reattach or create the sandbox and bind the backend.
+
+ First-time provisioning also runs bootstrap (tools → uv →
+ gateway venv → agentscope → helper scripts). Bootstrap is
+ detected by the gateway script path derived from the Daytona SDK
+ and every step is idempotent so an interrupted bootstrap
+ re-runs cleanly. The workspace layout (``workdir`` /
+ ``_gateway_home`` / data / skills / sessions) is created by
+ :meth:`SandboxedWorkspaceBase._ensure_workspace_layout` right
+ after this hook, so it is not created here.
+ """
+ await self._attach_or_create_sandbox()
+ await self._derive_sdk_paths()
+ self._backend = DaytonaBackend(self._sandbox, workdir=self.workdir)
+
+ async def _teardown_backend(self) -> None:
+ """Gracefully stop the sandbox and release the SDK client.
+
+ ``sandbox.stop(force=False)`` — not force stop / archive — so
+ the next :meth:`initialize` can reattach via labels and reuse
+ the persistent filesystem. Errors are swallowed.
+ """
+ if self._sandbox is not None:
+ try:
+ await self._sandbox.stop(
+ timeout=self.timeout_seconds,
+ force=False,
+ )
+ except Exception as e: # noqa: BLE001
+ logger.warning("DaytonaWorkspace: stop failed: %s", e)
+ self._sandbox = None
+
+ if self._daytona is not None:
+ try:
+ await self._daytona.close()
+ except Exception as e: # noqa: BLE001
+ logger.warning("DaytonaWorkspace: client close failed: %s", e)
+ self._daytona = None
+
+ # ── instructions ────────────────────────────────────────────
+
+ async def get_instructions(self) -> str:
+ """Return the system-prompt fragment for this workspace.
+
+ Substitutes ``{workdir}`` in the configured template with the
+ SDK-reported sandbox workdir. Before initialization, a readable
+ placeholder is used because Daytona paths are not known yet.
+ """
+ workdir = self.workdir or "<sandbox workdir>"
+ return self.instructions.format(workdir=workdir)
+
+ # ── internals: Daytona client / sandbox attach / create ─────
+
+ async def _get_daytona_client(self) -> Any:
+ """Return a per-workspace ``AsyncDaytona`` client.
+
+ Daytona SDK clients own network resources, so the workspace
+ does not share a global client with the manager or with other
+ workspaces. Empty config fields are omitted so the SDK can read
+ its normal environment defaults.
+ """
+ if self._daytona is not None:
+ return self._daytona
+
+ from daytona import AsyncDaytona, DaytonaConfig
+
+ config_kwargs: dict[str, str] = {}
+ if self.api_key:
+ config_kwargs["api_key"] = self.api_key
+ if self.api_url:
+ config_kwargs["api_url"] = self.api_url
+ if self.target:
+ config_kwargs["target"] = self.target
+
+ if config_kwargs:
+ self._daytona = AsyncDaytona(DaytonaConfig(**config_kwargs))
+ else:
+ self._daytona = AsyncDaytona()
+ return self._daytona
+
+ async def _attach_or_create_sandbox(self) -> None:
+ """Reattach to an existing sandbox by label, or create one.
+
+ Resolution rule: a single sandbox is expected per
+ ``workspace_id``. If multiple usable candidates are returned
+ (for example after an unclean shutdown), attach to the newest
+ one by provider timestamps and log a warning — manual cleanup
+ is left to the operator.
+
+ Existing candidates are normalized to a ready state before the
+ caller derives paths or starts the gateway. New sandboxes are
+ created from the constructor config captured during
+ ``__init__``.
+ """
+ existing = await self._find_existing_sandbox()
+ client = await self._get_daytona_client()
+
+ if existing is not None:
+ self._sandbox = existing
+ await self._ensure_existing_sandbox_ready()
+ return
+
+ self._sandbox = await client.create(
+ self._create_params(),
+ timeout=self.timeout_seconds,
+ )
+
+ async def _find_existing_sandbox(self) -> Any:
+ """Find the most recent usable Daytona sandbox for this workspace.
+
+ Daytona may return started, stopped, paused, transitional, or
+ error-state sandboxes. Candidate filtering is intentionally
+ conservative: unrecoverable errors are ignored, while stopped,
+ paused and pausing sandboxes can be resumed again.
+
+ Returns:
+ The most recent usable Daytona sandbox object, or ``None``
+ if no matching sandbox exists.
+ """
+ from daytona import ListSandboxesQuery, SandboxState
+
+ client = await self._get_daytona_client()
+ query = ListSandboxesQuery(
+ labels={METADATA_WORKSPACE_ID_KEY: self.workspace_id},
+ states=[
+ SandboxState.STARTED,
+ SandboxState.STOPPED,
+ SandboxState.STARTING,
+ SandboxState.STOPPING,
+ SandboxState.ERROR,
+ SandboxState.PAUSING,
+ SandboxState.PAUSED,
+ SandboxState.RESUMING,
+ ],
+ )
+
+ candidates: list[Any] = []
+ try:
+ async for sandbox in client.list(query):
+ candidates.append(sandbox)
+ except Exception as e: # noqa: BLE001
+ logger.warning("DaytonaWorkspace: list sandboxes failed: %s", e)
+ return None
+
+ usable = [
+ sandbox
+ for sandbox in candidates
+ if self._is_candidate_usable(sandbox)
+ ]
+ if not usable:
+ return None
+ if len(usable) > 1:
+ logger.warning(
+ "DaytonaWorkspace: %d sandboxes match workspace_id=%r; "
+ "attaching to most recent",
+ len(usable),
+ self.workspace_id,
+ )
+ usable.sort(key=_candidate_sort_key, reverse=True)
+ return usable[0]
+
+ def _is_candidate_usable(self, sandbox: Any) -> bool:
+ """Return whether a listed sandbox can be attached.
+
+ Recoverable error sandboxes can be recovered; unrecoverable
+ error sandboxes are ignored so a fresh sandbox can be created.
+ """
+ state = _state_value(sandbox.state)
+ if state == "error":
+ return bool(sandbox.recoverable)
+ return state in {
+ "started",
+ "stopped",
+ "starting",
+ "stopping",
+ "pausing",
+ "paused",
+ "resuming",
+ }
+
+ async def _ensure_existing_sandbox_ready(self) -> None:
+ """Start or recover an existing sandbox when needed.
+
+ Daytona exposes different state transitions for stopped,
+ paused, pausing, stopping, starting, resuming and recoverable error
+ sandboxes. This method normalizes those states into a running
+ sandbox before bootstrap / gateway setup continues.
+ """
+ state = _state_value(self._sandbox.state)
+ if state == "error":
+ await self._sandbox.recover(timeout=self.timeout_seconds)
+ elif state in {"stopped", "paused"}:
+ await self._sandbox.start(timeout=self.timeout_seconds)
+ elif state in {"stopping", "pausing"}:
+ await self._sandbox.wait_for_sandbox_stop(
+ timeout=self.timeout_seconds,
+ )
+ await self._sandbox.start(timeout=self.timeout_seconds)
+ elif state in {"starting", "resuming"}:
+ await self._sandbox.wait_for_sandbox_start(
+ timeout=self.timeout_seconds,
+ )
+
+ await self._sandbox.refresh_data()
+
+ def _create_params(self) -> Any:
+ """Build Daytona create params from initialized workspace config.
+
+ The first release keeps the config surface intentionally
+ minimal and aligned with E2B. Snapshot/image/language/TTL are
+ not exposed here; Daytona defaults apply. AgentScope sets
+ ``public=False`` explicitly and uses its own manager TTL.
+ """
+ from daytona import CreateSandboxFromSnapshotParams
+
+ labels = {
+ METADATA_WORKSPACE_ID_KEY: self.workspace_id,
+ **self.sandbox_metadata,
+ }
+ kwargs: dict[str, Any] = {
+ "labels": labels,
+ "public": False,
+ }
+ if self.env:
+ kwargs["env_vars"] = self.env
+ if self.os_user is not None:
+ kwargs["os_user"] = self.os_user
+ return CreateSandboxFromSnapshotParams(**kwargs)
+
+ # ── internals: SDK paths / bootstrap ────────────────────────
+
+ async def _derive_sdk_paths(self) -> None:
+ """Derive gateway paths from Daytona SDK path APIs.
+
+ Daytona docs show common ``/home/daytona`` examples, but the
+ SDK is the source of truth. AgentScope's shared workspace layout
+ derives from ``self.workdir`` via :class:`WorkspaceBase`; only
+ Daytona-specific gateway/runtime paths are set here.
+ """
+ self.workdir = await self._sandbox.get_work_dir()
+ self._user_home = await self._sandbox.get_user_home_dir()
+
+ self._gateway_home = posixpath.join(
+ self._user_home,
+ GATEWAY_HOME_NAME,
+ )
+ self._uv_bin = posixpath.join(self._user_home, ".local", "bin", "uv")
+
+ def _bootstrap_commands(self) -> list[str]:
+ """Provisioning commands for a fresh Daytona sandbox.
+
+ The shared sandbox base runs these only when the gateway script
+ is missing, then uploads the glob helper and gateway script.
+ Every step is idempotent so an interrupted bootstrap re-runs
+ cleanly. Path anchors come from the Daytona SDK, so the sequence
+ does not assume a fixed OS user or home directory.
+
+ ``--no-deps`` on agentscope is mandatory for the same reason as
+ E2B: the gateway only imports :class:`agentscope.mcp.MCPClient`,
+ whose transitive needs are already covered by the gateway base
+ requirements. Pulling the full dependency tree would make first
+ bootstrap slower and more fragile in minimal snapshots.
+
+ Returns:
+ `list[str]`:
+ Shell command strings executed in order through
+ ``["sh", "-c", command]``.
+ """
+ pip_pkgs = list(_GATEWAY_BASE_REQUIREMENTS) + list(self.extra_pip)
+ # Quote every requirement so entries with spaces or shell
+ # metacharacters cannot break the command or become an injection
+ # vector inside the sandbox.
+ pip_args = " ".join(shlex.quote(pkg) for pkg in pip_pkgs)
+ uv_install_dir = f"{self._user_home}/.local/bin"
+
+ return [
+ # 1. Install ripgrep for the Grep builtin tool. Daytona
+ # snapshots may run as non-root users, so use sudo here
+ # and avoid assuming the SDK-selected OS user is root.
+ "sudo apt-get update -qq "
+ "&& sudo apt-get install -y --no-install-recommends ripgrep "
+ "&& sudo rm -rf /var/lib/apt/lists/*",
+ # 2. Astral uv — same shell installer as Docker/E2B. The
+ # SDK-reported user home is the install root so we do not
+ # assume /home/daytona or any fixed OS user.
+ f"curl -LsSf https://astral.sh/uv/install.sh "
+ f"| env UV_INSTALL_DIR={shlex.quote(uv_install_dir)} "
+ f"INSTALLER_NO_MODIFY_PATH=1 sh",
+ # 3. Gateway venv + base requirements.
+ f"{shlex.quote(self._uv_bin)} venv "
+ f"{shlex.quote(self._gateway_venv)}",
+ f"{shlex.quote(self._uv_bin)} pip install --python "
+ f"{shlex.quote(self._gateway_python)} {pip_args}",
+ # 4. agentscope itself.
+ f"{shlex.quote(self._uv_bin)} pip install --python "
+ f"{shlex.quote(self._gateway_python)} --no-deps 'agentscope'",
+ ]
+
+
+# ── SDK response helpers ──────────────────────────────────────────
+
+
+def _state_value(state: Any) -> str:
+ """Normalize SDK enum/string sandbox states."""
+ value = getattr(state, "value", state)
+ return "" if value is None else str(value).lower()
+
+
+def _candidate_sort_key(sandbox: Any) -> str:
+ """Newest-first sort key for duplicate SDK candidates."""
+ return str(
+ sandbox.last_activity_at
+ or sandbox.updated_at
+ or sandbox.created_at
+ or sandbox.id,
+ )
diff --git a/src/agentscope/workspace/_sandboxed_base.py b/src/agentscope/workspace/_sandboxed_base.py
index 279c10ca1..d89a47a01 100644
--- a/src/agentscope/workspace/_sandboxed_base.py
+++ b/src/agentscope/workspace/_sandboxed_base.py
@@ -61,6 +61,12 @@ class SandboxedWorkspaceBase(WorkspaceBase):
_gateway: GatewayClient | None
"""Workspace-side gateway facade. ``None`` before init / after close."""
+ is_alive: bool
+ """Inherited lifecycle flag, repeated for file-scoped type checks."""
+
+ _mcps: list[MCPClient]
+ """Inherited MCP handle list, repeated for file-scoped type checks."""
+
_bootstrap_cmd_timeout: float = 1800.0
"""Per-command timeout applied to every :meth:`_setup_mcp_gateway`
bootstrap step. Subclasses lower this for lighter base images
@@ -409,11 +415,19 @@ class SandboxedWorkspaceBase(WorkspaceBase):
_read_gateway_script_bytes(),
)
- # Launch. ``pkill`` clears any gateway left running by a
- # previous resume so the new one can bind the port cleanly.
- # The gateway reads ``.mcp`` directly — no separate config file.
+ # Clear any gateway left running by a previous resume so the
+ # new one can bind the port cleanly. Keep this in a separate
+ # shell command from launch: some providers expose the full
+ # launch shell command line to ``pkill -f``, which would also
+ # contain the gateway script path and terminate the launch
+ # before ``nohup`` starts.
+ await backend.exec_shell(
+ ["sh", "-c", "pkill -f '[_]mcp_gateway_app.py' || true"],
+ )
+
+ # Launch. The gateway reads ``.mcp`` directly — no separate
+ # config file.
launch_cmd = (
- "pkill -f _mcp_gateway_app.py || true; "
f"nohup {shlex.quote(self._gateway_python)} -u "
f"{shlex.quote(self._gateway_script)} "
f"--config {shlex.quote(self._mcp_file)} "
diff --git a/tests/_daytona_live_utils.py b/tests/_daytona_live_utils.py
new file mode 100644
index 000000000..ba8308ed3
--- /dev/null
+++ b/tests/_daytona_live_utils.py
@@ -0,0 +1,50 @@
+# -*- coding: utf-8 -*-
+"""Shared helpers for optional live Daytona tests."""
+
+import os
+import uuid
+
+from agentscope.workspace._daytona._constants import METADATA_WORKSPACE_ID_KEY
+
+DAYTONA_API_KEY = os.getenv("DAYTONA_API_KEY", "")
+DAYTONA_API_URL = os.getenv("DAYTONA_API_URL", "")
+DAYTONA_TARGET = os.getenv("DAYTONA_TARGET", "")
+SKIP_REASON = "DAYTONA_API_KEY environment variable is not set"
+
+
+def live_daytona_workspace_id(prefix: str) -> str:
+ """Return a unique provider label value for one live Daytona test."""
+ return f"{prefix}-{uuid.uuid4().hex}"
+
+
+def live_daytona_kwargs() -> dict[str, str]:
+ """Connection kwargs shared by live Daytona tests."""
+ return {
+ "api_key": os.getenv("DAYTONA_API_KEY", ""),
+ "api_url": os.getenv("DAYTONA_API_URL", ""),
+ "target": os.getenv("DAYTONA_TARGET", ""),
+ }
+
+
+async def delete_live_daytona_workspace(workspace_id: str) -> None:
+ """Delete one live test sandbox by AgentScope workspace label."""
+ from daytona import AsyncDaytona, DaytonaConfig, ListSandboxesQuery
+
+ config = {
+ key: value for key, value in live_daytona_kwargs().items() if value
+ }
+ client = (
+ AsyncDaytona(DaytonaConfig(**config)) if config else AsyncDaytona()
+ )
+ try:
+ query = ListSandboxesQuery(
+ labels={METADATA_WORKSPACE_ID_KEY: workspace_id},
+ )
+ async for sandbox in client.list(query):
+ try:
+ await sandbox.stop(timeout=60, force=True)
+ except Exception:
+ pass
+ await sandbox.delete(timeout=60)
+ finally:
+ await client.close()
diff --git a/tests/backend_daytona_test.py b/tests/backend_daytona_test.py
new file mode 100644
index 000000000..9dc8c0463
--- /dev/null
+++ b/tests/backend_daytona_test.py
@@ -0,0 +1,222 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Test cases for :class:`DaytonaBackend`.
+
+A live smoke suite exercises the real SDK mapping and is skipped unless
+``DAYTONA_API_KEY`` is set.
+"""
+
+import unittest
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from unittest.async_case import IsolatedAsyncioTestCase
+
+from _daytona_live_utils import (
+ DAYTONA_API_KEY,
+ SKIP_REASON,
+ delete_live_daytona_workspace,
+ live_daytona_kwargs,
+ live_daytona_workspace_id,
+)
+
+from agentscope.workspace import DaytonaBackend, DaytonaWorkspace
+
+
[email protected](DAYTONA_API_KEY, SKIP_REASON)
+class TestDaytonaBackendLive(IsolatedAsyncioTestCase):
+ """Live Daytona backend parity, skipped without credentials."""
+
+ @asynccontextmanager
+ async def _live_backend(
+ self,
+ suffix: str,
+ ) -> AsyncIterator[tuple[DaytonaWorkspace, DaytonaBackend]]:
+ """Create one live workspace and yield its backend."""
+ workspace_id = live_daytona_workspace_id(suffix)
+ workspace = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **live_daytona_kwargs(),
+ )
+ try:
+ await workspace.initialize()
+ backend = workspace._backend
+ self.assertIsInstance(backend, DaytonaBackend)
+ yield workspace, backend
+ finally:
+ await workspace.close()
+ await delete_live_daytona_workspace(workspace_id)
+
+ # ── exec ───────────────────────────────────────────────────────
+
+ async def test_exec_returns_stdout(self) -> None:
+ """A program's stdout/exit code are captured into ``ExecResult``."""
+ async with self._live_backend("daytona-live-exec-stdout") as (
+ _workspace,
+ backend,
+ ):
+ result = await backend.exec_shell(["echo", "hello daytona"])
+
+ self.assertTrue(result.ok())
+ self.assertEqual(result.stdout.decode().strip(), "hello daytona")
+ self.assertEqual(result.stderr, b"")
+
+ async def test_exec_nonzero_exit(self) -> None:
+ """A non-zero command exit is reported as a normal result."""
+ async with self._live_backend("daytona-live-exec-nonzero") as (
+ _workspace,
+ backend,
+ ):
+ result = await backend.exec_shell(
+ ["sh", "-c", "printf daytona-oops; exit 4"],
+ )
+
+ self.assertEqual(result.exit_code, 4)
+ self.assertIn("daytona-oops", result.stdout.decode())
+ self.assertEqual(result.stderr, b"")
+
+ async def test_exec_argv_quoting_preserved(self) -> None:
+ """An argv element with metacharacters survives SDK command mapping."""
+ tricky = "a b $(echo x) | ;"
+ async with self._live_backend("daytona-live-exec-argv") as (
+ _workspace,
+ backend,
+ ):
+ result = await 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."""
+ async with self._live_backend("daytona-live-exec-cwd") as (
+ workspace,
+ backend,
+ ):
+ result = await backend.exec_shell(["pwd"])
+
+ self.assertTrue(result.ok())
+ self.assertEqual(result.stdout.decode().strip(), workspace.workdir)
+
+ # ── file I/O ───────────────────────────────────────────────────
+
+ async def test_write_then_read_roundtrip(self) -> None:
+ """Bytes written into the sandbox are read back verbatim."""
+ async with self._live_backend("daytona-live-file-roundtrip") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/roundtrip.txt"
+ payload = b"hello\nworld\n"
+ await backend.write_file(path, payload)
+ self.assertEqual(await backend.read_file(path), payload)
+
+ async def test_write_creates_parent_dirs(self) -> None:
+ """``write_file`` creates missing parent directories."""
+ async with self._live_backend("daytona-live-file-parent") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/a/b/c/file.txt"
+ await backend.write_file(path, b"x")
+ self.assertEqual(await backend.read_file(path), b"x")
+
+ async def test_write_preserves_binary(self) -> None:
+ """Raw bytes survive the Daytona file upload/download round-trip."""
+ async with self._live_backend("daytona-live-file-binary") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/bin.dat"
+ payload = b"a\r\nb\x00\xffc"
+ await backend.write_file(path, payload)
+ self.assertEqual(await backend.read_file(path), payload)
+
+ async def test_read_missing_file_raises(self) -> None:
+ """Reading a non-existent file raises ``FileNotFoundError``."""
+ async with self._live_backend("daytona-live-file-missing") as (
+ workspace,
+ backend,
+ ):
+ with self.assertRaises(FileNotFoundError):
+ await backend.read_file(f"{workspace.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."""
+ async with self._live_backend("daytona-live-helper-exists") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/f.txt"
+ await backend.write_file(path, b"x")
+ self.assertTrue(await backend.file_exists(path))
+ self.assertTrue(await backend.file_exists(workspace.workdir))
+ self.assertTrue(await backend.is_dir(workspace.workdir))
+ self.assertFalse(await backend.is_dir(path))
+ self.assertFalse(
+ await backend.file_exists(f"{workspace.workdir}/missing"),
+ )
+
+ async def test_list_dir(self) -> None:
+ """Non-recursive ``list_dir`` returns immediate child base names."""
+ async with self._live_backend("daytona-live-helper-list") as (
+ workspace,
+ backend,
+ ):
+ base = f"{workspace.workdir}/listing"
+ await backend.write_file(f"{base}/a.txt", b"x")
+ await backend.write_file(f"{base}/b.txt", b"x")
+ entries = await backend.list_dir(base)
+
+ self.assertEqual(sorted(entries), ["a.txt", "b.txt"])
+
+ async def test_list_dir_recursive(self) -> None:
+ """Recursive ``list_dir`` returns file paths underneath the root."""
+ async with self._live_backend("daytona-live-helper-recursive") as (
+ workspace,
+ backend,
+ ):
+ base = f"{workspace.workdir}/rec"
+ await backend.write_file(f"{base}/top.txt", b"x")
+ await backend.write_file(f"{base}/sub/nested.txt", b"x")
+ entries = await backend.list_dir(base, recursive=True)
+
+ basenames = sorted(e.rsplit("/", 1)[-1] for e in entries)
+ self.assertEqual(basenames, ["nested.txt", "top.txt"])
+
+ async def test_stat_mtime(self) -> None:
+ """``stat_mtime`` returns a float for an existing path, None else."""
+ async with self._live_backend("daytona-live-helper-stat") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/stat.txt"
+ await backend.write_file(path, b"x")
+ mtime = await backend.stat_mtime(path)
+ missing = await backend.stat_mtime(f"{workspace.workdir}/missing")
+
+ self.assertIsInstance(mtime, float)
+ self.assertIsNone(missing)
+
+ async def test_delete_path(self) -> None:
+ """``delete_path`` removes files and trees; missing is a no-op."""
+ async with self._live_backend("daytona-live-helper-delete") as (
+ workspace,
+ backend,
+ ):
+ path = f"{workspace.workdir}/to_delete.txt"
+ await backend.write_file(path, b"x")
+ await backend.delete_path(path)
+ self.assertFalse(await backend.file_exists(path))
+
+ tree = f"{workspace.workdir}/tree"
+ await backend.write_file(f"{tree}/deep/f.txt", b"x")
+ await backend.delete_path(tree)
+ self.assertFalse(await backend.file_exists(tree))
+
+ await backend.delete_path(f"{workspace.workdir}/missing")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/docker/k8s_workspace_test.Dockerfile b/tests/docker/k8s_workspace_test.Dockerfile
index d5067bae0..8b51f213f 100644
--- a/tests/docker/k8s_workspace_test.Dockerfile
+++ b/tests/docker/k8s_workspace_test.Dockerfile
@@ -64,4 +64,3 @@ WORKDIR /workspace
# Container has nothing to run by itself — K8s Pod spec will override CMD
# with the sleep loop from ``_build_pod_spec``.
CMD ["sleep", "infinity"]
-
diff --git a/tests/workspace_daytona_test.py b/tests/workspace_daytona_test.py
new file mode 100644
index 000000000..e0c8f7817
--- /dev/null
+++ b/tests/workspace_daytona_test.py
@@ -0,0 +1,1714 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Test cases for :class:`DaytonaWorkspace`.
+
+Most tests patch the Daytona SDK boundary so they run in normal CI.
+Live tests are opt-in via ``DAYTONA_API_KEY``.
+"""
+
+import asyncio
+import json
+import os
+import shlex
+import shutil
+import sys
+import tempfile
+import types
+import unittest
+from collections.abc import AsyncIterator, Callable
+from contextlib import asynccontextmanager
+from enum import Enum
+from types import SimpleNamespace
+from typing import Any
+from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import patch
+
+from _daytona_live_utils import (
+ DAYTONA_API_KEY,
+ SKIP_REASON,
+ delete_live_daytona_workspace,
+ live_daytona_kwargs,
+ live_daytona_workspace_id,
+)
+
+from agentscope.agent import ContextConfig, ReActConfig
+from agentscope.app._manager import BackgroundTaskManager, SchedulerManager
+from agentscope.app._service import ResourceAccessService, get_toolkit
+from agentscope.app.access import DenyAllResourceAccessPolicy
+from agentscope.app.storage import (
+ AgentData,
+ AgentRecord,
+ SessionConfig,
+ SessionRecord,
+)
+from agentscope.mcp import MCPClient, StdioMCPConfig
+from agentscope.message import (
+ Base64Source,
+ DataBlock,
+ TextBlock,
+ ToolCallBlock,
+ ToolResultBlock,
+ ToolResultState,
+ UserMsg,
+)
+from agentscope.permission import PermissionMode
+from agentscope.state import AgentState
+from agentscope.tool import ToolResponse
+from agentscope.workspace import DaytonaBackend, DaytonaWorkspace
+from agentscope.workspace import _sandboxed_base as sandboxed_mod
+from agentscope.workspace._daytona._constants import (
+ DEFAULT_GATEWAY_PORT,
+ METADATA_WORKSPACE_ID_KEY,
+)
+from agentscope.workspace._utils import _GATEWAY_BASE_REQUIREMENTS
+
+
+class _NullBus:
+ """Message bus placeholder for service toolkit assembly."""
+
+
+class _NoOpStorage:
+ """Storage placeholder for tools that only bind the reference."""
+
+ async def list_agents(self, _user_id: str) -> list[AgentRecord]:
+ """No invitable agents in toolkit assembly tests."""
+ return []
+
+
+class _NoOpWorkspaceManager:
+ """Workspace manager placeholder for toolkit assembly tests."""
+
+
+class _FakeProcess:
+ """Daytona process fake."""
+
+ def __init__(self) -> None:
+ self.commands: list[str] = []
+ self.fs: Any = None
+
+ async def exec(self, command: str, **_kwargs: object) -> object:
+ """Record command and return success."""
+ self.commands.append(command)
+ args = shlex.split(command)
+ # ``DaytonaBackend`` appends a ``2>&1`` redirection to every
+ # command; a real shell consumes it, so drop it before parsing.
+ if args and args[-1] == "2>&1":
+ args = args[:-1]
+ exit_code = 0
+ if self.fs is not None and args[:2] == ["mkdir", "-p"]:
+ self.fs.dirs.update(args[2:])
+ elif self.fs is not None and args[:2] == ["test", "-e"]:
+ path = args[2]
+ exit_code = 0 if self.fs.exists(path) else 1
+ elif self.fs is not None and args[:2] == ["test", "-d"]:
+ path = args[2]
+ exit_code = 0 if path in self.fs.dirs else 1
+ return SimpleNamespace(
+ exit_code=exit_code,
+ result="",
+ artifacts=SimpleNamespace(stdout=""),
+ additional_properties={},
+ )
+
+
+class _FakeFS:
+ """Daytona fs fake."""
+
+ def __init__(self) -> None:
+ self.files: dict[str, bytes] = {}
+ self.dirs: set[str] = set()
+
+ def exists(self, path: str) -> bool:
+ """Return whether a fake file or directory exists."""
+ return path in self.files or path in self.dirs
+
+ async def download_file(self, path: str) -> bytes:
+ """Return stored file bytes."""
+ if path not in self.files:
+ raise FileNotFoundError(path)
+ return self.files[path]
+
+ async def upload_file(self, file: bytes, remote_path: str) -> None:
+ """Store uploaded bytes."""
+ parent = os.path.dirname(remote_path)
+ if parent:
+ self.dirs.add(parent)
+ self.files[remote_path] = file
+
+
+class _FakeSandbox:
+ """Daytona sandbox fake for workspace tests."""
+
+ def __init__(
+ self,
+ sandbox_id: str = "sandbox-1",
+ *,
+ state: str = "started",
+ recoverable: bool | None = None,
+ workdir: str = "/home/daytona",
+ user_home: str = "/home/daytona",
+ ) -> None:
+ self.id = sandbox_id
+ self.name = sandbox_id
+ self.state = state
+ self.recoverable = recoverable
+ self.workdir = workdir
+ self.user_home = user_home
+ self.labels: dict[str, str] = {}
+ self.created_at = f"2026-01-01T00:00:00Z-{sandbox_id}"
+ self.updated_at: str | None = None
+ self.last_activity_at: str | None = None
+ self.fs = _FakeFS()
+ self.process = _FakeProcess()
+ self.process.fs = self.fs
+ self.started = False
+ self.recovered = False
+ self.stopped: list[dict[str, object]] = []
+ self.waited_for_stop = False
+
+ async def get_work_dir(self) -> str:
+ """Return SDK-derived workdir."""
+ return self.workdir
+
+ async def get_user_home_dir(self) -> str:
+ """Return SDK-derived user home."""
+ return self.user_home
+
+ async def start(self, timeout: float | None = 60) -> None:
+ """Mark sandbox started."""
+ del timeout
+ self.started = True
+ self.state = "started"
+
+ async def recover(self, timeout: float | None = 60) -> None:
+ """Mark sandbox recovered."""
+ del timeout
+ self.recovered = True
+ self.state = "started"
+
+ async def stop(
+ self,
+ timeout: float | None = 60,
+ force: bool = False,
+ ) -> None:
+ """Record graceful stop."""
+ self.stopped.append({"timeout": timeout, "force": force})
+ self.state = "stopped"
+
+ async def wait_for_sandbox_start(
+ self,
+ timeout: float | None = 60,
+ ) -> None:
+ """No-op wait hook."""
+ del timeout
+
+ async def wait_for_sandbox_stop(
+ self,
+ timeout: float | None = 60,
+ ) -> None:
+ """Mark stop wait."""
+ del timeout
+ self.waited_for_stop = True
+ self.state = "stopped"
+
+ async def refresh_data(self) -> None:
+ """No-op refresh hook."""
+
+
+class _MappedProcess:
+ """Execute Daytona process commands against a mapped local directory."""
+
+ def __init__(self, host_root: str, sandbox_root: str) -> None:
+ self.host_root = host_root
+ self.sandbox_root = sandbox_root
+
+ def _to_host(self, value: str | None) -> str | None:
+ if value is None:
+ return None
+ return value.replace(self.sandbox_root, self.host_root)
+
+ def _to_sandbox(self, value: str) -> str:
+ return value.replace(self.host_root, self.sandbox_root)
+
+ async def exec(
+ self,
+ command: str,
+ cwd: str | None = None,
+ timeout: float | None = None,
+ ) -> object:
+ """Run the shell command locally with path translation."""
+ mapped_command = self._to_host(command)
+ assert mapped_command is not None
+ mapped_cwd = self._to_host(cwd) or self.host_root
+ env = dict(os.environ)
+ env["PATH"] = (
+ os.path.dirname(sys.executable) + os.pathsep + env.get("PATH", "")
+ )
+ proc = await asyncio.create_subprocess_shell(
+ mapped_command,
+ cwd=mapped_cwd,
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ env=env,
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(
+ proc.communicate(),
+ timeout=timeout,
+ )
+ except asyncio.TimeoutError:
+ proc.kill()
+ await proc.communicate()
+ return SimpleNamespace(
+ exit_code=-1,
+ result="",
+ artifacts=SimpleNamespace(stdout=""),
+ additional_properties={},
+ )
+ stdout_text = self._to_sandbox(stdout.decode("utf-8", "replace"))
+ stderr_text = self._to_sandbox(stderr.decode("utf-8", "replace"))
+ result = stdout_text + stderr_text
+ return SimpleNamespace(
+ exit_code=proc.returncode,
+ result=result,
+ artifacts=SimpleNamespace(stdout=result),
+ additional_properties={},
+ )
+
+
+class _MappedFS:
+ """Daytona fs fake backed by local files."""
+
+ def __init__(self, host_root: str, sandbox_root: str) -> None:
+ self.host_root = host_root
+ self.sandbox_root = sandbox_root
+
+ def _to_host(self, path: str) -> str:
+ return path.replace(self.sandbox_root, self.host_root)
+
+ async def download_file(self, path: str) -> bytes:
+ """Read mapped file bytes."""
+ host_path = self._to_host(path)
+ if not os.path.exists(host_path):
+ raise FileNotFoundError(path)
+ with open(host_path, "rb") as f:
+ return f.read()
+
+ async def upload_file(self, file: bytes, remote_path: str) -> None:
+ """Write mapped file bytes."""
+ host_path = self._to_host(remote_path)
+ os.makedirs(os.path.dirname(host_path), exist_ok=True)
+ with open(host_path, "wb") as f:
+ f.write(file)
+
+
+class _MappedSandbox(_FakeSandbox):
+ """Fake Daytona sandbox whose process/fs operate on a temp dir."""
+
+ def __init__(self, host_root: str) -> None:
+ super().__init__("mapped-sandbox")
+ self.host_root = host_root
+ self.sandbox_root = "/home/daytona"
+ self.process = _MappedProcess(host_root, self.sandbox_root)
+ self.fs = _MappedFS(host_root, self.sandbox_root)
+
+ async def get_work_dir(self) -> str:
+ """Return mapped sandbox workdir."""
+ return self.sandbox_root
+
+ async def get_user_home_dir(self) -> str:
+ """Return mapped sandbox home."""
+ return self.sandbox_root
+
+
+class _FakeDaytona:
+ """AsyncDaytona fake."""
+
+ instances: list["_FakeDaytona"] = []
+ list_result: list[_FakeSandbox] = []
+ created_params: list[object] = []
+ configs: list[object] = []
+
+ def __init__(self, config: object | None = None) -> None:
+ self.config = config
+ self.created: list[_FakeSandbox] = []
+ self.closed = False
+ _FakeDaytona.instances.append(self)
+ _FakeDaytona.configs.append(config)
+
+ async def create(
+ self,
+ params: object | None = None,
+ **_kwargs: object,
+ ) -> _FakeSandbox:
+ """Create and return a fake sandbox."""
+ _FakeDaytona.created_params.append(params)
+ sandbox = _FakeSandbox(f"sandbox-created-{len(self.created) + 1}")
+ self.created.append(sandbox)
+ return sandbox
+
+ async def get(self, sandbox_id: str) -> _FakeSandbox:
+ """Return a fake sandbox by id."""
+ for sandbox in _FakeDaytona.list_result:
+ if sandbox.id == sandbox_id:
+ return sandbox
+ return _FakeSandbox(sandbox_id)
+
+ async def list(
+ self,
+ query: object | None = None,
+ ) -> AsyncIterator[_FakeSandbox]:
+ """Return fake candidates, filtered by labels when possible."""
+ labels = getattr(query, "labels", None)
+ if labels:
+ candidates = (
+ sandbox
+ for sandbox in _FakeDaytona.list_result
+ if all(sandbox.labels.get(k) == v for k, v in labels.items())
+ )
+ else:
+ candidates = iter(_FakeDaytona.list_result)
+ for sandbox in candidates:
+ yield sandbox
+
+ async def close(self) -> None:
+ """Mark SDK client closed."""
+ self.closed = True
+
+
+class _FakeCreateSandboxFromSnapshotParams:
+ """Capture Daytona create params without importing the real SDK."""
+
+ def __init__(self, **kwargs: object) -> None:
+ self.kwargs = kwargs
+
+
+class _FakeDaytonaConfig:
+ """Capture Daytona config values."""
+
+ def __init__(self, **kwargs: object) -> None:
+ self.kwargs = kwargs
+
+
+class _FakeDaytonaNotFoundError(Exception):
+ """Fake Daytona structured not-found exception."""
+
+
+class _FakeListSandboxesQuery:
+ """Capture list filters."""
+
+ def __init__(self, **kwargs: object) -> None:
+ self.__dict__.update(kwargs)
+
+
+class _FakeSandboxState(str, Enum):
+ """Subset of Daytona sandbox states used by the workspace."""
+
+ STARTED = "started"
+ STOPPED = "stopped"
+ STARTING = "starting"
+ STOPPING = "stopping"
+ ERROR = "error"
+ PAUSING = "pausing"
+ PAUSED = "paused"
+ RESUMING = "resuming"
+
+
+class _FakeGateway:
+ """GatewayClient fake."""
+
+ instances: list["_FakeGateway"] = []
+
+ def __init__(
+ self,
+ *,
+ backend: DaytonaBackend,
+ gateway_port: int,
+ timeout: float | None = None,
+ inline_limit: int | None = None,
+ tmp_dir: str | None = None,
+ gateway_log_path: str | None = None,
+ ) -> None:
+ self.backend = backend
+ self.gateway_port = gateway_port
+ self.timeout = timeout
+ self.inline_limit = inline_limit
+ self.tmp_dir = tmp_dir
+ self.gateway_log_path = gateway_log_path
+ self.closed = False
+ _FakeGateway.instances.append(self)
+
+ async def health(self) -> bool:
+ """Always healthy."""
+ return True
+
+ async def list_mcps(self) -> list[MCPClient]:
+ """Read persisted MCP specs from the fake sandbox."""
+ path = self.backend.join_path(self.backend._workdir, ".mcp")
+ try:
+ raw = await self.backend.read_file(path)
+ except FileNotFoundError:
+ return []
+ specs = json.loads(raw.decode("utf-8"))
+ return [MCPClient.model_validate(spec) for spec in specs]
+
+ async def aclose(self) -> None:
+ """Mark closed."""
+ self.closed = True
+
+ def make_client(self, spec: dict[str, object]) -> MCPClient:
+ """Build a regular MCP client from spec for add_mcp tests."""
+ return _FakeGatewayMCPClient(spec)
+
+
+class _FakeGatewayMCPClient:
+ """Small gateway MCP client fake for add/remove tests."""
+
+ def __init__(self, spec: dict[str, object]) -> None:
+ self._spec = spec
+ self.name = str(spec["name"])
+ self.connected = False
+ self.closed = False
+
+ def model_dump(self, mode: str = "python") -> dict[str, object]:
+ """Return the original MCP spec for persistence."""
+ del mode
+ return self._spec
+
+ async def connect(self) -> None:
+ """Mark connected."""
+ self.connected = True
+
+ async def close(self) -> None:
+ """Mark closed."""
+ self.closed = True
+
+
+def _install_fake_daytona_module() -> types.ModuleType:
+ """Install a fake ``daytona`` module into ``sys.modules``."""
+ mod = types.ModuleType("daytona")
+ mod.AsyncDaytona = _FakeDaytona
+ mod.DaytonaConfig = _FakeDaytonaConfig
+ mod.CreateSandboxFromSnapshotParams = _FakeCreateSandboxFromSnapshotParams
+ mod.ListSandboxesQuery = _FakeListSandboxesQuery
+ mod.SandboxState = _FakeSandboxState
+ mod.DaytonaError = RuntimeError
+ mod.DaytonaNotFoundError = _FakeDaytonaNotFoundError
+ sys.modules["daytona"] = mod
+ return mod
+
+
+class TestDaytonaBootstrapHelpers(IsolatedAsyncioTestCase):
+ """Bootstrap command rendering via ``_bootstrap_commands``."""
+
+ @staticmethod
+ def _workspace_with_paths(
+ *,
+ user_home: str,
+ extra_pip: list[str],
+ ) -> DaytonaWorkspace:
+ """Build a workspace with the SDK-derived bootstrap paths set.
+
+ Binds a backend so the base-class gateway path properties
+ (``_gateway_venv`` / ``_gateway_python``) resolve without a live
+ sandbox, then sets the SDK-derived anchors directly.
+ """
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-bootstrap",
+ extra_pip=extra_pip,
+ )
+ workspace._backend = DaytonaBackend(None, workdir=user_home)
+ workspace._user_home = user_home
+ workspace._gateway_home = f"{user_home}/.agentscope"
+ workspace._uv_bin = f"{user_home}/.local/bin/uv"
+ return workspace
+
+ async def test_bootstrap_commands_include_tools_and_extra_pip(
+ self,
+ ) -> None:
+ """Bootstrap commands provision tools, venv and packages."""
+ workspace = self._workspace_with_paths(
+ user_home="/home/daytona",
+ extra_pip=["extra-a", "extra-b"],
+ )
+
+ commands = workspace._bootstrap_commands()
+
+ self.assertEqual(len(commands), 5)
+ self.assertIn("apt-get install", commands[0])
+ self.assertIn("ripgrep", commands[0])
+ self.assertIn("UV_INSTALL_DIR=/home/daytona/.local/bin", commands[1])
+ self.assertEqual(
+ commands[2],
+ "/home/daytona/.local/bin/uv venv "
+ "/home/daytona/.agentscope/.venv",
+ )
+ for package in (*_GATEWAY_BASE_REQUIREMENTS, "extra-a", "extra-b"):
+ self.assertIn(package, commands[3])
+ self.assertIn("--no-deps 'agentscope'", commands[4])
+
+ async def test_bootstrap_commands_quote_shell_arguments(self) -> None:
+ """SDK-derived paths and extra packages are shell-quoted."""
+ workspace = self._workspace_with_paths(
+ user_home="/home/day tona",
+ extra_pip=["safe-pkg", "bad; echo injected"],
+ )
+
+ commands = workspace._bootstrap_commands()
+
+ self.assertIn(
+ "UV_INSTALL_DIR='/home/day tona/.local/bin'",
+ commands[1],
+ )
+ self.assertEqual(
+ commands[2],
+ "'/home/day tona/.local/bin/uv' venv "
+ "'/home/day tona/.agentscope/.venv'",
+ )
+ self.assertIn("'bad; echo injected'", commands[3])
+
+
+class _DaytonaWorkspaceMockBase(IsolatedAsyncioTestCase):
+ """Shared fake-SDK fixture for Daytona workspace mock tests."""
+
+ async def asyncSetUp(self) -> None:
+ """Patch Daytona and gateway boundaries."""
+ _FakeDaytona.instances.clear()
+ _FakeDaytona.list_result.clear()
+ _FakeDaytona.created_params.clear()
+ _FakeDaytona.configs.clear()
+ _FakeGateway.instances.clear()
+ self.fake_daytona_mod = _install_fake_daytona_module()
+ self.gateway_patch = patch.object(
+ sandboxed_mod,
+ "GatewayClient",
+ _FakeGateway,
+ )
+ self.gateway_patch.start()
+ self.bootstrap_patch = patch.object(
+ DaytonaWorkspace,
+ "_bootstrap_commands",
+ return_value=[],
+ )
+ self.bootstrap_patch.start()
+
+ async def asyncTearDown(self) -> None:
+ """Undo patches."""
+ self.bootstrap_patch.stop()
+ self.gateway_patch.stop()
+ sys.modules.pop("daytona", None)
+
+
+class TestDaytonaWorkspaceMock(_DaytonaWorkspaceMockBase):
+ """Workspace lifecycle and configuration tests with a fake SDK."""
+
+ async def test_create_uses_minimal_params_and_sdk_paths(self) -> None:
+ """Create passes labels/env and the secure public default."""
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-1",
+ api_key="key",
+ api_url="https://daytona.example/api",
+ target="us",
+ env={"A": "B"},
+ sandbox_metadata={"team": "agents"},
+ )
+
+ await workspace.initialize()
+
+ self.assertEqual(workspace.workdir, "/home/daytona")
+ self.assertEqual(workspace._user_home, "/home/daytona")
+ self.assertIsInstance(workspace._backend, DaytonaBackend)
+ self.assertEqual(
+ _FakeDaytona.configs[0].kwargs,
+ {
+ "api_key": "key",
+ "api_url": "https://daytona.example/api",
+ "target": "us",
+ },
+ )
+ params = _FakeDaytona.created_params[0]
+ self.assertIsInstance(params, _FakeCreateSandboxFromSnapshotParams)
+ self.assertEqual(
+ params.kwargs,
+ {
+ "env_vars": {"A": "B"},
+ "labels": {
+ METADATA_WORKSPACE_ID_KEY: "wid-1",
+ "team": "agents",
+ },
+ "public": False,
+ },
+ )
+
+ async def test_create_passes_os_user_only_when_configured(self) -> None:
+ """Explicit ``os_user`` is forwarded to Daytona create params."""
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-os-user",
+ os_user="daytona",
+ )
+
+ await workspace.initialize()
+
+ params = _FakeDaytona.created_params[0]
+ self.assertEqual(params.kwargs["os_user"], "daytona")
+
+ async def test_initialize_is_idempotent(self) -> None:
+ """Repeated ``initialize`` calls do not create new runtime state."""
+ workspace = DaytonaWorkspace(workspace_id="wid-idempotent")
+
+ await workspace.initialize()
+ await workspace.initialize()
+
+ self.assertTrue(workspace.is_alive)
+ self.assertEqual(len(_FakeDaytona.created_params), 1)
+ self.assertEqual(len(_FakeGateway.instances), 1)
+
+ async def test_empty_config_uses_sdk_environment_defaults(self) -> None:
+ """No explicit connection config means ``AsyncDaytona()``."""
+ workspace = DaytonaWorkspace(workspace_id="wid-2")
+
+ await workspace._get_daytona_client()
+
+ self.assertIsNone(_FakeDaytona.configs[0])
+
+ async def test_initialize_reuses_stopped_candidate_and_starts_it(
+ self,
+ ) -> None:
+ """Stopped candidates are started instead of creating a new one."""
+ candidate = _FakeSandbox("sandbox-old", state="stopped")
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-3"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-3")
+ await workspace.initialize()
+
+ self.assertIs(workspace._sandbox, candidate)
+ self.assertTrue(candidate.started)
+ self.assertEqual(_FakeDaytona.created_params, [])
+
+ async def test_initialize_chooses_newest_duplicate_candidate(self) -> None:
+ """Duplicate usable candidates choose newest and log a warning."""
+ older = _FakeSandbox("sandbox-older", state="started")
+ older.labels = {METADATA_WORKSPACE_ID_KEY: "wid-duplicates"}
+ older.last_activity_at = "2026-01-01T00:00:00Z"
+ newer = _FakeSandbox("sandbox-newer", state="started")
+ newer.labels = {METADATA_WORKSPACE_ID_KEY: "wid-duplicates"}
+ newer.last_activity_at = "2026-01-02T00:00:00Z"
+ _FakeDaytona.list_result[:] = [older, newer]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-duplicates")
+ with self.assertLogs("as", level="WARNING") as logs:
+ await workspace.initialize()
+
+ self.assertIs(workspace._sandbox, newer)
+ self.assertEqual(_FakeDaytona.created_params, [])
+ self.assertIn("2 sandboxes match", "\n".join(logs.output))
+
+ async def test_initialize_waits_for_stopping_candidate_then_starts_it(
+ self,
+ ) -> None:
+ """Stopping candidates are waited to stopped before start."""
+ candidate = _FakeSandbox("sandbox-stopping", state="stopping")
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-stopping"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-stopping")
+ await workspace.initialize()
+
+ self.assertTrue(candidate.waited_for_stop)
+ self.assertTrue(candidate.started)
+
+ async def test_initialize_waits_for_pausing_candidate_then_starts_it(
+ self,
+ ) -> None:
+ """Pausing candidates are waited to stopped before start."""
+ candidate = _FakeSandbox("sandbox-pausing", state="pausing")
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-pausing"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-pausing")
+ await workspace.initialize()
+
+ self.assertIs(workspace._sandbox, candidate)
+ self.assertTrue(candidate.waited_for_stop)
+ self.assertTrue(candidate.started)
+ self.assertEqual(_FakeDaytona.created_params, [])
+
+ async def test_initialize_derives_all_paths_from_sdk_values(self) -> None:
+ """Workspace paths are rooted in SDK workdir and home values."""
+ candidate = _FakeSandbox(
+ "sandbox-custom-paths",
+ workdir="/workspace/project",
+ user_home="/users/daytona",
+ )
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-custom-paths"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-custom-paths")
+ await workspace.initialize()
+
+ self.assertEqual(workspace.workdir, "/workspace/project")
+ self.assertEqual(workspace._user_home, "/users/daytona")
+ self.assertEqual(workspace._data_dir, "/workspace/project/data")
+ self.assertEqual(workspace._skills_dir, "/workspace/project/skills")
+ self.assertEqual(
+ workspace._sessions_dir,
+ "/workspace/project/sessions",
+ )
+ self.assertEqual(workspace._mcp_file, "/workspace/project/.mcp")
+ self.assertEqual(workspace._gateway_home, "/users/daytona/.agentscope")
+ self.assertEqual(
+ workspace._gateway_venv,
+ "/users/daytona/.agentscope/.venv",
+ )
+ self.assertEqual(
+ workspace._gateway_script,
+ "/users/daytona/.agentscope/_mcp_gateway_app.py",
+ )
+ self.assertEqual(
+ workspace._glob_helper_path,
+ "/users/daytona/.agentscope/_glob_helper.py",
+ )
+ self.assertEqual(
+ workspace._gateway_log,
+ "/users/daytona/.agentscope/gateway.log",
+ )
+ self.assertEqual(workspace._uv_bin, "/users/daytona/.local/bin/uv")
+
+ async def test_initialize_recovers_recoverable_error_candidate(
+ self,
+ ) -> None:
+ """Recoverable candidates are recovered before use."""
+ candidate = _FakeSandbox(
+ "sandbox-error",
+ state="error",
+ recoverable=True,
+ )
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-4"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-4")
+ await workspace.initialize()
+
+ self.assertIs(workspace._sandbox, candidate)
+ self.assertTrue(candidate.recovered)
+
+ async def test_initialize_skips_unrecoverable_error_candidate(
+ self,
+ ) -> None:
+ """Unrecoverable candidates are ignored and a new sandbox is made."""
+ candidate = _FakeSandbox(
+ "sandbox-error",
+ state="error",
+ recoverable=False,
+ )
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-5"}
+ _FakeDaytona.list_result[:] = [candidate]
+
+ workspace = DaytonaWorkspace(workspace_id="wid-5")
+ await workspace.initialize()
+
+ self.assertNotEqual(workspace._sandbox.id, "sandbox-error")
+ self.assertEqual(len(_FakeDaytona.created_params), 1)
+
+ async def test_gateway_uses_shared_backend_shim(self) -> None:
+ """GatewayClient receives the Daytona backend, not a preview URL."""
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-6",
+ gateway_port=DEFAULT_GATEWAY_PORT,
+ )
+
+ await workspace.initialize()
+
+ gateway = _FakeGateway.instances[0]
+ self.assertIs(gateway.backend, workspace._backend)
+ self.assertEqual(gateway.gateway_port, DEFAULT_GATEWAY_PORT)
+ self.assertEqual(gateway.timeout, 30.0)
+
+ async def test_list_tools_requires_initialized_backend(self) -> None:
+ """Builtin tools cannot silently fall back to local backend."""
+ workspace = DaytonaWorkspace(workspace_id="wid-7")
+
+ with self.assertRaises(RuntimeError):
+ await workspace.list_tools()
+
+ async def test_list_tools_returns_six_builtin_tools(self) -> None:
+ """Initialized workspace exposes the six builtin tools."""
+ workspace = DaytonaWorkspace(workspace_id="wid-8")
+ await workspace.initialize()
+
+ tools = await workspace.list_tools()
+
+ self.assertEqual(
+ sorted(tool.name for tool in tools),
+ ["Bash", "Edit", "Glob", "Grep", "Read", "Write"],
+ )
+
+ async def test_mcp_file_roundtrip_uses_sdk_workdir(self) -> None:
+ """The persisted ``.mcp`` file is rooted at the SDK workdir."""
+ workspace = DaytonaWorkspace(workspace_id="wid-9")
+ await workspace.initialize()
+ workspace._mcps = [
+ MCPClient(
+ name="demo",
+ mcp_config=StdioMCPConfig(command="node", args=["server.js"]),
+ is_stateful=True,
+ ),
+ ]
+
+ await workspace._save_mcp_file()
+
+ raw = await workspace._backend.read_file("/home/daytona/.mcp")
+ data = json.loads(raw.decode("utf-8"))
+ self.assertEqual(data[0]["name"], "demo")
+
+ async def test_missing_mcp_file_seeds_default_mcps(self) -> None:
+ """Missing persisted MCP config falls back to configured defaults."""
+ default_mcp = MCPClient(
+ name="default",
+ mcp_config=StdioMCPConfig(command="python", args=["server.py"]),
+ is_stateful=True,
+ )
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-default-mcp",
+ default_mcps=[default_mcp],
+ )
+
+ await workspace.initialize()
+
+ self.assertEqual([m.name for m in workspace._mcps], ["default"])
+ raw = await workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(json.loads(raw.decode("utf-8"))[0]["name"], "default")
+
+ async def test_invalid_mcp_file_falls_back_to_default_mcps(self) -> None:
+ """Invalid persisted MCP JSON falls back to configured defaults."""
+ candidate = _FakeSandbox("sandbox-invalid-mcp")
+ candidate.labels = {METADATA_WORKSPACE_ID_KEY: "wid-invalid-mcp"}
+ candidate.fs.files["/home/daytona/.mcp"] = b"{not json"
+ _FakeDaytona.list_result[:] = [candidate]
+ default_mcp = MCPClient(
+ name="fallback",
+ mcp_config=StdioMCPConfig(command="python", args=["server.py"]),
+ is_stateful=True,
+ )
+ workspace = DaytonaWorkspace(
+ workspace_id="wid-invalid-mcp",
+ default_mcps=[default_mcp],
+ )
+
+ await workspace.initialize()
+
+ self.assertEqual([m.name for m in workspace._mcps], ["fallback"])
+ raw = await workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(
+ json.loads(raw.decode("utf-8"))[0]["name"],
+ "fallback",
+ )
+
+ async def test_initialize_bootstrap_error_includes_command_and_output(
+ self,
+ ) -> None:
+ """Bootstrap failures include command, exit code, stderr and stdout."""
+ self.bootstrap_patch.stop()
+ try:
+
+ class _FailingProcess(_FakeProcess):
+ async def exec(
+ self,
+ command: str,
+ **_kwargs: object,
+ ) -> object:
+ self.commands.append(command)
+ # Strip the ``2>&1`` redirection the backend appends.
+ args = shlex.split(command)
+ if args and args[-1] == "2>&1":
+ args = args[:-1]
+ if args == ["sh", "-c", "broken bootstrap"]:
+ return SimpleNamespace(
+ exit_code=9,
+ result="bootstrap stdout",
+ artifacts=SimpleNamespace(stdout=""),
+ additional_properties={},
+ )
+ return await super().exec(command, **_kwargs)
+
+ candidate = _FakeSandbox("sandbox-bootstrap-error")
+ candidate.labels = {
+ METADATA_WORKSPACE_ID_KEY: "wid-bootstrap-error",
+ }
+ candidate.process = _FailingProcess()
+ candidate.process.fs = candidate.fs
+ _FakeDaytona.list_result[:] = [candidate]
+ workspace = DaytonaWorkspace(workspace_id="wid-bootstrap-error")
+
+ with patch.object(
+ DaytonaWorkspace,
+ "_bootstrap_commands",
+ return_value=["broken bootstrap"],
+ ):
+ with self.assertRaisesRegex(
+ RuntimeError,
+ "DaytonaWorkspace bootstrap failed",
+ ) as cm:
+ await workspace.initialize()
+
+ msg = str(cm.exception)
+ self.assertIn("exit 9", msg)
+ self.assertIn("broken bootstrap", msg)
+ self.assertIn("stdout: bootstrap stdout", msg)
+ finally:
+ self.bootstrap_patch.start()
+
+ async def test_close_stops_gracefully_and_clears_runtime_state(
+ self,
+ ) -> None:
+ """``close`` uses graceful stop and releases host-side handles."""
+ workspace = DaytonaWorkspace(workspace_id="wid-10")
+ await workspace.initialize()
+ sandbox = workspace._sandbox
+ gateway = workspace._gateway
+ daytona_client = workspace._daytona
+
+ await workspace.close()
+
+ self.assertEqual(sandbox.stopped, [{"timeout": 300, "force": False}])
+ self.assertTrue(gateway.closed)
+ self.assertTrue(daytona_client.closed)
+ self.assertIsNone(workspace._sandbox)
+ self.assertIsNone(workspace._backend)
+ self.assertIsNone(workspace._gateway)
+ self.assertIsNone(workspace._daytona)
+ self.assertFalse(workspace.is_alive)
+
+
+async def _tool_text(tool: Callable[..., Any], **kwargs: object) -> str:
+ """Call a tool and return the concatenated text content."""
+ result = await tool(**kwargs)
+ chunks = []
+ if hasattr(result, "__aiter__"):
+ async for chunk in result:
+ chunks.append(chunk)
+ else:
+ chunks.append(result)
+ return "\n".join(
+ block.text
+ for chunk in chunks
+ for block in chunk.content
+ if hasattr(block, "text")
+ )
+
+
+class TestDaytonaWorkspaceBuiltinToolsMock(IsolatedAsyncioTestCase):
+ """Exercise all six builtin tools through ``DaytonaBackend``."""
+
+ async def asyncSetUp(self) -> None:
+ """Create a mapped fake sandbox and initialized workspace."""
+ _FakeDaytona.instances.clear()
+ _FakeDaytona.list_result.clear()
+ _FakeDaytona.created_params.clear()
+ _FakeDaytona.configs.clear()
+ _FakeGateway.instances.clear()
+ _install_fake_daytona_module()
+ self.temp_dir = tempfile.mkdtemp()
+ sandbox = _MappedSandbox(self.temp_dir)
+ sandbox.labels = {METADATA_WORKSPACE_ID_KEY: "wid-tools"}
+ _FakeDaytona.list_result[:] = [sandbox]
+
+ self.gateway_patch = patch.object(
+ sandboxed_mod,
+ "GatewayClient",
+ _FakeGateway,
+ )
+ self.gateway_patch.start()
+ self.bootstrap_patch = patch.object(
+ DaytonaWorkspace,
+ "_bootstrap_commands",
+ return_value=[],
+ )
+ self.bootstrap_patch.start()
+
+ self.workspace = DaytonaWorkspace(workspace_id="wid-tools")
+ await self.workspace.initialize()
+ self.tools = {
+ tool.name: tool for tool in await self.workspace.list_tools()
+ }
+
+ async def asyncTearDown(self) -> None:
+ """Close workspace and cleanup patches/temp files."""
+ await self.workspace.close()
+ self.bootstrap_patch.stop()
+ self.gateway_patch.stop()
+ sys.modules.pop("daytona", None)
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+
+ @unittest.skipIf(
+ os.name == "nt",
+ "host-backed Daytona fake relies on POSIX sandbox commands",
+ )
+ async def test_all_builtin_tools_use_daytona_backend(self) -> None:
+ """Bash, Write, Read, Edit, Grep and Glob operate in the sandbox."""
+ bash_text = await _tool_text(
+ self.tools["Bash"],
+ command="printf 'alpha\\n'",
+ )
+ self.assertEqual(bash_text, "alpha\n")
+
+ target = "/home/daytona/src/app.py"
+ write_text = await _tool_text(
+ self.tools["Write"],
+ file_path=target,
+ content="alpha\nbeta\n",
+ )
+ self.assertIn("written successfully", write_text)
+
+ read_text = await _tool_text(self.tools["Read"], file_path=target)
+ self.assertIn("alpha", read_text)
+ self.assertIn("beta", read_text)
+
+ edit_text = await _tool_text(
+ self.tools["Edit"],
+ file_path=target,
+ old_string="beta",
+ new_string="gamma",
+ )
+ self.assertIn("Successfully replaced", edit_text)
+
+ grep_text = await _tool_text(
+ self.tools["Grep"],
+ pattern="gamma",
+ path="/home/daytona/src",
+ output_mode="content",
+ )
+ self.assertIn("/home/daytona/src/app.py", grep_text)
+ self.assertIn("gamma", grep_text)
+
+ glob_text = await _tool_text(
+ self.tools["Glob"],
+ pattern="**/*.py",
+ path="/home/daytona/src",
+ )
+ self.assertIn("/home/daytona/src/app.py", glob_text)
+
+ async def test_mcp_add_remove_persists_mcp_file(self) -> None:
+ """Dynamic MCP changes are reflected in the sandbox ``.mcp`` file."""
+ mcp = MCPClient(
+ name="demo",
+ mcp_config=StdioMCPConfig(command="node", args=["server.js"]),
+ is_stateful=True,
+ )
+
+ await self.workspace.add_mcp(mcp)
+
+ self.assertIn("demo", [m.name for m in self.workspace._mcps])
+ raw = await self.workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(json.loads(raw.decode("utf-8"))[0]["name"], "demo")
+
+ gw_client = next(m for m in self.workspace._mcps if m.name == "demo")
+ await self.workspace.remove_mcp("demo")
+
+ self.assertTrue(gw_client.closed)
+ self.assertNotIn("demo", [m.name for m in self.workspace._mcps])
+ raw = await self.workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(json.loads(raw.decode("utf-8")), [])
+
+ async def test_remove_missing_mcp_is_noop(self) -> None:
+ """Removing an unknown MCP leaves persisted config unchanged."""
+ await self.workspace.remove_mcp("missing")
+
+ raw = await self.workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(json.loads(raw.decode("utf-8")), [])
+
+ @unittest.skipIf(
+ os.name == "nt",
+ "host-backed Daytona fake relies on POSIX sandbox commands",
+ )
+ async def test_skill_add_list_remove_uses_sandbox_skills_dir(self) -> None:
+ """Skill management stores and reads skills under SDK workdir."""
+ skill_dir = os.path.join(self.temp_dir, "local-skill")
+ os.makedirs(skill_dir)
+ with open(
+ os.path.join(skill_dir, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(
+ "---\n"
+ "name: demo-skill\n"
+ "description: Demo skill\n"
+ "---\n"
+ "Use this skill.\n",
+ )
+
+ await self.workspace.add_skill(skill_dir)
+ skills = await self.workspace.list_skills()
+
+ self.assertEqual([skill.name for skill in skills], ["demo-skill"])
+ self.assertEqual(
+ skills[0].dir,
+ "/home/daytona/skills/local-skill",
+ )
+
+ await self.workspace.remove_skill("demo-skill")
+ self.assertEqual(await self.workspace.list_skills(), [])
+
+ async def test_add_skill_rejects_invalid_skill(self) -> None:
+ """Skill upload validates local input before sandbox work."""
+ with self.assertRaisesRegex(ValueError, "SKILL.md not found"):
+ await self.workspace.add_skill(
+ os.path.join(self.temp_dir, "missing-skill"),
+ )
+
+ @unittest.skipIf(
+ os.name == "nt",
+ "host-backed Daytona fake relies on POSIX sandbox commands",
+ )
+ async def test_add_skill_rejects_duplicate_skill(self) -> None:
+ """Skill upload rejects duplicate remote dirs."""
+ skill_dir = os.path.join(self.temp_dir, "dupe-skill")
+ os.makedirs(skill_dir)
+ with open(
+ os.path.join(skill_dir, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(
+ "---\n"
+ "name: dupe-skill\n"
+ "description: Demo skill\n"
+ "---\n"
+ "Use this skill.\n",
+ )
+
+ await self.workspace.add_skill(skill_dir)
+ with self.assertRaisesRegex(ValueError, "already exists"):
+ await self.workspace.add_skill(skill_dir)
+
+ async def test_offload_context_tool_result_and_reset(self) -> None:
+ """Offload writes sessions/data and reset clears persistent state."""
+ data_block = DataBlock(
+ name="payload.txt",
+ source=Base64Source(data="aGVsbG8=", media_type="text/plain"),
+ )
+ context_path = await self.workspace.offload_context(
+ "session-1",
+ [
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="see"), data_block],
+ ),
+ ],
+ )
+
+ self.assertEqual(
+ context_path,
+ "/home/daytona/sessions/session-1/context.jsonl",
+ )
+ context_raw = await self.workspace._backend.read_file(context_path)
+ self.assertIn(
+ "file:///home/daytona/data/",
+ context_raw.decode("utf-8"),
+ )
+
+ tool_path = await self.workspace.offload_tool_result(
+ "session-1",
+ ToolResultBlock(
+ id="tool-1",
+ name="tool",
+ output=[
+ TextBlock(text="result"),
+ data_block,
+ ],
+ state=ToolResultState.SUCCESS,
+ ),
+ )
+ self.assertEqual(
+ tool_path,
+ "/home/daytona/sessions/session-1/tool_result-tool-1.txt",
+ )
+
+ self.assertTrue(
+ await self.workspace._backend.file_exists(
+ "/home/daytona/sessions",
+ ),
+ )
+ self.assertTrue(
+ await self.workspace._backend.file_exists("/home/daytona/data"),
+ )
+
+ await self.workspace.reset()
+
+ self.assertFalse(
+ await self.workspace._backend.file_exists(
+ "/home/daytona/sessions",
+ ),
+ )
+ self.assertFalse(
+ await self.workspace._backend.file_exists("/home/daytona/data"),
+ )
+ raw = await self.workspace._backend.read_file("/home/daytona/.mcp")
+ self.assertEqual(json.loads(raw.decode("utf-8")), [])
+
+
+def _mcp_server_script() -> bytes:
+ """Minimal FastMCP stdio server used by live reattach tests."""
+ return b"""from mcp.server import FastMCP
+
+mcp = FastMCP("Persist")
+
+
+def ping() -> str:
+ return "pong"
+
+
+if __name__ == "__main__":
+ mcp.run(transport="stdio")
+"""
+
+
+def _make_live_agent(agent_id_suffix: str) -> AgentRecord:
+ """Build a minimal agent record for live toolkit assembly."""
+ return AgentRecord(
+ user_id="daytona-live-user",
+ source="user",
+ data=AgentData(
+ name=f"daytona-agent-{agent_id_suffix}",
+ system_prompt="You operate inside the configured workspace.",
+ context_config=ContextConfig(),
+ react_config=ReActConfig(),
+ ),
+ )
+
+
+def _make_live_session(agent: AgentRecord, workspace_id: str) -> SessionRecord:
+ """Build a minimal session record bound to the Daytona workspace."""
+ return SessionRecord(
+ user_id="daytona-live-user",
+ agent_id=agent.id,
+ config=SessionConfig(workspace_id=workspace_id),
+ )
+
+
+async def _call_tool(
+ toolkit: object,
+ state: AgentState,
+ *,
+ tool_call_id: str,
+ name: str,
+ tool_input: dict[str, object],
+) -> ToolResponse:
+ """Call a toolkit tool and return the final response."""
+ response = None
+ async for result in toolkit.call_tool( # type: ignore[attr-defined]
+ ToolCallBlock(
+ id=tool_call_id,
+ name=name,
+ input=json.dumps(tool_input),
+ ),
+ state,
+ ):
+ if isinstance(result, ToolResponse):
+ response = result
+ assert response is not None
+ return response
+
+
+def _response_text(response: ToolResponse) -> str:
+ """Flatten text blocks from a tool response."""
+ parts: list[str] = []
+ for block in response.content:
+ text = getattr(block, "text", None)
+ if text is not None:
+ parts.append(str(text))
+ return "\n".join(parts)
+
+
[email protected](DAYTONA_API_KEY, SKIP_REASON)
+class TestDaytonaWorkspaceLive(IsolatedAsyncioTestCase):
+ """Live Daytona workspace coverage, skipped without credentials."""
+
+ @asynccontextmanager
+ async def _live_workspace(
+ self,
+ suffix: str,
+ **kwargs: object,
+ ) -> AsyncIterator[DaytonaWorkspace]:
+ """Create one live workspace and guarantee best-effort cleanup."""
+ workspace_id = live_daytona_workspace_id(suffix)
+ daytona_kwargs = live_daytona_kwargs()
+ daytona_kwargs.update(kwargs)
+ workspace = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **daytona_kwargs,
+ )
+ try:
+ await workspace.initialize()
+ yield workspace
+ finally:
+ await workspace.close()
+ await delete_live_daytona_workspace(workspace_id)
+
+ def _create_live_skill(
+ self,
+ root: str,
+ name: str,
+ description: str,
+ additional_files: dict[str, str] | None = None,
+ ) -> str:
+ """Create a local skill directory for live upload tests."""
+ skill_dir = os.path.join(root, name)
+ os.makedirs(skill_dir, exist_ok=True)
+ with open(
+ os.path.join(skill_dir, "SKILL.md"),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(
+ f"---\nname: {name}\ndescription: {description}\n---\n\n"
+ f"# {name}\n\n{description}\n",
+ )
+ for filename, content in (additional_files or {}).items():
+ with open(
+ os.path.join(skill_dir, filename),
+ "w",
+ encoding="utf-8",
+ ) as f:
+ f.write(content)
+ return skill_dir
+
+ async def test_initialize_idempotent(self) -> None:
+ """Calling ``initialize`` on a live workspace is a no-op."""
+ async with self._live_workspace("daytona-live-init-idempotent") as ws:
+ sandbox = ws._sandbox
+ sandbox_id = ws.sandbox_id
+
+ await ws.initialize()
+
+ self.assertTrue(ws.is_alive)
+ self.assertIs(ws._sandbox, sandbox)
+ self.assertEqual(ws.sandbox_id, sandbox_id)
+
+ async def test_close_marks_inactive(self) -> None:
+ """``close`` flips ``is_alive`` and clears runtime handles."""
+ workspace_id = live_daytona_workspace_id("daytona-live-close")
+ workspace = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **live_daytona_kwargs(),
+ )
+ try:
+ await workspace.initialize()
+ self.assertTrue(workspace.is_alive)
+
+ await workspace.close()
+
+ self.assertFalse(workspace.is_alive)
+ self.assertIsNone(workspace._sandbox)
+ self.assertIsNone(workspace._backend)
+ finally:
+ await workspace.close()
+ await delete_live_daytona_workspace(workspace_id)
+
+ async def test_list_tools_builtin(self) -> None:
+ """``list_tools`` returns the six builtin tools backed by Daytona."""
+ from agentscope.tool._builtin import (
+ Bash,
+ Edit,
+ Glob,
+ Grep,
+ Read,
+ Write,
+ )
+
+ async with self._live_workspace("daytona-live-tools") as workspace:
+ tools = await workspace.list_tools()
+
+ self.assertEqual(len(tools), 6)
+ self.assertSetEqual(
+ {type(tool) for tool in tools},
+ {Bash, Edit, Glob, Grep, Read, Write},
+ )
+ for tool in tools:
+ self.assertIsInstance(tool._backend, DaytonaBackend)
+
+ async def test_skill_paths_add_list_remove(self) -> None:
+ """Skill paths and runtime skill changes work in a live sandbox."""
+ with tempfile.TemporaryDirectory() as skill_root:
+ seed_one = self._create_live_skill(
+ skill_root,
+ "live_seed_one",
+ "First live skill",
+ {"tool.py": "def run():\n return 'one'\n"},
+ )
+ seed_two = self._create_live_skill(
+ skill_root,
+ "live_seed_two",
+ "Second live skill",
+ )
+
+ async with self._live_workspace(
+ "daytona-live-skills",
+ skill_paths=[seed_one, seed_two],
+ ) as workspace:
+ seeded = sorted(
+ await workspace.list_skills(),
+ key=lambda skill: skill.name,
+ )
+ self.assertEqual(
+ [skill.name for skill in seeded],
+ ["live_seed_one", "live_seed_two"],
+ )
+ self.assertEqual(
+ [skill.description for skill in seeded],
+ ["First live skill", "Second live skill"],
+ )
+ self.assertEqual(
+ [skill.dir for skill in seeded],
+ [
+ f"{workspace.workdir}/skills/live_seed_one",
+ f"{workspace.workdir}/skills/live_seed_two",
+ ],
+ )
+
+ added = self._create_live_skill(
+ skill_root,
+ "live_added_skill",
+ "Added live skill",
+ )
+ await workspace.add_skill(added)
+ skills = await workspace.list_skills()
+ self.assertIn(
+ "live_added_skill",
+ [skill.name for skill in skills],
+ )
+
+ await workspace.remove_skill("live_added_skill")
+ self.assertNotIn(
+ "live_added_skill",
+ [skill.name for skill in await workspace.list_skills()],
+ )
+
+ async def test_offload_context_tool_result_and_reset(self) -> None:
+ """Live offload writes sessions/data and reset clears them."""
+ async with self._live_workspace("daytona-live-offload-reset") as ws:
+ data_block = DataBlock(
+ name="payload.txt",
+ source=Base64Source(data="aGVsbG8=", media_type="text/plain"),
+ )
+ context_path = await ws.offload_context(
+ "session-live-reset",
+ [
+ UserMsg(
+ name="user",
+ content=[TextBlock(text="live context"), data_block],
+ ),
+ ],
+ )
+ context_raw = await ws._backend.read_file(context_path)
+ self.assertIn("live context", context_raw.decode("utf-8"))
+ self.assertIn("file://", context_raw.decode("utf-8"))
+
+ tool_path = await ws.offload_tool_result(
+ "session-live-reset",
+ ToolResultBlock(
+ id="tool-live-reset",
+ name="tool",
+ output=[TextBlock(text="live tool result"), data_block],
+ state=ToolResultState.SUCCESS,
+ ),
+ )
+ tool_raw = await ws._backend.read_file(tool_path)
+ self.assertIn("live tool result", tool_raw.decode("utf-8"))
+ self.assertTrue(await ws._backend.file_exists(ws._sessions_dir))
+ self.assertTrue(await ws._backend.file_exists(ws._data_dir))
+
+ await ws.reset()
+
+ self.assertFalse(await ws._backend.file_exists(ws._sessions_dir))
+ self.assertFalse(await ws._backend.file_exists(ws._data_dir))
+ raw = await ws._backend.read_file(ws._mcp_file)
+ self.assertEqual(json.loads(raw.decode("utf-8")), [])
+
+ async def test_persistent_state_survives_close_and_reattach(self) -> None:
+ """Live Daytona reattach preserves MCP, sessions, and data files."""
+ workspace_id = live_daytona_workspace_id("daytona-live-persist")
+ session_id = "session-live"
+ mcp_name = "persist_mcp"
+
+ workspace = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **live_daytona_kwargs(),
+ )
+
+ reattached = None
+ try:
+ await workspace.initialize()
+ sandbox_id = workspace.sandbox_id
+ data_block = DataBlock(
+ name="payload.txt",
+ source=Base64Source(
+ data="cmVhdHRhY2gtcGF5bG9hZA==",
+ media_type="text/plain",
+ ),
+ )
+ context_path = await workspace.offload_context(
+ session_id,
+ [
+ UserMsg(
+ name="user",
+ content=[
+ TextBlock(text="persist context"),
+ data_block,
+ ],
+ ),
+ ],
+ )
+ tool_path = await workspace.offload_tool_result(
+ session_id,
+ ToolResultBlock(
+ id="tool-live",
+ name="tool",
+ output=[
+ TextBlock(text="persist tool result"),
+ data_block,
+ ],
+ state=ToolResultState.SUCCESS,
+ ),
+ )
+
+ mcp_script = f"{workspace.workdir}/persist_mcp.py"
+ await workspace._backend.write_file(
+ mcp_script,
+ _mcp_server_script(),
+ )
+ await workspace.add_mcp(
+ MCPClient(
+ name=mcp_name,
+ is_stateful=True,
+ mcp_config=StdioMCPConfig(
+ command=workspace._gateway_python,
+ args=[mcp_script],
+ ),
+ ),
+ )
+ self.assertIn(
+ mcp_name,
+ [mcp.name for mcp in await workspace.list_mcps()],
+ )
+
+ await workspace.close()
+
+ reattached = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **live_daytona_kwargs(),
+ )
+ await reattached.initialize()
+
+ self.assertEqual(reattached.sandbox_id, sandbox_id)
+ context_raw = await reattached._backend.read_file(context_path)
+ self.assertIn(
+ "persist context",
+ context_raw.decode("utf-8"),
+ )
+ self.assertIn(
+ "file://",
+ context_raw.decode("utf-8"),
+ )
+ tool_raw = await reattached._backend.read_file(tool_path)
+ self.assertIn(
+ "persist tool result",
+ tool_raw.decode("utf-8"),
+ )
+
+ mcp_raw = await reattached._backend.read_file(
+ f"{reattached.workdir}/.mcp",
+ )
+ self.assertEqual(
+ json.loads(mcp_raw.decode("utf-8"))[0]["name"],
+ mcp_name,
+ )
+ mcps = await reattached.list_mcps()
+ self.assertIn(mcp_name, [mcp.name for mcp in mcps])
+ raw_tools = await mcps[0].list_raw_tools()
+ self.assertIn("ping", [tool.name for tool in raw_tools])
+ finally:
+ if reattached is not None:
+ await reattached.close()
+ else:
+ await workspace.close()
+ await delete_live_daytona_workspace(workspace_id)
+
+ async def test_agent_toolkit_write_read_operates_in_sandbox(self) -> None:
+ """Agent-facing toolkit tools operate through Daytona workspace."""
+ workspace_id = live_daytona_workspace_id("daytona-live-agent")
+ workspace = DaytonaWorkspace(
+ workspace_id=workspace_id,
+ **live_daytona_kwargs(),
+ )
+ try:
+ await workspace.initialize()
+ agent = _make_live_agent("toolkit")
+ session = _make_live_session(agent, workspace.workspace_id)
+ toolkit = await get_toolkit(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ workspace=workspace,
+ workspace_manager=(
+ _NoOpWorkspaceManager() # type: ignore[arg-type]
+ ),
+ scheduler_manager=SchedulerManager(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ ),
+ background_task_manager=BackgroundTaskManager(
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ ),
+ message_bus=_NullBus(), # type: ignore[arg-type]
+ middlewares=[],
+ user_id="daytona-live-user",
+ agent_record=agent,
+ session_record=session,
+ resource_access_service=ResourceAccessService(
+ storage=_NoOpStorage(), # type: ignore[arg-type]
+ policy=DenyAllResourceAccessPolicy(),
+ ),
+ extra_factory=None,
+ )
+
+ state = AgentState(session_id=session.id)
+ state.permission_context.mode = PermissionMode.BYPASS
+ file_path = f"{workspace.workdir}/agent-toolkit.txt"
+
+ write_response = await _call_tool(
+ toolkit,
+ state,
+ tool_call_id="write-live",
+ name="Write",
+ tool_input={
+ "file_path": file_path,
+ "content": "from agent toolkit\n",
+ },
+ )
+ self.assertEqual(write_response.state, ToolResultState.SUCCESS)
+ self.assertIn(
+ "written successfully",
+ _response_text(write_response),
+ )
+
+ read_response = await _call_tool(
+ toolkit,
+ state,
+ tool_call_id="read-live",
+ name="Read",
+ tool_input={"file_path": file_path},
+ )
+ self.assertEqual(read_response.state, ToolResultState.SUCCESS)
+ self.assertIn("from agent toolkit", _response_text(read_response))
+
+ raw = await workspace._backend.read_file(file_path)
+ self.assertEqual(raw, b"from agent toolkit\n")
+ finally:
+ await workspace.close()
+ await delete_live_daytona_workspace(workspace_id)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/workspace_manager_daytona_test.py b/tests/workspace_manager_daytona_test.py
new file mode 100644
index 000000000..bdfe1d5f3
--- /dev/null
+++ b/tests/workspace_manager_daytona_test.py
@@ -0,0 +1,206 @@
+# -*- coding: utf-8 -*-
+# pylint: disable=protected-access
+"""Test cases for :class:`DaytonaWorkspaceManager`."""
+
+import asyncio
+import unittest
+from types import SimpleNamespace
+from unittest.async_case import IsolatedAsyncioTestCase
+from unittest.mock import AsyncMock, patch
+
+from agentscope.app.workspace_manager import (
+ DaytonaWorkspaceManager,
+ 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 TestDaytonaWorkspaceManager(IsolatedAsyncioTestCase):
+ """Manager cache, metadata and TTL behavior."""
+
+ async def asyncSetUp(self) -> None:
+ """Patch the workspace class used by the manager."""
+ _FakeWorkspace.created.clear()
+ self.workspace_patch = patch(
+ "agentscope.app.workspace_manager."
+ "_daytona_workspace_manager.DaytonaWorkspace",
+ _FakeWorkspace,
+ )
+ self.workspace_patch.start()
+
+ async def asyncTearDown(self) -> None:
+ """Undo patches."""
+ self.workspace_patch.stop()
+
+ async def test_get_workspace_forwards_config_and_metadata(self) -> None:
+ """Manager forwards only the confirmed Daytona config surface."""
+ manager = DaytonaWorkspaceManager(
+ api_key="key",
+ api_url="https://daytona.example/api",
+ target="us",
+ env={"A": "B"},
+ sandbox_metadata={"team": "agents"},
+ extra_pip=["x"],
+ os_user="daytona",
+ ttl=10,
+ sweep_interval=1,
+ )
+
+ workspace = await manager.get_workspace("u1", "a1", "s1", "wid")
+
+ self.assertIs(workspace, _FakeWorkspace.created[0])
+ self.assertTrue(workspace.initialized)
+ self.assertEqual(
+ workspace.kwargs,
+ {
+ "workspace_id": "wid",
+ "api_key": "key",
+ "api_url": "https://daytona.example/api",
+ "target": "us",
+ "timeout_seconds": 300,
+ "gateway_port": 5600,
+ "env": {"A": "B"},
+ "sandbox_metadata": {
+ "agentscope.user.id": "u1",
+ "agentscope.agent.id": "a1",
+ "team": "agents",
+ },
+ "extra_pip": ["x"],
+ "default_mcps": [],
+ "skill_paths": [],
+ "os_user": "daytona",
+ },
+ )
+ self.assertIn(workspace.workspace_id, manager._cache)
+
+ async def test_get_workspace_uses_workspace_id_cache_key(self) -> None:
+ """Same workspace id returns cached instance regardless of session."""
+ manager = DaytonaWorkspaceManager()
+
+ first = await manager.get_workspace("u", "a", "s1", "wid")
+ second = await manager.get_workspace("u", "a", "s2", "wid")
+
+ self.assertIs(first, second)
+ self.assertEqual(len(_FakeWorkspace.created), 1)
+ self.assertEqual(first.kwargs["workspace_id"], "wid")
+
+ async def test_get_workspace_without_id_uses_isolation_policy(
+ self,
+ ) -> None:
+ """``workspace_id=None`` follows the base manager API contract."""
+ manager = DaytonaWorkspaceManager(
+ isolation=IsolationPolicy.PER_USER,
+ )
+
+ first = await manager.get_workspace("u", "a1", "s1")
+ second = await manager.get_workspace("u", "a2", "s2")
+
+ self.assertIs(first, second)
+ self.assertEqual(len(_FakeWorkspace.created), 1)
+ self.assertEqual(
+ first.kwargs["workspace_id"],
+ manager.assign_workspace_id(
+ user_id="u",
+ agent_id="a1",
+ session_id="",
+ ),
+ )
+
+ async def test_concurrent_get_workspace_creates_one_instance(self) -> None:
+ """Concurrent requests for one id share the initialized workspace."""
+ manager = DaytonaWorkspaceManager()
+
+ results = await asyncio.gather(
+ *(
+ manager.get_workspace("u", "a", f"s{i}", "wid-concurrent")
+ for i in range(8)
+ ),
+ )
+
+ self.assertEqual(len(_FakeWorkspace.created), 1)
+ self.assertTrue(_FakeWorkspace.created[0].initialized)
+ self.assertTrue(all(result is results[0] for result in results))
+ self.assertIs(manager._cache["wid-concurrent"][0], results[0])
+
+ async def test_close_and_close_all_release_cached_workspaces(self) -> None:
+ """Explicit close operations evict and close workspaces."""
+ manager = DaytonaWorkspaceManager()
+ first = await manager.get_workspace("u", "a", "s", "wid-1")
+ second = await manager.get_workspace("u", "a", "s", "wid-2")
+
+ await manager.close("wid-1")
+ self.assertTrue(first.closed)
+ self.assertNotIn("wid-1", manager._cache)
+
+ await manager.close_all()
+ self.assertTrue(second.closed)
+ self.assertEqual(manager._cache, {})
+
+ async def test_sweep_once_evicts_idle_workspaces(self) -> None:
+ """The TTL sweeper closes expired cache entries."""
+ manager = DaytonaWorkspaceManager(ttl=10)
+ workspace = await manager.get_workspace("u", "a", "s", "wid")
+ manager._cache["wid"] = (workspace, 0.0)
+ manager._safe_close = AsyncMock(wraps=manager._safe_close)
+
+ await manager._sweep_once()
+
+ self.assertNotIn("wid", manager._cache)
+ self.assertTrue(workspace.closed)
+ manager._safe_close.assert_awaited_once_with(workspace)
+
+ async def test_context_manager_starts_sweeper_and_closes_all(self) -> None:
+ """Async context starts the sweeper and closes cached workspaces."""
+ manager = DaytonaWorkspaceManager(sweep_interval=60)
+ manager.close_all = AsyncMock(wraps=manager.close_all)
+
+ async with manager as entered:
+ sweep_task = manager._sweep_task
+
+ self.assertIs(entered, manager)
+ self.assertIsNotNone(sweep_task)
+ self.assertFalse(sweep_task.done())
+
+ self.assertIsNone(manager._sweep_task)
+ self.assertTrue(sweep_task.done())
+ manager.close_all.assert_awaited_once()
+
+ async def test_safe_close_swallows_workspace_close_errors(self) -> None:
+ """``_safe_close`` logs close errors without raising."""
+
+ async def _raise_close() -> None:
+ raise RuntimeError("close failed")
+
+ workspace = SimpleNamespace(
+ workspace_id="wid-error",
+ close=_raise_close,
+ )
+
+ await DaytonaWorkspaceManager._safe_close( # type: ignore[arg-type]
+ workspace,
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()