The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
"""Declarative registry of services the orchestrator manages.
11 daemon boxes:
postgres, redis, rustfs, registry, rauthy, jaeger,
pgadmin, registry-ui, maildev, otel-collector, caddy.
otel-collector runs the upstream `otel/opentelemetry-collector` image and
forwards traces to the jaeger box; see `_otel_config()`. caddy is the
unified reverse proxy; see `_caddyfile()`.
"""
from __future__ import annotations
import base64
from dataclasses import dataclass, field, replace
import secrets
from typing import Callable, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from .config import InfraConfig
@dataclass
class HealthCheck:
"""Box health probe. One of `exec` or `http_url` should be set."""
exec: Optional[list[str] | Callable[["InfraConfig"], list[str]]] = None
http_url: Optional[str] = None
interval_s: float = 2.0
timeout_s: float = 5.0
retries: int = 30
start_period_s: float = 0.0
@dataclass
class ServiceSpec:
"""Declarative definition of one BoxLite-backed service."""
name: str
image: str
cpus: int = 1
memory_mib: int = 256
ports: list[tuple[int, int]] = field(default_factory=list)
env: Callable[["InfraConfig"], dict[str, str]] = field(default=lambda cfg: {})
volumes: Callable[["InfraConfig"], list[tuple[str, str]]] = field(default=lambda cfg: [])
cmd: Optional[list[str] | Callable[["InfraConfig"], list[str]]] = None
entrypoint: Optional[list[str]] = None # overrides image entrypoint (e.g. ["sh"]); None keeps image default
working_dir: Optional[str] = None
user: Optional[str] = None
depends_on: list[str] = field(default_factory=list)
healthcheck: Optional[HealthCheck] = None
auto_remove: bool = False
SPEC_PG = ServiceSpec(
name="postgres",
# Pinned to PG 17 to match prod (RDS boxlite-dev runs 17.9).
image="postgres:17-alpine",
cpus=1,
memory_mib=512,
ports=[(25432, 5432)],
env=lambda cfg: {
"POSTGRES_USER": cfg.pg_user,
"POSTGRES_PASSWORD": cfg.pg_password,
"POSTGRES_DB": cfg.pg_db,
"POSTGRES_HOST_AUTH_METHOD": "trust",
"PGDATA": "/var/lib/postgresql/data/pgdata",
},
# Server-side resilience against the microVM↔host transport silently
# wedging a connection mid-query. Without this, a wedged backend stays
# `active` forever holding a connection, and the API's per-10s lifecycle
# crons accumulate stuck backends until the pool is exhausted and the
# dashboard hangs. These reap the orphaned server backend so it doesn't
# leak. The client side is deliberately left unprotected to keep apps/
# unmodified: a wedged API pool connection may hold its slot until
# `make stack-restart COMPONENTS=api`. Root fix belongs in the transport.
# - statement_timeout: cap any single query at 30s.
# - tcp_keepalives_*: detect a dead peer (~60s) and close the backend.
# "postgres" as first arg keeps docker-entrypoint.sh's init (initdb/seed).
cmd=lambda cfg: [
"postgres",
"-c", "statement_timeout=30000",
"-c", "idle_in_transaction_session_timeout=60000",
"-c", "tcp_keepalives_idle=30",
"-c", "tcp_keepalives_interval=10",
"-c", "tcp_keepalives_count=3",
],
volumes=lambda cfg: [
(str(cfg.data_dir / "pg"), "/var/lib/postgresql/data"),
],
depends_on=[],
# Callable healthcheck — passes cfg-derived user/db (validates Phase-2 debt #2 fix).
healthcheck=HealthCheck(
exec=lambda cfg: ["pg_isready", "-U", cfg.pg_user, "-d", cfg.pg_db, "-t", "1"],
interval_s=2.0,
retries=30,
),
)
SPEC_REDIS = ServiceSpec(
name="redis",
image="redis:7-alpine",
cpus=1,
memory_mib=256,
ports=[(26379, 6379)],
volumes=lambda cfg: [(str(cfg.data_dir / "redis"), "/data")],
depends_on=[],
healthcheck=HealthCheck(
exec=["redis-cli", "PING"],
interval_s=2.0,
retries=30,
),
)
SPEC_RUSTFS = ServiceSpec(
name="rustfs",
image="ghcr.io/rustfs/rustfs:1.0.4-glibc",
cpus=1,
memory_mib=512,
ports=[(29000, 9000), (29001, 9001)],
env=lambda cfg: {
"RUSTFS_ACCESS_KEY": cfg.rustfs_user,
"RUSTFS_SECRET_KEY": cfg.rustfs_password,
"RUSTFS_CONSOLE_ENABLE": "true",
},
cmd=["/data"],
# Run as root inside this dev VM; do not chown the developer's host files.
user="0:0",
volumes=lambda cfg: [(str(cfg.data_dir / "rustfs"), "/data")],
depends_on=[],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:29000/health",
interval_s=2.0,
retries=30,
),
)
SPEC_REGISTRY = ServiceSpec(
name="registry",
image="registry:2",
cpus=1,
memory_mib=256,
ports=[(25000, 5000)],
volumes=lambda cfg: [(str(cfg.data_dir / "registry"), "/var/lib/registry")],
depends_on=[],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:25000/v2/",
interval_s=2.0,
retries=30,
),
)
# ─── 3b services ──────────────────────────────────────────────────────────
def _rauthy_env(cfg) -> dict[str, str]:
"""Per-Box settings; the static ones live in apps/rauthy/config.toml."""
public = f"localhost:{cfg.rauthy_host_port}"
return {
"PUB_URL": public,
"RP_ORIGIN": f"http://{public}",
# Random per Box: the database lives on the Box disk and is
# re-seeded whenever the Box is recreated.
"ENC_KEYS": f"local/{base64.b64encode(secrets.token_bytes(32)).decode()}",
"ENC_KEY_ACTIVE": "local",
"HQL_SECRET_RAFT": secrets.token_hex(16),
"HQL_SECRET_API": secrets.token_hex(16),
}
SPEC_RAUTHY = ServiceSpec(
name="rauthy",
image="ghcr.io/sebadob/rauthy:0.37.2@sha256:d733b7580f53c1601c286b5504853b2774e70245f5f9427d9bcda32496b753ee",
cpus=1,
memory_mib=256,
ports=[(25556, 8080)],
env=_rauthy_env,
volumes=lambda cfg: [(str(cfg.repo_root / "apps" / "rauthy"), "/rauthy")],
cmd=["serve", "--config-file", "/rauthy/config.toml"],
depends_on=[],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:25556/auth/v1/.well-known/openid-configuration",
interval_s=2.0,
retries=30,
),
)
# Jaeger's OTLP gRPC receiver, host-mapped so the otel-collector box can
# reach it via host-as-hub (host.boxlite.internal:<this>). Jaeger 1.67
# all-in-one with COLLECTOR_OTLP_ENABLED=true listens for OTLP on :4317
# (gRPC) / :4318 (HTTP) inside the box. Module-level constant because
# ServiceSpec.ports is a static list (can't reference cfg) and the otel
# config below needs the same value.
_JAEGER_OTLP_GRPC_PORT = 26687
SPEC_JAEGER = ServiceSpec(
name="jaeger",
image="jaegertracing/all-in-one:1.67.0",
cpus=1,
memory_mib=512,
ports=[
(26686, 16686), # Jaeger UI
(_JAEGER_OTLP_GRPC_PORT, 4317), # OTLP gRPC receiver (fed by the otel collector)
],
env=lambda cfg: {
"COLLECTOR_OTLP_ENABLED": "true",
},
depends_on=[],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:26686/",
interval_s=2.0,
retries=30,
),
)
# pgAdmin runs as uid 5050. In a Box its python lacks the image's
# CAP_NET_BIND_SERVICE file capability and ports below 1024 stay privileged,
# so the image default :80 fails with EACCES; listen on an unprivileged port.
PGADMIN_GUEST_PORT = 5050
SPEC_PGADMIN = ServiceSpec(
name="pgadmin",
image="dpage/pgadmin4:9.2.0",
cpus=1,
memory_mib=512,
ports=[(25051, PGADMIN_GUEST_PORT)],
env=lambda cfg: {
"PGADMIN_DEFAULT_EMAIL": cfg.pgadmin_email,
"PGADMIN_DEFAULT_PASSWORD": cfg.pgadmin_password,
# Skip the password-setup wizard so probes don't redirect forever.
"PGADMIN_CONFIG_SERVER_MODE": "False",
"PGADMIN_CONFIG_MASTER_PASSWORD_REQUIRED": "False",
"PGADMIN_LISTEN_PORT": str(PGADMIN_GUEST_PORT),
# Force IPv4 bind (image default is [::] dual-stack).
"PGADMIN_LISTEN_ADDRESS": "0.0.0.0",
},
depends_on=["postgres"],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:25051/misc/ping",
interval_s=2.0,
retries=60, # pgadmin can take 30s+ to warm up
),
)
SPEC_REGISTRY_UI = ServiceSpec(
name="registry-ui",
image="joxit/docker-registry-ui:main",
cpus=1,
memory_mib=256, # 128 OOMs during nginx-alpine entrypoint init
ports=[(25052, 80)],
env=lambda cfg: {
"REGISTRY_TITLE": "BoxLite local registry",
"NGINX_PROXY_PASS_URL": f"http://{cfg.host_hub}:{cfg.registry_host_port}",
"SINGLE_REGISTRY": "true",
},
depends_on=["registry"],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:25052/",
interval_s=2.0,
retries=90, # nginx-alpine entrypoint takes 60-90s
),
)
# The API's only outbound mail is the organization-invitation email
# (apps/api email.service.ts). Catching it here is what makes that path
# exercisable locally: without an SMTP host the API disables the transporter
# at boot and the invite is created but never sent. The deployed stacks point
# SMTP_* at a real provider instead — a catcher has no place on the internet.
SPEC_MAILDEV = ServiceSpec(
name="maildev",
image="maildev/maildev:2.2.1",
cpus=1,
memory_mib=256,
ports=[
(25053, 1080), # web UI
(25054, 1025), # SMTP — apps/api connects here (see infra-local/api.env)
],
env=lambda cfg: {
# Force IPv4 bind: MailDev's --ip defaults to `::` and --web-ip
# follows it, which leaves both listeners dual-stack only. Same fix
# pgadmin needs above.
"MAILDEV_IP": "0.0.0.0",
},
depends_on=[],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:25053/healthz",
interval_s=2.0,
retries=30,
),
)
# ─── 3c services ──────────────────────────────────────────────────────────
def _otel_config(cfg) -> str:
"""otel-collector config. Receives OTLP and fans out:
- traces → debug (stdout) + the jaeger box, so the Jaeger UI at
http://127.0.0.1:26686 actually shows traces. The jaeger
hop goes through host-as-hub (a separate box) and targets
jaeger's host-mapped OTLP gRPC port.
- metrics → debug only (jaeger doesn't ingest metrics)
- logs → debug only (jaeger doesn't ingest logs)
"""
return f"""\
receivers:
otlp:
protocols:
grpc:
endpoint: 0.0.0.0:4317
http:
endpoint: 0.0.0.0:4318
exporters:
debug:
verbosity: basic
otlp/jaeger:
endpoint: {cfg.host_hub}:{_JAEGER_OTLP_GRPC_PORT}
tls:
insecure: true
extensions:
health_check:
endpoint: 0.0.0.0:13133
service:
extensions: [health_check]
pipelines:
traces:
receivers: [otlp]
exporters: [debug, otlp/jaeger]
metrics:
receivers: [otlp]
exporters: [debug]
logs:
receivers: [otlp]
exporters: [debug]
"""
SPEC_OTEL = ServiceSpec(
name="otel",
image="otel/opentelemetry-collector:latest",
cpus=1,
memory_mib=256,
# All EXPOSE'd ports are non-priv (4317, 4318, 13133, 8888), so the SDK
# auto-bind doesn't hit the privileged-port bug — but we map explicitly
# for cleanliness + parent design §3.8 consistency.
ports=[
(24317, 4317), # OTLP gRPC
(24318, 4318), # OTLP HTTP
(23133, 13133), # health_check
],
# The otelcol image is distroless — no shell. Pass config via env var
# using `--config=env:OTEL_CONFIG` (supported since otel-collector v0.79.0).
# Image entrypoint is `/otelcol`; cmd becomes its argv.
env=lambda cfg: {"OTEL_CONFIG": _otel_config(cfg)},
cmd=["--config=env:OTEL_CONFIG"],
# jaeger must be up first — the traces pipeline exports to it.
depends_on=["jaeger"],
healthcheck=HealthCheck(
http_url="http://127.0.0.1:23133/",
interval_s=2.0,
retries=30,
),
)
def _caddyfile(cfg) -> str:
"""Inline Caddyfile body. Path-based routing on plain HTTP.
TLS (`tls internal`) is intentionally NOT used because Caddy's internal
issuer can't mint certs for raw IP addresses (`127.0.0.1`), and we don't
have DNS hijack yet (no `*.boxlite.test`). Once dns-shim lands, switch
`:80` block below to `*.boxlite.test:443 { tls internal ... }` and add
redir back.
"""
pgadmin_route = "" if cfg.external_stores else f"""\
\thandle_path /pgadmin/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.pgadmin_host_port}
\t}}
"""
pgadmin_help = "" if cfg.external_stores else " /pgadmin/ -> pgadmin\n"
return f"""\
{{
\tauto_https off
\tadmin 0.0.0.0:2019
}}
:80 {{
\t# Box port proxy: hostnames look like `<port>-d-<hex box ID>.localhost:28080`
\t# (returned by `POST /api/v1/.../network/tunnel`). Forward any host that
\t# starts with `<digits>-` to the apps/proxy service on the host (port 4000),
\t# which resolves the box → runner and proxies through.
\t@port_proxy_host header_regexp Host ^[0-9]+-[A-Za-z0-9-]+\\.
\thandle @port_proxy_host {{
\t\treverse_proxy {cfg.host_hub}:4000 {{
\t\t\theader_up Host {{http.request.host}}
\t\t}}
\t}}
{pgadmin_route}\thandle_path /jaeger/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.jaeger_host_port}
\t}}
\thandle /auth/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.rauthy_host_port}
\t}}
\thandle_path /rustfs-console/* {{
\t\treverse_proxy {cfg.host_hub}:29001
\t}}
\thandle_path /rustfs/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.rustfs_host_port}
\t}}
\thandle_path /registry-ui/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.registry_ui_host_port}
\t}}
\thandle_path /registry/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.registry_host_port}
\t}}
\thandle_path /maildev/* {{
\t\treverse_proxy {cfg.host_hub}:{cfg.maildev_ui_host_port}
\t}}
\thandle / {{
\t\trespond `boxlite-local Caddy reverse proxy
routes:
{pgadmin_help} /jaeger/ -> jaeger
/auth/ -> rauthy (OIDC)
/rustfs/ -> rustfs S3 API
/rustfs-console/ -> rustfs console UI
/registry-ui/ -> registry UI
/registry/ -> docker registry v2
/maildev/ -> maildev (caught mail)
`
\t}}
}}
"""
_CADDY_ENTRYPOINT_TEMPLATE = """\
set -e
mkdir -p /etc/caddy
cat > /etc/caddy/Caddyfile <<'__CFG__'
{caddyfile}
__CFG__
exec caddy run --config /etc/caddy/Caddyfile --adapter caddyfile
"""
SPEC_CADDY = ServiceSpec(
name="caddy",
image="caddy:2-alpine",
cpus=1,
memory_mib=256,
ports=[
(28080, 80),
(28443, 443), # reserved for future `tls internal` (see README §TLS)
(12019, 2019), # Caddy admin API — used by the healthcheck below
],
entrypoint=["sh"],
cmd=lambda cfg: ["-c", _CADDY_ENTRYPOINT_TEMPLATE.format(caddyfile=_caddyfile(cfg))],
depends_on=["rauthy", "jaeger", "pgadmin", "rustfs", "registry", "registry-ui", "maildev"],
healthcheck=HealthCheck(
# Caddy admin API on :2019/config/ returns 200 once config loaded.
http_url="http://127.0.0.1:12019/config/",
interval_s=2.0,
retries=30,
),
)
SERVICES: dict[str, ServiceSpec] = {
"postgres": SPEC_PG,
"redis": SPEC_REDIS,
"rustfs": SPEC_RUSTFS,
"registry": SPEC_REGISTRY,
"rauthy": SPEC_RAUTHY,
"jaeger": SPEC_JAEGER,
"pgadmin": SPEC_PGADMIN,
"registry-ui": SPEC_REGISTRY_UI,
"maildev": SPEC_MAILDEV,
"otel": SPEC_OTEL,
"caddy": SPEC_CADDY,
}
def local_services(cfg: InfraConfig) -> dict[str, ServiceSpec]:
if not cfg.external_stores:
return SERVICES
selected = {name: spec for name, spec in SERVICES.items()
if name not in {"postgres", "redis", "pgadmin"}}
selected["caddy"] = replace(SPEC_CADDY, depends_on=[n for n in SPEC_CADDY.depends_on if n in selected])
return selected