mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(opensandbox): sync enabled skills and per-agent projections (#8451)
* fix(opensandbox): sync enabled skills and per-agent projections * fix(opensandbox): retain workspaces on skill upload failure * test(opensandbox): make skill upload checks portable --------- Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
parent
e09cd88c2d
commit
6f9d6cd7c6
@ -107,6 +107,25 @@ count against the file limit. Each release revisits retained outputs, including
|
||||
unchanged files; equal file size does not prove equal content. Large accumulated
|
||||
output directories may reach the pass limits before all files are mirrored.
|
||||
|
||||
Skill synchronization is required before a new or reclaimed sandbox is exposed
|
||||
to the run. OpenSandbox stages the enabled skill view under `skills.container_path`;
|
||||
an explicit Agent policy replaces the four managed directories with its own view,
|
||||
including an empty view for an empty list. The provider refuses symlinks in the
|
||||
skills root or its ancestors. Within a package it preserves relative links to
|
||||
files and directories in the same package, and skips unsafe links and
|
||||
non-portable path components with a warning.
|
||||
|
||||
A pass uploads at most 2,000 files and links, 512 MiB of file content, and
|
||||
100 MiB per file. Its 120-second deadline is cooperative: it is checked
|
||||
between operations, and an in-flight SDK file call is bounded separately by
|
||||
`request_timeout`. The remote image needs `mkdir`, `rm`, `mv`, `rmdir`, and
|
||||
`ln -sT` for staging and publication. Unlike output mirroring, a skill sync
|
||||
failure fails the acquire or turn. A failed upload before publication leaves
|
||||
an existing sandbox unavailable to tools in the same scope's warm pool, where
|
||||
normal expiry and eviction still apply. A retry clears the abandoned staging
|
||||
directory before uploading again. Failure to set up or publish the staged tree
|
||||
discards the sandbox rather than making an uncertain skill view available.
|
||||
|
||||
Create returns only after the SDK readiness check and DeerFlow's
|
||||
`/mnt/user-data/{workspace,uploads,outputs}` bootstrap succeed. A bootstrap
|
||||
failure explicitly destroys the newly created remote sandbox.
|
||||
|
||||
@ -8,6 +8,7 @@ import ipaddress
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
import posixpath
|
||||
import shlex
|
||||
import stat
|
||||
import tempfile
|
||||
@ -15,7 +16,8 @@ import threading
|
||||
import time
|
||||
import unicodedata
|
||||
import uuid
|
||||
from collections.abc import Mapping
|
||||
from collections.abc import Callable, Mapping
|
||||
from contextlib import ExitStack
|
||||
from datetime import timedelta
|
||||
from functools import partial
|
||||
from pathlib import Path, PurePosixPath
|
||||
@ -27,6 +29,8 @@ from deerflow.sandbox.acquire_serialization import AcquireSerializer, AcquireSer
|
||||
from deerflow.sandbox.identity import derive_sandbox_scope_token
|
||||
from deerflow.sandbox.sandbox import Sandbox, _validate_extra_env
|
||||
from deerflow.sandbox.sandbox_provider import SandboxProvider
|
||||
from deerflow.skills.projection import SkillProjectionPaths, _projection_lock
|
||||
from deerflow.skills.types import SkillCategory
|
||||
|
||||
from ..warm_pool_lifecycle import WarmPoolLifecycleMixin
|
||||
from .sandbox import _MAX_DOWNLOAD_SIZE, OpenSandboxSandbox, execution_stdout, format_execution
|
||||
@ -46,6 +50,50 @@ DEFAULT_COMMAND_TIMEOUT = 10 * 60
|
||||
_BOOTSTRAP_TIMEOUT = 30.0
|
||||
_BOOTSTRAP_COMMAND = "mkdir -p /mnt/user-data/workspace /mnt/user-data/uploads /mnt/user-data/outputs"
|
||||
_WINDOWS_RESERVED_NAMES = frozenset({"CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"} | {f"{prefix}{digit}" for prefix in ("COM", "LPT") for digit in "123456789¹²³"})
|
||||
_SKILL_CATEGORIES = (SkillCategory.PUBLIC, SkillCategory.CUSTOM, SkillCategory.LEGACY, SkillCategory.INTEGRATION)
|
||||
_PROTECTED_SKILLS_ROOTS = tuple(PurePosixPath(path) for path in ("/bin", "/boot", "/dev", "/etc", "/lib", "/lib32", "/lib64", "/libx32", "/proc", "/run", "/sbin", "/sys", "/usr", "/var", "/mnt/user-data", "/mnt/acp-workspace"))
|
||||
|
||||
|
||||
class _SkillUploadError(RuntimeError):
|
||||
"""The upload failed before the published skill view was changed."""
|
||||
|
||||
|
||||
def _skills_root(path: str) -> PurePosixPath:
|
||||
root = PurePosixPath(path)
|
||||
if (
|
||||
len(root.parts) < 2
|
||||
or not root.is_absolute()
|
||||
or path.startswith("//")
|
||||
or root.as_posix() != path
|
||||
or ".." in root.parts
|
||||
or "\\" in path
|
||||
or "\0" in path
|
||||
or path in {"/home", "/root"}
|
||||
or any(root.is_relative_to(protected) or protected.is_relative_to(root) for protected in _PROTECTED_SKILLS_ROOTS)
|
||||
):
|
||||
raise ValueError("skills.container_path must be a dedicated absolute OpenSandbox skills directory")
|
||||
return root
|
||||
|
||||
|
||||
def _portable_skill_name(name: str) -> bool:
|
||||
try:
|
||||
name.encode("utf-8")
|
||||
except UnicodeEncodeError:
|
||||
return False
|
||||
return not ("\\" in name or ":" in name or name.endswith((" ", ".")) or name.partition(".")[0].rstrip(" ").upper() in _WINDOWS_RESERVED_NAMES)
|
||||
|
||||
|
||||
def _skill_link_target(path: Path, package: Path) -> Path | None:
|
||||
raw_target = Path(os.readlink(path))
|
||||
if raw_target.is_absolute() or any(part != ".." and not _portable_skill_name(part) for part in raw_target.parts):
|
||||
return None
|
||||
try:
|
||||
resolved = path.resolve(strict=True)
|
||||
except (OSError, RuntimeError):
|
||||
return None
|
||||
if not resolved.is_relative_to(package) or not all(_portable_skill_name(part) for part in resolved.relative_to(package).parts):
|
||||
return None
|
||||
return resolved
|
||||
|
||||
|
||||
def _uses_insecure_remote_http(domain: Any, protocol: str) -> bool:
|
||||
@ -82,11 +130,15 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
|
||||
uses_thread_data_mounts = False
|
||||
needs_upload_permission_adjustment = True
|
||||
supports_agent_skill_isolation = True
|
||||
_idle_checker_thread_name = "opensandbox-idle-reaper"
|
||||
_MAX_SYNC_FILES = 2000
|
||||
_MAX_SYNC_TOTAL_BYTES = 512 * 1024 * 1024
|
||||
_MAX_SYNC_LISTING_BYTES = 512 * 1024
|
||||
_SYNC_DEADLINE_SECONDS = 120.0
|
||||
_MAX_SKILL_FILES = 2000
|
||||
_MAX_SKILL_FILE_BYTES = 100 * 1024 * 1024
|
||||
_MAX_SKILL_TOTAL_BYTES = 512 * 1024 * 1024
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._lock = threading.Lock()
|
||||
@ -113,7 +165,8 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
return resolved
|
||||
|
||||
def _load_config(self) -> dict[str, Any]:
|
||||
sandbox_config = get_app_config().sandbox
|
||||
app_config = get_app_config()
|
||||
sandbox_config = app_config.sandbox
|
||||
|
||||
def option(name: str) -> Any:
|
||||
return getattr(sandbox_config, name, None)
|
||||
@ -185,6 +238,7 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
"idle_timeout": idle_timeout if idle_timeout is not None else self.DEFAULT_IDLE_TIMEOUT,
|
||||
"resource": resource_option("resource"),
|
||||
"resource_requests": resource_option("resource_requests"),
|
||||
"skills_root": _skills_root(app_config.skills.container_path),
|
||||
}
|
||||
|
||||
def _get_sdk(self) -> tuple[type[SandboxSync], type[ConnectionConfigSync], type[RunCommandOpts]]:
|
||||
@ -256,6 +310,11 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
if thread_id is None:
|
||||
sandbox_id = str(uuid.uuid4())[:8]
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=None, user_id=user_id)
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=None, user_id=user_id)
|
||||
except BaseException:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
@ -303,15 +362,18 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
if not invalidated or not active.is_closed or shutting_down:
|
||||
raise
|
||||
logger.info("Rebuilding terminal OpenSandbox %s during acquire", existing)
|
||||
reclaimed = self._reclaim_warm_pool(sandbox_id)
|
||||
if reclaimed is not None:
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
raise RuntimeError("OpenSandboxProvider shut down during acquire")
|
||||
if reclaimed in self._sandboxes:
|
||||
self._thread_sandboxes[key] = reclaimed
|
||||
return reclaimed
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id)
|
||||
sandbox = self._reclaim_warm_pool(sandbox_id)
|
||||
reclaimed = sandbox is not None
|
||||
if sandbox is None:
|
||||
sandbox = self._create_sandbox(sandbox_id, thread_id=thread_id, user_id=user_id)
|
||||
try:
|
||||
self._prepare_new_skill_view(sandbox, thread_id=thread_id, user_id=user_id)
|
||||
except BaseException as exc:
|
||||
if reclaimed and isinstance(exc, _SkillUploadError):
|
||||
self._park_failed_skill_upload(sandbox, was_active=False)
|
||||
else:
|
||||
self._destroy_quietly(sandbox, context="skill projection setup failed")
|
||||
raise
|
||||
with self._lock:
|
||||
if self._shutdown_called:
|
||||
destroy_after_unlock = True
|
||||
@ -377,7 +439,7 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
on_terminal_failure=self._invalidate_sandbox,
|
||||
)
|
||||
|
||||
def _reclaim_warm_pool(self, sandbox_id: str) -> str | None:
|
||||
def _reclaim_warm_pool(self, sandbox_id: str) -> OpenSandboxSandbox | None:
|
||||
with self._lock:
|
||||
warm_entry = self._warm_pool.get(sandbox_id)
|
||||
if warm_entry is None:
|
||||
@ -393,14 +455,193 @@ class OpenSandboxProvider(WarmPoolLifecycleMixin[OpenSandboxSandbox], SandboxPro
|
||||
removed = self._warm_pool.pop(sandbox_id, None)
|
||||
if removed is None:
|
||||
return None
|
||||
self._sandboxes[sandbox_id] = removed[0]
|
||||
logger.info("Reclaimed warm OpenSandbox %s (remote=%s)", sandbox_id, sandbox.remote_id)
|
||||
return sandbox_id
|
||||
return removed[0]
|
||||
|
||||
def get(self, sandbox_id: str) -> Sandbox | None:
|
||||
with self._lock:
|
||||
return self._sandboxes.get(sandbox_id)
|
||||
|
||||
def _prepare_new_skill_view(self, sandbox: OpenSandboxSandbox, *, thread_id: str | None, user_id: str | None) -> None:
|
||||
if not user_id:
|
||||
return
|
||||
from deerflow.skills.projection import ensure_skill_projections, thread_skill_projection_exists
|
||||
from deerflow.skills.storage import get_or_new_user_skill_storage
|
||||
|
||||
storage = get_or_new_user_skill_storage(user_id, app_config=get_app_config())
|
||||
# Eager middleware installs the scoped view. Until then do not expose
|
||||
# either the shared view or the previous agent's files on a warm remote.
|
||||
projection = None if thread_id is not None and thread_skill_projection_exists(storage, thread_id) else ensure_skill_projections(storage)
|
||||
self._replace_skill_projection(sandbox, projection)
|
||||
|
||||
def _park_failed_skill_upload(self, sandbox: OpenSandboxSandbox, *, was_active: bool) -> None:
|
||||
sandbox_id = sandbox.id
|
||||
with self._lock:
|
||||
if was_active:
|
||||
if self._sandboxes.get(sandbox_id) is not sandbox:
|
||||
return
|
||||
self._sandboxes.pop(sandbox_id)
|
||||
for key in [key for key, value in self._thread_sandboxes.items() if value == sandbox_id]:
|
||||
self._thread_sandboxes.pop(key)
|
||||
if not self._shutdown_called:
|
||||
self._warm_pool[sandbox_id] = (sandbox, time.monotonic())
|
||||
return
|
||||
self._destroy_quietly(sandbox, context="skill upload failed during shutdown")
|
||||
|
||||
def sync_agent_skills(self, sandbox_id: str, *, thread_id: str, user_id: str, projection: SkillProjectionPaths) -> None:
|
||||
from deerflow.skills.projection import get_thread_skill_projection_paths
|
||||
from deerflow.skills.storage import get_or_new_user_skill_storage
|
||||
|
||||
with self._acquire_serializer.hold(sandbox_id):
|
||||
with self._lock:
|
||||
sandbox = self._sandboxes.get(sandbox_id)
|
||||
owner_matches = self._thread_sandboxes.get(self._thread_key(thread_id, user_id)) == sandbox_id
|
||||
if sandbox is None or not owner_matches:
|
||||
raise RuntimeError("OpenSandbox is not active for this skill projection scope")
|
||||
storage = get_or_new_user_skill_storage(user_id, app_config=get_app_config())
|
||||
if projection != get_thread_skill_projection_paths(storage, thread_id):
|
||||
raise RuntimeError("OpenSandbox skill projection does not belong to this scope")
|
||||
try:
|
||||
self._replace_skill_projection(sandbox, projection)
|
||||
except _SkillUploadError:
|
||||
self._park_failed_skill_upload(sandbox, was_active=True)
|
||||
raise
|
||||
except BaseException:
|
||||
self._invalidate_sandbox(sandbox_id, "skill projection setup failed")
|
||||
raise
|
||||
|
||||
def _replace_skill_projection(self, sandbox: OpenSandboxSandbox, projection: SkillProjectionPaths | None) -> None:
|
||||
root = self._config["skills_root"]
|
||||
stage = root / ".deerflow-skills-stage"
|
||||
deadline = time.monotonic() + self._SYNC_DEADLINE_SECONDS
|
||||
ancestors = [*reversed(root.parents[:-1]), root]
|
||||
no_links = "; ".join(f"test ! -L {shlex.quote(str(path))}" for path in ancestors)
|
||||
destinations = " ".join(shlex.quote(str(root / category)) for category in _SKILL_CATEGORIES)
|
||||
staged = " ".join(shlex.quote(str(stage / category)) for category in _SKILL_CATEGORIES)
|
||||
qroot = shlex.quote(str(root))
|
||||
qstage = shlex.quote(str(stage))
|
||||
|
||||
def run(script: str) -> None:
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
raise TimeoutError("OpenSandbox skill projection deadline exceeded")
|
||||
result = sandbox._run(f"set -e; {script}", timeout=min(remaining, _BOOTSTRAP_TIMEOUT))
|
||||
if getattr(result, "exit_code", None) != 0:
|
||||
raise RuntimeError("OpenSandbox skill projection command failed")
|
||||
|
||||
try:
|
||||
run(f"{no_links}; mkdir -p -- {qroot}; rm -rf -- {qstage}; mkdir -m 700 -- {qstage}; mkdir -- {staged}")
|
||||
except Exception as exc:
|
||||
raise RuntimeError("Failed to synchronize OpenSandbox skill projection") from exc
|
||||
if projection is not None:
|
||||
try:
|
||||
self._upload_skill_projection(sandbox, projection, stage=stage, run=run, deadline=deadline)
|
||||
except Exception as exc:
|
||||
raise _SkillUploadError("Failed to synchronize OpenSandbox skill projection") from exc
|
||||
try:
|
||||
run(f"{no_links}; test ! -L {qstage}; rm -rf -- {destinations}; mv -- {staged} {qroot}; rmdir -- {qstage}")
|
||||
except Exception as exc:
|
||||
raise RuntimeError("Failed to synchronize OpenSandbox skill projection") from exc
|
||||
|
||||
def _upload_skill_projection(
|
||||
self,
|
||||
sandbox: OpenSandboxSandbox,
|
||||
projection: SkillProjectionPaths,
|
||||
*,
|
||||
stage: PurePosixPath,
|
||||
run: Callable[[str], None],
|
||||
deadline: float,
|
||||
) -> None:
|
||||
sources = (projection.public, projection.custom, projection.legacy, projection.integrations)
|
||||
entries: list[tuple[PurePosixPath, int, bool]] = []
|
||||
links: list[tuple[PurePosixPath, PurePosixPath, bool]] = []
|
||||
total = 0
|
||||
|
||||
def fail_scan(error: OSError) -> None:
|
||||
raise error
|
||||
|
||||
def check_deadline() -> None:
|
||||
if time.monotonic() >= deadline:
|
||||
raise TimeoutError("OpenSandbox skill projection deadline exceeded")
|
||||
|
||||
def portable(name: str) -> bool:
|
||||
if _portable_skill_name(name):
|
||||
return True
|
||||
logger.warning("Skipping non-portable OpenSandbox skill path component %r", name)
|
||||
return False
|
||||
|
||||
# Capture under the publication locks, but do not hold the global
|
||||
# public projection lock across SDK calls for one user's sandbox.
|
||||
with tempfile.TemporaryFile() as payload:
|
||||
with ExitStack() as locks:
|
||||
for lock_root in dict.fromkeys(source.parent for source in sources):
|
||||
locks.enter_context(_projection_lock(lock_root, timeout=5.0))
|
||||
for category, source in zip(_SKILL_CATEGORIES, sources, strict=True):
|
||||
if source.is_symlink() or any(parent.is_symlink() for parent in source.parents):
|
||||
raise ValueError("Symlink in OpenSandbox skill projection root")
|
||||
packages: set[Path] = set()
|
||||
category_root = stage / category
|
||||
for directory, dirnames, filenames in os.walk(source, followlinks=False, onerror=fail_scan):
|
||||
check_deadline()
|
||||
parent = Path(directory)
|
||||
package = next((root for root in (parent, *parent.parents) if root in packages), None)
|
||||
if package is None and "SKILL.md" in filenames and stat.S_ISREG((parent / "SKILL.md").lstat().st_mode):
|
||||
packages.add(parent)
|
||||
package = parent
|
||||
target_dir = category_root / parent.relative_to(source).as_posix()
|
||||
dirnames[:] = [name for name in dirnames if portable(name)]
|
||||
dir_links = {name for name in dirnames if (parent / name).is_symlink()}
|
||||
dirnames[:] = [name for name in dirnames if name not in dir_links]
|
||||
for name in (*dir_links, *(name for name in filenames if portable(name))):
|
||||
check_deadline()
|
||||
path = parent / name
|
||||
info = path.lstat()
|
||||
if stat.S_ISLNK(info.st_mode):
|
||||
resolved = _skill_link_target(path, package) if package is not None else None
|
||||
if resolved is None or not (resolved.is_dir() or resolved.is_file()):
|
||||
logger.warning("Skipping unsafe OpenSandbox skill link %r", path.relative_to(source).as_posix())
|
||||
continue
|
||||
if len(entries) + len(links) >= self._MAX_SKILL_FILES:
|
||||
raise ValueError("OpenSandbox skill projection exceeds upload limits")
|
||||
links.append((target_dir / name, category_root / resolved.relative_to(source).as_posix(), resolved.is_dir()))
|
||||
continue
|
||||
if not stat.S_ISREG(info.st_mode):
|
||||
continue
|
||||
if len(entries) + len(links) >= self._MAX_SKILL_FILES or info.st_size > min(self._MAX_SKILL_FILE_BYTES, self._MAX_SKILL_TOTAL_BYTES - total):
|
||||
raise ValueError("OpenSandbox skill projection exceeds upload limits")
|
||||
flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0)
|
||||
with os.fdopen(os.open(path, flags), "rb") as file:
|
||||
opened = os.fstat(file.fileno())
|
||||
if not stat.S_ISREG(opened.st_mode) or not os.path.samestat(info, opened):
|
||||
raise ValueError("OpenSandbox skill projection changed during upload")
|
||||
data = file.read(info.st_size + 1)
|
||||
if len(data) != info.st_size:
|
||||
raise ValueError("OpenSandbox skill projection changed during upload")
|
||||
payload.write(data)
|
||||
entries.append((target_dir / name, len(data), bool(info.st_mode & stat.S_IXUSR)))
|
||||
total += len(data)
|
||||
payload.seek(0)
|
||||
created = {stage / category for category in _SKILL_CATEGORIES}
|
||||
|
||||
def ensure_dir(path: PurePosixPath) -> None:
|
||||
if path not in created:
|
||||
run(f"mkdir -p -- {shlex.quote(str(path))}")
|
||||
created.add(path)
|
||||
|
||||
for target, size, executable in entries:
|
||||
ensure_dir(target.parent)
|
||||
check_deadline()
|
||||
sandbox._upload_skill_file(str(target), payload.read(size), executable=executable)
|
||||
files = {target for target, _, _ in entries}
|
||||
for link, target, is_dir in links:
|
||||
if is_dir:
|
||||
ensure_dir(target)
|
||||
elif target not in files:
|
||||
continue
|
||||
ensure_dir(link.parent)
|
||||
relative = posixpath.relpath(target, start=link.parent)
|
||||
run(f"ln -sT -- {shlex.quote(relative)} {shlex.quote(str(link))}")
|
||||
|
||||
def release(self, sandbox_id: str) -> None:
|
||||
# Same scope lock as acquire: no next turn may reuse a client while its
|
||||
# previous outputs are still being mirrored. Keep it active until sync
|
||||
|
||||
@ -328,6 +328,12 @@ class OpenSandboxSandbox(Sandbox):
|
||||
resolved = self._resolve_path(path)
|
||||
self._file_op(lambda files: files.write_file(resolved, content, mode=644))
|
||||
|
||||
def _upload_skill_file(self, path: str, content: bytes, *, executable: bool) -> None:
|
||||
resolved = self._resolve_path(path)
|
||||
if resolved != path:
|
||||
raise ValueError("OpenSandbox skill path contains a non-portable separator")
|
||||
self._file_op(lambda files: files.write_file(resolved, content, mode=755 if executable else 644))
|
||||
|
||||
def download_file(self, path: str, *, max_bytes: int | None = None) -> bytes:
|
||||
return self._download_file_bounded(path, max_bytes=download_limit(max_bytes, _MAX_DOWNLOAD_SIZE))
|
||||
|
||||
|
||||
@ -362,14 +362,14 @@ def _update_tree_digest(
|
||||
if entry.is_symlink():
|
||||
kind = "link"
|
||||
if follow_package_directory_symlinks and relative_root == Path(".") and entry.is_dir(follow_symlinks=True):
|
||||
digest.update(f"{label}:{relative.as_posix()}:target:{Path(entry.path).resolve(strict=False)}\0".encode())
|
||||
digest.update(f"{label}:{relative.as_posix()}:target:{Path(entry.path).resolve(strict=False)}\0".encode(errors="surrogatepass"))
|
||||
child_dirs.append((Path(entry.path), relative))
|
||||
elif entry.is_dir(follow_symlinks=False):
|
||||
kind = "dir"
|
||||
child_dirs.append((Path(entry.path), relative))
|
||||
else:
|
||||
kind = "file"
|
||||
digest.update((f"{label}:{relative.as_posix()}:{kind}:{metadata.st_ino}:{metadata.st_mode}:{metadata.st_size}:{metadata.st_mtime_ns}\0").encode())
|
||||
digest.update((f"{label}:{relative.as_posix()}:{kind}:{metadata.st_ino}:{metadata.st_mode}:{metadata.st_size}:{metadata.st_mtime_ns}\0").encode(errors="surrogatepass"))
|
||||
stack.extend(reversed(child_dirs))
|
||||
|
||||
|
||||
|
||||
@ -16,12 +16,16 @@ provider creation path: under contention, no blocking IO may run on the loop.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from blockbuster import BlockingError
|
||||
from test_opensandbox_provider import _FakeRemote, _FakeSandboxClass, _install
|
||||
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.skills.projection import SkillProjectionPaths
|
||||
|
||||
pytestmark = pytest.mark.asyncio
|
||||
|
||||
|
||||
@ -54,3 +58,52 @@ async def test_sync_acquire_on_loop_trips_the_gate(tmp_path: Path, monkeypatch:
|
||||
with pytest.raises(BlockingError):
|
||||
provider.acquire("thread-anchor", user_id="u-anchor")
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
async def test_agent_skill_upload_is_off_loop_and_drains_before_cancellation(tmp_path, monkeypatch):
|
||||
provider, sdk = _install(monkeypatch)
|
||||
paths = await asyncio.to_thread(Paths, base_dir=tmp_path)
|
||||
monkeypatch.setattr("deerflow.config.paths.get_paths", lambda: paths)
|
||||
root = paths.thread_skills_view_dir("thread-anchor", user_id="u-anchor")
|
||||
projection = SkillProjectionPaths(root / "public", root / "custom", root / "legacy", root / "integrations")
|
||||
|
||||
def prepare():
|
||||
for path in (projection.public, projection.custom, projection.legacy, projection.integrations):
|
||||
path.mkdir(parents=True)
|
||||
(projection.public / "SKILL.md").write_bytes(b"example")
|
||||
|
||||
await asyncio.to_thread(prepare)
|
||||
sandbox_id = await provider.acquire_async("thread-anchor", user_id="u-anchor")
|
||||
remote = sdk.remotes[0]
|
||||
loop = asyncio.get_running_loop()
|
||||
started = asyncio.Event()
|
||||
proceed = threading.Event()
|
||||
owner = threading.get_ident()
|
||||
calls = []
|
||||
|
||||
def write(path, data, *, mode):
|
||||
calls.append(threading.get_ident())
|
||||
loop.call_soon_threadsafe(started.set)
|
||||
if not proceed.wait(timeout=5):
|
||||
raise TimeoutError("upload test did not open its gate")
|
||||
(tmp_path / "uploaded").write_bytes(data)
|
||||
|
||||
monkeypatch.setattr(remote.files, "write_file", write)
|
||||
upload = asyncio.create_task(provider.sync_agent_skills_async(sandbox_id, thread_id="thread-anchor", user_id="u-anchor", projection=projection))
|
||||
entered = asyncio.create_task(started.wait())
|
||||
try:
|
||||
await asyncio.wait({upload, entered}, timeout=5, return_when=asyncio.FIRST_COMPLETED)
|
||||
if upload.done():
|
||||
upload.result()
|
||||
assert started.is_set(), "upload did not start"
|
||||
upload.cancel()
|
||||
await asyncio.sleep(0)
|
||||
assert not upload.done()
|
||||
finally:
|
||||
proceed.set()
|
||||
entered.cancel()
|
||||
result, _ = await asyncio.gather(upload, entered, return_exceptions=True)
|
||||
await asyncio.to_thread(provider.shutdown)
|
||||
assert isinstance(result, asyncio.CancelledError)
|
||||
assert calls and owner not in calls
|
||||
assert (tmp_path / "uploaded").read_bytes() == b"example"
|
||||
|
||||
@ -11,6 +11,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import base64
|
||||
import errno
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
@ -26,11 +27,19 @@ from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from langgraph.runtime import Runtime
|
||||
|
||||
from deerflow.community.opensandbox.provider import OpenSandboxProvider, _import_sdk
|
||||
from deerflow.community.opensandbox.sandbox import OpenSandboxSandbox
|
||||
from deerflow.config import ExtensionsConfig, SkillsConfig
|
||||
from deerflow.config.extensions_config import SkillStateConfig
|
||||
from deerflow.config.paths import Paths
|
||||
from deerflow.sandbox.middleware import SandboxMiddleware
|
||||
from deerflow.sandbox.sandbox_provider import reset_sandbox_provider, set_sandbox_provider
|
||||
from deerflow.skills.projection import get_thread_skill_projection_paths
|
||||
from deerflow.skills.storage import get_or_new_user_skill_storage
|
||||
|
||||
|
||||
@dataclass
|
||||
@ -254,12 +263,13 @@ class _TerminalApiError(RuntimeError):
|
||||
|
||||
def _stub_config(attrs: dict[str, Any] | None = None) -> types.SimpleNamespace:
|
||||
values = {"idle_timeout": 0, **(attrs or {})}
|
||||
return types.SimpleNamespace(sandbox=types.SimpleNamespace(**values))
|
||||
return types.SimpleNamespace(sandbox=types.SimpleNamespace(**values), skills=SkillsConfig())
|
||||
|
||||
|
||||
def _install(monkeypatch: pytest.MonkeyPatch, *, sdk: _FakeSandboxClass | None = None, config: dict[str, Any] | None = None) -> tuple[OpenSandboxProvider, _FakeSandboxClass]:
|
||||
fake_sdk = sdk or _FakeSandboxClass()
|
||||
monkeypatch.setattr("deerflow.community.opensandbox.provider.get_app_config", lambda: _stub_config(config))
|
||||
monkeypatch.setattr(OpenSandboxProvider, "_prepare_new_skill_view", lambda *a, **kw: None)
|
||||
monkeypatch.setattr(
|
||||
"deerflow.community.opensandbox.provider._import_sdk",
|
||||
lambda: (fake_sdk, _FakeConnectionConfig, _FakeRunCommandOpts),
|
||||
@ -539,6 +549,268 @@ def test_release_and_same_scope_warm_reclaim(monkeypatch: pytest.MonkeyPatch) ->
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def opensandbox_skill_view(monkeypatch: pytest.MonkeyPatch, tmp_path: Path):
|
||||
shell = shutil.which("sh")
|
||||
if os.name != "posix" or shell is None:
|
||||
pytest.skip("requires a POSIX remote filesystem and shell")
|
||||
paths = Paths(base_dir=tmp_path / "host")
|
||||
canonical = tmp_path / "skills"
|
||||
remote_roots = tmp_path / "remote"
|
||||
remote_roots.mkdir()
|
||||
skills_root = "/mnt/team skills"
|
||||
config = _stub_config()
|
||||
config.skills = SkillsConfig(path=str(canonical), container_path=skills_root)
|
||||
extensions = ExtensionsConfig(skills={"disabled": SkillStateConfig(enabled=False)})
|
||||
monkeypatch.setattr("deerflow.config.get_app_config", lambda: config)
|
||||
monkeypatch.setattr("deerflow.config.paths.get_paths", lambda: paths)
|
||||
monkeypatch.setattr("deerflow.config.extensions_config.ExtensionsConfig.from_file", lambda *a, **kw: extensions)
|
||||
monkeypatch.setattr("deerflow.config.extensions_config.get_extensions_config", lambda: extensions)
|
||||
|
||||
def create_remote(index):
|
||||
remote = _FakeRemote(f"remote-{index}")
|
||||
remote.skill_root = (remote_roots / remote.id).resolve()
|
||||
run_fallback = remote.commands.run
|
||||
|
||||
def run(command, *, opts=None):
|
||||
if skills_root not in command:
|
||||
return run_fallback(command, opts=opts)
|
||||
command = command.replace(shlex.quote(skills_root), shlex.quote(str(remote.skill_root)))
|
||||
command = command.replace(skills_root + "/", str(remote.skill_root) + "/")
|
||||
proc = subprocess.run([shell, "-c", command], capture_output=True, text=True, encoding="utf-8", check=False, timeout=5)
|
||||
return _execution(stdout=tuple(proc.stdout.splitlines()), stderr=(proc.stderr,), exit_code=proc.returncode)
|
||||
|
||||
def write(path, data, *, mode):
|
||||
remote.files.calls.append(("write_file", path))
|
||||
target = remote.skill_root / path.removeprefix(skills_root + "/")
|
||||
target.write_bytes(data)
|
||||
target.chmod(int(str(mode), 8))
|
||||
|
||||
remote.commands.run = run
|
||||
remote.files.write_file = write
|
||||
return remote
|
||||
|
||||
sdk = _FakeSandboxClass(create_remote)
|
||||
monkeypatch.setattr("deerflow.community.opensandbox.provider.get_app_config", lambda: config)
|
||||
monkeypatch.setattr("deerflow.sandbox.middleware.authorize_sandbox_execution", lambda **_: None)
|
||||
monkeypatch.setattr("deerflow.community.opensandbox.provider._import_sdk", lambda: (sdk, _FakeConnectionConfig, _FakeRunCommandOpts))
|
||||
provider = OpenSandboxProvider()
|
||||
set_sandbox_provider(provider)
|
||||
|
||||
def skill(name, *, owner=None):
|
||||
root = canonical / "public" if owner is None else paths.user_custom_skills_dir(owner)
|
||||
file = root / name / "SKILL.md"
|
||||
file.parent.mkdir(parents=True)
|
||||
file.write_text(f"---\nname: {name}\ndescription: Demo skill\n---\n\n{name}\n", encoding="utf-8")
|
||||
return file.parent
|
||||
|
||||
try:
|
||||
yield types.SimpleNamespace(provider=provider, sdk=sdk, paths=paths, config=config, skill=skill)
|
||||
finally:
|
||||
reset_sandbox_provider()
|
||||
provider.shutdown()
|
||||
|
||||
|
||||
def _remote_skills(remote):
|
||||
return {item.parent.name for item in remote.skill_root.rglob("SKILL.md")}
|
||||
|
||||
|
||||
def test_opensandbox_skill_views_replace_on_warm_reuse(opensandbox_skill_view):
|
||||
env = opensandbox_skill_view
|
||||
package = env.skill("alpha")
|
||||
helper = package / "helper's script"
|
||||
helper.write_bytes(b"#!/bin/sh\n")
|
||||
helper.chmod(0o755)
|
||||
env.skill("beta")
|
||||
env.skill("disabled")
|
||||
env.skill("alice-only", owner="alice")
|
||||
env.skill("bob-only", owner="bob")
|
||||
|
||||
alice_id = env.provider.acquire("thread", user_id="alice")
|
||||
alice = env.sdk.remotes[0]
|
||||
assert _remote_skills(alice) == {"alpha", "beta", "alice-only"}
|
||||
assert (alice.skill_root / "public" / "alpha" / helper.name).read_bytes() == helper.read_bytes()
|
||||
assert os.access(alice.skill_root / "public" / "alpha" / helper.name, os.X_OK)
|
||||
bob_id = env.provider.acquire("thread", user_id="bob")
|
||||
bob = env.sdk.remotes[1]
|
||||
assert bob_id != alice_id
|
||||
assert _remote_skills(bob) == {"alpha", "beta", "bob-only"}
|
||||
bob_projection = get_thread_skill_projection_paths(get_or_new_user_skill_storage("bob", app_config=env.config), "thread")
|
||||
with pytest.raises(RuntimeError, match="scope"):
|
||||
env.provider.sync_agent_skills(alice_id, thread_id="thread", user_id="bob", projection=bob_projection)
|
||||
with pytest.raises(RuntimeError, match="scope"):
|
||||
env.provider.sync_agent_skills(alice_id, thread_id="thread", user_id="alice", projection=bob_projection)
|
||||
assert _remote_skills(alice) == {"alpha", "beta", "alice-only"}
|
||||
env.provider.release(alice_id)
|
||||
|
||||
for allowlist, expected in [({"alpha"}, {"alpha"}), (set(), set()), (None, {"alpha", "beta", "alice-only"})]:
|
||||
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
|
||||
update = SandboxMiddleware(lazy_init=True, available_skills=allowlist).before_agent({}, runtime)
|
||||
assert update == {"sandbox": {"sandbox_id": alice_id}}
|
||||
assert _remote_skills(alice) == expected
|
||||
assert {p.name for p in alice.skill_root.iterdir()} == {"public", "custom", "legacy", "integrations"}
|
||||
env.provider.release(alice_id)
|
||||
assert len(env.sdk.remotes) == 2
|
||||
assert _remote_skills(bob) == {"alpha", "beta", "bob-only"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("restricted", [False, True])
|
||||
def test_opensandbox_skill_partial_upload_preserves_warm_workspace(opensandbox_skill_view, monkeypatch, restricted):
|
||||
env = opensandbox_skill_view
|
||||
env.skill("alpha")
|
||||
env.skill("beta")
|
||||
allowed = env.skill("allowed", owner="alice")
|
||||
(allowed / "asset").write_bytes(b"asset")
|
||||
sandbox_id = env.provider.acquire("thread", user_id="alice")
|
||||
remote = env.sdk.remotes[0]
|
||||
draft = "/mnt/user-data/workspace/draft.txt"
|
||||
remote.file_data[draft] = b"unsaved work"
|
||||
env.provider.release(sandbox_id)
|
||||
calls = []
|
||||
write = remote.files.write_file
|
||||
|
||||
def fail_second_write(path, data, *, mode):
|
||||
calls.append(path)
|
||||
if len(calls) == 2:
|
||||
raise OSError("upload interrupted")
|
||||
write(path, data, mode=mode)
|
||||
|
||||
monkeypatch.setattr(remote.files, "write_file", fail_second_write)
|
||||
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
|
||||
middleware = SandboxMiddleware(lazy_init=False, available_skills={"allowed"} if restricted else None)
|
||||
with pytest.raises(RuntimeError, match="skill projection"):
|
||||
middleware.before_agent({}, runtime)
|
||||
assert len(calls) == 2
|
||||
assert "sandbox_id" not in runtime.context
|
||||
assert env.provider.get(sandbox_id) is None
|
||||
assert remote.destroy_calls == 0
|
||||
assert (remote.skill_root / "custom" / "allowed").exists() is not restricted
|
||||
|
||||
assert middleware.before_agent({}, runtime) == {"sandbox": {"sandbox_id": sandbox_id}}
|
||||
assert len(env.sdk.remotes) == 1
|
||||
assert env.provider.get(sandbox_id).read_file(draft) == "unsaved work"
|
||||
assert _remote_skills(remote) == ({"allowed"} if restricted else {"alpha", "beta", "allowed"})
|
||||
assert {p.name for p in remote.skill_root.iterdir()} == {"public", "custom", "legacy", "integrations"}
|
||||
|
||||
|
||||
def test_opensandbox_skill_upload_preserves_package_links(opensandbox_skill_view, tmp_path):
|
||||
# The fake remote runs the production commands with the host's utilities.
|
||||
probe = subprocess.run(["ln", "-sT", "--", "target", tmp_path / "ln-probe"], capture_output=True, check=False, timeout=5)
|
||||
if probe.returncode != 0:
|
||||
pytest.skip("host ln does not support -sT for the fake OpenSandbox remote")
|
||||
|
||||
env = opensandbox_skill_view
|
||||
package = env.skill("allowed", owner="alice")
|
||||
assets = package / "assets"
|
||||
assets.mkdir()
|
||||
(assets / "data's.txt").write_bytes(b"data")
|
||||
(package / "file link").symlink_to("assets/data's.txt")
|
||||
(package / "dir link").symlink_to("assets", target_is_directory=True)
|
||||
(assets / "nested link").symlink_to("../file link")
|
||||
(assets / "empty").mkdir()
|
||||
(package / "empty link").symlink_to("assets/empty", target_is_directory=True)
|
||||
|
||||
runtime = Runtime(context={"thread_id": "thread", "user_id": "alice"})
|
||||
SandboxMiddleware(lazy_init=True, available_skills={"allowed"}).before_agent({}, runtime)
|
||||
uploaded = env.sdk.remotes[0].skill_root / "custom" / "allowed"
|
||||
assert (uploaded / "file link").is_symlink()
|
||||
assert (uploaded / "file link").read_bytes() == b"data"
|
||||
assert (uploaded / "dir link").is_symlink()
|
||||
assert (uploaded / "dir link" / "data's.txt").read_bytes() == b"data"
|
||||
assert (uploaded / "assets" / "nested link").is_symlink()
|
||||
assert (uploaded / "assets" / "nested link").read_bytes() == b"data"
|
||||
assert (uploaded / "empty link").is_symlink()
|
||||
assert (uploaded / "empty link").is_dir()
|
||||
|
||||
|
||||
def test_opensandbox_skill_upload_skips_unsafe_links_and_nonportable_names(opensandbox_skill_view, caplog):
|
||||
env = opensandbox_skill_view
|
||||
package = env.skill("alpha")
|
||||
env.skill("beta")
|
||||
(package / "external").symlink_to("../beta/SKILL.md")
|
||||
(package / "absolute").symlink_to(package / "SKILL.md")
|
||||
(package / "invalid\\name").write_bytes(b"skip")
|
||||
(package / "invalid\\directory").mkdir()
|
||||
(package / "invalid\\directory" / "child").write_bytes(b"skip")
|
||||
(package / "portable.txt").write_bytes(b"keep")
|
||||
(package / "broken").symlink_to("missing")
|
||||
|
||||
env.provider.acquire("thread", user_id="alice")
|
||||
remote = env.sdk.remotes[0]
|
||||
assert _remote_skills(remote) == {"alpha", "beta"}
|
||||
uploaded = remote.skill_root / "public" / "alpha"
|
||||
assert {p.name for p in uploaded.iterdir()} == {"SKILL.md", "portable.txt"}
|
||||
assert (uploaded / "portable.txt").read_bytes() == b"keep"
|
||||
assert "non-portable" in caplog.text
|
||||
|
||||
|
||||
def test_opensandbox_skill_upload_skips_non_utf8_filename(opensandbox_skill_view, caplog):
|
||||
env = opensandbox_skill_view
|
||||
package = env.skill("alpha")
|
||||
try:
|
||||
(package / os.fsdecode(b"non-utf8-\xff")).write_bytes(b"skip")
|
||||
except OSError as exc:
|
||||
if exc.errno in {errno.EILSEQ, errno.EINVAL, errno.EPERM}:
|
||||
pytest.skip("host filesystem cannot create a non-UTF-8 filename")
|
||||
raise
|
||||
|
||||
env.provider.acquire("thread", user_id="alice")
|
||||
uploaded = env.sdk.remotes[0].skill_root / "public" / "alpha"
|
||||
assert {p.name for p in uploaded.iterdir()} == {"SKILL.md"}
|
||||
assert "non-portable" in caplog.text
|
||||
|
||||
|
||||
def test_opensandbox_skill_sync_refuses_symlinked_remote_root(opensandbox_skill_view, tmp_path):
|
||||
env = opensandbox_skill_view
|
||||
sandbox_id = env.provider.acquire("thread", user_id="alice")
|
||||
remote = env.sdk.remotes[0]
|
||||
env.provider.release(sandbox_id)
|
||||
shutil.rmtree(remote.skill_root)
|
||||
destination = tmp_path / "unmanaged"
|
||||
destination.mkdir()
|
||||
marker = destination / "public"
|
||||
marker.write_bytes(b"keep")
|
||||
remote.skill_root.symlink_to(destination, target_is_directory=True)
|
||||
|
||||
with pytest.raises(RuntimeError, match="skill projection"):
|
||||
env.provider.acquire("thread", user_id="alice")
|
||||
assert marker.read_bytes() == b"keep"
|
||||
assert remote.destroy_calls == 1
|
||||
assert env.provider.get(sandbox_id) is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_server_proxy", [False, True])
|
||||
def test_opensandbox_skill_file_binary_sdk_payload(use_server_proxy):
|
||||
pytest.importorskip("opensandbox")
|
||||
from opensandbox.config.connection_sync import ConnectionConfigSync
|
||||
from opensandbox.models.sandboxes import SandboxEndpoint
|
||||
from opensandbox.sync.adapters.filesystem_adapter import FilesystemAdapterSync
|
||||
|
||||
path = "/mnt/team skills/public/example/executable"
|
||||
content = b"\x00\xff\r\n"
|
||||
requests = []
|
||||
|
||||
def reply(request):
|
||||
requests.append(request)
|
||||
assert request.url.path.endswith("/files/upload")
|
||||
body = request.read()
|
||||
assert content in body
|
||||
metadata = json.dumps({"path": path, "owner": None, "group": None, "mode": 755}).encode()
|
||||
assert metadata in body
|
||||
return httpx.Response(200)
|
||||
|
||||
remote = _FakeRemote("wire")
|
||||
remote.files = FilesystemAdapterSync(
|
||||
ConnectionConfigSync(transport=httpx.MockTransport(reply), use_server_proxy=use_server_proxy),
|
||||
SandboxEndpoint(endpoint="execd.test"),
|
||||
)
|
||||
try:
|
||||
_box(remote)._upload_skill_file(path, content, executable=True)
|
||||
finally:
|
||||
remote.files._httpx_client.close()
|
||||
assert len(requests) == 1
|
||||
|
||||
|
||||
def test_release_mirrors_outputs_for_gateway_download(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
||||
from app.gateway.routers.artifacts import _read_artifact_payload
|
||||
|
||||
|
||||
@ -95,6 +95,12 @@ Outputs with case- or Unicode-equivalent file or directory names are skipped
|
||||
before copying, and aliases of existing local paths are rejected, preserving
|
||||
previous complete copies.
|
||||
|
||||
OpenSandbox also uploads enabled skills to `skills.container_path`. An explicit
|
||||
Agent skill list replaces the managed skill directories before tools run; an
|
||||
empty list exposes no skills there. Switching Agents in the same thread
|
||||
refreshes the managed view. It does not delete files already copied to the
|
||||
workspace.
|
||||
|
||||
The optional [boxd provider](../../backend/packages/harness/deerflow/community/boxd_sandbox/README.md)
|
||||
runs each user/thread scope in an isolated boxd machine. A new machine receives
|
||||
the thread's files and skills before it is handed out, and release copies
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user