Skip to content
Merged
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
55 changes: 55 additions & 0 deletions .github/workflows/langchain-floo-sandbox.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
name: Deep Agents sandbox package

on:
pull_request:
paths:
- "python/langchain-floo-sandbox/**"
- ".github/workflows/langchain-floo-sandbox.yml"
push:
tags:
- "langchain-floo-sandbox-v*"

permissions:
contents: read

jobs:
build:
runs-on: ubuntu-latest
defaults:
run:
working-directory: python/langchain-floo-sandbox
steps:
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09
- uses: astral-sh/setup-uv@37802adc94f370d6bfd71619e3f0bf239e1f3b78
with:
python-version: "3.13"
- run: uv sync --locked --group test
- run: |
uv run --no-sync ruff check .
uv run --no-sync ruff format --check .
uv run --no-sync ty check langchain_floo_sandbox
uv run --no-sync pytest --disable-socket tests/unit_tests
- if: github.ref_type == 'tag'
run: |
version=$(uv version --short)
test "$GITHUB_REF_NAME" = "langchain-floo-sandbox-v${version}"
- run: uv build
- uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f
with:
name: python-dist
path: python/langchain-floo-sandbox/dist/
if-no-files-found: error

publish:
if: github.repository == 'getfloo/floo-cli' && github.ref_type == 'tag'
needs: build
runs-on: ubuntu-latest
environment: langchain-floo-sandbox-pypi
permissions:
id-token: write
steps:
- uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131
with:
name: python-dist
path: dist/
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086
3 changes: 3 additions & 0 deletions python/langchain-floo-sandbox/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__/
dist/
.venv/
21 changes: 21 additions & 0 deletions python/langchain-floo-sandbox/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) LangChain, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
42 changes: 42 additions & 0 deletions python/langchain-floo-sandbox/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# floo sandbox backend for Deep Agents

`FlooSandbox` runs a Deep Agents agent's shell commands and file operations in an existing floo sandbox. Install the package with Python 3.11 or later.

```sh
pip install "langchain-floo-sandbox @ git+https://github.com/getfloo/floo-cli.git@langchain-floo-sandbox-v0.0.1#subdirectory=python/langchain-floo-sandbox"
```

Set `FLOO_API_KEY`. For a personal key, also set `FLOO_ORG_ID` to the org that owns the sandbox.

```python
import floo_sandbox as floo
from langchain_floo_sandbox import FlooSandbox

app = floo.App.lookup("deepagents", create_if_missing=True)
sandbox = floo.Sandbox.create(app=app, image=floo.Image.debian_slim(), timeout=300)
try:
backend = FlooSandbox(sandbox=sandbox)
# Pass backend to create_deep_agent(..., backend=backend).
result = backend.write("/app/input.txt", "hello from floo\n")
assert result.error is None, result.error
command = backend.execute("tr a-z A-Z < /app/input.txt > /app/output.txt")
assert command.exit_code == 0, command.output
output, = backend.download_files(["/app/output.txt"])
assert output.content == b"HELLO FROM FLOO\n"
finally:
sandbox.terminate(wait=True)
```

Pass the backend to `create_deep_agent(model=model, backend=backend)` while the sandbox is open. The caller chooses the model and closes the sandbox.

## Run the tests

From this directory, run:

```sh
uv sync --locked --group test
uv run --locked --group test pytest --disable-socket tests/unit_tests
uv run --locked --group test pytest --timeout 120 tests/integration_tests
```

The integration tests use your floo credentials and create two short-lived sandboxes. Seven assertions in `langchain-tests==1.2.0` have strict expected failures. Deep Agents returns absolute file paths, excludes directories from glob results, and replaces existing files on write. The lifecycle test checks all three behaviors.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""floo sandbox backend for Deep Agents."""

from langchain_floo_sandbox.sandbox import FlooSandbox

__all__ = ["FlooSandbox"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
"""Version information for `langchain-floo-sandbox`."""

# Keep the `x-release-please-version` annotation. Release Please uses it to
# bump `__version__` in sync with `pyproject.toml` on every release PR.
__version__ = "0.0.1" # x-release-please-version
172 changes: 172 additions & 0 deletions python/langchain-floo-sandbox/langchain_floo_sandbox/sandbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""Run Deep Agents file and shell operations in a floo sandbox."""

from __future__ import annotations

from typing import TYPE_CHECKING

from deepagents.backends.protocol import (
FILE_NOT_FOUND,
INVALID_PATH,
IS_DIRECTORY,
PERMISSION_DENIED,
ExecuteResponse,
FileDownloadResponse,
FileUploadResponse,
)
from deepagents.backends.sandbox import BaseSandbox
from floo_sandbox import exception

if TYPE_CHECKING:
from floo_sandbox import Sandbox


# Keep each SDK request below the filesystem and transport size limits.
_CHUNK_BYTES = 512 * 1024
# Leave room for request metadata in the SDK's 8 MiB transport frame.
_MAX_INLINE_UPLOAD = 7 * 1024 * 1024

# Stage beside the destination so a short or interrupted upload leaves it intact.
_WRITE_STREAM = """
import os
import shutil
import stat
import sys
import tempfile
from pathlib import Path

path = Path(sys.argv[1]).resolve()
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as temp:
try:
shutil.copyfileobj(sys.stdin.buffer, temp)
if temp.tell() != int(sys.argv[2]):
sys.exit("Incomplete file upload")
temp.flush()
if path.exists():
mode = path.stat().st_mode
if not stat.S_ISREG(mode):
sys.exit("Destination is not a regular file")
os.chmod(temp.name, mode & 0o777)
os.replace(temp.name, path)
finally:
Path(temp.name).unlink(missing_ok=True)
"""


# Measure the opened file, including when the requested path is a symlink.
_READ_STREAM = """
import os
import shutil
import sys

with open(sys.argv[1], "rb") as source:
print(os.fstat(source.fileno()).st_size, file=sys.stderr)
shutil.copyfileobj(source, sys.stdout.buffer)
"""


def _file_error(error: exception.SandboxFilesystemError) -> str:
if isinstance(
error,
(
exception.SandboxFilesystemNotFoundError,
exception.SandboxFilesystemNotADirectoryError,
),
):
return FILE_NOT_FOUND
if isinstance(error, exception.SandboxFilesystemIsADirectoryError):
return IS_DIRECTORY
if isinstance(error, exception.SandboxFilesystemPermissionError):
return PERMISSION_DENIED
return str(error)


class FlooSandbox(BaseSandbox):
"""Deep Agents backend for a caller-owned floo sandbox."""

def __init__(self, *, sandbox: Sandbox) -> None:
"""Wrap an existing sandbox. The caller owns its lifetime."""
self._sandbox = sandbox

@property
def id(self) -> str:
"""Return the floo sandbox ID."""
return self._sandbox.object_id

def execute(self, command: str, *, timeout: int | None = None) -> ExecuteResponse:
"""Run a shell command with an optional timeout in seconds."""
process = self._sandbox.exec("bash", "-c", command, timeout=timeout, text=False)
code = process.wait()
streams = (process.stdout.read(), process.stderr.read())
output = b"\n".join(part for part in streams if part).decode(errors="replace")
return ExecuteResponse(output=output, exit_code=code, truncated=False)

def _write_bytes(self, path: str, content: bytes) -> str | None:
if len(content) <= _MAX_INLINE_UPLOAD:
try:
self._sandbox.filesystem.write_bytes(content, path)
except exception.SandboxFilesystemFileTooLargeError:
pass # Fall back to streaming when the workspace rejects the size.
else:
return None
process = self._sandbox.exec(
"python3", "-c", _WRITE_STREAM, path, str(len(content)), timeout=300
)
try:
for start in range(0, len(content), _CHUNK_BYTES):
process.stdin.write(content[start : start + _CHUNK_BYTES])
process.stdin.drain()
finally:
process.stdin.write_eof()
process.stdin.drain()
return None if process.wait() == 0 else process.stderr.read() or "Upload failed"

def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
"""Write each file to its absolute workspace path."""
results = []
for path, content in files:
result = FileUploadResponse(path=path)
if not path.startswith("/") or "\x00" in path:
result.error = INVALID_PATH
else:
try:
result.error = self._write_bytes(path, content)
except exception.SandboxFilesystemError as error:
result.error = _file_error(error)
results.append(result)
return results

def _read_bytes(self, path: str) -> FileDownloadResponse:
try:
return FileDownloadResponse(
path=path, content=self._sandbox.filesystem.read_bytes(path)
)
except exception.SandboxFilesystemFileTooLargeError:
process = self._sandbox.exec(
"python3", "-c", _READ_STREAM, path, text=False
)
if process.wait() != 0:
return FileDownloadResponse(
path=path,
error=process.stderr.read().decode(errors="replace")
or "Download failed",
)
content = process.stdout.read()
if process.stderr.read().strip() != str(len(content)).encode():
return FileDownloadResponse(path=path, error="Incomplete file download")
return FileDownloadResponse(path=path, content=content)

def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
"""Read each file as bytes, returning a result for each requested path."""
results = []
for path in paths:
result = FileDownloadResponse(path=path)
if not path.startswith("/") or "\x00" in path:
result.error = INVALID_PATH
else:
try:
result = self._read_bytes(path)
except exception.SandboxFilesystemError as error:
result.error = _file_error(error)
results.append(result)
return results
Loading