Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/source/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ A few integrations ship as optional extras. Install them with
|-------|----------|
| `inspect` | The Inspect AI evaluation harness |
| `harbor` | The [Harbor integration](environments/harbor) and its sandbox backends (Python 3.12+) |
| `daytona`, `aca`, `modal`, `novita` | Cloud sandbox providers (see [Runtime Providers](guides/runtime-providers)) |
| `daytona`, `aca`, `modal`, `novita`, `groundbox` | Cloud sandbox providers (see [Runtime Providers](guides/runtime-providers)) |

## Try an Environment

Expand Down Expand Up @@ -155,7 +155,7 @@ with EchoEnv(base_url="http://localhost:8000").sync() as client:
result = client.reset()
```

The same client also runs environments on cloud sandboxes (Daytona, Modal, Novita, Azure Container Apps, Hugging Face) and on a Kubernetes cluster through runtime providers. `HFSandboxProvider` ships with core OpenEnv and needs a Hugging Face token for an account that can run Jobs (the sandboxes are billed as Jobs): it runs an environment's Space image in a Hugging Face sandbox ([example](guides/runtime-providers#hfsandboxprovider)). `KubernetesProvider` is an optional extra (`pip install openenv[kubernetes]`, [example](guides/runtime-providers#kubernetesprovider)). See the [Runtime Providers guide](guides/runtime-providers) to pick one.
The same client also runs environments on cloud sandboxes (Daytona, Modal, Novita, Azure Container Apps, Groundbox, Hugging Face) and on a Kubernetes cluster through runtime providers. `HFSandboxProvider` ships with core OpenEnv and needs a Hugging Face token for an account that can run Jobs (the sandboxes are billed as Jobs): it runs an environment's Space image in a Hugging Face sandbox ([example](guides/runtime-providers#hfsandboxprovider)). `KubernetesProvider` is an optional extra (`pip install openenv[kubernetes]`, [example](guides/runtime-providers#kubernetesprovider)). See the [Runtime Providers guide](guides/runtime-providers) to pick one.

## Next Steps

Expand Down
46 changes: 44 additions & 2 deletions docs/source/guides/runtime-providers.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ is a one-line change.
| `ACASandboxProvider` | Azure Container Apps Sandboxes | `pip install openenv[aca]` | ✅ |
| `ModalProvider` | Modal sandboxes | `pip install openenv[modal]` | ✅ |
| `NovitaSandboxProvider` | Novita AI sandboxes | `pip install openenv[novita]` | ✅ |
| `GroundboxProvider` | Groundbox sandboxes (microVMs) | `pip install openenv[groundbox]` | ✅ |
| `HFSandboxProvider` | Hugging Face sandboxes (billed as HF Jobs) | core | ✅ |
| `KubernetesProvider` | Kubernetes cluster | `pip install openenv[kubernetes]` | ✅ |

Expand Down Expand Up @@ -91,8 +92,8 @@ async with MyEnv(provider=provider) as env:
...
```

`ModalProvider`, `DaytonaProvider`, `ACASandboxProvider`, and `HFSandboxProvider`
support this provider-owned flow. Providers that require an explicit image at
`ModalProvider`, `DaytonaProvider`, `ACASandboxProvider`, `GroundboxProvider`, and
`HFSandboxProvider` support this provider-owned flow. Providers that require an explicit image at
`start_container()` time, such as `LocalDockerProvider` and
`DockerSwarmProvider`, should still be started manually and passed in with the
returned `base_url`:
Expand Down Expand Up @@ -205,6 +206,47 @@ from openenv.core.containers.runtime import DockerSwarmProvider
provider = DockerSwarmProvider()
```

### GroundboxProvider

Runs the server in a [Groundbox](https://groundbox.dev) sandbox, a Linux microVM
of its own. Install with `pip install openenv[groundbox]`. Sign in once in the
browser, which saves an API key (a new account gets free credit):

```bash
openenv groundbox login
```

The key is kept where the Groundbox CLI keeps it
(`~/.config/groundbox/credentials.json`). `GROUNDBOX_API_KEY` or `api_key=` take
precedence, for CI and other machines without a browser.

The sandbox starts from a Docker image, such as an environment's Space image, or
from a Groundbox template. The first sandbox from an image waits while the image
is turned into a disk; later ones start in about a second.

```python
from echo_env import EchoEnv
from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider

provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest")
base_url = provider.start_container()
try:
provider.wait_for_ready(base_url)
with EchoEnv(base_url=base_url).sync() as env:
env.reset()
finally:
provider.stop_container()
```

Images must be `linux/amd64` and public, or pushed to your Groundbox registry.
Groundbox does not run the image's `CMD`: the server command comes from the
image's `openenv.yaml` (as for Daytona), or from `cmd=`. `cpus` and `memory_gb`
size the sandbox, and `timeout_minutes` (default 60) deletes it even if
`stop_container()` is never called. The server's port gets a public HTTPS URL
with an unguessable host name, which ends with the sandbox.

Full example: [`examples/groundbox_echo_env.py`](https://github.com/openenv/OpenEnv/blob/main/examples/groundbox_echo_env.py).

### HFSandboxProvider

Runs the server in a Hugging Face sandbox, when your Hugging Face account is
Expand Down
11 changes: 11 additions & 0 deletions docs/source/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,17 @@ pass the key through `OPENAI_API_KEY` instead.

[[autodoc]] openenv.cli.commands.collect.collect

## `openenv groundbox login`

Signs in to Groundbox in the browser for
[`GroundboxProvider`](../guides/runtime-providers#groundboxprovider) and saves
an API key where the Groundbox CLI keeps it. A new account is made on the way,
with free credit. It uses OAuth with PKCE and a redirect to `127.0.0.1`, so no
key is copied by hand. `GROUNDBOX_OAUTH_CLIENT_ID` overrides OpenEnv's OAuth
client; set it empty to register a new client for each sign-in. `--no-browser` prints the link instead of opening it.

[[autodoc]] openenv.cli.commands.groundbox.login

## `openenv harbor`

Runs [Harbor](../environments/harbor) tasks with real coding agents and
Expand Down
2 changes: 2 additions & 0 deletions docs/source/reference/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ See [Evaluating with Environments](../tutorials/evaluation-inspect) for a worked

[[autodoc]] openenv.core.containers.runtime.novita_provider.NovitaSandboxProvider

[[autodoc]] openenv.core.containers.runtime.groundbox_provider.GroundboxProvider

[[autodoc]] openenv.core.containers.runtime.hf_sandbox_provider.HFSandboxProvider

[[autodoc]] openenv.core.containers.runtime.kubernetes_provider.KubernetesProvider
50 changes: 50 additions & 0 deletions examples/groundbox_echo_env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#!/usr/bin/env python3
"""Hello-world example running the Echo environment on Groundbox.

Starts the echo-env server in a Groundbox sandbox from its Hugging Face Space
image via ``GroundboxProvider``, then talks to it through ``EchoEnv`` over the
sandbox's HTTPS preview URL (https/wss). The sandbox is deleted at the
end.

Usage:
pip install "openenv[groundbox]"
openenv groundbox login (one-time; or set GROUNDBOX_API_KEY)
PYTHONPATH=src:envs uv run python examples/groundbox_echo_env.py
"""

import logging

from echo_env import EchoEnv
from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider
from openenv.core.env_server.mcp_types import CallToolAction

logger = logging.getLogger(__name__)


def main() -> int:
logging.basicConfig(level=logging.INFO, format="%(message)s")

provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest")
logger.info(
"Starting Groundbox sandbox (the first start from an image is slower)..."
)
base_url = provider.start_container()
try:
provider.wait_for_ready(base_url)
logger.info("Server ready in sandbox %s.", provider.sandbox_id)
with EchoEnv(base_url=base_url).sync() as env:
env.reset()
result = env.step(
CallToolAction(
tool_name="echo_message", arguments={"message": "Hello, World!"}
)
)
logger.info("echo_message -> %s", result.observation)
finally:
provider.stop_container()
logger.info("Sandbox deleted.")
return 0


if __name__ == "__main__":
raise SystemExit(main())
3 changes: 3 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ modal = [
"modal>=1.6.3",
"pyyaml>=6.0",
]
groundbox = [
"groundbox>=0.6.0",
]
kubernetes = [
"kubernetes>=29.0.0",
]
Expand Down
6 changes: 6 additions & 0 deletions src/openenv/cli/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
catalog,
collect,
fork,
groundbox,
harbor,
import_env,
init,
Expand Down Expand Up @@ -44,6 +45,11 @@
name="harbor",
help="Run Harbor tasks with token-level capture (requires: pip install openenv\\[harbor])",
)
app.add_typer(
groundbox.app,
name="groundbox",
help="Sign in to Groundbox for GroundboxProvider",
)
app.command(name="validate", help="Validate a package against the OpenEnv quality bar")(
validate.validate
)
Expand Down
166 changes: 166 additions & 0 deletions src/openenv/cli/commands/groundbox.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
# SPDX-License-Identifier: BSD-3-Clause

"""Sign in to Groundbox, for `GroundboxProvider`."""

from __future__ import annotations

import base64
import hashlib
import json
import os
import secrets
import time
import webbrowser
from http.server import BaseHTTPRequestHandler, HTTPServer
from typing import Annotated
from urllib.parse import parse_qs, urlencode, urlsplit

import requests
import typer
from openenv.core.containers.runtime.groundbox_provider import (
groundbox_credentials_path,
)

from .._cli_utils import console

app = typer.Typer(no_args_is_help=True)

_SCOPES = "sandboxes:read sandboxes:write"
# OpenEnv's public OAuth client on Groundbox (PKCE, no secret). Override with
# GROUNDBOX_OAUTH_CLIENT_ID; set it empty to register a client for each login.
_CLIENT_ID = "gbc_N9uJ9s2zobxBqPp8mDOsfsMW"
_PAGE = "<!doctype html><title>OpenEnv</title><p style='font-family:sans-serif'>{}</p>"


def _oauth_origin() -> str:
api = urlsplit(os.environ.get("GROUNDBOX_API_URL", "https://api.groundbox.dev/v1"))
return f"{api.scheme}://{api.netloc}"


def _wait_for_redirect(server: HTTPServer, timeout_s: float) -> dict[str, str]:
"""Serve the loopback redirect until it brings `code` or `error`."""
answer: dict[str, str] = {}

class Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None:
url = urlsplit(self.path)
params = {k: v[0] for k, v in parse_qs(url.query).items()}
if url.path != "/callback" or not ("code" in params or "error" in params):
self.send_response(404)
self.end_headers()
return
answer.update(params)
text = (
"Signed in to Groundbox. You can close this tab."
if "code" in params
else "Sign-in did not finish. Run the command again."
)
body = _PAGE.format(text).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def log_message(self, *args: object) -> None:
pass

server.RequestHandlerClass = Handler
deadline = time.monotonic() + timeout_s
while not answer:
server.timeout = deadline - time.monotonic()
if server.timeout <= 0:
raise TimeoutError("Nobody finished signing in to Groundbox in time.")
server.handle_request()
return answer


@app.command()
def login(
no_browser: Annotated[
bool,
typer.Option(
"--no-browser", help="Print the sign-in link instead of opening it"
),
] = False,
timeout: Annotated[
float,
typer.Option("--timeout", help="Seconds to wait for the sign-in to finish"),
] = 600.0,
) -> None:
"""Sign in to Groundbox in the browser and save an API key for GroundboxProvider.

A new account is made on the way, with free credit. The key is saved where the
Groundbox CLI keeps it (`~/.config/groundbox/credentials.json`).
"""
origin = _oauth_origin()
server = HTTPServer(("127.0.0.1", 0), BaseHTTPRequestHandler)
redirect_uri = f"http://127.0.0.1:{server.server_port}/callback"
try:
client_id = os.environ.get("GROUNDBOX_OAUTH_CLIENT_ID", _CLIENT_ID)
if not client_id:
registered = requests.post(
f"{origin}/oauth/register",
json={
"client_name": "OpenEnv",
"redirect_uris": ["http://127.0.0.1/callback"],
},
timeout=30,
)
registered.raise_for_status()
client_id = registered.json()["client_id"]

verifier = secrets.token_urlsafe(48)
challenge = (
base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest())
.rstrip(b"=")
.decode()
)
state = secrets.token_urlsafe(24)
authorize_url = f"{origin}/oauth/authorize?" + urlencode(
{
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": _SCOPES,
"state": state,
"code_challenge": challenge,
"code_challenge_method": "S256",
"prompt": "create",
}
)
console.print("Sign in to Groundbox (a new account gets free credit):")
console.print(authorize_url, soft_wrap=True)
if not no_browser:
webbrowser.open(authorize_url)

answer = _wait_for_redirect(server, timeout)
finally:
server.server_close()

if answer.get("state") != state:
console.print("[red]Groundbox sign-in came back with the wrong state.[/red]")
raise typer.Exit(1)
if "error" in answer:
console.print(f"[red]Groundbox sign-in failed: {answer['error']}[/red]")
raise typer.Exit(1)

token = requests.post(
f"{origin}/oauth/token",
data={
"grant_type": "authorization_code",
"code": answer["code"],
"redirect_uri": redirect_uri,
"client_id": client_id,
"code_verifier": verifier,
},
timeout=30,
)
token.raise_for_status()

path = groundbox_credentials_path()
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump({"api_key": token.json()["access_token"]}, f, indent=2)
console.print(f"Signed in to Groundbox. The API key is saved in {path}.")
Loading