sandboxplease 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.
- sandboxplease/__init__.py +139 -0
- sandboxplease/_async_client.py +503 -0
- sandboxplease/_capabilities.py +493 -0
- sandboxplease/_client.py +506 -0
- sandboxplease/_errors.py +246 -0
- sandboxplease/_shared.py +160 -0
- sandboxplease/_types.py +412 -0
- sandboxplease/py.typed +0 -0
- sandboxplease-0.1.0.dist-info/METADATA +228 -0
- sandboxplease-0.1.0.dist-info/RECORD +12 -0
- sandboxplease-0.1.0.dist-info/WHEEL +4 -0
- sandboxplease-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
from ._async_client import AsyncSandbox, AsyncSandboxPlease
|
|
2
|
+
from ._capabilities import (
|
|
3
|
+
CapabilityFact,
|
|
4
|
+
CapabilityGroup,
|
|
5
|
+
CapabilityId,
|
|
6
|
+
CapabilityRequirements,
|
|
7
|
+
CapabilityValues,
|
|
8
|
+
CatalogCapabilities,
|
|
9
|
+
RequireName,
|
|
10
|
+
)
|
|
11
|
+
from ._client import Sandbox, SandboxPlease
|
|
12
|
+
from ._errors import (
|
|
13
|
+
APIConnectionError,
|
|
14
|
+
AuthenticationError,
|
|
15
|
+
CommandError,
|
|
16
|
+
DeviceLimitError,
|
|
17
|
+
FeatureNotLiveError,
|
|
18
|
+
InsufficientCreditsError,
|
|
19
|
+
InvalidRequestError,
|
|
20
|
+
KeyLimitError,
|
|
21
|
+
KeyPolicyError,
|
|
22
|
+
NoEligibleProviderError,
|
|
23
|
+
NotFoundError,
|
|
24
|
+
PermissionDeniedError,
|
|
25
|
+
ProviderError,
|
|
26
|
+
RateLimitError,
|
|
27
|
+
SandboxEndedError,
|
|
28
|
+
SandboxPausedError,
|
|
29
|
+
SandboxPleaseError,
|
|
30
|
+
)
|
|
31
|
+
from ._types import (
|
|
32
|
+
BaseImage,
|
|
33
|
+
BlaxelOptions,
|
|
34
|
+
CatalogDevice,
|
|
35
|
+
CodeSandboxOptions,
|
|
36
|
+
CustomSize,
|
|
37
|
+
DaytonaOptions,
|
|
38
|
+
Device,
|
|
39
|
+
DeviceKind,
|
|
40
|
+
DeviceRequest,
|
|
41
|
+
E2BOptions,
|
|
42
|
+
ExecProviderOptions,
|
|
43
|
+
ExecResult,
|
|
44
|
+
Fallback,
|
|
45
|
+
FallbackReason,
|
|
46
|
+
Feature,
|
|
47
|
+
FileEntry,
|
|
48
|
+
Gpu,
|
|
49
|
+
GpuRequest,
|
|
50
|
+
KeyInfo,
|
|
51
|
+
KillAllResult,
|
|
52
|
+
ModalOptions,
|
|
53
|
+
NetworkAllow,
|
|
54
|
+
NetworkPolicy,
|
|
55
|
+
NorthflankOptions,
|
|
56
|
+
ProviderOptions,
|
|
57
|
+
ProviderPreferences,
|
|
58
|
+
Quote,
|
|
59
|
+
QuoteCandidate,
|
|
60
|
+
QuoteLimit,
|
|
61
|
+
QuoteSkip,
|
|
62
|
+
QuoteUnlock,
|
|
63
|
+
Region,
|
|
64
|
+
SandboxSize,
|
|
65
|
+
Snapshot,
|
|
66
|
+
SpritesOptions,
|
|
67
|
+
VercelOptions,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
__all__ = [
|
|
71
|
+
"CapabilityFact",
|
|
72
|
+
"CapabilityGroup",
|
|
73
|
+
"CapabilityId",
|
|
74
|
+
"CapabilityRequirements",
|
|
75
|
+
"CapabilityValues",
|
|
76
|
+
"CatalogCapabilities",
|
|
77
|
+
"RequireName",
|
|
78
|
+
"CatalogDevice",
|
|
79
|
+
"Device",
|
|
80
|
+
"DeviceKind",
|
|
81
|
+
"DeviceRequest",
|
|
82
|
+
"Gpu",
|
|
83
|
+
"GpuRequest",
|
|
84
|
+
"DeviceLimitError",
|
|
85
|
+
"FeatureNotLiveError",
|
|
86
|
+
"Fallback",
|
|
87
|
+
"FallbackReason",
|
|
88
|
+
"VercelOptions",
|
|
89
|
+
"SpritesOptions",
|
|
90
|
+
"ProviderOptions",
|
|
91
|
+
"NorthflankOptions",
|
|
92
|
+
"ModalOptions",
|
|
93
|
+
"NetworkAllow",
|
|
94
|
+
"NetworkPolicy",
|
|
95
|
+
"ExecProviderOptions",
|
|
96
|
+
"E2BOptions",
|
|
97
|
+
"DaytonaOptions",
|
|
98
|
+
"CodeSandboxOptions",
|
|
99
|
+
"BlaxelOptions",
|
|
100
|
+
"APIConnectionError",
|
|
101
|
+
"AsyncSandboxPlease",
|
|
102
|
+
"AsyncSandbox",
|
|
103
|
+
"AuthenticationError",
|
|
104
|
+
"CommandError",
|
|
105
|
+
"CustomSize",
|
|
106
|
+
"ExecResult",
|
|
107
|
+
"Feature",
|
|
108
|
+
"FileEntry",
|
|
109
|
+
"KillAllResult",
|
|
110
|
+
"InsufficientCreditsError",
|
|
111
|
+
"InvalidRequestError",
|
|
112
|
+
"KeyLimitError",
|
|
113
|
+
"KeyPolicyError",
|
|
114
|
+
"KeyInfo",
|
|
115
|
+
"BaseImage",
|
|
116
|
+
"PermissionDeniedError",
|
|
117
|
+
"SandboxPausedError",
|
|
118
|
+
"NoEligibleProviderError",
|
|
119
|
+
"NotFoundError",
|
|
120
|
+
"ProviderError",
|
|
121
|
+
"ProviderPreferences",
|
|
122
|
+
"Quote",
|
|
123
|
+
"QuoteCandidate",
|
|
124
|
+
"QuoteLimit",
|
|
125
|
+
"QuoteSkip",
|
|
126
|
+
"QuoteUnlock",
|
|
127
|
+
"RateLimitError",
|
|
128
|
+
"Region",
|
|
129
|
+
"SandboxPlease",
|
|
130
|
+
"SandboxPleaseError",
|
|
131
|
+
"Sandbox",
|
|
132
|
+
"SandboxEndedError",
|
|
133
|
+
"SandboxSize",
|
|
134
|
+
"Snapshot",
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
for _name in __all__:
|
|
138
|
+
if isinstance(globals()[_name], type):
|
|
139
|
+
globals()[_name].__module__ = "sandboxplease"
|
|
@@ -0,0 +1,503 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import uuid
|
|
5
|
+
from types import TracebackType
|
|
6
|
+
from typing import Any, cast, overload
|
|
7
|
+
from urllib.parse import quote
|
|
8
|
+
|
|
9
|
+
import httpx
|
|
10
|
+
|
|
11
|
+
from ._errors import surface, surface_async
|
|
12
|
+
from ._shared import (
|
|
13
|
+
USER_AGENT,
|
|
14
|
+
ExecCollector,
|
|
15
|
+
OutputCallback,
|
|
16
|
+
backoff_delay,
|
|
17
|
+
connection_error,
|
|
18
|
+
create_body,
|
|
19
|
+
exec_body,
|
|
20
|
+
raise_for_status,
|
|
21
|
+
resolve_config,
|
|
22
|
+
should_retry,
|
|
23
|
+
)
|
|
24
|
+
from ._types import (
|
|
25
|
+
AnyExecOptions,
|
|
26
|
+
AnyProviderOptions,
|
|
27
|
+
BaseImage,
|
|
28
|
+
Catalog,
|
|
29
|
+
CustomSize,
|
|
30
|
+
Device,
|
|
31
|
+
DeviceRequest,
|
|
32
|
+
ExecResult,
|
|
33
|
+
Fallback,
|
|
34
|
+
FileEntry,
|
|
35
|
+
Gpu,
|
|
36
|
+
GpuRequest,
|
|
37
|
+
KeyInfo,
|
|
38
|
+
KillAllResult,
|
|
39
|
+
NetworkPolicy,
|
|
40
|
+
ProviderPreferences,
|
|
41
|
+
Quote,
|
|
42
|
+
Region,
|
|
43
|
+
SandboxInfo,
|
|
44
|
+
SandboxSize,
|
|
45
|
+
Snapshot,
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _AsyncHttp:
|
|
50
|
+
def __init__(self, client: httpx.AsyncClient, max_retries: int) -> None:
|
|
51
|
+
self.client = client
|
|
52
|
+
self.max_retries = max_retries
|
|
53
|
+
|
|
54
|
+
async def request(self, method: str, path: str, *, retry: bool = False, **kwargs: Any) -> httpx.Response:
|
|
55
|
+
retries = self.max_retries if retry else 0
|
|
56
|
+
attempt = 0
|
|
57
|
+
while True:
|
|
58
|
+
try:
|
|
59
|
+
res = await self.client.request(method, path, **kwargs)
|
|
60
|
+
except httpx.TransportError as e:
|
|
61
|
+
if attempt >= retries:
|
|
62
|
+
raise connection_error(method, path, str(self.client.base_url), e) from e
|
|
63
|
+
await asyncio.sleep(backoff_delay(attempt, None))
|
|
64
|
+
else:
|
|
65
|
+
if not should_retry(res, attempt, retries):
|
|
66
|
+
raise_for_status(res)
|
|
67
|
+
return res
|
|
68
|
+
await asyncio.sleep(backoff_delay(attempt, res.headers.get("retry-after")))
|
|
69
|
+
attempt += 1
|
|
70
|
+
|
|
71
|
+
async def json(self, method: str, path: str, *, retry: bool = False, **kwargs: Any) -> Any:
|
|
72
|
+
return (await self.request(method, path, retry=retry, **kwargs)).json()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class AsyncFiles:
|
|
76
|
+
def __init__(self, http: _AsyncHttp, sandbox_id: str) -> None:
|
|
77
|
+
self._http = http
|
|
78
|
+
self._path = f"/v1/sandboxes/{sandbox_id}/files"
|
|
79
|
+
|
|
80
|
+
@surface_async
|
|
81
|
+
async def write(self, path: str, content: str | bytes) -> None:
|
|
82
|
+
"""Create or overwrite a file; parent directories are created."""
|
|
83
|
+
data = content.encode() if isinstance(content, str) else content
|
|
84
|
+
await self._http.request("PUT", self._path, retry=True, params={"path": path}, content=data)
|
|
85
|
+
|
|
86
|
+
@surface_async
|
|
87
|
+
async def read(self, path: str) -> str:
|
|
88
|
+
return (await self.read_bytes(path)).decode()
|
|
89
|
+
|
|
90
|
+
@surface_async
|
|
91
|
+
async def read_bytes(self, path: str) -> bytes:
|
|
92
|
+
return (await self._http.request("GET", self._path, retry=True, params={"path": path})).content
|
|
93
|
+
|
|
94
|
+
@surface_async
|
|
95
|
+
async def list(self, path: str) -> list[FileEntry]:
|
|
96
|
+
return (await self._http.json("GET", f"{self._path}?path={quote(path)}&list", retry=True))["data"]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
class AsyncPorts:
|
|
100
|
+
def __init__(self, http: _AsyncHttp, sandbox_id: str) -> None:
|
|
101
|
+
self._http = http
|
|
102
|
+
self._path = f"/v1/sandboxes/{sandbox_id}/ports"
|
|
103
|
+
|
|
104
|
+
@surface_async
|
|
105
|
+
async def url(self, port: int) -> str:
|
|
106
|
+
"""Public URL that reaches ``port`` inside the sandbox. Needs a provider with the ``ports`` feature."""
|
|
107
|
+
return (await self._http.json("GET", f"{self._path}/{port}", retry=True))["url"]
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class AsyncSandbox:
|
|
111
|
+
"""A running sandbox. Use it as an async context manager to kill it automatically."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, http: _AsyncHttp, info: SandboxInfo) -> None:
|
|
114
|
+
self._http = http
|
|
115
|
+
self.id: str = info["id"]
|
|
116
|
+
self.info = info
|
|
117
|
+
self.files = AsyncFiles(http, self.id)
|
|
118
|
+
self.ports = AsyncPorts(http, self.id)
|
|
119
|
+
|
|
120
|
+
@property
|
|
121
|
+
def provider(self) -> str:
|
|
122
|
+
"""Provider the router picked, e.g. ``"e2b"``."""
|
|
123
|
+
return self.info["provider"]
|
|
124
|
+
|
|
125
|
+
@property
|
|
126
|
+
def fallback(self) -> Fallback | None:
|
|
127
|
+
"""Set when the first choice did not serve it, e.g. ``{"from": "e2b", "reason": "plan_limit"}``."""
|
|
128
|
+
fallback = self.info.get("fallback")
|
|
129
|
+
return cast(Fallback, fallback) if isinstance(fallback, dict) else None
|
|
130
|
+
|
|
131
|
+
@property
|
|
132
|
+
def devices(self) -> list[Device]:
|
|
133
|
+
"""Mobile devices attached at create, empty when none were asked."""
|
|
134
|
+
return self.info.get("devices") or []
|
|
135
|
+
|
|
136
|
+
@property
|
|
137
|
+
def region(self) -> Region | None:
|
|
138
|
+
"""Region the sandbox runs in: the requested ``provider.region``, else the provider's default."""
|
|
139
|
+
return self.info.get("region")
|
|
140
|
+
|
|
141
|
+
@property
|
|
142
|
+
def size(self) -> SandboxSize:
|
|
143
|
+
return self.info["size"]
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def gpu(self) -> Gpu | None:
|
|
147
|
+
"""GPUs attached at create, ``None`` without."""
|
|
148
|
+
return self.info.get("gpu")
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def price_per_hour(self) -> float:
|
|
152
|
+
"""List price in USD per hour, billed per second, GPUs included."""
|
|
153
|
+
return self.info["price_per_hour"]
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def device_price_per_minute(self) -> float:
|
|
157
|
+
"""USD per started minute for the attached devices together, 0 without devices."""
|
|
158
|
+
return self.info.get("device_price_per_minute") or 0.0
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def cold_start_ms(self) -> int:
|
|
162
|
+
"""Milliseconds from the create request to a sandbox ready to exec."""
|
|
163
|
+
return self.info["cold_start_ms"]
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def provider_sandbox_id(self) -> str:
|
|
167
|
+
"""The sandbox's id at its provider: pass it to the vendor's SDK for features SandboxPlease does not route."""
|
|
168
|
+
return self.info["provider_sandbox_id"]
|
|
169
|
+
|
|
170
|
+
@property
|
|
171
|
+
def provider_metadata(self) -> dict[str, Any]:
|
|
172
|
+
"""Non-secret fields of the provider's create response, e.g. E2B's ``sandboxID`` and ``domain``."""
|
|
173
|
+
return self.info["provider_metadata"]
|
|
174
|
+
|
|
175
|
+
@property
|
|
176
|
+
def status(self) -> str:
|
|
177
|
+
return self.info["status"]
|
|
178
|
+
|
|
179
|
+
@property
|
|
180
|
+
def from_snapshot(self) -> str | None:
|
|
181
|
+
"""Id of the snapshot the sandbox started from, ``None`` otherwise."""
|
|
182
|
+
return self.info.get("from_snapshot")
|
|
183
|
+
|
|
184
|
+
@property
|
|
185
|
+
def network(self) -> NetworkPolicy:
|
|
186
|
+
"""The network policy the provider enforces, ``"allow-all"`` unless the create locked it down."""
|
|
187
|
+
return self.info.get("network") or "allow-all"
|
|
188
|
+
|
|
189
|
+
@property
|
|
190
|
+
def idle_timeout(self) -> int | None:
|
|
191
|
+
"""Seconds without a call before the sandbox is killed, ``None`` when off."""
|
|
192
|
+
return self.info.get("idle_timeout")
|
|
193
|
+
|
|
194
|
+
@property
|
|
195
|
+
def cost(self) -> float:
|
|
196
|
+
"""USD billed so far, devices included."""
|
|
197
|
+
return self.info.get("cost") or 0.0
|
|
198
|
+
|
|
199
|
+
@property
|
|
200
|
+
def expires_at(self) -> str:
|
|
201
|
+
return self.info["expires_at"]
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def end_reason(self) -> str | None:
|
|
205
|
+
"""Why the sandbox ended (``killed``, ``lifetime_limit``, ``idle``...), ``None`` while it runs."""
|
|
206
|
+
return self.info.get("end_reason")
|
|
207
|
+
|
|
208
|
+
@surface_async
|
|
209
|
+
async def exec(
|
|
210
|
+
self,
|
|
211
|
+
cmd: str,
|
|
212
|
+
*,
|
|
213
|
+
cwd: str | None = None,
|
|
214
|
+
env: dict[str, str] | None = None,
|
|
215
|
+
timeout: int | None = None,
|
|
216
|
+
exec_options: AnyExecOptions | None = None,
|
|
217
|
+
check: bool = False,
|
|
218
|
+
on_stdout: OutputCallback | None = None,
|
|
219
|
+
on_stderr: OutputCallback | None = None,
|
|
220
|
+
) -> ExecResult:
|
|
221
|
+
"""Run a shell command and wait for it to finish.
|
|
222
|
+
|
|
223
|
+
``timeout`` is in seconds. ``on_stdout``/``on_stderr`` receive output as it streams.
|
|
224
|
+
``exec_options`` passes native command fields, e.g. ``{"vercel": {"sudo": True}}``.
|
|
225
|
+
With ``check=True`` a non-zero exit raises ``CommandError``.
|
|
226
|
+
|
|
227
|
+
>>> (await sbx.exec("python3 -c 'print(1 + 1)'", check=True)).stdout
|
|
228
|
+
'2\\n'
|
|
229
|
+
"""
|
|
230
|
+
collector = ExecCollector(on_stdout, on_stderr)
|
|
231
|
+
body = exec_body(cmd, cwd, env, timeout, exec_options)
|
|
232
|
+
path = f"/v1/sandboxes/{self.id}/exec"
|
|
233
|
+
try:
|
|
234
|
+
async with self._http.client.stream("POST", path, json=body, timeout=None) as res:
|
|
235
|
+
if not res.is_success:
|
|
236
|
+
await res.aread()
|
|
237
|
+
raise_for_status(res)
|
|
238
|
+
async for line in res.aiter_lines():
|
|
239
|
+
collector.feed(line)
|
|
240
|
+
except httpx.TransportError as e:
|
|
241
|
+
raise connection_error("POST", path, str(self._http.client.base_url), e) from e
|
|
242
|
+
return collector.result(cmd, check)
|
|
243
|
+
|
|
244
|
+
@surface_async
|
|
245
|
+
async def pause(self) -> None:
|
|
246
|
+
"""Pause billing and freeze the sandbox. Needs a provider with the ``pause`` feature. Mobile devices cannot
|
|
247
|
+
keep their state: a pause releases them and ``resume()`` boots new ones of the same kinds."""
|
|
248
|
+
self.info = await self._http.json("POST", f"/v1/sandboxes/{self.id}/pause")
|
|
249
|
+
|
|
250
|
+
@surface_async
|
|
251
|
+
async def resume(self) -> None:
|
|
252
|
+
self.info = await self._http.json("POST", f"/v1/sandboxes/{self.id}/resume")
|
|
253
|
+
|
|
254
|
+
@surface_async
|
|
255
|
+
async def snapshot(self) -> Snapshot:
|
|
256
|
+
"""Copy the sandbox, which keeps running, to start new sandboxes from with ``create(from_snapshot=...)``.
|
|
257
|
+
|
|
258
|
+
Needs a provider with the ``fork`` or ``snapshot`` feature. The snapshot expires after 7 days.
|
|
259
|
+
"""
|
|
260
|
+
return await self._http.json("POST", f"/v1/sandboxes/{self.id}/snapshot")
|
|
261
|
+
|
|
262
|
+
@surface_async
|
|
263
|
+
async def kill(self) -> None:
|
|
264
|
+
"""Stop the sandbox and its billing. Safe to call twice."""
|
|
265
|
+
self.info = await self._http.json("DELETE", f"/v1/sandboxes/{self.id}", retry=True)
|
|
266
|
+
|
|
267
|
+
async def __aenter__(self) -> AsyncSandbox:
|
|
268
|
+
return self
|
|
269
|
+
|
|
270
|
+
async def __aexit__(self, *_: object) -> None:
|
|
271
|
+
if self.status != "killed":
|
|
272
|
+
await self.kill()
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
class AsyncSandboxes:
|
|
276
|
+
def __init__(self, http: _AsyncHttp) -> None:
|
|
277
|
+
self._http = http
|
|
278
|
+
|
|
279
|
+
@overload
|
|
280
|
+
async def create(
|
|
281
|
+
self,
|
|
282
|
+
sandbox: str = "auto",
|
|
283
|
+
*,
|
|
284
|
+
size: str | CustomSize | None = None,
|
|
285
|
+
provider: ProviderPreferences | None = None,
|
|
286
|
+
timeout: int | None = None,
|
|
287
|
+
idle_timeout: int | None = None,
|
|
288
|
+
template: str | None = None,
|
|
289
|
+
env: dict[str, str] | None = None,
|
|
290
|
+
provider_options: AnyProviderOptions | None = None,
|
|
291
|
+
devices: list[DeviceRequest] | None = None,
|
|
292
|
+
gpu: GpuRequest | None = None,
|
|
293
|
+
network: NetworkPolicy | None = None,
|
|
294
|
+
from_snapshot: str | None = None,
|
|
295
|
+
count: None = None,
|
|
296
|
+
) -> AsyncSandbox: ...
|
|
297
|
+
|
|
298
|
+
@overload
|
|
299
|
+
async def create(
|
|
300
|
+
self,
|
|
301
|
+
sandbox: str = "auto",
|
|
302
|
+
*,
|
|
303
|
+
size: str | CustomSize | None = None,
|
|
304
|
+
provider: ProviderPreferences | None = None,
|
|
305
|
+
timeout: int | None = None,
|
|
306
|
+
idle_timeout: int | None = None,
|
|
307
|
+
template: str | None = None,
|
|
308
|
+
env: dict[str, str] | None = None,
|
|
309
|
+
provider_options: AnyProviderOptions | None = None,
|
|
310
|
+
devices: list[DeviceRequest] | None = None,
|
|
311
|
+
gpu: GpuRequest | None = None,
|
|
312
|
+
network: NetworkPolicy | None = None,
|
|
313
|
+
from_snapshot: str | None = None,
|
|
314
|
+
count: int,
|
|
315
|
+
) -> list[AsyncSandbox]: ...
|
|
316
|
+
|
|
317
|
+
@surface_async
|
|
318
|
+
async def create(
|
|
319
|
+
self,
|
|
320
|
+
sandbox: str = "auto",
|
|
321
|
+
*,
|
|
322
|
+
size: str | CustomSize | None = None,
|
|
323
|
+
provider: ProviderPreferences | None = None,
|
|
324
|
+
timeout: int | None = None,
|
|
325
|
+
idle_timeout: int | None = None,
|
|
326
|
+
template: str | None = None,
|
|
327
|
+
env: dict[str, str] | None = None,
|
|
328
|
+
provider_options: AnyProviderOptions | None = None,
|
|
329
|
+
devices: list[DeviceRequest] | None = None,
|
|
330
|
+
gpu: GpuRequest | None = None,
|
|
331
|
+
network: NetworkPolicy | None = None,
|
|
332
|
+
from_snapshot: str | None = None,
|
|
333
|
+
count: int | None = None,
|
|
334
|
+
) -> AsyncSandbox | list[AsyncSandbox]:
|
|
335
|
+
"""Start a sandbox on the best provider for the request.
|
|
336
|
+
|
|
337
|
+
``sandbox`` is ``"auto"``, a provider (``"e2b"``) or a provider and size (``"e2b/large"``);
|
|
338
|
+
``timeout`` is the lifetime in seconds; ``idle_timeout`` kills it after that many seconds without a call on
|
|
339
|
+
it (a command counts until it ends). ``provider_options`` passes native create fields per
|
|
340
|
+
provider, e.g. ``{"e2b": {"metadata": {"team": "ml"}}}``; only the picked provider's entry is sent.
|
|
341
|
+
``devices`` attaches cloud mobile devices, e.g. ``[{"kind": "android_phone"}]``, driven from inside the
|
|
342
|
+
sandbox with miniSandbox's device tool: at most 3 per sandbox (more raises ``InvalidRequestError``) and 10
|
|
343
|
+
attached at once per workspace (more raises ``DeviceLimitError``); contact support for more. Only
|
|
344
|
+
miniSandbox sandboxes take devices: the sandbox runs on ``minisandbox``, and naming another provider raises
|
|
345
|
+
``InvalidRequestError``. Private beta: raises
|
|
346
|
+
``FeatureNotLiveError`` until your account is in.
|
|
347
|
+
``gpu`` attaches GPUs, e.g. ``{"type": "H100", "count": 2}``: the sandbox runs on the cheapest provider
|
|
348
|
+
offering them, billed on credits at its list price per GPU-hour (offers: ``catalog()`` ``gpus``).
|
|
349
|
+
``network`` locks the sandbox's network down: ``"deny-all"`` or ``{"allow": ["pypi.org", "*.github.com"]}``;
|
|
350
|
+
only providers that enforce it are used.
|
|
351
|
+
``from_snapshot`` starts from a snapshot taken with ``sandbox.snapshot()``, on its provider, size and region.
|
|
352
|
+
``count`` starts that many sandboxes (1 to 20) and returns them as a list: all of them, or none.
|
|
353
|
+
Retries are safe: each call carries an idempotency key, so a retried request never starts a
|
|
354
|
+
second sandbox.
|
|
355
|
+
"""
|
|
356
|
+
body = create_body(
|
|
357
|
+
sandbox,
|
|
358
|
+
size,
|
|
359
|
+
provider,
|
|
360
|
+
timeout,
|
|
361
|
+
template,
|
|
362
|
+
env,
|
|
363
|
+
provider_options,
|
|
364
|
+
devices,
|
|
365
|
+
network,
|
|
366
|
+
from_snapshot,
|
|
367
|
+
count,
|
|
368
|
+
gpu,
|
|
369
|
+
idle_timeout,
|
|
370
|
+
)
|
|
371
|
+
headers = {"idempotency-key": str(uuid.uuid4())}
|
|
372
|
+
created = await self._http.json("POST", "/v1/sandboxes", retry=True, json=body, headers=headers)
|
|
373
|
+
if count is None:
|
|
374
|
+
return AsyncSandbox(self._http, created)
|
|
375
|
+
return [AsyncSandbox(self._http, info) for info in cast(list[SandboxInfo], created["data"])]
|
|
376
|
+
|
|
377
|
+
@surface_async
|
|
378
|
+
async def get(self, sandbox_id: str) -> AsyncSandbox:
|
|
379
|
+
return AsyncSandbox(self._http, await self._http.json("GET", f"/v1/sandboxes/{sandbox_id}", retry=True))
|
|
380
|
+
|
|
381
|
+
@surface_async
|
|
382
|
+
async def list(self) -> list[AsyncSandbox]:
|
|
383
|
+
"""Sandboxes of this account that are still running or paused."""
|
|
384
|
+
data = cast(list[SandboxInfo], (await self._http.json("GET", "/v1/sandboxes", retry=True))["data"])
|
|
385
|
+
return [AsyncSandbox(self._http, info) for info in data]
|
|
386
|
+
|
|
387
|
+
@surface_async
|
|
388
|
+
async def kill_all(
|
|
389
|
+
self, *, provider: str | None = None, key: str | None = None, older_than_hours: int | None = None
|
|
390
|
+
) -> KillAllResult:
|
|
391
|
+
"""Kill every running or paused sandbox this key reaches, in one call: for when your agent lost track of
|
|
392
|
+
its sandboxes. ``provider``, ``key`` (an API key id) or ``older_than_hours`` (1 to 24: only sandboxes started
|
|
393
|
+
that long ago) narrow it down."""
|
|
394
|
+
params = {"provider": provider, "key": key, "older_than_hours": older_than_hours}
|
|
395
|
+
body = {k: v for k, v in params.items() if v is not None}
|
|
396
|
+
return cast(KillAllResult, await self._http.json("POST", "/v1/sandboxes/kill-all", retry=True, json=body))
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
class AsyncSnapshots:
|
|
400
|
+
def __init__(self, http: _AsyncHttp) -> None:
|
|
401
|
+
self._http = http
|
|
402
|
+
|
|
403
|
+
@surface_async
|
|
404
|
+
async def get(self, snapshot_id: str) -> Snapshot:
|
|
405
|
+
return await self._http.json("GET", f"/v1/snapshots/{snapshot_id}", retry=True)
|
|
406
|
+
|
|
407
|
+
@surface_async
|
|
408
|
+
async def delete(self, snapshot_id: str) -> Snapshot:
|
|
409
|
+
"""Delete the snapshot and bill its storage. Safe to call twice."""
|
|
410
|
+
return await self._http.json("DELETE", f"/v1/snapshots/{snapshot_id}", retry=True)
|
|
411
|
+
|
|
412
|
+
@surface_async
|
|
413
|
+
async def list(self) -> list[Snapshot]:
|
|
414
|
+
"""Snapshots of this account that are ready to start sandboxes from."""
|
|
415
|
+
return (await self._http.json("GET", "/v1/snapshots", retry=True))["data"]
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
class AsyncSandboxPlease:
|
|
419
|
+
"""Async SandboxPlease client. With ``SANDBOXPLEASE_API_KEY`` set, ``AsyncSandboxPlease()`` needs no arguments.
|
|
420
|
+
|
|
421
|
+
``base_url`` defaults to ``SANDBOXPLEASE_BASE_URL``, then https://api.sandboxplease.com. ``timeout`` is in
|
|
422
|
+
seconds per request; safe requests retry ``max_retries`` times on 429, 5xx and network errors.
|
|
423
|
+
"""
|
|
424
|
+
|
|
425
|
+
@surface
|
|
426
|
+
def __init__(
|
|
427
|
+
self,
|
|
428
|
+
api_key: str | None = None,
|
|
429
|
+
*,
|
|
430
|
+
base_url: str | None = None,
|
|
431
|
+
timeout: float = 60.0,
|
|
432
|
+
max_retries: int = 2,
|
|
433
|
+
) -> None:
|
|
434
|
+
key, url = resolve_config(api_key, base_url)
|
|
435
|
+
self._client = httpx.AsyncClient(
|
|
436
|
+
base_url=url, headers={"authorization": f"Bearer {key}", "user-agent": USER_AGENT}, timeout=timeout
|
|
437
|
+
)
|
|
438
|
+
self._http = _AsyncHttp(self._client, max_retries)
|
|
439
|
+
self.sandboxes = AsyncSandboxes(self._http)
|
|
440
|
+
self.snapshots = AsyncSnapshots(self._http)
|
|
441
|
+
|
|
442
|
+
@surface_async
|
|
443
|
+
async def quote(
|
|
444
|
+
self,
|
|
445
|
+
sandbox: str = "auto",
|
|
446
|
+
*,
|
|
447
|
+
size: str | CustomSize | None = None,
|
|
448
|
+
provider: ProviderPreferences | None = None,
|
|
449
|
+
timeout: int | None = None,
|
|
450
|
+
idle_timeout: int | None = None,
|
|
451
|
+
template: str | None = None,
|
|
452
|
+
provider_options: AnyProviderOptions | None = None,
|
|
453
|
+
devices: list[DeviceRequest] | None = None,
|
|
454
|
+
gpu: GpuRequest | None = None,
|
|
455
|
+
network: NetworkPolicy | None = None,
|
|
456
|
+
duration: int | None = None,
|
|
457
|
+
) -> Quote:
|
|
458
|
+
"""What ``sandboxes.create()`` with the same arguments would run and cost, without starting anything.
|
|
459
|
+
|
|
460
|
+
Same as ``SandboxPlease.quote``.
|
|
461
|
+
"""
|
|
462
|
+
body = create_body(
|
|
463
|
+
sandbox,
|
|
464
|
+
size,
|
|
465
|
+
provider,
|
|
466
|
+
timeout,
|
|
467
|
+
template,
|
|
468
|
+
None,
|
|
469
|
+
provider_options,
|
|
470
|
+
devices,
|
|
471
|
+
network,
|
|
472
|
+
gpu=gpu,
|
|
473
|
+
idle_timeout=idle_timeout,
|
|
474
|
+
)
|
|
475
|
+
if duration is not None:
|
|
476
|
+
body["duration"] = duration
|
|
477
|
+
return await self._http.json("POST", "/v1/quote", retry=True, json=body)
|
|
478
|
+
|
|
479
|
+
@surface_async
|
|
480
|
+
async def catalog(self) -> Catalog:
|
|
481
|
+
"""Every provider with its sizes, prices, features and live latency."""
|
|
482
|
+
return await self._http.json("GET", "/v1/catalog", retry=True)
|
|
483
|
+
|
|
484
|
+
@surface_async
|
|
485
|
+
async def key(self) -> KeyInfo:
|
|
486
|
+
"""This key's account balance and what is left of its credit limit this period. Check it before a long job."""
|
|
487
|
+
return await self._http.json("GET", "/v1/key", retry=True)
|
|
488
|
+
|
|
489
|
+
@surface_async
|
|
490
|
+
async def base_image(self) -> BaseImage:
|
|
491
|
+
"""``sandboxplease/base`` on every provider: how it gets there, whether it runs there now, its last verify."""
|
|
492
|
+
return await self._http.json("GET", "/v1/catalog/base-image", retry=True)
|
|
493
|
+
|
|
494
|
+
async def close(self) -> None:
|
|
495
|
+
await self._client.aclose()
|
|
496
|
+
|
|
497
|
+
async def __aenter__(self) -> AsyncSandboxPlease:
|
|
498
|
+
return self
|
|
499
|
+
|
|
500
|
+
async def __aexit__(
|
|
501
|
+
self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None
|
|
502
|
+
) -> None:
|
|
503
|
+
await self.close()
|