From 20ebd1a69db65a241fd065d587ae30d767848a23 Mon Sep 17 00:00:00 2001 From: Yash Shah Date: Wed, 19 Aug 2026 00:19:05 +0530 Subject: [PATCH] feat(init): add agentbox v0.1 foundation Self-hosted agent code execution API with FastAPI, subprocess sandbox, Python SDK client, Docker Compose service, and unit tests. --- .env.example | 5 ++ .github/workflows/ci.yml | 11 ++++ .gitignore | 4 ++ CHANGELOG.md | 8 +++ CONTRIBUTING.md | 15 +++++ LICENSE | 21 ++++++ README.md | 109 +++++++++++++++++++++++++++++++ compose.yaml | 26 ++++++++ docker/Dockerfile | 18 +++++ pyproject.toml | 39 +++++++++++ src/agentbox/__init__.py | 3 + src/agentbox/api/__init__.py | 0 src/agentbox/api/app.py | 51 +++++++++++++++ src/agentbox/cli.py | 33 ++++++++++ src/agentbox/config.py | 14 ++++ src/agentbox/sandbox/__init__.py | 0 src/agentbox/sandbox/runner.py | 46 +++++++++++++ src/agentbox/sdk/__init__.py | 0 src/agentbox/sdk/client.py | 22 +++++++ tests/test_api.py | 21 ++++++ tests/test_sdk.py | 9 +++ 21 files changed, 455 insertions(+) create mode 100644 .env.example create mode 100644 .github/workflows/ci.yml create mode 100644 .gitignore create mode 100644 CHANGELOG.md create mode 100644 CONTRIBUTING.md create mode 100644 LICENSE create mode 100644 README.md create mode 100644 compose.yaml create mode 100644 docker/Dockerfile create mode 100644 pyproject.toml create mode 100644 src/agentbox/__init__.py create mode 100644 src/agentbox/api/__init__.py create mode 100644 src/agentbox/api/app.py create mode 100644 src/agentbox/cli.py create mode 100644 src/agentbox/config.py create mode 100644 src/agentbox/sandbox/__init__.py create mode 100644 src/agentbox/sandbox/runner.py create mode 100644 src/agentbox/sdk/__init__.py create mode 100644 src/agentbox/sdk/client.py create mode 100644 tests/test_api.py create mode 100644 tests/test_sdk.py diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..f02b032 --- /dev/null +++ b/.env.example @@ -0,0 +1,5 @@ +AGENTBOX_HOST=0.0.0.0 +AGENTBOX_PORT=8080 +AGENTBOX_LOG_LEVEL=INFO +AGENTBOX_DEFAULT_TIMEOUT_SECONDS=30 +AGENTBOX_SANDBOX_BACKEND=subprocess diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..8adefc6 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,11 @@ +name: CI +on: [push, pull_request] +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: {python-version: "3.12"} + - run: pip install -e ".[dev]" + - run: pytest tests/ -v diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..aa21101 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +__pycache__/ +.venv/ +.pytest_cache/ +dist/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..370151b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,8 @@ +# Changelog + +## [0.1.0] - 2026-08-18 + +### Added +- FastAPI service with /health and /v1/run +- Subprocess sandbox backend (MVP) +- Python SDK client skeleton diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..7ba387d --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,15 @@ +# Contributing + +```bash +pip install -e ".[dev]" +pytest tests/ -v +agentbox serve +curl http://localhost:8080/health +``` + +Docker: + +```bash +docker compose up agentbox +docker compose run --rm test +``` diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f5ebae3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 agentbox contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..49f7002 --- /dev/null +++ b/README.md @@ -0,0 +1,109 @@ +# agentbox + +Self-hosted **code execution sandbox** for AI agents — one `docker compose up` gives you an HTTP API for running untrusted code in isolated environments. + +> **Status:** v0.1 foundation — FastAPI service with subprocess sandbox; gVisor/docker backends and snapshots are next. + +## Problem + +Every agent that writes and runs code needs a safe execution environment. Teams either YOLO in shared containers or pay per-second for hosted sandboxes. Self-hosting gVisor/Firecracker is weeks of work. + +## Key features (v0.1) + +- HTTP API: `POST /v1/run` executes Python code +- Health endpoint for orchestration +- Python SDK client +- Configurable timeout and output limits +- Docker Compose single-node deployment + +## Architecture + +``` +Agent / SDK + └── POST /v1/run + └── SubprocessSandbox (MVP) + └── (next) gVisor / Docker backend +``` + +| Component | Technology | Why | +|-----------|------------|-----| +| API | FastAPI | Async-ready, OpenAPI docs, widely adopted | +| Server | uvicorn | Standard ASGI server | +| Config | pydantic-settings | Typed env config | +| Tests | pytest + httpx TestClient | Fast API testing | + +## Installation + +```bash +pip install agentbox +pip install -e ".[dev]" +``` + +## Usage + +### Start server + +```bash +agentbox serve +# or +docker compose up agentbox +``` + +### Run code + +```bash +curl -X POST http://localhost:8080/v1/run \ + -H 'Content-Type: application/json' \ + -d '{"code": "print(sum(range(10)))"}' +``` + +### Python SDK + +```python +from agentbox.sdk.client import AgentboxClient + +client = AgentboxClient("http://localhost:8080") +print(client.health()) +print(client.run("print('hello')")) +client.close() +``` + +## Docker + +```bash +docker compose up agentbox # start API on :8080 +docker compose run --rm test # run unit tests +``` + +## Configuration + +| Variable | Default | Description | +|----------|---------|-------------| +| `AGENTBOX_HOST` | `0.0.0.0` | Bind host | +| `AGENTBOX_PORT` | `8080` | Bind port | +| `AGENTBOX_DEFAULT_TIMEOUT_SECONDS` | `30` | Execution timeout | +| `AGENTBOX_SANDBOX_BACKEND` | `subprocess` | Backend selector | + +## Running tests + +```bash +pytest tests/ -v +``` + +## Roadmap + +- [ ] gVisor runsc backend with warm pool +- [ ] Filesystem snapshot/restore +- [ ] Node.js and shell runtimes +- [ ] Default-deny egress with allowlists + +## License + +MIT + +## Known limitations (v0.1) + +- Subprocess sandbox only — **not production-grade isolation** +- Python runtime only +- Single-node, no warm pool +- No filesystem write API beyond temp script diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..0b64df7 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,26 @@ +services: + agentbox: + build: + context: . + dockerfile: docker/Dockerfile + target: runtime + ports: + - "8080:8080" + environment: + AGENTBOX_LOG_LEVEL: INFO + AGENTBOX_DEFAULT_TIMEOUT_SECONDS: 30 + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health')"] + interval: 10s + timeout: 5s + retries: 3 + + test: + build: + context: . + dockerfile: docker/Dockerfile + target: dev + volumes: + - .:/app + working_dir: /app + command: ["pytest", "tests/", "-v"] diff --git a/docker/Dockerfile b/docker/Dockerfile new file mode 100644 index 0000000..9815fc4 --- /dev/null +++ b/docker/Dockerfile @@ -0,0 +1,18 @@ +FROM python:3.12-slim AS base +WORKDIR /app +ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 + +FROM base AS dev +COPY pyproject.toml README.md ./ +COPY src ./src +COPY tests ./tests +RUN pip install --no-cache-dir -e ".[dev]" +CMD ["pytest", "tests/", "-v"] + +FROM base AS runtime +COPY pyproject.toml README.md ./ +COPY src ./src +RUN pip install --no-cache-dir . +EXPOSE 8080 +HEALTHCHECK CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health')" +CMD ["agentbox", "serve", "--host", "0.0.0.0", "--port", "8080"] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..475a841 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,39 @@ +[build-system] +requires = ["hatchling"] +build-backend = "hatchling.build" + +[project] +name = "agentbox" +version = "0.1.0" +description = "Self-hosted code execution sandbox for AI agents" +readme = "README.md" +license = "MIT" +requires-python = ">=3.11" +dependencies = [ + "fastapi>=0.111", + "pydantic>=2.6", + "pydantic-settings>=2.2", + "structlog>=24.1", + "uvicorn[standard]>=0.29", +] + +[project.optional-dependencies] +dev = ["pytest>=8.0", "httpx>=0.27", "ruff>=0.4", "mypy>=1.9"] + +[project.scripts] +agentbox = "agentbox.cli:main" + +[tool.hatch.build.targets.wheel] +packages = ["src/agentbox"] + +[tool.pytest.ini_options] +testpaths = ["tests"] + +[tool.ruff] +target-version = "py311" +line-length = 100 + +[tool.mypy] +python_version = "3.11" +strict = true +packages = ["agentbox"] diff --git a/src/agentbox/__init__.py b/src/agentbox/__init__.py new file mode 100644 index 0000000..4b7e03b --- /dev/null +++ b/src/agentbox/__init__.py @@ -0,0 +1,3 @@ +"""Self-hosted code execution sandbox for AI agents.""" + +__version__ = "0.1.0" diff --git a/src/agentbox/api/__init__.py b/src/agentbox/api/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/agentbox/api/app.py b/src/agentbox/api/app.py new file mode 100644 index 0000000..d82a179 --- /dev/null +++ b/src/agentbox/api/app.py @@ -0,0 +1,51 @@ +"""FastAPI HTTP API.""" + +import subprocess + +from fastapi import FastAPI, HTTPException +from pydantic import BaseModel, Field + +from agentbox import __version__ +from agentbox.config import Settings +from agentbox.sandbox.runner import SubprocessSandbox + +settings = Settings() +sandbox = SubprocessSandbox( + timeout_seconds=settings.default_timeout_seconds, + max_output_bytes=settings.max_output_bytes, +) + +app = FastAPI(title="agentbox", version=__version__) + + +class RunRequest(BaseModel): + code: str = Field(..., min_length=1, max_length=100_000) + language: str = "python" + + +class RunResponse(BaseModel): + stdout: str + stderr: str + exit_code: int + duration_ms: int + + +@app.get("/health") +def health() -> dict[str, str]: + return {"status": "ok", "version": __version__, "backend": settings.sandbox_backend} + + +@app.post("/v1/run", response_model=RunResponse) +def run_code(req: RunRequest) -> RunResponse: + if req.language != "python": + raise HTTPException(status_code=400, detail=f"Unsupported language: {req.language}") + try: + result = sandbox.run_python(req.code) + except subprocess.TimeoutExpired as exc: + raise HTTPException(status_code=408, detail="Execution timed out") from exc + return RunResponse( + stdout=result.stdout, + stderr=result.stderr, + exit_code=result.exit_code, + duration_ms=result.duration_ms, + ) diff --git a/src/agentbox/cli.py b/src/agentbox/cli.py new file mode 100644 index 0000000..86a7ecc --- /dev/null +++ b/src/agentbox/cli.py @@ -0,0 +1,33 @@ +"""CLI entry point.""" + +import click +import uvicorn + +from agentbox.config import Settings + + +@click.group() +def main() -> None: + """Self-hosted code execution sandbox for AI agents.""" + + +@main.command("serve") +@click.option("--host", default=None) +@click.option("--port", default=None, type=int) +def serve(host: str | None, port: int | None) -> None: + settings = Settings() + uvicorn.run( + "agentbox.api.app:app", + host=host or settings.host, + port=port or settings.port, + reload=False, + ) + + +@main.command("health") +def health_cmd() -> None: + click.echo("agentbox OK") + + +if __name__ == "__main__": + main() diff --git a/src/agentbox/config.py b/src/agentbox/config.py new file mode 100644 index 0000000..62476ee --- /dev/null +++ b/src/agentbox/config.py @@ -0,0 +1,14 @@ +"""Configuration.""" + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class Settings(BaseSettings): + model_config = SettingsConfigDict(env_prefix="AGENTBOX_", env_file=".env", extra="ignore") + + host: str = "0.0.0.0" + port: int = 8080 + log_level: str = "INFO" + default_timeout_seconds: int = 30 + max_output_bytes: int = 1_048_576 + sandbox_backend: str = "subprocess" # subprocess | docker (future) diff --git a/src/agentbox/sandbox/__init__.py b/src/agentbox/sandbox/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/agentbox/sandbox/runner.py b/src/agentbox/sandbox/runner.py new file mode 100644 index 0000000..9d7ef02 --- /dev/null +++ b/src/agentbox/sandbox/runner.py @@ -0,0 +1,46 @@ +"""Sandbox execution backends.""" + +from __future__ import annotations + +import subprocess +import tempfile +from dataclasses import dataclass +from pathlib import Path + + +@dataclass +class RunResult: + stdout: str + stderr: str + exit_code: int + duration_ms: int + + +class SubprocessSandbox: + """MVP sandbox: isolated temp directory + subprocess timeout. + + ponytail: not production isolation — upgrade path is gVisor/docker backend. + """ + + def __init__(self, timeout_seconds: int = 30, max_output_bytes: int = 1_048_576) -> None: + self.timeout_seconds = timeout_seconds + self.max_output_bytes = max_output_bytes + + def run_python(self, code: str) -> RunResult: + import time + + start = time.monotonic() + with tempfile.TemporaryDirectory(prefix="agentbox-") as tmp: + script = Path(tmp) / "main.py" + script.write_text(code, encoding="utf-8") + proc = subprocess.run( + ["python3", str(script)], + capture_output=True, + text=True, + timeout=self.timeout_seconds, + cwd=tmp, + ) + duration = int((time.monotonic() - start) * 1000) + stdout = proc.stdout[: self.max_output_bytes] + stderr = proc.stderr[: self.max_output_bytes] + return RunResult(stdout=stdout, stderr=stderr, exit_code=proc.returncode, duration_ms=duration) diff --git a/src/agentbox/sdk/__init__.py b/src/agentbox/sdk/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/agentbox/sdk/client.py b/src/agentbox/sdk/client.py new file mode 100644 index 0000000..607a0f9 --- /dev/null +++ b/src/agentbox/sdk/client.py @@ -0,0 +1,22 @@ +"""Python SDK client.""" + +import httpx + + +class AgentboxClient: + def __init__(self, base_url: str = "http://localhost:8080") -> None: + self.base_url = base_url.rstrip("/") + self._client = httpx.Client(base_url=self.base_url, timeout=60.0) + + def health(self) -> dict[str, str]: + resp = self._client.get("/health") + resp.raise_for_status() + return resp.json() + + def run(self, code: str, language: str = "python") -> dict[str, object]: + resp = self._client.post("/v1/run", json={"code": code, "language": language}) + resp.raise_for_status() + return resp.json() + + def close(self) -> None: + self._client.close() diff --git a/tests/test_api.py b/tests/test_api.py new file mode 100644 index 0000000..4351465 --- /dev/null +++ b/tests/test_api.py @@ -0,0 +1,21 @@ +"""Tests for agentbox API.""" + +from fastapi.testclient import TestClient + +from agentbox.api.app import app + +client = TestClient(app) + + +def test_health() -> None: + resp = client.get("/health") + assert resp.status_code == 200 + assert resp.json()["status"] == "ok" + + +def test_run_python() -> None: + resp = client.post("/v1/run", json={"code": "print('hello agentbox')"}) + assert resp.status_code == 200 + body = resp.json() + assert "hello agentbox" in body["stdout"] + assert body["exit_code"] == 0 diff --git a/tests/test_sdk.py b/tests/test_sdk.py new file mode 100644 index 0000000..c590ce4 --- /dev/null +++ b/tests/test_sdk.py @@ -0,0 +1,9 @@ +"""Tests for SDK client.""" + +from agentbox.sdk.client import AgentboxClient + + +def test_client_instantiation() -> None: + client = AgentboxClient(base_url="http://localhost:8080") + assert client.base_url == "http://localhost:8080" + client.close()