mirror of
https://github.com/yashshah9/agentbox.git
synced 2026-11-18 18:03:44 +00:00
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.
This commit is contained in:
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,4 @@
|
||||
__pycache__/
|
||||
.venv/
|
||||
.pytest_cache/
|
||||
dist/
|
||||
@@ -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
|
||||
@@ -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
|
||||
```
|
||||
@@ -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.
|
||||
@@ -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
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,3 @@
|
||||
"""Self-hosted code execution sandbox for AI agents."""
|
||||
|
||||
__version__ = "0.1.0"
|
||||
@@ -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,
|
||||
)
|
||||
@@ -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()
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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()
|
||||
@@ -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
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user