agentvms 0.14.18__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.
- agentvm/__init__.py +29 -0
- agentvm/client.py +409 -0
- agentvm/sandbox_cli.py +82 -0
- agentvm/sandboxes.py +295 -0
- agentvms-0.14.18.dist-info/METADATA +52 -0
- agentvms-0.14.18.dist-info/RECORD +9 -0
- agentvms-0.14.18.dist-info/WHEEL +5 -0
- agentvms-0.14.18.dist-info/entry_points.txt +2 -0
- agentvms-0.14.18.dist-info/top_level.txt +1 -0
agentvm/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
from .client import (
|
|
2
|
+
AgentVM,
|
|
3
|
+
AgentVMAPIError,
|
|
4
|
+
AgentVMMachine,
|
|
5
|
+
AgentVMVolume,
|
|
6
|
+
AgentVMNetworkIdentity,
|
|
7
|
+
AgentVMDnsZone,
|
|
8
|
+
AgentVMConnection,
|
|
9
|
+
AgentVMDataSource,
|
|
10
|
+
AgentVMDataDestination,
|
|
11
|
+
AgentVMDataRoute,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
from .sandboxes import SharedSandboxes, SandboxBatch
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"SharedSandboxes",
|
|
18
|
+
"SandboxBatch",
|
|
19
|
+
"AgentVM",
|
|
20
|
+
"AgentVMAPIError",
|
|
21
|
+
"AgentVMMachine",
|
|
22
|
+
"AgentVMVolume",
|
|
23
|
+
"AgentVMNetworkIdentity",
|
|
24
|
+
"AgentVMDnsZone",
|
|
25
|
+
"AgentVMConnection",
|
|
26
|
+
"AgentVMDataSource",
|
|
27
|
+
"AgentVMDataDestination",
|
|
28
|
+
"AgentVMDataRoute",
|
|
29
|
+
]
|
agentvm/client.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
import urllib.error
|
|
6
|
+
import urllib.parse
|
|
7
|
+
import urllib.request
|
|
8
|
+
from typing import Any, Callable, Dict, Iterable, Optional, Union
|
|
9
|
+
|
|
10
|
+
DEFAULT_API_URL = "https://api.agentvm.sh/v1"
|
|
11
|
+
TERMINAL_OPERATION_STATES = {"completed", "failed", "expired", "canceled"}
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class AgentVMAPIError(RuntimeError):
|
|
15
|
+
def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None, payload: Any = None):
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.status = status
|
|
18
|
+
self.code = code
|
|
19
|
+
self.payload = payload
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _required(value: Any, label: str) -> str:
|
|
23
|
+
normalized = str(value or "").strip()
|
|
24
|
+
if not normalized:
|
|
25
|
+
raise ValueError(f"{label} is required.")
|
|
26
|
+
return normalized
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _command(value: Union[str, Iterable[Any]]) -> list[str]:
|
|
30
|
+
if isinstance(value, str) and value.strip():
|
|
31
|
+
return ["bash", "-lc", value]
|
|
32
|
+
if not isinstance(value, str):
|
|
33
|
+
items = [str(item) for item in value]
|
|
34
|
+
if items:
|
|
35
|
+
return items
|
|
36
|
+
raise ValueError("Command must be a non-empty string or iterable of arguments.")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class AgentVM:
|
|
40
|
+
def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 30.0):
|
|
41
|
+
self.api_key = str(api_key or os.getenv("AGENTVM_API_KEY") or "").strip()
|
|
42
|
+
self.base_url = str(base_url or os.getenv("AGENTVM_API_URL") or DEFAULT_API_URL).strip().rstrip("/")
|
|
43
|
+
if not self.base_url.startswith(("http://", "https://")):
|
|
44
|
+
raise ValueError("AgentVM API URL must use HTTP or HTTPS.")
|
|
45
|
+
self.timeout = float(timeout)
|
|
46
|
+
self.machines = _MachineCollection(self)
|
|
47
|
+
self.volumes = _VolumeCollection(self)
|
|
48
|
+
self.network_identities = _NetworkIdentityCollection(self)
|
|
49
|
+
self.dns = _DnsNamespace(self)
|
|
50
|
+
self.connections = _ConnectionCollection(self)
|
|
51
|
+
self.data = _DataNamespace(self)
|
|
52
|
+
from .sandboxes import SharedSandboxes
|
|
53
|
+
self.sandboxes = SharedSandboxes(self)
|
|
54
|
+
|
|
55
|
+
def request(self, path: str, method: str = "GET", body: Any = None, headers: Optional[Dict[str, str]] = None, timeout: Optional[float] = None) -> Any:
|
|
56
|
+
request_headers = {"accept": "application/json", **(headers or {})}
|
|
57
|
+
if self.api_key:
|
|
58
|
+
request_headers["authorization"] = f"Bearer {self.api_key}"
|
|
59
|
+
encoded_body = None
|
|
60
|
+
if body is not None:
|
|
61
|
+
request_headers.setdefault("content-type", "application/json")
|
|
62
|
+
if request_headers["content-type"] == "application/json":
|
|
63
|
+
encoded_body = json.dumps(body, separators=(",", ":")).encode("utf-8")
|
|
64
|
+
elif isinstance(body, bytes):
|
|
65
|
+
encoded_body = body
|
|
66
|
+
else:
|
|
67
|
+
encoded_body = str(body).encode("utf-8")
|
|
68
|
+
request = urllib.request.Request(f"{self.base_url}{path}", data=encoded_body, headers=request_headers, method=method)
|
|
69
|
+
try:
|
|
70
|
+
with urllib.request.urlopen(request, timeout=timeout or self.timeout) as response:
|
|
71
|
+
raw = response.read()
|
|
72
|
+
if not raw:
|
|
73
|
+
return {}
|
|
74
|
+
try:
|
|
75
|
+
return json.loads(raw.decode("utf-8"))
|
|
76
|
+
except json.JSONDecodeError:
|
|
77
|
+
return {"message": raw.decode("utf-8", errors="replace")}
|
|
78
|
+
except urllib.error.HTTPError as error:
|
|
79
|
+
raw = error.read()
|
|
80
|
+
try:
|
|
81
|
+
payload = json.loads(raw.decode("utf-8")) if raw else {}
|
|
82
|
+
except json.JSONDecodeError:
|
|
83
|
+
payload = {"message": raw.decode("utf-8", errors="replace")}
|
|
84
|
+
message = payload.get("message") or (payload.get("error") or {}).get("message") or f"AgentVM API request failed with HTTP {error.code}."
|
|
85
|
+
code = payload.get("code") or (payload.get("error") or {}).get("code")
|
|
86
|
+
raise AgentVMAPIError(message, status=error.code, code=code, payload=payload) from error
|
|
87
|
+
|
|
88
|
+
def machine(self, machine_id: str):
|
|
89
|
+
return AgentVMMachine(self, _required(machine_id, "Machine ID"))
|
|
90
|
+
|
|
91
|
+
def volume(self, volume_id: str):
|
|
92
|
+
return AgentVMVolume(self, {"id": _required(volume_id, "Volume ID")})
|
|
93
|
+
|
|
94
|
+
def network_identity(self, identity_id: str):
|
|
95
|
+
return AgentVMNetworkIdentity(self, {"id": _required(identity_id, "Network identity ID")})
|
|
96
|
+
|
|
97
|
+
def dns_zone(self, zone_id: str):
|
|
98
|
+
return AgentVMDnsZone(self, {"id": _required(zone_id, "DNS zone ID")})
|
|
99
|
+
|
|
100
|
+
def connection(self, connection_id: str):
|
|
101
|
+
return AgentVMConnection(self, {"id": _required(connection_id, "Connection ID")})
|
|
102
|
+
|
|
103
|
+
def data_source(self, source_id: str):
|
|
104
|
+
return AgentVMDataSource(self, {"id": _required(source_id, "Data source ID")})
|
|
105
|
+
|
|
106
|
+
def data_destination(self, destination_id: str):
|
|
107
|
+
return AgentVMDataDestination(self, {"id": _required(destination_id, "Data destination ID")})
|
|
108
|
+
|
|
109
|
+
def data_route(self, route_id: str):
|
|
110
|
+
return AgentVMDataRoute(self, {"id": _required(route_id, "Data route ID")})
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _MachineCollection:
|
|
114
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
115
|
+
def get(self, machine_id: str, refresh: bool = True):
|
|
116
|
+
machine = self.client.machine(machine_id)
|
|
117
|
+
machine.refresh(refresh=refresh)
|
|
118
|
+
return machine
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class _VolumeCollection:
|
|
122
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
123
|
+
def list(self, workspace_id: Optional[str] = None):
|
|
124
|
+
query = f"?workspaceId={urllib.parse.quote(str(workspace_id))}" if workspace_id else ""
|
|
125
|
+
return self.client.request(f"/compute/volumes{query}").get("volumes", [])
|
|
126
|
+
def get(self, volume_id: str):
|
|
127
|
+
volume = self.client.volume(volume_id)
|
|
128
|
+
volume.refresh()
|
|
129
|
+
return volume
|
|
130
|
+
def create(self, **options):
|
|
131
|
+
return AgentVMVolume(self.client, self.client.request("/compute/volumes", method="POST", body=options)["volume"])
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class _NetworkIdentityCollection:
|
|
135
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
136
|
+
def list(self, workspace_id: Optional[str] = None):
|
|
137
|
+
query = f"?workspaceId={urllib.parse.quote(str(workspace_id))}" if workspace_id else ""
|
|
138
|
+
return [AgentVMNetworkIdentity(self.client, item) for item in self.client.request(f"/compute/network-identities{query}").get("networkIdentities", [])]
|
|
139
|
+
def get(self, identity_id: str):
|
|
140
|
+
identity = self.client.network_identity(identity_id)
|
|
141
|
+
identity.refresh()
|
|
142
|
+
return identity
|
|
143
|
+
def create(self, **options):
|
|
144
|
+
return AgentVMNetworkIdentity(self.client, self.client.request("/compute/network-identities", method="POST", body=options)["networkIdentity"])
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class _DnsZoneCollection:
|
|
148
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
149
|
+
def list(self, workspace_id: Optional[str] = None):
|
|
150
|
+
query = f"?workspaceId={urllib.parse.quote(str(workspace_id))}" if workspace_id else ""
|
|
151
|
+
return [AgentVMDnsZone(self.client, item) for item in self.client.request(f"/network/dns/zones{query}").get("zones", [])]
|
|
152
|
+
def get(self, zone_id: str):
|
|
153
|
+
zone = self.client.dns_zone(zone_id)
|
|
154
|
+
zone.refresh()
|
|
155
|
+
return zone
|
|
156
|
+
def create(self, **options):
|
|
157
|
+
return AgentVMDnsZone(self.client, self.client.request("/network/dns/zones", method="POST", body=options)["zone"])
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
class _DnsNamespace:
|
|
161
|
+
def __init__(self, client: AgentVM):
|
|
162
|
+
self.client = client
|
|
163
|
+
self.zones = _DnsZoneCollection(client)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
class _ConnectionCollection:
|
|
167
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
168
|
+
def list(self, instance_id: Optional[str] = None):
|
|
169
|
+
query = f"?instanceId={urllib.parse.quote(str(instance_id))}" if instance_id else ""
|
|
170
|
+
return [AgentVMConnection(self.client, item) for item in self.client.request(f"/connections{query}").get("connections", [])]
|
|
171
|
+
def get(self, connection_id: str):
|
|
172
|
+
connection = self.client.connection(connection_id)
|
|
173
|
+
connection.refresh()
|
|
174
|
+
return connection
|
|
175
|
+
def create(self, **options):
|
|
176
|
+
return AgentVMConnection(self.client, self.client.request("/connections", method="POST", body=options)["connection"])
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class _DataSourceCollection:
|
|
180
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
181
|
+
def list(self): return [AgentVMDataSource(self.client, item) for item in self.client.request("/data/sources").get("sources", [])]
|
|
182
|
+
def get(self, source_id: str):
|
|
183
|
+
source = self.client.data_source(source_id)
|
|
184
|
+
source.refresh()
|
|
185
|
+
return source
|
|
186
|
+
def create(self, **options):
|
|
187
|
+
payload = self.client.request("/data/sources", method="POST", body=options)
|
|
188
|
+
return AgentVMDataSource(self.client, payload["source"]), payload.get("token")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
class _DataDestinationCollection:
|
|
192
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
193
|
+
def list(self): return [AgentVMDataDestination(self.client, item) for item in self.client.request("/data/destinations").get("destinations", [])]
|
|
194
|
+
def get(self, destination_id: str):
|
|
195
|
+
destination = self.client.data_destination(destination_id)
|
|
196
|
+
destination.refresh()
|
|
197
|
+
return destination
|
|
198
|
+
def create(self, **options):
|
|
199
|
+
payload = self.client.request("/data/destinations", method="POST", body=options)
|
|
200
|
+
return AgentVMDataDestination(self.client, payload["destination"]), payload.get("signingSecret")
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
class _DataRouteCollection:
|
|
204
|
+
def __init__(self, client: AgentVM): self.client = client
|
|
205
|
+
def list(self): return [AgentVMDataRoute(self.client, item) for item in self.client.request("/data/routes").get("routes", [])]
|
|
206
|
+
def get(self, route_id: str):
|
|
207
|
+
route = self.client.data_route(route_id)
|
|
208
|
+
route.refresh()
|
|
209
|
+
return route
|
|
210
|
+
def create(self, **options):
|
|
211
|
+
return AgentVMDataRoute(self.client, self.client.request("/data/routes", method="POST", body=options)["route"])
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class _DataNamespace:
|
|
215
|
+
def __init__(self, client: AgentVM):
|
|
216
|
+
self.client = client
|
|
217
|
+
self.sources = _DataSourceCollection(client)
|
|
218
|
+
self.destinations = _DataDestinationCollection(client)
|
|
219
|
+
self.routes = _DataRouteCollection(client)
|
|
220
|
+
def overview(self): return self.client.request("/data/overview")
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
class AgentVMMachine:
|
|
224
|
+
def __init__(self, client: AgentVM, machine_id: str):
|
|
225
|
+
self.client = client
|
|
226
|
+
self.id = machine_id
|
|
227
|
+
self.data = None
|
|
228
|
+
self.files = _MachineFiles(self)
|
|
229
|
+
self.processes = _MachineProcesses(self)
|
|
230
|
+
self.connections = _MachineConnections(self)
|
|
231
|
+
self.static_egress = _MachineStaticEgress(self)
|
|
232
|
+
|
|
233
|
+
def refresh(self, refresh: bool = True):
|
|
234
|
+
query = "?refresh=true" if refresh else ""
|
|
235
|
+
payload = self.client.request(f"/compute/instances/{urllib.parse.quote(self.id)}{query}")
|
|
236
|
+
self.data = payload.get("instance", payload)
|
|
237
|
+
return self.data
|
|
238
|
+
|
|
239
|
+
def create_operation(self, body: Dict[str, Any]):
|
|
240
|
+
return self.client.request(f"/compute/instances/{urllib.parse.quote(self.id)}/operations", method="POST", body=body)["operation"]
|
|
241
|
+
|
|
242
|
+
def get_operation(self, operation_id: str):
|
|
243
|
+
return self.client.request(f"/compute/instances/{urllib.parse.quote(self.id)}/operations/{urllib.parse.quote(_required(operation_id, 'Operation ID'))}")["operation"]
|
|
244
|
+
|
|
245
|
+
def cancel_operation(self, operation_id: str):
|
|
246
|
+
return self.client.request(f"/compute/instances/{urllib.parse.quote(self.id)}/operations/{urllib.parse.quote(_required(operation_id, 'Operation ID'))}/cancel", method="POST", body={})["operation"]
|
|
247
|
+
|
|
248
|
+
def wait_operation(self, operation_id: str, timeout: float = 390.0, poll_interval: float = 0.5, on_stdout: Optional[Callable[[str], None]] = None, on_stderr: Optional[Callable[[str], None]] = None):
|
|
249
|
+
started = time.monotonic()
|
|
250
|
+
stdout_length = 0
|
|
251
|
+
stderr_length = 0
|
|
252
|
+
while time.monotonic() - started < timeout:
|
|
253
|
+
operation = self.get_operation(operation_id)
|
|
254
|
+
result = operation.get("result") or {}
|
|
255
|
+
stdout = str(result.get("stdout") or "")
|
|
256
|
+
stderr = str(result.get("stderr") or "")
|
|
257
|
+
if on_stdout and len(stdout) > stdout_length:
|
|
258
|
+
on_stdout(stdout[stdout_length:])
|
|
259
|
+
if on_stderr and len(stderr) > stderr_length:
|
|
260
|
+
on_stderr(stderr[stderr_length:])
|
|
261
|
+
stdout_length = max(stdout_length, len(stdout))
|
|
262
|
+
stderr_length = max(stderr_length, len(stderr))
|
|
263
|
+
if operation.get("status") in TERMINAL_OPERATION_STATES:
|
|
264
|
+
return operation
|
|
265
|
+
time.sleep(max(0.1, poll_interval))
|
|
266
|
+
raise TimeoutError(f"Timed out waiting for AgentVM operation {operation_id}.")
|
|
267
|
+
|
|
268
|
+
def exec(self, command, cwd: str = "/home/user", env: Optional[Dict[str, str]] = None, timeout_seconds: int = 300, wait_timeout: Optional[float] = None, poll_interval: float = 0.5, on_stdout=None, on_stderr=None):
|
|
269
|
+
streaming = bool(on_stdout or on_stderr)
|
|
270
|
+
operation = self.create_operation({"operationType": "exec", "command": _command(command), "cwd": cwd, "env": env or {}, "timeoutSeconds": timeout_seconds, "stream": streaming})
|
|
271
|
+
completed = self.wait_operation(operation["id"], timeout=wait_timeout or timeout_seconds + 90, poll_interval=poll_interval, on_stdout=on_stdout, on_stderr=on_stderr)
|
|
272
|
+
return {"operation": completed, **(completed.get("result") or {})}
|
|
273
|
+
|
|
274
|
+
def action(self, action: str):
|
|
275
|
+
normalized = str(action or "").strip().lower()
|
|
276
|
+
if normalized not in {"poweron", "reboot", "poweroff", "suspend", "resume", "destroy"}:
|
|
277
|
+
raise ValueError(f"Unsupported machine action: {action}")
|
|
278
|
+
payload = self.client.request(f"/compute/instances/{urllib.parse.quote(self.id)}/{normalized}", method="POST", body={})
|
|
279
|
+
self.data = payload.get("instance", self.data)
|
|
280
|
+
return self.data
|
|
281
|
+
|
|
282
|
+
def suspend(self): return self.action("suspend")
|
|
283
|
+
def resume(self): return self.action("resume")
|
|
284
|
+
|
|
285
|
+
def _filesystem(self, action: str, path: str, **values):
|
|
286
|
+
operation = self.create_operation({"operationType": "filesystem", "action": action, "path": path, **values})
|
|
287
|
+
completed = self.wait_operation(operation["id"])
|
|
288
|
+
if completed.get("status") != "completed":
|
|
289
|
+
raise AgentVMAPIError(completed.get("errorMessage") or f"Filesystem operation {completed['id']} failed.")
|
|
290
|
+
return completed.get("result") or {}
|
|
291
|
+
|
|
292
|
+
def _process(self, action: str, **values):
|
|
293
|
+
operation = self.create_operation({"operationType": "process", "action": action, **values})
|
|
294
|
+
completed = self.wait_operation(operation["id"])
|
|
295
|
+
if completed.get("status") != "completed":
|
|
296
|
+
raise AgentVMAPIError(completed.get("errorMessage") or f"Process operation {completed['id']} failed.")
|
|
297
|
+
return completed.get("result") or {}
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
class _MachineFiles:
|
|
301
|
+
def __init__(self, machine: AgentVMMachine): self.machine = machine
|
|
302
|
+
def list(self, path: str): return self.machine._filesystem("list", path)
|
|
303
|
+
def stat(self, path: str): return self.machine._filesystem("stat", path)
|
|
304
|
+
def read(self, path: str): return self.machine._filesystem("read", path)
|
|
305
|
+
def write(self, path: str, content: Union[str, bytes], create_parents: bool = True, mode: Optional[str] = None):
|
|
306
|
+
raw = content.encode("utf-8") if isinstance(content, str) else bytes(content)
|
|
307
|
+
return self.machine._filesystem("write", path, contentBase64=base64.b64encode(raw).decode("ascii"), createParents=create_parents, mode=mode)
|
|
308
|
+
def mkdir(self, path: str, exist_ok: bool = True): return self.machine._filesystem("mkdir", path, existOk=exist_ok)
|
|
309
|
+
def remove(self, path: str, recursive: bool = False): return self.machine._filesystem("remove", path, recursive=recursive)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class _MachineProcesses:
|
|
313
|
+
def __init__(self, machine: AgentVMMachine): self.machine = machine
|
|
314
|
+
def start(self, command, cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None, stdout_path: Optional[str] = None, stderr_path: Optional[str] = None):
|
|
315
|
+
return self.machine._process("start", command=_command(command), cwd=cwd, env=env, stdoutPath=stdout_path, stderrPath=stderr_path)
|
|
316
|
+
def list(self): return self.machine._process("list")
|
|
317
|
+
def status(self, process_id: str): return self.machine._process("status", processId=process_id)
|
|
318
|
+
def kill(self, process_id: str, signal: str = "TERM"): return self.machine._process("kill", processId=process_id, signal=signal)
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
class _MachineStaticEgress:
|
|
322
|
+
def __init__(self, machine): self.machine = machine
|
|
323
|
+
def get(self): return self.machine.client.request(f"/compute/instances/{urllib.parse.quote(self.machine.id)}/static-egress")
|
|
324
|
+
def enable(self): return self.machine.client.request(f"/compute/instances/{urllib.parse.quote(self.machine.id)}/static-egress/enable", method="POST", body={})
|
|
325
|
+
def disable(self): return self.machine.client.request(f"/compute/instances/{urllib.parse.quote(self.machine.id)}/static-egress/disable", method="POST", body={})
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
class _MachineConnections:
|
|
329
|
+
def __init__(self, machine: AgentVMMachine): self.machine = machine
|
|
330
|
+
def list(self): return self.machine.client.connections.list(instance_id=self.machine.id)
|
|
331
|
+
def create(self, **options): return self.machine.client.connections.create(instanceId=self.machine.id, **options)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
class AgentVMVolume:
|
|
335
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Volume ID")
|
|
336
|
+
def refresh(self): self.data = self.client.request(f"/compute/volumes/{urllib.parse.quote(self.id)}").get("volume", {}); return self.data
|
|
337
|
+
def attach(self, instance_id: str, mount_path: str = "/data"): return self.client.request(f"/compute/volumes/{urllib.parse.quote(self.id)}/attach", method="POST", body={"instanceId": _required(instance_id, "Machine ID"), "mountPath": mount_path})
|
|
338
|
+
def detach(self): return self.client.request(f"/compute/volumes/{urllib.parse.quote(self.id)}/detach", method="POST", body={})
|
|
339
|
+
def delete(self): return self.client.request(f"/compute/volumes/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
class AgentVMNetworkIdentity:
|
|
343
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Network identity ID")
|
|
344
|
+
def refresh(self): self.data = self.client.request(f"/compute/network-identities/{urllib.parse.quote(self.id)}").get("networkIdentity", {}); return self.data
|
|
345
|
+
def attach(self, instance_id: str): return self.client.request(f"/compute/network-identities/{urllib.parse.quote(self.id)}/attach", method="POST", body={"instanceId": _required(instance_id, "Machine ID")})
|
|
346
|
+
def detach(self): return self.client.request(f"/compute/network-identities/{urllib.parse.quote(self.id)}/detach", method="POST", body={})
|
|
347
|
+
def set_ptr(self, hostname: Optional[str]):
|
|
348
|
+
payload = self.client.request(f"/compute/network-identities/{urllib.parse.quote(self.id)}/ptr", method="POST", body={"hostname": hostname})
|
|
349
|
+
self.data = payload.get("networkIdentity", self.data)
|
|
350
|
+
return self.data
|
|
351
|
+
def delete(self): return self.client.request(f"/compute/network-identities/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
class AgentVMDnsZone:
|
|
355
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "DNS zone ID")
|
|
356
|
+
def refresh(self): self.data = self.client.request(f"/network/dns/zones/{urllib.parse.quote(self.id)}").get("zone", {}); return self.data
|
|
357
|
+
def upsert_record(self, **record): return self.client.request(f"/network/dns/zones/{urllib.parse.quote(self.id)}/records", method="POST", body=record).get("recordSet", {})
|
|
358
|
+
def delete_record(self, name: str, record_type: str): return self.client.request(f"/network/dns/zones/{urllib.parse.quote(self.id)}/records/delete", method="POST", body={"name": name, "type": record_type})
|
|
359
|
+
def bind(self, network_identity_id: str, record_name: str = "@", ptr_hostname: Optional[str] = None, ttl: Optional[int] = None):
|
|
360
|
+
payload = self.client.request(f"/network/dns/zones/{urllib.parse.quote(self.id)}/bind", method="POST", body={"networkIdentityId": _required(network_identity_id, "Network identity ID"), "recordName": record_name, "ptrHostname": ptr_hostname, "ttl": ttl})
|
|
361
|
+
self.data = payload.get("zone", self.data)
|
|
362
|
+
return self.data
|
|
363
|
+
def delete(self): return self.client.request(f"/network/dns/zones/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
class AgentVMConnection:
|
|
367
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Connection ID")
|
|
368
|
+
def refresh(self): self.data = self.client.request(f"/connections/{urllib.parse.quote(self.id)}").get("connection", {}); return self.data
|
|
369
|
+
def update(self, **changes): self.data = self.client.request(f"/connections/{urllib.parse.quote(self.id)}", method="PATCH", body=changes).get("connection", self.data); return self.data
|
|
370
|
+
def delete(self): return self.client.request(f"/connections/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class AgentVMDataSource:
|
|
374
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Data source ID")
|
|
375
|
+
def refresh(self): self.data = self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}").get("source", {}); return self.data
|
|
376
|
+
def update(self, **changes): self.data = self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}", method="PATCH", body=changes).get("source", self.data); return self.data
|
|
377
|
+
def delete(self): return self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
378
|
+
def rotate_token(self):
|
|
379
|
+
payload = self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}/rotate-token", method="POST", body={})
|
|
380
|
+
self.data = payload.get("source", self.data)
|
|
381
|
+
return payload.get("token")
|
|
382
|
+
def deliveries(self): return self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}/deliveries").get("deliveries", [])
|
|
383
|
+
def delivery(self, delivery_id: str):
|
|
384
|
+
payload = self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}/deliveries/{urllib.parse.quote(_required(delivery_id, 'Delivery ID'))}")
|
|
385
|
+
return payload.get("delivery", payload)
|
|
386
|
+
def replay(self, delivery_id: str): return self.client.request(f"/data/sources/{urllib.parse.quote(self.id)}/deliveries/{urllib.parse.quote(_required(delivery_id, 'Delivery ID'))}/replay", method="POST", body={})
|
|
387
|
+
|
|
388
|
+
|
|
389
|
+
class AgentVMDataDestination:
|
|
390
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Data destination ID")
|
|
391
|
+
def refresh(self): self.data = self.client.request(f"/data/destinations/{urllib.parse.quote(self.id)}").get("destination", {}); return self.data
|
|
392
|
+
def update(self, **changes): self.data = self.client.request(f"/data/destinations/{urllib.parse.quote(self.id)}", method="PATCH", body=changes).get("destination", self.data); return self.data
|
|
393
|
+
def delete(self): return self.client.request(f"/data/destinations/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
394
|
+
def rotate_signing_secret(self):
|
|
395
|
+
payload = self.client.request(f"/data/destinations/{urllib.parse.quote(self.id)}/rotate-signing-secret", method="POST", body={})
|
|
396
|
+
self.data = payload.get("destination", self.data)
|
|
397
|
+
return payload.get("signingSecret")
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
class AgentVMDataRoute:
|
|
401
|
+
def __init__(self, client: AgentVM, data: Dict[str, Any]): self.client, self.data, self.id = client, data or {}, _required((data or {}).get("id"), "Data route ID")
|
|
402
|
+
def refresh(self): self.data = self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}").get("route", {}); return self.data
|
|
403
|
+
def update(self, **changes): self.data = self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}", method="PATCH", body=changes).get("route", self.data); return self.data
|
|
404
|
+
def delete(self): return self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}", method="DELETE")
|
|
405
|
+
def deliveries(self): return self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}/deliveries").get("deliveries", [])
|
|
406
|
+
def delivery(self, delivery_id: str):
|
|
407
|
+
payload = self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}/deliveries/{urllib.parse.quote(_required(delivery_id, 'Route delivery ID'))}")
|
|
408
|
+
return payload.get("delivery", payload)
|
|
409
|
+
def replay(self, delivery_id: str): return self.client.request(f"/data/routes/{urllib.parse.quote(self.id)}/deliveries/{urllib.parse.quote(_required(delivery_id, 'Route delivery ID'))}/replay", method="POST", body={})
|
agentvm/sandbox_cli.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""CLI for manifest-based Shared Sandbox execution (macOS and Linux)."""
|
|
2
|
+
import argparse
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import sqlite3
|
|
6
|
+
import sys
|
|
7
|
+
import urllib.error
|
|
8
|
+
|
|
9
|
+
from .client import AgentVM, AgentVMAPIError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _tasks(path):
|
|
13
|
+
with open(path, encoding="utf-8") as source:
|
|
14
|
+
for number, line in enumerate(source, 1):
|
|
15
|
+
if not line.strip():
|
|
16
|
+
continue
|
|
17
|
+
try:
|
|
18
|
+
task = json.loads(line)
|
|
19
|
+
if not isinstance(task, dict) or set(task) != {"id", "script"}:
|
|
20
|
+
raise ValueError("expected id and script")
|
|
21
|
+
except (ValueError, TypeError) as error:
|
|
22
|
+
raise ValueError(f"Invalid manifest entry on line {number}; expected id and script.") from error
|
|
23
|
+
yield task
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def main(argv=None):
|
|
27
|
+
parser = argparse.ArgumentParser(description="Plan and drive local Shared Sandbox batches.")
|
|
28
|
+
sub = parser.add_subparsers(dest="action", required=True)
|
|
29
|
+
plan = sub.add_parser("plan", help="Quote and create a private checkpoint; no execution")
|
|
30
|
+
plan.add_argument("manifest")
|
|
31
|
+
plan.add_argument("checkpoint")
|
|
32
|
+
plan.add_argument("--profile", default="small")
|
|
33
|
+
plan.add_argument("--seconds", type=int, default=60)
|
|
34
|
+
run = sub.add_parser("run", help="Launch or resume the same checkpoint")
|
|
35
|
+
run.add_argument("checkpoint")
|
|
36
|
+
run.add_argument("--max-usd", required=True, help="Explicit ceiling for the entire batch (0 for nonbillable preview)")
|
|
37
|
+
run.add_argument("--concurrency", type=int, choices=(1, 2), default=1)
|
|
38
|
+
run.add_argument("--poll-interval", type=float, default=5)
|
|
39
|
+
run.add_argument("--timeout", type=float, default=3600)
|
|
40
|
+
for action in ("status", "results"):
|
|
41
|
+
sub.add_parser(action).add_argument("checkpoint")
|
|
42
|
+
sub.add_parser("cancel").add_argument("run_id")
|
|
43
|
+
args = parser.parse_args(argv)
|
|
44
|
+
try:
|
|
45
|
+
token = os.getenv("AGENTVM_API_KEY") or os.getenv("AGENTVM_ACCESS_TOKEN")
|
|
46
|
+
if args.action in {"plan", "run", "cancel"} and not token:
|
|
47
|
+
raise ValueError("Set AGENTVM_API_KEY or AGENTVM_ACCESS_TOKEN securely in the environment.")
|
|
48
|
+
sandboxes = AgentVM(api_key=token).sandboxes
|
|
49
|
+
if args.action == "plan":
|
|
50
|
+
batch = sandboxes.prepare_batch(args.checkpoint, _tasks(args.manifest), profile=args.profile, seconds=args.seconds)
|
|
51
|
+
result = batch.summary()
|
|
52
|
+
elif args.action == "run":
|
|
53
|
+
result = sandboxes.batch(args.checkpoint).run(maximum_usd=args.max_usd, concurrency=args.concurrency,
|
|
54
|
+
poll_interval=args.poll_interval, timeout=args.timeout)
|
|
55
|
+
print(json.dumps(result, indent=2))
|
|
56
|
+
return 0 if result["states"].get("completed", 0) == result["count"] else 1
|
|
57
|
+
elif args.action == "status":
|
|
58
|
+
result = sandboxes.batch(args.checkpoint).summary()
|
|
59
|
+
elif args.action == "results":
|
|
60
|
+
for record in sandboxes.batch(args.checkpoint).results():
|
|
61
|
+
print(json.dumps(record, ensure_ascii=True))
|
|
62
|
+
return 0
|
|
63
|
+
else:
|
|
64
|
+
result = sandboxes.cancel(args.run_id)
|
|
65
|
+
# Cancellation is a request, not confirmation of termination.
|
|
66
|
+
result = {"id": result["id"], "state": result["state"]}
|
|
67
|
+
print(json.dumps(result, indent=2))
|
|
68
|
+
return 0
|
|
69
|
+
except KeyboardInterrupt:
|
|
70
|
+
print("Interrupted. Preserve the checkpoint; remote jobs may still be active.", file=sys.stderr)
|
|
71
|
+
return 130
|
|
72
|
+
except AgentVMAPIError as error:
|
|
73
|
+
print(f"Sandbox API error: HTTP {error.status}, {error.code or 'request_failed'}. Preserve the checkpoint if created.", file=sys.stderr)
|
|
74
|
+
except (urllib.error.URLError, TimeoutError, ConnectionError):
|
|
75
|
+
print("Sandbox API connection or wait timed out. Preserve the checkpoint; remote jobs may still be active.", file=sys.stderr)
|
|
76
|
+
except (ValueError, RuntimeError, OSError, sqlite3.Error, KeyError, TypeError) as error:
|
|
77
|
+
print(f"Sandbox batch error ({type(error).__name__}): {error}", file=sys.stderr)
|
|
78
|
+
return 2
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
if __name__ == "__main__":
|
|
82
|
+
sys.exit(main())
|
agentvm/sandboxes.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
"""Bounded CPU jobs and a local, resumable CI/evaluation batch driver."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sqlite3
|
|
8
|
+
import stat
|
|
9
|
+
import time
|
|
10
|
+
import urllib.parse
|
|
11
|
+
import urllib.error
|
|
12
|
+
import uuid
|
|
13
|
+
from contextlib import closing, contextmanager
|
|
14
|
+
from decimal import Decimal
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
TERMINAL = {"completed", "failed", "cancelled"}
|
|
18
|
+
ACTIVE = {"queued", "dispatching", "running", "cancel_requested"}
|
|
19
|
+
RUN_ID = re.compile(r"sbox_[a-f0-9]{32}\Z")
|
|
20
|
+
REQUEST_ID = re.compile(r"[A-Za-z0-9_-]{12,100}\Z")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _usd(value):
|
|
24
|
+
if not re.fullmatch(r"[0-9]+(?:\.[0-9]{1,6})?", str(value)):
|
|
25
|
+
raise ValueError("USD must be a nonnegative decimal with at most six fractional digits.")
|
|
26
|
+
return Decimal(str(value))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _validate_task(profile, seconds, script, limits):
|
|
30
|
+
if not isinstance(profile, str) or not profile:
|
|
31
|
+
raise ValueError("A sandbox profile is required.")
|
|
32
|
+
if type(seconds) is not int or not 1 <= seconds <= limits["maximumRuntimeSeconds"]:
|
|
33
|
+
raise ValueError("Runtime exceeds the published sandbox limits.")
|
|
34
|
+
if not isinstance(script, str) or not script.strip() or len(script.encode("utf-8")) > limits["maximumScriptBytes"]:
|
|
35
|
+
raise ValueError("Script must be nonempty and fit the published byte limit.")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class SharedSandboxes:
|
|
39
|
+
"""Direct REST access; the server remains responsible for authorization and billing."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, client):
|
|
42
|
+
self.client = client
|
|
43
|
+
|
|
44
|
+
def _require_secure_url(self):
|
|
45
|
+
parsed = urllib.parse.urlsplit(self.client.base_url)
|
|
46
|
+
if parsed.scheme != "https" and not (parsed.scheme == "http" and parsed.hostname in {"localhost", "127.0.0.1", "::1"}):
|
|
47
|
+
raise ValueError("Shared Sandbox API requires HTTPS outside loopback.")
|
|
48
|
+
if parsed.username or parsed.password or parsed.query or parsed.fragment:
|
|
49
|
+
raise ValueError("Invalid Shared Sandbox API base URL.")
|
|
50
|
+
|
|
51
|
+
def _request(self, path, **options):
|
|
52
|
+
self._require_secure_url()
|
|
53
|
+
return self.client.request(path, **options)
|
|
54
|
+
|
|
55
|
+
def catalog(self):
|
|
56
|
+
return self._request("/public/shared-sandboxes")["catalog"]
|
|
57
|
+
|
|
58
|
+
def access(self):
|
|
59
|
+
return self._request("/shared-sandboxes/access")["access"]
|
|
60
|
+
|
|
61
|
+
def owner(self):
|
|
62
|
+
owner = self._request("/me")["user"]["id"]
|
|
63
|
+
if not isinstance(owner, str) or not owner:
|
|
64
|
+
raise ValueError("Could not determine the authenticated account.")
|
|
65
|
+
return owner
|
|
66
|
+
|
|
67
|
+
def quote(self, profile, seconds, jobs=1):
|
|
68
|
+
return self._request("/public/shared-sandboxes/quote", method="POST", body={
|
|
69
|
+
"profileId": profile, "durationSeconds": seconds, "jobs": jobs,
|
|
70
|
+
})["estimate"]
|
|
71
|
+
|
|
72
|
+
def submit(self, *, profile, seconds, script, request_id, expected_maximum_charge=None):
|
|
73
|
+
if not isinstance(request_id, str) or not REQUEST_ID.fullmatch(request_id):
|
|
74
|
+
raise ValueError("A stable 12–100 character request ID is required.")
|
|
75
|
+
body = {"profileId": profile, "maximumRuntimeSeconds": seconds, "script": script,
|
|
76
|
+
"clientRequestId": request_id}
|
|
77
|
+
if expected_maximum_charge is not None:
|
|
78
|
+
_usd(expected_maximum_charge)
|
|
79
|
+
body["expectedMaximumCharge"] = str(expected_maximum_charge)
|
|
80
|
+
return self._request("/shared-sandboxes", method="POST", body=body)["run"]
|
|
81
|
+
|
|
82
|
+
def get(self, run_id):
|
|
83
|
+
if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id):
|
|
84
|
+
raise ValueError("Invalid sandbox run ID.")
|
|
85
|
+
return self._request(f"/shared-sandboxes/{run_id}")["run"]
|
|
86
|
+
|
|
87
|
+
def cancel(self, run_id):
|
|
88
|
+
if not isinstance(run_id, str) or not RUN_ID.fullmatch(run_id):
|
|
89
|
+
raise ValueError("Invalid sandbox run ID.")
|
|
90
|
+
return self._request(f"/shared-sandboxes/{run_id}/cancel", method="POST", body={})["run"]
|
|
91
|
+
|
|
92
|
+
def prepare_batch(self, path, tasks, *, profile="small", seconds=60):
|
|
93
|
+
return SandboxBatch.prepare(self, path, tasks, profile=profile, seconds=seconds)
|
|
94
|
+
|
|
95
|
+
def batch(self, path):
|
|
96
|
+
return SandboxBatch(self, path)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
@contextmanager
|
|
100
|
+
def _exclusive(path):
|
|
101
|
+
# Keep the driver lock separate from SQLite's own database locks (macOS).
|
|
102
|
+
# Resolve symlink aliases; keep this sidecar inode stable across acquisitions.
|
|
103
|
+
# Never run a checkpoint from multiple hosts, hard-link it, or rename it in use.
|
|
104
|
+
import fcntl
|
|
105
|
+
checkpoint = Path(path).resolve(strict=True)
|
|
106
|
+
if checkpoint.stat().st_nlink != 1:
|
|
107
|
+
raise ValueError("Hard-linked sandbox checkpoints are not supported.")
|
|
108
|
+
lock_path = checkpoint.with_name(checkpoint.name + ".driver.lock")
|
|
109
|
+
fd = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
|
|
110
|
+
with os.fdopen(fd, "rb+") as handle:
|
|
111
|
+
lock_stat = os.fstat(handle.fileno())
|
|
112
|
+
if not stat.S_ISREG(lock_stat.st_mode) or lock_stat.st_nlink != 1:
|
|
113
|
+
raise ValueError("Invalid sandbox driver lock file.")
|
|
114
|
+
try:
|
|
115
|
+
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
116
|
+
except BlockingIOError as error:
|
|
117
|
+
raise RuntimeError("This batch is already being driven by another local process.") from error
|
|
118
|
+
try:
|
|
119
|
+
yield
|
|
120
|
+
finally:
|
|
121
|
+
fcntl.flock(handle, fcntl.LOCK_UN)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _connect(path):
|
|
125
|
+
db = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=rw", uri=True)
|
|
126
|
+
db.row_factory = sqlite3.Row
|
|
127
|
+
return db
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class SandboxBatch:
|
|
131
|
+
"""Local SQLite checkpoint, not a server-side scheduler or a capacity reservation."""
|
|
132
|
+
|
|
133
|
+
def __init__(self, sandboxes, path):
|
|
134
|
+
self.sandboxes = sandboxes
|
|
135
|
+
self.path = Path(path)
|
|
136
|
+
|
|
137
|
+
@classmethod
|
|
138
|
+
def prepare(cls, sandboxes, path, tasks, *, profile, seconds):
|
|
139
|
+
catalog = sandboxes.catalog()
|
|
140
|
+
limits = {"maximumRuntimeSeconds": catalog["maximumRuntimeSeconds"],
|
|
141
|
+
"maximumScriptBytes": catalog.get("maximumScriptBytes", 4096)}
|
|
142
|
+
access = sandboxes.access()
|
|
143
|
+
if not access.get("canLaunch"):
|
|
144
|
+
raise RuntimeError("This account cannot launch Shared Sandboxes.")
|
|
145
|
+
owner = sandboxes.owner()
|
|
146
|
+
quote = sandboxes.quote(profile, seconds)
|
|
147
|
+
if quote["currency"] != "USD" or quote["chargeable"] != access["billingEnabled"]:
|
|
148
|
+
raise RuntimeError("Sandbox quote and execution mode disagree. Prepare again after checking access.")
|
|
149
|
+
rate = str(quote["perJobAmount"])
|
|
150
|
+
if _usd(rate) <= 0:
|
|
151
|
+
raise ValueError("A positive configured sandbox rate is required.")
|
|
152
|
+
path = Path(path)
|
|
153
|
+
# Exclusive creation; never overwrite a checkpoint or its request IDs.
|
|
154
|
+
fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
155
|
+
os.close(fd)
|
|
156
|
+
try:
|
|
157
|
+
with closing(_connect(path)) as db, db:
|
|
158
|
+
db.execute("CREATE TABLE meta (value TEXT NOT NULL)")
|
|
159
|
+
db.execute("""CREATE TABLE tasks (seq INTEGER PRIMARY KEY, task_id TEXT UNIQUE NOT NULL,
|
|
160
|
+
script TEXT NOT NULL, request_id TEXT UNIQUE NOT NULL, state TEXT NOT NULL DEFAULT 'pending',
|
|
161
|
+
run_id TEXT, result TEXT)""")
|
|
162
|
+
db.execute("CREATE INDEX task_state ON tasks(state, seq)")
|
|
163
|
+
batch_id = uuid.uuid4().hex
|
|
164
|
+
count = 0
|
|
165
|
+
for task in tasks:
|
|
166
|
+
count += 1
|
|
167
|
+
if count > 50000:
|
|
168
|
+
raise ValueError("A local batch may contain at most 50,000 tasks; this is not a concurrency guarantee.")
|
|
169
|
+
task_id, script = task["id"], task["script"]
|
|
170
|
+
if not isinstance(task_id, str) or not task_id.strip() or len(task_id) > 200:
|
|
171
|
+
raise ValueError("Task ID must be a nonempty string of at most 200 characters.")
|
|
172
|
+
_validate_task(profile, seconds, script, limits)
|
|
173
|
+
request_id = "batch_" + hashlib.sha256(f"{batch_id}\0{task_id}".encode()).hexdigest()
|
|
174
|
+
db.execute("INSERT INTO tasks (task_id, script, request_id) VALUES (?, ?, ?)",
|
|
175
|
+
(task_id, script, request_id))
|
|
176
|
+
if not count:
|
|
177
|
+
raise ValueError("Batch must contain at least one task.")
|
|
178
|
+
info = {"version": 1, "batchId": batch_id, "owner": owner, "apiUrl": sandboxes.client.base_url,
|
|
179
|
+
"profile": profile, "seconds": seconds, "chargeable": quote["chargeable"],
|
|
180
|
+
"perJobAmount": rate, "count": count,
|
|
181
|
+
"estimatedMaximumUsd": str(_usd(rate) * count),
|
|
182
|
+
"maximumChargeUsd": str(_usd(rate) * count) if quote["chargeable"] else "0"}
|
|
183
|
+
db.execute("INSERT INTO meta VALUES (?)", (json.dumps(info),))
|
|
184
|
+
except BaseException:
|
|
185
|
+
path.unlink(missing_ok=True)
|
|
186
|
+
raise
|
|
187
|
+
return cls(sandboxes, path)
|
|
188
|
+
|
|
189
|
+
@staticmethod
|
|
190
|
+
def _info(db):
|
|
191
|
+
info = json.loads(db.execute("SELECT value FROM meta").fetchone()[0])
|
|
192
|
+
if info.get("version") != 1:
|
|
193
|
+
raise ValueError("Unsupported sandbox checkpoint format.")
|
|
194
|
+
return info
|
|
195
|
+
|
|
196
|
+
def summary(self):
|
|
197
|
+
with closing(_connect(self.path)) as db:
|
|
198
|
+
info = self._info(db)
|
|
199
|
+
counts = dict(db.execute("SELECT state, COUNT(*) FROM tasks GROUP BY state").fetchall())
|
|
200
|
+
# Owner and API URL are only needed for resume validation.
|
|
201
|
+
return {**{key: value for key, value in info.items() if key not in {"owner", "apiUrl"}}, "states": counts}
|
|
202
|
+
|
|
203
|
+
def results(self):
|
|
204
|
+
"""Yield one record per manifest entry, including pending or ambiguous submissions."""
|
|
205
|
+
with closing(_connect(self.path)) as db:
|
|
206
|
+
for row in db.execute("SELECT task_id, request_id, state, run_id, result FROM tasks ORDER BY seq"):
|
|
207
|
+
yield {"id": row["task_id"], "requestId": row["request_id"], "state": row["state"],
|
|
208
|
+
"runId": row["run_id"], "run": json.loads(row["result"]) if row["result"] else None}
|
|
209
|
+
|
|
210
|
+
@staticmethod
|
|
211
|
+
def _record(db, row, run, owner):
|
|
212
|
+
run_id, state = run["id"], run["state"]
|
|
213
|
+
expected_id = "sbox_" + hashlib.sha256(f"{owner}\0{row['request_id']}".encode()).hexdigest()[:32]
|
|
214
|
+
if run_id != expected_id or (row["run_id"] and row["run_id"] != run_id):
|
|
215
|
+
raise RuntimeError("Unexpected sandbox run identity; checkpoint preserved.")
|
|
216
|
+
if state not in ACTIVE | TERMINAL:
|
|
217
|
+
raise RuntimeError("Unknown sandbox state; checkpoint preserved.")
|
|
218
|
+
if state == "completed" and run.get("exitCode") != 0:
|
|
219
|
+
# Never report a passing CI job when the server has no successful exit code.
|
|
220
|
+
local_state = "failed"
|
|
221
|
+
else:
|
|
222
|
+
local_state = state if state in TERMINAL else "active"
|
|
223
|
+
with db:
|
|
224
|
+
db.execute("UPDATE tasks SET state=?, run_id=?, result=? WHERE seq=?",
|
|
225
|
+
(local_state, run_id, json.dumps(run), row["seq"]))
|
|
226
|
+
|
|
227
|
+
@staticmethod
|
|
228
|
+
def _retryable(error):
|
|
229
|
+
from .client import AgentVMAPIError
|
|
230
|
+
if isinstance(error, AgentVMAPIError):
|
|
231
|
+
return error.status in {429, 500, 502, 504}
|
|
232
|
+
return isinstance(error, (urllib.error.URLError, TimeoutError, ConnectionError))
|
|
233
|
+
|
|
234
|
+
def run(self, *, maximum_usd, concurrency=1, poll_interval=5, timeout=3600):
|
|
235
|
+
"""Drive the batch until terminal or timeout. Never retry a terminal workload.
|
|
236
|
+
|
|
237
|
+
The full planned charge must be authorized on every invocation. On an
|
|
238
|
+
uncertain submission, resume the same file; do not prepare a new batch.
|
|
239
|
+
"""
|
|
240
|
+
ceiling = _usd(maximum_usd)
|
|
241
|
+
if type(concurrency) is not int or not 1 <= concurrency <= 2:
|
|
242
|
+
raise ValueError("Pilot concurrency must be 1 or 2 per local batch.")
|
|
243
|
+
if not math.isfinite(poll_interval) or poll_interval < 1 or not math.isfinite(timeout) or timeout <= 0:
|
|
244
|
+
raise ValueError("poll_interval must be >=1 second and timeout must be positive.")
|
|
245
|
+
deadline = time.monotonic() + timeout
|
|
246
|
+
with _exclusive(self.path), closing(_connect(self.path)) as db:
|
|
247
|
+
info = self._info(db)
|
|
248
|
+
if info["apiUrl"] != self.sandboxes.client.base_url or info["owner"] != self.sandboxes.owner():
|
|
249
|
+
raise RuntimeError("Checkpoint belongs to a different API or authenticated account.")
|
|
250
|
+
if ceiling < _usd(info["maximumChargeUsd"]):
|
|
251
|
+
raise ValueError("Explicit USD ceiling is below the full planned maximum charge.")
|
|
252
|
+
access = self.sandboxes.access()
|
|
253
|
+
if not access.get("canLaunch") or access["billingEnabled"] != info["chargeable"]:
|
|
254
|
+
raise RuntimeError("Execution access or billing mode changed; checkpoint preserved.")
|
|
255
|
+
while True:
|
|
256
|
+
if time.monotonic() >= deadline:
|
|
257
|
+
raise TimeoutError("Batch wait expired; resume the same checkpoint. Remote runs may still be active.")
|
|
258
|
+
outstanding = db.execute("SELECT * FROM tasks WHERE state IN ('active','submitting') ORDER BY seq").fetchall()
|
|
259
|
+
# Resolve accepted and uncertain jobs before launching any new work.
|
|
260
|
+
for row in outstanding:
|
|
261
|
+
if time.monotonic() >= deadline:
|
|
262
|
+
break
|
|
263
|
+
try:
|
|
264
|
+
if row["run_id"]:
|
|
265
|
+
run = self.sandboxes.get(row["run_id"])
|
|
266
|
+
else:
|
|
267
|
+
run = self._submit(info, row)
|
|
268
|
+
self._record(db, row, run, info["owner"])
|
|
269
|
+
except Exception as error:
|
|
270
|
+
if not self._retryable(error):
|
|
271
|
+
raise
|
|
272
|
+
occupied = db.execute("SELECT COUNT(*) FROM tasks WHERE state IN ('active','submitting')").fetchone()[0]
|
|
273
|
+
pending = db.execute("SELECT * FROM tasks WHERE state='pending' ORDER BY seq LIMIT ?",
|
|
274
|
+
(max(0, concurrency - occupied),)).fetchall()
|
|
275
|
+
for row in pending:
|
|
276
|
+
if time.monotonic() >= deadline:
|
|
277
|
+
break
|
|
278
|
+
# Commit intent before sending any potentially billable request.
|
|
279
|
+
with db:
|
|
280
|
+
db.execute("UPDATE tasks SET state='submitting' WHERE seq=?", (row["seq"],))
|
|
281
|
+
try:
|
|
282
|
+
self._record(db, row, self._submit(info, row), info["owner"])
|
|
283
|
+
except Exception as error:
|
|
284
|
+
if not self._retryable(error):
|
|
285
|
+
raise
|
|
286
|
+
if not db.execute("SELECT 1 FROM tasks WHERE state IN ('pending','active','submitting') LIMIT 1").fetchone():
|
|
287
|
+
return self.summary()
|
|
288
|
+
remaining = deadline - time.monotonic()
|
|
289
|
+
if remaining > 0:
|
|
290
|
+
time.sleep(min(poll_interval, remaining))
|
|
291
|
+
|
|
292
|
+
def _submit(self, info, row):
|
|
293
|
+
return self.sandboxes.submit(profile=info["profile"], seconds=info["seconds"], script=row["script"],
|
|
294
|
+
request_id=row["request_id"],
|
|
295
|
+
expected_maximum_charge=info["perJobAmount"] if info["chargeable"] else None)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: agentvms
|
|
3
|
+
Version: 0.14.18
|
|
4
|
+
Summary: First-party Python SDK for AgentVM managed computers, Shared Sandboxes and Data Relay
|
|
5
|
+
Author: WunderCorp
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://agentvm.sh
|
|
8
|
+
Keywords: agentvm,agents,cloud,virtual-machines,iot
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
|
|
14
|
+
# AgentVM Python SDK
|
|
15
|
+
|
|
16
|
+
First-party synchronous Python SDK for AgentVM machines, Data Relay, Connections, and persistent volumes.
|
|
17
|
+
|
|
18
|
+
Install from PyPI (Python 3.10 or later):
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
python -m pip install agentvms
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
If you installed the previous `wundercorp-agentvm` distribution, uninstall it first and then install `agentvms`. Both distributions use the same `agentvm` import namespace and should not be installed together.
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from agentvm import AgentVM
|
|
28
|
+
|
|
29
|
+
client = AgentVM()
|
|
30
|
+
machine = client.machines.get("vm_...")
|
|
31
|
+
result = machine.exec("python3 job.py", on_stdout=print)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
The SDK uses only the Python standard library at runtime.
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
Data Relay and Connections use lifecycle objects that mirror the Node SDK:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
source, token = client.data.sources.create(name="sensor", type="mqtt", brokerUrl="mqtts://broker.example.com", topicFilter="sensors/#")
|
|
41
|
+
deliveries = source.deliveries()
|
|
42
|
+
delivery = source.delivery(deliveries[0]["id"])
|
|
43
|
+
source.replay(delivery["id"])
|
|
44
|
+
|
|
45
|
+
destination, signing_secret = client.data.destinations.create(name="warehouse", type="http", url="https://example.com/hook")
|
|
46
|
+
route = client.data.routes.create(name="sensor-to-warehouse", sourceId=source.id, destinationId=destination.id)
|
|
47
|
+
connection = client.connections.create(instanceId=machine.id, name="github", baseUrl="https://api.github.com", allowedMethods=["GET"], allowedPathPrefixes=["/repos"])
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
## Shared Sandbox workloads (pilot)
|
|
51
|
+
|
|
52
|
+
The SDK includes `client.sandboxes` and the `agentvm-sandbox` command for bounded CPU scripts, CI test shards and offline evaluations. Prepare a private local checkpoint, explicitly authorize the total maximum charge, and resume the same file after interruptions. The existing pilot limits and server billing gates still apply. See the [CI and RL workloads guide](https://agentvm.sh/docs?doc=sandbox-workloads) for commands, supported workloads and limitations.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
agentvm/__init__.py,sha256=zVKrwEvWBtCPoHHVE0BXXc7dhBGD9DKJPFb2vgWwxig,590
|
|
2
|
+
agentvm/client.py,sha256=OrU0ql6cXWU32CQ_JspHarm131N1vfvvLzzUr1HMz0s,24711
|
|
3
|
+
agentvm/sandbox_cli.py,sha256=Csf-kBqCJsy8ghonqZPdWdRpEzG-gmHFJMIYRfXGIdg,4057
|
|
4
|
+
agentvm/sandboxes.py,sha256=7GX13SddDESwU1QAc55mDgxu8xpwecqnHDyw6UXBY9Y,15133
|
|
5
|
+
agentvms-0.14.18.dist-info/METADATA,sha256=Zj6QFHZBBX7RzYOdZuM38zYPHHVwz_k2BZ0dsX14pcg,2347
|
|
6
|
+
agentvms-0.14.18.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
7
|
+
agentvms-0.14.18.dist-info/entry_points.txt,sha256=AH-QDaspdKQsYxNz0ssgd3RZrHrvnCuYqUsVMlJ6xH4,61
|
|
8
|
+
agentvms-0.14.18.dist-info/top_level.txt,sha256=Xxjwl3g6Y3s04QdKBB97gKMia6nY8_mLghT37CXvZOA,8
|
|
9
|
+
agentvms-0.14.18.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
agentvm
|