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/models.py ADDED
@@ -0,0 +1,455 @@
1
+ """Data models and wire (API payload) parsing for the DevBox Python SDK.
2
+
3
+ The ``from_wire`` classmethods accept the documented field names and common
4
+ snake_case variants, and raise :class:`ProtocolError` on invalid values.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass, field
12
+ from datetime import datetime, timezone
13
+ from enum import Enum
14
+ from typing import Any, Generic, Literal, TypeVar, cast
15
+
16
+ from .errors import ProtocolError
17
+
18
+
19
+ class SandboxState(str, Enum):
20
+ """Lifecycle states of a sandbox as reported by the Manager API."""
21
+
22
+ RUNNING = "running"
23
+ PAUSED = "paused"
24
+ STOPPED = "stopped"
25
+
26
+
27
+ class FileType(str, Enum):
28
+ """Entry types returned by the sandbox filesystem."""
29
+
30
+ FILE = "file"
31
+ DIRECTORY = "directory"
32
+ SYMLINK = "symlink"
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class SandboxLifecycle:
37
+ """Deadline behavior requested at sandbox creation."""
38
+
39
+ on_timeout: Literal["kill", "pause"] = "kill"
40
+ auto_resume: bool = False
41
+
42
+ @classmethod
43
+ def from_wire(cls, value: object) -> SandboxLifecycle | None:
44
+ """Parses a lifecycle payload; returns ``None`` when absent."""
45
+ if not isinstance(value, Mapping):
46
+ return None
47
+ on_timeout = str(value.get("onTimeout", "kill"))
48
+ if on_timeout not in {"kill", "pause"}:
49
+ raise ProtocolError("DevBox returned an invalid sandbox lifecycle")
50
+ return cls(
51
+ auto_resume=bool(value.get("autoResume", False)),
52
+ on_timeout=cast(Literal["kill", "pause"], on_timeout),
53
+ )
54
+
55
+
56
+ @dataclass(frozen=True, slots=True)
57
+ class TemplateInfo:
58
+ """A sandbox template: an image with its default resource footprint."""
59
+
60
+ template_id: str
61
+ name: str
62
+ aliases: tuple[str, ...]
63
+ build_id: str
64
+ cpu_count: int
65
+ memory_mb: int
66
+ disk_size_mb: int
67
+ names: tuple[str, ...] = ()
68
+
69
+ @classmethod
70
+ def from_wire(cls, value: Mapping[str, Any]) -> TemplateInfo:
71
+ """Parses a Manager API template payload."""
72
+ return cls(
73
+ template_id=str(_pick(value, "templateId", "templateID", "template_id")),
74
+ name=str(
75
+ value.get("name")
76
+ or next(iter(_string_tuple(value.get("names"))), value.get("templateID", ""))
77
+ ),
78
+ aliases=_string_tuple(value.get("aliases")),
79
+ build_id=str(_pick(value, "buildId", "buildID", "build_id")),
80
+ cpu_count=_integer(_pick(value, "cpuCount")),
81
+ memory_mb=_integer(_pick(value, "memoryMB", "memoryMb", "memory_mb")),
82
+ disk_size_mb=_integer(_pick(value, "diskSizeMB", "diskSizeMb", "disk_size_mb")),
83
+ names=_string_tuple(value.get("names")),
84
+ )
85
+
86
+
87
+ @dataclass(frozen=True, slots=True)
88
+ class SandboxInfo:
89
+ """Sandbox details as reported by the Manager API."""
90
+
91
+ sandbox_id: str
92
+ template_id: str
93
+ state: SandboxState
94
+ started_at: datetime | None = None
95
+ end_at: datetime | None = None
96
+ cpu_count: int | None = None
97
+ memory_mb: int | None = None
98
+ disk_size_mb: int | None = None
99
+ metadata: Mapping[str, str] = field(default_factory=dict)
100
+ lifecycle: SandboxLifecycle | None = None
101
+
102
+ @classmethod
103
+ def from_wire(cls, value: Mapping[str, Any]) -> SandboxInfo:
104
+ """Parses a Manager API sandbox payload."""
105
+ return cls(
106
+ sandbox_id=str(_pick(value, "sandboxId", "sandboxID", "sandbox_id", "id")),
107
+ template_id=str(
108
+ _pick(value, "templateId", "templateID", "template_id", default="default")
109
+ ),
110
+ state=_enum(SandboxState, _pick(value, "state", "status", default="running")),
111
+ started_at=parse_optional_datetime(
112
+ _pick(value, "createdAt", "created_at", "startedAt", "started_at", default=None)
113
+ ),
114
+ end_at=parse_optional_datetime(
115
+ _pick(value, "expiresAt", "expires_at", "endAt", "end_at", default=None)
116
+ ),
117
+ cpu_count=_optional_int(value.get("cpuCount")),
118
+ memory_mb=_optional_int(value.get("memoryMB")),
119
+ disk_size_mb=_optional_int(value.get("diskSizeMB")),
120
+ metadata=_string_map(value.get("metadata")),
121
+ lifecycle=SandboxLifecycle.from_wire(value.get("lifecycle")),
122
+ )
123
+
124
+
125
+ @dataclass(frozen=True, slots=True)
126
+ class SandboxConnection:
127
+ """Connection credentials for the sandbox-local envd service."""
128
+
129
+ sandbox_id: str
130
+ domain: str
131
+ tunnel_id: str = ""
132
+ connect_token: str = field(default="", repr=False)
133
+ token_expiration: int | None = None
134
+ envd_access_token: str = field(default="", repr=False)
135
+
136
+ @classmethod
137
+ def from_wire(cls, value: Mapping[str, Any], sandbox_id: str) -> SandboxConnection:
138
+ """Parses a connect/create/resume payload; normalizes the envd
139
+ endpoint to a complete HTTPS URL and fills the connect token from
140
+ ``connectToken`` or ``envdAccessToken``."""
141
+ domain = str(value.get("domain") or "")
142
+ url = value.get("envdUrl")
143
+ if not url:
144
+ url = domain
145
+ if (
146
+ value.get("envdAccessToken")
147
+ and not value.get("connectToken")
148
+ and "://" not in domain
149
+ ):
150
+ url = f"https://49983-{sandbox_id}.{domain}" if domain else ""
151
+ return cls(
152
+ sandbox_id=sandbox_id,
153
+ domain=_domain(url),
154
+ tunnel_id=str(value.get("tunnelId") or ""),
155
+ connect_token=str(value.get("connectToken", value.get("envdAccessToken")) or ""),
156
+ token_expiration=_optional_int(value.get("tokenExpiration")),
157
+ envd_access_token=str(value.get("envdAccessToken") or ""),
158
+ )
159
+
160
+
161
+ @dataclass(frozen=True, slots=True)
162
+ class ProcessInfo:
163
+ """A process running (or previously run) in the sandbox."""
164
+
165
+ pid: int
166
+ command: str
167
+ running: bool
168
+ started_at: datetime | None = None
169
+
170
+ @classmethod
171
+ def from_wire(cls, value: Mapping[str, Any]) -> ProcessInfo:
172
+ """Parses a process list entry."""
173
+ config = value.get("config")
174
+ process = config if isinstance(config, Mapping) else value
175
+ cmd = str(_pick(process, "command", "cmd", default=""))
176
+ args = _string_tuple(process.get("args"))
177
+ return cls(
178
+ pid=_integer(_pick(value, "pid")),
179
+ command=" ".join((cmd, *args)).strip(),
180
+ running=bool(_pick(value, "running", default=True)),
181
+ started_at=parse_optional_datetime(
182
+ _pick(value, "startedAt", "started_at", default=None)
183
+ ),
184
+ )
185
+
186
+
187
+ @dataclass(frozen=True, slots=True)
188
+ class OutputChunk:
189
+ """One decoded chunk of command output."""
190
+
191
+ stream: str
192
+ data: str
193
+ timestamp: datetime | None = None
194
+
195
+
196
+ @dataclass(frozen=True, slots=True)
197
+ class CommandResult:
198
+ """Final result of a completed command."""
199
+
200
+ exit_code: int
201
+ stdout: str = ""
202
+ stderr: str = ""
203
+ pid: int | None = None
204
+
205
+
206
+ @dataclass(frozen=True, slots=True)
207
+ class PtySize:
208
+ """Terminal dimensions for PTY sessions."""
209
+
210
+ rows: int = 24
211
+ cols: int = 80
212
+
213
+ def __post_init__(self) -> None:
214
+ if self.rows < 1 or self.cols < 1:
215
+ raise ValueError("PTY rows and cols must be positive")
216
+
217
+
218
+ @dataclass(frozen=True, slots=True)
219
+ class EnvdHealth:
220
+ """Health info of the sandbox-local envd service."""
221
+
222
+ envd_version: str
223
+
224
+
225
+ @dataclass(frozen=True, slots=True)
226
+ class OomKill:
227
+ """One guest-kernel OOM kill event."""
228
+
229
+ seq: int
230
+ process: str
231
+
232
+ @classmethod
233
+ def from_wire(cls, value: Mapping[str, Any]) -> OomKill:
234
+ """Parses an envd OOM kill entry."""
235
+ return cls(seq=_integer(_pick(value, "seq")), process=str(_pick(value, "process")))
236
+
237
+
238
+ @dataclass(frozen=True, slots=True)
239
+ class EnvdMetrics:
240
+ """CPU, memory and disk usage of the sandbox, as reported by envd."""
241
+
242
+ timestamp: datetime
243
+ cpu_count: int
244
+ cpu_used_pct: float
245
+ mem_total: int
246
+ mem_used: int
247
+ mem_cache: int
248
+ disk_total: int
249
+ disk_used: int
250
+ oom_kills: tuple[OomKill, ...] | None = None
251
+ cpu_possible: int | None = None
252
+ cpu_target: int | None = None
253
+ cpu_target_attempts: int | None = None
254
+ cpu_write_pending_ms: int | None = None
255
+
256
+ @classmethod
257
+ def from_wire(cls, value: Mapping[str, Any]) -> EnvdMetrics:
258
+ """Parses an envd ``/metrics`` payload."""
259
+ timestamp = parse_optional_datetime(_pick(value, "ts"))
260
+ if timestamp is None:
261
+ raise ProtocolError("EnvD metrics response field is missing: ts")
262
+ oom_kills: tuple[OomKill, ...] | None = None
263
+ raw_oom_kills = value.get("oom_kills")
264
+ if raw_oom_kills is not None:
265
+ if not isinstance(raw_oom_kills, list) or not all(
266
+ isinstance(entry, Mapping) for entry in raw_oom_kills
267
+ ):
268
+ raise ProtocolError("EnvD metrics response field is invalid: oom_kills")
269
+ oom_kills = tuple(OomKill.from_wire(entry) for entry in raw_oom_kills)
270
+ return cls(
271
+ timestamp=timestamp,
272
+ cpu_count=_integer(_pick(value, "cpu_count")),
273
+ cpu_used_pct=_number(_pick(value, "cpu_used_pct")),
274
+ mem_total=_integer(_pick(value, "mem_total")),
275
+ mem_used=_integer(_pick(value, "mem_used")),
276
+ mem_cache=_integer(_pick(value, "mem_cache")),
277
+ disk_total=_integer(_pick(value, "disk_total")),
278
+ disk_used=_integer(_pick(value, "disk_used")),
279
+ oom_kills=oom_kills,
280
+ cpu_possible=_optional_int(value.get("cpu_possible")),
281
+ cpu_target=_optional_int(value.get("cpu_target")),
282
+ cpu_target_attempts=_optional_int(value.get("cpu_target_attempts")),
283
+ cpu_write_pending_ms=_optional_int(value.get("cpu_write_pending_ms")),
284
+ )
285
+
286
+
287
+ @dataclass(frozen=True, slots=True)
288
+ class FileInfo:
289
+ """Metadata of a file or directory in the sandbox."""
290
+
291
+ name: str
292
+ path: str
293
+ type: FileType
294
+ size: int
295
+ mode: int | None = None
296
+ permissions: str | None = None
297
+ owner: str | None = None
298
+ group: str | None = None
299
+ modified_at: datetime | None = None
300
+ symlink_target: str | None = None
301
+
302
+ @classmethod
303
+ def from_wire(cls, value: Mapping[str, Any]) -> FileInfo:
304
+ """Parses a filesystem entry; raises on unknown file types."""
305
+ file_type = {
306
+ "FILE_TYPE_FILE": FileType.FILE,
307
+ "FILE_TYPE_DIRECTORY": FileType.DIRECTORY,
308
+ "FILE_TYPE_SYMLINK": FileType.SYMLINK,
309
+ }.get(str(_pick(value, "type", default="file")))
310
+ return cls(
311
+ name=str(_pick(value, "name")),
312
+ path=str(_pick(value, "path")),
313
+ type=file_type or _enum(FileType, _pick(value, "type", default="file")),
314
+ size=_integer(_pick(value, "size", default=0)),
315
+ mode=_optional_int(value.get("mode")),
316
+ permissions=_optional_str(value.get("permissions")),
317
+ owner=_optional_str(value.get("owner")),
318
+ group=_optional_str(value.get("group")),
319
+ modified_at=parse_optional_datetime(
320
+ _pick(value, "modifiedTime", "modifiedAt", "modified_at", default=None)
321
+ ),
322
+ symlink_target=_optional_str(
323
+ _pick(value, "symlinkTarget", "symlink_target", default=None)
324
+ ),
325
+ )
326
+
327
+
328
+ @dataclass(frozen=True, slots=True)
329
+ class FileWatchEvent:
330
+ """One change event from :meth:`Filesystem.watch`."""
331
+
332
+ name: str
333
+ type: str
334
+ path: str | None = None
335
+ entry: FileInfo | None = None
336
+
337
+ @classmethod
338
+ def from_wire(cls, value: Mapping[str, Any]) -> FileWatchEvent:
339
+ """Parses a filesystem watch event."""
340
+ raw_entry = value.get("entry")
341
+ return cls(
342
+ name=str(value.get("name", "")),
343
+ type=str(value.get("type", value.get("operation", ""))),
344
+ path=_optional_str(value.get("path")),
345
+ entry=FileInfo.from_wire(raw_entry) if isinstance(raw_entry, Mapping) else None,
346
+ )
347
+
348
+
349
+ T = TypeVar("T")
350
+
351
+
352
+ @dataclass(frozen=True, slots=True)
353
+ class Page(Generic[T]):
354
+ """A paginated list result with the server-provided continuation token."""
355
+
356
+ items: tuple[T, ...]
357
+ next_token: str | None = None
358
+ total: int | None = None
359
+
360
+
361
+ def parse_optional_datetime(value: object) -> datetime | None:
362
+ """Parses a timestamp (ISO text, epoch seconds or datetime) to UTC-aware
363
+ :class:`datetime`; returns ``None`` for empty input."""
364
+ if value is None or value == "":
365
+ return None
366
+ if isinstance(value, datetime):
367
+ return value if value.tzinfo else value.replace(tzinfo=timezone.utc)
368
+ try:
369
+ if isinstance(value, int | float):
370
+ return datetime.fromtimestamp(value, timezone.utc)
371
+ text = str(value).replace("Z", "+00:00")
372
+ parsed = datetime.fromisoformat(text)
373
+ except (OSError, OverflowError, ValueError) as error:
374
+ raise ProtocolError("DevBox returned an invalid timestamp") from error
375
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
376
+
377
+
378
+ def _pick(value: Mapping[str, Any], *keys: str, default: object = ...) -> object:
379
+ for key in keys:
380
+ if key in value:
381
+ return value[key]
382
+ if default is not ...:
383
+ return default
384
+ raise ProtocolError(f"DevBox response field is missing: {keys[0]}")
385
+
386
+
387
+ def _string_map(value: object) -> Mapping[str, str]:
388
+ if not isinstance(value, Mapping):
389
+ return {}
390
+ return {str(key): str(item) for key, item in value.items()}
391
+
392
+
393
+ def _optional_str(value: object) -> str | None:
394
+ return None if value is None else str(value)
395
+
396
+
397
+ def _optional_int(value: object) -> int | None:
398
+ return None if value is None else _integer(value)
399
+
400
+
401
+ def _string_tuple(value: object) -> tuple[str, ...]:
402
+ if not isinstance(value, list | tuple):
403
+ return ()
404
+ return tuple(str(item) for item in value)
405
+
406
+
407
+ def _domain(value: object) -> str:
408
+ raw = str(value or "")
409
+ if not raw or raw == "None":
410
+ return ""
411
+ return raw if raw.startswith(("http://", "https://")) else f"https://{raw}"
412
+
413
+
414
+ def _integer(value: object) -> int:
415
+ if isinstance(value, bool):
416
+ return int(value)
417
+ if isinstance(value, int):
418
+ return value
419
+ if isinstance(value, float):
420
+ return int(value)
421
+ if isinstance(value, str | bytes | bytearray):
422
+ try:
423
+ return int(value)
424
+ except ValueError as error:
425
+ raise ProtocolError("DevBox response value is not an integer") from error
426
+ raise ProtocolError("DevBox response value is not an integer")
427
+
428
+
429
+ def _number(value: object) -> float:
430
+ if isinstance(value, bool):
431
+ value = int(value)
432
+ if isinstance(value, int | float):
433
+ try:
434
+ number = float(value)
435
+ except OverflowError as error:
436
+ raise ProtocolError("DevBox response value is not a number") from error
437
+ if not math.isfinite(number):
438
+ raise ProtocolError("DevBox response value is not a finite number")
439
+ return number
440
+ if isinstance(value, str | bytes | bytearray):
441
+ try:
442
+ return float(value)
443
+ except (OverflowError, ValueError) as error:
444
+ raise ProtocolError("DevBox response value is not a number") from error
445
+ raise ProtocolError("DevBox response value is not a number")
446
+
447
+
448
+ E = TypeVar("E", bound=Enum)
449
+
450
+
451
+ def _enum(enum_type: type[E], value: object) -> E:
452
+ try:
453
+ return enum_type(str(value))
454
+ except ValueError as error:
455
+ raise ProtocolError(f"DevBox returned an invalid {enum_type.__name__}") from error
devbox/pty.py ADDED
@@ -0,0 +1,142 @@
1
+ """Interactive terminal (PTY) sessions inside a sandbox.
2
+
3
+ Exposed as :attr:`Sandbox.pty` / :attr:`AsyncSandbox.pty`; input goes through
4
+ :meth:`CommandHandle.send_stdin`, output arrives via the handle's event
5
+ stream.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Awaitable, Callable, Mapping
11
+
12
+ from ._transport import AsyncTransport, SyncTransport
13
+ from .commands import (
14
+ AsyncCommandHandle,
15
+ AsyncCommands,
16
+ CommandHandle,
17
+ Commands,
18
+ )
19
+ from .models import PtySize
20
+
21
+
22
+ class Pty:
23
+ """Open and reconnect interactive terminal sessions."""
24
+
25
+ def __init__(self, commands: Commands, transport: Callable[[], SyncTransport]) -> None:
26
+ self._commands = commands
27
+ self._transport = transport
28
+
29
+ def start(
30
+ self,
31
+ command: str = "/bin/bash",
32
+ *,
33
+ size: PtySize | None = None,
34
+ envs: Mapping[str, str] | None = None,
35
+ cwd: str | None = None,
36
+ user: str | None = None,
37
+ ) -> CommandHandle:
38
+ """Start an interactive process and return its process handle.
39
+
40
+ The first event of the handle's stream carries the process PID.
41
+ """
42
+ size = size or PtySize()
43
+ environment = {"TERM": "xterm-256color", **dict(envs or {})}
44
+ process: dict[str, object] = {
45
+ "cmd": command,
46
+ "args": ["-i", "-l"] if command == "/bin/bash" else [],
47
+ "envs": environment,
48
+ }
49
+ if cwd:
50
+ process["cwd"] = cwd
51
+ body = {"process": process}
52
+ return self._commands._start(body, timeout=None, user=user, pty=size, input_stream="pty")
53
+
54
+ def connect(
55
+ self,
56
+ pid: int,
57
+ *,
58
+ timeout: float | None = None,
59
+ ) -> CommandHandle:
60
+ """Reconnect to an interactive process by process ID."""
61
+ return CommandHandle(
62
+ pid,
63
+ self._commands,
64
+ self._commands._connect_events(pid, timeout),
65
+ input_stream="pty",
66
+ reconnect_timeout=timeout,
67
+ )
68
+
69
+ def resize(self, pid: int, size: PtySize) -> None:
70
+ """Change the terminal dimensions for an interactive process."""
71
+ self._transport().connect_unary(
72
+ "/process.Process/Update",
73
+ json_body={
74
+ "process": {"pid": pid},
75
+ "pty": {"size": {"rows": size.rows, "cols": size.cols}},
76
+ },
77
+ )
78
+
79
+
80
+ class AsyncPty:
81
+ """Asynchronous counterpart of :class:`Pty`."""
82
+
83
+ def __init__(
84
+ self,
85
+ commands: AsyncCommands,
86
+ transport: Callable[[], Awaitable[AsyncTransport]],
87
+ ) -> None:
88
+ self._commands = commands
89
+ self._transport = transport
90
+
91
+ async def start(
92
+ self,
93
+ command: str = "/bin/bash",
94
+ *,
95
+ size: PtySize | None = None,
96
+ envs: Mapping[str, str] | None = None,
97
+ cwd: str | None = None,
98
+ user: str | None = None,
99
+ ) -> AsyncCommandHandle:
100
+ """Start an interactive process and return its process handle.
101
+
102
+ The first event of the handle's stream carries the process PID.
103
+ """
104
+ size = size or PtySize()
105
+ environment = {"TERM": "xterm-256color", **dict(envs or {})}
106
+ process: dict[str, object] = {
107
+ "cmd": command,
108
+ "args": ["-i", "-l"] if command == "/bin/bash" else [],
109
+ "envs": environment,
110
+ }
111
+ if cwd:
112
+ process["cwd"] = cwd
113
+ body = {"process": process}
114
+ return await self._commands._start(
115
+ body, timeout=None, user=user, pty=size, input_stream="pty"
116
+ )
117
+
118
+ async def connect(
119
+ self,
120
+ pid: int,
121
+ *,
122
+ timeout: float | None = None,
123
+ ) -> AsyncCommandHandle:
124
+ """Reconnect to an interactive process by process ID."""
125
+ return AsyncCommandHandle(
126
+ pid,
127
+ self._commands,
128
+ await self._commands._connect_events(pid, timeout),
129
+ input_stream="pty",
130
+ reconnect_timeout=timeout,
131
+ )
132
+
133
+ async def resize(self, pid: int, size: PtySize) -> None:
134
+ """Change the terminal dimensions for an interactive process."""
135
+ transport = await self._transport()
136
+ await transport.connect_unary(
137
+ "/process.Process/Update",
138
+ json_body={
139
+ "process": {"pid": pid},
140
+ "pty": {"size": {"rows": size.rows, "cols": size.cols}},
141
+ },
142
+ )
devbox/py.typed ADDED
@@ -0,0 +1 @@
1
+