Metadata-Version: 2.5
Name: groundbox
Version: 0.6.0
Summary: Python SDK for the Groundbox API: sandboxes and CI runners for your agents
Project-URL: Homepage, https://groundbox.dev
Project-URL: Documentation, https://groundbox.dev/docs
Author-email: Groundbox <contact@groundbox.dev>
License-Expression: MIT
License-File: LICENSE
Keywords: agents,ci,groundbox,sandbox,sdk
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries
Classifier: Typing :: Typed
Requires-Python: >=3.9
Description-Content-Type: text/markdown

# groundbox

The Python client for the Groundbox API: sandboxes and CI runners for your agents.

```sh
pip install groundbox
```

## Quickstart

```python
from groundbox import Groundbox
gb = Groundbox()  # reads GROUNDBOX_API_KEY
sandbox = gb.create_sandbox(cpus=2)
print(gb.run_command(sandbox["id"], "uname -a")["stdout"])
gb.delete_sandbox(sandbox["id"])
```

`list_sandboxes` keeps stopped and failed sandboxes. To get only the ones that are not over, or only some: `gb.list_sandboxes(live=True, metadata={"project": "alpha"})`, or `status=["running", "paused"]`.

`make_dir`, `stat_file`, `file_exists` and `delete_file` (with `recursive=True` for a folder that has files in it) work on single paths.

A failed call raises `GroundboxError` with the API's `code`, `status` and `request_id`. A version too old for the API raises `UpgradeRequiredError` (code `upgrade_required`), with `upgrade`, the command that fixes it. Python 3.9 or newer, standard library only.

## Updates

The SDK never prints. `gb.latest_version` is the newest version the API has named, or `None` before the first call. To hear of a newer one, pass a callback:

```python
gb = Groundbox(on_update_available=lambda u: print(f"groundbox {u['latest']} is out (you have {u['current']}): {u['upgrade']}"))
```

It is called once per new version.

## From a Docker image

`image` starts a sandbox from a Docker image, with no template made first: a public image, one in your Groundbox registry, or a private image on another registry with its login.

```python
sandbox = gb.create_sandbox(image="python:3.12-slim")
sandbox = gb.wait_for_sandbox(sandbox["id"])  # running, or failed with sandbox["error"]
print(gb.run_command(sandbox["id"], "python -V")["stdout"])
```

The first sandbox from an image comes back `queued` while the image is turned into a disk; later ones start like a template's. Commands run as root with the image's `ENV`. Its `ENTRYPOINT`, `CMD`, `USER` and `WORKDIR` are not used: start your program with a command and pass `cwd`.

A private image on another registry (ghcr.io, Docker Hub, ECR, Artifact Registry) takes `image_auth`: the username and the name of a team secret that holds the password or token. The key needs `secrets:use`; a refused login is a 400 with `details.reason` `registry_auth_failed`. ECR and Artifact Registry tokens expire: set the secret again before they do. Templates take `image_auth` too.

```python
sandbox = gb.create_sandbox(
    image="ghcr.io/acme/app:1",
    image_auth={"username": "bot", "password_secret": "GHCR_TOKEN"},
)
```

A command is a string (a shell line, run with `sh -c`) or a list (a program and its arguments, run with no shell). `stdin` is text or bytes; `encoding="base64"` returns the output as base64, byte for byte.

```python
gb.run_command(sandbox["id"], ["git", "commit", "-m", "Fix the $PATH bug"])
print(gb.run_command(sandbox["id"], ["python3", "-"], stdin="print(6 * 7)\n")["stdout"])
```

Commands in the background: `start_command` returns at once with the command's id, `get_command_output` reads what it printed from a position, `follow_command` yields output until it ends, `list_commands` is the sandbox's command history (everything run there, by any client, filtered by `status` and `kind`, paged with `cursor`), and `kill_command` ends one.

```python
server = gb.start_command(sandbox["id"], "npm run dev", cwd="/home/runner/app")
for part in gb.follow_command(sandbox["id"], server["id"]):
    print(part["stdout"], end="")
```

## Commands as root

By default commands run as `runner`, the image's own user, which has `sudo` with no password. `user: "root"` makes every command run as root instead, with no `sudo` in front:

```python
sandbox = gb.create_sandbox(user="root")
print(gb.run_command(sandbox["id"], "id -u")["stdout"])  # 0
```

It covers `exec`, `run`, streams, background commands and the file calls (a file you write is root's). Your `env`, `PATH` and `cwd` are kept; `HOME` stays `/home/runner`. The user is set once: forks keep it, and a sandbox started from a snapshot has the user of the sandbox the snapshot was taken of. `sandbox["user"]` says which. A sandbox from an image is always root.

## Snapshots

A snapshot keeps a sandbox as it is at one moment: memory, disk and running processes. It stays when the sandbox is deleted, and new sandboxes start from it.

```python
snapshot = gb.keep_snapshot(sandbox["id"], label="deps installed")
gb.delete_sandbox(sandbox["id"])
copy = gb.create_sandbox(snapshot_id=snapshot["id"])
gb.list_snapshots()
gb.delete_snapshot(snapshot["id"])
```

`keep_snapshot` waits until the snapshot is ready. Pass `snapshot_id` to keep one of the sandbox's save points instead of the moment now; that also works while the sandbox is paused. Storage is billed per GB-month like a paused sandbox.

## Templates and volumes

A template is a ready-made disk (an image, a Dockerfile or a list of packages) built once. Sandboxes of the template's exact size start from its warm snapshot in well under a second.

```python
gb.create_template("python-ml", image="python:3.12-slim", pip=["numpy", "pandas"])
for line in gb.follow_template_logs("python-ml", 1):
    print(line["text"])
gb.create_volume(10, name="data")
sandbox = gb.create_sandbox(template="python-ml", volumes=[{"volume": "data", "path": "/data"}])
```

A Storage bucket can be a folder in a sandbox: files written there stay in the bucket after the sandbox is deleted, and every sandbox that mounts it sees them.

```python
gb.create_bucket("results")
worker = gb.create_sandbox(buckets=[{"bucket": "results", "path": "/mnt/results"}])
# worker["buckets"][0]["status"] is "mounted", or "failed" with "error"
```

## Webhooks

Groundbox POSTs a signed JSON event to your URL when something happens: `ci.job.failed`, `ci.diagnosis.completed`, and sandbox, snapshot and volume events (`groundbox webhooks events` lists them). The secret is in the answer to `create_webhook` once; check every delivery with it before you trust it.

```python
from groundbox import Groundbox, verify_webhook_signature

made = gb.create_webhook("https://example.com/groundbox", events=["ci.job.failed", "ci.diagnosis.completed"])
webhook, secret = made["webhook"], made["secret"]
gb.test_webhook(webhook["id"])  # "status" is "delivered" or "failed", with "status_code" and "error"
gb.list_webhook_deliveries(webhook["id"])
gb.update_webhook(webhook["id"], enabled=False)

# In your endpoint: the raw body, before any JSON parsing.
ok = verify_webhook_signature(secret, raw_body, headers.get("Groundbox-Signature"))
```

The header is `Groundbox-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`; `verify_webhook_signature` also refuses a `t` more than 300 seconds from now (`tolerance_seconds`). Answer 2xx within 10 seconds; anything else is tried again for about a day. An event's `id` stays the same across tries. Keys need `webhooks:read` to list and `webhooks:write` to change.

## Slack

The Groundbox Slack app posts to a channel when a CI job fails, then adds why it failed and what to do once the diagnosis is in (`groundbox slack events` lists what a channel can be sent; sandbox failures too, if picked). Adding it to a channel is a browser step: open `install_url` signed in as an owner or admin, and Slack asks which channel.

```python
page = gb.list_slack_connections()  # {"data": [...], "install_url": ...}; install_url is None when the Slack app is not set up
channel = page["data"][0]["id"]
gb.update_slack_connection(channel, events=["ci.job.failed", "ci.diagnosis.completed", "sandbox.failed"])
gb.test_slack_connection(channel)  # {"ok": True, "error": None}, or the error with what Slack said
gb.update_slack_connection(channel, enabled=False)
gb.delete_slack_connection(channel)  # remove the app in Slack to take its access away too
```

Keys need `webhooks:read` to list and `webhooks:write` to change.

## Merge queue

The merge queue tests each pull request on top of main and the pull requests ahead of it, and merges it only when that passes. It is included on the $20 plan; on the Free plan, turning a queue on or queueing a pull request answers `paid_plan_required` (402). The repo's workflows must run on push to `groundbox-queue/**` (`groundbox queue trigger` adds it). Reads need a key with `ci:read`, changes `ci:write`.

```python
gb.update_merge_queue_settings("acme/app")  # turns it on: depth 3, squash, every job required, auto_queue "ci_passes"
gb.update_merge_queue_settings("acme/app", auto_queue="approved")  # or "manual": only /merge and enqueue_merge
gb.enqueue_merge("acme/app", 678)
line = gb.get_merge_queue("acme/app")["entries"]  # next to land first, with eta_seconds
gb.dequeue_merge("acme/app", 678)
gb.get_merge_queue_history("acme/app", pr=678)
stats = gb.get_merge_queue_stats("acme/app", days=30)  # breaks caught, waits, CI cost per merge
gb.update_merge_queue_settings("acme/app", paused=True)
gb.list_merge_queues()

# Run the full tests once: the workflow change that takes the slow jobs off pull requests, as a diff per file.
change = gb.merge_queue_full_tests("acme/app", "queue", pr_jobs=["lint"])
gb.update_merge_queue_settings("acme/app", full_tests="queue")  # once the change is in the repo
```

Docs: https://groundbox.dev/docs
