diff --git a/docs/source/getting-started.md b/docs/source/getting-started.md index e799629962..805b742765 100644 --- a/docs/source/getting-started.md +++ b/docs/source/getting-started.md @@ -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 @@ -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 diff --git a/docs/source/guides/runtime-providers.md b/docs/source/guides/runtime-providers.md index 5258d51730..64a46810d1 100644 --- a/docs/source/guides/runtime-providers.md +++ b/docs/source/guides/runtime-providers.md @@ -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]` | ✅ | @@ -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`: @@ -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 diff --git a/docs/source/reference/cli.md b/docs/source/reference/cli.md index 3c1e743e37..d2e0529e70 100644 --- a/docs/source/reference/cli.md +++ b/docs/source/reference/cli.md @@ -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 diff --git a/docs/source/reference/core.md b/docs/source/reference/core.md index fc0b672691..05c6374da2 100644 --- a/docs/source/reference/core.md +++ b/docs/source/reference/core.md @@ -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 diff --git a/examples/groundbox_echo_env.py b/examples/groundbox_echo_env.py new file mode 100644 index 0000000000..fc8c596912 --- /dev/null +++ b/examples/groundbox_echo_env.py @@ -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()) diff --git a/pyproject.toml b/pyproject.toml index bb11abf606..2ede6ef8c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -54,6 +54,9 @@ modal = [ "modal>=1.6.3", "pyyaml>=6.0", ] +groundbox = [ + "groundbox>=0.6.0", +] kubernetes = [ "kubernetes>=29.0.0", ] diff --git a/src/openenv/cli/__main__.py b/src/openenv/cli/__main__.py index b4f32159ec..388f883c7c 100644 --- a/src/openenv/cli/__main__.py +++ b/src/openenv/cli/__main__.py @@ -15,6 +15,7 @@ catalog, collect, fork, + groundbox, harbor, import_env, init, @@ -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 ) diff --git a/src/openenv/cli/commands/groundbox.py b/src/openenv/cli/commands/groundbox.py new file mode 100644 index 0000000000..c877c4c2e8 --- /dev/null +++ b/src/openenv/cli/commands/groundbox.py @@ -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 = "
{}
" + + +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}.") diff --git a/src/openenv/core/containers/runtime/groundbox_provider.py b/src/openenv/core/containers/runtime/groundbox_provider.py new file mode 100644 index 0000000000..6d3caf9f53 --- /dev/null +++ b/src/openenv/core/containers/runtime/groundbox_provider.py @@ -0,0 +1,329 @@ +# SPDX-License-Identifier: BSD-3-Clause + +""" +Groundbox container provider for running OpenEnv environments in Groundbox sandboxes. + +Requires the ``groundbox`` SDK: ``pip install openenv[groundbox]`` + +Each environment runs in its own Groundbox sandbox, a Linux microVM started +from a Docker image or a Groundbox template. The server's port gets an HTTPS +preview URL that ``EnvClient`` connects to over ``wss://``. +""" + +from __future__ import annotations + +import json +import os +import shlex +import time +from pathlib import Path +from typing import Any, Dict, Optional + +import requests + +from ._server_config import parse_openenv_app_field +from .providers import ContainerProvider + +_DEFAULT_PORT = 8000 +_LOG_PATH = "/tmp/openenv-server.log" +_PID_PATH = "/tmp/openenv-server.pid" +_KEY_HELP = ( + "Groundbox needs an API key. Run `openenv groundbox login` to sign in (a new " + "account gets free credit), set GROUNDBOX_API_KEY, or pass api_key=." +) + + +def groundbox_credentials_path() -> Path: + """Where the Groundbox CLI and `openenv groundbox login` keep the API key.""" + config_dir = os.environ.get("GROUNDBOX_CONFIG_DIR") + if config_dir: + return Path(config_dir) / "credentials.json" + xdg = os.environ.get("XDG_CONFIG_HOME") or str(Path.home() / ".config") + return Path(xdg) / "groundbox" / "credentials.json" + + +def _resolve_api_key(api_key: Optional[str]) -> str: + if api_key: + return api_key + if os.environ.get("GROUNDBOX_API_KEY"): + return os.environ["GROUNDBOX_API_KEY"] + path = groundbox_credentials_path() + if path.is_file(): + saved = json.loads(path.read_text()).get("api_key") + if saved: + return saved + raise RuntimeError(_KEY_HELP) + + +def _refusal(exc: Any) -> RuntimeError: + """A readable error for a create Groundbox refused.""" + details = exc.details or {} + if exc.code == "trial_credit_exhausted": + message = ( + "The Groundbox account's free credit is used up. Add a card at " + "https://app.groundbox.dev/billing to keep starting sandboxes." + ) + elif exc.code == "trial_limit" and details.get("limit") == "sandbox_lifetime": + message = ( + "On free credit a Groundbox sandbox lives at most " + f"{details.get('max_sandbox_minutes')} minutes. Pass a smaller " + "timeout_minutes, or add a card at https://app.groundbox.dev/billing." + ) + elif exc.code == "trial_limit": + message = ( + "Groundbox starts sandboxes this size once the account has a card on " + "file. Pass smaller cpus/memory_gb, or add a card at " + "https://app.groundbox.dev/billing." + ) + else: + message = f"Groundbox refused to start the sandbox ({exc.code}: {exc.message})" + return RuntimeError(message) + + +class GroundboxProvider(ContainerProvider): + """ + Container provider that runs environments in Groundbox sandboxes. + + The sandbox starts from a Docker image (pulled once and kept as a disk, so + later starts take about a second) or from a Groundbox template. Groundbox + does not run the image's `CMD`: the server command is `cmd`, or is found + from the image's `openenv.yaml`. The server's port gets a public HTTPS + preview URL with an unguessable host name, which ends with the sandbox. + + Args: + image (`str`, *optional*): + Docker image to start from, such as + `"registry.hf.space/openenv-echo-env:latest"`. Images must be + `linux/amd64` and public, or in your Groundbox registry. + template (`str`, *optional*): + Groundbox template (id, name or `name:version`) to start from + instead of an image. + env_vars (`dict[str, str]`, *optional*): + Environment variables for the server. + api_key (`str`, *optional*): + Groundbox API key. Falls back to `GROUNDBOX_API_KEY`, then to the + key saved by `openenv groundbox login` or `groundbox login`. + cpus (`int`, *optional*): + vCPUs for the sandbox. Groundbox's default when omitted. + memory_gb (`int`, *optional*): + Memory in GB, at most 4 per vCPU. Groundbox's default when omitted. + timeout_minutes (`int`, *optional*, defaults to `60`): + Lifetime of the sandbox. It is deleted after this long even if + `stop_container()` is never called. + cmd (`str`, *optional*): + Shell command that starts the server inside the sandbox. + create_timeout (`float`, *optional*, defaults to `600`): + Seconds to wait for the sandbox to start. The first sandbox from an + image waits while the image is turned into a disk. + + Examples: + + ```python + from openenv.core.containers.runtime.groundbox_provider import GroundboxProvider + from openenv.core.generic_client import GenericEnvClient + + provider = GroundboxProvider(image="registry.hf.space/openenv-echo-env:latest") + with GenericEnvClient(provider=provider).sync() as env: + env.reset() + ``` + """ + + def __init__( + self, + *, + image: Optional[str] = None, + template: Optional[str] = None, + env_vars: Optional[Dict[str, str]] = None, + api_key: Optional[str] = None, + cpus: Optional[int] = None, + memory_gb: Optional[int] = None, + timeout_minutes: int = 60, + cmd: Optional[str] = None, + create_timeout: float = 600, + ): + from groundbox import Groundbox + + if image is not None and template is not None: + raise ValueError("Pass image or template to GroundboxProvider, not both.") + self._client = Groundbox(api_key=_resolve_api_key(api_key)) + self._image = image + self._template = template + self._env_vars = env_vars + self._cpus = cpus + self._memory_gb = memory_gb + self._timeout_minutes = timeout_minutes + self._cmd = cmd + self._create_timeout = create_timeout + self._sandbox_id: Optional[str] = None + + @property + def sandbox_id(self) -> Optional[str]: + """Id of the running sandbox, or `None` when none is running.""" + return self._sandbox_id + + def start_container( + self, + image: Optional[str] = None, + port: Optional[int] = None, + env_vars: Optional[Dict[str, str]] = None, + **kwargs: Any, + ) -> str: + """ + Start a Groundbox sandbox and the environment server in it. + + Args: + image (`str`, *optional*): + Docker image, or `"template: