Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .agentenv/config.example.toml
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ agent_default = "local" # agents too
# api_key = "secret:kosa8_api_key" # or "env:KOSA8_API_KEY"
# region = "us" # optional: "us", "eu", "us-ash1" or "eu-hel1"

# Optional Mirage virtual terminals, for deploy_sandbox steps (no extra; needs a running Mirage daemon):
# [sandbox.providers.mirage.config]
# url = "http://127.0.0.1:8765"
# token = "secret:mirage_token" # optional

# Optional CoreWeave Sandboxes (install the 'coreweave' extra):
# [sandbox.providers.coreweave.config]
# api_key = "secret:cwsandbox_api_key" # or wandb_api_key, with optional wandb_entity and wandb_project
Expand Down
8 changes: 4 additions & 4 deletions AGENTS.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/agent_env/cli/a2a_agent/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
@click.option("--ttl-seconds", type=click.IntRange(min=MIN_TTL_SECONDS, max=MAX_TTL_SECONDS), default=DEFAULT_TTL_SECONDS,
help=f"VM lifetime in seconds (default {DEFAULT_TTL_SECONDS})")
@click.option("--sandbox", default=None,
help="Sandbox backend(s): a built-in (modal, modal_vm, e2b, tensorlake, tenki, boxd, coreweave, daytona, boat, agent37, kosa8, local) "
help="Sandbox backend(s): a built-in (modal, modal_vm, e2b, tensorlake, tenki, boxd, coreweave, daytona, boat, agent37, kosa8, mirage, local) "
"or a name from [sandbox.providers] in .agentenv/config.toml; comma-separated for a "
"fallback chain. Defaults to [sandbox].agent_default (else local) when omitted.")
def deploy(agent_id: str, agent_version: int | None, env_var_pairs: tuple[str, ...], ttl_seconds: int, sandbox: str):
Expand Down
2 changes: 1 addition & 1 deletion src/agent_env/cli/env/deploy.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
@click.option("--gateway-mode", type=click.Choice([m.value for m in GatewayMode], case_sensitive=False),
default=GatewayMode.PERFORMANCE.value, help="Gateway mode (performance or consistent)")
@click.option("--sandbox", default=None,
help="Sandbox backend(s): a built-in (modal, modal_vm, e2b, tensorlake, tenki, boxd, coreweave, daytona, boat, agent37, kosa8, local) "
help="Sandbox backend(s): a built-in (modal, modal_vm, e2b, tensorlake, tenki, boxd, coreweave, daytona, boat, agent37, kosa8, mirage, local) "
"or a name from [sandbox.providers] in .agentenv/config.toml; comma-separated for a "
"fallback chain. Defaults to [sandbox].default (else local) when omitted.")
@click.option("--service-db", "service_db_env_id", default=None,
Expand Down
140 changes: 140 additions & 0 deletions src/agent_env/providers/sandbox_providers/mirage/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
# `mirage` sandbox provider

Runs agent-env sandboxes as [Mirage](https://github.com/strukto-ai/mirage) virtual terminals, sandbox-like terminal
environments for AI agents. Each `deploy_sandbox` step gets its own Mirage workspace, which starts with KBs of memory:
Mirage keeps the shell and the files, and programs run on the
[machines](https://docs.mirage.strukto.ai/home/setup/machine/overview) its config names, so a container or cloud
sandbox serves only as compute. A workspace serves no ports, so envs and agents stay on another provider.

## Set up

### 1. No extra to install

The provider drives the daemon's HTTP API with `httpx`, which agent-env already depends on.

### 2. Start a Mirage daemon

Mirage needs Python 3.12 or later, so give it a venv of its own:

```bash
pip install mirage-ai
python -m uvicorn mirage.server.daemon:app --host 127.0.0.1 --port 8765
```

A daemon that others can reach should take a token
([`MIRAGE_AUTH_MODE=token`](https://docs.mirage.strukto.ai/home/access/http)).

### 3. Configure

```toml
[sandbox.providers.mirage.config]
url = "http://127.0.0.1:8765"
# token = "secret:mirage_token"
```

Then pass `--sandbox mirage`, or set `sandbox_type: "mirage"` on a `deploy_sandbox` step. Keep `[sandbox] default` and
`agent_default` on a provider that serves ports, where envs and agents deploy.

### 4. Run something

```bash
agent-env run hello --sandbox mirage
```

`agent-env -v run …` also logs each workspace as it starts
(`Mirage workspace started: id=… daemon=… memory=…MiB network=… attribution=…`).

## Configuration reference

All keys go under `[sandbox.providers.mirage.config]`. Unknown keys are refused.

| Key | Default | Meaning |
| ----------- | ----------------------- | --------------------------------------------------------------------------------------------- |
| `url` | `http://127.0.0.1:8765` | The Mirage daemon. |
| `token` | none | The daemon's bearer token, as an `env:` or `secret:` reference. |
| `workspace` | none | A [Mirage workspace config](https://docs.mirage.strukto.ai/home/configuration/workspace) that every sandbox starts from, such as its `mounts` or `env`. It can't set `network`, `max_memory` or the id, which come from each step. |

## Examples

**Mirage's commands only.** With no machine, a sandbox has Mirage's shell and its own commands. `load_artifact`,
`verify_sandbox` and `collect_artifacts` run and `agent-env run hello` passes; `python3` and `docker` are
`command not found`, so `run_code` exits 127. The config is `url` alone.

**Python inside Mirage.** Mirage's in-process Monty interpreter runs `python3 -c` and the Python scripts a step loads.
`run_code` doesn't run on it: its runner needs `subprocess` and `signal`, which Monty lacks.

```toml
[sandbox.providers.mirage.config.workspace.machines.py]
provider = "in_process"
runtime = "monty"
```

**A Docker container as the compute.** Mirage serves the container's filesystem as the workspace and runs every program
in the container, `run_code` included, while its shell stays Mirage's. You start the container; the daemon's host needs
`docker`. Six SWE-bench Verified trajectories replayed this way, one container per instance image, with every recorded
exit code matching.

```toml
[sandbox.providers.mirage.config.workspace.machines.box]
provider = "docker"
container = "my-container"
captures = ["@python", "@external"]

[sandbox.providers.mirage.config.workspace.mounts."/"]
vfs = "machine"
mode = "exec"
config = { machines = ["box"], root = "/" }
```

**A read-only S3 bucket at `/data`** in every sandbox, beside the RAM root:

```toml
[sandbox.providers.mirage.config.workspace.mounts."/data"]
vfs = "s3"
mode = "read"
config = { bucket = "datasets", region = "us-east-1", aws_access_key_id = "env:AWS_ACCESS_KEY_ID", aws_secret_access_key = "secret:aws_secret" }
```

## Resources and lifetime

- **Memory:** the step's `memory` is the workspace's `max_memory`. A write past it fails with `Disk quota exceeded`.
- **Ignored requests:** `cpu`, `disk_size_gb` and `timeout` have no Mirage equivalent. `boot_mode` and `env` log a
warning.
- **Refused requests:** a per-sandbox `image` or `exposed_ports` is refused before anything is created.
- **Lifetime:** a workspace lasts until it is terminated or the daemon stops. A run that crashes leaves its workspace;
`agent-env task teardown --instance <id>` deletes it.

## Networking

- **Ports:** none, so `tunnel_urls` is empty.
- **Egress:** allow-all, nothing, or an allowlist of hostnames, `*.` wildcards, addresses and ranges, as the workspace's
`network.allowed_domains`. Mirage holds every connection it opens for the workspace to it, its commands' and its
mounts' alike; a program on a machine uses that machine's network.
- **Wildcards:** `*.example.com` covers every name under `example.com` but not `example.com` itself.
- **Reconnect:** `get_sandbox` restores the workspace. Its `network_policy` reads `None`, since the daemon doesn't
report it; the workspace keeps enforcing it.

## Cleanup

- A workspace whose setup fails, or whose create is cancelled, after the daemon made it is deleted.
- `terminate` is idempotent: a workspace that is already gone is not an error.

## Things to know

- **The shell is Mirage's:** bash-compatible, with coreutils, `curl`, `jq`, `tar` and more. Other programs, such as
`python3` or `docker`, run on the machines in `workspace.machines` (see [Examples](#examples)).
- **Each command runs in a session of its own,** from `/`, so a `cd` or `export` doesn't carry over. There are no
users, so the `sudo` agent-env prefixes is dropped.
- **No output caps:** Mirage's defaults (2,000 lines for `cat`, `head` and the like, 600 s a line) are lifted;
`workspace.command_limits` sets caps of your own.
- **Lost connections:** a command whose answer is lost returns exit code -1. `exec_script` retries idempotent scripts
on -1 only.
- **Files** go through the daemon's file API in 2 MiB pieces, so a secret never enters a command line. `/tmp` is made in
each workspace for staging.

## Testing

`tst/integration/providers/sandbox_providers/mirage_sandbox_smoke_test.py` runs against a real daemon when one answers
`/v1/health` at the provider's `url`. Otherwise it skips with `agentenv-capability-missing: remote_sandbox`. The unit
tests are `tst/unit/providers/sandbox_providers/mirage_sandbox_provider_test.py` and `mirage_sandbox_test.py`, and run
offline against an in-memory daemon behind `httpx.MockTransport`.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
"""Mirage workspace sandbox provider (no extra: it drives a Mirage daemon's HTTP API with ``httpx``); see README.md."""
172 changes: 172 additions & 0 deletions src/agent_env/providers/sandbox_providers/mirage/provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""Mirage workspace sandbox provider.

Each sandbox is a Mirage virtual terminal: a workspace on a Mirage daemon, with a virtual shell, filesystem, CLIs and
machines. A workspace serves no ports, so it holds no env's gateway and no agent.
"""

from __future__ import annotations

import asyncio
import logging
import uuid
from typing import Any, Self

import httpx

from agent_env.attribution import Attribution
from agent_env.config.errors import ConfigError
from agent_env.providers.sandbox_providers.mirage.sandbox import MirageApi, MirageError, MirageSandbox
from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy
from agent_env.providers.sandbox_providers.sandbox_provider import (
SandboxProvider,
apply_default_attribution,
refuse_unenforceable_policy,
)

logger = logging.getLogger(__name__)

NAME_PREFIX = "agentenv"
NAME_SUFFIX_LENGTH = 16
_SECTION = "[sandbox.providers.mirage.config]"
_CONFIG_KEYS = frozenset({"url", "token", "workspace"})
_cleanups: set[asyncio.Task] = set()


def workspace_id() -> str:
return f"{NAME_PREFIX}-{uuid.uuid4().hex[:NAME_SUFFIX_LENGTH]}"


def network_setting(policy: NetworkPolicy) -> bool | dict[str, list[str]]:
if not policy.restricts_egress:
return True
if policy.closed:
return False
return {"allowed_domains": [*policy.allow_hosts, *policy.allow_cidrs]}


async def _settle(cleanup: Any) -> None:
"""Run ``cleanup`` to its end, also while the caller is being cancelled: ``asyncio.run`` waits for the task it
cancels, so it waits for the cleanup too. A second cancellation leaves the cleanup running on its own."""
task = asyncio.ensure_future(cleanup)
_cleanups.add(task)
task.add_done_callback(_cleanups.discard)
await asyncio.shield(task)


class MirageSandboxProvider(SandboxProvider):
"""Workspaces on a Mirage daemon, the Python or the TypeScript one, each a sandbox of its own.

``token`` comes from resolved provider config, never from the process environment: configure it with an ``env:`` or
``secret:`` reference in ``[sandbox.providers.mirage.config]``. Workloads never see it, nor the credentials of the
mounts ``workspace`` configures, which stay in the daemon.
"""

def __init__(
self,
*,
url: str = "http://127.0.0.1:8765",
token: str | None = None,
workspace: dict[str, Any] | None = None,
transport: httpx.AsyncBaseTransport | None = None,
):
workspace = workspace or {}
# Mirage cuts `cat` at 2,000 lines and a line at 600 s by default, which breaks agent-env's file reads.
self._workspace = {
"command_limits": {"@all": {"max_lines": None, "max_bytes": None}, "@line": {"timeout_seconds": None}},
**workspace,
"mounts": {"/": {"vfs": "ram", "mode": "exec"}, **workspace.get("mounts", {})},
}
self._api = MirageApi(url, token=token, transport=transport)

@classmethod
def from_config(cls, **config: Any) -> Self:
unknown = set(config) - _CONFIG_KEYS
if unknown:
raise ConfigError(f"{_SECTION} has unknown key(s): {sorted(unknown)}")
for key in ("url", "token"):
value = config.get(key)
if value is not None and (not isinstance(value, str) or not value.strip()):
raise ConfigError(f"{_SECTION} '{key}' must be a non-empty string")
workspace = config.get("workspace")
if workspace is not None:
if not isinstance(workspace, dict):
raise ConfigError(f"{_SECTION} 'workspace' must be a table: a Mirage workspace config")
if taken := sorted({"network", "max_memory", "workspace_id"} & set(workspace)):
raise ConfigError(f"{_SECTION} 'workspace' sets {taken}, which each sandbox's step sets")
if not isinstance(workspace.get("mounts", {}), dict):
raise ConfigError(f"{_SECTION} 'workspace.mounts' must be a table of mounts by path")
return cls(**config)

@classmethod
def supports_network_policy(cls, policy: NetworkPolicy) -> bool:
"""Mirage holds a workspace's shell and mounts to hostnames, ``*.`` wildcards, addresses and ranges."""
return True

async def close(self) -> None:
"""Close this event loop's client; a sandbox this provider made reopens its connection if it is used again."""
await self._api.close()

async def create_vm(
self,
*,
image: str | None = None,
boot_mode: str | None = None,
cpu: float = 1.0,
memory: int = 8192,
disk_size_gb: float = 10,
timeout: int = 3600 * 2,
exposed_ports: list[int] | None = None,
setup_for_gateway: bool = True,
attribution: Attribution | None = None,
network_policy: NetworkPolicy | None = None,
env: dict[str, str] | None = None,
) -> MirageSandbox:
"""A workspace boots no image and serves no port, so ``image`` and ``exposed_ports`` are refused; it has no
CPU, disk or lifetime limit, so ``cpu``, ``disk_size_gb`` and ``timeout`` are ignored."""
if image is not None:
raise ValueError("a Mirage workspace boots no image; a per-call image is unsupported")
if exposed_ports:
raise ValueError(f"a Mirage workspace serves no ports, so it can't expose {exposed_ports}")
if boot_mode is not None:
logger.warning("Ignoring boot_mode=%s: Mirage workspaces have no boot modes", boot_mode)
if env:
logger.warning("Ignoring env for a Mirage workspace: it boots no disk image to seed")
refuse_unenforceable_policy(self, network_policy)
effective_policy = self.effective_network_policy(network_policy)
resolved_attribution = {
key: str(value)
for key, value in apply_default_attribution(dict(attribution or {})).items()
if value is not None
}
config = {**self._workspace, "network": network_setting(effective_policy), "max_memory": memory * 1024 * 1024}
sandbox = MirageSandbox(self._api, workspace_id(), network_policy=effective_policy)
made = False
try:
await self._api.create_workspace(sandbox.sandbox_id, config)
made = True
await sandbox.exec_script("mkdir -p /tmp") # where agent-env stages files; a RAM root starts empty
except BaseException as exc:
# A lost answer may still have made the workspace; a refusal or no daemon didn't.
if made or not isinstance(exc, (MirageError, httpx.ConnectError)):
await _settle(self._delete_quietly(sandbox.sandbox_id))
raise
logger.info(
"Mirage workspace started: id=%s daemon=%s memory=%sMiB network=%s attribution=%s",
sandbox.sandbox_id, self._api.url, memory, config["network"], resolved_attribution,
)
return sandbox

async def _delete_quietly(self, sandbox_id: str) -> None:
try:
await self._api.delete_workspace(sandbox_id)
except Exception as exc: # noqa: BLE001 - logged; the caller's own error is the one raised
logger.error("Mirage workspace %s from a failed create is still on the daemon: %s", sandbox_id, exc)

async def get_sandbox(self, sandbox_id: str) -> MirageSandbox:
"""Reconnect. The daemon doesn't report a workspace's network setting, so the applied policy reads as unknown
(None)."""
await self._api.get_workspace(sandbox_id)
return MirageSandbox(self._api, sandbox_id, network_policy=None)

async def terminate_sandbox(self, sandbox_id: str) -> None:
await self._api.delete_workspace(sandbox_id)
Loading