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/config.py ADDED
@@ -0,0 +1,94 @@
1
+ """Connection settings and URL resolution for the DevBox Python SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import warnings
7
+ from collections.abc import Mapping
8
+ from dataclasses import dataclass, field
9
+ from urllib.parse import urlsplit
10
+
11
+ from .errors import ConfigurationError
12
+
13
+ DEFAULT_API_URL = "https://devbox.developer.myhuaweicloud.com"
14
+
15
+
16
+ def gateway_verify_tls() -> bool:
17
+ """Reports whether gateway TLS certificates should be verified.
18
+
19
+ Controlled by the ``DEVBOX_GATEWAY_SKIP_TLS_VERIFY`` environment
20
+ variable; disabling verification emits a :class:`RuntimeWarning` because
21
+ the connect token and sandbox data become interceptable.
22
+ """
23
+ skip = os.getenv("DEVBOX_GATEWAY_SKIP_TLS_VERIFY", "").strip().lower()
24
+ if skip in {"true", "1", "yes", "on"}:
25
+ warnings.warn(
26
+ "Gateway TLS certificate verification is disabled for debugging; "
27
+ "the connect token and sandbox data may be exposed to interception.",
28
+ RuntimeWarning,
29
+ stacklevel=2,
30
+ )
31
+ return False
32
+ return True
33
+
34
+
35
+ @dataclass(frozen=True, slots=True)
36
+ class ConnectionConfig:
37
+ """Connection settings shared by control-plane requests."""
38
+
39
+ api_key: str = field(repr=False)
40
+ api_url: str = DEFAULT_API_URL
41
+ gateway_url: str | None = None
42
+ request_timeout: float = 30.0
43
+ control_timeout: float = 150.0
44
+ headers: Mapping[str, str] = field(default_factory=dict, repr=False)
45
+
46
+ @classmethod
47
+ def resolve(
48
+ cls,
49
+ *,
50
+ api_key: str | None = None,
51
+ api_url: str | None = None,
52
+ gateway_url: str | None = None,
53
+ request_timeout: float | None = None,
54
+ headers: Mapping[str, str] | None = None,
55
+ ) -> ConnectionConfig:
56
+ """Fills defaults from the ``DEVBOX_API_KEY`` / ``E2B_API_KEY`` /
57
+ ``DEVBOX_API_URL`` / ``E2B_API_URL`` / ``DEVBOX_GATEWAY_URL``
58
+ environment variables and validates the URLs.
59
+
60
+ Raises :class:`ConfigurationError` when no API key is available.
61
+ """
62
+ resolved_key = (
63
+ api_key or os.getenv("DEVBOX_API_KEY") or os.getenv("E2B_API_KEY") or ""
64
+ ).strip()
65
+ if not resolved_key:
66
+ raise ConfigurationError(
67
+ "api_key is required; set DEVBOX_API_KEY, E2B_API_KEY, or pass api_key"
68
+ )
69
+ resolved_api_url = (
70
+ api_url or os.getenv("DEVBOX_API_URL") or os.getenv("E2B_API_URL") or DEFAULT_API_URL
71
+ )
72
+ resolved_gateway_url = gateway_url or os.getenv("DEVBOX_GATEWAY_URL") or None
73
+ if request_timeout is not None and request_timeout <= 0:
74
+ raise ConfigurationError("request_timeout must be positive")
75
+ return cls(
76
+ api_key=resolved_key,
77
+ api_url=_service_url(resolved_api_url, "api_url"),
78
+ gateway_url=(
79
+ _service_url(resolved_gateway_url, "gateway_url") if resolved_gateway_url else None
80
+ ),
81
+ request_timeout=30.0 if request_timeout is None else request_timeout,
82
+ control_timeout=150.0 if request_timeout is None else request_timeout,
83
+ headers=dict(headers or {}),
84
+ )
85
+
86
+
87
+ def _service_url(value: str, name: str) -> str:
88
+ url = value.strip().rstrip("/")
89
+ parsed = urlsplit(url)
90
+ if parsed.scheme == "https" and parsed.netloc:
91
+ return url
92
+ if parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}:
93
+ return url
94
+ raise ConfigurationError(f"{name} must use https (http is allowed only for localhost)")
devbox/envd.py ADDED
@@ -0,0 +1,68 @@
1
+ """Data-plane access to the sandbox-local envd service: metrics, environment
2
+ variables and health.
3
+
4
+ Exposed as :attr:`Sandbox.envd` / :attr:`AsyncSandbox.envd`.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from collections.abc import Awaitable, Callable, Mapping
10
+
11
+ from ._transport import AsyncTransport, SyncTransport
12
+ from .errors import ProtocolError
13
+ from .models import EnvdHealth, EnvdMetrics
14
+
15
+
16
+ class Envd:
17
+ """Synchronous EnvD runtime API operations."""
18
+
19
+ def __init__(self, transport: Callable[[], SyncTransport]) -> None:
20
+ self._transport = transport
21
+
22
+ def get_metrics(self) -> EnvdMetrics:
23
+ """Return one realtime CPU, memory and disk sample."""
24
+ return EnvdMetrics.from_wire(_mapping(self._transport().request("GET", "/metrics")))
25
+
26
+ def get_envs(self) -> Mapping[str, str]:
27
+ """Return EnvD's current environment variables."""
28
+ value = self._transport().request("GET", "/envs")
29
+ if not isinstance(value, Mapping):
30
+ raise ProtocolError("EnvD returned an invalid envs response")
31
+ return {str(key): str(item) for key, item in value.items()}
32
+
33
+ def health(self) -> EnvdHealth:
34
+ """Probe EnvD directly and return its version header."""
35
+ _, headers = self._transport().request_with_headers("GET", "/health")
36
+ return EnvdHealth(envd_version=headers.get("X-Envd-Version", ""))
37
+
38
+
39
+ class AsyncEnvd:
40
+ """Asynchronous EnvD runtime API operations."""
41
+
42
+ def __init__(self, transport: Callable[[], Awaitable[AsyncTransport]]) -> None:
43
+ self._transport = transport
44
+
45
+ async def get_metrics(self) -> EnvdMetrics:
46
+ """Return one realtime CPU, memory and disk sample."""
47
+ transport = await self._transport()
48
+ return EnvdMetrics.from_wire(_mapping(await transport.request("GET", "/metrics")))
49
+
50
+ async def get_envs(self) -> Mapping[str, str]:
51
+ """Return EnvD's current environment variables."""
52
+ transport = await self._transport()
53
+ value = await transport.request("GET", "/envs")
54
+ if not isinstance(value, Mapping):
55
+ raise ProtocolError("EnvD returned an invalid envs response")
56
+ return {str(key): str(item) for key, item in value.items()}
57
+
58
+ async def health(self) -> EnvdHealth:
59
+ """Probe EnvD directly and return its version header."""
60
+ transport = await self._transport()
61
+ _, headers = await transport.request_with_headers("GET", "/health")
62
+ return EnvdHealth(envd_version=headers.get("X-Envd-Version", ""))
63
+
64
+
65
+ def _mapping(value: object) -> Mapping[str, object]:
66
+ if not isinstance(value, Mapping):
67
+ raise ProtocolError("EnvD returned an invalid object response")
68
+ return value
devbox/errors.py ADDED
@@ -0,0 +1,215 @@
1
+ """Exception types and API error decoding for the DevBox SDK.
2
+
3
+ Every error raised by the SDK derives from :class:`DevBoxError`; HTTP and
4
+ Connect (EnvD) error responses are mapped to the concrete subclasses by
5
+ :func:`raise_for_response` and :func:`raise_connect_error`.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import Mapping
11
+ from dataclasses import dataclass
12
+ from datetime import datetime, timezone
13
+ from email.utils import parsedate_to_datetime
14
+ from typing import TYPE_CHECKING, Any, NoReturn
15
+
16
+ import httpx
17
+
18
+ if TYPE_CHECKING:
19
+ from .models import CommandResult
20
+
21
+
22
+ @dataclass(frozen=True, slots=True)
23
+ class ErrorDetail:
24
+ """One structured detail entry from a DevBox API error response."""
25
+
26
+ code: str
27
+ message: str
28
+ target: str | None = None
29
+
30
+
31
+ class DevBoxError(Exception):
32
+ """Base exception returned by the DevBox SDK."""
33
+
34
+ def __init__(
35
+ self,
36
+ message: str,
37
+ *,
38
+ code: str = "",
39
+ status_code: int | None = None,
40
+ target: str | None = None,
41
+ details: tuple[ErrorDetail, ...] = (),
42
+ request_id: str | None = None,
43
+ retry_after: float | None = None,
44
+ ) -> None:
45
+ super().__init__(message)
46
+ self.message = message
47
+ self.code = code
48
+ self.status_code = status_code
49
+ self.target = target
50
+ self.details = details
51
+ self.request_id = request_id
52
+ self.retry_after = retry_after
53
+
54
+ def __str__(self) -> str:
55
+ suffix = f" [{self.code}]" if self.code else ""
56
+ return self.message + suffix
57
+
58
+
59
+ class ConfigurationError(DevBoxError):
60
+ """Invalid client configuration (blank API key, bad URL, bad timeout...)."""
61
+
62
+
63
+ class AuthenticationError(DevBoxError):
64
+ """The API key was rejected (HTTP 401)."""
65
+
66
+
67
+ class PermissionDeniedError(DevBoxError):
68
+ """The API key lacks permission for the operation (HTTP 403)."""
69
+
70
+
71
+ class ValidationError(DevBoxError):
72
+ """The request payload was rejected (HTTP 400/422)."""
73
+
74
+
75
+ class NotFoundError(DevBoxError):
76
+ """The referenced resource does not exist (HTTP 404)."""
77
+
78
+
79
+ class ConflictError(DevBoxError):
80
+ """The operation conflicts with the current resource state (HTTP 409)."""
81
+
82
+
83
+ class RateLimitError(DevBoxError):
84
+ """Rate limit exceeded (HTTP 429); see :attr:`DevBoxError.retry_after`."""
85
+
86
+
87
+ class RequestTimeoutError(DevBoxError):
88
+ """The request timed out (HTTP 408 or transport timeout)."""
89
+
90
+
91
+ class ServiceUnavailableError(DevBoxError):
92
+ """The service is temporarily unavailable (HTTP 503)."""
93
+
94
+
95
+ class ProtocolError(DevBoxError):
96
+ """The server response violated the SDK protocol expectations."""
97
+
98
+
99
+ class CommandExitError(DevBoxError):
100
+ """Raised when a command exits nonzero and ``check`` is true."""
101
+
102
+ def __init__(self, result: CommandResult) -> None:
103
+ super().__init__(f"command exited with status {result.exit_code}", code="COMMAND_EXIT")
104
+ self.result = result
105
+
106
+
107
+ def transport_error(error: Exception) -> Exception:
108
+ """Maps an httpx transport failure to a :class:`DevBoxError` subclass."""
109
+ if isinstance(error, httpx.TimeoutException):
110
+ return RequestTimeoutError(f"request timed out ({type(error).__name__})")
111
+ if isinstance(error, httpx.HTTPError):
112
+ detail = str(error.__cause__ or error)
113
+ return ServiceUnavailableError(
114
+ f"DevBox transport failed ({type(error).__name__}): {detail}"
115
+ )
116
+ return error
117
+
118
+
119
+ def raise_for_response(response: httpx.Response) -> NoReturn:
120
+ """Raises the matching :class:`DevBoxError` subclass for a failed HTTP response."""
121
+ payload: Mapping[str, Any] = {}
122
+ try:
123
+ decoded = response.json()
124
+ if isinstance(decoded, Mapping):
125
+ payload = decoded
126
+ except ValueError:
127
+ pass
128
+
129
+ raw_error = payload.get("error", payload)
130
+ error = raw_error if isinstance(raw_error, Mapping) else payload
131
+ message = str(
132
+ error.get("message")
133
+ or error.get("error_message")
134
+ or f"request failed with status {response.status_code}"
135
+ )
136
+ code = str(
137
+ error.get("error_code") or error.get("error") or error.get("code") or response.status_code
138
+ )
139
+ target = str(error["target"]) if error.get("target") is not None else None
140
+ details = _details(error.get("details"))
141
+ request_id = response.headers.get("X-Request-Id") or response.headers.get("X-Request-ID")
142
+ retry_after = _retry_after(response.headers.get("Retry-After"))
143
+ exception_type: type[DevBoxError] = {
144
+ 400: ValidationError,
145
+ 401: AuthenticationError,
146
+ 403: PermissionDeniedError,
147
+ 404: NotFoundError,
148
+ 408: RequestTimeoutError,
149
+ 409: ConflictError,
150
+ 422: ValidationError,
151
+ 429: RateLimitError,
152
+ }.get(response.status_code, DevBoxError)
153
+ if response.status_code >= 500:
154
+ exception_type = ServiceUnavailableError
155
+ raise exception_type(
156
+ message,
157
+ code=code,
158
+ status_code=response.status_code,
159
+ target=target,
160
+ details=details,
161
+ request_id=request_id,
162
+ retry_after=retry_after,
163
+ )
164
+
165
+
166
+ def raise_connect_error(error: Mapping[str, Any]) -> NoReturn:
167
+ """Raises the matching :class:`DevBoxError` subclass for a Connect (EnvD) error."""
168
+ code = str(error.get("code", "unknown"))
169
+ message = str(error.get("message") or "EnvD request failed")
170
+ status_code, exception_type = {
171
+ "invalid_argument": (400, ValidationError),
172
+ "out_of_range": (400, ValidationError),
173
+ "unauthenticated": (401, AuthenticationError),
174
+ "permission_denied": (403, PermissionDeniedError),
175
+ "not_found": (404, NotFoundError),
176
+ "already_exists": (409, ConflictError),
177
+ "aborted": (409, ConflictError),
178
+ "resource_exhausted": (429, RateLimitError),
179
+ "deadline_exceeded": (408, RequestTimeoutError),
180
+ "unavailable": (503, ServiceUnavailableError),
181
+ "internal": (500, ServiceUnavailableError),
182
+ }.get(code, (None, DevBoxError))
183
+ raise exception_type(message, code=code, status_code=status_code)
184
+
185
+
186
+ def _details(value: object) -> tuple[ErrorDetail, ...]:
187
+ if not isinstance(value, list):
188
+ return ()
189
+ result: list[ErrorDetail] = []
190
+ for item in value:
191
+ if not isinstance(item, Mapping):
192
+ continue
193
+ result.append(
194
+ ErrorDetail(
195
+ code=str(item.get("code", "")),
196
+ message=str(item.get("message", "")),
197
+ target=str(item["target"]) if item.get("target") is not None else None,
198
+ )
199
+ )
200
+ return tuple(result)
201
+
202
+
203
+ def _retry_after(value: str | None) -> float | None:
204
+ if value is None:
205
+ return None
206
+ try:
207
+ return float(value)
208
+ except ValueError:
209
+ try:
210
+ retry_at = parsedate_to_datetime(value)
211
+ except (TypeError, ValueError):
212
+ return None
213
+ if retry_at.tzinfo is None:
214
+ retry_at = retry_at.replace(tzinfo=timezone.utc)
215
+ return max(0.0, (retry_at - datetime.now(timezone.utc)).total_seconds())
devbox/filesystem.py ADDED
@@ -0,0 +1,299 @@
1
+ """File operations inside a sandbox: read/write files, list directories,
2
+ watch changes and upload/download.
3
+
4
+ Exposed as :attr:`Sandbox.files` / :attr:`AsyncSandbox.files`; paths must be
5
+ absolute.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from collections.abc import AsyncGenerator, Awaitable, Callable, Generator, Mapping, Sequence
11
+ from pathlib import Path
12
+ from typing import Any, cast
13
+
14
+ from ._transport import AsyncTransport, SyncTransport
15
+ from .errors import NotFoundError, ProtocolError
16
+ from .models import FileInfo, FileWatchEvent
17
+
18
+ SyncTransportProvider = Callable[[], SyncTransport]
19
+ AsyncTransportProvider = Callable[[], Awaitable[AsyncTransport]]
20
+
21
+ _FILESYSTEM = "/filesystem.Filesystem"
22
+
23
+
24
+ class Filesystem:
25
+ """Read and modify the filesystem inside a sandbox."""
26
+
27
+ def __init__(self, transport: SyncTransportProvider) -> None:
28
+ self._transport = transport
29
+
30
+ def read_bytes(self, path: str) -> bytes:
31
+ """Read a remote file without text decoding."""
32
+ return self._transport().request_bytes("GET", "/files", params={"path": _path(path)})
33
+
34
+ def read(self, path: str, *, encoding: str = "utf-8") -> str:
35
+ """Read and decode a remote text file."""
36
+ return self.read_bytes(path).decode(encoding)
37
+
38
+ def write(
39
+ self,
40
+ path: str,
41
+ data: str | bytes,
42
+ *,
43
+ encoding: str = "utf-8",
44
+ ) -> FileInfo:
45
+ """Create or replace one remote file."""
46
+ content = data.encode(encoding) if isinstance(data, str) else data
47
+ payload = self._transport().request_content(
48
+ "POST",
49
+ "/files",
50
+ content,
51
+ params={"path": _path(path)},
52
+ headers={"Content-Type": "application/octet-stream"},
53
+ )
54
+ return FileInfo.from_wire(_first_item(payload))
55
+
56
+ def write_batch(
57
+ self, files: Mapping[str, str | bytes], *, encoding: str = "utf-8"
58
+ ) -> tuple[FileInfo, ...]:
59
+ """Write several remote files in mapping order."""
60
+ return tuple(self.write(path, data, encoding=encoding) for path, data in files.items())
61
+
62
+ def list(self, path: str, *, depth: int = 1) -> tuple[FileInfo, ...]:
63
+ """List entries below a remote directory."""
64
+ if depth < 1:
65
+ raise ValueError("depth must be positive")
66
+ payload = self._transport().connect_unary(
67
+ f"{_FILESYSTEM}/ListDir", {"path": _path(path), "depth": depth}
68
+ )
69
+ return tuple(FileInfo.from_wire(item) for item in _items(payload, "entries"))
70
+
71
+ def stat(self, path: str) -> FileInfo:
72
+ """Return metadata for a remote path."""
73
+ payload = self._transport().connect_unary(f"{_FILESYSTEM}/Stat", {"path": _path(path)})
74
+ return FileInfo.from_wire(_entry(payload))
75
+
76
+ def exists(self, path: str) -> bool:
77
+ """Return whether a remote path exists."""
78
+ try:
79
+ self.stat(path)
80
+ return True
81
+ except NotFoundError:
82
+ return False
83
+
84
+ def make_dir(self, path: str) -> None:
85
+ """Create a remote directory."""
86
+ self._transport().connect_unary(f"{_FILESYSTEM}/MakeDir", {"path": _path(path)})
87
+
88
+ def move(self, source: str, destination: str) -> None:
89
+ """Move or rename a remote path."""
90
+ self._transport().connect_unary(
91
+ f"{_FILESYSTEM}/Move",
92
+ {"source": _path(source), "destination": _path(destination)},
93
+ )
94
+
95
+ def remove(self, path: str) -> None:
96
+ """Remove a remote file or directory."""
97
+ self._transport().connect_unary(f"{_FILESYSTEM}/Remove", {"path": _path(path)})
98
+
99
+ def upload(self, local_path: str | Path, remote_path: str) -> FileInfo:
100
+ """Upload one local file to the sandbox."""
101
+ return self.write(remote_path, Path(local_path).read_bytes())
102
+
103
+ def download(self, remote_path: str, local_path: str | Path) -> Path:
104
+ """Download one sandbox file to the local machine."""
105
+ destination = Path(local_path)
106
+ destination.write_bytes(self.read_bytes(remote_path))
107
+ return destination
108
+
109
+ def watch(
110
+ self,
111
+ path: str,
112
+ *,
113
+ recursive: bool = False,
114
+ include_entry: bool = True,
115
+ ) -> Generator[FileWatchEvent, None, None]:
116
+ """Yield filesystem changes until the returned generator is closed."""
117
+ events = self._transport().connect_stream(
118
+ f"{_FILESYSTEM}/WatchDir",
119
+ {
120
+ "path": _path(path),
121
+ "recursive": recursive,
122
+ "includeEntry": include_entry,
123
+ },
124
+ timeout=None,
125
+ )
126
+ try:
127
+ yield from _filesystem_events(events)
128
+ finally:
129
+ events.close()
130
+
131
+
132
+ class AsyncFilesystem:
133
+ """Read and modify the sandbox filesystem asynchronously."""
134
+
135
+ def __init__(self, transport: AsyncTransportProvider) -> None:
136
+ self._transport = transport
137
+
138
+ async def read_bytes(self, path: str) -> bytes:
139
+ """Read a remote file without text decoding."""
140
+ transport = await self._transport()
141
+ return await transport.request_bytes("GET", "/files", params={"path": _path(path)})
142
+
143
+ async def read(self, path: str, *, encoding: str = "utf-8") -> str:
144
+ """Read and decode a remote text file."""
145
+ return (await self.read_bytes(path)).decode(encoding)
146
+
147
+ async def write(
148
+ self,
149
+ path: str,
150
+ data: str | bytes,
151
+ *,
152
+ encoding: str = "utf-8",
153
+ ) -> FileInfo:
154
+ """Create or replace one remote file."""
155
+ content = data.encode(encoding) if isinstance(data, str) else data
156
+ transport = await self._transport()
157
+ payload = await transport.request_content(
158
+ "POST",
159
+ "/files",
160
+ content,
161
+ params={"path": _path(path)},
162
+ headers={"Content-Type": "application/octet-stream"},
163
+ )
164
+ return FileInfo.from_wire(_first_item(payload))
165
+
166
+ async def write_batch(
167
+ self, files: Mapping[str, str | bytes], *, encoding: str = "utf-8"
168
+ ) -> tuple[FileInfo, ...]:
169
+ """Write several remote files in mapping order."""
170
+ result: list[FileInfo] = []
171
+ for path, data in files.items():
172
+ result.append(await self.write(path, data, encoding=encoding))
173
+ return tuple(result)
174
+
175
+ async def list(self, path: str, *, depth: int = 1) -> tuple[FileInfo, ...]:
176
+ """List entries below a remote directory."""
177
+ if depth < 1:
178
+ raise ValueError("depth must be positive")
179
+ transport = await self._transport()
180
+ payload = await transport.connect_unary(
181
+ f"{_FILESYSTEM}/ListDir", {"path": _path(path), "depth": depth}
182
+ )
183
+ return tuple(FileInfo.from_wire(item) for item in _items(payload, "entries"))
184
+
185
+ async def stat(self, path: str) -> FileInfo:
186
+ """Return metadata for a remote path."""
187
+ transport = await self._transport()
188
+ payload = await transport.connect_unary(f"{_FILESYSTEM}/Stat", {"path": _path(path)})
189
+ return FileInfo.from_wire(_entry(payload))
190
+
191
+ async def exists(self, path: str) -> bool:
192
+ """Return whether a remote path exists."""
193
+ try:
194
+ await self.stat(path)
195
+ return True
196
+ except NotFoundError:
197
+ return False
198
+
199
+ async def make_dir(self, path: str) -> None:
200
+ """Create a remote directory."""
201
+ transport = await self._transport()
202
+ await transport.connect_unary(f"{_FILESYSTEM}/MakeDir", {"path": _path(path)})
203
+
204
+ async def move(self, source: str, destination: str) -> None:
205
+ """Move or rename a remote path."""
206
+ transport = await self._transport()
207
+ await transport.connect_unary(
208
+ f"{_FILESYSTEM}/Move",
209
+ {"source": _path(source), "destination": _path(destination)},
210
+ )
211
+
212
+ async def remove(self, path: str) -> None:
213
+ """Remove a remote file or directory."""
214
+ transport = await self._transport()
215
+ await transport.connect_unary(f"{_FILESYSTEM}/Remove", {"path": _path(path)})
216
+
217
+ async def upload(self, local_path: str | Path, remote_path: str) -> FileInfo:
218
+ """Upload one local file to the sandbox."""
219
+ return await self.write(remote_path, Path(local_path).read_bytes())
220
+
221
+ async def download(self, remote_path: str, local_path: str | Path) -> Path:
222
+ """Download one sandbox file to the local machine."""
223
+ destination = Path(local_path)
224
+ destination.write_bytes(await self.read_bytes(remote_path))
225
+ return destination
226
+
227
+ async def watch(
228
+ self,
229
+ path: str,
230
+ *,
231
+ recursive: bool = False,
232
+ include_entry: bool = True,
233
+ ) -> AsyncGenerator[FileWatchEvent, None]:
234
+ """Yield filesystem changes until the stream is closed."""
235
+ transport = await self._transport()
236
+ events = transport.connect_stream(
237
+ f"{_FILESYSTEM}/WatchDir",
238
+ {
239
+ "path": _path(path),
240
+ "recursive": recursive,
241
+ "includeEntry": include_entry,
242
+ },
243
+ timeout=None,
244
+ )
245
+ try:
246
+ async for response in events:
247
+ event = _filesystem_event(response)
248
+ if event is not None:
249
+ yield event
250
+ finally:
251
+ await events.aclose()
252
+
253
+
254
+ def _filesystem_events(
255
+ responses: Generator[Mapping[str, Any], None, None],
256
+ ) -> Generator[FileWatchEvent, None, None]:
257
+ for response in responses:
258
+ event = _filesystem_event(response)
259
+ if event is not None:
260
+ yield event
261
+
262
+
263
+ def _filesystem_event(response: Mapping[str, Any]) -> FileWatchEvent | None:
264
+ value = response.get("filesystem")
265
+ if value is None:
266
+ event = response.get("event")
267
+ value = event.get("filesystem") if isinstance(event, Mapping) else None
268
+ return FileWatchEvent.from_wire(value) if isinstance(value, Mapping) else None
269
+
270
+
271
+ def _path(value: str) -> str:
272
+ if not value or not value.startswith("/"):
273
+ raise ValueError("sandbox paths must be absolute")
274
+ return value
275
+
276
+
277
+ def _entry(payload: object) -> Mapping[str, Any]:
278
+ if isinstance(payload, Mapping) and isinstance(payload.get("entry"), Mapping):
279
+ return cast(Mapping[str, Any], payload["entry"])
280
+ raise ProtocolError("filesystem response does not contain an entry")
281
+
282
+
283
+ def _first_item(payload: object) -> Mapping[str, Any]:
284
+ values = _items(payload, "files")
285
+ if not values:
286
+ raise ProtocolError("file upload response is empty")
287
+ return values[0]
288
+
289
+
290
+ def _items(value: object, key: str) -> Sequence[Mapping[str, Any]]:
291
+ if isinstance(value, list):
292
+ source = value
293
+ elif isinstance(value, Mapping):
294
+ source = value.get(key, [])
295
+ else:
296
+ source = []
297
+ if not isinstance(source, list):
298
+ raise ProtocolError("filesystem response is invalid")
299
+ return tuple(item for item in source if isinstance(item, Mapping))