openai-agents-pilldrops 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openai_agents_pilldrops-0.1.0/.gitignore +6 -0
- openai_agents_pilldrops-0.1.0/PKG-INFO +85 -0
- openai_agents_pilldrops-0.1.0/README.md +73 -0
- openai_agents_pilldrops-0.1.0/openai_agents_pilldrops/__init__.py +15 -0
- openai_agents_pilldrops-0.1.0/openai_agents_pilldrops/sandbox.py +294 -0
- openai_agents_pilldrops-0.1.0/pyproject.toml +19 -0
- openai_agents_pilldrops-0.1.0/tests/live_check.py +50 -0
- openai_agents_pilldrops-0.1.0/tests/test_types.py +26 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: openai-agents-pilldrops
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: PillDrops sandboxes for the OpenAI Agents SDK
|
|
5
|
+
Project-URL: Homepage, https://pilldrops.com
|
|
6
|
+
Project-URL: Repository, https://github.com/pilldrops-oss/pilldrops-integrations
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Requires-Dist: openai-agents<0.27.0,>=0.26.0
|
|
10
|
+
Requires-Dist: pilldrops>=1.6.0
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# openai-agents-pilldrops
|
|
14
|
+
|
|
15
|
+
[PillDrops](https://pilldrops.com) sandboxes for the
|
|
16
|
+
[OpenAI Agents SDK](https://openai.github.io/openai-agents-python/sandbox/). A `SandboxAgent`'s
|
|
17
|
+
shell and file tools run in a PillDrops cloud sandbox.
|
|
18
|
+
|
|
19
|
+
## Install
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install openai-agents-pilldrops
|
|
23
|
+
export PILLDROPS_API_KEY=sf_live_... # from https://pilldrops.com/dashboard
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
## Use
|
|
27
|
+
|
|
28
|
+
```python
|
|
29
|
+
import asyncio
|
|
30
|
+
|
|
31
|
+
from agents import RunConfig, Runner
|
|
32
|
+
from agents.sandbox import SandboxAgent, SandboxRunConfig
|
|
33
|
+
|
|
34
|
+
from openai_agents_pilldrops import PillDropsSandboxClient, PillDropsSandboxClientOptions
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
async def main():
|
|
38
|
+
agent = SandboxAgent(name="Analyst", instructions="Use the sandbox tools.")
|
|
39
|
+
result = await Runner.run(
|
|
40
|
+
agent,
|
|
41
|
+
"Create primes.py that prints the primes below 50, run it, and tell me how many there are.",
|
|
42
|
+
run_config=RunConfig(sandbox=SandboxRunConfig(
|
|
43
|
+
client=PillDropsSandboxClient(),
|
|
44
|
+
options=PillDropsSandboxClientOptions(template="code-interpreter"),
|
|
45
|
+
)),
|
|
46
|
+
)
|
|
47
|
+
print(result.final_output)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
asyncio.run(main())
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
The runner creates the sandbox, puts the agent's workspace in `/workspace`, and deletes the
|
|
54
|
+
sandbox when the run ends.
|
|
55
|
+
|
|
56
|
+
With a model other than OpenAI's (for example Claude through `LitellmModel`), pass
|
|
57
|
+
`capabilities=[Shell()]` from `agents.sandbox.capabilities`. The default set includes
|
|
58
|
+
`apply_patch`, which only OpenAI's Responses API supports.
|
|
59
|
+
|
|
60
|
+
## Options
|
|
61
|
+
|
|
62
|
+
| Option | Default | Meaning |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `template` | `code-interpreter` | Any [PillDrops template](https://pilldrops.com/templates), e.g. `node` or `browser` |
|
|
65
|
+
| `timeout` | server default | Sandbox lifetime in seconds |
|
|
66
|
+
| `envs` | none | Environment variables for every command |
|
|
67
|
+
| `pause_on_exit` | `False` | Pause instead of delete at the end, so a saved run state can resume in the same sandbox |
|
|
68
|
+
|
|
69
|
+
## Supported
|
|
70
|
+
|
|
71
|
+
- Commands, file reads and writes, workspace snapshots (tar) and restore, and resume: it
|
|
72
|
+
reconnects to the same sandbox when it still exists, or starts a new one.
|
|
73
|
+
- Not supported, and rejected with an error: PTY sessions, commands as another user, manifest
|
|
74
|
+
mounts and exposed ports.
|
|
75
|
+
|
|
76
|
+
## Tests
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
pip install -e . pytest && pytest tests # options and state serialization
|
|
80
|
+
python tests/live_check.py # a real sandbox; needs PILLDROPS_API_KEY
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
MIT
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
# openai-agents-pilldrops
|
|
2
|
+
|
|
3
|
+
[PillDrops](https://pilldrops.com) sandboxes for the
|
|
4
|
+
[OpenAI Agents SDK](https://openai.github.io/openai-agents-python/sandbox/). A `SandboxAgent`'s
|
|
5
|
+
shell and file tools run in a PillDrops cloud sandbox.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install openai-agents-pilldrops
|
|
11
|
+
export PILLDROPS_API_KEY=sf_live_... # from https://pilldrops.com/dashboard
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
## Use
|
|
15
|
+
|
|
16
|
+
```python
|
|
17
|
+
import asyncio
|
|
18
|
+
|
|
19
|
+
from agents import RunConfig, Runner
|
|
20
|
+
from agents.sandbox import SandboxAgent, SandboxRunConfig
|
|
21
|
+
|
|
22
|
+
from openai_agents_pilldrops import PillDropsSandboxClient, PillDropsSandboxClientOptions
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def main():
|
|
26
|
+
agent = SandboxAgent(name="Analyst", instructions="Use the sandbox tools.")
|
|
27
|
+
result = await Runner.run(
|
|
28
|
+
agent,
|
|
29
|
+
"Create primes.py that prints the primes below 50, run it, and tell me how many there are.",
|
|
30
|
+
run_config=RunConfig(sandbox=SandboxRunConfig(
|
|
31
|
+
client=PillDropsSandboxClient(),
|
|
32
|
+
options=PillDropsSandboxClientOptions(template="code-interpreter"),
|
|
33
|
+
)),
|
|
34
|
+
)
|
|
35
|
+
print(result.final_output)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
asyncio.run(main())
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The runner creates the sandbox, puts the agent's workspace in `/workspace`, and deletes the
|
|
42
|
+
sandbox when the run ends.
|
|
43
|
+
|
|
44
|
+
With a model other than OpenAI's (for example Claude through `LitellmModel`), pass
|
|
45
|
+
`capabilities=[Shell()]` from `agents.sandbox.capabilities`. The default set includes
|
|
46
|
+
`apply_patch`, which only OpenAI's Responses API supports.
|
|
47
|
+
|
|
48
|
+
## Options
|
|
49
|
+
|
|
50
|
+
| Option | Default | Meaning |
|
|
51
|
+
|---|---|---|
|
|
52
|
+
| `template` | `code-interpreter` | Any [PillDrops template](https://pilldrops.com/templates), e.g. `node` or `browser` |
|
|
53
|
+
| `timeout` | server default | Sandbox lifetime in seconds |
|
|
54
|
+
| `envs` | none | Environment variables for every command |
|
|
55
|
+
| `pause_on_exit` | `False` | Pause instead of delete at the end, so a saved run state can resume in the same sandbox |
|
|
56
|
+
|
|
57
|
+
## Supported
|
|
58
|
+
|
|
59
|
+
- Commands, file reads and writes, workspace snapshots (tar) and restore, and resume: it
|
|
60
|
+
reconnects to the same sandbox when it still exists, or starts a new one.
|
|
61
|
+
- Not supported, and rejected with an error: PTY sessions, commands as another user, manifest
|
|
62
|
+
mounts and exposed ports.
|
|
63
|
+
|
|
64
|
+
## Tests
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
pip install -e . pytest && pytest tests # options and state serialization
|
|
68
|
+
python tests/live_check.py # a real sandbox; needs PILLDROPS_API_KEY
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## License
|
|
72
|
+
|
|
73
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""PillDrops sandboxes for the OpenAI Agents SDK."""
|
|
2
|
+
|
|
3
|
+
from openai_agents_pilldrops.sandbox import (
|
|
4
|
+
PillDropsSandboxClient,
|
|
5
|
+
PillDropsSandboxClientOptions,
|
|
6
|
+
PillDropsSandboxSession,
|
|
7
|
+
PillDropsSandboxSessionState,
|
|
8
|
+
)
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"PillDropsSandboxClient",
|
|
12
|
+
"PillDropsSandboxClientOptions",
|
|
13
|
+
"PillDropsSandboxSession",
|
|
14
|
+
"PillDropsSandboxSessionState",
|
|
15
|
+
]
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""PillDrops sandbox client and session for the OpenAI Agents SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import base64
|
|
7
|
+
import binascii
|
|
8
|
+
import io
|
|
9
|
+
import logging
|
|
10
|
+
import shlex
|
|
11
|
+
import uuid
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Literal
|
|
14
|
+
|
|
15
|
+
from agents.sandbox.errors import (
|
|
16
|
+
ExecTransportError,
|
|
17
|
+
WorkspaceArchiveReadError,
|
|
18
|
+
WorkspaceArchiveWriteError,
|
|
19
|
+
WorkspaceReadNotFoundError,
|
|
20
|
+
WorkspaceStartError,
|
|
21
|
+
WorkspaceWriteTypeError,
|
|
22
|
+
)
|
|
23
|
+
from agents.sandbox.manifest import Manifest
|
|
24
|
+
from agents.sandbox.session import SandboxSession, SandboxSessionState
|
|
25
|
+
from agents.sandbox.session.base_sandbox_session import BaseSandboxSession
|
|
26
|
+
from agents.sandbox.session.manager import Instrumentation
|
|
27
|
+
from agents.sandbox.session.runtime_helpers import RESOLVE_WORKSPACE_PATH_HELPER, RuntimeHelperScript
|
|
28
|
+
from agents.sandbox.session.sandbox_client import BaseSandboxClient, BaseSandboxClientOptions
|
|
29
|
+
from agents.sandbox.session.tar_workspace import shell_tar_exclude_args
|
|
30
|
+
from agents.sandbox.snapshot import SnapshotBase, SnapshotSpec, resolve_snapshot
|
|
31
|
+
from agents.sandbox.types import ExecResult, User
|
|
32
|
+
from agents.sandbox.util.tar_utils import UnsafeTarMemberError, validate_tar_bytes
|
|
33
|
+
from agents.sandbox.workspace_paths import posix_path_for_error, sandbox_path_str
|
|
34
|
+
from pilldrops import APIError, Sandbox
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
# Commands with no timeout still need one on the wire; a day is effectively unbounded.
|
|
39
|
+
_UNBOUNDED_EXEC_S = 24 * 60 * 60
|
|
40
|
+
_NOT_FOUND = 3
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class PillDropsSandboxClientOptions(BaseSandboxClientOptions):
|
|
44
|
+
"""Options for a new PillDrops sandbox."""
|
|
45
|
+
|
|
46
|
+
type: Literal["pilldrops"] = "pilldrops"
|
|
47
|
+
template: str = "code-interpreter"
|
|
48
|
+
timeout: int | None = None
|
|
49
|
+
"""Sandbox lifetime in seconds; the server default when unset."""
|
|
50
|
+
envs: dict[str, str] | None = None
|
|
51
|
+
pause_on_exit: bool = False
|
|
52
|
+
"""Pause instead of delete when the run ends, so `resume` can reconnect to it."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class PillDropsSandboxSessionState(SandboxSessionState):
|
|
56
|
+
type: Literal["pilldrops"] = "pilldrops"
|
|
57
|
+
sandbox_id: str
|
|
58
|
+
template: str = "code-interpreter"
|
|
59
|
+
sandbox_timeout: int | None = None
|
|
60
|
+
base_envs: dict[str, str] = {}
|
|
61
|
+
pause_on_exit: bool = False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class PillDropsSandboxSession(BaseSandboxSession):
|
|
65
|
+
"""A session backed by one PillDrops sandbox. PTY sessions and per-user commands are not supported."""
|
|
66
|
+
|
|
67
|
+
state: PillDropsSandboxSessionState
|
|
68
|
+
|
|
69
|
+
def __init__(self, *, state: PillDropsSandboxSessionState, sandbox: Sandbox) -> None:
|
|
70
|
+
self.state = state
|
|
71
|
+
self._sandbox = sandbox
|
|
72
|
+
|
|
73
|
+
@property
|
|
74
|
+
def sandbox_id(self) -> str:
|
|
75
|
+
return self.state.sandbox_id
|
|
76
|
+
|
|
77
|
+
async def _validate_path_access(self, path: Path | str, *, for_write: bool = False) -> Path:
|
|
78
|
+
return await self._validate_remote_path_access(path, for_write=for_write)
|
|
79
|
+
|
|
80
|
+
def _runtime_helpers(self) -> tuple[RuntimeHelperScript, ...]:
|
|
81
|
+
return (RESOLVE_WORKSPACE_PATH_HELPER,)
|
|
82
|
+
|
|
83
|
+
def _current_runtime_helper_cache_key(self) -> object | None:
|
|
84
|
+
return self.state.sandbox_id
|
|
85
|
+
|
|
86
|
+
async def _resolved_envs(self) -> dict[str, str]:
|
|
87
|
+
return {**self.state.base_envs, **await self.state.manifest.environment.resolve()}
|
|
88
|
+
|
|
89
|
+
async def _run(self, command: str, *, timeout: float | None, cwd: str = "") -> ExecResult:
|
|
90
|
+
seconds = _UNBOUNDED_EXEC_S if timeout is None else max(1, int(timeout))
|
|
91
|
+
env = await self._resolved_envs()
|
|
92
|
+
result = await asyncio.to_thread(self._sandbox.run, command, cwd, seconds, env or None)
|
|
93
|
+
return ExecResult(
|
|
94
|
+
stdout=result.stdout.encode("utf-8", errors="replace"),
|
|
95
|
+
stderr=result.stderr.encode("utf-8", errors="replace"),
|
|
96
|
+
exit_code=result.exit_code,
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
async def _prepare_backend_workspace(self) -> None:
|
|
100
|
+
root = sandbox_path_str(self._workspace_root_path())
|
|
101
|
+
try:
|
|
102
|
+
result = await self._run(f"mkdir -p -- {shlex.quote(root)}", timeout=30)
|
|
103
|
+
except Exception as e:
|
|
104
|
+
raise WorkspaceStartError(path=self._workspace_root_path(), cause=e) from e
|
|
105
|
+
if not result.ok():
|
|
106
|
+
raise WorkspaceStartError(
|
|
107
|
+
path=self._workspace_root_path(),
|
|
108
|
+
context={"reason": "workspace_root_nonzero_exit", "stderr": result.stderr.decode()},
|
|
109
|
+
)
|
|
110
|
+
self.state.workspace_root_ready = True
|
|
111
|
+
|
|
112
|
+
async def _exec_internal(self, *command: str | Path, timeout: float | None = None) -> ExecResult:
|
|
113
|
+
parts = [str(c) for c in command]
|
|
114
|
+
if len(parts) >= 4 and parts[0] == "sudo" and parts[1] == "-u" and parts[3] == "--":
|
|
115
|
+
raise ExecTransportError(command=command, context={"reason": "pilldrops runs commands as root; users are not supported"})
|
|
116
|
+
cwd = sandbox_path_str(self._workspace_root_path()) if self.state.workspace_root_ready else ""
|
|
117
|
+
try:
|
|
118
|
+
return await self._run(shlex.join(parts), timeout=timeout, cwd=cwd)
|
|
119
|
+
except Exception as e:
|
|
120
|
+
raise ExecTransportError(command=command, cause=e) from e
|
|
121
|
+
|
|
122
|
+
async def read(self, path: Path, *, user: str | User | None = None) -> io.IOBase:
|
|
123
|
+
if user is not None:
|
|
124
|
+
raise WorkspaceArchiveReadError(path=path, context={"reason": "users are not supported"})
|
|
125
|
+
target = shlex.quote(sandbox_path_str(await self._validate_path_access(path)))
|
|
126
|
+
try:
|
|
127
|
+
result = await self._run(f"test -f {target} || exit {_NOT_FOUND}; base64 < {target}", timeout=120)
|
|
128
|
+
except Exception as e:
|
|
129
|
+
raise WorkspaceArchiveReadError(path=path, cause=e) from e
|
|
130
|
+
if result.exit_code == _NOT_FOUND:
|
|
131
|
+
raise WorkspaceReadNotFoundError(path=path)
|
|
132
|
+
if not result.ok():
|
|
133
|
+
raise WorkspaceArchiveReadError(path=path, context={"stderr": result.stderr.decode()})
|
|
134
|
+
return io.BytesIO(base64.b64decode(result.stdout))
|
|
135
|
+
|
|
136
|
+
async def write(self, path: Path, data: io.IOBase, *, user: str | User | None = None) -> None:
|
|
137
|
+
if user is not None:
|
|
138
|
+
raise WorkspaceArchiveWriteError(path=path, context={"reason": "users are not supported"})
|
|
139
|
+
payload = data.read()
|
|
140
|
+
if isinstance(payload, str):
|
|
141
|
+
payload = payload.encode("utf-8")
|
|
142
|
+
if not isinstance(payload, bytes | bytearray):
|
|
143
|
+
raise WorkspaceWriteTypeError(path=path, actual_type=type(payload).__name__)
|
|
144
|
+
target = await self._validate_path_access(path, for_write=True)
|
|
145
|
+
await self._put(bytes(payload), sandbox_path_str(target), error_path=target)
|
|
146
|
+
|
|
147
|
+
async def _put(self, payload: bytes, target: str, *, error_path: Path) -> None:
|
|
148
|
+
"""Write bytes to any absolute path: the files API is rooted at the sandbox home, so stage there."""
|
|
149
|
+
staged = f".pilldrops-upload-{uuid.uuid4().hex}"
|
|
150
|
+
quoted = shlex.quote(target)
|
|
151
|
+
try:
|
|
152
|
+
await asyncio.to_thread(self._sandbox.files.write, staged, payload)
|
|
153
|
+
result = await asyncio.to_thread(
|
|
154
|
+
self._sandbox.run, f"mkdir -p -- \"$(dirname {quoted})\" && mv -- {staged} {quoted}"
|
|
155
|
+
)
|
|
156
|
+
except Exception as e:
|
|
157
|
+
raise WorkspaceArchiveWriteError(path=error_path, cause=e) from e
|
|
158
|
+
if result.exit_code != 0:
|
|
159
|
+
await asyncio.to_thread(self._sandbox.run, f"rm -f -- {staged}")
|
|
160
|
+
raise WorkspaceArchiveWriteError(path=error_path, context={"stderr": result.stderr})
|
|
161
|
+
|
|
162
|
+
async def running(self) -> bool:
|
|
163
|
+
if not self.state.workspace_root_ready:
|
|
164
|
+
return False
|
|
165
|
+
try:
|
|
166
|
+
current = await asyncio.to_thread(Sandbox.connect, self.state.sandbox_id)
|
|
167
|
+
except Exception:
|
|
168
|
+
return False
|
|
169
|
+
return current.status == "running"
|
|
170
|
+
|
|
171
|
+
async def persist_workspace(self) -> io.IOBase:
|
|
172
|
+
root = self._workspace_root_path()
|
|
173
|
+
excludes = " ".join(shell_tar_exclude_args(self._persist_workspace_skip_relpaths()))
|
|
174
|
+
try:
|
|
175
|
+
result = await self._run(f"tar {excludes} -C {shlex.quote(root.as_posix())} -cf - . | base64", timeout=300)
|
|
176
|
+
except Exception as e:
|
|
177
|
+
raise WorkspaceArchiveReadError(path=posix_path_for_error(root), cause=e) from e
|
|
178
|
+
if not result.ok():
|
|
179
|
+
raise WorkspaceArchiveReadError(
|
|
180
|
+
path=posix_path_for_error(root),
|
|
181
|
+
context={"reason": "snapshot_nonzero_exit", "stderr": result.stderr.decode()},
|
|
182
|
+
)
|
|
183
|
+
try:
|
|
184
|
+
return io.BytesIO(base64.b64decode(result.stdout))
|
|
185
|
+
except (binascii.Error, ValueError) as e:
|
|
186
|
+
raise WorkspaceArchiveReadError(
|
|
187
|
+
path=posix_path_for_error(root), context={"reason": "snapshot_invalid_base64"}, cause=e
|
|
188
|
+
) from e
|
|
189
|
+
|
|
190
|
+
async def hydrate_workspace(self, data: io.IOBase) -> None:
|
|
191
|
+
root = self._workspace_root_path()
|
|
192
|
+
error_root = posix_path_for_error(root)
|
|
193
|
+
raw = data.read()
|
|
194
|
+
if isinstance(raw, str):
|
|
195
|
+
raw = raw.encode("utf-8")
|
|
196
|
+
if not isinstance(raw, bytes | bytearray):
|
|
197
|
+
raise WorkspaceWriteTypeError(path=root, actual_type=type(raw).__name__)
|
|
198
|
+
try:
|
|
199
|
+
validate_tar_bytes(bytes(raw), allow_external_symlink_targets=False)
|
|
200
|
+
except UnsafeTarMemberError as e:
|
|
201
|
+
raise WorkspaceArchiveWriteError(
|
|
202
|
+
path=error_root, context={"reason": "unsafe_or_invalid_tar", "member": e.member}, cause=e
|
|
203
|
+
) from e
|
|
204
|
+
tar_path = f"/tmp/sandbox-hydrate-{self.state.session_id.hex}.tar"
|
|
205
|
+
await self._put(bytes(raw), tar_path, error_path=error_root)
|
|
206
|
+
try:
|
|
207
|
+
result = await self._run(
|
|
208
|
+
f"mkdir -p -- {shlex.quote(root.as_posix())} && tar -C {shlex.quote(root.as_posix())} -xf {tar_path}",
|
|
209
|
+
timeout=300,
|
|
210
|
+
)
|
|
211
|
+
finally:
|
|
212
|
+
await self._run(f"rm -f -- {tar_path}", timeout=30)
|
|
213
|
+
if not result.ok():
|
|
214
|
+
raise WorkspaceArchiveWriteError(
|
|
215
|
+
path=error_root, context={"reason": "hydrate_nonzero_exit", "stderr": result.stderr.decode()}
|
|
216
|
+
)
|
|
217
|
+
self.state.workspace_root_ready = True
|
|
218
|
+
|
|
219
|
+
async def _shutdown_backend(self) -> None:
|
|
220
|
+
try:
|
|
221
|
+
if self.state.pause_on_exit:
|
|
222
|
+
await asyncio.to_thread(self._sandbox.pause)
|
|
223
|
+
else:
|
|
224
|
+
await asyncio.to_thread(self._sandbox.kill)
|
|
225
|
+
except Exception:
|
|
226
|
+
logger.warning("Could not stop PillDrops sandbox %s", self.state.sandbox_id, exc_info=True)
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class PillDropsSandboxClient(BaseSandboxClient[PillDropsSandboxClientOptions]):
|
|
230
|
+
"""Creates PillDrops sandboxes for `SandboxRunConfig(client=...)`. Reads `PILLDROPS_API_KEY`."""
|
|
231
|
+
|
|
232
|
+
backend_id = "pilldrops"
|
|
233
|
+
|
|
234
|
+
def __init__(self, *, instrumentation: Instrumentation | None = None) -> None:
|
|
235
|
+
self._instrumentation = instrumentation if instrumentation is not None else Instrumentation()
|
|
236
|
+
self._dependencies = None
|
|
237
|
+
|
|
238
|
+
async def create(
|
|
239
|
+
self,
|
|
240
|
+
*,
|
|
241
|
+
snapshot: SnapshotSpec | SnapshotBase | None = None,
|
|
242
|
+
manifest: Manifest | None = None,
|
|
243
|
+
options: PillDropsSandboxClientOptions,
|
|
244
|
+
) -> SandboxSession:
|
|
245
|
+
manifest = manifest if manifest is not None else Manifest()
|
|
246
|
+
self._validate_manifest_for_create(manifest)
|
|
247
|
+
if manifest.ephemeral_mount_targets():
|
|
248
|
+
raise ValueError("PillDropsSandboxClient does not support manifest mounts")
|
|
249
|
+
base_envs = dict(options.envs or {})
|
|
250
|
+
envs = {**base_envs, **await manifest.environment.resolve()}
|
|
251
|
+
sandbox = await asyncio.to_thread(
|
|
252
|
+
Sandbox.create, options.template, env=envs or None, timeout=options.timeout or 0
|
|
253
|
+
)
|
|
254
|
+
session_id = uuid.uuid4()
|
|
255
|
+
state = PillDropsSandboxSessionState(
|
|
256
|
+
session_id=session_id,
|
|
257
|
+
manifest=manifest,
|
|
258
|
+
snapshot=resolve_snapshot(snapshot, str(session_id)),
|
|
259
|
+
sandbox_id=sandbox.id,
|
|
260
|
+
template=options.template,
|
|
261
|
+
sandbox_timeout=options.timeout,
|
|
262
|
+
base_envs=base_envs,
|
|
263
|
+
pause_on_exit=options.pause_on_exit,
|
|
264
|
+
)
|
|
265
|
+
return self._wrap_session(PillDropsSandboxSession(state=state, sandbox=sandbox), instrumentation=self._instrumentation)
|
|
266
|
+
|
|
267
|
+
async def delete(self, session: SandboxSession) -> SandboxSession:
|
|
268
|
+
if not isinstance(session._inner, PillDropsSandboxSession):
|
|
269
|
+
raise TypeError("PillDropsSandboxClient.delete expects a PillDropsSandboxSession")
|
|
270
|
+
return session
|
|
271
|
+
|
|
272
|
+
async def resume(self, state: SandboxSessionState) -> SandboxSession:
|
|
273
|
+
if not isinstance(state, PillDropsSandboxSessionState):
|
|
274
|
+
raise TypeError("PillDropsSandboxClient.resume expects a PillDropsSandboxSessionState")
|
|
275
|
+
state.assert_path_grants_rebound()
|
|
276
|
+
reconnected = False
|
|
277
|
+
try:
|
|
278
|
+
sandbox = await asyncio.to_thread(Sandbox.connect, state.sandbox_id)
|
|
279
|
+
if sandbox.status == "paused":
|
|
280
|
+
await asyncio.to_thread(sandbox.resume)
|
|
281
|
+
reconnected = True
|
|
282
|
+
except APIError:
|
|
283
|
+
envs = {**state.base_envs, **await state.manifest.environment.resolve()}
|
|
284
|
+
sandbox = await asyncio.to_thread(
|
|
285
|
+
Sandbox.create, state.template, env=envs or None, timeout=state.sandbox_timeout or 0
|
|
286
|
+
)
|
|
287
|
+
state.sandbox_id = sandbox.id
|
|
288
|
+
state.workspace_root_ready = False
|
|
289
|
+
inner = PillDropsSandboxSession(state=state, sandbox=sandbox)
|
|
290
|
+
inner._set_start_state_preserved(reconnected, system=reconnected)
|
|
291
|
+
return self._wrap_session(inner, instrumentation=self._instrumentation)
|
|
292
|
+
|
|
293
|
+
def deserialize_session_state(self, payload: dict[str, object]) -> SandboxSessionState:
|
|
294
|
+
return self._deserialize_session_state_payload(payload, PillDropsSandboxSessionState)
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "openai-agents-pilldrops"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "PillDrops sandboxes for the OpenAI Agents SDK"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
dependencies = ["openai-agents>=0.26.0,<0.27.0", "pilldrops>=1.6.0"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Homepage = "https://pilldrops.com"
|
|
16
|
+
Repository = "https://github.com/pilldrops-oss/pilldrops-integrations"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["openai_agents_pilldrops"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""Live check against a real PillDrops sandbox: python tests/live_check.py (needs PILLDROPS_API_KEY)."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import io
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from agents import RunConfig, Runner
|
|
7
|
+
from agents.sandbox import SandboxAgent, SandboxRunConfig
|
|
8
|
+
from agents.sandbox.capabilities import Shell
|
|
9
|
+
from agents.sandbox.errors import WorkspaceReadNotFoundError
|
|
10
|
+
from agents.testing import ScriptedModel, assistant_message, function_call
|
|
11
|
+
|
|
12
|
+
from openai_agents_pilldrops import PillDropsSandboxClient, PillDropsSandboxClientOptions
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
async def main() -> None:
|
|
16
|
+
client = PillDropsSandboxClient()
|
|
17
|
+
|
|
18
|
+
model = ScriptedModel([
|
|
19
|
+
[function_call("exec_command", {"cmd": "echo provider-ok > note.txt && cat note.txt && pwd"}, call_id="c1")],
|
|
20
|
+
[assistant_message("done")],
|
|
21
|
+
])
|
|
22
|
+
agent = SandboxAgent(name="live check", model=model, capabilities=[Shell()])
|
|
23
|
+
result = await Runner.run(agent, "Run the command.", run_config=RunConfig(
|
|
24
|
+
tracing_disabled=True, sandbox=SandboxRunConfig(client=client, options=PillDropsSandboxClientOptions())))
|
|
25
|
+
outputs = " ".join(str(i.output) for i in result.new_items if i.type == "tool_call_output_item")
|
|
26
|
+
assert "provider-ok" in outputs and "/workspace" in outputs, outputs
|
|
27
|
+
print("runner: ok")
|
|
28
|
+
|
|
29
|
+
session = await client.create(options=PillDropsSandboxClientOptions())
|
|
30
|
+
await session.start()
|
|
31
|
+
try:
|
|
32
|
+
assert await session.running()
|
|
33
|
+
blob = bytes(range(256)) * 40
|
|
34
|
+
await session.write(Path("data/blob.bin"), io.BytesIO(blob))
|
|
35
|
+
assert (await session.read(Path("data/blob.bin"))).read() == blob
|
|
36
|
+
snapshot = (await session.persist_workspace()).read()
|
|
37
|
+
await session.exec("rm", "-rf", "data", shell=False)
|
|
38
|
+
await session.hydrate_workspace(io.BytesIO(snapshot))
|
|
39
|
+
assert (await session.read(Path("data/blob.bin"))).read() == blob
|
|
40
|
+
try:
|
|
41
|
+
await session.read(Path("missing.txt"))
|
|
42
|
+
raise AssertionError("expected WorkspaceReadNotFoundError")
|
|
43
|
+
except WorkspaceReadNotFoundError:
|
|
44
|
+
pass
|
|
45
|
+
print(f"session: ok (snapshot {len(snapshot)} bytes)")
|
|
46
|
+
finally:
|
|
47
|
+
await session.shutdown()
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
asyncio.run(main())
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Options and session state register with the SDK and survive a serialization round trip."""
|
|
2
|
+
import uuid
|
|
3
|
+
|
|
4
|
+
from agents.sandbox.manifest import Manifest
|
|
5
|
+
from agents.sandbox.session import BaseSandboxClientOptions
|
|
6
|
+
from agents.sandbox.snapshot import resolve_snapshot
|
|
7
|
+
|
|
8
|
+
from openai_agents_pilldrops import PillDropsSandboxClient, PillDropsSandboxClientOptions, PillDropsSandboxSessionState
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def test_options_parse_from_a_dict():
|
|
12
|
+
opts = BaseSandboxClientOptions.parse({"type": "pilldrops", "template": "node", "pause_on_exit": True})
|
|
13
|
+
assert isinstance(opts, PillDropsSandboxClientOptions)
|
|
14
|
+
assert (opts.template, opts.pause_on_exit) == ("node", True)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def test_state_round_trips_through_the_client():
|
|
18
|
+
session_id = uuid.uuid4()
|
|
19
|
+
state = PillDropsSandboxSessionState(
|
|
20
|
+
session_id=session_id, manifest=Manifest(), snapshot=resolve_snapshot(None, str(session_id)), sandbox_id="sb-1",
|
|
21
|
+
template="node", sandbox_timeout=600, base_envs={"A": "1"}, pause_on_exit=True,
|
|
22
|
+
)
|
|
23
|
+
back = PillDropsSandboxClient().deserialize_session_state(state.model_dump(mode="json"))
|
|
24
|
+
assert isinstance(back, PillDropsSandboxSessionState)
|
|
25
|
+
assert (back.sandbox_id, back.template, back.sandbox_timeout, back.base_envs, back.pause_on_exit) == (
|
|
26
|
+
"sb-1", "node", 600, {"A": "1"}, True)
|