spawnbox-sdk 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.
spawnbox/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from .client import (
|
|
2
|
+
AsyncCodeInterpreter,
|
|
3
|
+
AsyncSandbox,
|
|
4
|
+
AsyncSandboxBrowser,
|
|
5
|
+
AsyncSpawnboxClient,
|
|
6
|
+
CodeInterpreter,
|
|
7
|
+
Sandbox,
|
|
8
|
+
SandboxBrowser,
|
|
9
|
+
SpawnboxClient,
|
|
10
|
+
SpawnboxError,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"AsyncCodeInterpreter",
|
|
15
|
+
"AsyncSandbox",
|
|
16
|
+
"AsyncSandboxBrowser",
|
|
17
|
+
"AsyncSpawnboxClient",
|
|
18
|
+
"CodeInterpreter",
|
|
19
|
+
"Sandbox",
|
|
20
|
+
"SandboxBrowser",
|
|
21
|
+
"SpawnboxClient",
|
|
22
|
+
"SpawnboxError",
|
|
23
|
+
]
|
spawnbox/client.py
ADDED
|
@@ -0,0 +1,980 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
import time
|
|
6
|
+
import urllib.error
|
|
7
|
+
import urllib.parse
|
|
8
|
+
import urllib.request
|
|
9
|
+
from collections.abc import AsyncIterator, Iterator
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class SpawnboxError(Exception):
|
|
14
|
+
def __init__(self, status: int, body: str, message: str | None = None) -> None:
|
|
15
|
+
super().__init__(message or f"Spawnbox API error ({status}): {body}")
|
|
16
|
+
self.status = status
|
|
17
|
+
self.body = body
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class CodeInterpreter:
|
|
21
|
+
def __init__(self, sandbox: Sandbox, port: int = 8888) -> None:
|
|
22
|
+
self._sandbox = sandbox
|
|
23
|
+
self._port = port
|
|
24
|
+
|
|
25
|
+
def run_code(
|
|
26
|
+
self, code: str, *, context_id: str = "default", timeout_s: float = 30.0
|
|
27
|
+
) -> dict[str, Any]:
|
|
28
|
+
payload = json.dumps(
|
|
29
|
+
{"code": code, "context_id": context_id, "timeout_s": timeout_s}
|
|
30
|
+
)
|
|
31
|
+
res = self._sandbox.exec(
|
|
32
|
+
f"curl -sfS -X POST http://127.0.0.1:{self._port}/exec -H 'Content-Type: application/json' --data-binary @-",
|
|
33
|
+
stdin=payload,
|
|
34
|
+
timeout_s=int(timeout_s) + 15,
|
|
35
|
+
)
|
|
36
|
+
if res.get("exit_code", 1) != 0:
|
|
37
|
+
raise RuntimeError(
|
|
38
|
+
f"code-interpreter failed (exit {res.get('exit_code')}): {res.get('stderr', '')}"
|
|
39
|
+
)
|
|
40
|
+
return json.loads(res.get("stdout", "{}"))
|
|
41
|
+
|
|
42
|
+
def interrupt(self, *, context_id: str = "default") -> dict[str, Any]:
|
|
43
|
+
res = self._sandbox.exec(
|
|
44
|
+
f"curl -sfS -X POST http://127.0.0.1:{self._port}/interrupt -H 'Content-Type: application/json' --data-binary @-",
|
|
45
|
+
stdin=json.dumps({"context_id": context_id}),
|
|
46
|
+
)
|
|
47
|
+
return json.loads(res.get("stdout", "{}"))
|
|
48
|
+
|
|
49
|
+
def restart(self, *, context_id: str = "default") -> dict[str, Any]:
|
|
50
|
+
res = self._sandbox.exec(
|
|
51
|
+
f"curl -sfS -X POST http://127.0.0.1:{self._port}/restart -H 'Content-Type: application/json' --data-binary @-",
|
|
52
|
+
stdin=json.dumps({"context_id": context_id}),
|
|
53
|
+
)
|
|
54
|
+
return json.loads(res.get("stdout", "{}"))
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
class SandboxBrowser:
|
|
58
|
+
def __init__(
|
|
59
|
+
self,
|
|
60
|
+
sandbox: Sandbox,
|
|
61
|
+
*,
|
|
62
|
+
cdp_port: int = 9222,
|
|
63
|
+
vnc_port: int = 6080,
|
|
64
|
+
api_port: int = 6081,
|
|
65
|
+
) -> None:
|
|
66
|
+
self._sandbox = sandbox
|
|
67
|
+
self._cdp_port = cdp_port
|
|
68
|
+
self._vnc_port = vnc_port
|
|
69
|
+
self._api_port = api_port
|
|
70
|
+
|
|
71
|
+
def cdp_url(self, *, access: str = "token") -> dict[str, Any]:
|
|
72
|
+
published = self._sandbox.publish_port(self._cdp_port, access=access)
|
|
73
|
+
url = str(published.get("url", ""))
|
|
74
|
+
if url.startswith("https://"):
|
|
75
|
+
ws_url = "wss://" + url[len("https://") :]
|
|
76
|
+
elif url.startswith("http://"):
|
|
77
|
+
ws_url = "ws://" + url[len("http://") :]
|
|
78
|
+
else:
|
|
79
|
+
ws_url = url
|
|
80
|
+
return {**published, "ws_url": ws_url}
|
|
81
|
+
|
|
82
|
+
def live_view_url(self, *, access: str = "token") -> dict[str, Any]:
|
|
83
|
+
return self._sandbox.publish_port(self._vnc_port, access=access)
|
|
84
|
+
|
|
85
|
+
def screenshot(self) -> dict[str, Any]:
|
|
86
|
+
res = self._sandbox.exec(
|
|
87
|
+
f"curl -sfS http://127.0.0.1:{self._api_port}/screenshot"
|
|
88
|
+
)
|
|
89
|
+
return json.loads(res.get("stdout", "{}"))
|
|
90
|
+
|
|
91
|
+
def _post_action(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
|
|
92
|
+
res = self._sandbox.exec(
|
|
93
|
+
f"curl -sfS -X POST http://127.0.0.1:{self._api_port}{path} -H 'Content-Type: application/json' --data-binary @-",
|
|
94
|
+
stdin=json.dumps(body),
|
|
95
|
+
)
|
|
96
|
+
return json.loads(res.get("stdout", "{}"))
|
|
97
|
+
|
|
98
|
+
def click(self, x: int, y: int, *, button: int = 1) -> dict[str, Any]:
|
|
99
|
+
return self._post_action("/click", {"x": x, "y": y, "button": button})
|
|
100
|
+
|
|
101
|
+
def double_click(self, x: int, y: int) -> dict[str, Any]:
|
|
102
|
+
return self._post_action("/double_click", {"x": x, "y": y})
|
|
103
|
+
|
|
104
|
+
def move(self, x: int, y: int) -> dict[str, Any]:
|
|
105
|
+
return self._post_action("/move", {"x": x, "y": y})
|
|
106
|
+
|
|
107
|
+
def type(self, text: str, *, delay_ms: int = 12) -> dict[str, Any]:
|
|
108
|
+
return self._post_action("/type", {"text": text, "delay_ms": delay_ms})
|
|
109
|
+
|
|
110
|
+
def key(self, key: str) -> dict[str, Any]:
|
|
111
|
+
return self._post_action("/key", {"key": key})
|
|
112
|
+
|
|
113
|
+
def scroll(self, delta_y: int) -> dict[str, Any]:
|
|
114
|
+
return self._post_action("/scroll", {"delta_y": delta_y})
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class Sandbox:
|
|
118
|
+
def __init__(self, client: SpawnboxClient, info: dict[str, Any]) -> None:
|
|
119
|
+
self._client = client
|
|
120
|
+
self.info = info
|
|
121
|
+
self.id: str = str(info["id"])
|
|
122
|
+
|
|
123
|
+
def __enter__(self) -> Sandbox:
|
|
124
|
+
return self
|
|
125
|
+
|
|
126
|
+
def __exit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
127
|
+
self.delete()
|
|
128
|
+
|
|
129
|
+
def exec(
|
|
130
|
+
self,
|
|
131
|
+
cmd: str,
|
|
132
|
+
*,
|
|
133
|
+
cwd: str | None = None,
|
|
134
|
+
env: dict[str, str] | None = None,
|
|
135
|
+
user: str | None = None,
|
|
136
|
+
timeout_s: int | None = None,
|
|
137
|
+
stdin: str | None = None,
|
|
138
|
+
no_new_privs: bool | None = None,
|
|
139
|
+
) -> dict[str, Any]:
|
|
140
|
+
payload: dict[str, Any] = {"cmd": cmd}
|
|
141
|
+
if cwd is not None:
|
|
142
|
+
payload["cwd"] = cwd
|
|
143
|
+
if env is not None:
|
|
144
|
+
payload["env"] = env
|
|
145
|
+
if user is not None:
|
|
146
|
+
payload["user"] = user
|
|
147
|
+
if timeout_s is not None:
|
|
148
|
+
payload["timeout_s"] = timeout_s
|
|
149
|
+
if stdin is not None:
|
|
150
|
+
payload["stdin"] = stdin
|
|
151
|
+
if no_new_privs is not None:
|
|
152
|
+
payload["no_new_privs"] = no_new_privs
|
|
153
|
+
return self._client.exec(self.id, payload)
|
|
154
|
+
|
|
155
|
+
def exec_stream(
|
|
156
|
+
self,
|
|
157
|
+
cmd: str,
|
|
158
|
+
*,
|
|
159
|
+
cwd: str | None = None,
|
|
160
|
+
env: dict[str, str] | None = None,
|
|
161
|
+
user: str | None = None,
|
|
162
|
+
timeout_s: int | None = None,
|
|
163
|
+
stdin: str | None = None,
|
|
164
|
+
no_new_privs: bool | None = None,
|
|
165
|
+
) -> Iterator[dict[str, Any]]:
|
|
166
|
+
payload: dict[str, Any] = {"cmd": cmd}
|
|
167
|
+
if cwd is not None:
|
|
168
|
+
payload["cwd"] = cwd
|
|
169
|
+
if env is not None:
|
|
170
|
+
payload["env"] = env
|
|
171
|
+
if user is not None:
|
|
172
|
+
payload["user"] = user
|
|
173
|
+
if timeout_s is not None:
|
|
174
|
+
payload["timeout_s"] = timeout_s
|
|
175
|
+
if stdin is not None:
|
|
176
|
+
payload["stdin"] = stdin
|
|
177
|
+
if no_new_privs is not None:
|
|
178
|
+
payload["no_new_privs"] = no_new_privs
|
|
179
|
+
return self._client.exec_stream(self.id, payload)
|
|
180
|
+
|
|
181
|
+
def code_interpreter(self, *, port: int = 8888) -> CodeInterpreter:
|
|
182
|
+
return CodeInterpreter(self, port=port)
|
|
183
|
+
|
|
184
|
+
def browser(
|
|
185
|
+
self,
|
|
186
|
+
*,
|
|
187
|
+
cdp_port: int = 9222,
|
|
188
|
+
vnc_port: int = 6080,
|
|
189
|
+
api_port: int = 6081,
|
|
190
|
+
) -> SandboxBrowser:
|
|
191
|
+
return SandboxBrowser(
|
|
192
|
+
self, cdp_port=cdp_port, vnc_port=vnc_port, api_port=api_port
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def read_file(self, path: str) -> bytes:
|
|
196
|
+
return self._client.read_file(self.id, path)
|
|
197
|
+
|
|
198
|
+
def read_text_file(self, path: str, encoding: str = "utf-8") -> str:
|
|
199
|
+
return self.read_file(path).decode(encoding)
|
|
200
|
+
|
|
201
|
+
def write_file(self, path: str, content: str | bytes) -> None:
|
|
202
|
+
self._client.write_file(self.id, path, content)
|
|
203
|
+
|
|
204
|
+
def list_files(self, path: str) -> Any:
|
|
205
|
+
return self._client.list_files(self.id, path)
|
|
206
|
+
|
|
207
|
+
def delete_file(self, path: str) -> None:
|
|
208
|
+
self._client.delete_file(self.id, path)
|
|
209
|
+
|
|
210
|
+
def upload_archive(
|
|
211
|
+
self, path: str, tar_zst: bytes, *, user: str | None = None
|
|
212
|
+
) -> dict[str, Any]:
|
|
213
|
+
return self._client.upload_archive(self.id, path, tar_zst, user=user)
|
|
214
|
+
|
|
215
|
+
def download_archive(self, path: str, *, user: str | None = None) -> bytes:
|
|
216
|
+
return self._client.download_archive(self.id, path, user=user)
|
|
217
|
+
|
|
218
|
+
def fork(self, *, count: int | None = None) -> dict[str, Any]:
|
|
219
|
+
return self._client.fork_sandbox(self.id, count=count)
|
|
220
|
+
|
|
221
|
+
def snapshot(self, name: str) -> dict[str, Any]:
|
|
222
|
+
return self._client.snapshot_sandbox(self.id, name)
|
|
223
|
+
|
|
224
|
+
def pause(self) -> dict[str, Any]:
|
|
225
|
+
return self._client.pause_sandbox(self.id)
|
|
226
|
+
|
|
227
|
+
def resume(self) -> dict[str, Any]:
|
|
228
|
+
return self._client.resume_sandbox(self.id)
|
|
229
|
+
|
|
230
|
+
def publish_port(
|
|
231
|
+
self, port: int, *, access: str | None = None
|
|
232
|
+
) -> dict[str, Any]:
|
|
233
|
+
return self._client.publish_port(self.id, port, access=access)
|
|
234
|
+
|
|
235
|
+
def list_ports(self) -> dict[str, Any]:
|
|
236
|
+
return self._client.list_ports(self.id)
|
|
237
|
+
|
|
238
|
+
def unpublish_port(self, port: int) -> bool:
|
|
239
|
+
return self._client.unpublish_port(self.id, port)
|
|
240
|
+
|
|
241
|
+
def port_ready(self, port: int, *, wait_s: int | None = None) -> bool:
|
|
242
|
+
return self._client.port_ready(self.id, port, wait_s=wait_s)
|
|
243
|
+
|
|
244
|
+
def list_services(self) -> dict[str, Any]:
|
|
245
|
+
return self._client.list_services(self.id)
|
|
246
|
+
|
|
247
|
+
def restart_service(self, name: str) -> None:
|
|
248
|
+
self._client.restart_service(self.id, name)
|
|
249
|
+
|
|
250
|
+
def service_logs(self, name: str) -> str:
|
|
251
|
+
return self._client.service_logs(self.id, name)
|
|
252
|
+
|
|
253
|
+
def git_clone(
|
|
254
|
+
self,
|
|
255
|
+
url: str,
|
|
256
|
+
*,
|
|
257
|
+
path: str | None = None,
|
|
258
|
+
branch: str | None = None,
|
|
259
|
+
depth: int | None = None,
|
|
260
|
+
user: str | None = None,
|
|
261
|
+
) -> dict[str, Any]:
|
|
262
|
+
return self._client.git_clone(
|
|
263
|
+
self.id, url, path=path, branch=branch, depth=depth, user=user
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
def events(self, *, limit: int | None = None) -> dict[str, Any]:
|
|
267
|
+
return self._client.sandbox_events(self.id, limit=limit)
|
|
268
|
+
|
|
269
|
+
def delete(self) -> bool:
|
|
270
|
+
return self._client.delete_sandbox(self.id)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class SpawnboxClient:
|
|
274
|
+
def __init__(
|
|
275
|
+
self,
|
|
276
|
+
base_url: str,
|
|
277
|
+
api_key: str = "",
|
|
278
|
+
*,
|
|
279
|
+
max_retries: int = 2,
|
|
280
|
+
timeout_s: float = 60.0,
|
|
281
|
+
) -> None:
|
|
282
|
+
self.base_url = base_url.rstrip("/")
|
|
283
|
+
self.api_key = api_key
|
|
284
|
+
self.max_retries = max_retries
|
|
285
|
+
self.timeout_s = timeout_s
|
|
286
|
+
|
|
287
|
+
def create_sandbox(
|
|
288
|
+
self,
|
|
289
|
+
template: str,
|
|
290
|
+
*,
|
|
291
|
+
timeout_s: int | None = None,
|
|
292
|
+
idle_pause_s: int | None = None,
|
|
293
|
+
persistent: bool | None = None,
|
|
294
|
+
labels: dict[str, str] | None = None,
|
|
295
|
+
env: dict[str, str] | None = None,
|
|
296
|
+
secrets: list[str] | None = None,
|
|
297
|
+
egress: dict[str, Any] | None = None,
|
|
298
|
+
volumes: list[dict[str, Any]] | None = None,
|
|
299
|
+
services: list[dict[str, Any]] | None = None,
|
|
300
|
+
extra: dict[str, Any] | None = None,
|
|
301
|
+
) -> Sandbox:
|
|
302
|
+
payload: dict[str, Any] = {"template": template}
|
|
303
|
+
if timeout_s is not None:
|
|
304
|
+
payload["timeout_s"] = timeout_s
|
|
305
|
+
if idle_pause_s is not None:
|
|
306
|
+
payload["idle_pause_s"] = idle_pause_s
|
|
307
|
+
if persistent is not None:
|
|
308
|
+
payload["persistent"] = persistent
|
|
309
|
+
if labels is not None:
|
|
310
|
+
payload["labels"] = labels
|
|
311
|
+
if env is not None:
|
|
312
|
+
payload["env"] = env
|
|
313
|
+
if secrets is not None:
|
|
314
|
+
payload["secrets"] = secrets
|
|
315
|
+
if egress is not None:
|
|
316
|
+
payload["egress"] = egress
|
|
317
|
+
if volumes is not None:
|
|
318
|
+
payload["volumes"] = volumes
|
|
319
|
+
if services is not None:
|
|
320
|
+
payload["services"] = services
|
|
321
|
+
if extra:
|
|
322
|
+
payload.update(extra)
|
|
323
|
+
info = self._request_json("POST", "/v1/sandboxes", payload)
|
|
324
|
+
return Sandbox(self, info)
|
|
325
|
+
|
|
326
|
+
def get_sandbox(self, sandbox_id: str) -> dict[str, Any] | None:
|
|
327
|
+
status, body = self._raw_request("GET", f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}")
|
|
328
|
+
if status == 404:
|
|
329
|
+
return None
|
|
330
|
+
return self._parse_json(status, body)
|
|
331
|
+
|
|
332
|
+
def list_sandboxes(self) -> list[dict[str, Any]]:
|
|
333
|
+
data = self._request_json("GET", "/v1/sandboxes")
|
|
334
|
+
if isinstance(data, list):
|
|
335
|
+
return data
|
|
336
|
+
return list(data.get("sandboxes", []))
|
|
337
|
+
|
|
338
|
+
def delete_sandbox(self, sandbox_id: str) -> bool:
|
|
339
|
+
status, body = self._raw_request("DELETE", f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}")
|
|
340
|
+
if status == 404:
|
|
341
|
+
return False
|
|
342
|
+
if not (200 <= status < 300):
|
|
343
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
344
|
+
return True
|
|
345
|
+
|
|
346
|
+
def exec(self, sandbox_id: str, spec: dict[str, Any]) -> dict[str, Any]:
|
|
347
|
+
return self._request_json(
|
|
348
|
+
"POST",
|
|
349
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/exec",
|
|
350
|
+
spec,
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
def exec_stream(
|
|
354
|
+
self, sandbox_id: str, spec: dict[str, Any]
|
|
355
|
+
) -> Iterator[dict[str, Any]]:
|
|
356
|
+
url = f"{self.base_url}/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/exec"
|
|
357
|
+
headers = {
|
|
358
|
+
"Content-Type": "application/json",
|
|
359
|
+
"Accept": "text/event-stream",
|
|
360
|
+
}
|
|
361
|
+
if self.api_key:
|
|
362
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
363
|
+
req = urllib.request.Request(
|
|
364
|
+
url,
|
|
365
|
+
data=json.dumps(spec).encode("utf-8"),
|
|
366
|
+
headers=headers,
|
|
367
|
+
method="POST",
|
|
368
|
+
)
|
|
369
|
+
try:
|
|
370
|
+
resp = urllib.request.urlopen(req, timeout=self.timeout_s)
|
|
371
|
+
except urllib.error.HTTPError as err:
|
|
372
|
+
body = err.read().decode("utf-8", errors="replace")
|
|
373
|
+
err.close()
|
|
374
|
+
raise SpawnboxError(err.code, body) from err
|
|
375
|
+
with resp:
|
|
376
|
+
event_name = "message"
|
|
377
|
+
data_lines: list[str] = []
|
|
378
|
+
for raw_line in resp:
|
|
379
|
+
line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n")
|
|
380
|
+
if line == "":
|
|
381
|
+
if data_lines:
|
|
382
|
+
raw_data = "\n".join(data_lines)
|
|
383
|
+
try:
|
|
384
|
+
parsed: Any = json.loads(raw_data)
|
|
385
|
+
except json.JSONDecodeError:
|
|
386
|
+
parsed = raw_data
|
|
387
|
+
yield {"event": event_name, "data": parsed}
|
|
388
|
+
data_lines.clear()
|
|
389
|
+
event_name = "message"
|
|
390
|
+
continue
|
|
391
|
+
if line.startswith("event:"):
|
|
392
|
+
event_name = line[6:].strip()
|
|
393
|
+
elif line.startswith("data:"):
|
|
394
|
+
data_lines.append(line[5:].lstrip(" "))
|
|
395
|
+
if data_lines:
|
|
396
|
+
raw_data = "\n".join(data_lines)
|
|
397
|
+
try:
|
|
398
|
+
parsed = json.loads(raw_data)
|
|
399
|
+
except json.JSONDecodeError:
|
|
400
|
+
parsed = raw_data
|
|
401
|
+
yield {"event": event_name, "data": parsed}
|
|
402
|
+
|
|
403
|
+
def read_file(self, sandbox_id: str, path: str) -> bytes:
|
|
404
|
+
query = urllib.parse.urlencode({"path": path})
|
|
405
|
+
status, body = self._raw_request(
|
|
406
|
+
"GET",
|
|
407
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files?{query}",
|
|
408
|
+
)
|
|
409
|
+
if not (200 <= status < 300):
|
|
410
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
411
|
+
return body
|
|
412
|
+
|
|
413
|
+
def write_file(self, sandbox_id: str, path: str, content: str | bytes) -> None:
|
|
414
|
+
query = urllib.parse.urlencode({"path": path})
|
|
415
|
+
raw = content.encode("utf-8") if isinstance(content, str) else content
|
|
416
|
+
status, body = self._raw_request(
|
|
417
|
+
"PUT",
|
|
418
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files?{query}",
|
|
419
|
+
raw,
|
|
420
|
+
"application/octet-stream",
|
|
421
|
+
)
|
|
422
|
+
if not (200 <= status < 300):
|
|
423
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
424
|
+
|
|
425
|
+
def list_files(self, sandbox_id: str, path: str) -> Any:
|
|
426
|
+
query = urllib.parse.urlencode({"path": path})
|
|
427
|
+
return self._request_json(
|
|
428
|
+
"GET",
|
|
429
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files?{query}",
|
|
430
|
+
)
|
|
431
|
+
|
|
432
|
+
def delete_file(self, sandbox_id: str, path: str) -> None:
|
|
433
|
+
query = urllib.parse.urlencode({"path": path})
|
|
434
|
+
status, body = self._raw_request(
|
|
435
|
+
"DELETE",
|
|
436
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files?{query}",
|
|
437
|
+
)
|
|
438
|
+
if status != 404 and not (200 <= status < 300):
|
|
439
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
440
|
+
|
|
441
|
+
def upload_archive(
|
|
442
|
+
self,
|
|
443
|
+
sandbox_id: str,
|
|
444
|
+
path: str,
|
|
445
|
+
tar_zst: bytes,
|
|
446
|
+
*,
|
|
447
|
+
user: str | None = None,
|
|
448
|
+
) -> dict[str, Any]:
|
|
449
|
+
params: dict[str, str] = {"path": path}
|
|
450
|
+
if user is not None:
|
|
451
|
+
params["user"] = user
|
|
452
|
+
query = urllib.parse.urlencode(params)
|
|
453
|
+
status, body = self._raw_request(
|
|
454
|
+
"PUT",
|
|
455
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files:archive?{query}",
|
|
456
|
+
tar_zst,
|
|
457
|
+
"application/zstd",
|
|
458
|
+
)
|
|
459
|
+
return self._parse_json(status, body)
|
|
460
|
+
|
|
461
|
+
def download_archive(
|
|
462
|
+
self, sandbox_id: str, path: str, *, user: str | None = None
|
|
463
|
+
) -> bytes:
|
|
464
|
+
params: dict[str, str] = {"path": path}
|
|
465
|
+
if user is not None:
|
|
466
|
+
params["user"] = user
|
|
467
|
+
query = urllib.parse.urlencode(params)
|
|
468
|
+
status, body = self._raw_request(
|
|
469
|
+
"GET",
|
|
470
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/files:archive?{query}",
|
|
471
|
+
)
|
|
472
|
+
if not (200 <= status < 300):
|
|
473
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
474
|
+
return body
|
|
475
|
+
|
|
476
|
+
def fork_sandbox(
|
|
477
|
+
self, sandbox_id: str, *, count: int | None = None
|
|
478
|
+
) -> dict[str, Any]:
|
|
479
|
+
payload: dict[str, Any] = {}
|
|
480
|
+
if count is not None:
|
|
481
|
+
payload["count"] = count
|
|
482
|
+
raw = self._request_json(
|
|
483
|
+
"POST",
|
|
484
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}:fork",
|
|
485
|
+
payload,
|
|
486
|
+
)
|
|
487
|
+
return {
|
|
488
|
+
"sandboxes": [Sandbox(self, info) for info in raw.get("sandboxes", [])],
|
|
489
|
+
"failed": raw.get("failed", []),
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
def pause_sandbox(self, sandbox_id: str) -> dict[str, Any]:
|
|
493
|
+
return self._request_json(
|
|
494
|
+
"POST",
|
|
495
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}:pause",
|
|
496
|
+
{},
|
|
497
|
+
)
|
|
498
|
+
|
|
499
|
+
def resume_sandbox(self, sandbox_id: str) -> dict[str, Any]:
|
|
500
|
+
return self._request_json(
|
|
501
|
+
"POST",
|
|
502
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}:resume",
|
|
503
|
+
{},
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
def publish_port(
|
|
507
|
+
self, sandbox_id: str, port: int, *, access: str | None = None
|
|
508
|
+
) -> dict[str, Any]:
|
|
509
|
+
payload: dict[str, Any] = {"port": port}
|
|
510
|
+
if access is not None:
|
|
511
|
+
payload["access"] = access
|
|
512
|
+
return self._request_json(
|
|
513
|
+
"POST",
|
|
514
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/ports",
|
|
515
|
+
payload,
|
|
516
|
+
)
|
|
517
|
+
|
|
518
|
+
def list_ports(self, sandbox_id: str) -> dict[str, Any]:
|
|
519
|
+
return self._request_json(
|
|
520
|
+
"GET",
|
|
521
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/ports",
|
|
522
|
+
)
|
|
523
|
+
|
|
524
|
+
def unpublish_port(self, sandbox_id: str, port: int) -> bool:
|
|
525
|
+
status, body = self._raw_request(
|
|
526
|
+
"DELETE",
|
|
527
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/ports/{port}",
|
|
528
|
+
)
|
|
529
|
+
if status == 404:
|
|
530
|
+
return False
|
|
531
|
+
if not (200 <= status < 300):
|
|
532
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
533
|
+
return True
|
|
534
|
+
|
|
535
|
+
def port_ready(
|
|
536
|
+
self, sandbox_id: str, port: int, *, wait_s: int | None = None
|
|
537
|
+
) -> bool:
|
|
538
|
+
query = "" if wait_s is None else f"?wait_s={wait_s}"
|
|
539
|
+
status, body = self._raw_request(
|
|
540
|
+
"GET",
|
|
541
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/ports/{port}/ready{query}",
|
|
542
|
+
)
|
|
543
|
+
if status in (404, 503):
|
|
544
|
+
return False
|
|
545
|
+
if not (200 <= status < 300):
|
|
546
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
547
|
+
return True
|
|
548
|
+
|
|
549
|
+
def snapshot_sandbox(self, sandbox_id: str, name: str) -> dict[str, Any]:
|
|
550
|
+
return self._request_json(
|
|
551
|
+
"POST",
|
|
552
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}:snapshot",
|
|
553
|
+
{"name": name},
|
|
554
|
+
)
|
|
555
|
+
|
|
556
|
+
def list_services(self, sandbox_id: str) -> dict[str, Any]:
|
|
557
|
+
return self._request_json(
|
|
558
|
+
"GET",
|
|
559
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/services",
|
|
560
|
+
)
|
|
561
|
+
|
|
562
|
+
def restart_service(self, sandbox_id: str, name: str) -> None:
|
|
563
|
+
status, body = self._raw_request(
|
|
564
|
+
"POST",
|
|
565
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/services/{urllib.parse.quote(name, safe='')}:restart",
|
|
566
|
+
)
|
|
567
|
+
if not (200 <= status < 300):
|
|
568
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
569
|
+
|
|
570
|
+
def service_logs(self, sandbox_id: str, name: str) -> str:
|
|
571
|
+
status, body = self._raw_request(
|
|
572
|
+
"GET",
|
|
573
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/services/{urllib.parse.quote(name, safe='')}/logs",
|
|
574
|
+
)
|
|
575
|
+
if not (200 <= status < 300):
|
|
576
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
577
|
+
return body.decode("utf-8", errors="replace")
|
|
578
|
+
|
|
579
|
+
def git_clone(
|
|
580
|
+
self,
|
|
581
|
+
sandbox_id: str,
|
|
582
|
+
url: str,
|
|
583
|
+
*,
|
|
584
|
+
path: str | None = None,
|
|
585
|
+
branch: str | None = None,
|
|
586
|
+
depth: int | None = None,
|
|
587
|
+
user: str | None = None,
|
|
588
|
+
) -> dict[str, Any]:
|
|
589
|
+
payload: dict[str, Any] = {"url": url}
|
|
590
|
+
if path is not None:
|
|
591
|
+
payload["path"] = path
|
|
592
|
+
if branch is not None:
|
|
593
|
+
payload["branch"] = branch
|
|
594
|
+
if depth is not None:
|
|
595
|
+
payload["depth"] = depth
|
|
596
|
+
if user is not None:
|
|
597
|
+
payload["user"] = user
|
|
598
|
+
return self._request_json(
|
|
599
|
+
"POST",
|
|
600
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/git:clone",
|
|
601
|
+
payload,
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
def sandbox_events(
|
|
605
|
+
self, sandbox_id: str, *, limit: int | None = None
|
|
606
|
+
) -> dict[str, Any]:
|
|
607
|
+
query = "" if limit is None else f"?limit={limit}"
|
|
608
|
+
return self._request_json(
|
|
609
|
+
"GET",
|
|
610
|
+
f"/v1/sandboxes/{urllib.parse.quote(sandbox_id, safe='')}/events{query}",
|
|
611
|
+
)
|
|
612
|
+
|
|
613
|
+
def list_events(self, *, limit: int | None = None) -> dict[str, Any]:
|
|
614
|
+
query = "" if limit is None else f"?limit={limit}"
|
|
615
|
+
return self._request_json("GET", f"/v1/events{query}")
|
|
616
|
+
|
|
617
|
+
def create_volume(
|
|
618
|
+
self, name: str, *, size_gib: int | None = None
|
|
619
|
+
) -> dict[str, Any]:
|
|
620
|
+
payload: dict[str, Any] = {"name": name}
|
|
621
|
+
if size_gib is not None:
|
|
622
|
+
payload["size_gib"] = size_gib
|
|
623
|
+
return self._request_json("POST", "/v1/volumes", payload)
|
|
624
|
+
|
|
625
|
+
def list_volumes(self) -> Any:
|
|
626
|
+
return self._request_json("GET", "/v1/volumes")
|
|
627
|
+
|
|
628
|
+
def get_volume(self, name: str) -> dict[str, Any] | None:
|
|
629
|
+
status, body = self._raw_request(
|
|
630
|
+
"GET", f"/v1/volumes/{urllib.parse.quote(name, safe='')}"
|
|
631
|
+
)
|
|
632
|
+
if status == 404:
|
|
633
|
+
return None
|
|
634
|
+
return self._parse_json(status, body)
|
|
635
|
+
|
|
636
|
+
def delete_volume(self, name: str) -> bool:
|
|
637
|
+
status, body = self._raw_request(
|
|
638
|
+
"DELETE", f"/v1/volumes/{urllib.parse.quote(name, safe='')}"
|
|
639
|
+
)
|
|
640
|
+
if status == 404:
|
|
641
|
+
return False
|
|
642
|
+
if not (200 <= status < 300):
|
|
643
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
644
|
+
return True
|
|
645
|
+
|
|
646
|
+
def list_templates(self) -> Any:
|
|
647
|
+
return self._request_json("GET", "/v1/templates")
|
|
648
|
+
|
|
649
|
+
def get_template(self, name: str) -> dict[str, Any] | None:
|
|
650
|
+
status, body = self._raw_request(
|
|
651
|
+
"GET", f"/v1/templates/{urllib.parse.quote(name, safe='')}"
|
|
652
|
+
)
|
|
653
|
+
if status == 404:
|
|
654
|
+
return None
|
|
655
|
+
return self._parse_json(status, body)
|
|
656
|
+
|
|
657
|
+
def put_template(self, spec: dict[str, Any]) -> dict[str, Any]:
|
|
658
|
+
return self._request_json("POST", "/v1/templates", spec)
|
|
659
|
+
|
|
660
|
+
def delete_template(self, name: str) -> bool:
|
|
661
|
+
status, body = self._raw_request(
|
|
662
|
+
"DELETE", f"/v1/templates/{urllib.parse.quote(name, safe='')}"
|
|
663
|
+
)
|
|
664
|
+
if status == 404:
|
|
665
|
+
return False
|
|
666
|
+
if not (200 <= status < 300):
|
|
667
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
668
|
+
return True
|
|
669
|
+
|
|
670
|
+
def list_secrets(self) -> Any:
|
|
671
|
+
return self._request_json("GET", "/v1/secrets")
|
|
672
|
+
|
|
673
|
+
def upsert_secret(self, spec: dict[str, Any]) -> dict[str, Any]:
|
|
674
|
+
return self._request_json("POST", "/v1/secrets", spec)
|
|
675
|
+
|
|
676
|
+
def delete_secret(self, name: str) -> bool:
|
|
677
|
+
status, body = self._raw_request(
|
|
678
|
+
"DELETE", f"/v1/secrets/{urllib.parse.quote(name, safe='')}"
|
|
679
|
+
)
|
|
680
|
+
if status == 404:
|
|
681
|
+
return False
|
|
682
|
+
if not (200 <= status < 300):
|
|
683
|
+
raise SpawnboxError(status, body.decode("utf-8", errors="replace"))
|
|
684
|
+
return True
|
|
685
|
+
|
|
686
|
+
def _request_json(
|
|
687
|
+
self, method: str, path: str, payload: dict[str, Any] | None = None
|
|
688
|
+
) -> Any:
|
|
689
|
+
raw = None if payload is None else json.dumps(payload).encode("utf-8")
|
|
690
|
+
content_type = None if payload is None else "application/json"
|
|
691
|
+
status, body = self._raw_request(method, path, raw, content_type)
|
|
692
|
+
return self._parse_json(status, body)
|
|
693
|
+
|
|
694
|
+
def _parse_json(self, status: int, body: bytes) -> Any:
|
|
695
|
+
text = body.decode("utf-8", errors="replace")
|
|
696
|
+
if not (200 <= status < 300):
|
|
697
|
+
raise SpawnboxError(status, text)
|
|
698
|
+
return {} if not text else json.loads(text)
|
|
699
|
+
|
|
700
|
+
def _raw_request(
|
|
701
|
+
self,
|
|
702
|
+
method: str,
|
|
703
|
+
path: str,
|
|
704
|
+
body: bytes | None = None,
|
|
705
|
+
content_type: str | None = None,
|
|
706
|
+
) -> tuple[int, bytes]:
|
|
707
|
+
url = f"{self.base_url}{path}"
|
|
708
|
+
headers: dict[str, str] = {}
|
|
709
|
+
if self.api_key:
|
|
710
|
+
headers["Authorization"] = f"Bearer {self.api_key}"
|
|
711
|
+
if content_type is not None:
|
|
712
|
+
headers["Content-Type"] = content_type
|
|
713
|
+
|
|
714
|
+
attempt = 0
|
|
715
|
+
while True:
|
|
716
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
717
|
+
try:
|
|
718
|
+
with urllib.request.urlopen(req, timeout=self.timeout_s) as resp:
|
|
719
|
+
status = resp.status
|
|
720
|
+
data = resp.read()
|
|
721
|
+
except urllib.error.HTTPError as err:
|
|
722
|
+
status = err.code
|
|
723
|
+
data = err.read()
|
|
724
|
+
err.close()
|
|
725
|
+
|
|
726
|
+
if status in (429, 502, 503, 504) and attempt < self.max_retries:
|
|
727
|
+
attempt += 1
|
|
728
|
+
time.sleep(0.1 * attempt)
|
|
729
|
+
continue
|
|
730
|
+
return status, data
|
|
731
|
+
|
|
732
|
+
|
|
733
|
+
class AsyncCodeInterpreter:
|
|
734
|
+
def __init__(self, inner: CodeInterpreter) -> None:
|
|
735
|
+
self._inner = inner
|
|
736
|
+
|
|
737
|
+
async def run_code(
|
|
738
|
+
self, code: str, *, context_id: str = "default", timeout_s: float = 30.0
|
|
739
|
+
) -> dict[str, Any]:
|
|
740
|
+
return await asyncio.to_thread(
|
|
741
|
+
self._inner.run_code, code, context_id=context_id, timeout_s=timeout_s
|
|
742
|
+
)
|
|
743
|
+
|
|
744
|
+
async def interrupt(self, *, context_id: str = "default") -> dict[str, Any]:
|
|
745
|
+
return await asyncio.to_thread(self._inner.interrupt, context_id=context_id)
|
|
746
|
+
|
|
747
|
+
async def restart(self, *, context_id: str = "default") -> dict[str, Any]:
|
|
748
|
+
return await asyncio.to_thread(self._inner.restart, context_id=context_id)
|
|
749
|
+
|
|
750
|
+
|
|
751
|
+
class AsyncSandboxBrowser:
|
|
752
|
+
def __init__(self, inner: SandboxBrowser) -> None:
|
|
753
|
+
self._inner = inner
|
|
754
|
+
|
|
755
|
+
async def cdp_url(self, *, access: str = "token") -> dict[str, Any]:
|
|
756
|
+
return await asyncio.to_thread(self._inner.cdp_url, access=access)
|
|
757
|
+
|
|
758
|
+
async def live_view_url(self, *, access: str = "token") -> dict[str, Any]:
|
|
759
|
+
return await asyncio.to_thread(self._inner.live_view_url, access=access)
|
|
760
|
+
|
|
761
|
+
async def screenshot(self) -> dict[str, Any]:
|
|
762
|
+
return await asyncio.to_thread(self._inner.screenshot)
|
|
763
|
+
|
|
764
|
+
async def click(self, x: int, y: int, *, button: int = 1) -> dict[str, Any]:
|
|
765
|
+
return await asyncio.to_thread(self._inner.click, x, y, button=button)
|
|
766
|
+
|
|
767
|
+
async def double_click(self, x: int, y: int) -> dict[str, Any]:
|
|
768
|
+
return await asyncio.to_thread(self._inner.double_click, x, y)
|
|
769
|
+
|
|
770
|
+
async def move(self, x: int, y: int) -> dict[str, Any]:
|
|
771
|
+
return await asyncio.to_thread(self._inner.move, x, y)
|
|
772
|
+
|
|
773
|
+
async def type(self, text: str, *, delay_ms: int = 12) -> dict[str, Any]:
|
|
774
|
+
return await asyncio.to_thread(self._inner.type, text, delay_ms=delay_ms)
|
|
775
|
+
|
|
776
|
+
async def key(self, key: str) -> dict[str, Any]:
|
|
777
|
+
return await asyncio.to_thread(self._inner.key, key)
|
|
778
|
+
|
|
779
|
+
async def scroll(self, delta_y: int) -> dict[str, Any]:
|
|
780
|
+
return await asyncio.to_thread(self._inner.scroll, delta_y)
|
|
781
|
+
|
|
782
|
+
|
|
783
|
+
class AsyncSandbox:
|
|
784
|
+
def __init__(self, client: AsyncSpawnboxClient, inner: Sandbox) -> None:
|
|
785
|
+
self._client = client
|
|
786
|
+
self._inner = inner
|
|
787
|
+
self.info = inner.info
|
|
788
|
+
self.id = inner.id
|
|
789
|
+
|
|
790
|
+
async def __aenter__(self) -> AsyncSandbox:
|
|
791
|
+
return self
|
|
792
|
+
|
|
793
|
+
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
|
794
|
+
await self.delete()
|
|
795
|
+
|
|
796
|
+
async def exec(self, cmd: str, **kwargs: Any) -> dict[str, Any]:
|
|
797
|
+
return await asyncio.to_thread(self._inner.exec, cmd, **kwargs)
|
|
798
|
+
|
|
799
|
+
async def exec_stream(
|
|
800
|
+
self, cmd: str, **kwargs: Any
|
|
801
|
+
) -> AsyncIterator[dict[str, Any]]:
|
|
802
|
+
iterator = await asyncio.to_thread(self._inner.exec_stream, cmd, **kwargs)
|
|
803
|
+
sentinel = object()
|
|
804
|
+
while True:
|
|
805
|
+
item = await asyncio.to_thread(next, iterator, sentinel)
|
|
806
|
+
if item is sentinel:
|
|
807
|
+
break
|
|
808
|
+
yield item # type: ignore[misc]
|
|
809
|
+
|
|
810
|
+
def code_interpreter(self, *, port: int = 8888) -> AsyncCodeInterpreter:
|
|
811
|
+
return AsyncCodeInterpreter(self._inner.code_interpreter(port=port))
|
|
812
|
+
|
|
813
|
+
def browser(
|
|
814
|
+
self,
|
|
815
|
+
*,
|
|
816
|
+
cdp_port: int = 9222,
|
|
817
|
+
vnc_port: int = 6080,
|
|
818
|
+
api_port: int = 6081,
|
|
819
|
+
) -> AsyncSandboxBrowser:
|
|
820
|
+
return AsyncSandboxBrowser(
|
|
821
|
+
self._inner.browser(
|
|
822
|
+
cdp_port=cdp_port, vnc_port=vnc_port, api_port=api_port
|
|
823
|
+
)
|
|
824
|
+
)
|
|
825
|
+
|
|
826
|
+
async def read_file(self, path: str) -> bytes:
|
|
827
|
+
return await asyncio.to_thread(self._inner.read_file, path)
|
|
828
|
+
|
|
829
|
+
async def read_text_file(self, path: str, encoding: str = "utf-8") -> str:
|
|
830
|
+
return await asyncio.to_thread(self._inner.read_text_file, path, encoding)
|
|
831
|
+
|
|
832
|
+
async def write_file(self, path: str, content: str | bytes) -> None:
|
|
833
|
+
await asyncio.to_thread(self._inner.write_file, path, content)
|
|
834
|
+
|
|
835
|
+
async def list_files(self, path: str) -> Any:
|
|
836
|
+
return await asyncio.to_thread(self._inner.list_files, path)
|
|
837
|
+
|
|
838
|
+
async def delete_file(self, path: str) -> None:
|
|
839
|
+
await asyncio.to_thread(self._inner.delete_file, path)
|
|
840
|
+
|
|
841
|
+
async def upload_archive(
|
|
842
|
+
self, path: str, tar_zst: bytes, *, user: str | None = None
|
|
843
|
+
) -> dict[str, Any]:
|
|
844
|
+
return await asyncio.to_thread(
|
|
845
|
+
self._inner.upload_archive, path, tar_zst, user=user
|
|
846
|
+
)
|
|
847
|
+
|
|
848
|
+
async def download_archive(
|
|
849
|
+
self, path: str, *, user: str | None = None
|
|
850
|
+
) -> bytes:
|
|
851
|
+
return await asyncio.to_thread(
|
|
852
|
+
self._inner.download_archive, path, user=user
|
|
853
|
+
)
|
|
854
|
+
|
|
855
|
+
async def fork(self, *, count: int | None = None) -> dict[str, Any]:
|
|
856
|
+
raw = await asyncio.to_thread(self._inner.fork, count=count)
|
|
857
|
+
return {
|
|
858
|
+
"sandboxes": [
|
|
859
|
+
AsyncSandbox(self._client, sb) for sb in raw.get("sandboxes", [])
|
|
860
|
+
],
|
|
861
|
+
"failed": raw.get("failed", []),
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
async def snapshot(self, name: str) -> dict[str, Any]:
|
|
865
|
+
return await asyncio.to_thread(self._inner.snapshot, name)
|
|
866
|
+
|
|
867
|
+
async def pause(self) -> dict[str, Any]:
|
|
868
|
+
return await asyncio.to_thread(self._inner.pause)
|
|
869
|
+
|
|
870
|
+
async def resume(self) -> dict[str, Any]:
|
|
871
|
+
return await asyncio.to_thread(self._inner.resume)
|
|
872
|
+
|
|
873
|
+
async def publish_port(
|
|
874
|
+
self, port: int, *, access: str | None = None
|
|
875
|
+
) -> dict[str, Any]:
|
|
876
|
+
return await asyncio.to_thread(
|
|
877
|
+
self._inner.publish_port, port, access=access
|
|
878
|
+
)
|
|
879
|
+
|
|
880
|
+
async def list_ports(self) -> dict[str, Any]:
|
|
881
|
+
return await asyncio.to_thread(self._inner.list_ports)
|
|
882
|
+
|
|
883
|
+
async def unpublish_port(self, port: int) -> bool:
|
|
884
|
+
return await asyncio.to_thread(self._inner.unpublish_port, port)
|
|
885
|
+
|
|
886
|
+
async def port_ready(
|
|
887
|
+
self, port: int, *, wait_s: int | None = None
|
|
888
|
+
) -> bool:
|
|
889
|
+
return await asyncio.to_thread(
|
|
890
|
+
self._inner.port_ready, port, wait_s=wait_s
|
|
891
|
+
)
|
|
892
|
+
|
|
893
|
+
async def list_services(self) -> dict[str, Any]:
|
|
894
|
+
return await asyncio.to_thread(self._inner.list_services)
|
|
895
|
+
|
|
896
|
+
async def restart_service(self, name: str) -> None:
|
|
897
|
+
await asyncio.to_thread(self._inner.restart_service, name)
|
|
898
|
+
|
|
899
|
+
async def service_logs(self, name: str) -> str:
|
|
900
|
+
return await asyncio.to_thread(self._inner.service_logs, name)
|
|
901
|
+
|
|
902
|
+
async def git_clone(self, url: str, **kwargs: Any) -> dict[str, Any]:
|
|
903
|
+
return await asyncio.to_thread(self._inner.git_clone, url, **kwargs)
|
|
904
|
+
|
|
905
|
+
async def events(self, *, limit: int | None = None) -> dict[str, Any]:
|
|
906
|
+
return await asyncio.to_thread(self._inner.events, limit=limit)
|
|
907
|
+
|
|
908
|
+
async def delete(self) -> bool:
|
|
909
|
+
return await asyncio.to_thread(self._inner.delete)
|
|
910
|
+
|
|
911
|
+
|
|
912
|
+
class AsyncSpawnboxClient:
|
|
913
|
+
def __init__(
|
|
914
|
+
self,
|
|
915
|
+
base_url: str,
|
|
916
|
+
api_key: str = "",
|
|
917
|
+
*,
|
|
918
|
+
max_retries: int = 2,
|
|
919
|
+
timeout_s: float = 60.0,
|
|
920
|
+
) -> None:
|
|
921
|
+
self._sync = SpawnboxClient(
|
|
922
|
+
base_url, api_key, max_retries=max_retries, timeout_s=timeout_s
|
|
923
|
+
)
|
|
924
|
+
|
|
925
|
+
async def create_sandbox(
|
|
926
|
+
self, template: str, **kwargs: Any
|
|
927
|
+
) -> AsyncSandbox:
|
|
928
|
+
sb = await asyncio.to_thread(
|
|
929
|
+
self._sync.create_sandbox, template, **kwargs
|
|
930
|
+
)
|
|
931
|
+
return AsyncSandbox(self, sb)
|
|
932
|
+
|
|
933
|
+
async def get_sandbox(self, sandbox_id: str) -> dict[str, Any] | None:
|
|
934
|
+
return await asyncio.to_thread(self._sync.get_sandbox, sandbox_id)
|
|
935
|
+
|
|
936
|
+
async def list_sandboxes(self) -> list[dict[str, Any]]:
|
|
937
|
+
return await asyncio.to_thread(self._sync.list_sandboxes)
|
|
938
|
+
|
|
939
|
+
async def delete_sandbox(self, sandbox_id: str) -> bool:
|
|
940
|
+
return await asyncio.to_thread(self._sync.delete_sandbox, sandbox_id)
|
|
941
|
+
|
|
942
|
+
async def create_volume(
|
|
943
|
+
self, name: str, *, size_gib: int | None = None
|
|
944
|
+
) -> dict[str, Any]:
|
|
945
|
+
return await asyncio.to_thread(
|
|
946
|
+
self._sync.create_volume, name, size_gib=size_gib
|
|
947
|
+
)
|
|
948
|
+
|
|
949
|
+
async def list_volumes(self) -> Any:
|
|
950
|
+
return await asyncio.to_thread(self._sync.list_volumes)
|
|
951
|
+
|
|
952
|
+
async def get_volume(self, name: str) -> dict[str, Any] | None:
|
|
953
|
+
return await asyncio.to_thread(self._sync.get_volume, name)
|
|
954
|
+
|
|
955
|
+
async def delete_volume(self, name: str) -> bool:
|
|
956
|
+
return await asyncio.to_thread(self._sync.delete_volume, name)
|
|
957
|
+
|
|
958
|
+
async def list_templates(self) -> Any:
|
|
959
|
+
return await asyncio.to_thread(self._sync.list_templates)
|
|
960
|
+
|
|
961
|
+
async def get_template(self, name: str) -> dict[str, Any] | None:
|
|
962
|
+
return await asyncio.to_thread(self._sync.get_template, name)
|
|
963
|
+
|
|
964
|
+
async def put_template(self, spec: dict[str, Any]) -> dict[str, Any]:
|
|
965
|
+
return await asyncio.to_thread(self._sync.put_template, spec)
|
|
966
|
+
|
|
967
|
+
async def delete_template(self, name: str) -> bool:
|
|
968
|
+
return await asyncio.to_thread(self._sync.delete_template, name)
|
|
969
|
+
|
|
970
|
+
async def list_secrets(self) -> Any:
|
|
971
|
+
return await asyncio.to_thread(self._sync.list_secrets)
|
|
972
|
+
|
|
973
|
+
async def upsert_secret(self, spec: dict[str, Any]) -> dict[str, Any]:
|
|
974
|
+
return await asyncio.to_thread(self._sync.upsert_secret, spec)
|
|
975
|
+
|
|
976
|
+
async def delete_secret(self, name: str) -> bool:
|
|
977
|
+
return await asyncio.to_thread(self._sync.delete_secret, name)
|
|
978
|
+
|
|
979
|
+
async def list_events(self, *, limit: int | None = None) -> dict[str, Any]:
|
|
980
|
+
return await asyncio.to_thread(self._sync.list_events, limit=limit)
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spawnbox-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python SDK for the self-hosted Spawnbox microVM sandbox runtime
|
|
5
|
+
License-Expression: Apache-2.0
|
|
6
|
+
Project-URL: Homepage, https://spawnbox.tulipfarm.ai
|
|
7
|
+
Project-URL: Repository, https://github.com/TulipFarm/spawnbox
|
|
8
|
+
Project-URL: Issues, https://github.com/TulipFarm/spawnbox/issues
|
|
9
|
+
Keywords: spawnbox,sandbox,microvm,firecracker,ai-agents,sdk
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# spawnbox-sdk
|
|
21
|
+
|
|
22
|
+
Official zero-dependency Python SDK (sync and `asyncio`) for the self-hosted [Spawnbox](https://github.com/TulipFarm/spawnbox) microVM sandbox runtime.
|
|
23
|
+
|
|
24
|
+
## Installation
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
pip install spawnbox-sdk
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
or with `uv`:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
uv add spawnbox-sdk
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Requires Python `>= 3.10`. Zero external runtime dependencies.
|
|
37
|
+
|
|
38
|
+
## Quickstart (Sync)
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
import os
|
|
42
|
+
from spawnbox import SpawnboxClient
|
|
43
|
+
|
|
44
|
+
client = SpawnboxClient(
|
|
45
|
+
os.environ.get("SPAWNBOX_URL", "http://127.0.0.1:8080"),
|
|
46
|
+
os.environ.get("SPAWNBOX_API_KEY", ""),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
with client.create_sandbox("python-3.12") as sb:
|
|
50
|
+
res = sb.exec("python3 -c 'print(6 * 7)'", no_new_privs=True)
|
|
51
|
+
print(res["stdout"])
|
|
52
|
+
|
|
53
|
+
for event in sb.exec_stream("for i in 1 2 3; do echo $i; done"):
|
|
54
|
+
print(event["event"], event["data"])
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Quickstart (Async)
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
import asyncio
|
|
61
|
+
import os
|
|
62
|
+
from spawnbox import AsyncSpawnboxClient
|
|
63
|
+
|
|
64
|
+
async def main() -> None:
|
|
65
|
+
client = AsyncSpawnboxClient(
|
|
66
|
+
os.environ.get("SPAWNBOX_URL", "http://127.0.0.1:8080"),
|
|
67
|
+
os.environ.get("SPAWNBOX_API_KEY", ""),
|
|
68
|
+
)
|
|
69
|
+
async with await client.create_sandbox("code-interpreter") as sb:
|
|
70
|
+
run = await sb.code_interpreter().run_code("x = 41\nprint(x + 1)")
|
|
71
|
+
print(run["stdout"])
|
|
72
|
+
|
|
73
|
+
asyncio.run(main())
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Browser Helper
|
|
77
|
+
|
|
78
|
+
```python
|
|
79
|
+
with client.create_sandbox("browser-computer-use") as sb:
|
|
80
|
+
browser = sb.browser()
|
|
81
|
+
live = browser.live_view_url(access="token")
|
|
82
|
+
shot = browser.screenshot()
|
|
83
|
+
browser.click(640, 360)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## API Coverage
|
|
87
|
+
|
|
88
|
+
- **Sandboxes**: `create_sandbox`, `get_sandbox`, `list_sandboxes`, `delete_sandbox`, `fork`, `snapshot`, `pause`, `resume`, `events`
|
|
89
|
+
- **Execution**: `exec` (JSON, stdin, `no_new_privs`), `exec_stream` (SSE iterator / async iterator)
|
|
90
|
+
- **Files & Archives**: `read_file`, `read_text_file`, `write_file`, `list_files`, `delete_file`, `upload_archive`, `download_archive` (`tar.zst`)
|
|
91
|
+
- **Ports, Services & Git**: `publish_port`, `list_ports`, `unpublish_port`, `port_ready`, `list_services`, `restart_service`, `service_logs`, `git_clone`
|
|
92
|
+
- **Volumes, Templates & Secrets**: `create_volume`, `list_volumes`, `get_volume`, `delete_volume`, `list_templates`, `get_template`, `put_template`, `delete_template`, `list_secrets`, `upsert_secret`, `delete_secret`
|
|
93
|
+
|
|
94
|
+
## License
|
|
95
|
+
|
|
96
|
+
[Apache-2.0](https://github.com/TulipFarm/spawnbox/blob/main/LICENSE)
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
spawnbox/__init__.py,sha256=G6AMSzFv4LwmJi6WzLaNAzOT99imHCes8OUZxykoXEE,431
|
|
2
|
+
spawnbox/client.py,sha256=KSaM6mTN7B_j0kPYR23kaBqrFuUE7e_Ete8KObXPx_g,35771
|
|
3
|
+
spawnbox_sdk-0.1.0.dist-info/METADATA,sha256=UPxI4yhZTDxLkV4hcew-kYr0n2LPpgt84l12DVbVtUc,3183
|
|
4
|
+
spawnbox_sdk-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
spawnbox_sdk-0.1.0.dist-info/top_level.txt,sha256=rvJCphOZrCI8Hn9lmjvaOnSsekrHVEjfwPHBJcRbRLk,9
|
|
6
|
+
spawnbox_sdk-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
spawnbox
|