The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = [
# "fastapi>=0.115",
# "uvicorn>=0.34",
# "sse-starlette>=2.0",
# "PyJWT>=2.8",
# "python-multipart>=0.0.9",
# "python-dotenv>=1.0",
# ]
# ///
"""
BoxLite REST API Reference Server
Reference implementation of the BoxLite Box API.
Implements the OpenAPI spec at ../box.openapi.yaml.
Purpose: showcase the API and validate client implementations.
NOT production-ready — no persistence, no real auth, single-tenant.
Usage:
make dev:python # build boxlite SDK
uv run --active server.py
"""
from __future__ import annotations
import asyncio
import base64
import io
import json
import logging
import os
import sys
import tarfile
import tempfile
import time
import uuid
from contextlib import asynccontextmanager, suppress
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Literal, Optional
import hmac
import jwt
import uvicorn
from fastapi import (
Depends,
FastAPI,
Header,
HTTPException,
Path,
Query,
Request,
Response,
)
from fastapi.responses import JSONResponse, StreamingResponse
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
from sse_starlette.sse import EventSourceResponse, ServerSentEvent
import boxlite
from config import (
DEFAULT_ENV_FILE_PATH,
ServerConfig,
RuntimeConfig,
build_main_parser,
load_env_file,
load_runtime_config_from_env,
load_server_config_from_env,
logging_level_from_name,
normalize_log_level,
parse_bootstrap_env_file,
)
from errors import classify_error, error_envelope
# ============================================================================
# Configuration
# ============================================================================
JWT_ALGORITHM = "HS256"
logger = logging.getLogger("boxlite-server")
# ============================================================================
# Pydantic Models
# ============================================================================
class ErrorModel(BaseModel):
message: str
type: str
# Stable snake_case machine identifier, per box.openapi.yaml — not the HTTP
# status, which the status line already carries.
code: str
stack: Optional[list[str]] = None
class ErrorResponse(BaseModel):
error: ErrorModel
class SecretSpec(BaseModel):
name: str
value: str
hosts: list[str] = Field(default_factory=list)
placeholder: Optional[str] = None
headers: dict[str, str] = Field(min_length=1)
class NetworkSpec(BaseModel):
model_config = ConfigDict(extra="forbid")
mode: Literal["enabled", "disabled"]
allow_net: list[str] = Field(default_factory=list)
@model_validator(mode="after")
def validate_allow_net(self) -> "NetworkSpec":
if self.mode == "disabled" and self.allow_net:
raise ValueError(
'network.allow_net is incompatible with network.mode="disabled"'
)
return self
class ContainerCapabilities(BaseModel):
model_config = ConfigDict(extra="forbid")
add: list[str] = Field(default_factory=list)
drop: list[str] = Field(default_factory=list)
@field_validator("add", "drop")
@classmethod
def validate_capabilities(cls, capabilities: list[str]) -> list[str]:
for capability in capabilities:
if not capability.isascii():
raise ValueError("capability names must contain only ASCII characters")
normalized = capability.upper()
if normalized == "ALL":
continue
name = normalized.removeprefix("CAP_")
if (
not name
or not name[0].isalpha()
or not all(
char.isalpha() or char.isdigit() or char == "_" for char in name
)
):
raise ValueError(f"malformed Linux capability: {capability}")
return capabilities
class CreateBoxAdvancedOptions(BaseModel):
model_config = ConfigDict(extra="forbid")
capabilities: Optional[ContainerCapabilities] = None
privileged: bool = False
class CreateBoxRequest(BaseModel):
model_config = ConfigDict(extra="forbid")
name: Optional[str] = None
image: Optional[str] = "alpine:latest"
rootfs_path: Optional[str] = None
cpus: Optional[float] = None
memory_mib: Optional[int] = None
disk_size_gb: Optional[int] = None
working_dir: Optional[str] = None
env: Optional[dict[str, str]] = None
entrypoint: Optional[list[str]] = None
cmd: Optional[list[str]] = None
user: Optional[str] = None
volumes: Optional[list[dict]] = None
network: Optional[NetworkSpec] = None
secrets: Optional[list[SecretSpec]] = None
auto_stop: Optional[int] = Field(default=None, ge=0)
auto_delete: Optional[int] = Field(default=None, ge=0)
auto_resume: Optional[bool] = None
detach: Optional[bool] = False
tty: Optional[bool] = None
advanced: Optional[CreateBoxAdvancedOptions] = None
# `security` is deliberately absent. Sandbox isolation is the operator's
# policy, set server-side; a client that could pick a preset would be
# choosing its own isolation level, and `development` turns jailer,
# seccomp and close_fds off. `extra="forbid"` above makes any attempt to
# smuggle one in a validation error rather than a quiet fall-through. See
# `test_create_request_rejects_client_supplied_security_policy`, and the
# same refusal in src/boxlite/src/rest/types.rs and
# src/cli/src/commands/serve/types.rs.
class StopBoxRequest(BaseModel):
timeout_seconds: Optional[float] = 30
class ExecCommandRequest(BaseModel):
command: str
args: Optional[list[str]] = None
env: Optional[dict[str, str]] = None
# Validate raw sync limits below so invalid types return 400 without coercion.
timeout_seconds: Optional[Any] = None
max_output_bytes: Optional[Any] = None
working_dir: Optional[str] = None
tty: bool = False
sync: bool = False
stdin: Optional[str] = None
user: Optional[str] = None
class SignalRequest(BaseModel):
signal: int
class ResizeRequest(BaseModel):
cols: int
rows: int
class CreateSnapshotRequest(BaseModel):
name: str
class CloneBoxRequest(BaseModel):
name: Optional[str] = None
class ExportBoxRequest(BaseModel):
pass # Forward-compatible, no configurable fields yet
# ============================================================================
# State
# ============================================================================
@dataclass
class ActiveExecution:
the_execution: Any
box_id: str
stdout: Any
stderr: Any
stdin: Any
status: str = "running"
exit_code: Optional[int] = None
error_message: Optional[str] = None
started_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
class AppState:
def __init__(self):
self.runtime: Optional[boxlite.Boxlite] = None
self.server_config: Optional[ServerConfig] = None
self.runtime_config: Optional[RuntimeConfig] = None
self.active_executions: dict[str, ActiveExecution] = {}
self.active_boxes_by_id: dict[str, Any] = {}
self.active_boxes_lock = asyncio.Lock()
state = AppState()
def get_server_config() -> ServerConfig:
if state.server_config is None:
raise RuntimeError("server configuration not initialized")
return state.server_config
# ============================================================================
# Error Mapping
# ============================================================================
def error_response(
status: int, message: str, error_type: str, code: str
) -> JSONResponse:
return JSONResponse(
status_code=status,
content=error_envelope(message, error_type, code),
)
# ============================================================================
# Auth
# ============================================================================
bearer_scheme = HTTPBearer(auto_error=False)
# --- Auth: format-agnostic Bearer acceptance ---
#
# The reference server accepts ANY non-empty Bearer token. Real validation
# is the production gateway's job (see plan §9 — pluggable validators).
LOCAL_PRINCIPAL = {
"sub": "local-anonymous",
"principal_type": "service_account",
"email": "[email protected]",
"display_name": "Local development",
"prefix": "default",
"scopes": [
"box:read", "box:write", "box:exec", "box:delete",
"image:read", "image:write",
"snapshot:read", "snapshot:write", "snapshot:delete",
"me:read",
],
"expires_at": None,
}
async def require_auth(
credentials: Optional[HTTPAuthorizationCredentials] = Depends(bearer_scheme),
) -> dict:
# Always-on: a missing/empty bearer is a 401 regardless of config
# (enforces the declared BearerAuth scheme's presence — Prism-style).
if credentials is None or not credentials.credentials:
raise HTTPException(
status_code=401,
detail=error_envelope(
"missing authorization header", "AuthError", "unauthenticated"
),
)
cfg = state.server_config
expected = cfg.api_key if cfg is not None else None
if expected is not None and not hmac.compare_digest(
credentials.credentials, expected
):
# Configured expected key + mismatch ⇒ reject (constant-time).
raise HTTPException(
status_code=401,
detail=error_envelope("invalid api key", "AuthError", "unauthenticated"),
)
# No expected key configured ⇒ accept any non-empty bearer (the
# zero-config reference default). Configured ⇒ matched above.
return {"sub": "local-anonymous"}
# ============================================================================
# Helpers
# ============================================================================
def box_info_to_dict(info) -> dict:
box = {
"box_id": info.id,
"name": info.name,
"status": info.state.status,
"created_at": info.created_at,
"updated_at": info.created_at,
"pid": info.state.pid,
"image": info.image,
"cpus": info.cpus,
"memory_mib": info.memory_mib,
"labels": {},
}
# Absent, not null, when nothing was recorded: 0 is a real exit code, so
# the field's presence is what says the main command has exited.
if info.state.exit_code is not None:
box["exit_code"] = info.state.exit_code
if info.privileged is not None:
box["privileged"] = info.privileged
return box
def build_box_options(req: CreateBoxRequest) -> boxlite.BoxOptions:
kwargs = {}
if req.image and not req.rootfs_path:
kwargs["image"] = req.image
if req.rootfs_path:
kwargs["rootfs_path"] = req.rootfs_path
if req.cpus is not None:
kwargs["cpus"] = req.cpus
if req.memory_mib is not None:
kwargs["memory_mib"] = req.memory_mib
if req.disk_size_gb is not None:
kwargs["disk_size_gb"] = req.disk_size_gb
if req.working_dir is not None:
kwargs["working_dir"] = req.working_dir
if req.env:
kwargs["env"] = list(req.env.items())
if req.network is not None:
kwargs["network"] = boxlite.NetworkSpec(
mode=req.network.mode,
allow_net=req.network.allow_net,
)
if req.entrypoint is not None:
kwargs["entrypoint"] = req.entrypoint
if req.cmd is not None:
kwargs["cmd"] = req.cmd
if req.user is not None:
kwargs["user"] = req.user
if req.advanced is not None:
kwargs["advanced"] = boxlite.AdvancedBoxOptions(
privileged=req.advanced.privileged,
capabilities=boxlite.ContainerCapabilities(
add=req.advanced.capabilities.add,
drop=req.advanced.capabilities.drop,
)
if req.advanced.capabilities is not None
else None,
)
if req.secrets:
kwargs["secrets"] = [
boxlite.Secret(
name=secret.name,
value=secret.value,
hosts=secret.hosts,
placeholder=secret.placeholder,
headers=secret.headers,
)
for secret in req.secrets
]
if req.auto_stop is not None:
kwargs["auto_stop"] = req.auto_stop
if req.auto_delete is not None:
kwargs["auto_delete"] = req.auto_delete
if req.auto_resume is not None:
kwargs["auto_resume"] = req.auto_resume
if req.detach is not None:
kwargs["detach"] = req.detach
if req.tty is not None:
kwargs["tty"] = req.tty
if req.volumes:
# The wire carries managed volumes only; a host path would name this
# server's filesystem rather than the caller's. Dict form, because a
# tuple is always a host bind in the Python SDK.
kwargs["volumes"] = [
{
"managed_volume": v["managed_volume"],
"guest_path": v["guest_path"],
"read_only": v.get("read_only", False),
}
for v in req.volumes
]
return boxlite.BoxOptions(**kwargs)
def snapshot_info_to_dict(info) -> dict:
return {
"id": info.id,
"box_id": info.box_id,
"name": info.name,
"created_at": info.created_at,
"guest_disk_bytes": info.guest_disk_bytes,
"container_disk_bytes": info.container_disk_bytes,
"size_bytes": info.size_bytes,
}
async def cache_box_handle(box_handle: Any) -> str:
box_id = (await box_handle.info()).id
async with state.active_boxes_lock:
state.active_boxes_by_id[box_id] = box_handle
return box_id
async def get_cached_box_handle(box_id: str) -> Optional[Any]:
async with state.active_boxes_lock:
return state.active_boxes_by_id.get(box_id)
async def evict_cached_box_by_id(box_id: str) -> None:
async with state.active_boxes_lock:
state.active_boxes_by_id.pop(box_id, None)
async def find_box_info(id_or_name: str):
"""Find metadata without attaching a handle or observing live networking."""
cached = await get_cached_box_handle(id_or_name)
if cached is not None:
return await cached.info()
infos = await state.runtime.list_info()
return next(
(
info
for info in infos
if str(info.id) == id_or_name or info.name == id_or_name
),
None,
)
async def clear_cached_box_handles() -> None:
async with state.active_boxes_lock:
state.active_boxes_by_id.clear()
async def get_box_or_404(box_id: str):
cached = await get_cached_box_handle(box_id)
if cached is not None:
return cached
box_handle = await state.runtime.get(box_id)
if box_handle is None:
raise HTTPException(
status_code=404,
detail=error_envelope(
f"box not found: {box_id}", "NotFoundError", "not_found"
),
)
await cache_box_handle(box_handle)
return box_handle
def execution_not_found(exec_id: str) -> HTTPException:
return HTTPException(
status_code=404,
detail=error_envelope(
f"execution not found: {exec_id}", "NotFoundError", "not_found"
),
)
async def watch_execution(active: ActiveExecution) -> None:
"""Record a session's terminal status without blocking the request path."""
try:
result = await active.the_execution.wait()
active.exit_code = result.exit_code
active.error_message = result.error_message
active.status = "completed" if result.exit_code is not None else "killed"
except Exception as err:
active.status = "killed"
active.error_message = str(err)
async def get_active_execution_or_recover(
box_id: str, exec_id: str
) -> ActiveExecution:
"""Resolve an execution from the local registry or the guest.
The local map only holds handles this server started or recovered. The
guest registry is authoritative, so a miss there falls through to it: the
main command and sessions started before a server restart are live but have
no local handle.
"""
active = state.active_executions.get(exec_id)
if active is not None and active.box_id == box_id:
return active
box_handle = await get_box_or_404(box_id)
canonical = box_handle.id
if active is not None and active.box_id == canonical:
return active
if active is not None:
# The id belongs to another box; do not leak it through this route.
raise execution_not_found(exec_id)
sessions = await box_handle.executions().list()
info = next((s for s in sessions if s.execution_id == exec_id), None)
if info is None:
raise execution_not_found(exec_id)
# Control-only: status/signal/resize do not claim the output reader.
execution = await box_handle.executions().get(exec_id)
active = ActiveExecution(
the_execution=execution,
box_id=canonical,
stdout=None,
stderr=None,
stdin=None,
started_at=datetime.fromtimestamp(
info.started_at / 1000, tz=timezone.utc
),
)
existing = state.active_executions.setdefault(exec_id, active)
if existing is not active:
return existing
asyncio.create_task(watch_execution(active))
return active
# ============================================================================
# App
# ============================================================================
@asynccontextmanager
async def lifespan(app: FastAPI):
runtime_config = state.runtime_config
if runtime_config is None:
raise RuntimeError("runtime configuration not initialized")
options = boxlite.Options(
home_dir=runtime_config.home_dir,
image_registries=runtime_config.image_registries,
)
state.runtime = boxlite.Boxlite(options)
logger.info(
"BoxLite runtime initialized (home_dir=%s, image_registries=%s)",
runtime_config.home_dir,
",".join(runtime_config.image_registries),
)
yield
await clear_cached_box_handles()
try:
await state.runtime.shutdown(timeout=10)
except Exception as e:
logger.warning("Shutdown error: %s", e)
finally:
await clear_cached_box_handles()
app = FastAPI(
title="BoxLite Box API",
version="0.1.0",
lifespan=lifespan,
)
@app.exception_handler(RuntimeError)
async def runtime_error_handler(request: Request, err: RuntimeError):
message = str(err)
status, error_type, code = classify_error(message)
return error_response(status, message, error_type, code)
# ============================================================================
# Config & Auth
# ============================================================================
@app.get("/v1/config")
async def get_config():
return {
"defaults": {
"cpus": 2,
"memory_mib": 512,
"disk_size_gb": 10,
"auto_delete": 0,
},
"overrides": {},
"capabilities": {
"linux_capabilities_enabled": True,
"privileged_enabled": True,
"max_cpus": 16,
"max_memory_mib": 16384,
"max_disk_size_gb": 100,
"max_boxes_per_prefix": 50,
"max_concurrent_executions": 10,
"file_transfer_max_bytes": 1073741824,
"exec_timeout_max_seconds": 3600,
"tty_enabled": True,
"streaming_enabled": True,
"sync_exec_enabled": True,
"snapshots_enabled": True,
"clone_enabled": True,
"export_enabled": True,
"import_enabled": True,
"idempotency_key_lifetime": "PT24H",
},
}
@app.get("/v1/me")
async def get_me(_auth: dict = Depends(require_auth)):
"""Identity + scopes for the calling credential."""
return LOCAL_PRINCIPAL
# ============================================================================
# Boxes
# ============================================================================
@app.post("/v1/{prefix}/boxes", status_code=201)
async def create_box(
prefix: str,
req: CreateBoxRequest,
_auth: dict = Depends(require_auth),
):
options = build_box_options(req)
box_handle = await state.runtime.create(options, req.name)
await cache_box_handle(box_handle)
info = await box_handle.info()
data = box_info_to_dict(info)
return JSONResponse(
status_code=201,
content=data,
headers={"Location": f"/v1/{prefix}/boxes/{info.id}"},
)
@app.get("/v1/{prefix}/boxes")
async def list_boxes(
prefix: str,
status: Optional[str] = Query(None),
pageSize: int = Query(100, ge=1, le=1000),
pageToken: Optional[str] = Query(None),
_auth: dict = Depends(require_auth),
):
infos = await state.runtime.list_info()
if status:
infos = [i for i in infos if i.state.status == status]
boxes = [box_info_to_dict(i) for i in infos]
return {"boxes": boxes, "next_page_token": None}
@app.get("/v1/{prefix}/boxes/{box_id}")
async def get_box(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
info = await state.runtime.get_info(box_id)
if info is None:
return error_response(
404, f"box not found: {box_id}", "NotFoundError", "not_found"
)
return box_info_to_dict(info)
@app.head("/v1/{prefix}/boxes/{box_id}")
async def box_exists(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
info = await find_box_info(box_id)
if info is None:
return Response(status_code=404)
return Response(status_code=204)
@app.delete("/v1/{prefix}/boxes/{box_id}", status_code=204)
async def remove_box(
prefix: str,
box_id: str,
force: bool = Query(False),
_auth: dict = Depends(require_auth),
):
info = await find_box_info(box_id)
await state.runtime.remove(box_id, force=force)
if info is not None:
await evict_cached_box_by_id(info.id)
return Response(status_code=204)
@app.post("/v1/{prefix}/boxes/{box_id}/start")
async def start_box(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
await box_handle.start()
await cache_box_handle(box_handle)
info = await box_handle.info()
return box_info_to_dict(info)
@app.post("/v1/{prefix}/boxes/{box_id}/stop")
async def stop_box(
prefix: str,
box_id: str,
req: Optional[StopBoxRequest] = None,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
await box_handle.stop()
info = await box_handle.info()
await evict_cached_box_by_id(info.id)
return box_info_to_dict(info)
@app.put("/v1/{prefix}/boxes/{box_id}/network/inbound")
async def set_inbound_network(
prefix: str, box_id: str, req: NetworkSpec, _auth: dict = Depends(require_auth)
):
box_handle = await get_box_or_404(box_id)
await box_handle.network.update_inbound(
boxlite.InboundNetworkSpec(mode=req.mode, allow_net=req.allow_net)
)
return req.model_dump()
@app.put("/v1/{prefix}/boxes/{box_id}/network/outbound")
async def set_outbound_network(
prefix: str, box_id: str, req: NetworkSpec, _auth: dict = Depends(require_auth)
):
box_handle = await get_box_or_404(box_id)
await box_handle.network.update_outbound(
boxlite.OutboundNetworkSpec(mode=req.mode, allow_net=req.allow_net)
)
return req.model_dump()
@app.post("/v1/{prefix}/boxes/{box_id}/snapshots", status_code=201)
async def create_snapshot(
prefix: str,
box_id: str,
req: CreateSnapshotRequest,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
opts = boxlite.SnapshotOptions()
info = await box_handle.snapshot.create(req.name, opts)
return JSONResponse(status_code=201, content=snapshot_info_to_dict(info))
@app.get("/v1/{prefix}/boxes/{box_id}/snapshots")
async def list_snapshots(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
snapshots = await box_handle.snapshot.list()
return {"snapshots": [snapshot_info_to_dict(s) for s in snapshots]}
@app.get("/v1/{prefix}/boxes/{box_id}/snapshots/{snapshot_name}")
async def get_snapshot(
prefix: str,
box_id: str,
snapshot_name: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
info = await box_handle.snapshot.get(snapshot_name)
if info is None:
return error_response(
404, f"snapshot '{snapshot_name}' not found", "NotFoundError", "not_found"
)
return snapshot_info_to_dict(info)
@app.delete("/v1/{prefix}/boxes/{box_id}/snapshots/{snapshot_name}", status_code=204)
async def remove_snapshot(
prefix: str,
box_id: str,
snapshot_name: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
await box_handle.snapshot.remove(snapshot_name)
return Response(status_code=204)
@app.post(
"/v1/{prefix}/boxes/{box_id}/snapshots/{snapshot_name}/restore",
status_code=204,
)
async def restore_snapshot(
prefix: str,
box_id: str,
snapshot_name: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
await box_handle.snapshot.restore(snapshot_name)
return Response(status_code=204)
@app.post("/v1/{prefix}/boxes/{box_id}/clone", status_code=201)
async def clone_box(
prefix: str,
box_id: str,
req: CloneBoxRequest,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
opts = boxlite.CloneOptions()
cloned = await box_handle.clone(req.name, opts)
await cache_box_handle(cloned)
info = await cloned.info()
return JSONResponse(
status_code=201,
content=box_info_to_dict(info),
headers={"Location": f"/v1/{prefix}/boxes/{info.id}"},
)
@app.post("/v1/{prefix}/boxes/{box_id}/export")
async def export_box(
prefix: str,
box_id: str,
req: Optional[ExportBoxRequest] = None,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
opts = boxlite.ExportOptions()
with tempfile.TemporaryDirectory() as tmpdir:
archive_path = await box_handle.export(tmpdir, opts)
with open(archive_path, "rb") as f:
payload = f.read()
return Response(content=payload, media_type="application/octet-stream")
@app.post("/v1/{prefix}/boxes/import", status_code=201)
async def import_box(
prefix: str,
request: Request,
name: Optional[str] = Query(None),
_auth: dict = Depends(require_auth),
):
payload = await request.body()
if not payload:
return error_response(
400,
"archive payload is required",
"InvalidArgumentError",
"invalid_argument",
)
with tempfile.TemporaryDirectory() as tmpdir:
archive_path = os.path.join(tmpdir, "import.boxlite")
with open(archive_path, "wb") as f:
f.write(payload)
imported = await state.runtime.import_box(
archive_path, name=name, untrusted=True
)
await cache_box_handle(imported)
info = await imported.info()
return JSONResponse(
status_code=201,
content=box_info_to_dict(info),
headers={"Location": f"/v1/{prefix}/boxes/{info.id}"},
)
# ============================================================================
# Execution
# ============================================================================
async def exec_with_transport_retry(box_handle, command: str, **kwargs):
# Box startup and guest bridge establishment can be briefly racy.
for _ in range(4):
try:
return await box_handle.exec(command, **kwargs)
except Exception as err:
if "transport error" not in str(err).lower():
raise
await asyncio.sleep(0.2)
return await box_handle.exec(command, **kwargs)
@app.post("/v1/{prefix}/boxes/{box_id}/exec", status_code=201)
async def start_execution(
prefix: str,
box_id: str,
req: ExecCommandRequest,
_auth: dict = Depends(require_auth),
):
if req.sync:
return await _run_sync_execution(box_id, req)
box_handle = await get_box_or_404(box_id)
kwargs = {}
if req.args:
kwargs["args"] = req.args
if req.env:
kwargs["env"] = list(req.env.items())
if req.tty:
kwargs["tty"] = True
execution = await exec_with_transport_retry(box_handle, req.command, **kwargs)
exec_id = execution.id()
# Take streams immediately (can only be called once)
active = ActiveExecution(
the_execution=execution,
# Canonical id, so a later request by name and by id agree on ownership.
box_id=box_handle.id,
stdout=execution.stdout(),
stderr=execution.stderr(),
stdin=execution.stdin(),
)
state.active_executions[exec_id] = active
asyncio.create_task(watch_execution(active))
return JSONResponse(
status_code=201,
content={"execution_id": exec_id},
headers={
"Location": f"/v1/{prefix}/boxes/{box_id}/executions/{exec_id}"
},
)
async def collect_exec_output(stream, limit: int) -> tuple[str, bool]:
buffered = bytearray()
truncated = False
async for chunk in stream:
remaining = limit - len(buffered)
if remaining == 0:
# Keep draining both streams even after the capture limit is reached.
truncated = truncated or bool(chunk)
continue
if isinstance(chunk, str):
chunk = chunk.encode("utf-8")
buffered.extend(chunk[:remaining])
truncated = truncated or len(chunk) > remaining
return buffered.decode("utf-8", errors="replace"), truncated
def _validate_sync_exec_request(
req: ExecCommandRequest,
) -> tuple[float, int] | JSONResponse:
if req.stdin is not None:
return error_response(
400,
"stdin is not supported for synchronous exec",
"InvalidArgumentError",
"invalid_argument",
)
if not req.command:
return error_response(
400, "command must not be empty", "InvalidArgumentError", "invalid_argument"
)
if req.tty:
return error_response(
400,
"tty is not supported when sync is true",
"InvalidArgumentError",
"invalid_argument",
)
timeout_seconds = 30.0 if req.timeout_seconds is None else req.timeout_seconds
if (
isinstance(timeout_seconds, bool)
or not isinstance(timeout_seconds, (int, float))
or not 0.1 <= timeout_seconds <= 300.0
):
return error_response(
400,
"timeout_seconds must be between 0.1 and 300",
"InvalidArgumentError",
"invalid_argument",
)
max_output_bytes = 1_048_576 if req.max_output_bytes is None else req.max_output_bytes
if (
isinstance(max_output_bytes, bool)
or not isinstance(max_output_bytes, int)
or max_output_bytes < 1024
or max_output_bytes > 10_485_760
):
return error_response(
400,
"max_output_bytes must be an integer between 1024 and 10485760",
"InvalidArgumentError",
"invalid_argument",
)
return float(timeout_seconds), max_output_bytes
async def _run_sync_execution(box_id: str, req: ExecCommandRequest) -> JSONResponse:
validated = _validate_sync_exec_request(req)
if isinstance(validated, JSONResponse):
return validated
timeout_seconds, max_output_bytes = validated
box_handle = await get_box_or_404(box_id)
execution = None
async def run():
nonlocal execution
# Synchronous exec is at-most-once: never retry transport errors.
execution = await box_handle.exec(
req.command,
args=req.args,
env=list(req.env.items()) if req.env is not None else None,
tty=False,
cwd=req.working_dir,
user=req.user,
timeout_secs=timeout_seconds + 5.0,
)
stdout = execution.stdout()
stderr = execution.stderr()
stdin = execution.stdin()
async def wait():
await stdin.close() # Commands that read stdin should see EOF.
return await execution.wait()
tasks = (
asyncio.create_task(collect_exec_output(stdout, max_output_bytes)),
asyncio.create_task(collect_exec_output(stderr, max_output_bytes)),
asyncio.create_task(wait()),
)
try:
return await asyncio.gather(*tasks)
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
try:
(stdout, stdout_truncated), (stderr, stderr_truncated), result = (
await asyncio.wait_for(run(), timeout=timeout_seconds)
)
except asyncio.TimeoutError:
if execution is not None:
with suppress(Exception):
await asyncio.wait_for(execution.kill(), timeout=1)
return error_response(408, "execution timed out", "TimeoutError", "timeout")
payload = {
"exit_code": result.exit_code,
"stdout": stdout,
"stderr": stderr,
"stdout_truncated": stdout_truncated,
"stderr_truncated": stderr_truncated,
}
if result.error_message:
payload["error_message"] = result.error_message
return JSONResponse(status_code=200, content=payload)
@app.get("/v1/{prefix}/boxes/{box_id}/executions")
async def list_executions(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
executions = await box_handle.executions().list()
return {
"executions": [
{
"execution_id": info.execution_id,
"argv": info.argv,
"started_at": info.started_at,
"tty": info.tty,
"is_main_session": info.is_main_session,
}
for info in executions
]
}
@app.get("/v1/{prefix}/boxes/{box_id}/executions/{exec_id}")
async def get_execution(
prefix: str,
box_id: str,
exec_id: str,
_auth: dict = Depends(require_auth),
):
active = await get_active_execution_or_recover(box_id, exec_id)
elapsed = (datetime.now(timezone.utc) - active.started_at).total_seconds()
return {
"execution_id": exec_id,
"status": active.status,
"exit_code": active.exit_code,
"started_at": active.started_at.isoformat(),
"duration_ms": int(elapsed * 1000) if active.status != "running" else None,
"error_message": active.error_message,
}
@app.post(
"/v1/{prefix}/boxes/{box_id}/executions/{exec_id}/signal",
status_code=204,
)
async def signal_execution(
prefix: str,
box_id: str,
exec_id: str,
req: SignalRequest,
_auth: dict = Depends(require_auth),
):
active = await get_active_execution_or_recover(box_id, exec_id)
if active.status != "running":
return error_response(
409, "execution is not running", "InvalidStateError", "invalid_state"
)
# SDK only supports kill (SIGKILL)
await active.the_execution.kill()
active.status = "killed"
return Response(status_code=204)
@app.post(
"/v1/{prefix}/boxes/{box_id}/executions/{exec_id}/resize",
status_code=204,
)
async def resize_execution_tty(
prefix: str,
box_id: str,
exec_id: str,
req: ResizeRequest,
_auth: dict = Depends(require_auth),
):
active = await get_active_execution_or_recover(box_id, exec_id)
if active.status != "running":
return error_response(
409, "execution is not running", "InvalidStateError", "invalid_state"
)
await active.the_execution.resize_tty(req.rows, req.cols)
return Response(status_code=204)
# ============================================================================
# Files
# ============================================================================
@app.put("/v1/{prefix}/boxes/{box_id}/files", status_code=204)
async def upload_files(
prefix: str,
box_id: str,
path: str = Query(..., description="Destination path inside the container"),
overwrite: bool = Query(True),
request: Request = None,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
body = await request.body()
with tempfile.TemporaryDirectory() as tmpdir:
tar_path = os.path.join(tmpdir, "upload.tar")
with open(tar_path, "wb") as f:
f.write(body)
extract_dir = os.path.join(tmpdir, "extracted")
os.makedirs(extract_dir)
with tarfile.open(tar_path, "r:*") as tar:
tar.extractall(extract_dir)
# Land what the archive held, not the extraction directory: its
# contents ("/." is docker cp's spelling for them), or a lone file by
# itself so that it still lands *as* `path`.
entries = os.listdir(extract_dir)
if len(entries) == 1 and os.path.isfile(os.path.join(extract_dir, entries[0])):
source = os.path.join(extract_dir, entries[0])
else:
source = extract_dir + "/."
await box_handle.copy_in(
source, path,
boxlite.CopyOptions(overwrite=overwrite),
)
return Response(status_code=204)
@app.get("/v1/{prefix}/boxes/{box_id}/files")
async def download_files(
prefix: str,
box_id: str,
path: str = Query(
..., description="Source path inside the container"
),
follow_symlinks: bool = Query(False),
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
with tempfile.TemporaryDirectory() as tmpdir:
dest = os.path.join(tmpdir, "out")
os.makedirs(dest)
await box_handle.copy_out(
path,
dest,
boxlite.CopyOptions(follow_symlinks=follow_symlinks),
)
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w") as tar:
for entry in os.listdir(dest):
tar.add(os.path.join(dest, entry), arcname=entry)
tar_bytes = buf.getvalue()
return Response(content=tar_bytes, media_type="application/x-tar")
# ============================================================================
# Metrics
# ============================================================================
@app.get("/v1/{prefix}/metrics")
async def get_runtime_metrics(
prefix: str,
_auth: dict = Depends(require_auth),
):
m = await state.runtime.metrics()
return {
"boxes_created_total": m.boxes_created_total,
"boxes_failed_total": m.boxes_failed_total,
"boxes_stopped_total": 0, # Python SDK doesn't expose this counter
"num_running_boxes": m.num_running_boxes,
"total_commands_executed": m.total_commands_executed,
"total_exec_errors": m.total_exec_errors,
}
@app.get("/v1/{prefix}/boxes/{box_id}/metrics")
async def get_box_metrics(
prefix: str,
box_id: str,
_auth: dict = Depends(require_auth),
):
box_handle = await get_box_or_404(box_id)
m = await box_handle.metrics()
return {
"commands_executed_total": m.commands_executed_total,
"exec_errors_total": m.exec_errors_total,
"bytes_sent_total": m.bytes_sent_total,
"bytes_received_total": m.bytes_received_total,
"cpu_percent": m.cpu_percent,
"memory_bytes": m.memory_bytes,
"network_bytes_sent": m.network_bytes_sent,
"network_bytes_received": m.network_bytes_received,
"network_tcp_connections": m.network_tcp_connections,
"network_tcp_errors": m.network_tcp_errors,
"boot_timing": {
"total_create_ms": m.total_create_duration_ms,
"guest_boot_ms": m.guest_boot_duration_ms,
"filesystem_setup_ms": m.stage_filesystem_setup_ms,
"image_prepare_ms": m.stage_image_prepare_ms,
"guest_rootfs_ms": m.stage_guest_rootfs_ms,
"box_config_ms": m.stage_box_config_ms,
"box_spawn_ms": m.stage_box_spawn_ms,
"container_init_ms": m.stage_container_init_ms,
},
}
# ============================================================================
# Main
# ============================================================================
def main():
env_file_arg = parse_bootstrap_env_file(sys.argv[1:])
try:
loaded_env_path = load_env_file(env_file_arg)
env_server_config = load_server_config_from_env()
runtime_config = load_runtime_config_from_env()
except ValueError as err:
raise SystemExit(f"configuration error: {err}")
parser = build_main_parser(env_server_config)
args = parser.parse_args()
server_config = ServerConfig(
host=args.host,
port=args.port,
log_level=normalize_log_level(args.log_level),
jwt_secret=env_server_config.jwt_secret,
jwt_expiry_seconds=env_server_config.jwt_expiry_seconds,
api_key=env_server_config.api_key,
)
state.server_config = server_config
state.runtime_config = runtime_config
logging.basicConfig(
level=logging_level_from_name(server_config.log_level),
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
if loaded_env_path is not None:
logger.info("Loaded environment from %s", loaded_env_path)
elif env_file_arg is None:
logger.info("No .env file found at %s", DEFAULT_ENV_FILE_PATH)
uvicorn.run(
app,
host=server_config.host,
port=server_config.port,
log_level=server_config.log_level,
)
if __name__ == "__main__":
main()