groundbox 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
groundbox/__init__.py ADDED
@@ -0,0 +1,15 @@
1
+ """Groundbox Python SDK: sandboxes and CI for your agents.
2
+
3
+ from groundbox import Groundbox
4
+
5
+ gb = Groundbox() # GROUNDBOX_API_KEY, or Groundbox(api_key="gbx_...")
6
+ sandbox = gb.create_sandbox(cpus=2)
7
+ result = gb.run_command(sandbox["id"], "uname -a")
8
+ print(result["exit_code"], result["stdout"])
9
+ gb.delete_sandbox(sandbox["id"])
10
+ """
11
+
12
+ from .client import DEFAULT_BASE_URL, Groundbox, GroundboxError
13
+
14
+ __version__ = "0.1.0"
15
+ __all__ = ["DEFAULT_BASE_URL", "Groundbox", "GroundboxError", "__version__"]
groundbox/client.py ADDED
@@ -0,0 +1,299 @@
1
+ """The Groundbox API client. One method per MCP tool, with the same names.
2
+
3
+ Standard library only. Responses are the API's JSON as dicts; the shapes are in
4
+ packages/contracts/src/api.ts.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+ from typing import Any, Dict, List, Optional, Union
15
+
16
+ DEFAULT_BASE_URL = "https://api.groundbox.dev/v1"
17
+ _VERSION = "0.1.0"
18
+
19
+ Json = Dict[str, Any]
20
+
21
+
22
+ class GroundboxError(Exception):
23
+ """A call the API answered with an error, or could not be reached (status 0)."""
24
+
25
+ def __init__(
26
+ self,
27
+ code: str,
28
+ message: str,
29
+ status: int,
30
+ method: str,
31
+ path: str,
32
+ request_id: Optional[str] = None,
33
+ details: Optional[Json] = None,
34
+ ) -> None:
35
+ super().__init__(message)
36
+ #: The API's error code, "network" when no answer came, "bad_response" when it was not the API's JSON.
37
+ self.code = code
38
+ self.message = message
39
+ self.status = status
40
+ self.method = method
41
+ self.path = path
42
+ self.request_id = request_id
43
+ self.details = details
44
+
45
+ def __str__(self) -> str:
46
+ return f"{self.code}: {self.message}"
47
+
48
+
49
+ def _drop_none(values: Json) -> Json:
50
+ return {name: value for name, value in values.items() if value is not None}
51
+
52
+
53
+ class Groundbox:
54
+ """The Groundbox API.
55
+
56
+ api_key a gbx_... key; defaults to the GROUNDBOX_API_KEY environment variable
57
+ base_url the API's base, ending in /v1; defaults to GROUNDBOX_API_URL, then
58
+ https://api.groundbox.dev/v1
59
+ timeout seconds to wait for an answer; a command's own timeout is added to it
60
+ """
61
+
62
+ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, timeout: float = 60.0) -> None:
63
+ self.api_key = api_key if api_key is not None else os.environ.get("GROUNDBOX_API_KEY")
64
+ self.base_url = (base_url or os.environ.get("GROUNDBOX_API_URL") or DEFAULT_BASE_URL).rstrip("/")
65
+ self.timeout = timeout
66
+ #: The last call that failed, for send_feedback.
67
+ self.last_error: Optional[GroundboxError] = None
68
+
69
+ # ------------------------------------------------------------------
70
+ # Sandboxes
71
+ # ------------------------------------------------------------------
72
+
73
+ def create_sandbox(
74
+ self,
75
+ cpus: Optional[int] = None,
76
+ memory_gb: Optional[int] = None,
77
+ disk_gb: Optional[int] = None,
78
+ timeout_minutes: Optional[int] = None,
79
+ env: Optional[Dict[str, str]] = None,
80
+ metadata: Optional[Dict[str, str]] = None,
81
+ allow_hosts: Optional[List[str]] = None,
82
+ idempotency_key: Optional[str] = None,
83
+ ) -> Json:
84
+ """Start a sandbox. It is usually running when this returns; if it is still queued, commands wait for it."""
85
+ body = _drop_none(
86
+ {
87
+ "cpus": cpus,
88
+ "memory_gb": memory_gb,
89
+ "disk_gb": disk_gb,
90
+ "timeout_minutes": timeout_minutes,
91
+ "env": env,
92
+ "metadata": metadata,
93
+ "allow_hosts": allow_hosts,
94
+ }
95
+ )
96
+ return self._json("POST", "/sandboxes", body=body, idempotency_key=idempotency_key)
97
+
98
+ def list_sandboxes(self, status: Optional[str] = None, limit: Optional[int] = None, cursor: Optional[str] = None) -> Json:
99
+ return self._json("GET", "/sandboxes", query={"status": status, "limit": limit, "cursor": cursor})
100
+
101
+ def get_sandbox(self, sandbox_id: str) -> Json:
102
+ return self._json("GET", f"/sandboxes/{sandbox_id}")
103
+
104
+ def update_sandbox(
105
+ self,
106
+ sandbox_id: str,
107
+ timeout_minutes: Optional[int] = None,
108
+ metadata: Optional[Dict[str, str]] = None,
109
+ allow_hosts: Union[List[str], None, bool] = False,
110
+ ) -> Json:
111
+ """Renew the timeout (minutes from now), change the metadata or the allowlist.
112
+
113
+ allow_hosts=None removes the allowlist; leave it out to keep it.
114
+ """
115
+ body = _drop_none({"timeout_minutes": timeout_minutes, "metadata": metadata})
116
+ if allow_hosts is not False:
117
+ body["allow_hosts"] = allow_hosts
118
+ return self._json("PATCH", f"/sandboxes/{sandbox_id}", body=body)
119
+
120
+ def delete_sandbox(self, sandbox_id: str) -> Json:
121
+ """Stop and destroy a sandbox. Billing stops."""
122
+ return self._json("DELETE", f"/sandboxes/{sandbox_id}")
123
+
124
+ def pause_sandbox(self, sandbox_id: str) -> Json:
125
+ return self._json("POST", f"/sandboxes/{sandbox_id}/pause")
126
+
127
+ def resume_sandbox(self, sandbox_id: str) -> Json:
128
+ return self._json("POST", f"/sandboxes/{sandbox_id}/resume")
129
+
130
+ def fork_sandbox(
131
+ self,
132
+ sandbox_id: str,
133
+ timeout_minutes: Optional[int] = None,
134
+ metadata: Optional[Dict[str, str]] = None,
135
+ idempotency_key: Optional[str] = None,
136
+ ) -> Json:
137
+ """Copy a running sandbox into a second one with the same files and processes."""
138
+ body = _drop_none({"timeout_minutes": timeout_minutes, "metadata": metadata})
139
+ return self._json("POST", f"/sandboxes/{sandbox_id}/fork", body=body, idempotency_key=idempotency_key)
140
+
141
+ def get_sandbox_usage(self, sandbox_id: str) -> Json:
142
+ return self._json("GET", f"/sandboxes/{sandbox_id}/usage")
143
+
144
+ def run_command(
145
+ self,
146
+ sandbox_id: str,
147
+ cmd: str,
148
+ cwd: Optional[str] = None,
149
+ env: Optional[Dict[str, str]] = None,
150
+ timeout_s: Optional[int] = None,
151
+ ) -> Json:
152
+ """Run a command with sh -c and wait for it.
153
+
154
+ Returns exit_code, stdout, stderr, duration_ms and timed_out. A non-zero exit
155
+ code is a result, not an error.
156
+ """
157
+ body = _drop_none({"cmd": cmd, "cwd": cwd, "env": env, "timeout_s": timeout_s})
158
+ return self._json("POST", f"/sandboxes/{sandbox_id}/exec", body=body, timeout=self.timeout + (timeout_s or 60))
159
+
160
+ def write_file(self, sandbox_id: str, path: str, content: Union[str, bytes]) -> Json:
161
+ """Upload one file. Parent folders are made."""
162
+ data = content.encode("utf-8") if isinstance(content, str) else bytes(content)
163
+ return self._json("PUT", f"/sandboxes/{sandbox_id}/files", query={"path": path}, data=data)
164
+
165
+ def read_file(self, sandbox_id: str, path: str) -> bytes:
166
+ """Download one file as bytes."""
167
+ return self._send("GET", f"/sandboxes/{sandbox_id}/files", query={"path": path})
168
+
169
+ def read_text_file(self, sandbox_id: str, path: str) -> str:
170
+ return self.read_file(sandbox_id, path).decode("utf-8")
171
+
172
+ def list_files(self, sandbox_id: str, dir: str) -> Json: # noqa: A002 - the API's own name
173
+ return self._json("GET", f"/sandboxes/{sandbox_id}/files", query={"dir": dir})
174
+
175
+ # ------------------------------------------------------------------
176
+ # Schedules, CI, account
177
+ # ------------------------------------------------------------------
178
+
179
+ def schedule_command(
180
+ self,
181
+ cron: str,
182
+ cmd: str,
183
+ name: Optional[str] = None,
184
+ timezone: Optional[str] = None,
185
+ sandbox: Optional[Json] = None,
186
+ ) -> Json:
187
+ """Run a command on a cron schedule, each time in a fresh sandbox."""
188
+ body = _drop_none({"cron": cron, "cmd": cmd, "name": name, "timezone": timezone, "sandbox": sandbox})
189
+ return self._json("POST", "/schedules", body=body)
190
+
191
+ def list_ci_runs(
192
+ self,
193
+ repo: Optional[str] = None,
194
+ branch: Optional[str] = None,
195
+ sha: Optional[str] = None,
196
+ status: Optional[str] = None,
197
+ limit: Optional[int] = None,
198
+ cursor: Optional[str] = None,
199
+ ) -> Json:
200
+ return self._json("GET", "/ci/runs", query={"repo": repo, "branch": branch, "sha": sha, "status": status, "limit": limit, "cursor": cursor})
201
+
202
+ def get_ci_logs(self, job_id: str) -> Json:
203
+ return self._json("GET", f"/ci/jobs/{job_id}/logs")
204
+
205
+ def wait_for_ci(
206
+ self,
207
+ repo: str,
208
+ branch: Optional[str] = None,
209
+ sha: Optional[str] = None,
210
+ run_id: Optional[int] = None,
211
+ timeout_s: Optional[int] = None,
212
+ ) -> Json:
213
+ """Wait for a push's CI: passed, failed (with the failing step's log) or timed_out."""
214
+ body = _drop_none({"repo": repo, "branch": branch, "sha": sha, "run_id": run_id, "timeout_s": timeout_s})
215
+ return self._json("POST", "/ci/wait", body=body, timeout=self.timeout + (timeout_s or 600))
216
+
217
+ def get_balance(self) -> Json:
218
+ """Balance, usage this month, limits and the key in use."""
219
+ return self._json("GET", "/account")
220
+
221
+ def signup(self, agent_name: Optional[str] = None, email: Optional[str] = None) -> Json:
222
+ """Agent self-signup: a key that works once a person opens claim_url and adds credits. Needs no key."""
223
+ return self._json("POST", "/signup", body=_drop_none({"agent_name": agent_name, "email": email}))
224
+
225
+ def send_feedback(self, message: str) -> Json:
226
+ """Tell the Groundbox team something did not work. The last failed call is sent along, without secrets."""
227
+ body: Json = {"message": message, "source": "api"}
228
+ last = self.last_error
229
+ if last is not None:
230
+ body["last_call"] = _drop_none(
231
+ {
232
+ "method": last.method,
233
+ "path": last.path,
234
+ "status": last.status or None,
235
+ "request_id": last.request_id,
236
+ "error": f"{last.code}: {last.message}"[:500],
237
+ }
238
+ )
239
+ return self._json("POST", "/feedback", body=body)
240
+
241
+ # ------------------------------------------------------------------
242
+ # plumbing
243
+ # ------------------------------------------------------------------
244
+
245
+ def _json(self, method: str, path: str, **options: Any) -> Json:
246
+ raw = self._send(method, path, **options)
247
+ try:
248
+ return json.loads(raw.decode("utf-8"))
249
+ except ValueError:
250
+ raise self._failed(GroundboxError("bad_response", f"{method} {path} did not answer with JSON", 200, method, path)) from None
251
+
252
+ def _send(
253
+ self,
254
+ method: str,
255
+ path: str,
256
+ query: Optional[Json] = None,
257
+ body: Optional[Json] = None,
258
+ data: Optional[bytes] = None,
259
+ idempotency_key: Optional[str] = None,
260
+ timeout: Optional[float] = None,
261
+ ) -> bytes:
262
+ url = f"{self.base_url}{path}"
263
+ params = _drop_none(query or {})
264
+ if params:
265
+ url += "?" + urllib.parse.urlencode(params)
266
+ headers = {"User-Agent": f"groundbox-python/{_VERSION}", "Accept": "application/json"}
267
+ if self.api_key:
268
+ headers["Authorization"] = f"Bearer {self.api_key}"
269
+ if idempotency_key:
270
+ headers["Idempotency-Key"] = idempotency_key
271
+ payload = data
272
+ if data is not None:
273
+ headers["Content-Type"] = "application/octet-stream"
274
+ elif body is not None or method in ("POST", "PATCH"):
275
+ headers["Content-Type"] = "application/json"
276
+ payload = json.dumps(body or {}).encode("utf-8")
277
+
278
+ request = urllib.request.Request(url, data=payload, headers=headers, method=method)
279
+ try:
280
+ with urllib.request.urlopen(request, timeout=timeout or self.timeout) as response:
281
+ return response.read()
282
+ except urllib.error.HTTPError as error:
283
+ raw = error.read()
284
+ request_id = error.headers.get("X-Request-Id")
285
+ try:
286
+ parsed = json.loads(raw.decode("utf-8"))["error"]
287
+ failure = GroundboxError(
288
+ parsed["code"], parsed["message"], error.code, method, path, parsed.get("request_id") or request_id, parsed.get("details")
289
+ )
290
+ except (ValueError, KeyError, TypeError):
291
+ failure = GroundboxError("bad_response", f"{method} {path} answered {error.code}", error.code, method, path, request_id)
292
+ raise self._failed(failure) from None
293
+ except (urllib.error.URLError, OSError) as error:
294
+ reason = getattr(error, "reason", error)
295
+ raise self._failed(GroundboxError("network", f"Could not reach {self.base_url}: {reason}", 0, method, path)) from None
296
+
297
+ def _failed(self, error: GroundboxError) -> GroundboxError:
298
+ self.last_error = error
299
+ return error
groundbox/py.typed ADDED
File without changes
@@ -0,0 +1,46 @@
1
+ Metadata-Version: 2.5
2
+ Name: groundbox
3
+ Version: 0.1.0
4
+ Summary: Python SDK for the Groundbox API: sandboxes and CI runners for your agents
5
+ Project-URL: Homepage, https://groundbox.dev
6
+ Project-URL: Documentation, https://groundbox.dev/docs
7
+ Author-email: Groundbox <contact@groundbox.dev>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: agents,ci,groundbox,sandbox,sdk
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3 :: Only
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Typing :: Typed
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+
26
+ # groundbox
27
+
28
+ The Python client for the Groundbox API: sandboxes and CI runners for your agents.
29
+
30
+ ```sh
31
+ pip install groundbox
32
+ ```
33
+
34
+ ## Quickstart
35
+
36
+ ```python
37
+ from groundbox import Groundbox
38
+ gb = Groundbox() # reads GROUNDBOX_API_KEY
39
+ sandbox = gb.create_sandbox(cpus=2)
40
+ print(gb.run_command(sandbox["id"], "uname -a")["stdout"])
41
+ gb.delete_sandbox(sandbox["id"])
42
+ ```
43
+
44
+ A failed call raises `GroundboxError` with the API's `code`, `status` and `request_id`. Python 3.9 or newer, standard library only.
45
+
46
+ Docs: https://groundbox.dev/docs
@@ -0,0 +1,7 @@
1
+ groundbox/__init__.py,sha256=LkTpINzl-M94Y952eMhe83wzmLZ6ZinZMy5MIh_Lm3Y,522
2
+ groundbox/client.py,sha256=9suf5wjY8MB2VilPbL1uRzJkeSQo1XKuLgfXsW9M0iM,12431
3
+ groundbox/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
+ groundbox-0.1.0.dist-info/METADATA,sha256=HBESMWlRUeB-4JJS9fbDRK7izyR-ZE09uG_2iDzZtb8,1542
5
+ groundbox-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ groundbox-0.1.0.dist-info/licenses/LICENSE,sha256=yAi3RG9w3tIHOXcL5LS_DHhLNYqcIRjyX7WyAIcnXgI,1080
7
+ groundbox-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Power Only Transit Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.