|
| 1 | +"""Translate the Agents sandbox operations to an owned Vercel service client. |
| 2 | +
|
| 3 | +Execution always uses the captured runtime session. A named Vercel handle can |
| 4 | +resume implicitly, which must not preserve the Agents workspace-ready flag. |
| 5 | +""" |
| 6 | + |
| 7 | +from __future__ import annotations |
| 8 | + |
| 9 | +import asyncio |
| 10 | +import uuid |
| 11 | +from collections.abc import AsyncIterator |
| 12 | +from dataclasses import dataclass |
| 13 | +from datetime import timedelta |
| 14 | +from typing import cast |
| 15 | + |
| 16 | +from vercel.oidc.credentials import get_credentials |
| 17 | +from vercel.sandbox import ( |
| 18 | + Sandbox, |
| 19 | + SandboxClient, |
| 20 | + SandboxCredentials, |
| 21 | + SandboxInvalidHandleError, |
| 22 | + SandboxPathNotFoundError, |
| 23 | + SandboxResources, |
| 24 | + SandboxRuntimeSession, |
| 25 | + SandboxServiceOptions, |
| 26 | + SandboxStatus, |
| 27 | + SandboxTerminalStateError, |
| 28 | + SnapshotSource, |
| 29 | +) |
| 30 | + |
| 31 | +from ._network_policy import NetworkPolicy, to_provider |
| 32 | + |
| 33 | +DEFAULT_VERCEL_WAIT_FOR_RUNNING_TIMEOUT_S = 45.0 |
| 34 | + |
| 35 | +# The released runtime images use Amazon Linux, including the S3 mount tools. |
| 36 | +_RUNTIME_IMAGES = { |
| 37 | + "node22": "vercel/sandbox/node:al-22", |
| 38 | + "node24": "vercel/sandbox/node:al-24", |
| 39 | + "node26": "vercel/sandbox/node:al-26", |
| 40 | + "python3.13": "vercel/sandbox/python:al-3.13.1", |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +@dataclass |
| 45 | +class _CommandResult: |
| 46 | + exit_code: int |
| 47 | + _stdout: str |
| 48 | + _stderr: str |
| 49 | + |
| 50 | + async def stdout(self) -> str: |
| 51 | + return self._stdout |
| 52 | + |
| 53 | + async def stderr(self) -> str: |
| 54 | + return self._stderr |
| 55 | + |
| 56 | + |
| 57 | +@dataclass |
| 58 | +class _SnapshotReference: |
| 59 | + snapshot_id: str |
| 60 | + |
| 61 | + |
| 62 | +class ProviderSandbox: |
| 63 | + """Own one provider transport and one exact execution session.""" |
| 64 | + |
| 65 | + def __init__(self, client: SandboxClient, sandbox: Sandbox) -> None: |
| 66 | + session = sandbox.current_session |
| 67 | + if session is None: |
| 68 | + raise SandboxInvalidHandleError("Sandbox has no execution session") |
| 69 | + self.client = client |
| 70 | + self._sandbox = sandbox |
| 71 | + self._session: SandboxRuntimeSession = session |
| 72 | + |
| 73 | + @property |
| 74 | + def sandbox_id(self) -> str: |
| 75 | + return self._session.id |
| 76 | + |
| 77 | + @property |
| 78 | + def sandbox_name(self) -> str: |
| 79 | + return self._sandbox.name |
| 80 | + |
| 81 | + @property |
| 82 | + def status(self) -> SandboxStatus | None: |
| 83 | + return self._session.status |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def _client(token: str | None, project_id: str | None, team_id: str | None) -> SandboxClient: |
| 87 | + resolved = get_credentials(token=token, project_id=project_id, team_id=team_id) |
| 88 | + |
| 89 | + async def credentials() -> SandboxCredentials: |
| 90 | + return SandboxCredentials( |
| 91 | + token=resolved.token, project_id=resolved.project_id, team_id=resolved.team_id |
| 92 | + ) |
| 93 | + |
| 94 | + return SandboxClient.create(options=SandboxServiceOptions(credentials_factory=credentials)) |
| 95 | + |
| 96 | + @classmethod |
| 97 | + async def create( |
| 98 | + cls, |
| 99 | + *, |
| 100 | + token: str | None = None, |
| 101 | + project_id: str | None = None, |
| 102 | + team_id: str | None = None, |
| 103 | + source: SnapshotSource | None = None, |
| 104 | + ports: list[int] | None = None, |
| 105 | + timeout: int | None = None, |
| 106 | + resources: SandboxResources | None = None, |
| 107 | + runtime: str | None = None, |
| 108 | + interactive: bool = False, |
| 109 | + env: dict[str, str] | None = None, |
| 110 | + network_policy: NetworkPolicy | None = None, |
| 111 | + ) -> ProviderSandbox: |
| 112 | + # The provider's controller now owns interactive connections; creation |
| 113 | + # no longer needs the legacy flag. Keep accepting it for existing state. |
| 114 | + image = _RUNTIME_IMAGES.get(runtime or "node24") |
| 115 | + if image is None: |
| 116 | + raise ValueError(f"Unsupported Vercel runtime: {runtime!r}") |
| 117 | + client = cls._client(token, project_id, team_id) |
| 118 | + sandbox = None |
| 119 | + name = "agents-" + uuid.uuid4().hex |
| 120 | + try: |
| 121 | + sandbox = await asyncio.wait_for( |
| 122 | + client.create_sandbox( |
| 123 | + name=name, |
| 124 | + image=image, |
| 125 | + source=source, |
| 126 | + ports=ports, |
| 127 | + execution_time_limit=None |
| 128 | + if timeout is None |
| 129 | + else timedelta(milliseconds=timeout), |
| 130 | + resources=resources, |
| 131 | + persistent=False, |
| 132 | + env=env, |
| 133 | + network_policy=to_provider(network_policy), |
| 134 | + ), |
| 135 | + timeout=DEFAULT_VERCEL_WAIT_FOR_RUNNING_TIMEOUT_S, |
| 136 | + ) |
| 137 | + return cls(client, sandbox) |
| 138 | + except BaseException as error: |
| 139 | + if isinstance(error, SandboxTerminalStateError) and isinstance(error.sandbox, Sandbox): |
| 140 | + sandbox = error.sandbox |
| 141 | + try: |
| 142 | + if sandbox is None: |
| 143 | + sandbox = await client.get_sandbox(name=name) |
| 144 | + if sandbox is not None and sandbox.current_session is not None: |
| 145 | + await sandbox.current_session.stop() |
| 146 | + except (Exception, asyncio.CancelledError): |
| 147 | + # Best-effort cleanup must not replace the original failure or cancellation. |
| 148 | + pass |
| 149 | + try: |
| 150 | + await client.aclose() |
| 151 | + except (Exception, asyncio.CancelledError): |
| 152 | + # Best-effort cleanup must not replace the original failure or cancellation. |
| 153 | + pass |
| 154 | + raise |
| 155 | + |
| 156 | + @classmethod |
| 157 | + async def get( |
| 158 | + cls, |
| 159 | + *, |
| 160 | + sandbox_id: str, |
| 161 | + sandbox_name: str | None = None, |
| 162 | + token: str | None = None, |
| 163 | + project_id: str | None = None, |
| 164 | + team_id: str | None = None, |
| 165 | + ) -> ProviderSandbox: |
| 166 | + client = cls._client(token, project_id, team_id) |
| 167 | + try: |
| 168 | + sandbox = await client.get_sandbox(name=sandbox_name or sandbox_id) |
| 169 | + result = cls(client, sandbox) |
| 170 | + if result.sandbox_id != sandbox_id: |
| 171 | + raise SandboxInvalidHandleError("Sandbox execution session has changed") |
| 172 | + return result |
| 173 | + except BaseException: |
| 174 | + try: |
| 175 | + await client.aclose() |
| 176 | + except (Exception, asyncio.CancelledError): |
| 177 | + # Best-effort cleanup must not replace the original failure or cancellation. |
| 178 | + pass |
| 179 | + raise |
| 180 | + |
| 181 | + async def refresh(self) -> None: |
| 182 | + await self._session.refresh() |
| 183 | + |
| 184 | + async def wait_for_status(self, status: SandboxStatus, *, timeout: float) -> None: |
| 185 | + async def wait() -> None: |
| 186 | + while self.status != status: |
| 187 | + current_status = self.status |
| 188 | + if current_status in { |
| 189 | + SandboxStatus.STOPPING, |
| 190 | + SandboxStatus.STOPPED, |
| 191 | + SandboxStatus.FAILED, |
| 192 | + SandboxStatus.ABORTED, |
| 193 | + SandboxStatus.SNAPSHOTTING, |
| 194 | + }: |
| 195 | + raise SandboxTerminalStateError( |
| 196 | + "Sandbox execution cannot reach the requested status", |
| 197 | + status=current_status, |
| 198 | + ) |
| 199 | + await asyncio.sleep(0.5) |
| 200 | + await self.refresh() |
| 201 | + |
| 202 | + await asyncio.wait_for(wait(), timeout=timeout) |
| 203 | + |
| 204 | + async def stop(self, *, blocking: bool = False) -> None: |
| 205 | + await self._session.stop() |
| 206 | + # Named-resource deletion cannot be conditional on this execution ID. |
| 207 | + # Retain the name so cleanup cannot delete a concurrent replacement. |
| 208 | + |
| 209 | + async def run_command( |
| 210 | + self, |
| 211 | + command: str, |
| 212 | + args: list[str] | None = None, |
| 213 | + *, |
| 214 | + cwd: str | None = None, |
| 215 | + env: dict[str, str] | None = None, |
| 216 | + sudo: bool = False, |
| 217 | + ) -> _CommandResult: |
| 218 | + result = await self._session.run_process( |
| 219 | + command, args, cwd=cwd, env=env, sudo=sudo, capture_output=True, check=False |
| 220 | + ) |
| 221 | + return _CommandResult(result.returncode, result.stdout or "", result.stderr or "") |
| 222 | + |
| 223 | + def domain(self, port: int) -> str: |
| 224 | + for route in self._sandbox.routes: |
| 225 | + if route.port == port and not route.system: |
| 226 | + return route.url |
| 227 | + raise ValueError(f"No route for port {port}") |
| 228 | + |
| 229 | + async def read_file(self, path: str) -> bytes | None: |
| 230 | + try: |
| 231 | + return await self._session.fs.read_bytes(path) |
| 232 | + except SandboxPathNotFoundError: |
| 233 | + return None |
| 234 | + |
| 235 | + async def iter_file(self, path: str, *, chunk_size: int) -> AsyncIterator[bytes]: |
| 236 | + async def chunks() -> AsyncIterator[bytes]: |
| 237 | + async with self._session.fs.open(path, "rb") as reader: |
| 238 | + while data := await reader.read(chunk_size): |
| 239 | + yield data |
| 240 | + |
| 241 | + return chunks() |
| 242 | + |
| 243 | + async def write_files(self, files: list[dict[str, object]]) -> None: |
| 244 | + async with self._session.fs.batch() as batch: |
| 245 | + for file in files: |
| 246 | + batch.write_bytes(cast(str, file["path"]), cast(bytes, file["content"])) |
| 247 | + |
| 248 | + async def snapshot(self, *, expiration: int | None = None) -> _SnapshotReference: |
| 249 | + result = await self._session.snapshot( |
| 250 | + expiration=None if expiration is None else timedelta(milliseconds=expiration) |
| 251 | + ) |
| 252 | + return _SnapshotReference(result.id) |
0 commit comments