opensandbox-deepagents 0.1.0__py3-none-any.whl
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.
- opensandbox_deepagents/__init__.py +36 -0
- opensandbox_deepagents/provider.py +234 -0
- opensandbox_deepagents/sandbox.py +317 -0
- opensandbox_deepagents-0.1.0.dist-info/METADATA +153 -0
- opensandbox_deepagents-0.1.0.dist-info/RECORD +8 -0
- opensandbox_deepagents-0.1.0.dist-info/WHEEL +4 -0
- opensandbox_deepagents-0.1.0.dist-info/entry_points.txt +2 -0
- opensandbox_deepagents-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
"""OpenSandbox integration for Deep Agents.
|
|
2
|
+
|
|
3
|
+
Exposes:
|
|
4
|
+
|
|
5
|
+
- `OpenSandboxSandbox`: a `deepagents.backends.sandbox.BaseSandbox` backend
|
|
6
|
+
over the official OpenSandbox Python SDK (`SandboxSync`).
|
|
7
|
+
- `OpenSandboxProvider`: a `deepagents-code` sandbox provider, registered under
|
|
8
|
+
the `deepagents_code.sandbox_providers` entry-point group (requires the
|
|
9
|
+
optional `dcode` extra).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import TYPE_CHECKING
|
|
15
|
+
|
|
16
|
+
from opensandbox_deepagents.sandbox import OpenSandboxSandbox
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from opensandbox_deepagents.provider import OpenSandboxProvider
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
|
|
23
|
+
__all__ = [
|
|
24
|
+
"OpenSandboxProvider",
|
|
25
|
+
"OpenSandboxSandbox",
|
|
26
|
+
"__version__",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def __getattr__(name: str) -> object:
|
|
31
|
+
"""Lazy-import the provider so `deepagents-code` stays an optional dep."""
|
|
32
|
+
if name == "OpenSandboxProvider":
|
|
33
|
+
from opensandbox_deepagents.provider import OpenSandboxProvider
|
|
34
|
+
|
|
35
|
+
return OpenSandboxProvider
|
|
36
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""OpenSandbox provider for Deep Agents Code.
|
|
2
|
+
|
|
3
|
+
`OpenSandboxProvider` implements the `SandboxProvider` interface consumed by
|
|
4
|
+
`deepagents-code`. It is registered under the `deepagents_code.sandbox_providers`
|
|
5
|
+
entry-point group, so once this package is installed:
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
dcode --sandbox opensandbox
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
works without any further configuration. The provider supports connecting to an
|
|
12
|
+
existing sandbox by id, creating one from an image, and the snapshot workflow
|
|
13
|
+
(`snapshot=<name>` resolves an existing snapshot by name or builds one from the
|
|
14
|
+
image on first use).
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
from datetime import timedelta
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from deepagents_code.integrations.sandbox_provider import (
|
|
24
|
+
SandboxInstallHint,
|
|
25
|
+
SandboxProvider,
|
|
26
|
+
SandboxProviderMetadata,
|
|
27
|
+
)
|
|
28
|
+
from opensandbox import SandboxManagerSync, SandboxSync
|
|
29
|
+
from opensandbox.models.sandboxes import SnapshotFilter, SnapshotInfo
|
|
30
|
+
|
|
31
|
+
from opensandbox_deepagents.sandbox import OpenSandboxSandbox
|
|
32
|
+
|
|
33
|
+
logger = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
PROVIDER_NAME = "opensandbox"
|
|
36
|
+
PACKAGE_NAME = "opensandbox-deepagents"
|
|
37
|
+
|
|
38
|
+
DEFAULT_IMAGE = "python:3.12-slim"
|
|
39
|
+
"""Image used when neither `image` nor `snapshot` is provided."""
|
|
40
|
+
|
|
41
|
+
DEFAULT_SANDBOX_LIFETIME = timedelta(minutes=60)
|
|
42
|
+
"""Sandbox lifetime applied on create when the caller does not override it.
|
|
43
|
+
|
|
44
|
+
The sandbox self-terminates after this budget unless renewed or deleted
|
|
45
|
+
earlier through the provider.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
_TERMINAL_SNAPSHOT_STATE_FRAGMENTS = ("fail", "error", "delet", "abort")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class OpenSandboxProvider(SandboxProvider):
|
|
52
|
+
"""Create, connect to, and delete OpenSandbox sandboxes for dcode."""
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def metadata(self) -> SandboxProviderMetadata:
|
|
56
|
+
"""Describe the provider for the dcode registry."""
|
|
57
|
+
return SandboxProviderMetadata(
|
|
58
|
+
name=PROVIDER_NAME,
|
|
59
|
+
working_dir="/workspace",
|
|
60
|
+
install=SandboxInstallHint(kind="package", name=PACKAGE_NAME),
|
|
61
|
+
supports_sandbox_id=True,
|
|
62
|
+
supports_snapshot_name=True,
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
def get_or_create(
|
|
66
|
+
self,
|
|
67
|
+
*,
|
|
68
|
+
sandbox_id: str | None = None,
|
|
69
|
+
image: str | None = None,
|
|
70
|
+
snapshot: str | None = None,
|
|
71
|
+
connection_config: Any | None = None,
|
|
72
|
+
lifetime_seconds: int | None = None,
|
|
73
|
+
**kwargs: Any,
|
|
74
|
+
) -> OpenSandboxSandbox:
|
|
75
|
+
"""Get an existing sandbox by id, or create one.
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
sandbox_id: Connect to an existing sandbox instead of creating.
|
|
79
|
+
image: Container image for new sandboxes (default `python:3.12-slim`).
|
|
80
|
+
Ignored when `sandbox_id` is given or `snapshot` resolves.
|
|
81
|
+
snapshot: Snapshot name. When given, the provider restores the
|
|
82
|
+
named snapshot, creating it from `image` first if it does not
|
|
83
|
+
exist yet. Requires a deployment with snapshot support.
|
|
84
|
+
connection_config: Optional OpenSandbox `ConnectionConfigSync` for
|
|
85
|
+
endpoint/auth overrides.
|
|
86
|
+
lifetime_seconds: Sandbox lifetime budget in seconds for newly
|
|
87
|
+
created sandboxes (default 60 minutes). Pass `0` for a sandbox
|
|
88
|
+
that lives until explicitly deleted.
|
|
89
|
+
**kwargs: Additional keyword arguments are forwarded to
|
|
90
|
+
`SandboxSync.create`.
|
|
91
|
+
|
|
92
|
+
Returns:
|
|
93
|
+
A ready `OpenSandboxSandbox` backend.
|
|
94
|
+
|
|
95
|
+
"""
|
|
96
|
+
if sandbox_id:
|
|
97
|
+
return OpenSandboxSandbox(
|
|
98
|
+
sandbox=SandboxSync.connect(
|
|
99
|
+
sandbox_id,
|
|
100
|
+
connection_config=connection_config,
|
|
101
|
+
),
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
if lifetime_seconds is None:
|
|
105
|
+
lifetime = DEFAULT_SANDBOX_LIFETIME
|
|
106
|
+
elif lifetime_seconds == 0:
|
|
107
|
+
lifetime = None
|
|
108
|
+
else:
|
|
109
|
+
lifetime = timedelta(seconds=lifetime_seconds)
|
|
110
|
+
|
|
111
|
+
if snapshot is not None:
|
|
112
|
+
manager = SandboxManagerSync.create(connection_config)
|
|
113
|
+
snapshot_id = self._ensure_snapshot(
|
|
114
|
+
manager,
|
|
115
|
+
snapshot_name=snapshot,
|
|
116
|
+
image=image or DEFAULT_IMAGE,
|
|
117
|
+
lifetime=lifetime,
|
|
118
|
+
connection_config=connection_config,
|
|
119
|
+
**kwargs,
|
|
120
|
+
)
|
|
121
|
+
return OpenSandboxSandbox(
|
|
122
|
+
sandbox=SandboxSync.create(
|
|
123
|
+
snapshot_id=snapshot_id,
|
|
124
|
+
timeout=lifetime,
|
|
125
|
+
connection_config=connection_config,
|
|
126
|
+
**_create_kwargs(kwargs),
|
|
127
|
+
),
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
return OpenSandboxSandbox(
|
|
131
|
+
sandbox=SandboxSync.create(
|
|
132
|
+
image or DEFAULT_IMAGE,
|
|
133
|
+
timeout=lifetime,
|
|
134
|
+
connection_config=connection_config,
|
|
135
|
+
**kwargs,
|
|
136
|
+
),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
def delete(
|
|
140
|
+
self,
|
|
141
|
+
*,
|
|
142
|
+
sandbox_id: str,
|
|
143
|
+
**kwargs: Any, # noqa: ARG002 # provider interface requires the kwarg sink
|
|
144
|
+
) -> None:
|
|
145
|
+
"""Terminate a sandbox by id."""
|
|
146
|
+
SandboxManagerSync.create().kill_sandbox(sandbox_id)
|
|
147
|
+
|
|
148
|
+
def _ensure_snapshot(
|
|
149
|
+
self,
|
|
150
|
+
manager: SandboxManagerSync,
|
|
151
|
+
*,
|
|
152
|
+
snapshot_name: str,
|
|
153
|
+
image: str,
|
|
154
|
+
lifetime: timedelta | None,
|
|
155
|
+
connection_config: Any | None,
|
|
156
|
+
**create_kwargs: Any,
|
|
157
|
+
) -> str:
|
|
158
|
+
"""Resolve a snapshot by name, building it from `image` when missing.
|
|
159
|
+
|
|
160
|
+
The state vocabulary for snapshots is deployment-specific; the poll
|
|
161
|
+
treats states containing `fail`, `error`, `delet`, or `abort` as
|
|
162
|
+
terminal and waits out anything else up to a bounded budget.
|
|
163
|
+
"""
|
|
164
|
+
existing = self._find_snapshot_by_name(manager, snapshot_name)
|
|
165
|
+
if existing is not None:
|
|
166
|
+
return existing.id
|
|
167
|
+
|
|
168
|
+
logger.info(
|
|
169
|
+
"Snapshot %r not found; building it from image %r", snapshot_name, image
|
|
170
|
+
)
|
|
171
|
+
builder = SandboxSync.create(
|
|
172
|
+
image,
|
|
173
|
+
timeout=DEFAULT_SANDBOX_LIFETIME,
|
|
174
|
+
connection_config=connection_config,
|
|
175
|
+
**create_kwargs,
|
|
176
|
+
)
|
|
177
|
+
try:
|
|
178
|
+
snapshot = builder.create_snapshot(name=snapshot_name)
|
|
179
|
+
self._raise_if_terminal(manager, snapshot, snapshot_name)
|
|
180
|
+
return snapshot.id
|
|
181
|
+
finally:
|
|
182
|
+
try:
|
|
183
|
+
builder.destroy()
|
|
184
|
+
except Exception: # noqa: BLE001 # cleanup must not mask the result
|
|
185
|
+
logger.warning(
|
|
186
|
+
"Could not destroy builder sandbox %s", builder.id, exc_info=True
|
|
187
|
+
)
|
|
188
|
+
|
|
189
|
+
def _find_snapshot_by_name(
|
|
190
|
+
self,
|
|
191
|
+
manager: SandboxManagerSync,
|
|
192
|
+
snapshot_name: str,
|
|
193
|
+
) -> SnapshotInfo | None:
|
|
194
|
+
"""Return the most recent non-terminal snapshot with this name."""
|
|
195
|
+
page = manager.list_snapshots(SnapshotFilter(name=snapshot_name))
|
|
196
|
+
for snapshot in page.snapshot_infos:
|
|
197
|
+
state = (snapshot.status.state or "").lower()
|
|
198
|
+
if not any(
|
|
199
|
+
fragment in state for fragment in _TERMINAL_SNAPSHOT_STATE_FRAGMENTS
|
|
200
|
+
):
|
|
201
|
+
return snapshot
|
|
202
|
+
return None
|
|
203
|
+
|
|
204
|
+
def _raise_if_terminal(
|
|
205
|
+
self,
|
|
206
|
+
manager: SandboxManagerSync,
|
|
207
|
+
snapshot: SnapshotInfo,
|
|
208
|
+
snapshot_name: str,
|
|
209
|
+
) -> None:
|
|
210
|
+
"""Fail fast when a fresh snapshot reports a terminal-bad state.
|
|
211
|
+
|
|
212
|
+
Restore readiness itself is re-checked by `SandboxSync.create` during
|
|
213
|
+
the restore, so no ready-poll is attempted here.
|
|
214
|
+
"""
|
|
215
|
+
try:
|
|
216
|
+
current = manager.get_snapshot(snapshot.id)
|
|
217
|
+
except Exception: # noqa: BLE001 # transient lookup failures are not terminal
|
|
218
|
+
return
|
|
219
|
+
state = (
|
|
220
|
+
(current.status.state if current is not None else "") or ""
|
|
221
|
+
).lower()
|
|
222
|
+
if any(
|
|
223
|
+
fragment in state for fragment in _TERMINAL_SNAPSHOT_STATE_FRAGMENTS
|
|
224
|
+
):
|
|
225
|
+
raise RuntimeError(
|
|
226
|
+
f"Snapshot '{snapshot_name}' reported terminal state '{state}' "
|
|
227
|
+
"during creation"
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _create_kwargs(kwargs: dict[str, Any]) -> dict[str, Any]:
|
|
232
|
+
"""Forward creation kwargs to `SandboxSync.create` for snapshot restores."""
|
|
233
|
+
# `image` is handled by the snapshot builder, not the restore call.
|
|
234
|
+
return {key: value for key, value in kwargs.items() if key != "image"}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""OpenSandbox backend for Deep Agents.
|
|
2
|
+
|
|
3
|
+
`OpenSandboxSandbox` implements the Deep Agents `BaseSandbox` contract on top of
|
|
4
|
+
the official OpenSandbox Python SDK (`SandboxSync`). All high-level file
|
|
5
|
+
operations (list, read, write, edit, glob, grep) are inherited from
|
|
6
|
+
`BaseSandbox` and run through `execute()`; this module only provides the
|
|
7
|
+
command-execution and bulk file-transfer primitives.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import logging
|
|
13
|
+
import stat
|
|
14
|
+
from datetime import timedelta
|
|
15
|
+
from typing import TYPE_CHECKING, Any
|
|
16
|
+
|
|
17
|
+
from deepagents.backends.protocol import (
|
|
18
|
+
ExecuteResponse,
|
|
19
|
+
FileDownloadResponse,
|
|
20
|
+
FileUploadResponse,
|
|
21
|
+
)
|
|
22
|
+
from deepagents.backends.sandbox import BaseSandbox
|
|
23
|
+
from opensandbox.exceptions import SandboxApiException
|
|
24
|
+
from opensandbox.models.execd import OutputMessage, RunCommandOpts
|
|
25
|
+
|
|
26
|
+
if TYPE_CHECKING:
|
|
27
|
+
from opensandbox import SandboxSync
|
|
28
|
+
from opensandbox.models.execd import Execution
|
|
29
|
+
from opensandbox.models.filesystem import EntryInfo
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
DEFAULT_COMMAND_TIMEOUT = 30 * 60
|
|
34
|
+
"""Default `execute()` timeout in seconds when the caller passes ``None``.
|
|
35
|
+
|
|
36
|
+
Matches the default used by the other Deep Agents sandbox integrations.
|
|
37
|
+
"""
|
|
38
|
+
|
|
39
|
+
_NO_TIMEOUT = 0
|
|
40
|
+
"""`timeout=0` sentinel: wait indefinitely (no server-side deadline)."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _combine_output(execution: Execution) -> str:
|
|
44
|
+
"""Merge stdout and stderr messages into one output string.
|
|
45
|
+
|
|
46
|
+
Messages are ordered chronologically by their sandbox-side timestamp;
|
|
47
|
+
ties keep emission order so line boundaries within each stream are never
|
|
48
|
+
reordered relative to each other. Text is joined without inserting
|
|
49
|
+
separators because each message already carries its own trailing newline
|
|
50
|
+
(or is a fragment).
|
|
51
|
+
"""
|
|
52
|
+
ordered: list[tuple[int, int, OutputMessage]] = []
|
|
53
|
+
for index, messages in (
|
|
54
|
+
(0, execution.logs.stdout),
|
|
55
|
+
(1, execution.logs.stderr),
|
|
56
|
+
):
|
|
57
|
+
for position, message in enumerate(messages):
|
|
58
|
+
ordered.append((message.timestamp, index * 10_000_000 + position, message))
|
|
59
|
+
ordered.sort(key=lambda item: (item[0], item[1]))
|
|
60
|
+
return "".join(message.text for _, _, message in ordered)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class OpenSandboxSandbox(BaseSandbox):
|
|
64
|
+
"""Deep Agents sandbox backend backed by an OpenSandbox sandbox.
|
|
65
|
+
|
|
66
|
+
The backend wraps a caller-owned `SandboxSync` instance and implements the
|
|
67
|
+
two primitives the `BaseSandbox` contract requires: `execute()` (shell
|
|
68
|
+
commands) and bulk `upload_files()` / `download_files()`. Everything else
|
|
69
|
+
(read, write, edit, ls, glob, grep, delete) is derived by `BaseSandbox`
|
|
70
|
+
from those primitives and assumes a POSIX shell plus `python3` in the
|
|
71
|
+
sandbox image.
|
|
72
|
+
|
|
73
|
+
Example:
|
|
74
|
+
```python
|
|
75
|
+
from opensandbox import SandboxSync
|
|
76
|
+
|
|
77
|
+
from opensandbox_deepagents import OpenSandboxSandbox
|
|
78
|
+
|
|
79
|
+
sandbox = SandboxSync.create("python:3.12-slim")
|
|
80
|
+
backend = OpenSandboxSandbox(sandbox=sandbox)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
!!! note
|
|
84
|
+
|
|
85
|
+
The integration uses the synchronous SDK deliberately: the Deep Agents
|
|
86
|
+
sync contract maps to it directly, and Deep Agents already provides
|
|
87
|
+
non-blocking async wrappers (`aexecute`, `aread`, ...) that run sync
|
|
88
|
+
backends in worker threads.
|
|
89
|
+
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
*,
|
|
95
|
+
sandbox: SandboxSync,
|
|
96
|
+
default_timeout: int = DEFAULT_COMMAND_TIMEOUT,
|
|
97
|
+
) -> None:
|
|
98
|
+
"""Create a backend wrapping an existing OpenSandbox sandbox.
|
|
99
|
+
|
|
100
|
+
Args:
|
|
101
|
+
sandbox: A connected `SandboxSync` instance. Ownership stays with
|
|
102
|
+
the caller: the backend does not destroy the sandbox on
|
|
103
|
+
garbage collection; call `sandbox.destroy()` yourself (or go
|
|
104
|
+
through the provider, which manages lifecycle).
|
|
105
|
+
default_timeout: Command timeout in seconds used when `execute()`
|
|
106
|
+
is called without an explicit `timeout`.
|
|
107
|
+
|
|
108
|
+
"""
|
|
109
|
+
self._sandbox = sandbox
|
|
110
|
+
self._default_timeout = default_timeout
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def id(self) -> str:
|
|
114
|
+
"""Return the OpenSandbox sandbox id."""
|
|
115
|
+
return str(self._sandbox.id)
|
|
116
|
+
|
|
117
|
+
def execute(
|
|
118
|
+
self,
|
|
119
|
+
command: str,
|
|
120
|
+
*,
|
|
121
|
+
timeout: int | None = None,
|
|
122
|
+
) -> ExecuteResponse:
|
|
123
|
+
"""Execute a shell command inside the sandbox.
|
|
124
|
+
|
|
125
|
+
Args:
|
|
126
|
+
command: Full shell command string to execute.
|
|
127
|
+
timeout: Maximum time in seconds to wait for the command. The
|
|
128
|
+
deadline is enforced server-side by OpenSandbox, which
|
|
129
|
+
terminates the process when it fires.
|
|
130
|
+
|
|
131
|
+
- `None` uses `default_timeout`.
|
|
132
|
+
- `0` waits indefinitely (no server-side deadline).
|
|
133
|
+
|
|
134
|
+
Returns:
|
|
135
|
+
`ExecuteResponse` with stdout and stderr merged in chronological
|
|
136
|
+
order, the command exit code, and `truncated=False` (the
|
|
137
|
+
OpenSandbox command transport does not clip output).
|
|
138
|
+
|
|
139
|
+
When the server reports an execution error without an exit
|
|
140
|
+
code (e.g. the command was killed at the deadline), the error
|
|
141
|
+
text is appended to the output and the exit code is `1`;
|
|
142
|
+
when no exit code is available and no error is reported
|
|
143
|
+
(older servers), the exit code is `0`.
|
|
144
|
+
|
|
145
|
+
"""
|
|
146
|
+
effective_timeout = self._default_timeout if timeout is None else timeout
|
|
147
|
+
opts = RunCommandOpts(
|
|
148
|
+
timeout=(
|
|
149
|
+
None
|
|
150
|
+
if effective_timeout == _NO_TIMEOUT
|
|
151
|
+
else timedelta(seconds=effective_timeout)
|
|
152
|
+
),
|
|
153
|
+
)
|
|
154
|
+
execution = self._sandbox.commands.run(command, opts=opts)
|
|
155
|
+
output = _combine_output(execution)
|
|
156
|
+
exit_code = execution.exit_code
|
|
157
|
+
if exit_code is None:
|
|
158
|
+
if execution.error is not None:
|
|
159
|
+
detail = f"[error] {execution.error.name}: {execution.error.value}"
|
|
160
|
+
output = f"{output}\n{detail}" if output else detail
|
|
161
|
+
exit_code = 1
|
|
162
|
+
else:
|
|
163
|
+
exit_code = 0
|
|
164
|
+
return ExecuteResponse(output=output, exit_code=exit_code, truncated=False)
|
|
165
|
+
|
|
166
|
+
def upload_files(self, files: list[tuple[str, bytes]]) -> list[FileUploadResponse]:
|
|
167
|
+
"""Upload files into the sandbox, preserving input order.
|
|
168
|
+
|
|
169
|
+
Parent directories are created first (`mkdir -p` semantics) for all
|
|
170
|
+
valid target paths. Each file is transferred individually so a failure
|
|
171
|
+
on one file does not discard the others.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
files: `(absolute_path, content)` pairs. Relative paths are
|
|
175
|
+
rejected with `error="invalid_path"`.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
One `FileUploadResponse` per input path, in input order, with
|
|
179
|
+
`error` set on per-file failures.
|
|
180
|
+
|
|
181
|
+
"""
|
|
182
|
+
responses: list[FileUploadResponse] = []
|
|
183
|
+
valid: list[tuple[str, bytes]] = []
|
|
184
|
+
for path, content in files:
|
|
185
|
+
if not path.startswith("/"):
|
|
186
|
+
responses.append(FileUploadResponse(path=path, error="invalid_path"))
|
|
187
|
+
else:
|
|
188
|
+
valid.append((path, content))
|
|
189
|
+
responses.append(FileUploadResponse(path=path, error=None))
|
|
190
|
+
|
|
191
|
+
if valid:
|
|
192
|
+
self._ensure_parent_directories([path for path, _ in valid])
|
|
193
|
+
for index, (path, content) in enumerate(valid):
|
|
194
|
+
try:
|
|
195
|
+
self._sandbox.files.write_file(path, content)
|
|
196
|
+
except Exception as exc: # noqa: BLE001 # per-file partial success
|
|
197
|
+
responses[index] = FileUploadResponse(
|
|
198
|
+
path=path, error=_normalize_fs_error(exc)
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
return responses
|
|
202
|
+
|
|
203
|
+
def download_files(self, paths: list[str]) -> list[FileDownloadResponse]:
|
|
204
|
+
"""Download files from the sandbox, preserving input order.
|
|
205
|
+
|
|
206
|
+
Args:
|
|
207
|
+
paths: Absolute file paths. Relative paths are rejected with
|
|
208
|
+
`error="invalid_path"`.
|
|
209
|
+
|
|
210
|
+
Returns:
|
|
211
|
+
One `FileDownloadResponse` per input path, in input order. Known
|
|
212
|
+
failures are normalized to `file_not_found`,
|
|
213
|
+
`permission_denied`, or `is_directory`; anything else keeps a
|
|
214
|
+
short description of the underlying error.
|
|
215
|
+
|
|
216
|
+
"""
|
|
217
|
+
responses: list[FileDownloadResponse] = []
|
|
218
|
+
valid: list[str] = []
|
|
219
|
+
for path in paths:
|
|
220
|
+
if not path.startswith("/"):
|
|
221
|
+
responses.append(
|
|
222
|
+
FileDownloadResponse(path=path, content=None, error="invalid_path")
|
|
223
|
+
)
|
|
224
|
+
else:
|
|
225
|
+
valid.append(path)
|
|
226
|
+
|
|
227
|
+
infos = self._get_file_infos(valid)
|
|
228
|
+
for path in valid:
|
|
229
|
+
info = infos.get(path) if infos else None
|
|
230
|
+
try:
|
|
231
|
+
content = self._sandbox.files.read_bytes(path)
|
|
232
|
+
except Exception as exc: # noqa: BLE001 # per-file partial success
|
|
233
|
+
responses.append(
|
|
234
|
+
FileDownloadResponse(
|
|
235
|
+
path=path,
|
|
236
|
+
content=None,
|
|
237
|
+
error=_map_download_error(exc, info),
|
|
238
|
+
)
|
|
239
|
+
)
|
|
240
|
+
else:
|
|
241
|
+
responses.append(
|
|
242
|
+
FileDownloadResponse(path=path, content=content, error=None)
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
return responses
|
|
246
|
+
|
|
247
|
+
def _ensure_parent_directories(self, paths: list[str]) -> None:
|
|
248
|
+
"""Create parent directories for all target paths in one command."""
|
|
249
|
+
parents: list[str] = []
|
|
250
|
+
seen: set[str] = set()
|
|
251
|
+
for path in paths:
|
|
252
|
+
parent = path.rsplit("/", 1)[0]
|
|
253
|
+
if parent and parent not in seen:
|
|
254
|
+
seen.add(parent)
|
|
255
|
+
parents.append(parent)
|
|
256
|
+
if not parents:
|
|
257
|
+
return
|
|
258
|
+
command = "mkdir -p " + " ".join(
|
|
259
|
+
"'" + parent.replace("'", "'\\''") + "'" for parent in parents
|
|
260
|
+
)
|
|
261
|
+
result = self.execute(command, timeout=30)
|
|
262
|
+
if result.exit_code != 0:
|
|
263
|
+
logger.warning(
|
|
264
|
+
"Parent directory creation failed for upload targets: %s",
|
|
265
|
+
result.output.strip()[:200],
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def _get_file_infos(self, paths: list[str]) -> dict[str, EntryInfo] | None:
|
|
269
|
+
"""Best-effort metadata lookup used to classify download errors."""
|
|
270
|
+
if not paths:
|
|
271
|
+
return None
|
|
272
|
+
try:
|
|
273
|
+
return self._sandbox.files.get_file_info(paths)
|
|
274
|
+
except Exception: # noqa: BLE001 # metadata is advisory only
|
|
275
|
+
return None
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _is_directory_info(info: Any) -> bool:
|
|
279
|
+
"""Whether an `EntryInfo` record describes a directory."""
|
|
280
|
+
if info is None:
|
|
281
|
+
return False
|
|
282
|
+
entry_type = getattr(info, "entry_type", None)
|
|
283
|
+
if isinstance(entry_type, str) and "dir" in entry_type.lower():
|
|
284
|
+
return True
|
|
285
|
+
mode = getattr(info, "mode", None)
|
|
286
|
+
if isinstance(mode, int):
|
|
287
|
+
return stat.S_ISDIR(mode)
|
|
288
|
+
return False
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
def _map_download_error(exc: Exception, info: Any) -> str:
|
|
292
|
+
"""Normalize a download failure into the shared error vocabulary."""
|
|
293
|
+
if _is_directory_info(info):
|
|
294
|
+
return "is_directory"
|
|
295
|
+
if isinstance(exc, SandboxApiException):
|
|
296
|
+
status = getattr(exc, "status_code", None)
|
|
297
|
+
if status == 404:
|
|
298
|
+
return "file_not_found"
|
|
299
|
+
if status == 403:
|
|
300
|
+
return "permission_denied"
|
|
301
|
+
if status == 400:
|
|
302
|
+
# Some deployments report directories and special files as 400s.
|
|
303
|
+
return "invalid_path"
|
|
304
|
+
return str(exc)[:200]
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _normalize_fs_error(exc: Exception) -> str:
|
|
308
|
+
"""Shorten an upload failure into a stable error string."""
|
|
309
|
+
if isinstance(exc, SandboxApiException):
|
|
310
|
+
status = getattr(exc, "status_code", None)
|
|
311
|
+
if status == 403:
|
|
312
|
+
return "permission_denied"
|
|
313
|
+
if status == 404:
|
|
314
|
+
return "file_not_found"
|
|
315
|
+
if status == 400:
|
|
316
|
+
return "invalid_path"
|
|
317
|
+
return str(exc)[:200]
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: opensandbox-deepagents
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: OpenSandbox sandbox backend and provider for Deep Agents and Deep Agents Code
|
|
5
|
+
Project-URL: Homepage, https://github.com/yjjnls/opensandbox-deepagents
|
|
6
|
+
Project-URL: Repository, https://github.com/yjjnls/opensandbox-deepagents
|
|
7
|
+
Project-URL: Issues, https://github.com/yjjnls/opensandbox-deepagents/issues
|
|
8
|
+
License: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
18
|
+
Requires-Python: <4.0,>=3.11
|
|
19
|
+
Requires-Dist: deepagents<0.8.0,>=0.7.38
|
|
20
|
+
Requires-Dist: opensandbox<2,>=1.2
|
|
21
|
+
Provides-Extra: dcode
|
|
22
|
+
Requires-Dist: deepagents-code>=0.2.9; extra == 'dcode'
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
|
|
25
|
+
# opensandbox-deepagents
|
|
26
|
+
|
|
27
|
+
[OpenSandbox](https://github.com/opensandbox-group/OpenSandbox) sandbox backend and provider for
|
|
28
|
+
[Deep Agents](https://github.com/langchain-ai/deepagents) and [Deep Agents Code](https://github.com/langchain-ai/deepagents) (`dcode`).
|
|
29
|
+
|
|
30
|
+
Run Deep Agents file and shell tooling inside a self-hosted OpenSandbox deployment: the
|
|
31
|
+
`OpenSandboxSandbox` backend implements the `BaseSandbox` contract on top of the official
|
|
32
|
+
OpenSandbox Python SDK, and `OpenSandboxProvider` plugs into `dcode` through its
|
|
33
|
+
`deepagents_code.sandbox_providers` entry-point group — no upstream changes required.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```bash
|
|
38
|
+
pip install opensandbox-deepagents
|
|
39
|
+
|
|
40
|
+
# with the dcode provider integration (deepagents-code requires Python >= 3.14):
|
|
41
|
+
pip install "opensandbox-deepagents[dcode]"
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
Environment configuration follows the OpenSandbox SDK: `OPEN_SANDBOX_API_KEY` /
|
|
45
|
+
`OPEN_SANDBOX_DOMAIN` (or a `ConnectionConfigSync` passed to `create`/`connect`),
|
|
46
|
+
same as any `opensandbox` SDK program.
|
|
47
|
+
|
|
48
|
+
## Use with the Deep Agents SDK
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from opensandbox import SandboxSync
|
|
52
|
+
|
|
53
|
+
from opensandbox_deepagents import OpenSandboxSandbox
|
|
54
|
+
|
|
55
|
+
# Create (or connect with SandboxSync.connect(sandbox_id=...))
|
|
56
|
+
sandbox = SandboxSync.create("python:3.12-slim", timeout=None)
|
|
57
|
+
|
|
58
|
+
backend = OpenSandboxSandbox(sandbox=sandbox)
|
|
59
|
+
|
|
60
|
+
# use as any other Deep Agents backend, e.g.
|
|
61
|
+
# agent = create_deep_agent(model=model, backend=backend)
|
|
62
|
+
result = backend.execute("python3 -c 'print(1 + 1)'")
|
|
63
|
+
print(result.output, result.exit_code)
|
|
64
|
+
|
|
65
|
+
# destroy when done (caller-owned lifecycle)
|
|
66
|
+
sandbox.destroy()
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
## Use with Deep Agents Code
|
|
70
|
+
|
|
71
|
+
After `pip install "opensandbox-deepagents[dcode]"` the provider is discovered through the
|
|
72
|
+
`deepagents_code.sandbox_providers` entry-point group:
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
dcode --sandbox opensandbox
|
|
76
|
+
|
|
77
|
+
# connect to an existing sandbox
|
|
78
|
+
dcode --sandbox opensandbox --sandbox-id <id>
|
|
79
|
+
|
|
80
|
+
# restore a named snapshot (built from the image on first use)
|
|
81
|
+
dcode --sandbox opensandbox --snapshot-name my-snapshot
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Config-level parameters (`~/.deepagents/config.toml`) are forwarded to the provider:
|
|
85
|
+
|
|
86
|
+
```toml
|
|
87
|
+
[sandboxes.providers.opensandbox.params]
|
|
88
|
+
image = "python:3.12-slim"
|
|
89
|
+
lifetime_seconds = 3600 # 0 = live until explicitly deleted
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Interface mapping
|
|
93
|
+
|
|
94
|
+
| Deep Agents contract | OpenSandbox SDK |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| `execute(command, timeout)` | `SandboxSync.commands.run(command, opts=RunCommandOpts(timeout=...))` |
|
|
97
|
+
| `upload_files([(path, bytes)])` | parent `mkdir -p` via `commands.run`, then per-file `files.write_file(path, data)` |
|
|
98
|
+
| `download_files([paths])` | `files.get_file_info(paths)` for error classification, then per-file `files.read_bytes(path)` |
|
|
99
|
+
| `id` | `SandboxSync.id` |
|
|
100
|
+
| timeout `None` | provider default (30 min per command) |
|
|
101
|
+
| timeout `0` | no deadline (`RunCommandOpts.timeout=None`) |
|
|
102
|
+
| stdout/stderr merge | log messages interleaved chronologically by sandbox timestamp, line boundaries preserved |
|
|
103
|
+
| `provider.get_or_create(sandbox_id=...)` | `SandboxSync.connect(sandbox_id)` |
|
|
104
|
+
| `provider.get_or_create(image=...)` | `SandboxSync.create(image, timeout=...)` |
|
|
105
|
+
| `provider.get_or_create(snapshot=name)` | `SandboxManagerSync.list_snapshots(SnapshotFilter(name=...))` → reuse, else build: `SandboxSync.create(image)` + `create_snapshot(name)` + `destroy()`, then restore via `SandboxSync.create(snapshot_id=...)` |
|
|
106
|
+
| `provider.delete(sandbox_id)` | `SandboxManagerSync.kill_sandbox(sandbox_id)` |
|
|
107
|
+
|
|
108
|
+
All other file operations (`read`, `write`, `edit`, `ls`, `glob`, `grep`, `delete`) are
|
|
109
|
+
derived by `BaseSandbox` from `execute()` and require a POSIX shell plus `python3` in the
|
|
110
|
+
sandbox image (`python:3.12-slim` works as-is).
|
|
111
|
+
|
|
112
|
+
## Tests
|
|
113
|
+
|
|
114
|
+
```bash
|
|
115
|
+
uv sync --group test
|
|
116
|
+
uv run pytest
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Unit tests run fully offline against fakes. To run the official Deep Agents conformance
|
|
120
|
+
suite against a live deployment:
|
|
121
|
+
|
|
122
|
+
```python
|
|
123
|
+
# tests/integration_tests/test_live.py
|
|
124
|
+
from langchain_tests.integration_tests import SandboxIntegrationTests
|
|
125
|
+
from opensandbox import SandboxSync
|
|
126
|
+
|
|
127
|
+
from opensandbox_deepagents import OpenSandboxSandbox
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class TestOpenSandboxStandard(SandboxIntegrationTests):
|
|
131
|
+
@pytest.fixture(scope="class")
|
|
132
|
+
def sandbox(self):
|
|
133
|
+
sandbox = SandboxSync.create("python:3.12-slim", timeout=None)
|
|
134
|
+
try:
|
|
135
|
+
yield OpenSandboxSandbox(sandbox=sandbox)
|
|
136
|
+
finally:
|
|
137
|
+
sandbox.destroy()
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
## Status
|
|
141
|
+
|
|
142
|
+
- Backend: command execution, upload/download with per-file partial success, parent
|
|
143
|
+
directory creation, and the shared error vocabulary (`invalid_path`, `file_not_found`,
|
|
144
|
+
`permission_denied`, `is_directory`).
|
|
145
|
+
- Provider: connect by id, create from image, snapshot-name resolution with build-on-miss,
|
|
146
|
+
delete.
|
|
147
|
+
- Snapshot states: the lifecycle state vocabulary is deployment-specific; the provider
|
|
148
|
+
treats states containing `fail`/`error`/`delet`/`abort` as terminal and defers restore
|
|
149
|
+
readiness to `SandboxSync.create`'s own health checks.
|
|
150
|
+
|
|
151
|
+
## License
|
|
152
|
+
|
|
153
|
+
MIT. Depends on `deepagents` (MIT) and the OpenSandbox Python SDK (Apache-2.0).
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
opensandbox_deepagents/__init__.py,sha256=8DzzWaFH2gbtTkpGgPZQt-Vri9F1Ws2NpPLsCG1Tdl4,1046
|
|
2
|
+
opensandbox_deepagents/provider.py,sha256=NxQ-A4tCfamifMPdymNt1kYt6rg8iz6XjLH85Pw1Jvc,8314
|
|
3
|
+
opensandbox_deepagents/sandbox.py,sha256=EPK-qWqyUE1pkuyn1t4lU8wvt0d4tdOpxtewe38Kiho,11905
|
|
4
|
+
opensandbox_deepagents-0.1.0.dist-info/METADATA,sha256=-ybMlQ1iBsc9evNBCRKUhoM4DSqwDHTzMVRpnIxVj9o,6042
|
|
5
|
+
opensandbox_deepagents-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
6
|
+
opensandbox_deepagents-0.1.0.dist-info/entry_points.txt,sha256=7KZGbOBS8ZOV2Yy270NL2TW0G5CY9BCX0GCWDLW8HC0,102
|
|
7
|
+
opensandbox_deepagents-0.1.0.dist-info/licenses/LICENSE,sha256=1pQ2xZ4CCmPEOvmqdx3kfIIb1tU44kS3niQX1TW2D3E,1092
|
|
8
|
+
opensandbox_deepagents-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 opensandbox-deepagents contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|