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
134 changes: 92 additions & 42 deletions src/agents/sandbox/sandboxes/unix_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,12 @@
import time
import uuid
from collections import deque
from collections.abc import Collection, Mapping, Sequence
from collections.abc import Callable, Collection, Mapping, Sequence
from contextlib import suppress
from dataclasses import dataclass, field
from functools import partial
from pathlib import Path
from typing import Literal, cast
from typing import Any, Literal, TypeVar, cast

from ...logger import log_tool_action_warning
from .._mount_security import redact_mount_error_data
Expand Down Expand Up @@ -73,6 +73,8 @@
_DEFAULT_MANIFEST_ROOT = cast(str, Manifest.model_fields["root"].default)
_PTY_READ_CHUNK_BYTES = 16_384
_PTY_CHILD_SIGNAL_DEFAULTS = (signal.SIGINT, signal.SIGQUIT)

_WorkspaceIOResultT = TypeVar("_WorkspaceIOResultT")
_PTY_FD_CLOSE_GRACE_SECONDS = 0.1
_HOST_ENVIRONMENT_ALLOWLIST = frozenset(
{
Expand Down Expand Up @@ -116,6 +118,90 @@ def _restore_pty_child_signal_defaults() -> None:
signal.signal(signum, signal.SIG_DFL)


async def _run_workspace_io(
func: Callable[..., _WorkspaceIOResultT],
*args: Any,
) -> _WorkspaceIOResultT:
"""Run blocking workspace I/O on a worker thread and own that worker's lifetime.

``asyncio.to_thread`` cannot interrupt the thread it starts, so returning as soon as the
caller is cancelled would report the operation as stopped while the worker is still
walking or writing the workspace. Callers act on that immediately: the snapshot
lifecycle closes the archive stream in a ``finally`` as soon as the await returns, and a
resume clears the workspace root. Either would land on a live worker.

So the cancellation is recorded, the worker is allowed to settle, and only then does the
cancellation propagate. Repeated cancellation is absorbed the same way. This mirrors
``memory.sqlite_session._await_mutation``, which owns cancellation for session writes.
"""
task = asyncio.ensure_future(asyncio.to_thread(func, *args))
cancellation: asyncio.CancelledError | None = None
while not task.done():
try:
await asyncio.wait({task})
except asyncio.CancelledError as exc:
if cancellation is None:
cancellation = exc

if cancellation is not None:
# Consume any worker failure so it is not reported as never retrieved. The caller
# asked to stop, so the cancellation is what it hears about.
task.exception()
raise cancellation from None
return task.result()


# The two helpers below carry the unbounded workspace I/O. They run on a worker thread via
# ``_run_workspace_io`` so archiving and extraction do not hold the event loop; keeping them
# at module level makes that boundary obvious and keeps session state on the loop side of it.


def _archive_workspace(root: Path, skip: set[Path]) -> io.BytesIO:
"""Tar the whole workspace tree into an in-memory archive."""
if not root.exists():
raise WorkspaceArchiveReadError(path=root, context={"reason": "workspace_root_not_found"})

buf = io.BytesIO()
try:
with tarfile.open(fileobj=buf, mode="w") as tar:
tar.add(
root,
arcname=".",
filter=lambda ti: (
None
if should_skip_tar_member(
ti.name,
skip_rel_paths=skip,
root_name=None,
)
else ti
),
)
except (tarfile.TarError, OSError) as e:
raise WorkspaceArchiveReadError(path=root, cause=e) from e

buf.seek(0)
return buf


def _extract_workspace_archive(root: Path, data: io.IOBase) -> None:
"""Extract an archive over the workspace tree."""
try:
root.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=data, mode="r:*") as tar:
safe_extract_tarfile(
tar,
root=root,
allow_external_symlink_targets=False,
)
except UnsafeTarMemberError as e:
raise WorkspaceArchiveWriteError(
path=root, context={"reason": e.reason, "member": e.member}, cause=e
) from e
except (tarfile.TarError, OSError) as e:
raise WorkspaceArchiveWriteError(path=root, cause=e) from e


class UnixLocalSandboxSessionState(SandboxSessionState):
type: Literal["unix_local"] = "unix_local"
workspace_root_owned: bool = False
Expand Down Expand Up @@ -1075,51 +1161,15 @@ async def running(self) -> bool:
return self._running

async def persist_workspace(self) -> io.IOBase:
# Archiving the whole workspace tree is unbounded work, so it runs on a worker
# thread. Session state is read here, on the loop, and only plain values cross over.
root = Path(self.state.manifest.root)
if not root.exists():
raise WorkspaceArchiveReadError(
path=root, context={"reason": "workspace_root_not_found"}
)

skip = self._persist_workspace_skip_relpaths()
buf = io.BytesIO()
try:
with tarfile.open(fileobj=buf, mode="w") as tar:
tar.add(
root,
arcname=".",
filter=lambda ti: (
None
if should_skip_tar_member(
ti.name,
skip_rel_paths=skip,
root_name=None,
)
else ti
),
)
except (tarfile.TarError, OSError) as e:
raise WorkspaceArchiveReadError(path=root, cause=e) from e

buf.seek(0)
return buf
return await _run_workspace_io(_archive_workspace, root, skip)

async def hydrate_workspace(self, data: io.IOBase) -> None:
root = Path(self.state.manifest.root)
try:
root.mkdir(parents=True, exist_ok=True)
with tarfile.open(fileobj=data, mode="r:*") as tar:
safe_extract_tarfile(
tar,
root=root,
allow_external_symlink_targets=False,
)
except UnsafeTarMemberError as e:
raise WorkspaceArchiveWriteError(
path=root, context={"reason": e.reason, "member": e.member}, cause=e
) from e
except (tarfile.TarError, OSError) as e:
raise WorkspaceArchiveWriteError(path=root, cause=e) from e
await _run_workspace_io(_extract_workspace_archive, root, data)


class UnixLocalSandboxClient(BaseSandboxClient[UnixLocalSandboxClientOptions | None]):
Expand Down
Loading