Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
- 手机截图写到专家自己的工作区。只改定时任务文案时,间隔任务不再重新计时
- 浏览器工作台恢复中文输入。主动关怀等对话安静后再发
- 向导密码随数据目录迁移。Linux 桌面无边框窗口可以拖边缘调整大小
- OpenSandbox 存储后端缺 `mkdir_path` / `delete_path` / `move_path` 三个工作区原语,非挂载启动专家直接失败;Octop 兼容层已补齐(Fixes #1813)

### 变更
- 云端协同默认打码对端地址和账号。共享来的资源在头像上做标记
Expand Down
55 changes: 55 additions & 0 deletions src/octop/infra/backend/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@

import asyncio
import inspect
import posixpath
import shlex
import threading
from collections.abc import Coroutine
from concurrent.futures import Future
Expand All @@ -48,12 +50,65 @@ def adapt_backend_protocol(backend: Any) -> Any:
if isinstance(backend, _LegacyProtocolBackend):
return backend
if not _needs_adapt(backend):
_patch_sandbox_path_ops(backend)
return backend
wrapped = _LegacyProtocolBackend(backend)
_patch_s3_list_v1(backend)
return wrapped


_SANDBOX_PATH_OPS = ("mkdir_path", "delete_path", "move_path")


def _patch_sandbox_path_ops(backend: Any) -> None:
"""Add the missing workspace mutation primitives to sandbox backends.

``octop_harness``'s ``OpenSandbox`` implements the deepagents ``BaseSandbox``
file surface with ``execute`` but not the ``mkdir_path`` / ``delete_path`` /
``move_path`` helpers ``DockerSandbox`` adds, so ``BackendWorkspace.mkdir``
raises ``BackendOperationNotSupportedError`` on workspace init and every
agent on that backend fails to start. Workspace files live inside the
sandbox (``sandbox_fs``), so no host mount can take over the fallback.

Patch the helpers in place with the same ``execute`` commands
``octop_harness.backends.docker_sandbox`` uses. Wrapping the backend would
drop the ``SandboxBackendProtocol`` instance behind ``supports_execution``.
No-op once the harness backend defines them itself.
"""
if not callable(getattr(backend, "execute", None)):
return
if not getattr(backend, "sandbox_fs", False):
return
if all(callable(getattr(backend, name, None)) for name in _SANDBOX_PATH_OPS):
return

def mkdir_path(path: str) -> None:
result = backend.execute(f"mkdir -p {shlex.quote(str(path))}")
if result.exit_code not in (0, None):
raise OSError(result.output or f"mkdir failed for {path!r}")

def delete_path(path: str) -> None:
result = backend.execute(f"rm -rf {shlex.quote(str(path))}")
if result.exit_code not in (0, None):
raise OSError(result.output or f"delete failed for {path!r}")

def move_path(src: str, dest: str) -> None:
parent = posixpath.dirname(str(dest)) or "/"
result = backend.execute(
f"mkdir -p {shlex.quote(parent)} && mv {shlex.quote(str(src))} {shlex.quote(str(dest))}"
)
if result.exit_code not in (0, None):
raise OSError(result.output or f"move failed for {src!r} -> {dest!r}")

for name, patched in (
("mkdir_path", mkdir_path),
("delete_path", delete_path),
("move_path", move_path),
):
if not callable(getattr(backend, name, None)):
setattr(backend, name, patched)


async def _s3_als_info_v1(backend: Any, path: str) -> list[Any]:
prefix = path.lstrip("/")
if prefix and not prefix.endswith("/"):
Expand Down
86 changes: 85 additions & 1 deletion tests/unit/backend/test_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,13 @@
from __future__ import annotations

import asyncio
from pathlib import Path
from types import SimpleNamespace

import pytest
from deepagents.backends.protocol import BackendProtocol, ReadResult
from deepagents.backends.protocol import BackendProtocol, ExecuteResponse, ReadResult
from octop_harness.backends.utils import BackendOperationNotSupportedError
from octop_harness.backends.workspace import BackendWorkspace

from octop.infra.backend.compat import adapt_backend_protocol, is_adapted_backend

Expand Down Expand Up @@ -262,3 +265,84 @@ async def als_info(self, path: str) -> list[dict[str, object]]:
wrapped = compat.adapt_backend_protocol(_Hung())
with pytest.raises(TimeoutError, match="backend I/O timed out"):
wrapped.ls("/")


class _FakeSandbox:
"""Mirrors ``octop_harness`` OpenSandbox: execute-capable, no path ops."""

sandbox_fs = True
virtual_mode = True

def __init__(self, *, exit_code: int = 0, output: str = "") -> None:
self.commands: list[str] = []
self._exit_code = exit_code
self._output = output

def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
del timeout
self.commands.append(command)
return ExecuteResponse(output=self._output, exit_code=self._exit_code, truncated=False)


def test_unpatched_sandbox_backend_cannot_mkdir(tmp_path: Path) -> None:
"""The harness contract ``adapt_backend_protocol`` has to bridge (issue #1813)."""
with pytest.raises(BackendOperationNotSupportedError, match="mkdir"):
BackendWorkspace(_FakeSandbox(), tmp_path).mkdir("skills/demo")


def test_sandbox_path_ops_enable_workspace_mutations(tmp_path: Path) -> None:
backend = _FakeSandbox()
adapted = adapt_backend_protocol(backend)
assert adapted is backend
assert adapt_backend_protocol(adapted) is adapted

workspace = BackendWorkspace(adapted, tmp_path)
workspace.mkdir("skills/demo")
workspace.delete("skills/demo")
workspace.move("SOUL.md", "skills/demo/SOUL.md")
workspace.mkdir("a b")
assert backend.commands == [
"mkdir -p /skills/demo",
"rm -rf /skills/demo",
"mkdir -p /skills/demo && mv /SOUL.md /skills/demo/SOUL.md",
"mkdir -p '/a b'",
]


def test_sandbox_path_ops_raise_on_failure() -> None:
adapted = adapt_backend_protocol(_FakeSandbox(exit_code=1, output="denied"))
with pytest.raises(OSError, match="denied"):
adapted.mkdir_path("/skills")
with pytest.raises(OSError, match="denied"):
adapted.delete_path("/skills")
with pytest.raises(OSError, match="denied"):
adapted.move_path("/a", "/b")


def test_sandbox_path_ops_keep_existing_implementations() -> None:
class _WithPathOps(_FakeSandbox):
def __init__(self) -> None:
super().__init__()
self.mkdirs: list[str] = []

def mkdir_path(self, path: str) -> None:
self.mkdirs.append(path)

backend = _WithPathOps()
adapted = adapt_backend_protocol(backend)
adapted.mkdir_path("/skills")
assert backend.mkdirs == ["/skills"]
assert backend.commands == []


def test_sandbox_path_ops_skip_backends_without_sandbox_fs() -> None:
class _ShellLike:
virtual_mode = True

def execute(self, command: str) -> ExecuteResponse:
raise AssertionError("must not run")

adapted = adapt_backend_protocol(_ShellLike())
assert not callable(getattr(adapted, "mkdir_path", None))
assert not callable(getattr(adapted, "delete_path", None))
assert not callable(getattr(adapted, "move_path", None))