AgentBox
A minimal open-source agent platform — durable execution, sandboxed agents, Logfire tracing.
November 4, 2026
AgentBox Documentation¶
AgentBox is a minimal open-source agent platform for running untrusted, long-lived AI agent workloads in isolated sandboxes, with durable (resumable) execution backed by Postgres and full observability via Logfire/OpenTelemetry.
Why AgentBox?¶
Running AI agents in production is hard:
- Long-lived: agents take 30–60+ seconds, making them crash-prone.
- Expensive: a mid-run crash wastes LLM API costs and compute time.
- Untrusted: agents run code, make network calls, and handle credentials — they need strong isolation.
AgentBox solves these problems with durable execution, sandboxing, and least-privilege credentials.
Quick Links¶
- Getting Started Set up AgentBox in under 5 minutes.
- Architecture Understand the design: control plane, launcher, sandbox, and durability.
- Development Contribute to AgentBox — setup, testing, and code style.
- GitHub Source code, issues, and pull requests.
Key Concepts¶
| Concept | Description |
|---|---|
| Durable Execution | Every model call and tool call is checkpointed to Postgres. If a container is killed mid-run, the run resumes from the last checkpoint with zero repeated LLM calls. |
| Sandboxing | Containers with resource limits, read-only rootfs, default-deny egress via a proxy, and optional gVisor integration. |
| Least-Privilege Credentials | Master API keys never enter the sandbox or the database. A credential proxy stores keys in-memory; the sandbox only gets a per-run token. |
| Row-Level Security | The runner connects via a restricted Postgres role with RLS enforcing per-run data isolation. |
| Full Observability | Every span (API → scheduler → container → model/tool call) is traced in Logfire. |
| Cost Tracking | Estimated USD cost per run (LLM tokens + compute time). |
Project Structure¶
agentbox/
├── pyproject.toml # Python project config
├── Makefile # Build, test, and run commands
├── docker-compose.yml # Postgres + control-plane + launcher + proxy
├── migrations/
│ ├── 001_init.sql # Database schema
│ └── 002_runner_rls.sql # Runner role + RLS policies
├── k8s/ # Kubernetes manifests
├── src/agentbox/
│ ├── api/ # FastAPI control plane
│ ├── db/ # Database layer (asyncpg)
│ ├── launcher/ # Queue poller + sandbox backends
│ ├── runner/ # Code that runs inside the sandbox
│ ├── mcp_server/ # MCP server for Logfire telemetry
│ ├── secrets/ # Credential scoping (per-run token minting)
│ ├── cost/ # Cost tracking
│ └── settings.py # Configuration via pydantic-settings
├── docker/
│ ├── Dockerfile.runner # Runner image
│ ├── Dockerfile.controlplane # Control plane image
│ ├── Dockerfile.credential-proxy # Credential proxy image
│ ├── credential_proxy.py # Credential proxy implementation
│ ├── tinyproxy.conf # Tinyproxy configuration
│ ├── tinyproxy-allowlist.txt # Egress domain allowlist
│ └── entrypoint.sh # Control plane entrypoint
└── tests/
├── unit/ # Unit tests
└── e2e/ # Integration tests
Tech Stack¶
| Concern | Choice |
|---|---|
| Language | Python 3.12+ |
| Agent framework | pydantic-ai |
| API | FastAPI + uvicorn |
| Database | Postgres 16, asyncpg, plain SQL migrations |
| Container runtime | Docker (default), Kubernetes Jobs |
| Egress control | Tinyproxy on internal Docker network |
| Observability | Logfire (OpenTelemetry) |
| MCP | Python MCP SDK → Logfire API |
| Package manager | uv |
Getting Started¶
Set up AgentBox and run your first agent in under 5 minutes.
Prerequisites¶
- Python 3.12+
- Docker + Docker Compose
- An LLM API key (DeepSeek or Anthropic)
-
uvpackage manager
Installation¶
1. Clone the repository¶
2. Install dependencies¶
3. Configure environment¶
Edit .env and set at least one API key:
# Required: at least one LLM API key
DEEPSEEK_API_KEY=sk-...
# or
ANTHROPIC_API_KEY=sk-ant-...
# Optional: Logfire observability
LOGFIRE_TOKEN=...
# Optional: override defaults
AGENTBOX_API_TOKEN=dev-token
MODEL_NAME=deepseek-chat
Quickstart¶
Start Postgres and run migrations¶
Build the runner image¶
This builds the Docker image that runs inside the sandbox (with your agent code, not the full control plane).
Start the launcher and API¶
In two separate terminals:
# Terminal 1: Start the launcher worker
make dev-launcher
# Terminal 2: Start the API server
make dev-api
Submit a run¶
curl -X POST http://localhost:8000/runs \
-H "Authorization: Bearer dev-token" \
-H "Content-Type: application/json" \
-d '{
"agent_name": "incident-investigator",
"prompt": "Investigate the web service. Analyze logs and fetch metrics."
}'
You'll get a response with the run ID. Check its status:
Get cost breakdown¶
Kill-and-Resume Demo¶
This is the signature feature of AgentBox. Run the automated test:
The test:
- Submits a run that takes ~30–60 seconds
- Waits for ≥2 checkpoints
- Force-kills the container
- Verifies the run requeues, resumes, and completes with zero repeated LLM calls
Or use the Makefile demo target:
Kubernetes (kind)¶
For running with Kubernetes instead of Docker:
# Create a kind cluster
kind create cluster --config k8s/kind-config.yaml
# Apply manifests
kubectl apply -f k8s/namespace.yaml
kubectl apply -f k8s/resource-quota.yaml
kubectl apply -f k8s/network-policy.yaml
kubectl apply -f k8s/rbac.yaml
# Run the launcher with K8s backend
AGENTBOX_BACKEND=k8s uv run python -m agentbox.launcher.worker
Makefile Reference¶
| Command | Purpose |
|---|---|
make build-runner |
Build the runner Docker image |
make build-controlplane |
Build the control-plane Docker image |
make dev-api |
Start API server locally with hot-reload |
make dev-launcher |
Start launcher worker locally |
make postgres-up |
Start only Postgres (for local dev) |
make up |
Start all services in Docker Compose |
make down |
Stop all services and remove volumes |
make migrate |
Run database migrations |
make test |
Run all tests |
make test-unit |
Run unit tests only |
make test-e2e |
Run end-to-end tests |
make lint |
Run ruff linter |
make demo |
Build, start, and run the kill-and-resume demo |
make clean |
Remove cached and temporary files |
Architecture¶
AgentBox is designed around a control-plane / launcher / sandbox architecture with durable execution at its core.
System Overview¶
POST /runs
client ──────────────► control-plane (FastAPI)
│ INSERT run (status=queued)
│ mint per-run token (UUID) for credentials
▼
Postgres ◄──────────────────────────┐
▲ checkpoints, leases, │
poll queue │ heartbeats, results │
launcher/worker ────────────┘ │
│ claims run (FOR UPDATE SKIP LOCKED) │
│ registers {per_run_token → real_api_key} ─────► credential-proxy
│ injects AGENTBOX_CREDENTIALS_JSON (token only) │ (in-memory map)
▼ │
┌─────────────────────────────┐ egress proxy │
│ sandbox container │────► (tinyproxy, allowlist) ─┤──► LLM API
│ runner.py │ per-run token ──────────┘
│ └─ Pydantic AI agent │ writes checkpoints ──────► Postgres
│ wrapped in DurableModel │ (via agentbox_runner role + RLS)
└─────────────────────────────┘
all components emit OpenTelemetry spans ──► Logfire
Components¶
1. Control Plane (agentbox/api/)¶
A FastAPI application that:
- Accepts run submissions via
POST /runs - Mints a per-run token (UUID) — the real API key never enters the database or the sandbox
- Returns run status, checkpoints, and cost estimates
- Exposes
GET /runs/{id}/checkpoints,GET /runs/{id}/cost, andPUT /runs/{id}/cancel
The control plane is stateless — all state lives in Postgres.
2. Credential Proxy (docker/credential_proxy.py)¶
A lightweight HTTP proxy that:
- Stores an in-memory mapping:
{per_run_token → real_api_key, base_url, expires_at} - Receives LLM API requests from the sandbox (bearing the per-run token)
- Replaces the
Authorizationheader with the real API key and forwards to the LLM provider - Exposes
/admin/keysAPI for the launcher to register/unregister keys - Never persists real API keys to disk or database
- Checks
expires_aton every request, rejecting expired tokens
This is the cornerstone of AgentBox's least-privilege credential design. The master API key lives only in: 1. The environment variable on the host running the launcher 2. The credential proxy's in-memory key store
It never enters the sandbox container or the database.
3. Launcher Worker (agentbox/launcher/)¶
The "brain" of the system. It runs two concurrent loops:
Poll Loop¶
- Claims queued runs using
FOR UPDATE SKIP LOCKED(round-robin across tenants) - Creates a lease for each claimed run (with a 30s heartbeat TTL)
- Registers the real API key with the credential proxy (mapping per-run token → real key)
- Starts a sandbox container via the configured backend (Docker or Kubernetes)
- Injects
AGENTBOX_CREDENTIALS_JSONwith only the per-run token — no real keys
Reaper Loop¶
- Finds dead leases (no heartbeat for 30s) where status is still
running - Kills the corresponding container
- If max attempts exceeded: marks run as
failedpermanently - Otherwise: sets run back to
queuedfor retry
4. Runner (agentbox/runner/)¶
Code that executes inside the sandbox container. It:
- Connects to Postgres using the restricted
agentbox_runnerrole with Row-Level Security - Calls
SELECT set_config('app.run_id', $1, false)to scope all RLS policies - Loads the run configuration and credential tokens from env vars
- Builds a pydantic-ai Agent wrapped in
DurableModel - Heartbeats the lease every 5 seconds
- Executes the agent, checkpointing every model and tool call
- Writes the final result back to Postgres
- Deletes its lease on completion (so the reaper doesn't interfere)
5. PostgreSQL Database¶
The single source of truth, containing:
| Table | Purpose | RLS for runner |
|---|---|---|
tenants |
Multi-tenant configuration | No access (policy USING (false)) |
runs |
Run metadata, status, results | SELECT all, UPDATE only own run_id |
checkpoints |
Step-by-step checkpoints for durable execution | SELECT/INSERT only own run_id |
leases |
Container lease management (heartbeat-based) | Full CRUD only own run_id |
scoped_credentials |
Per-run tokens (UUIDs, NOT real keys) | No access (policy USING (false)) |
The runner connects using the agentbox_runner Postgres role, which has:
- Minimal column-level grants (only the columns the runner needs)
- Row-Level Security on every table
- app.run_id session variable set at connection init time, used by all RLS policies
6. Egress Proxy (Tinyproxy)¶
All outbound HTTP(S) traffic from sandbox containers goes through a Tinyproxy on an internal Docker network. This enforces default-deny egress:
FilterDefaultDeny Yes— only explicitly allowlisted domains are reachable- Allowlist uses anchored POSIX basic regular expressions (e.g.,
^api\.deepseek\.com$) - The internal Docker network has
internal: true, preventing direct internet access
7. Logfire / OpenTelemetry¶
All components emit spans to Logfire:
- Control plane: API request spans
- Launcher: claim and reap spans with run_id, attempt, replayed=true/false attributes
- Runner: model call and tool call spans with run_id, step_index attributes
- asyncpg and httpx are instrumented for full visibility
Durable Execution¶
This is the core innovation of AgentBox. Here's how it works:
Run 1 (live): step 0 ──► step 1 ──► step 2 [CONTAINER KILLED]
│ │
checkpoint checkpoint
stored ✓ stored ✓
Run 2 (resume): step 0 ──► step 1 ──► step 2 ──► step 3
│ │ │
replayed! replayed! live!
(no LLM (no LLM (new work)
call) call)
Key Design Decisions¶
Why replay-based durability (not Temporal)?
Temporal is excellent but heavyweight. The Postgres checkpoint layer is:
- Simple: a few SQL queries, no external workflow engine.
- Debuggable: checkpoints are just rows in a
checkpointstable. - Testable: inject an in-memory pool for unit tests.
The tradeoff: the agent code must be deterministic (or replayed steps must tolerate different fingerprints). In practice, pydantic-ai agents are deterministic given the same input, so this works well.
The Step Protocol¶
Every side-effecting operation gets a deterministic, monotonically increasing step_index:
- Before executing step N, check Postgres for a checkpoint at
(run_id, N) - Found it? Return the stored result without re-executing (fast-forward)
- Not found? Execute, store the result, and continue
The DurableContext class (in agentbox.runner.durable) implements this protocol.
Fingerprint Verification¶
Each checkpoint stores a SHA-256 fingerprint of the input. On replay, if the fingerprint doesn't match, a warning is logged — this helps detect non-determinism in the agent code.
Credential Security Model¶
What happens with your API key¶
┌──────────────────────┐
│ Launcher host │
│ env: DEEPSEEK_API_KEY│
└──────┬───────────────┘
│ register key
▼
┌──────────────────────┐
│ credential-proxy │
│ in-memory map: │
│ token → real_key │
└──────┬───────────────┘
│ proxy request
▼
┌──────────────────────┐
│ sandbox container │
│ env: per-run token │
│ (NOT the real key) │
└──────────────────────┘
- At startup: launcher reads
DEEPSEEK_API_KEYfrom its environment - On run claim: launcher calls credential proxy's
/admin/keysAPI: - Registers
{per_run_token → real_api_key, base_url, expires_at} - The real key exists only in the proxy's memory
- In the sandbox: runner only has
AGENTBOX_CREDENTIALS_JSONwith the per-run token - On LLM call: runner sends the per-run token to
credential-proxy:9090 - Proxy looks up the real key, replaces
Authorizationheader, forwards the request - Proxy checks
expires_atand rejects expired tokens
Database RLS¶
The agentbox_runner Postgres role enforces row-level security:
runs: can SELECT any row (needed for validation), but UPDATE only its ownrun_idcheckpoints: SELECT/INSERT only rows matchingapp.run_idleases: full CRUD only on its own lease rowscoped_credentials: completely invisible to the runnertenants: completely invisible to the runner
The runner sets app.run_id at connection init via SELECT set_config('app.run_id', $1, false), and all RLS policies reference current_setting('app.run_id').
Failure Modes¶
| Failure | Behavior |
|---|---|
| Container killed mid-run | Lease expires (30s), reaper requeues run, retry with checkpoints |
| Launcher crashes | Containers keep running; new launcher picks up on restart |
| Postgres down | API returns 503; launcher retries connections |
| LLM API timeout | Model call checkpoint records error; run fails with attempt retry |
| Credential proxy down | Launcher logs warning, runs fail at first LLM call (no key injection) |
| Non-deterministic agent | Fingerprint mismatch logged as warning; cached result still used |
| Concurrent tool calls | Step index is sequentially assigned per checkpoint (see docs/development.md for edge cases) |
Backends¶
Docker¶
The default backend. Creates a single container per run on an internal Docker network (agentbox-internal) with:
- Resource limits (CPU, memory, PIDs)
- Read-only root filesystem
- No elevated capabilities
- Egress through Tinyproxy
Kubernetes¶
Creates a K8s Job per run with:
- Temporary Secrets for credentials (cleaned up on completion/reap)
- Optional gVisor runtime class for stronger isolation
- NetworkPolicy with matchExpressions for pod-level filtering
- automountServiceAccountToken: false — runner pod has no K8s API access
Successfully completed Jobs are automatically cleaned up after 5 minutes (ttlSecondsAfterFinished).
What Production Would Need¶
- Firecracker/Kata microVMs: stronger isolation than containers
- Vault: for true scoped credential minting with audit logging
- Per-tenant credential vault: isolate credential blast radius per tenant
- Fair scheduling with preemption: weighted queues, priority classes
- Autoscaling: scale launcher workers and warm pool based on queue depth
Design Decisions¶
Architecture Decision Records for the choices most likely to be questioned.
ADR-1: A Postgres checkpoint layer instead of Temporal / DBOS / Prefect¶
Status: accepted
Pydantic AI ships first-class durable-execution integrations for Temporal, DBOS, and Prefect. Why does AgentBox implement its own replay layer on Postgres?
Context¶
AgentBox already needs Postgres for its control plane: the run queue
(FOR UPDATE SKIP LOCKED), leases/heartbeats, tenants, and scoped
credential metadata all live there. The durability requirement is narrow
and precise: a killed sandbox must resume without repeating a single
LLM call.
Decision¶
Checkpoint every side-effecting step (model call, tool call) to a
checkpoints table keyed by (run_id, step_index), and replay by
fast-forwarding through existing checkpoints on restart.
Rationale¶
- No second system. Temporal adds a server cluster plus worker processes; DBOS and Prefect add their own runtime and control plane. For a platform whose entire state already lives in one Postgres, a second source of truth increases the operational surface more than it saves code — the whole replay layer is ~200 lines.
- The checkpoint table is also the product. Checkpoints double as
the audit log, the cost ledger (token counts and USD per step), and
the data behind
GET /runs/{id}/checkpoints. A workflow engine would keep this state internal, and we would re-export it anyway. - One isolation model. Runner containers connect with a restricted
role under Row-Level Security scoped to their
run_id. Checkpoints written through the same connection inherit exactly the same isolation guarantees as everything else the runner touches. - Deterministic-replay contract is small here. Agent loops are linear conversations: the N-th model call sees the same messages on replay (verified by fingerprint). We do not need Temporal's general workflow versioning, signals, or timers.
Trade-offs accepted¶
- At-least-once boundaries. If the runner dies after an LLM call returns but before the checkpoint INSERT commits, that one in-flight call is repeated on resume. Temporal has the same fundamental window; we document it in Failure Modes.
- No cross-run orchestration. Fan-out/fan-in across runs, timers, and human-in-the-loop signals would favor a workflow engine. If AgentBox grows those requirements, the right move is Pydantic AI's DBOS integration (closest to our "durability inside Postgres" shape), not more custom code.
- Concurrent tool execution. Step indices are assigned in call
order. Agents that execute multiple tool calls concurrently could
interleave differently on replay; the demo agent's tools run
sequentially. A production version would key tool checkpoints by
(run_id, tool_name, args_fingerprint)instead of a global counter.
ADR-2: Credential proxy instead of vault-issued credentials¶
Status: accepted
The sandbox never receives a real LLM API key. It gets a random per-run
token; the credential proxy holds {token → real key} in memory only,
swaps the Authorization header on each request, and enforces the token's
TTL. Compromising the sandbox therefore yields a credential that expires
in minutes, works only through the proxy, and can be revoked centrally.
A vault (e.g. HashiCorp Vault) issuing short-lived downstream credentials would be the production-grade version of the same idea, but most LLM providers cannot mint scoped sub-keys — so a header-rewriting proxy is what actually enforces the boundary either way.
ADR-3: Egress allowlist is global, not per-run (known limitation)¶
Status: accepted (limitation documented)
POST /runs accepts an egress_allow list and stores it, but the
tinyproxy allowlist is a single static file shared by all runs — per-run
domains are not currently appended. Enforcing per-run policy needs
one of:
- a proxy with a dynamic admin API (regenerate + reload per run),
- per-run proxy sidecars, or
- K8s NetworkPolicy objects generated per run.
All three are heavier than the MVP needs; the field stays in the API so
the data model doesn't change when enforcement lands. Until then, the
global allowlist in docker/tinyproxy-allowlist.txt is the boundary.
Development¶
Guide for contributing to AgentBox.
Setup¶
Prerequisites¶
- Python 3.12+
- Docker + Docker Compose
uvpackage manager
Clone and install¶
Start Postgres¶
Running Tests¶
# All tests (requires Postgres)
make test
# Unit tests only (no Postgres needed)
make test-unit
# End-to-end tests (requires Postgres)
make test-e2e
# Linting
make lint
Test Structure¶
tests/
├── unit/
│ ├── test_durable.py # Core checkpoint/replay tests
│ ├── test_mcp_server.py # MCP server tests
│ ├── test_cost.py # Cost tracking tests
│ └── test_kill_and_resume.py # Unit test with TestModel
└── e2e/
├── test_api.py # API integration tests
└── test_kill_and_resume.py # Kill-and-resume demo test (requires Docker)
Writing Tests¶
- Unit tests use an
InMemoryPoolto avoid requiring Postgres - The
FakeModelclass intest_durable.pysimulates an LLM - Tests verify that replay fast-forwards without re-calling the model
@pytest.mark.asyncio
async def test_replay_uses_checkpoints(pool, fake_model):
"""Verify replay uses cached checkpoints, not live calls."""
run_id = "test-replay"
context = DurableContext(run_id, pool)
durable = DurableModel(fake_model, context)
agent = Agent(durable, tools=[...], system_prompt="...")
# First run: live execution
result1 = await agent.run("Analyze...")
# Second run: replay (model should NOT be called)
context2 = DurableContext(run_id, pool)
durable2 = DurableModel(fake_model, context2)
agent2 = Agent(durable2, tools=[...], system_prompt="...")
result2 = await agent2.run("Analyze...")
assert model.call_count == 0 # No live calls during replay
assert str(result2.output) == str(result1.output) # Same output
Code Style¶
- Linter: Ruff (
make lint) - Line length: 100 characters
- Type hints: Required for all public APIs
- Async: Use
async/awaitthroughout - Imports: Use
from __future__ import annotationsin all modules
Project Structure¶
src/agentbox/ # Main source code
├── api/ # FastAPI control plane
│ ├── main.py # App setup, lifespan, middleware
│ └── routes.py # API endpoints
├── cost/ # Cost estimation
│ └── tracker.py # Token + compute cost calculations
├── db/ # Database layer
│ ├── migrate.py # Migration runner
│ └── queries.py # asyncpg query functions
├── launcher/ # Queue poller + sandbox backends
│ ├── worker.py # Poll loop + reaper
│ ├── backend_docker.py # Docker SDK backend
│ ├── backend_k8s.py # Kubernetes backend
│ └── warm_pool.py # Cold-start optimization
├── mcp_server/ # MCP server for telemetry
│ └── server.py
├── runner/ # Code inside the sandbox
│ ├── main.py # Runner entrypoint (sets app.run_id via set_config)
│ ├── durable.py # Core checkpoint/replay engine
│ ├── durable_model.py # pydantic-ai Model wrapper
│ ├── durable_tool.py # Tool checkpointing decorator
│ ├── agents.py # Demo agent definitions
│ └── credentials.py # Scoped credential loader
├── secrets/ # Credential scoping (per-run token minting)
│ └── scoper.py
└── settings.py # pydantic-settings configuration
Key Modules¶
durable.py — Checkpoint/Replay Engine¶
The DurableContext class manages step-by-step checkpointing:
context = DurableContext(run_id, pool)
# On first run: executes fn() and stores result
result = await context.step("model_call", fn, fingerprint=sha)
# On replay: returns stored result without calling fn()
result = await context.step("model_call", fn, fingerprint=sha)
The step() method uses a single database connection for both reading and writing checkpoints, ensuring atomicity.
durable_model.py — Model Wrapper¶
DurableModel wraps any pydantic-ai Model and routes every request() through DurableContext.step(). This is a drop-in replacement:
inner = OpenAIModel("gpt-4", api_key=key)
model = DurableModel(inner, context=durable_context)
agent = Agent(model)
During replay, stored checkpoint data (serialized as dicts) is reconstructed into proper ModelResponse objects via _deserialize_model_response().
worker.py — Launcher + Reaper¶
The launcher runs two concurrent loops:
- Poll loop: claims queued runs (round-robin across tenants) and starts containers
- Reaper loop: finds dead leases and requeues or fails runs
The _handle_claimed_run() method orchestrates lease creation, credential proxy registration, and container startup.
The launcher registers {per_run_token → real_api_key} with the credential proxy at /admin/keys. The per-run token is fetched from scoped_credentials (which stores only a UUID, NOT the master key). On container start failure, the key mapping is unregistered from the proxy.
Making Changes¶
- Create a feature branch from
main. - Run
make lint && make testlocally. - Ensure all tests pass.
- Open a PR with a clear description of the changes.
License¶
By contributing, you agree that your contributions will be licensed under the MIT License.