devbox-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.
devbox/__init__.py ADDED
@@ -0,0 +1,83 @@
1
+ """Public DevBox SDK API.
2
+
3
+ Start with :class:`Sandbox` for one sandbox. Use :class:`DevBox` only when an
4
+ application needs to manage several sandboxes through one reusable client.
5
+ """
6
+
7
+ from ._version import __version__
8
+ from .client import AsyncDevBox, DevBox
9
+ from .commands import AsyncCommandHandle, CommandHandle
10
+ from .envd import AsyncEnvd, Envd
11
+ from .errors import (
12
+ AuthenticationError,
13
+ CommandExitError,
14
+ ConfigurationError,
15
+ ConflictError,
16
+ DevBoxError,
17
+ ErrorDetail,
18
+ NotFoundError,
19
+ PermissionDeniedError,
20
+ ProtocolError,
21
+ RateLimitError,
22
+ RequestTimeoutError,
23
+ ServiceUnavailableError,
24
+ ValidationError,
25
+ )
26
+ from .git import GitCredentials
27
+ from .models import (
28
+ CommandResult,
29
+ EnvdHealth,
30
+ EnvdMetrics,
31
+ FileInfo,
32
+ FileType,
33
+ FileWatchEvent,
34
+ OomKill,
35
+ Page,
36
+ ProcessInfo,
37
+ PtySize,
38
+ SandboxInfo,
39
+ SandboxLifecycle,
40
+ SandboxState,
41
+ TemplateInfo,
42
+ )
43
+ from .sandbox import AsyncSandbox, Sandbox
44
+
45
+ __all__ = [
46
+ "AsyncCommandHandle",
47
+ "AsyncDevBox",
48
+ "AsyncEnvd",
49
+ "AsyncSandbox",
50
+ "AuthenticationError",
51
+ "CommandExitError",
52
+ "CommandHandle",
53
+ "CommandResult",
54
+ "ConfigurationError",
55
+ "ConflictError",
56
+ "DevBox",
57
+ "DevBoxError",
58
+ "Envd",
59
+ "EnvdHealth",
60
+ "EnvdMetrics",
61
+ "ErrorDetail",
62
+ "FileInfo",
63
+ "FileType",
64
+ "FileWatchEvent",
65
+ "GitCredentials",
66
+ "NotFoundError",
67
+ "OomKill",
68
+ "Page",
69
+ "PermissionDeniedError",
70
+ "ProcessInfo",
71
+ "ProtocolError",
72
+ "PtySize",
73
+ "RateLimitError",
74
+ "RequestTimeoutError",
75
+ "Sandbox",
76
+ "SandboxInfo",
77
+ "SandboxLifecycle",
78
+ "SandboxState",
79
+ "ServiceUnavailableError",
80
+ "TemplateInfo",
81
+ "ValidationError",
82
+ "__version__",
83
+ ]
devbox/_transport.py ADDED
@@ -0,0 +1,448 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import json
5
+ import time
6
+ from collections.abc import AsyncGenerator, Callable, Generator, Iterator, Mapping
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from ._version import __version__
12
+ from .errors import ProtocolError, raise_connect_error, raise_for_response, transport_error
13
+
14
+ _CONNECT_RETRY_DELAYS = (0.1, 0.2)
15
+ _CONNECT_ERRORS = (httpx.ConnectError, httpx.ConnectTimeout)
16
+ _CONNECT_HEADERS = {
17
+ "Connect-Protocol-Version": "1",
18
+ "Content-Type": "application/connect+json",
19
+ }
20
+ QueryParams = Mapping[str, str | int | float | bool | None]
21
+
22
+
23
+ class SyncTransport:
24
+ def __init__(
25
+ self,
26
+ base_url: str,
27
+ *,
28
+ headers: Mapping[str, str],
29
+ timeout: float,
30
+ transport: httpx.BaseTransport | None = None,
31
+ verify: bool = True,
32
+ response_hook: Callable[[httpx.Response], None] | None = None,
33
+ ) -> None:
34
+ request_headers = {"User-Agent": f"devbox-python-sdk/{__version__}", **headers}
35
+ event_hooks = {"response": [response_hook]} if response_hook else None
36
+ self._client = httpx.Client(
37
+ base_url=base_url.rstrip("/"),
38
+ headers=request_headers,
39
+ timeout=timeout,
40
+ transport=transport,
41
+ verify=verify,
42
+ event_hooks=event_hooks,
43
+ )
44
+
45
+ def request(
46
+ self,
47
+ method: str,
48
+ path: str,
49
+ *,
50
+ json_body: object | None = None,
51
+ params: QueryParams | None = None,
52
+ headers: Mapping[str, str] | None = None,
53
+ ) -> Any:
54
+ return _response_body(
55
+ self._send(method, path, json_body=json_body, params=params, headers=headers)
56
+ )
57
+
58
+ def request_content(
59
+ self,
60
+ method: str,
61
+ path: str,
62
+ content: bytes,
63
+ *,
64
+ params: QueryParams | None = None,
65
+ headers: Mapping[str, str] | None = None,
66
+ ) -> Any:
67
+ return _response_body(
68
+ self._send(method, path, content=content, params=params, headers=headers)
69
+ )
70
+
71
+ def request_with_headers(
72
+ self,
73
+ method: str,
74
+ path: str,
75
+ *,
76
+ json_body: object | None = None,
77
+ params: QueryParams | None = None,
78
+ headers: Mapping[str, str] | None = None,
79
+ ) -> tuple[Any, httpx.Headers]:
80
+ response = self._send(method, path, json_body=json_body, params=params, headers=headers)
81
+ return _response_body(response), response.headers
82
+
83
+ def request_bytes(
84
+ self,
85
+ method: str,
86
+ path: str,
87
+ *,
88
+ params: QueryParams | None = None,
89
+ headers: Mapping[str, str] | None = None,
90
+ ) -> bytes:
91
+ return self._send(method, path, params=params, headers=headers).content
92
+
93
+ def connect_unary(
94
+ self,
95
+ path: str,
96
+ json_body: object,
97
+ *,
98
+ headers: Mapping[str, str] | None = None,
99
+ ) -> Any:
100
+ request_headers = {
101
+ "Connect-Protocol-Version": "1",
102
+ "Content-Type": "application/json",
103
+ **dict(headers or {}),
104
+ }
105
+ return _response_body(
106
+ self._send("POST", path, json_body=json_body, headers=request_headers)
107
+ )
108
+
109
+ def connect_stream(
110
+ self,
111
+ path: str,
112
+ json_body: object,
113
+ *,
114
+ timeout: float | None = None,
115
+ headers: Mapping[str, str] | None = None,
116
+ ) -> Generator[Mapping[str, Any], None, None]:
117
+ request_headers = _connect_headers(timeout, headers)
118
+ network_timeout = httpx.Timeout(self._client.timeout)
119
+ network_timeout.read = _stream_timeout(timeout)
120
+ try:
121
+ with self._client.stream(
122
+ "POST",
123
+ path,
124
+ content=_connect_frame(json_body),
125
+ headers=request_headers,
126
+ timeout=network_timeout,
127
+ ) as response:
128
+ _reject_redirect(response)
129
+ if response.is_error:
130
+ response.read()
131
+ raise_for_response(response)
132
+ _validate_connect_response(response)
133
+ decoder = _ConnectDecoder()
134
+ for chunk in response.iter_bytes():
135
+ yield from decoder.feed(chunk)
136
+ decoder.finish()
137
+ except Exception as error:
138
+ mapped = transport_error(error)
139
+ if mapped is error:
140
+ raise
141
+ raise mapped from error
142
+
143
+ def close(self) -> None:
144
+ self._client.close()
145
+
146
+ def update_headers(self, headers: Mapping[str, str]) -> None:
147
+ self._client.headers.update(headers)
148
+
149
+ def __enter__(self) -> SyncTransport:
150
+ return self
151
+
152
+ def __exit__(self, *args: object) -> None:
153
+ self.close()
154
+
155
+ def _send(
156
+ self,
157
+ method: str,
158
+ path: str,
159
+ *,
160
+ json_body: object | None = None,
161
+ content: bytes | None = None,
162
+ params: QueryParams | None = None,
163
+ headers: Mapping[str, str] | None = None,
164
+ ) -> httpx.Response:
165
+ for attempt in range(len(_CONNECT_RETRY_DELAYS) + 1):
166
+ try:
167
+ response = self._client.request(
168
+ method,
169
+ path,
170
+ json=json_body,
171
+ content=content,
172
+ params=params,
173
+ headers=headers,
174
+ )
175
+ _reject_redirect(response)
176
+ if response.is_error:
177
+ raise_for_response(response)
178
+ return response
179
+ except Exception as error:
180
+ if isinstance(error, _CONNECT_ERRORS) and attempt < len(_CONNECT_RETRY_DELAYS):
181
+ time.sleep(_CONNECT_RETRY_DELAYS[attempt])
182
+ continue
183
+ mapped = transport_error(error)
184
+ if mapped is error:
185
+ raise
186
+ raise mapped from error
187
+ raise AssertionError("request retry loop did not return")
188
+
189
+
190
+ class AsyncTransport:
191
+ def __init__(
192
+ self,
193
+ base_url: str,
194
+ *,
195
+ headers: Mapping[str, str],
196
+ timeout: float,
197
+ transport: httpx.AsyncBaseTransport | None = None,
198
+ verify: bool = True,
199
+ response_hook: Callable[[httpx.Response], None] | None = None,
200
+ ) -> None:
201
+ request_headers = {"User-Agent": f"devbox-python-sdk/{__version__}", **headers}
202
+ event_hooks = None
203
+ if response_hook:
204
+
205
+ async def invoke_response_hook(response: httpx.Response) -> None:
206
+ response_hook(response)
207
+
208
+ event_hooks = {"response": [invoke_response_hook]}
209
+ self._client = httpx.AsyncClient(
210
+ base_url=base_url.rstrip("/"),
211
+ headers=request_headers,
212
+ timeout=timeout,
213
+ transport=transport,
214
+ verify=verify,
215
+ event_hooks=event_hooks,
216
+ )
217
+
218
+ async def request(
219
+ self,
220
+ method: str,
221
+ path: str,
222
+ *,
223
+ json_body: object | None = None,
224
+ params: QueryParams | None = None,
225
+ headers: Mapping[str, str] | None = None,
226
+ ) -> Any:
227
+ return _response_body(
228
+ await self._send(method, path, json_body=json_body, params=params, headers=headers)
229
+ )
230
+
231
+ async def request_content(
232
+ self,
233
+ method: str,
234
+ path: str,
235
+ content: bytes,
236
+ *,
237
+ params: QueryParams | None = None,
238
+ headers: Mapping[str, str] | None = None,
239
+ ) -> Any:
240
+ return _response_body(
241
+ await self._send(method, path, content=content, params=params, headers=headers)
242
+ )
243
+
244
+ async def request_with_headers(
245
+ self,
246
+ method: str,
247
+ path: str,
248
+ *,
249
+ json_body: object | None = None,
250
+ params: QueryParams | None = None,
251
+ headers: Mapping[str, str] | None = None,
252
+ ) -> tuple[Any, httpx.Headers]:
253
+ response = await self._send(
254
+ method, path, json_body=json_body, params=params, headers=headers
255
+ )
256
+ return _response_body(response), response.headers
257
+
258
+ async def request_bytes(
259
+ self,
260
+ method: str,
261
+ path: str,
262
+ *,
263
+ params: QueryParams | None = None,
264
+ headers: Mapping[str, str] | None = None,
265
+ ) -> bytes:
266
+ return (await self._send(method, path, params=params, headers=headers)).content
267
+
268
+ async def connect_unary(
269
+ self,
270
+ path: str,
271
+ json_body: object,
272
+ *,
273
+ headers: Mapping[str, str] | None = None,
274
+ ) -> Any:
275
+ request_headers = {
276
+ "Connect-Protocol-Version": "1",
277
+ "Content-Type": "application/json",
278
+ **dict(headers or {}),
279
+ }
280
+ return _response_body(
281
+ await self._send("POST", path, json_body=json_body, headers=request_headers)
282
+ )
283
+
284
+ async def connect_stream(
285
+ self,
286
+ path: str,
287
+ json_body: object,
288
+ *,
289
+ timeout: float | None = None,
290
+ headers: Mapping[str, str] | None = None,
291
+ ) -> AsyncGenerator[Mapping[str, Any], None]:
292
+ request_headers = _connect_headers(timeout, headers)
293
+ network_timeout = httpx.Timeout(self._client.timeout)
294
+ network_timeout.read = _stream_timeout(timeout)
295
+ try:
296
+ async with self._client.stream(
297
+ "POST",
298
+ path,
299
+ content=_connect_frame(json_body),
300
+ headers=request_headers,
301
+ timeout=network_timeout,
302
+ ) as response:
303
+ _reject_redirect(response)
304
+ if response.is_error:
305
+ await response.aread()
306
+ raise_for_response(response)
307
+ _validate_connect_response(response)
308
+ decoder = _ConnectDecoder()
309
+ async for chunk in response.aiter_bytes():
310
+ for event in decoder.feed(chunk):
311
+ yield event
312
+ decoder.finish()
313
+ except Exception as error:
314
+ mapped = transport_error(error)
315
+ if mapped is error:
316
+ raise
317
+ raise mapped from error
318
+
319
+ async def close(self) -> None:
320
+ await self._client.aclose()
321
+
322
+ def update_headers(self, headers: Mapping[str, str]) -> None:
323
+ self._client.headers.update(headers)
324
+
325
+ async def __aenter__(self) -> AsyncTransport:
326
+ return self
327
+
328
+ async def __aexit__(self, *args: object) -> None:
329
+ await self.close()
330
+
331
+ async def _send(
332
+ self,
333
+ method: str,
334
+ path: str,
335
+ *,
336
+ json_body: object | None = None,
337
+ content: bytes | None = None,
338
+ params: QueryParams | None = None,
339
+ headers: Mapping[str, str] | None = None,
340
+ ) -> httpx.Response:
341
+ for attempt in range(len(_CONNECT_RETRY_DELAYS) + 1):
342
+ try:
343
+ response = await self._client.request(
344
+ method,
345
+ path,
346
+ json=json_body,
347
+ content=content,
348
+ params=params,
349
+ headers=headers,
350
+ )
351
+ _reject_redirect(response)
352
+ if response.is_error:
353
+ raise_for_response(response)
354
+ return response
355
+ except Exception as error:
356
+ if isinstance(error, _CONNECT_ERRORS) and attempt < len(_CONNECT_RETRY_DELAYS):
357
+ await asyncio.sleep(_CONNECT_RETRY_DELAYS[attempt])
358
+ continue
359
+ mapped = transport_error(error)
360
+ if mapped is error:
361
+ raise
362
+ raise mapped from error
363
+ raise AssertionError("request retry loop did not return")
364
+
365
+
366
+ def _reject_redirect(response: httpx.Response) -> None:
367
+ if response.is_redirect:
368
+ raise ProtocolError("DevBox service returned an unexpected redirect")
369
+
370
+
371
+ class _ConnectDecoder:
372
+ def __init__(self) -> None:
373
+ self._buffer = bytearray()
374
+ self._ended = False
375
+
376
+ def feed(self, chunk: bytes) -> Iterator[Mapping[str, Any]]:
377
+ if self._ended and chunk:
378
+ raise ProtocolError("EnvD sent data after the Connect stream ended")
379
+ self._buffer.extend(chunk)
380
+ while len(self._buffer) >= 5:
381
+ flags = self._buffer[0]
382
+ size = int.from_bytes(self._buffer[1:5], "big")
383
+ if len(self._buffer) < size + 5:
384
+ return
385
+ data = bytes(self._buffer[5 : size + 5])
386
+ del self._buffer[: size + 5]
387
+ if flags & 1:
388
+ raise ProtocolError("compressed Connect messages are not supported")
389
+ payload = _decode_mapping(data)
390
+ if flags & 2:
391
+ self._ended = True
392
+ error = payload.get("error")
393
+ if isinstance(error, Mapping):
394
+ raise_connect_error(error)
395
+ if self._buffer:
396
+ raise ProtocolError("EnvD sent data after the Connect stream ended")
397
+ return
398
+ yield payload
399
+
400
+ def finish(self) -> None:
401
+ if self._buffer:
402
+ raise ProtocolError("EnvD returned a truncated Connect stream")
403
+ if not self._ended:
404
+ raise ProtocolError("EnvD closed the Connect stream without a trailer")
405
+
406
+
407
+ def _connect_headers(timeout: float | None, headers: Mapping[str, str] | None) -> dict[str, str]:
408
+ result = {**_CONNECT_HEADERS, **dict(headers or {})}
409
+ normalized_timeout = _stream_timeout(timeout)
410
+ if normalized_timeout:
411
+ result["Connect-Timeout-Ms"] = str(max(1, round(normalized_timeout * 1000)))
412
+ return result
413
+
414
+
415
+ def _connect_frame(value: object) -> bytes:
416
+ data = json.dumps(value, separators=(",", ":")).encode()
417
+ return bytes([0]) + len(data).to_bytes(4, "big") + data
418
+
419
+
420
+ def _stream_timeout(value: float | None) -> float | None:
421
+ if value is not None and value < 0:
422
+ raise ValueError("timeout must be non-negative or None")
423
+ return value if value and value > 0 else None
424
+
425
+
426
+ def _validate_connect_response(response: httpx.Response) -> None:
427
+ content_type = response.headers.get("Content-Type", "").split(";", 1)[0].lower()
428
+ if content_type != "application/connect+json":
429
+ raise ProtocolError("EnvD returned an invalid Connect content type")
430
+
431
+
432
+ def _decode_mapping(data: bytes) -> Mapping[str, Any]:
433
+ try:
434
+ value = json.loads(data)
435
+ except ValueError as error:
436
+ raise ProtocolError("EnvD returned invalid Connect JSON") from error
437
+ if not isinstance(value, Mapping):
438
+ raise ProtocolError("EnvD returned an invalid Connect message")
439
+ return value
440
+
441
+
442
+ def _response_body(response: httpx.Response) -> Any:
443
+ if response.status_code == 204 or not response.content:
444
+ return None
445
+ try:
446
+ return response.json()
447
+ except ValueError as error:
448
+ raise ProtocolError("DevBox returned invalid JSON") from error
devbox/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
devbox/client.py ADDED
@@ -0,0 +1,124 @@
1
+ """Client entry points for the DevBox Python SDK.
2
+
3
+ Both clients resolve the API key from the ``api_key`` argument or the
4
+ ``DEVBOX_API_KEY`` / ``E2B_API_KEY`` environment variables, and expose the
5
+ ``sandboxes`` and ``templates`` namespaces.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from types import TracebackType
12
+
13
+ import httpx
14
+
15
+ from ._transport import AsyncTransport, SyncTransport
16
+ from .config import ConnectionConfig
17
+ from .sandbox import AsyncSandboxes, Sandboxes
18
+ from .templates import AsyncTemplates, Templates
19
+
20
+
21
+ class DevBox:
22
+ """Reusable client for listing or operating multiple sandboxes.
23
+
24
+ Most applications can start with ``Sandbox.create()`` instead.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ *,
30
+ api_key: str | None = None,
31
+ api_url: str | None = None,
32
+ gateway_url: str | None = None,
33
+ request_timeout: float | None = None,
34
+ headers: Mapping[str, str] | None = None,
35
+ http_transport: httpx.BaseTransport | None = None,
36
+ ) -> None:
37
+ config = ConnectionConfig.resolve(
38
+ api_key=api_key,
39
+ api_url=api_url,
40
+ gateway_url=gateway_url,
41
+ request_timeout=request_timeout,
42
+ headers=headers,
43
+ )
44
+ request_headers = {**config.headers, "X-API-Key": config.api_key}
45
+ self._transport = SyncTransport(
46
+ config.api_url,
47
+ headers=request_headers,
48
+ timeout=config.control_timeout,
49
+ transport=http_transport,
50
+ )
51
+ self.sandboxes = Sandboxes(
52
+ self._transport,
53
+ config.request_timeout,
54
+ gateway_url=config.gateway_url,
55
+ )
56
+ self.templates = Templates(self._transport)
57
+
58
+ def close(self) -> None:
59
+ """Closes the shared control-plane transport and idle connections."""
60
+ self._transport.close()
61
+
62
+ def __enter__(self) -> DevBox:
63
+ return self
64
+
65
+ def __exit__(
66
+ self,
67
+ exc_type: type[BaseException] | None,
68
+ exc_value: BaseException | None,
69
+ traceback: TracebackType | None,
70
+ ) -> None:
71
+ self.close()
72
+
73
+
74
+ class AsyncDevBox:
75
+ """Asynchronous counterpart of :class:`DevBox`.
76
+
77
+ Most applications can start with ``await AsyncSandbox.create()`` instead.
78
+ """
79
+
80
+ def __init__(
81
+ self,
82
+ *,
83
+ api_key: str | None = None,
84
+ api_url: str | None = None,
85
+ gateway_url: str | None = None,
86
+ request_timeout: float | None = None,
87
+ headers: Mapping[str, str] | None = None,
88
+ http_transport: httpx.AsyncBaseTransport | None = None,
89
+ ) -> None:
90
+ config = ConnectionConfig.resolve(
91
+ api_key=api_key,
92
+ api_url=api_url,
93
+ gateway_url=gateway_url,
94
+ request_timeout=request_timeout,
95
+ headers=headers,
96
+ )
97
+ request_headers = {**config.headers, "X-API-Key": config.api_key}
98
+ self._transport = AsyncTransport(
99
+ config.api_url,
100
+ headers=request_headers,
101
+ timeout=config.control_timeout,
102
+ transport=http_transport,
103
+ )
104
+ self.sandboxes = AsyncSandboxes(
105
+ self._transport,
106
+ config.request_timeout,
107
+ gateway_url=config.gateway_url,
108
+ )
109
+ self.templates = AsyncTemplates(self._transport)
110
+
111
+ async def close(self) -> None:
112
+ """Closes the shared control-plane transport and idle connections."""
113
+ await self._transport.close()
114
+
115
+ async def __aenter__(self) -> AsyncDevBox:
116
+ return self
117
+
118
+ async def __aexit__(
119
+ self,
120
+ exc_type: type[BaseException] | None,
121
+ exc_value: BaseException | None,
122
+ traceback: TracebackType | None,
123
+ ) -> None:
124
+ await self.close()