Skip to content

Commit 9706013

Browse files
fix: migrate Vercel sandboxes to the owned provider client (#5255)
* fix(deps): bump vercel from 0.5.6 to 0.11.3 Bumps vercel from 0.5.6 to 0.11.3. --- updated-dependencies: - dependency-name: vercel dependency-version: 0.11.3 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <[email protected]> * fix: migrate Vercel sandboxes to the owned provider client * fix: close Vercel clients after failed reconnects * fix: verify isolated Vercel sandbox installations * fix: preserve Vercel execution ownership during cleanup --------- Signed-off-by: dependabot[bot] <[email protected]> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
1 parent acdbf28 commit 9706013

12 files changed

Lines changed: 995 additions & 65 deletions

File tree

‎integration_tests/packaging/test_released_api_contract.py‎

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,10 @@ def _extra_metadata_error(
5151
"the extra under [project.optional-dependencies]."
5252
)
5353

54-
distribution_name = canonicalize_name(dependency_module)
54+
# The Vercel sandbox distribution retains the shared `vercel` import namespace.
55+
distribution_name = canonicalize_name(
56+
"vercel-sandbox" if dependency_module == "vercel" else dependency_module
57+
)
5558
declared_distributions = _distributions_declared_by_extra(requirement_strings, extra)
5659
if distribution_name not in declared_distributions:
5760
return (
@@ -160,6 +163,27 @@ def test_extra_metadata_provenance_ignores_base_and_transitive_requirements() ->
160163
)
161164

162165

166+
def test_extra_metadata_provenance_uses_vercel_sandbox_distribution() -> None:
167+
assert (
168+
_extra_metadata_error(
169+
extra="vercel",
170+
dependency_module="vercel",
171+
provided_extras=["vercel"],
172+
requirement_strings=["vercel-sandbox>=0.7.0,<0.8; extra == 'vercel'"],
173+
)
174+
is None
175+
)
176+
assert (
177+
_extra_metadata_error(
178+
extra="vercel",
179+
dependency_module="vercel",
180+
provided_extras=["vercel"],
181+
requirement_strings=["vercel>=0.5.6; extra == 'vercel'"],
182+
)
183+
is not None
184+
)
185+
186+
163187
def test_extra_metadata_provenance_rejects_unknown_extra() -> None:
164188
assert _extra_metadata_error(
165189
extra="missing",

‎pyproject.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ modal = [
8383
"pygments>=2.20.0",
8484
]
8585
runloop = ["runloop_api_client>=1.16.0,<2.0.0"]
86-
vercel = ["vercel>=0.5.6,<0.6", "cbor2>=5.9.0"]
86+
vercel = ["vercel-sandbox>=0.7.0,<0.8", "cbor2>=5.9.0"]
8787
s3 = ["boto3>=1.34"]
8888
temporal = [
8989
"temporalio==1.33.0",
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""Keep the released Agents policy JSON independent of provider value-type changes."""
2+
3+
from __future__ import annotations
4+
5+
from typing import Literal
6+
7+
from pydantic import BaseModel
8+
from vercel import sandbox as provider
9+
10+
11+
class NetworkTransformer(BaseModel):
12+
headers: dict[str, str] | None = None
13+
14+
15+
class NetworkPolicyRule(BaseModel):
16+
transform: list[NetworkTransformer] | None = None
17+
18+
19+
class NetworkPolicySubnets(BaseModel):
20+
allow: list[str] | None = None
21+
deny: list[str] | None = None
22+
23+
24+
class NetworkPolicyCustom(BaseModel):
25+
allow: list[str] | dict[str, list[NetworkPolicyRule]]
26+
subnets: NetworkPolicySubnets | None = None
27+
28+
29+
NetworkPolicy = Literal["allow-all", "deny-all"] | NetworkPolicyCustom
30+
31+
32+
def to_provider(policy: NetworkPolicy | None) -> provider.NetworkPolicy | None:
33+
if policy is None:
34+
return None
35+
if policy == "allow-all":
36+
return provider.NetworkPolicy.allow_all()
37+
if policy == "deny-all":
38+
return provider.NetworkPolicy.deny_all()
39+
assert isinstance(policy, NetworkPolicyCustom)
40+
allow: dict[str, tuple[provider.NetworkPolicyRule, ...]]
41+
if isinstance(policy.allow, list):
42+
allow = {domain: () for domain in policy.allow}
43+
else:
44+
allow = {
45+
domain: tuple(
46+
provider.NetworkPolicyRule(
47+
transform=tuple(
48+
provider.NetworkPolicyTransform(headers=transform.headers)
49+
for transform in rule.transform or ()
50+
)
51+
)
52+
for rule in rules
53+
)
54+
for domain, rules in policy.allow.items()
55+
}
56+
subnets = (
57+
provider.NetworkPolicySubnets(allow=policy.subnets.allow, deny=policy.subnets.deny)
58+
if policy.subnets is not None
59+
else None
60+
)
61+
return provider.NetworkPolicy.custom(allow, subnets=subnets)
Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
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

Comments
 (0)