agentvms 0.14.18__tar.gz
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.
- agentvms-0.14.18/PKG-INFO +52 -0
- agentvms-0.14.18/README.md +39 -0
- agentvms-0.14.18/pyproject.toml +29 -0
- agentvms-0.14.18/setup.cfg +4 -0
- agentvms-0.14.18/src/agentvm/__init__.py +29 -0
- agentvms-0.14.18/src/agentvm/client.py +409 -0
- agentvms-0.14.18/src/agentvm/sandbox_cli.py +82 -0
- agentvms-0.14.18/src/agentvm/sandboxes.py +295 -0
- agentvms-0.14.18/src/agentvms.egg-info/PKG-INFO +52 -0
- agentvms-0.14.18/src/agentvms.egg-info/SOURCES.txt +13 -0
- agentvms-0.14.18/src/agentvms.egg-info/dependency_links.txt +1 -0
- agentvms-0.14.18/src/agentvms.egg-info/entry_points.txt +2 -0
- agentvms-0.14.18/src/agentvms.egg-info/top_level.txt +1 -0
- agentvms-0.14.18/tests/test_sandboxes.py +224 -0
- agentvms-0.14.18/tests/test_sdk.py +116 -0
|
@@ -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,39 @@
|
|
|
1
|
+
# AgentVM Python SDK
|
|
2
|
+
|
|
3
|
+
First-party synchronous Python SDK for AgentVM machines, Data Relay, Connections, and persistent volumes.
|
|
4
|
+
|
|
5
|
+
Install from PyPI (Python 3.10 or later):
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
python -m pip install agentvms
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
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.
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
from agentvm import AgentVM
|
|
15
|
+
|
|
16
|
+
client = AgentVM()
|
|
17
|
+
machine = client.machines.get("vm_...")
|
|
18
|
+
result = machine.exec("python3 job.py", on_stdout=print)
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The SDK uses only the Python standard library at runtime.
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
Data Relay and Connections use lifecycle objects that mirror the Node SDK:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
source, token = client.data.sources.create(name="sensor", type="mqtt", brokerUrl="mqtts://broker.example.com", topicFilter="sensors/#")
|
|
28
|
+
deliveries = source.deliveries()
|
|
29
|
+
delivery = source.delivery(deliveries[0]["id"])
|
|
30
|
+
source.replay(delivery["id"])
|
|
31
|
+
|
|
32
|
+
destination, signing_secret = client.data.destinations.create(name="warehouse", type="http", url="https://example.com/hook")
|
|
33
|
+
route = client.data.routes.create(name="sensor-to-warehouse", sourceId=source.id, destinationId=destination.id)
|
|
34
|
+
connection = client.connections.create(instanceId=machine.id, name="github", baseUrl="https://api.github.com", allowedMethods=["GET"], allowedPathPrefixes=["/repos"])
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Shared Sandbox workloads (pilot)
|
|
38
|
+
|
|
39
|
+
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,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agentvms"
|
|
7
|
+
version = "0.14.18"
|
|
8
|
+
description = "First-party Python SDK for AgentVM managed computers, Shared Sandboxes and Data Relay"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = {text = "Apache-2.0"}
|
|
12
|
+
authors = [{name = "WunderCorp"}]
|
|
13
|
+
keywords = ["agentvm", "agents", "cloud", "virtual-machines", "iot"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"License :: OSI Approved :: Apache Software License"
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
agentvm-sandbox = "agentvm.sandbox_cli:main"
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Homepage = "https://agentvm.sh"
|
|
24
|
+
|
|
25
|
+
[tool.setuptools]
|
|
26
|
+
package-dir = {"" = "src"}
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
@@ -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
|
+
]
|
|
@@ -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={})
|
|
@@ -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())
|