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/sandbox.py ADDED
@@ -0,0 +1,1008 @@
1
+ """Sandbox lifecycle operations and the per-sandbox handles.
2
+
3
+ :class:`Sandbox` / :class:`AsyncSandbox` are the main entry points; they
4
+ carry the connection credentials and the ``commands`` / ``files`` / ``pty``
5
+ / ``git`` / ``envd`` data-plane namespaces.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import time
12
+ from collections.abc import Mapping, Sequence
13
+ from dataclasses import replace
14
+ from types import TracebackType
15
+ from typing import Any, Literal
16
+ from urllib.parse import quote
17
+
18
+ import httpx
19
+
20
+ from ._transport import AsyncTransport, SyncTransport
21
+ from .commands import AsyncCommands, Commands
22
+ from .config import ConnectionConfig, gateway_verify_tls
23
+ from .envd import AsyncEnvd, Envd
24
+ from .errors import ConflictError, DevBoxError, NotFoundError, ProtocolError
25
+ from .filesystem import AsyncFilesystem, Filesystem
26
+ from .git import AsyncGit, Git
27
+ from .models import (
28
+ Page,
29
+ SandboxConnection,
30
+ SandboxInfo,
31
+ SandboxLifecycle,
32
+ SandboxState,
33
+ )
34
+ from .pty import AsyncPty, Pty
35
+
36
+ _TOKEN_REFRESH_WINDOW_SECONDS = 300
37
+ _CONNECT_TOKEN_REFRESHED_HEADER = "X-Devbox-Connect-Token-Refreshed"
38
+ _CONNECT_TOKEN_EXPIRATION_HEADER = "X-Devbox-Connect-Token-Expiration"
39
+
40
+
41
+ class Sandboxes:
42
+ """Sandbox lifecycle operations bound to a reusable client."""
43
+
44
+ def __init__(
45
+ self,
46
+ transport: SyncTransport,
47
+ request_timeout: float = 30.0,
48
+ *,
49
+ gateway_url: str | None = None,
50
+ ) -> None:
51
+ self._transport = transport
52
+ self._request_timeout = request_timeout
53
+ self._gateway_url = gateway_url
54
+
55
+ def create(
56
+ self,
57
+ template: str = "default",
58
+ *,
59
+ timeout: int = 300,
60
+ envs: Mapping[str, str] | None = None,
61
+ metadata: Mapping[str, str] | None = None,
62
+ build_id: str | None = None,
63
+ lifecycle: SandboxLifecycle | None = None,
64
+ network: Mapping[str, bool] | None = None,
65
+ ) -> Sandbox:
66
+ """Create a sandbox from a template and return its handle.
67
+
68
+ The handle carries a live envd connection with fresh credentials.
69
+ """
70
+ payload = self._transport.request(
71
+ "POST",
72
+ "/sandboxes",
73
+ json_body=_create_body(
74
+ template,
75
+ timeout,
76
+ envs,
77
+ metadata,
78
+ build_id,
79
+ lifecycle,
80
+ network,
81
+ ),
82
+ )
83
+ info, connection = _sandbox_payload(payload)
84
+ return Sandbox(
85
+ self._transport,
86
+ info,
87
+ connection,
88
+ request_timeout=self._request_timeout,
89
+ gateway_url=self._gateway_url,
90
+ )
91
+
92
+ def connect(self, sandbox_id: str, *, timeout: int = 300) -> Sandbox:
93
+ """Fetch Gateway credentials, resuming a paused sandbox when needed."""
94
+ payload = self._transport.request(
95
+ "POST",
96
+ f"/sandboxes/{_id(sandbox_id)}/connect",
97
+ json_body={"timeout": _checked_timeout(timeout)},
98
+ )
99
+ info, connection = _sandbox_payload(payload)
100
+ return Sandbox(
101
+ self._transport,
102
+ info,
103
+ connection,
104
+ request_timeout=self._request_timeout,
105
+ gateway_url=self._gateway_url,
106
+ )
107
+
108
+ def get(self, sandbox_id: str) -> SandboxInfo:
109
+ """Return full details for a sandbox."""
110
+ return SandboxInfo.from_wire(
111
+ _mapping(self._transport.request("GET", f"/sandboxes/{_id(sandbox_id)}"))
112
+ )
113
+
114
+ def list(
115
+ self,
116
+ *,
117
+ template: str | None = None,
118
+ metadata: str | None = None,
119
+ states: Sequence[SandboxState | str] = (),
120
+ limit: int | None = None,
121
+ next_token: str | None = None,
122
+ started_after: str | None = None,
123
+ order: Literal["asc", "desc"] | None = None,
124
+ ) -> Page[SandboxInfo]:
125
+ """Return a filtered, paginated list of sandboxes."""
126
+ payload, headers = self._transport.request_with_headers(
127
+ "GET",
128
+ "/sandboxes",
129
+ params=_list_params(
130
+ metadata, states, limit, next_token, template, started_after, order
131
+ ),
132
+ )
133
+ return _sandbox_page(payload, headers.get("X-Next-Token"), headers.get("X-Total-Running"))
134
+
135
+
136
+ class AsyncSandboxes:
137
+ """Asynchronous sandbox lifecycle operations bound to a reusable client."""
138
+
139
+ def __init__(
140
+ self,
141
+ transport: AsyncTransport,
142
+ request_timeout: float = 30.0,
143
+ *,
144
+ gateway_url: str | None = None,
145
+ ) -> None:
146
+ self._transport = transport
147
+ self._request_timeout = request_timeout
148
+ self._gateway_url = gateway_url
149
+
150
+ async def create(
151
+ self,
152
+ template: str = "default",
153
+ *,
154
+ timeout: int = 300,
155
+ envs: Mapping[str, str] | None = None,
156
+ metadata: Mapping[str, str] | None = None,
157
+ build_id: str | None = None,
158
+ lifecycle: SandboxLifecycle | None = None,
159
+ network: Mapping[str, bool] | None = None,
160
+ ) -> AsyncSandbox:
161
+ """Create a sandbox from a template and return its handle.
162
+
163
+ The handle carries a live envd connection with fresh credentials.
164
+ """
165
+ payload = await self._transport.request(
166
+ "POST",
167
+ "/sandboxes",
168
+ json_body=_create_body(
169
+ template,
170
+ timeout,
171
+ envs,
172
+ metadata,
173
+ build_id,
174
+ lifecycle,
175
+ network,
176
+ ),
177
+ )
178
+ info, connection = _sandbox_payload(payload)
179
+ return AsyncSandbox(
180
+ self._transport,
181
+ info,
182
+ connection,
183
+ request_timeout=self._request_timeout,
184
+ gateway_url=self._gateway_url,
185
+ )
186
+
187
+ async def connect(self, sandbox_id: str, *, timeout: int = 300) -> AsyncSandbox:
188
+ """Fetch Gateway credentials, resuming a paused sandbox when needed."""
189
+ payload = await self._transport.request(
190
+ "POST",
191
+ f"/sandboxes/{_id(sandbox_id)}/connect",
192
+ json_body={"timeout": _checked_timeout(timeout)},
193
+ )
194
+ info, connection = _sandbox_payload(payload)
195
+ return AsyncSandbox(
196
+ self._transport,
197
+ info,
198
+ connection,
199
+ request_timeout=self._request_timeout,
200
+ gateway_url=self._gateway_url,
201
+ )
202
+
203
+ async def get(self, sandbox_id: str) -> SandboxInfo:
204
+ """Return full details for a sandbox."""
205
+ return SandboxInfo.from_wire(
206
+ _mapping(await self._transport.request("GET", f"/sandboxes/{_id(sandbox_id)}"))
207
+ )
208
+
209
+ async def list(
210
+ self,
211
+ *,
212
+ template: str | None = None,
213
+ metadata: str | None = None,
214
+ states: Sequence[SandboxState | str] = (),
215
+ limit: int | None = None,
216
+ next_token: str | None = None,
217
+ started_after: str | None = None,
218
+ order: Literal["asc", "desc"] | None = None,
219
+ ) -> Page[SandboxInfo]:
220
+ """Return a filtered, paginated list of sandboxes."""
221
+ payload, headers = await self._transport.request_with_headers(
222
+ "GET",
223
+ "/sandboxes",
224
+ params=_list_params(
225
+ metadata, states, limit, next_token, template, started_after, order
226
+ ),
227
+ )
228
+ return _sandbox_page(payload, headers.get("X-Next-Token"), headers.get("X-Total-Running"))
229
+
230
+
231
+ class Sandbox:
232
+ """The main synchronous entry point for one remote sandbox.
233
+
234
+ Runtime work is grouped by purpose: ``commands`` runs processes, ``files``
235
+ manages files, ``pty`` opens interactive terminals, and ``git`` performs
236
+ common repository operations.
237
+
238
+ Exiting its context manager deletes the remote sandbox. Call ``close()``
239
+ directly when only local connections should be released.
240
+ """
241
+
242
+ commands: Commands
243
+ files: Filesystem
244
+ pty: Pty
245
+ git: Git
246
+ envd: Envd
247
+
248
+ def __init__(
249
+ self,
250
+ control: SyncTransport,
251
+ info: SandboxInfo,
252
+ connection: SandboxConnection,
253
+ *,
254
+ owns_control: bool = False,
255
+ request_timeout: float = 30.0,
256
+ gateway_url: str | None = None,
257
+ ) -> None:
258
+ self._control = control
259
+ self._info = info
260
+ self._connection = connection
261
+ self._owns_control = owns_control
262
+ self._request_timeout = request_timeout
263
+ self._gateway_url_override = gateway_url
264
+ self._gateway: SyncTransport | None = None
265
+ self.commands = Commands(self._gateway_transport)
266
+ self.files = Filesystem(self._gateway_transport)
267
+ self.pty = Pty(self.commands, self._gateway_transport)
268
+ self.git = Git(self.commands)
269
+ self.envd = Envd(self._gateway_transport)
270
+
271
+ @classmethod
272
+ def create(
273
+ cls,
274
+ template: str = "default",
275
+ *,
276
+ timeout: int = 300,
277
+ envs: Mapping[str, str] | None = None,
278
+ metadata: Mapping[str, str] | None = None,
279
+ build_id: str | None = None,
280
+ lifecycle: SandboxLifecycle | None = None,
281
+ network: Mapping[str, bool] | None = None,
282
+ api_key: str | None = None,
283
+ api_url: str | None = None,
284
+ gateway_url: str | None = None,
285
+ request_timeout: float | None = None,
286
+ headers: Mapping[str, str] | None = None,
287
+ ) -> Sandbox:
288
+ """Create a sandbox and connect its runtime APIs."""
289
+ config, transport = _sync_control(
290
+ api_key,
291
+ api_url,
292
+ gateway_url,
293
+ request_timeout,
294
+ headers,
295
+ )
296
+ try:
297
+ sandbox = Sandboxes(
298
+ transport,
299
+ config.request_timeout,
300
+ gateway_url=config.gateway_url,
301
+ ).create(
302
+ template,
303
+ timeout=timeout,
304
+ envs=envs,
305
+ metadata=metadata,
306
+ build_id=build_id,
307
+ lifecycle=lifecycle,
308
+ network=network,
309
+ )
310
+ except BaseException:
311
+ transport.close()
312
+ raise
313
+ sandbox._owns_control = True
314
+ return sandbox
315
+
316
+ @classmethod
317
+ def connect(
318
+ cls,
319
+ sandbox_id: str,
320
+ *,
321
+ timeout: int = 300,
322
+ api_key: str | None = None,
323
+ api_url: str | None = None,
324
+ gateway_url: str | None = None,
325
+ request_timeout: float | None = None,
326
+ headers: Mapping[str, str] | None = None,
327
+ ) -> Sandbox:
328
+ """Fetch Gateway credentials; this does not itself open a data connection."""
329
+ config, transport = _sync_control(
330
+ api_key,
331
+ api_url,
332
+ gateway_url,
333
+ request_timeout,
334
+ headers,
335
+ )
336
+ try:
337
+ sandbox = Sandboxes(
338
+ transport,
339
+ config.request_timeout,
340
+ gateway_url=config.gateway_url,
341
+ ).connect(sandbox_id, timeout=timeout)
342
+ except BaseException:
343
+ transport.close()
344
+ raise
345
+ sandbox._owns_control = True
346
+ return sandbox
347
+
348
+ @property
349
+ def sandbox_id(self) -> str:
350
+ """The sandbox ID of this handle."""
351
+ return self._info.sandbox_id
352
+
353
+ @property
354
+ def info(self) -> SandboxInfo:
355
+ """Cached sandbox info (refreshed by :meth:`get_info`)."""
356
+ return self._info
357
+
358
+ @property
359
+ def envd_url(self) -> str:
360
+ return _gateway_url(self._connection, self._gateway_url_override)
361
+
362
+ def get_info(self) -> SandboxInfo:
363
+ """Fetch the latest sandbox state from the Manager."""
364
+ self._info = SandboxInfo.from_wire(
365
+ _mapping(self._control.request("GET", f"/sandboxes/{_id(self.sandbox_id)}"))
366
+ )
367
+ return self._info
368
+
369
+ def is_running(self) -> bool:
370
+ """Return whether the Manager reports the sandbox as running."""
371
+ try:
372
+ return self.get_info().state is SandboxState.RUNNING
373
+ except NotFoundError:
374
+ self._info = replace(self._info, state=SandboxState.STOPPED)
375
+ return False
376
+
377
+ def set_timeout(self, timeout: int) -> None:
378
+ """Set the remaining sandbox lifetime in seconds."""
379
+ self._control.request(
380
+ "POST",
381
+ f"/sandboxes/{_id(self.sandbox_id)}/timeout",
382
+ json_body={"timeout": _checked_timeout(timeout)},
383
+ )
384
+
385
+ def refresh(self, duration: int = 300) -> None:
386
+ """Extend expiration to at least now plus duration; never shorten it."""
387
+ self._control.request(
388
+ "POST",
389
+ f"/sandboxes/{_id(self.sandbox_id)}/refreshes",
390
+ json_body={"duration": _checked_timeout(duration)},
391
+ )
392
+
393
+ def pause(
394
+ self, *, memory: bool | None = None, mode: Literal["full", "filesystem"] | None = None
395
+ ) -> None:
396
+ """Save memory and disk, then close local runtime connections.
397
+
398
+ Manager does not expire paused sandbox records. Context manager exit
399
+ still deletes it; use ``close()`` to leave it available for resume.
400
+ """
401
+ self._control.request(
402
+ "POST", f"/sandboxes/{_id(self.sandbox_id)}/pause", json_body=_pause_body(memory, mode)
403
+ )
404
+ self._info = replace(self._info, state=SandboxState.PAUSED)
405
+ self._close_gateway()
406
+
407
+ def resume(self, *, timeout: int = 300) -> Sandbox:
408
+ """Resume a paused sandbox and replace this handle's previous connect token."""
409
+ payload = self._control.request(
410
+ "POST",
411
+ f"/sandboxes/{_id(self.sandbox_id)}/resume",
412
+ json_body={"timeout": _checked_timeout(timeout)},
413
+ )
414
+ info, connection = _sandbox_payload(payload)
415
+ self._close_gateway()
416
+ self._info, self._connection = info, connection
417
+ return self
418
+
419
+ def kill(self) -> bool:
420
+ """Delete the sandbox, returning whether it still existed."""
421
+ try:
422
+ self._control.request("DELETE", f"/sandboxes/{_id(self.sandbox_id)}")
423
+ except (NotFoundError, ConflictError) as error:
424
+ if isinstance(error, ConflictError) and error.code != "already_killed":
425
+ raise
426
+ self._info = replace(self._info, state=SandboxState.STOPPED)
427
+ return False
428
+ finally:
429
+ self._close_gateway()
430
+ self._info = replace(self._info, state=SandboxState.STOPPED)
431
+ return True
432
+
433
+ def close(self) -> None:
434
+ """Close local connections without deleting the remote sandbox."""
435
+ self._close_gateway()
436
+ if self._owns_control:
437
+ self._control.close()
438
+
439
+ def __enter__(self) -> Sandbox:
440
+ return self
441
+
442
+ def __exit__(
443
+ self,
444
+ exc_type: type[BaseException] | None,
445
+ exc_value: BaseException | None,
446
+ traceback: TracebackType | None,
447
+ ) -> None:
448
+ try:
449
+ self.kill()
450
+ except DevBoxError:
451
+ if exc_type is None:
452
+ raise
453
+ finally:
454
+ self.close()
455
+
456
+ def _gateway_transport(self) -> SyncTransport:
457
+ if self._info.state is SandboxState.PAUSED and not (
458
+ self._info.lifecycle and self._info.lifecycle.auto_resume
459
+ ):
460
+ raise ConflictError("sandbox is paused; call resume() or Sandbox.connect() first")
461
+ self._refresh_connection_if_needed()
462
+ if self._gateway is None:
463
+ self._gateway = SyncTransport(
464
+ _gateway_url(self._connection, self._gateway_url_override),
465
+ headers=_gateway_headers(self._connection),
466
+ timeout=self._request_timeout,
467
+ verify=gateway_verify_tls(),
468
+ response_hook=self._handle_refreshed_connect_token,
469
+ )
470
+ return self._gateway
471
+
472
+ def _refresh_connection_if_needed(self) -> None:
473
+ if not _token_needs_refresh(self._connection):
474
+ return
475
+ old_url = _gateway_url(self._connection, self._gateway_url_override)
476
+ payload = self._control.request(
477
+ "POST",
478
+ f"/sandboxes/{_id(self.sandbox_id)}/connect",
479
+ json_body={"resume": bool(self._info.lifecycle and self._info.lifecycle.auto_resume)},
480
+ )
481
+ info, connection = _sandbox_payload(payload)
482
+ self._info, self._connection = info, connection
483
+ if self._gateway is not None:
484
+ if old_url == _gateway_url(connection, self._gateway_url_override):
485
+ self._gateway.update_headers(_gateway_headers(connection))
486
+ else:
487
+ self._close_gateway()
488
+
489
+ def _handle_refreshed_connect_token(self, response: httpx.Response) -> None:
490
+ token = response.headers.get(_CONNECT_TOKEN_REFRESHED_HEADER)
491
+ if not token:
492
+ return
493
+ expiration = response.headers.get(_CONNECT_TOKEN_EXPIRATION_HEADER)
494
+ if expiration is None:
495
+ raise ProtocolError("gateway refreshed token without an expiration")
496
+ try:
497
+ token_expiration = int(expiration)
498
+ except ValueError as error:
499
+ raise ProtocolError("gateway refreshed token expiration is not an integer") from error
500
+ if token_expiration <= 0:
501
+ raise ProtocolError("gateway refreshed token expiration must be positive")
502
+ self._connection = replace(
503
+ self._connection,
504
+ connect_token=token,
505
+ envd_access_token=(
506
+ token
507
+ if self._connection.envd_access_token == self._connection.connect_token
508
+ else self._connection.envd_access_token
509
+ ),
510
+ token_expiration=token_expiration,
511
+ )
512
+ if self._gateway is not None:
513
+ self._gateway.update_headers(_gateway_headers(self._connection))
514
+
515
+ def _close_gateway(self) -> None:
516
+ if self._gateway is not None:
517
+ self._gateway.close()
518
+ self._gateway = None
519
+
520
+
521
+ class AsyncSandbox:
522
+ """Asynchronous counterpart of :class:`Sandbox` with automatic cleanup."""
523
+
524
+ commands: AsyncCommands
525
+ files: AsyncFilesystem
526
+ pty: AsyncPty
527
+ git: AsyncGit
528
+ envd: AsyncEnvd
529
+
530
+ def __init__(
531
+ self,
532
+ control: AsyncTransport,
533
+ info: SandboxInfo,
534
+ connection: SandboxConnection,
535
+ *,
536
+ owns_control: bool = False,
537
+ request_timeout: float = 30.0,
538
+ gateway_url: str | None = None,
539
+ ) -> None:
540
+ self._control = control
541
+ self._info = info
542
+ self._connection = connection
543
+ self._owns_control = owns_control
544
+ self._request_timeout = request_timeout
545
+ self._gateway_url_override = gateway_url
546
+ self._gateway: AsyncTransport | None = None
547
+ self.commands = AsyncCommands(self._gateway_transport)
548
+ self.files = AsyncFilesystem(self._gateway_transport)
549
+ self.pty = AsyncPty(self.commands, self._gateway_transport)
550
+ self.git = AsyncGit(self.commands)
551
+ self.envd = AsyncEnvd(self._gateway_transport)
552
+
553
+ @classmethod
554
+ async def create(
555
+ cls,
556
+ template: str = "default",
557
+ *,
558
+ timeout: int = 300,
559
+ envs: Mapping[str, str] | None = None,
560
+ metadata: Mapping[str, str] | None = None,
561
+ build_id: str | None = None,
562
+ lifecycle: SandboxLifecycle | None = None,
563
+ network: Mapping[str, bool] | None = None,
564
+ api_key: str | None = None,
565
+ api_url: str | None = None,
566
+ gateway_url: str | None = None,
567
+ request_timeout: float | None = None,
568
+ headers: Mapping[str, str] | None = None,
569
+ ) -> AsyncSandbox:
570
+ """Create a sandbox and connect its runtime APIs."""
571
+ config, transport = _async_control(
572
+ api_key,
573
+ api_url,
574
+ gateway_url,
575
+ request_timeout,
576
+ headers,
577
+ )
578
+ try:
579
+ sandbox = await AsyncSandboxes(
580
+ transport,
581
+ config.request_timeout,
582
+ gateway_url=config.gateway_url,
583
+ ).create(
584
+ template,
585
+ timeout=timeout,
586
+ envs=envs,
587
+ metadata=metadata,
588
+ build_id=build_id,
589
+ lifecycle=lifecycle,
590
+ network=network,
591
+ )
592
+ except BaseException:
593
+ await transport.close()
594
+ raise
595
+ sandbox._owns_control = True
596
+ return sandbox
597
+
598
+ @classmethod
599
+ async def connect(
600
+ cls,
601
+ sandbox_id: str,
602
+ *,
603
+ timeout: int = 300,
604
+ api_key: str | None = None,
605
+ api_url: str | None = None,
606
+ gateway_url: str | None = None,
607
+ request_timeout: float | None = None,
608
+ headers: Mapping[str, str] | None = None,
609
+ ) -> AsyncSandbox:
610
+ """Fetch Gateway credentials; this does not itself open a data connection."""
611
+ config, transport = _async_control(
612
+ api_key,
613
+ api_url,
614
+ gateway_url,
615
+ request_timeout,
616
+ headers,
617
+ )
618
+ try:
619
+ sandbox = await AsyncSandboxes(
620
+ transport,
621
+ config.request_timeout,
622
+ gateway_url=config.gateway_url,
623
+ ).connect(sandbox_id, timeout=timeout)
624
+ except BaseException:
625
+ await transport.close()
626
+ raise
627
+ sandbox._owns_control = True
628
+ return sandbox
629
+
630
+ @property
631
+ def sandbox_id(self) -> str:
632
+ """The sandbox ID of this handle."""
633
+ return self._info.sandbox_id
634
+
635
+ @property
636
+ def info(self) -> SandboxInfo:
637
+ """Cached sandbox info (refreshed by :meth:`get_info`)."""
638
+ return self._info
639
+
640
+ @property
641
+ def envd_url(self) -> str:
642
+ return _gateway_url(self._connection, self._gateway_url_override)
643
+
644
+ async def get_info(self) -> SandboxInfo:
645
+ """Fetch the latest sandbox state from the Manager."""
646
+ self._info = SandboxInfo.from_wire(
647
+ _mapping(await self._control.request("GET", f"/sandboxes/{_id(self.sandbox_id)}"))
648
+ )
649
+ return self._info
650
+
651
+ async def is_running(self) -> bool:
652
+ """Return whether the Manager reports the sandbox as running."""
653
+ try:
654
+ return (await self.get_info()).state is SandboxState.RUNNING
655
+ except NotFoundError:
656
+ self._info = replace(self._info, state=SandboxState.STOPPED)
657
+ return False
658
+
659
+ async def set_timeout(self, timeout: int) -> None:
660
+ """Set the sandbox time-to-live in seconds from now."""
661
+ await self._control.request(
662
+ "POST",
663
+ f"/sandboxes/{_id(self.sandbox_id)}/timeout",
664
+ json_body={"timeout": _checked_timeout(timeout)},
665
+ )
666
+
667
+ async def refresh(self, duration: int = 300) -> None:
668
+ """Extend expiration to at least now plus duration; never shorten it."""
669
+ await self._control.request(
670
+ "POST",
671
+ f"/sandboxes/{_id(self.sandbox_id)}/refreshes",
672
+ json_body={"duration": _checked_timeout(duration)},
673
+ )
674
+
675
+ async def pause(
676
+ self, *, memory: bool | None = None, mode: Literal["full", "filesystem"] | None = None
677
+ ) -> None:
678
+ """Save memory and disk; context manager exit still deletes the sandbox."""
679
+ await self._control.request(
680
+ "POST", f"/sandboxes/{_id(self.sandbox_id)}/pause", json_body=_pause_body(memory, mode)
681
+ )
682
+ self._info = replace(self._info, state=SandboxState.PAUSED)
683
+ await self._close_gateway()
684
+
685
+ async def resume(self, *, timeout: int = 300) -> AsyncSandbox:
686
+ """Resume a paused sandbox and replace this handle's previous connect token."""
687
+ payload = await self._control.request(
688
+ "POST",
689
+ f"/sandboxes/{_id(self.sandbox_id)}/resume",
690
+ json_body={"timeout": _checked_timeout(timeout)},
691
+ )
692
+ info, connection = _sandbox_payload(payload)
693
+ await self._close_gateway()
694
+ self._info, self._connection = info, connection
695
+ return self
696
+
697
+ async def kill(self) -> bool:
698
+ """Delete the sandbox, returning whether it still existed."""
699
+ try:
700
+ await self._control.request("DELETE", f"/sandboxes/{_id(self.sandbox_id)}")
701
+ except (NotFoundError, ConflictError) as error:
702
+ if isinstance(error, ConflictError) and error.code != "already_killed":
703
+ raise
704
+ self._info = replace(self._info, state=SandboxState.STOPPED)
705
+ return False
706
+ finally:
707
+ await self._close_gateway()
708
+ self._info = replace(self._info, state=SandboxState.STOPPED)
709
+ return True
710
+
711
+ async def close(self) -> None:
712
+ """Close local connections without deleting the remote sandbox."""
713
+ await self._close_gateway()
714
+ if self._owns_control:
715
+ await self._control.close()
716
+
717
+ async def __aenter__(self) -> AsyncSandbox:
718
+ return self
719
+
720
+ async def __aexit__(
721
+ self,
722
+ exc_type: type[BaseException] | None,
723
+ exc_value: BaseException | None,
724
+ traceback: TracebackType | None,
725
+ ) -> None:
726
+ try:
727
+ await self.kill()
728
+ except DevBoxError:
729
+ if exc_type is None:
730
+ raise
731
+ finally:
732
+ await self.close()
733
+
734
+ async def _gateway_transport(self) -> AsyncTransport:
735
+ if self._info.state is SandboxState.PAUSED and not (
736
+ self._info.lifecycle and self._info.lifecycle.auto_resume
737
+ ):
738
+ raise ConflictError("sandbox is paused; call resume() or AsyncSandbox.connect() first")
739
+ await self._refresh_connection_if_needed()
740
+ if self._gateway is None:
741
+ self._gateway = AsyncTransport(
742
+ _gateway_url(self._connection, self._gateway_url_override),
743
+ headers=_gateway_headers(self._connection),
744
+ timeout=self._request_timeout,
745
+ verify=gateway_verify_tls(),
746
+ response_hook=self._handle_refreshed_connect_token,
747
+ )
748
+ return self._gateway
749
+
750
+ async def _refresh_connection_if_needed(self) -> None:
751
+ if not _token_needs_refresh(self._connection):
752
+ return
753
+ old_url = _gateway_url(self._connection, self._gateway_url_override)
754
+ payload = await self._control.request(
755
+ "POST",
756
+ f"/sandboxes/{_id(self.sandbox_id)}/connect",
757
+ json_body={"resume": bool(self._info.lifecycle and self._info.lifecycle.auto_resume)},
758
+ )
759
+ info, connection = _sandbox_payload(payload)
760
+ self._info, self._connection = info, connection
761
+ if self._gateway is not None:
762
+ if old_url == _gateway_url(connection, self._gateway_url_override):
763
+ self._gateway.update_headers(_gateway_headers(connection))
764
+ else:
765
+ await self._close_gateway()
766
+
767
+ def _handle_refreshed_connect_token(self, response: httpx.Response) -> None:
768
+ token = response.headers.get(_CONNECT_TOKEN_REFRESHED_HEADER)
769
+ if not token:
770
+ return
771
+ expiration = response.headers.get(_CONNECT_TOKEN_EXPIRATION_HEADER)
772
+ if expiration is None:
773
+ raise ProtocolError("gateway refreshed token without an expiration")
774
+ try:
775
+ token_expiration = int(expiration)
776
+ except ValueError as error:
777
+ raise ProtocolError("gateway refreshed token expiration is not an integer") from error
778
+ if token_expiration <= 0:
779
+ raise ProtocolError("gateway refreshed token expiration must be positive")
780
+ self._connection = replace(
781
+ self._connection,
782
+ connect_token=token,
783
+ envd_access_token=(
784
+ token
785
+ if self._connection.envd_access_token == self._connection.connect_token
786
+ else self._connection.envd_access_token
787
+ ),
788
+ token_expiration=token_expiration,
789
+ )
790
+ if self._gateway is not None:
791
+ self._gateway.update_headers(_gateway_headers(self._connection))
792
+
793
+ async def _close_gateway(self) -> None:
794
+ if self._gateway is not None:
795
+ await self._gateway.close()
796
+ self._gateway = None
797
+
798
+
799
+ def _sync_control(
800
+ api_key: str | None,
801
+ api_url: str | None,
802
+ gateway_url: str | None,
803
+ request_timeout: float | None,
804
+ headers: Mapping[str, str] | None,
805
+ ) -> tuple[ConnectionConfig, SyncTransport]:
806
+ config = ConnectionConfig.resolve(
807
+ api_key=api_key,
808
+ api_url=api_url,
809
+ gateway_url=gateway_url,
810
+ request_timeout=request_timeout,
811
+ headers=headers,
812
+ )
813
+ return config, SyncTransport(
814
+ config.api_url,
815
+ headers={**config.headers, "X-API-Key": config.api_key},
816
+ timeout=config.control_timeout,
817
+ )
818
+
819
+
820
+ def _async_control(
821
+ api_key: str | None,
822
+ api_url: str | None,
823
+ gateway_url: str | None,
824
+ request_timeout: float | None,
825
+ headers: Mapping[str, str] | None,
826
+ ) -> tuple[ConnectionConfig, AsyncTransport]:
827
+ config = ConnectionConfig.resolve(
828
+ api_key=api_key,
829
+ api_url=api_url,
830
+ gateway_url=gateway_url,
831
+ request_timeout=request_timeout,
832
+ headers=headers,
833
+ )
834
+ return config, AsyncTransport(
835
+ config.api_url,
836
+ headers={**config.headers, "X-API-Key": config.api_key},
837
+ timeout=config.control_timeout,
838
+ )
839
+
840
+
841
+ def _create_body(
842
+ template: str,
843
+ timeout: int,
844
+ envs: Mapping[str, str] | None,
845
+ metadata: Mapping[str, str] | None,
846
+ build_id: str | None,
847
+ lifecycle: SandboxLifecycle | None,
848
+ network: Mapping[str, bool] | None = None,
849
+ ) -> dict[str, object]:
850
+ if not template.strip():
851
+ raise ValueError("template must not be blank")
852
+ body: dict[str, object] = {
853
+ "templateID": template,
854
+ "timeout": _checked_timeout(timeout),
855
+ "metadata": dict(metadata or {}),
856
+ "envVars": dict(envs or {}),
857
+ }
858
+ if build_id:
859
+ body["buildID"] = build_id
860
+ if lifecycle is not None:
861
+ if lifecycle.on_timeout not in {"kill", "pause"}:
862
+ raise ValueError("lifecycle.on_timeout must be 'kill' or 'pause'")
863
+ if lifecycle.auto_resume and lifecycle.on_timeout != "pause":
864
+ raise ValueError("lifecycle.auto_resume requires on_timeout='pause'")
865
+ body["autoPause"] = lifecycle.on_timeout == "pause"
866
+ body["autoResume"] = {"enabled": lifecycle.auto_resume}
867
+ body["lifecycle"] = {
868
+ "onTimeout": lifecycle.on_timeout,
869
+ "autoResume": lifecycle.auto_resume,
870
+ }
871
+ if network is not None:
872
+ if not isinstance(network, Mapping) or set(network) - {"allow_public_traffic"}:
873
+ raise ValueError("network only supports allow_public_traffic")
874
+ if "allow_public_traffic" in network and not isinstance(
875
+ network["allow_public_traffic"], bool
876
+ ):
877
+ raise ValueError("network.allow_public_traffic must be a boolean")
878
+ body["network"] = (
879
+ {"allowPublicTraffic": network["allow_public_traffic"]}
880
+ if "allow_public_traffic" in network
881
+ else {}
882
+ )
883
+ return body
884
+
885
+
886
+ def _pause_body(memory: bool | None, mode: str | None) -> dict[str, bool] | None:
887
+ if memory is False or mode == "filesystem":
888
+ raise ValueError("Only full memory snapshots are supported")
889
+ if memory is not None and not isinstance(memory, bool):
890
+ raise ValueError("memory must be a boolean")
891
+ if mode is not None and mode != "full":
892
+ raise ValueError("mode must be full")
893
+ return {"memory": True} if memory is not None or mode is not None else None
894
+
895
+
896
+ def _sandbox_payload(value: object) -> tuple[SandboxInfo, SandboxConnection]:
897
+ payload = _mapping(value)
898
+ info = SandboxInfo.from_wire(payload)
899
+ return info, SandboxConnection.from_wire(payload, info.sandbox_id)
900
+
901
+
902
+ def _sandbox_page(value: object, next_token: str | None, total: str | None) -> Page[SandboxInfo]:
903
+ return Page(
904
+ tuple(SandboxInfo.from_wire(item) for item in _items(value)),
905
+ next_token or None,
906
+ _response_integer(total, "X-Total-Running") if total else None,
907
+ )
908
+
909
+
910
+ def _list_params(
911
+ metadata: str | None,
912
+ states: Sequence[SandboxState | str],
913
+ limit: int | None,
914
+ next_token: str | None,
915
+ template: str | None = None,
916
+ started_after: str | None = None,
917
+ order: Literal["asc", "desc"] | None = None,
918
+ ) -> dict[str, str | int]:
919
+ params: dict[str, str | int] = {}
920
+ if template:
921
+ params["template"] = template
922
+ if metadata:
923
+ params["metadata"] = metadata
924
+ if states:
925
+ params["state"] = ",".join(
926
+ item.value if isinstance(item, SandboxState) else item for item in states
927
+ )
928
+ if limit is not None:
929
+ if isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= 1000:
930
+ raise ValueError("limit must be an integer between 0 and 1000 (0 means no limit)")
931
+ params["limit"] = limit
932
+ if next_token:
933
+ params["nextToken"] = next_token
934
+ if started_after:
935
+ params["startedAfter"] = started_after
936
+ if order is not None:
937
+ if order not in ("asc", "desc"):
938
+ raise ValueError("order must be asc or desc")
939
+ params["order"] = order
940
+ return params
941
+
942
+
943
+ def _items(value: object) -> tuple[Mapping[str, Any], ...]:
944
+ if not isinstance(value, list | tuple):
945
+ raise ProtocolError("DevBox returned an invalid list response")
946
+ return tuple(_mapping(item) for item in value)
947
+
948
+
949
+ def _mapping(value: object) -> Mapping[str, Any]:
950
+ if not isinstance(value, Mapping):
951
+ raise ProtocolError("DevBox returned an invalid object response")
952
+ return value
953
+
954
+
955
+ def _checked_timeout(timeout: int) -> int:
956
+ if isinstance(timeout, bool) or not isinstance(timeout, int) or not 10 <= timeout <= 86400:
957
+ raise ValueError("timeout must be an integer between 10 and 86400 seconds")
958
+ return timeout
959
+
960
+
961
+ def _response_integer(value: str, field: str) -> int:
962
+ try:
963
+ return int(value)
964
+ except ValueError as error:
965
+ raise ProtocolError(f"DevBox response header is not an integer: {field}") from error
966
+
967
+
968
+ def _id(value: str) -> str:
969
+ if not value:
970
+ raise ValueError("identifier must not be blank")
971
+ return quote(value, safe="")
972
+
973
+
974
+ def _gateway_headers(connection: SandboxConnection) -> dict[str, str]:
975
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", connection.connect_token):
976
+ raise ProtocolError("sandbox response does not provide a valid connectToken")
977
+ headers = {
978
+ "Cookie": f"relay_token={connection.connect_token}",
979
+ "E2B-Sandbox-Id": connection.sandbox_id,
980
+ "E2B-Sandbox-Port": "49983",
981
+ }
982
+ if connection.envd_access_token:
983
+ if not re.fullmatch(r"[A-Za-z0-9._-]+", connection.envd_access_token):
984
+ raise ProtocolError("sandbox response does not provide a valid envdAccessToken")
985
+ headers["X-Access-Token"] = connection.envd_access_token
986
+ return headers
987
+
988
+
989
+ def _token_needs_refresh(connection: SandboxConnection) -> bool:
990
+ return (
991
+ connection.token_expiration is not None
992
+ and connection.token_expiration <= int(time.time()) + _TOKEN_REFRESH_WINDOW_SECONDS
993
+ )
994
+
995
+
996
+ def _gateway_url(connection: SandboxConnection, configured_url: str | None = None) -> str:
997
+ if configured_url:
998
+ if "{tunnel_id}" in configured_url and not connection.tunnel_id:
999
+ raise ProtocolError("sandbox response does not provide a tunnel ID")
1000
+ return configured_url.replace("{tunnel_id}", connection.tunnel_id).replace(
1001
+ "{port}", "49983"
1002
+ )
1003
+ url = connection.domain
1004
+ if not url:
1005
+ raise ProtocolError("sandbox response does not provide an EnvD endpoint")
1006
+ if url.removeprefix("https://").endswith(".sandbox.devbox.local"):
1007
+ raise ProtocolError("Manager returned a placeholder EnvD endpoint")
1008
+ return url