# Sandbox Lifecycle Manager Spawning Flow in Background‑Agents: A Complete Technical Guide

> Uncover the sandbox lifecycle manager spawning flow in BackgroundAgents. This guide details its six-stage pipeline from API request to container teardown for isolated coding environments.

- Repository: [Cole Murray/background-agents](https://github.com/ColeMurray/background-agents)
- Tags: deep-dive
- Published: 2026-07-13

---

**The sandbox lifecycle manager spawning flow in Background‑Agents orchestrates the creation, execution, and teardown of isolated coding environments through a six-stage pipeline that routes API requests through image building, Modal container instantiation, bridge initialization, and health-monitored cleanup.**

The Background‑Agents platform (`ColeMurray/background-agents`) implements a robust **sandbox lifecycle manager spawning flow** to provision secure, ephemeral development environments for AI coding agents. This system coordinates between the web API, image builders, and Modal infrastructure to transform a simple repository URL into a running sandbox with code-server, SSH access, and real-time bridge connectivity.

## The Six-Stage Spawning Pipeline

The complete lifecycle follows a deterministic sequence from initial request to final cleanup.

### Stage 1: API Request Validation and Scheduling

The flow begins when a client—such as a Web UI, Slack bot, or Linear webhook—invokes `web_api.create_sandbox`. According to the source code in `modal‑infra/src/web_api.py`, this function validates the incoming request, records the desired sandbox configuration, and forwards the request to the **Image‑Builder Scheduler** (`modal‑infra/src/scheduler/image_builder.py`).

### Stage 2: Image Building and Caching

The scheduler checks the image cache for existing builds. If no suitable image exists, the system launches a Modal **image‑builder** job that runs the repository’s Dockerfile, installs tools, and stores the built image in Modal’s image registry. This logic is implemented in `modal‑infra/src/scheduler/image_builder.py`.

### Stage 3: Modal Container Instantiation

Once the image is ready, [`sandbox/manager.py`](https://github.com/ColeMurray/background-agents/blob/main/sandbox/manager.py) receives the prepared image ID and invokes `modal.Image.from_registry` to start a **Modal container** (`modal.Container`). As implemented in `ColeMurray/background-agents`, the manager passes:

- Environment variables (including the sandbox secret token)
- Port mappings for the code‑server, SSH, and the custom bridge (`/bridge`)
- A start‑up script ([`entrypoint.py`](https://github.com/ColeMurray/background-agents/blob/main/entrypoint.py)) that launches the code‑server and the bridge supervisor

### Stage 4: Bridge Initialization and Supervision

Inside the container, the **bridge** (`sandbox‑runtime/src/sandbox_runtime/bridge.py`) opens a Server‑Sent Events (SSE) channel back to the Control Plane. A **supervisor** process watches the bridge, restarts the code‑server if it crashes, and forwards logs to the central log collector (`sandbox‑runtime/src/sandbox_runtime/log_config.py`). The entry point logic resides in `sandbox‑runtime/src/sandbox_runtime/entrypoint.py`.

### Stage 5: Health Checks and Heartbeat Registration

The manager registers a periodic heartbeat with the Control Plane Durable Object. If heartbeats stop—such as when the client disconnects or the sandbox exceeds its TTL—the manager triggers a graceful shutdown sequence.

### Stage 6: Graceful Teardown and Resource Cleanup

On timeout, explicit user request, or failure detection, the manager calls `container.stop()` and cleans up temporary files, ports, and D1 records. The sandbox’s image remains cached in the registry for future reuse.

## Practical Implementation Examples

You can interact with this spawning flow through the public REST API.

### Creating a Sandbox

```python
import requests

payload = {
    "repo_url": "https://github.com/example/my‑repo",
    "image_tag": "latest",
    "env": {"TOKEN": "placeholder"},
    "ttl_seconds": 3600,
}
resp = requests.post(
    "https://api.background‑agents.com/v1/sandboxes",
    json=payload,
    headers={"Authorization": "Bearer <user‑jwt>"},
)
sandbox_id = resp.json()["id"]
print(f"Sandbox created: {sandbox_id}")

```

### Polling Sandbox Status

```python
import time
import requests

while True:
    r = requests.get(
        f"https://api.background‑agents.com/v1/sandboxes/{sandbox_id}",
        headers={"Authorization": "Bearer <user‑jwt>"},
    )
    data = r.json()
    print(f"State: {data['state']} – Uptime: {data['uptime_seconds']}s")
    if data["state"] in ("READY", "FAILED"):
        break
    time.sleep(2)

```

### Graceful Shutdown

```python
requests.delete(
    f"https://api.background‑agents.com/v1/sandboxes/{sandbox_id}",
    headers={"Authorization": "Bearer <user‑jwt>"},
)

```

## Summary

- The **sandbox lifecycle manager spawning flow** begins with API validation in [`web_api.py`](https://github.com/ColeMurray/background-agents/blob/main/web_api.py) and ends with resource cleanup via `container.stop()`.
- **Image building** occurs on-demand through [`scheduler/image_builder.py`](https://github.com/ColeMurray/background-agents/blob/main/scheduler/image_builder.py), caching results for subsequent spawns.
- **Container instantiation** uses `modal.Image.from_registry` in [`sandbox/manager.py`](https://github.com/ColeMurray/background-agents/blob/main/sandbox/manager.py) to launch Modal containers with specific port mappings and environment variables.
- The **bridge** ([`bridge.py`](https://github.com/ColeMurray/background-agents/blob/main/bridge.py)) and **supervisor** maintain the SSE connection to the Control Plane and handle process restarts.
- **Health monitoring** relies on Control Plane Durable Object heartbeats to detect stale or orphaned sandboxes.
- **Teardown** preserves the built image in the registry while removing temporary files and network bindings.

## Frequently Asked Questions

### What triggers the sandbox lifecycle manager spawning flow?

The spawning flow triggers when a client makes a POST request to the sandbox creation endpoint, calling `web_api.create_sandbox`. This validates the request and initiates the image building and container instantiation sequence.

### How does the sandbox maintain connectivity with the Control Plane?

Inside each running container, the **bridge** module ([`sandbox_runtime/bridge.py`](https://github.com/ColeMurray/background-agents/blob/main/sandbox_runtime/bridge.py)) establishes a Server-Sent Events (SSE) channel back to the Control Plane. This bridge handles bidirectional communication while a supervisor process ensures the connection remains active by restarting crashed components.

### What happens if the sandbox exceeds its TTL or crashes?

If heartbeats cease or the TTL expires, the manager detects the failure and invokes `container.stop()` to initiate graceful shutdown. This process cleans up temporary files, releases port mappings, and removes D1 records without deleting the cached image, allowing for faster future spawns.

### Where is the sandbox configuration and image building logic defined?

The core spawning logic resides in `modal‑infra/src/sandbox/manager.py`, while image building is handled by `modal‑infra/src/scheduler/image_builder.py`. The runtime bridge and entrypoint scripts are located in the `sandbox‑runtime` package, specifically in [`bridge.py`](https://github.com/ColeMurray/background-agents/blob/main/bridge.py) and [`entrypoint.py`](https://github.com/ColeMurray/background-agents/blob/main/entrypoint.py).