opensandbox-deepagents 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.
@@ -0,0 +1,34 @@
1
+ name: tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ runs-on: ubuntu-latest
11
+ strategy:
12
+ fail-fast: false
13
+ matrix:
14
+ python-version: ["3.11", "3.12", "3.13", "3.14"]
15
+ steps:
16
+ - uses: actions/checkout@v4
17
+ - uses: actions/setup-python@v5
18
+ with:
19
+ python-version: ${{ matrix.python-version }}
20
+ - name: Install
21
+ run: |
22
+ python -m pip install --upgrade pip
23
+ pip install -e . pytest pytest-asyncio
24
+ # The dcode provider layer and entry-point tests need deepagents-code,
25
+ # which requires Python >= 3.14.
26
+ if [ "${{ matrix.python-version }}" = "3.14" ]; then
27
+ pip install "deepagents-code>=0.2.9"
28
+ fi
29
+ - name: Run tests
30
+ run: pytest -q
31
+ - name: Lint
32
+ run: |
33
+ pip install "ruff>=0.15,<0.16"
34
+ ruff check opensandbox_deepagents tests
@@ -0,0 +1,11 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ venv/
6
+ dist/
7
+ build/
8
+ .pytest_cache/
9
+ .ruff_cache/
10
+ .coverage
11
+ uv.lock
@@ -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.
@@ -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,129 @@
1
+ # opensandbox-deepagents
2
+
3
+ [OpenSandbox](https://github.com/opensandbox-group/OpenSandbox) sandbox backend and provider for
4
+ [Deep Agents](https://github.com/langchain-ai/deepagents) and [Deep Agents Code](https://github.com/langchain-ai/deepagents) (`dcode`).
5
+
6
+ Run Deep Agents file and shell tooling inside a self-hosted OpenSandbox deployment: the
7
+ `OpenSandboxSandbox` backend implements the `BaseSandbox` contract on top of the official
8
+ OpenSandbox Python SDK, and `OpenSandboxProvider` plugs into `dcode` through its
9
+ `deepagents_code.sandbox_providers` entry-point group — no upstream changes required.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pip install opensandbox-deepagents
15
+
16
+ # with the dcode provider integration (deepagents-code requires Python >= 3.14):
17
+ pip install "opensandbox-deepagents[dcode]"
18
+ ```
19
+
20
+ Environment configuration follows the OpenSandbox SDK: `OPEN_SANDBOX_API_KEY` /
21
+ `OPEN_SANDBOX_DOMAIN` (or a `ConnectionConfigSync` passed to `create`/`connect`),
22
+ same as any `opensandbox` SDK program.
23
+
24
+ ## Use with the Deep Agents SDK
25
+
26
+ ```python
27
+ from opensandbox import SandboxSync
28
+
29
+ from opensandbox_deepagents import OpenSandboxSandbox
30
+
31
+ # Create (or connect with SandboxSync.connect(sandbox_id=...))
32
+ sandbox = SandboxSync.create("python:3.12-slim", timeout=None)
33
+
34
+ backend = OpenSandboxSandbox(sandbox=sandbox)
35
+
36
+ # use as any other Deep Agents backend, e.g.
37
+ # agent = create_deep_agent(model=model, backend=backend)
38
+ result = backend.execute("python3 -c 'print(1 + 1)'")
39
+ print(result.output, result.exit_code)
40
+
41
+ # destroy when done (caller-owned lifecycle)
42
+ sandbox.destroy()
43
+ ```
44
+
45
+ ## Use with Deep Agents Code
46
+
47
+ After `pip install "opensandbox-deepagents[dcode]"` the provider is discovered through the
48
+ `deepagents_code.sandbox_providers` entry-point group:
49
+
50
+ ```bash
51
+ dcode --sandbox opensandbox
52
+
53
+ # connect to an existing sandbox
54
+ dcode --sandbox opensandbox --sandbox-id <id>
55
+
56
+ # restore a named snapshot (built from the image on first use)
57
+ dcode --sandbox opensandbox --snapshot-name my-snapshot
58
+ ```
59
+
60
+ Config-level parameters (`~/.deepagents/config.toml`) are forwarded to the provider:
61
+
62
+ ```toml
63
+ [sandboxes.providers.opensandbox.params]
64
+ image = "python:3.12-slim"
65
+ lifetime_seconds = 3600 # 0 = live until explicitly deleted
66
+ ```
67
+
68
+ ## Interface mapping
69
+
70
+ | Deep Agents contract | OpenSandbox SDK |
71
+ | --- | --- |
72
+ | `execute(command, timeout)` | `SandboxSync.commands.run(command, opts=RunCommandOpts(timeout=...))` |
73
+ | `upload_files([(path, bytes)])` | parent `mkdir -p` via `commands.run`, then per-file `files.write_file(path, data)` |
74
+ | `download_files([paths])` | `files.get_file_info(paths)` for error classification, then per-file `files.read_bytes(path)` |
75
+ | `id` | `SandboxSync.id` |
76
+ | timeout `None` | provider default (30 min per command) |
77
+ | timeout `0` | no deadline (`RunCommandOpts.timeout=None`) |
78
+ | stdout/stderr merge | log messages interleaved chronologically by sandbox timestamp, line boundaries preserved |
79
+ | `provider.get_or_create(sandbox_id=...)` | `SandboxSync.connect(sandbox_id)` |
80
+ | `provider.get_or_create(image=...)` | `SandboxSync.create(image, timeout=...)` |
81
+ | `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=...)` |
82
+ | `provider.delete(sandbox_id)` | `SandboxManagerSync.kill_sandbox(sandbox_id)` |
83
+
84
+ All other file operations (`read`, `write`, `edit`, `ls`, `glob`, `grep`, `delete`) are
85
+ derived by `BaseSandbox` from `execute()` and require a POSIX shell plus `python3` in the
86
+ sandbox image (`python:3.12-slim` works as-is).
87
+
88
+ ## Tests
89
+
90
+ ```bash
91
+ uv sync --group test
92
+ uv run pytest
93
+ ```
94
+
95
+ Unit tests run fully offline against fakes. To run the official Deep Agents conformance
96
+ suite against a live deployment:
97
+
98
+ ```python
99
+ # tests/integration_tests/test_live.py
100
+ from langchain_tests.integration_tests import SandboxIntegrationTests
101
+ from opensandbox import SandboxSync
102
+
103
+ from opensandbox_deepagents import OpenSandboxSandbox
104
+
105
+
106
+ class TestOpenSandboxStandard(SandboxIntegrationTests):
107
+ @pytest.fixture(scope="class")
108
+ def sandbox(self):
109
+ sandbox = SandboxSync.create("python:3.12-slim", timeout=None)
110
+ try:
111
+ yield OpenSandboxSandbox(sandbox=sandbox)
112
+ finally:
113
+ sandbox.destroy()
114
+ ```
115
+
116
+ ## Status
117
+
118
+ - Backend: command execution, upload/download with per-file partial success, parent
119
+ directory creation, and the shared error vocabulary (`invalid_path`, `file_not_found`,
120
+ `permission_denied`, `is_directory`).
121
+ - Provider: connect by id, create from image, snapshot-name resolution with build-on-miss,
122
+ delete.
123
+ - Snapshot states: the lifecycle state vocabulary is deployment-specific; the provider
124
+ treats states containing `fail`/`error`/`delet`/`abort` as terminal and defers restore
125
+ readiness to `SandboxSync.create`'s own health checks.
126
+
127
+ ## License
128
+
129
+ MIT. Depends on `deepagents` (MIT) and the OpenSandbox Python SDK (Apache-2.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"}