From 8bd7e9dd39f2aec8026ab7430a6d8c2f4c928064 Mon Sep 17 00:00:00 2001 From: Patrick Donohoe Date: Thu, 26 Nov 2026 13:18:04 -0500 Subject: [PATCH 1/2] Add the floo sandbox provider for the OpenAI Agents SDK --- python/openai-agents-floo/.gitignore | 3 + python/openai-agents-floo/LICENSE | 21 ++ python/openai-agents-floo/README.md | 61 +++++ python/openai-agents-floo/pyproject.toml | 17 ++ .../src/openai_agents_floo/__init__.py | 3 + .../src/openai_agents_floo/provider.py | 166 ++++++++++++ .../src/openai_agents_floo/py.typed | 0 .../src/openai_agents_floo/session.py | 246 ++++++++++++++++++ .../src/openai_agents_floo/state.py | 34 +++ .../openai-agents-floo/tests/live_runner.py | 136 ++++++++++ .../openai-agents-floo/tests/live_session.py | 151 +++++++++++ .../openai-agents-floo/tests/test_provider.py | 162 ++++++++++++ 12 files changed, 1000 insertions(+) create mode 100644 python/openai-agents-floo/.gitignore create mode 100644 python/openai-agents-floo/LICENSE create mode 100644 python/openai-agents-floo/README.md create mode 100644 python/openai-agents-floo/pyproject.toml create mode 100644 python/openai-agents-floo/src/openai_agents_floo/__init__.py create mode 100644 python/openai-agents-floo/src/openai_agents_floo/provider.py create mode 100644 python/openai-agents-floo/src/openai_agents_floo/py.typed create mode 100644 python/openai-agents-floo/src/openai_agents_floo/session.py create mode 100644 python/openai-agents-floo/src/openai_agents_floo/state.py create mode 100644 python/openai-agents-floo/tests/live_runner.py create mode 100644 python/openai-agents-floo/tests/live_session.py create mode 100644 python/openai-agents-floo/tests/test_provider.py diff --git a/python/openai-agents-floo/.gitignore b/python/openai-agents-floo/.gitignore new file mode 100644 index 0000000..b61da32 --- /dev/null +++ b/python/openai-agents-floo/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +dist/ +.ruff_cache/ diff --git a/python/openai-agents-floo/LICENSE b/python/openai-agents-floo/LICENSE new file mode 100644 index 0000000..1e47d24 --- /dev/null +++ b/python/openai-agents-floo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 floo contributors + +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. diff --git a/python/openai-agents-floo/README.md b/python/openai-agents-floo/README.md new file mode 100644 index 0000000..515a121 --- /dev/null +++ b/python/openai-agents-floo/README.md @@ -0,0 +1,61 @@ +# openai-agents-floo + +Run the OpenAI Agents SDK shell and filesystem tools in a floo sandbox. This package targets `openai-agents==0.26.0` and `floo-sandbox==0.2.0`. + +Install from the root of this checkout with Python 3.11 or newer. + +```sh +python -m pip install ./python/openai-agents-floo +``` + +Set `FLOO_API_KEY` in the application environment and `FLOO_APP_NAME` to an existing app. Set `FLOO_ORG_ID` to select an org when using a personal key. The floo SDK manages its shared transport. The provider captures that transport when you construct the client. + +```python +import asyncio +import os + +from agents import RunConfig, Runner +from agents.sandbox import SandboxAgent, SandboxRunConfig +from openai_agents_floo import FlooSandboxClient, FlooSandboxOptions + + +async def main(): + agent = SandboxAgent(name="Analyst", instructions="Use the sandbox to check your work.") + config = RunConfig(sandbox=SandboxRunConfig( + client=FlooSandboxClient(os.environ["FLOO_APP_NAME"]), + options=FlooSandboxOptions(lifetime_seconds=300), + )) + result = await Runner.run(agent, "Write and run a Python program that sums 1 through 100.", run_config=config) + print(result.final_output) + + +asyncio.run(main()) +``` + +This example uses the application's configured model. The live tests below use scripted turns and need only floo credentials. + +## Workspace and lifecycle + +Commands run with `/workspace` as their working directory. SDK file operations accept binary files and stay within that directory. Manifests support inline `File` and `Dir` entries, including nested and ephemeral entries. Commands run as the guest's default user with outbound networking blocked. The provider supports one-shot commands. PTYs, user switching, ports, host files, mounts, extra path grants, and manifest environment variables are unsupported. + +With `SandboxRunConfig(client=...)`, the runner starts and cleans up the sandbox. With `SandboxRunConfig(session=...)`, the application owns the session. Call `await session.aclose()` to persist its configured snapshot and terminate it. Use `await client.delete(session)` in a cleanup `finally` block to terminate a partially initialized session. Deletion is idempotent. + +Import `openai_agents_floo` in each resume worker. Save the SDK run state in trusted application storage. For a standalone session, use `client.serialize_session_state(session.state)`, then `await client.resume(client.deserialize_session_state(payload))`. Resuming a live sandbox transfers lifecycle ownership to the resumed handle. + +Version 0.1.0 records the `floo` backend ID, SDK session UUID, app name, floo sandbox ID, creation options, manifest, and SDK snapshot metadata. Resume with the same app and org. After termination, recovery requires the persisted snapshot. The runner selects its local snapshot directory by default. For a custom directory, pass the same absolute path to `FlooSandboxClient(snapshot_dir=...)` and `LocalSnapshotSpec(base_path=...)`. All resume workers need access to those archives. Direct `client.create()` uses a no-op snapshot by default and can reconnect only while the sandbox exists. + +Workspace files survive consecutive commands on the same sandbox. A replacement sandbox restores the workspace archive, including file modes. System packages, files outside the workspace, and background processes are outside the archive. Long-running processes require their original guest to remain running. Use a workspace-local dependency directory for dependencies that must survive restore. + +## Verify + +From this directory, build the wheel with `python -m build --wheel`, install it into a fresh environment, and run the following with that environment's Python. Set `FLOO_AGENTS_TEST_APP` to an existing app for the two live checks. + +```sh +python -m unittest discover -s tests -v +python tests/live_session.py +python tests/live_runner.py +``` + +The live checks allocate short-lived floo sandboxes and verify their final status. They use temporary local directories for snapshots. + +[OpenAI custom sandbox provider contract](https://openai.github.io/openai-agents-python/sandbox/custom-providers/) diff --git a/python/openai-agents-floo/pyproject.toml b/python/openai-agents-floo/pyproject.toml new file mode 100644 index 0000000..36091b6 --- /dev/null +++ b/python/openai-agents-floo/pyproject.toml @@ -0,0 +1,17 @@ +[build-system] +requires = ["hatchling>=1.27"] +build-backend = "hatchling.build" + +[project] +name = "openai-agents-floo" +version = "0.1.0" +description = "Run OpenAI Agents SDK sandbox sessions on floo." +requires-python = ">=3.11" +readme = "README.md" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "floo" }] +dependencies = ["openai-agents==0.26.0", "floo-sandbox==0.2.0"] + +[tool.hatch.build.targets.wheel] +packages = ["src/openai_agents_floo"] diff --git a/python/openai-agents-floo/src/openai_agents_floo/__init__.py b/python/openai-agents-floo/src/openai_agents_floo/__init__.py new file mode 100644 index 0000000..71af2c3 --- /dev/null +++ b/python/openai-agents-floo/src/openai_agents_floo/__init__.py @@ -0,0 +1,3 @@ +from .provider import FlooSandboxClient, FlooSandboxOptions, FlooSandboxState + +__all__ = ["FlooSandboxClient", "FlooSandboxOptions", "FlooSandboxState"] diff --git a/python/openai-agents-floo/src/openai_agents_floo/provider.py b/python/openai-agents-floo/src/openai_agents_floo/provider.py new file mode 100644 index 0000000..98ae01e --- /dev/null +++ b/python/openai-agents-floo/src/openai_agents_floo/provider.py @@ -0,0 +1,166 @@ +"""The OpenAI Agents SDK client and persisted state for floo sandboxes.""" + +import asyncio +from pathlib import Path +from typing import cast +from uuid import uuid4 + +from agents.sandbox.errors import WorkspaceStartError +from agents.sandbox.manifest import Manifest +from agents.sandbox.session import ( + BaseSandboxClient, + Instrumentation, + SandboxSession, + SandboxSessionState, +) +from agents.sandbox.snapshot import ( + LocalSnapshot, + NoopSnapshot, + SnapshotBase, + SnapshotSpec, + resolve_snapshot, +) +from agents.sandbox.snapshot_defaults import default_local_snapshot_base_dir +from floo_sandbox import App, Sandbox +from floo_sandbox import exception as floo_errors +from floo_sandbox.carrier import given + +from .session import FlooSandboxSession, error_details +from .state import FlooSandboxOptions, FlooSandboxState, validate_manifest + + +class FlooSandboxClient(BaseSandboxClient[FlooSandboxOptions]): + backend_id = "floo" + supports_default_options = True + + def __init__( + self, + app_name: str, + *, + snapshot_dir: Path | None = None, + instrumentation: Instrumentation | None = None, + ) -> None: + if not app_name: + raise ValueError("supply an existing floo app name") + self.app_name = app_name + self.snapshot_dir = ( + snapshot_dir or default_local_snapshot_base_dir() + ).resolve() + self._instrumentation = instrumentation + # Capture the authenticated transport once. A later environment change must + # not move a resumed session or cleanup request into another org. + self._connection = given(None) + + def _validate_state(self, state: FlooSandboxState) -> None: + if state.app_name != self.app_name: + raise ValueError("state belongs to a different floo app") + state.assert_path_grants_rebound() + self._validate_manifest_for_create(state.manifest) + validate_manifest(state.manifest) + if state.exposed_ports: + raise ValueError( + "floo does not support exposed ports in Agents SDK sessions" + ) + if isinstance(state.snapshot, LocalSnapshot): + if ( + state.snapshot.base_path.resolve() != self.snapshot_dir + or state.snapshot.id != str(state.session_id) + ): + raise ValueError( + "local snapshot must use the client's snapshot directory and session ID" + ) + elif not isinstance(state.snapshot, NoopSnapshot): + raise ValueError("floo supports local and no-op SDK snapshots") + + async def create( + self, + *, + snapshot: SnapshotSpec | SnapshotBase | None = None, + manifest: Manifest | None = None, + options: FlooSandboxOptions | None = None, + ) -> SandboxSession: + if options is not None and not isinstance(options, FlooSandboxOptions): + raise TypeError("expected FlooSandboxOptions") + session_id = uuid4() + state = FlooSandboxState( + app_name=self.app_name, + session_id=session_id, + manifest=manifest or Manifest(), + options=options or FlooSandboxOptions(), + snapshot=resolve_snapshot(snapshot, str(session_id)), + ) + return await self._open(state, resume=False) + + async def resume(self, state: SandboxSessionState) -> SandboxSession: + if not isinstance(state, FlooSandboxState): + raise TypeError("expected FlooSandboxState") + return await self._open(state.model_copy(deep=True), resume=True) + + async def _open(self, state: FlooSandboxState, *, resume: bool) -> SandboxSession: + self._validate_state(state) + name = f"agents-{state.session_id.hex}" + sandbox = None + preserved = False + try: + if resume and state.sandbox_id: + try: + sandbox = await Sandbox.from_name.aio( + self.app_name, name, client=self._connection + ) + except floo_errors.NotFoundError: + pass + if sandbox is not None and sandbox.object_id != state.sandbox_id: + raise ValueError("a different floo sandbox holds this session name") + preserved = sandbox is not None + if sandbox is None: + if resume and not await state.snapshot.restorable(): + raise WorkspaceStartError( + path=Path("/workspace"), + message="sandbox ended without a restorable snapshot", + ) + app = await App.lookup.aio(self.app_name, client=self._connection) + # A cancelled await cannot cancel the in-flight remote allocation. + # Recover its handle and terminate it before propagating cancellation. + allocation = asyncio.create_task( + Sandbox.create.aio( + app=app, + name=name, + timeout=state.options.lifetime_seconds, + block_network=True, + ) + ) + try: + sandbox = await asyncio.shield(allocation) + except asyncio.CancelledError: + sandbox = await allocation + await sandbox.terminate.aio() + raise + state.sandbox_id = sandbox.object_id + state.workspace_root_ready = False + except (floo_errors.Error, OSError) as exc: + raise WorkspaceStartError( + path=Path("/workspace"), **error_details(exc) + ) from None + + inner = FlooSandboxSession(state, sandbox, preserved) + try: + return self._wrap_session(inner, instrumentation=self._instrumentation) + except BaseException: + await inner.shutdown() + raise + + async def delete(self, session: SandboxSession) -> SandboxSession: + if not isinstance(session._inner, FlooSandboxSession): + raise TypeError("expected a floo session") + await session.shutdown() + return session + + def deserialize_session_state(self, payload: dict[str, object]) -> FlooSandboxState: + if payload.get("type") != self.backend_id: + raise ValueError("expected floo sandbox state") + state = cast( + FlooSandboxState, + self._deserialize_session_state_payload(dict(payload), FlooSandboxState), + ) + self._validate_state(state) + return state diff --git a/python/openai-agents-floo/src/openai_agents_floo/py.typed b/python/openai-agents-floo/src/openai_agents_floo/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/python/openai-agents-floo/src/openai_agents_floo/session.py b/python/openai-agents-floo/src/openai_agents_floo/session.py new file mode 100644 index 0000000..1ff9d9c --- /dev/null +++ b/python/openai-agents-floo/src/openai_agents_floo/session.py @@ -0,0 +1,246 @@ +import asyncio +import io +import math +from pathlib import Path +from typing import Any + +from agents.sandbox.errors import ( + ExecTimeoutError, + ExecTransportError, + WorkspaceArchiveReadError, + WorkspaceArchiveWriteError, + WorkspaceReadNotFoundError, + WorkspaceStartError, + WorkspaceStopError, + WorkspaceWriteTypeError, +) +from agents.sandbox.manifest import Manifest +from agents.sandbox.materialization import MaterializationResult +from agents.sandbox.session import BaseSandboxSession +from agents.sandbox.types import ExecResult, User +from agents.sandbox.util.tar_utils import validate_tar_bytes +from floo_sandbox import Sandbox +from floo_sandbox import exception as floo_errors + +from .state import FlooSandboxState, validate_manifest + +ROOT = Path("/workspace") + + +def error_details(exc: Exception) -> dict[str, Any]: + # Provider errors can include the request body or output. Only carry the class + # and whether the provider explicitly says that the operation can be retried. + retryable = True if isinstance(exc, floo_errors.ResourceExhaustedError) else None + return {"context": {"provider_error": type(exc).__name__}, "retryable": retryable} + + +def default_user(user: User | str | None) -> None: + if user is not None: + raise ValueError("floo supports only the sandbox's default user") + + +class FlooSandboxSession(BaseSandboxSession): + def __init__(self, state: FlooSandboxState, sandbox: Sandbox, preserved: bool): + self.state = state + self._sandbox = sandbox + self._closed = False + self._set_start_state_preserved(preserved) + + async def _prepare_backend_workspace(self) -> None: + try: + await self._sandbox.filesystem.make_directory.aio(ROOT.as_posix()) + except (floo_errors.Error, OSError) as exc: + raise WorkspaceStartError(path=ROOT, **error_details(exc)) from None + + async def start(self) -> None: + try: + validate_manifest(self.state.manifest) + await super().start() + self._set_start_state_preserved(True) + except BaseException: + await self.shutdown() + raise + + async def _validate_manifest_application( + self, + *, + only_ephemeral: bool = False, + manifest: Manifest | None = None, + session_running: bool | None = None, + ) -> None: + await super()._validate_manifest_application( + only_ephemeral=only_ephemeral, + manifest=manifest, + session_running=session_running, + ) + validate_manifest(manifest or self.state.manifest) + + async def apply_manifest( + self, *, only_ephemeral: bool = False + ) -> MaterializationResult: + validate_manifest(self.state.manifest) + return await super().apply_manifest(only_ephemeral=only_ephemeral) + + async def _validate_path_access( + self, path: Path | str, *, for_write: bool = False + ) -> Path: + return await self._validate_remote_path_access(path, for_write=for_write) + + def _prepare_exec_command( + self, *command: str | Path, shell: bool | list[str], user: str | User | None + ) -> list[str]: + default_user(user) + return super()._prepare_exec_command(*command, shell=shell, user=user) + + async def _exec_internal( + self, *command: str | Path, timeout: float | None = None + ) -> ExecResult: + return await self._run([str(arg) for arg in command], timeout=timeout) + + async def _run( + self, argv: list[str], *, timeout: float | None = None, stdin: bytes = b"" + ) -> ExecResult: + if self._closed: + raise ExecTransportError(command=(), context={"reason": "session_closed"}) + try: + async with asyncio.timeout(timeout): + proc = await self._sandbox.exec.aio( + *argv, + text=False, + workdir=ROOT.as_posix(), + timeout=math.ceil(timeout) if timeout is not None else None, + ) + if stdin: + proc.stdin.write(stdin) + proc.stdin.write_eof() + await proc.stdin.drain.aio() + stdout, stderr, code = await asyncio.gather( + proc.stdout.read.aio(), + proc.stderr.read.aio(), + proc.wait.aio(), + ) + except (TimeoutError, floo_errors.TimeoutError): + raise ExecTimeoutError(command=(), timeout_s=timeout) from None + except (floo_errors.Error, OSError) as exc: + raise ExecTransportError(command=(), **error_details(exc)) from None + if code == -1: + raise ExecTimeoutError(command=(), timeout_s=timeout) + return ExecResult(stdout=stdout, stderr=stderr, exit_code=code) + + async def read(self, path: Path, *, user: User | str | None = None) -> io.BytesIO: + default_user(user) + path = await self._validate_path_access(path) + try: + return io.BytesIO( + await self._sandbox.filesystem.read_bytes.aio(path.as_posix()) + ) + except floo_errors.SandboxFilesystemNotFoundError: + raise WorkspaceReadNotFoundError(path=path) from None + except (floo_errors.Error, OSError) as exc: + raise WorkspaceArchiveReadError(path=path, **error_details(exc)) from None + + async def _read_bounded(self, path: Path, *, max_bytes: int) -> bytes: + path = await self._validate_path_access(path) + command = ["head", "-c", str(max_bytes), "--", path.as_posix()] + result = await self._run(command) + if not result.ok(): + await self._raise_read_error_from_exec( + path=path, workspace_path=path, command=command, result=result + ) + return result.stdout + + async def write( + self, path: Path, data: io.IOBase, *, user: User | str | None = None + ) -> None: + default_user(user) + path = await self._validate_path_access(path, for_write=True) + payload = data.read() + if isinstance(payload, str): + payload = payload.encode() + if not isinstance(payload, (bytes, bytearray)): + raise WorkspaceWriteTypeError(path=path, actual_type=type(payload).__name__) + try: + await self._sandbox.filesystem.write_bytes.aio(payload, path.as_posix()) + except (floo_errors.Error, OSError) as exc: + raise WorkspaceArchiveWriteError(path=path, **error_details(exc)) from None + + async def running(self) -> bool: + if self._closed: + return False + try: + return await self._sandbox.poll.aio() is None + except floo_errors.NotFoundError: + return False + except (floo_errors.Error, OSError) as exc: + raise ExecTransportError(command=("poll",), **error_details(exc)) from None + + async def persist_workspace(self) -> io.BytesIO: + argv = ["tar", "--no-wildcards"] + for path in sorted(self._persist_workspace_skip_relpaths()): + argv.append(f"--exclude=./{path.as_posix()}") + result = await self._run([*argv, "-cf", "-", "."]) + if not result.ok(): + raise WorkspaceArchiveReadError( + path=ROOT, context={"exit_code": result.exit_code} + ) + try: + self._validate_workspace_archive(result.stdout) + except ValueError: + raise WorkspaceArchiveReadError( + path=ROOT, context={"reason": "unsupported_archive_member"} + ) from None + return io.BytesIO(result.stdout) + + def _validate_workspace_archive(self, raw: bytes) -> None: + validate_tar_bytes( + raw, + reject_rel_paths=self._persist_workspace_skip_relpaths(), + allow_external_symlink_targets=False, + ) + + async def hydrate_workspace(self, data: io.IOBase) -> None: + raw = data.read() + try: + self._validate_workspace_archive(raw) + except (ValueError, TypeError): + raise WorkspaceArchiveWriteError( + path=ROOT, context={"reason": "invalid_archive"} + ) from None + # Only extract into an empty directory. Existing symlinks are not covered + # by archive validation. The SDK clears the workspace before restoration. + result = await self._run( + [ + "sh", + "-c", + 'first=$(find . -mindepth 1 -maxdepth 1 -print -quit) && test -z "$first" && exec tar -xf -', + ], + stdin=raw, + ) + if not result.ok(): + raise WorkspaceArchiveWriteError( + path=ROOT, + context={"reason": "restore_failed", "exit_code": result.exit_code}, + ) + + async def _persist_snapshot(self) -> None: + if not self._closed and self.state.workspace_root_ready: + await super()._persist_snapshot() + + async def stop(self) -> None: + try: + await super().stop() + except BaseException: + # The SDK wrapper can exit aclose early when persistence fails. + await self.shutdown() + raise + + async def _shutdown_backend(self) -> None: + if self._closed: + return + try: + await self._sandbox.terminate.aio() + except floo_errors.NotFoundError: + pass + except (floo_errors.Error, OSError) as exc: + raise WorkspaceStopError(path=ROOT, **error_details(exc)) from None + self._closed = True diff --git a/python/openai-agents-floo/src/openai_agents_floo/state.py b/python/openai-agents-floo/src/openai_agents_floo/state.py new file mode 100644 index 0000000..36a0b17 --- /dev/null +++ b/python/openai-agents-floo/src/openai_agents_floo/state.py @@ -0,0 +1,34 @@ +from typing import Literal + +from agents.sandbox.entries import Dir, File +from agents.sandbox.manifest import Manifest +from agents.sandbox.session import BaseSandboxClientOptions, SandboxSessionState +from pydantic import ConfigDict, Field + + +class FlooSandboxOptions(BaseSandboxClientOptions): + model_config = ConfigDict(extra="forbid") + type: Literal["floo"] = "floo" + lifetime_seconds: int = Field(default=300, ge=1, le=86_400, strict=True) + + +class FlooSandboxState(SandboxSessionState): + model_config = ConfigDict(extra="forbid") + type: Literal["floo"] = "floo" + app_name: str = Field(min_length=1) + sandbox_id: str | None = None + options: FlooSandboxOptions = Field(default_factory=FlooSandboxOptions) + + +def validate_manifest(manifest: Manifest) -> None: + if manifest.root != "/workspace" or manifest.extra_path_grants: + raise ValueError("floo supports /workspace without extra path grants") + if manifest.users or manifest.groups or manifest.environment.value: + raise ValueError( + "floo does not support manifest users, groups, or environment variables" + ) + for _, entry in manifest.iter_entries(): + if type(entry) not in (Dir, File) or entry.group is not None: + raise ValueError( + "floo supports inline File and Dir entries without group overrides" + ) diff --git a/python/openai-agents-floo/tests/live_runner.py b/python/openai-agents-floo/tests/live_runner.py new file mode 100644 index 0000000..1d8753c --- /dev/null +++ b/python/openai-agents-floo/tests/live_runner.py @@ -0,0 +1,136 @@ +"""Exercise runner-managed and application-managed floo sessions without a model key.""" + +import asyncio +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory + +from agents import RunConfig, Runner, RunState, function_tool +from agents.sandbox import Manifest, SandboxAgent, SandboxRunConfig +from agents.sandbox.entries import File +from agents.sandbox.snapshot import LocalSnapshotSpec +from agents.testing import ScriptedModel, assistant_message, function_call +from live_session import assert_terminated + +from openai_agents_floo import FlooSandboxClient + + +@function_tool(needs_approval=True) +def checkpoint() -> str: + """Resume the test after a persisted approval.""" + return "approved" + + +def shell(command, call_id): + return function_call("exec_command", {"cmd": command}, call_id=call_id) + + +class ObservedClient(FlooSandboxClient): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.deleted = [] + + async def delete(self, session): + result = await super().delete(session) + self.deleted.append(session.state.sandbox_id) + return result + + +async def main(): + app = os.environ["FLOO_AGENTS_TEST_APP"] + with TemporaryDirectory() as tmp: + client = ObservedClient(app, snapshot_dir=Path(tmp)) + model = ScriptedModel( + [ + [shell("tr a-z A-Z < seed > reply", "make-reply")], + [function_call("checkpoint", {}, call_id="pause")], + [shell("cat reply", "read-reply")], + [assistant_message("done")], + ] + ) + agent = SandboxAgent(name="floo test", model=model, tools=[checkpoint]) + config = RunConfig( + tracing_disabled=True, + sandbox=SandboxRunConfig( + client=client, + manifest=Manifest(entries={"seed": File(content=b"runner proof\n")}), + snapshot=LocalSnapshotSpec(base_path=Path(tmp)), + ), + ) + paused = await Runner.run(agent, "Run the test", run_config=config) + assert len(paused.interruptions) == 1 + assert len(client.deleted) == 1 + await assert_terminated(client.deleted[0]) + saved = json.loads(json.dumps(paused.to_state().to_json())) + state = await RunState.from_json(agent, saved) + state.approve(state.get_interruptions()[0]) + finished = await Runner.run(agent, state, run_config=config) + assert finished.final_output == "done" + outputs = [ + item.output + for item in finished.new_items + if item.type == "tool_call_output_item" + ] + assert any("RUNNER PROOF" in str(value) for value in outputs), outputs + assert len(client.deleted) == 2 and client.deleted[0] != client.deleted[1] + await assert_terminated(client.deleted[1]) + print("Runner approval round trip restored reply = RUNNER PROOF", flush=True) + + live = await client.create() + try: + await live.start() + agent = SandboxAgent( + name="live", + model=ScriptedModel( + [ + [shell("printf live > owned", "write-owned")], + [assistant_message("done")], + ] + ), + ) + await Runner.run( + agent, + "Write", + run_config=RunConfig( + tracing_disabled=True, + sandbox=SandboxRunConfig(session=live), + ), + ) + assert await live.running() + assert (await live.read(Path("owned"))).read() == b"live" + print("Runner left application-owned session running", flush=True) + finally: + try: + await live.aclose() + finally: + await client.delete(live) + await assert_terminated(live.state.sandbox_id) + + entered = asyncio.Event() + + async def hold_model(_call): + entered.set() + await asyncio.Event().wait() + + from agents.testing import ModelStep + + interrupted = SandboxAgent( + name="cancel", model=ScriptedModel([ModelStep.respond(hold_model)]) + ) + task = asyncio.create_task(Runner.run(interrupted, "Wait", run_config=config)) + try: + await asyncio.wait_for(entered.wait(), timeout=90) + finally: + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + assert len(client.deleted) == 4 + await assert_terminated(client.deleted[-1]) + print("Runner cancelled after startup and terminated its sandbox", flush=True) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/python/openai-agents-floo/tests/live_session.py b/python/openai-agents-floo/tests/live_session.py new file mode 100644 index 0000000..b408a89 --- /dev/null +++ b/python/openai-agents-floo/tests/live_session.py @@ -0,0 +1,151 @@ +"""Run from an installed wheel with FLOO_API_KEY and FLOO_AGENTS_TEST_APP set.""" + +import asyncio +import io +import json +import os +from pathlib import Path +from tempfile import TemporaryDirectory + +from agents.sandbox import Manifest +from agents.sandbox.entries import File +from agents.sandbox.errors import ( + ExecTimeoutError, + InvalidManifestPathError, + WorkspaceReadNotFoundError, +) +from agents.sandbox.snapshot import LocalSnapshotSpec +from floo_sandbox import Sandbox +from floo_sandbox.exception import NotFoundError + +from openai_agents_floo import FlooSandboxClient + + +async def assert_terminated(sandbox_id): + try: + handle = await Sandbox.from_id.aio(sandbox_id) + code = await handle.poll.aio() + assert code is not None, sandbox_id + except NotFoundError: + code = "not_found" + print(f"cleanup {sandbox_id} = {code}", flush=True) + + +async def main(): + app = os.environ["FLOO_AGENTS_TEST_APP"] + with TemporaryDirectory() as tmp: + client = FlooSandboxClient(app, snapshot_dir=Path(tmp)) + first = await client.create( + snapshot=LocalSnapshotSpec(base_path=Path(tmp)), + manifest=Manifest( + entries={"scratch": File(content=b"initial", ephemeral=True)} + ), + ) + first_id = first.state.sandbox_id + print(f"created {first_id}", flush=True) + try: + await first.start() + await first.write(Path("input.txt"), io.BytesIO(b"floo sandbox\n")) + r = await first.exec( + "tr a-z A-Z < input.txt > result.txt && cat result.txt && printf diagnostic >&2" + ) + assert (r.stdout, r.stderr, r.exit_code) == ( + b"FLOO SANDBOX\n", + b"diagnostic", + 0, + ), (r.stdout, r.stderr, r.exit_code) + print("exec stdout=FLOO SANDBOX stderr=diagnostic exit=0", flush=True) + assert (await first.exec("exit 17")).exit_code == 17 + try: + await first.exec("sleep 5", timeout=0.5) + except ExecTimeoutError: + pass + else: + raise AssertionError("command did not time out") + assert await first.read_bounded(Path("result.txt"), max_bytes=4) == b"FLOO" + try: + await first.read_bounded(Path("missing"), max_bytes=4) + except WorkspaceReadNotFoundError: + pass + else: + raise AssertionError("missing file was accepted") + try: + await first.read(Path("/etc/os-release")) + except InvalidManifestPathError: + pass + else: + raise AssertionError("SDK read accepted a path outside /workspace") + print( + "nonzero exit=17, timeout, bounded read, missing file and workspace scope verified", + flush=True, + ) + network = await first.exec( + "python", + "-c", + """import socket +try: + socket.create_connection(('1.1.1.1', 443), timeout=2).close() +except OSError: + print('blocked') +""", + shell=False, + ) + assert network.ok() and network.stdout == b"blocked\n", network.stderr + separate = await client.create() + try: + await separate.start() + assert (await separate.exec("test ! -e result.txt")).ok() + assert (await first.exec("test -f result.txt")).ok() + finally: + await client.delete(separate) + await assert_terminated(separate.state.sandbox_id) + print( + "separate workspace and blocked guest TCP connection verified", + flush=True, + ) + saved = json.dumps(client.serialize_session_state(first.state)) + worker = FlooSandboxClient(app, snapshot_dir=Path(tmp)) + resumed = await worker.resume( + worker.deserialize_session_state(json.loads(saved)) + ) + try: + await resumed.start() + assert resumed.state.sandbox_id == first_id + assert (await resumed.read(Path("result.txt"))).read() == r.stdout + print( + f"reattached {first_id}, read result.txt = FLOO SANDBOX", flush=True + ) + await resumed.write(Path("scratch"), io.BytesIO(b"temporary change")) + assert (await resumed.exec("chmod 750 result.txt")).ok() + await resumed.aclose() + saved = json.dumps(worker.serialize_session_state(resumed.state)) + finally: + await worker.delete(resumed) + finally: + await client.delete(first) + await assert_terminated(first_id) + restored = await worker.resume( + worker.deserialize_session_state(json.loads(saved)) + ) + try: + await restored.start() + assert restored.state.sandbox_id != first_id + assert (await restored.read(Path("scratch"))).read() == b"initial" + assert ( + await restored.exec("stat -c %a result.txt") + ).stdout.strip() == b"750" + assert (await restored.read(Path("result.txt"))).read() == b"FLOO SANDBOX\n" + print( + f"snapshot restored {restored.state.sandbox_id}, read result.txt = FLOO SANDBOX", + flush=True, + ) + finally: + try: + await restored.aclose() + finally: + await worker.delete(restored) + await assert_terminated(restored.state.sandbox_id) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/python/openai-agents-floo/tests/test_provider.py b/python/openai-agents-floo/tests/test_provider.py new file mode 100644 index 0000000..91ffb26 --- /dev/null +++ b/python/openai-agents-floo/tests/test_provider.py @@ -0,0 +1,162 @@ +import asyncio +import json +import os +import subprocess +import sys +import unittest +from pathlib import Path +from tempfile import TemporaryDirectory +from unittest.mock import AsyncMock, Mock, patch + +from agents.sandbox import Manifest, SandboxRunConfig +from agents.sandbox.entries import Dir, LocalFile +from agents.sandbox.errors import WorkspaceStartError +from agents.sandbox.session import BaseSandboxClientOptions +from agents.sandbox.snapshot import LocalSnapshotSpec +from floo_sandbox import exception as floo_errors +from pydantic import ValidationError + +from openai_agents_floo import FlooSandboxClient, FlooSandboxOptions + + +class ProviderTests(unittest.IsolatedAsyncioTestCase): + def setUp(self): + self.tmp = TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.enterContext( + patch("openai_agents_floo.provider.given", return_value=object()) + ) + self.client = FlooSandboxClient("tests", snapshot_dir=self.root) + lookup = self.enterContext(patch("openai_agents_floo.provider.App.lookup")) + lookup.aio = AsyncMock() + self.lookup = lookup.aio + self.handle = Mock(object_id="sb-test") + self.handle.terminate.aio = AsyncMock() + create = self.enterContext(patch("openai_agents_floo.provider.Sandbox.create")) + create.aio = AsyncMock(return_value=self.handle) + self.create = create.aio + + def test_options(self): + config = SandboxRunConfig(client=self.client, options={"lifetime_seconds": 45}) + self.assertEqual(config.options, FlooSandboxOptions(lifetime_seconds=45)) + for payload in ( + {"exposed_ports": [80]}, + {"lifetime_seconds": 0}, + {"lifetime_seconds": True}, + ): + with self.subTest(payload=payload), self.assertRaises(ValidationError): + BaseSandboxClientOptions.parse({"type": "floo", **payload}) + + async def test_state_in_new_interpreter(self): + session = await self.client.create( + snapshot=LocalSnapshotSpec(base_path=self.root) + ) + payload = self.client.serialize_session_state(session.state) + script = """ +import json,sys +from pathlib import Path +from openai_agents_floo import FlooSandboxClient, FlooSandboxOptions, FlooSandboxState +from agents.sandbox.session import BaseSandboxClientOptions, SandboxSessionState +p=json.load(sys.stdin) +client=FlooSandboxClient("tests",snapshot_dir=Path(p["snapshot"]["base_path"])) +assert isinstance(BaseSandboxClientOptions.parse(p["options"]), FlooSandboxOptions) +assert isinstance(SandboxSessionState.parse(p), FlooSandboxState) +assert client.serialize_session_state(client.deserialize_session_state(p)) == p +""" + subprocess.run( + [sys.executable, "-I", "-c", script], + input=json.dumps(payload), + text=True, + env={**os.environ, "FLOO_API_KEY": "offline-test-key"}, + check=True, + cwd=self.tmp.name, + ) + await self.client.delete(session) + + async def test_malformed_state(self): + session = await self.client.create( + snapshot=LocalSnapshotSpec(base_path=self.root) + ) + p = self.client.serialize_session_state(session.state) + for delta in ( + {"type": "docker"}, + {"type": None}, + {"app_name": "other"}, + {"exposed_ports": [80]}, + {"snapshot": {**p["snapshot"], "base_path": "/"}}, + {"snapshot": {**p["snapshot"], "id": "other"}}, + {"options": {"type": "floo", "image": "other"}}, + ): + with self.subTest(delta=delta), self.assertRaises((ValueError, TypeError)): + self.client.deserialize_session_state({**p, **delta}) + + async def test_unsupported_inputs_before_allocation(self): + for manifest in ( + Manifest(root="/"), + Manifest(users=[{"name": "reader"}]), + Manifest(environment={"value": {"TEST": "value"}}), + Manifest( + entries={"d": Dir(children={"local": LocalFile(src=Path("host-file"))})} + ), + ): + with self.assertRaises(ValueError): + await self.client.create(manifest=manifest) + with self.assertRaises(TypeError): + await self.client.create(options={"image": "unsupported"}) + self.lookup.assert_not_awaited() + self.create.assert_not_awaited() + + async def test_start_failure_and_repeated_cleanup(self): + self.handle.filesystem.make_directory.aio = AsyncMock( + side_effect=floo_errors.AuthError("sensitive-response") + ) + session = await self.client.create() + with self.assertRaises(WorkspaceStartError) as result: + await session.start() + self.assertNotIn("sensitive-response", str(result.exception)) + self.assertEqual(result.exception.context["provider_error"], "AuthError") + await session.aclose() + await self.client.delete(session) + self.handle.terminate.aio.assert_awaited_once() + + async def test_cancel_allocation(self): + entered, release = asyncio.Event(), asyncio.Event() + + async def allocate(**kwargs): + entered.set() + await release.wait() + return self.handle + + self.create.side_effect = allocate + task = asyncio.create_task(self.client.create()) + await entered.wait() + task.cancel() + release.set() + with self.assertRaises(asyncio.CancelledError): + await task + self.handle.terminate.aio.assert_awaited_once() + + async def test_resume_does_not_replace_on_transport_failure(self): + state = (await self.client.create()).state + with patch("openai_agents_floo.provider.Sandbox.from_name") as lookup: + lookup.aio = AsyncMock( + side_effect=floo_errors.ConnectionError("sensitive-response") + ) + with self.assertRaises(WorkspaceStartError): + await self.client.resume(state) + self.create.assert_awaited_once() + + async def test_missing_without_snapshot(self): + state = (await self.client.create()).state + with patch("openai_agents_floo.provider.Sandbox.from_name") as lookup: + lookup.aio = AsyncMock(side_effect=floo_errors.NotFoundError()) + with self.assertRaisesRegex( + WorkspaceStartError, "without a restorable snapshot" + ): + await self.client.resume(state) + self.create.assert_awaited_once() + + +if __name__ == "__main__": + unittest.main() From 348568e835c5ab896661d98ddd7b12db11da7501 Mon Sep 17 00:00:00 2001 From: Patrick Donohoe Date: Thu, 3 Dec 2026 02:19:38 -0500 Subject: [PATCH 2/2] Publish the independently versioned provider through PyPI trusted publishing --- .../workflows/publish-openai-agents-floo.yml | 52 +++++++++++++++++++ python/openai-agents-floo/README.md | 6 ++- python/openai-agents-floo/pyproject.toml | 5 ++ 3 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/publish-openai-agents-floo.yml diff --git a/.github/workflows/publish-openai-agents-floo.yml b/.github/workflows/publish-openai-agents-floo.yml new file mode 100644 index 0000000..51280ce --- /dev/null +++ b/.github/workflows/publish-openai-agents-floo.yml @@ -0,0 +1,52 @@ +name: Publish openai-agents-floo + +on: + push: + tags: ["openai-agents-floo-v*"] + +permissions: + contents: read + +jobs: + build: + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 + with: + persist-credentials: false + fetch-depth: 0 + - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 + - name: Verify release tag and build the wheel + working-directory: python/openai-agents-floo + run: | + git merge-base --is-ancestor "$GITHUB_SHA" origin/main + test "$GITHUB_REF_NAME" = "openai-agents-floo-v$(uv version --short)" + uv build --wheel --out-dir "$RUNNER_TEMP/dist" + uvx twine==6.2.0 check --strict "$RUNNER_TEMP"/dist/*.whl + - name: Test the installed wheel + working-directory: python/openai-agents-floo + run: | + uv venv --python 3.11 "$RUNNER_TEMP/smoke" + uv pip install --python "$RUNNER_TEMP/smoke/bin/python" "$RUNNER_TEMP"/dist/*.whl + "$RUNNER_TEMP/smoke/bin/python" -I -m unittest discover -s tests -v + - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 + with: + name: provider-wheel + path: ${{ runner.temp }}/dist/*.whl + if-no-files-found: error + + publish: + needs: build + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 + with: + name: provider-wheel + path: dist + - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 + - run: uv publish --trusted-publishing always dist/*.whl diff --git a/python/openai-agents-floo/README.md b/python/openai-agents-floo/README.md index 515a121..24fb8af 100644 --- a/python/openai-agents-floo/README.md +++ b/python/openai-agents-floo/README.md @@ -2,12 +2,14 @@ Run the OpenAI Agents SDK shell and filesystem tools in a floo sandbox. This package targets `openai-agents==0.26.0` and `floo-sandbox==0.2.0`. -Install from the root of this checkout with Python 3.11 or newer. +Install with Python 3.11 or newer. ```sh -python -m pip install ./python/openai-agents-floo +python -m pip install openai-agents-floo==0.1.0 ``` +[floo quickstart](https://getfloo.com/docs/guides/openai-agents-sdk) + Set `FLOO_API_KEY` in the application environment and `FLOO_APP_NAME` to an existing app. Set `FLOO_ORG_ID` to select an org when using a personal key. The floo SDK manages its shared transport. The provider captures that transport when you construct the client. ```python diff --git a/python/openai-agents-floo/pyproject.toml b/python/openai-agents-floo/pyproject.toml index 36091b6..9901822 100644 --- a/python/openai-agents-floo/pyproject.toml +++ b/python/openai-agents-floo/pyproject.toml @@ -13,5 +13,10 @@ license-files = ["LICENSE"] authors = [{ name = "floo" }] dependencies = ["openai-agents==0.26.0", "floo-sandbox==0.2.0"] +[project.urls] +Documentation = "https://getfloo.com/docs/guides/openai-agents-sdk" +Repository = "https://github.com/getfloo/floo-cli/tree/main/python/openai-agents-floo" +Issues = "https://github.com/getfloo/floo-cli/issues" + [tool.hatch.build.targets.wheel] packages = ["src/openai_agents_floo"]