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
52 changes: 52 additions & 0 deletions .github/workflows/publish-openai-agents-floo.yml
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions python/openai-agents-floo/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
__pycache__/
dist/
.ruff_cache/
21 changes: 21 additions & 0 deletions python/openai-agents-floo/LICENSE
Original file line number Diff line number Diff line change
@@ -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.
63 changes: 63 additions & 0 deletions python/openai-agents-floo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# 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 with Python 3.11 or newer.

```sh
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
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/)
22 changes: 22 additions & 0 deletions python/openai-agents-floo/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[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"]

[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"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from .provider import FlooSandboxClient, FlooSandboxOptions, FlooSandboxState

__all__ = ["FlooSandboxClient", "FlooSandboxOptions", "FlooSandboxState"]
166 changes: 166 additions & 0 deletions python/openai-agents-floo/src/openai_agents_floo/provider.py
Original file line number Diff line number Diff line change
@@ -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
Empty file.
Loading