diff --git a/.agentenv/config.example.toml b/.agentenv/config.example.toml index 2c55a1fcd..29c97c4cc 100644 --- a/.agentenv/config.example.toml +++ b/.agentenv/config.example.toml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 181ad45b9..3ab89c14d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -71,9 +71,9 @@ or one of them only where it is used. store, an OCI registry at `localhost:5000`, env-var secret store, `LocalRunner`, `local` Docker sandboxes for envs and agents. MongoDB, DynamoDB, Firestore, S3, Cloud Storage, ECR, AWS Secrets Manager, Google Cloud Secret Manager, and the Modal, E2B, Sail, SmolVM, Tensorlake, Tenki, Vercel, boxd, - CoreWeave, Daytona, boat, Agent37 and kosa8 sandboxes exist as implementations and are selected by config (all but - Agent37 and kosa8 through their extras: `sail`, `smol`, `tensorlake`, `tenki`, `vercel`, `boxd`, `coreweave`, `daytona`, - `boat`; every extra but `smol` is in `dev`; Agent37 and kosa8 need only `httpx`). + CoreWeave, Daytona, boat, Agent37, kosa8 and Mirage sandboxes exist as implementations and are selected by config (all + but Agent37, kosa8 and Mirage through their extras: `sail`, `smol`, `tensorlake`, `tenki`, `vercel`, `boxd`, `coreweave`, + `daytona`, `boat`; every extra but `smol` is in `dev`; Agent37, kosa8 and Mirage need only `httpx`). - The model endpoint is unset until `[model] base_url` / `api_key` (or `LITELLM_BASE_URL` / `LITELLM_API_KEY`) is configured. A loopback URL handed into a `local` container (the model endpoint, an agent, peer or gateway on this machine) becomes `host.docker.internal`. On Linux that @@ -196,7 +196,7 @@ and deserialized through a registry. | `task/`, `task_step/` | A `Task` holds its `TaskStep`s inline; `Task.run()` executes them as a DAG. Its `headline_verifiers`, step ids saved only when set, name the grades that are its reward: one is the reward, several a multi-reward over them, none a multi-reward over every grade; it refuses one that names no step of the task, or one named twice. `depends_on` (None means all prior steps) gates a step, independent steps run concurrently, `fail_task_on_error` makes a failure fatal or tolerated, `retry_config` rolls a failed span back through the step journal and re-dispatches it. `task/lint.py` is `agent-env task lint` (a bundle folder, a task file or a stored task): an error is what a task gets wrong before it runs (a field its step doesn't read, a step's own `config_problems`, a headline that grades nothing, an aggregate source no verifier writes) and refuses `agent-env run`, `bundle register`, `task create`, `task validate` and `eval run`, and the bundle plans `openenv`'s `build_app` and the trainers make (`run`, `register`, `build_app`, `prepare_bundle` and the trainers take `--skip-lint`/`skip_lint`, which lifts lint's own rules but not a step's `config_problems`, which refused a bundle before lint; `eval run`'s lifts every error, since it checked none before); a warning is what may be wrong (a step's `config_warnings`, a store entity read with no version, no verifier, several and no headline, a judge that runs in the solver's own agent, which training refuses) and is only printed, each kind once by a run (`task.lint.said`), an eval run's unpinned references as one count (`unpinned_summary`), every one by `task lint`. `aggregate_verifiers` names its sources by step id (`sources`, `gates`) and reads their named grades: `combine` `pooled` (the default) pools their rows, `weighted_mean` weighs their scores, equally unless `weights` gives every source one, and a failing gate scores it 0; a failed or missing source fails it, and its older `verifier_ids` pools legacy entries as it always has. Built-in steps live in `task_step/task_steps/` (`deploy_env`, `deploy_agent`, `prompt_agent`, the verifiers under `verifiers/`, among them `start_computer_recording` (its driver draws each input over the frames in its caller's colour, and a pointer per role where the frames lack one, unless `annotation_settings` says `is_enabled: false`; a driver whose card lists no `annotate` records it plain, with a warning, and the run's recording entry says `annotated`) and `end_computer_recording`, `start_browser_recording` and `end_browser_recording` (`browser-recording/v1`: one recording per context, a lease's or the default one's, with a video of the tab its agent is on, its context's log, the browser's network log as HAR and opt-in frames keyed to the action log, the contexts its agents make recorded with it, one universe per recording, anything missing failing the run), and more). Every built-in verifier is on the `VerifierTaskStep` base (`verifiers/verifier.py`): it implements `verify` and returns a `Verification`, and the base writes the step's named grade to `context.metadata["grades"][]` (score, `min_passing_score`, `passed`, `verifier_status` graded, skipped or failed, criteria rows, type, version, the `attempt_epoch` it was written under, and `verifier_settings`, the values the run graded with, its overrides applied and named in `overridden`, with `scoring_rules`) beside the legacy `verifications` entries every reader still takes; a judge's grade also has `judge_calls`, a record of each model call it made (`JudgeUsage`), each naming exactly what it was sent (`input`: a direct call's messages, response format and settings, an agent call's message, every file its step staged in the judge's sandbox and, for a judge the task deployed, what the task's own `load_artifact` steps put there as the run recorded it, stored by sha256 under `judge-inputs/` in the background, `judge_utils/judge_inputs.py`; the step waits for those uploads, at most 120 s, before it writes its grade, `VerifierTaskStep.settle`, and one that failed or hadn't finished is the call's `input_error`, never a failed grade), and its `verifier_settings` hold the trajectory source of each turn it read (`trajectory_sources`); with `judge_samples` (a count, as a step field, a run override or `--judge-samples` on `run`, `task run` and `eval run`), a rubric_binary or rubric_partial judge grades each criterion that many times, each a call of its own under `judge_batch_concurrency` (an agent judge the verifier deploys gets a deployment of its own per sample, its trajectory staged in each; the task's own judge takes every sample), and keeps its median, the lower middle score on a tie, which fails it, the row the first sample that scored it gave with every sample's score, verdict and justification in its `samples` and its `agreement`, the share of samples giving its verdict; a row under `min_judge_agreement` (0.5 by default, which never fails, so the median decides; 1.0 fails any split; set where `judge_samples` is, `--min-judge-agreement`) fails the grade, its rows kept, and then the step (`JudgeDisagreementError`), and `agent-env run` names the criteria a grade that stood split on (`samples split:`), and one failed sample fails the grade (a run's count or agreement a judge of another format can't take is recorded in `not_sent`) and the effort and thinking budget its calls carried, with `not_sent` for those its route or agent card doesn't take (a value the model refuses fails the grade); an exception from `verify` or a `Verification` with an `error`, as a timed-out `run_container_unit_tests_verifier`, is a failed grade, and `rubrics_verifier` still writes its `-trajectory-mistakes` entry itself. On an env whose card serves computer-exec/v1 (a computer), `run_code` with `env_id` and `run_container_unit_tests_verifier` with `env_id` run inside it as its session user through the driver: files staged with `data/add` and read with `data/get`, commands run with `run`; `computer_exec` runs one command there through `run` (a program and its arguments, or a string through `sh -c`; in a multi env, the computer it names), recorded under `computer_exec` in the run's metadata, a non-zero exit or a timeout failing it unless `check` is off, or with `background` starts it and leaves it running, as an app launched for the agent, a program that isn't there exiting 127; with `scope: "system"` it runs as root instead, through the computer's sandbox (`RootChannel`, `docker exec -u 0`), in the session user's folder and `HOME`, its output capped in the computer, never with `background` and not on a computer booted from a disk; on a Windows computer, which has no `sh`, a string or `background` command is refused; on a multi env, `load_artifact` with `env_id` puts an environment artifact named after one of its computers, or after an app of one, into that computer, the computer's own as files at their paths under the session user's home; `env_outcome_verifier` hands a `verify` that takes an `env_url` keyword the env's address. A computer's framework-only routes (everything but MCP and the card) take the per-deploy control token its provider boots it with (`DeployedEnv.control_token`), each computer its own, a multi env's included, never the gateway's: its boot environment holds only the token's sha256 (`AGENTENV_CONTROL_TOKEN_SHA256`) when its probed card's computer/v1 says `control_token = "sha256"`, else, for a driver an older protocol built, the token itself (`AGENTENV_CONTROL_TOKEN`); the gateway learns each computer's (`CHILD_CONTROL_TOKENS`), puts it in place of its own on that computer's `/svc` routes, and lets a computer's token through only to that computer and its clock watch; a multi env's record grants each computer's `/svc` route its own token (`DeployedGatewayEnv.control_grants`, the longest granted address winning), and `CONTROL_TOKEN_CHILDREN`, the computers an older agent-env booted with the gateway's token, is kept for them; framework calls send `deployed.control_headers`, `Task.run` runs every step under `protocol_v1.authorized` with each deployed env's (a `verify` included), and a `run_code` script inside the computer gets `input["env"]["headers"]`. `teardown_run` and the `teardown_sandboxes` step share one core (`task/teardown.py` `tear_down`): the recordings the run left open end with fresh grants, each env still up closes (`Env.close`; a computer env ends any recording still open), what stayed open is registered from its namespace, then every sandbox is terminated by id. A run whose teardown leaves sandboxes up, stopped by a second signal or failing, keeps on its instance the context it ended with (`record_teardown`), and `agent-env run` and `task run --keep` name `agent-env task teardown --instance `, which tears down what that context still records up, a running one only with `--force`. `task/episode/` runs a task with some of its agents played from outside, as a training loop does (`EpisodeSpec`). | | `store/` | Four store ABCs with local and cloud implementations: `DocumentStore` (SQLite, MongoDB, DynamoDB, Firestore with MongoDB compatibility), `ObjectStore` (filesystem, S3, Cloud Storage), `ImageStore` (local OCI registry, ECR), `SecretStore` (env vars or file, AWS Secrets Manager, Google Cloud Secret Manager). `VersionedEntityStore` implements the shared versioned get/put logic, `QueryBuilder` is the immutable chained query API, `store/base.py` holds the error types. `store/routing.py` is the local namespaces, `@local` and `@hf` (`is_local_id`), each with a documents file of its own: while the CLI or a `build_app` server runs, a local id and what a local task's run records go to local stores beside the configured ones, and that run's writes to the configured stores are refused. A new backend must pass the conformance kits in `tst/store/`. | | `config/` | The `Config` singleton (`get_config`, `configure`, `reset_config`) in `config/runtime.py`, file discovery in `config/loader.py`, and `load_impl`, which resolves `module:Class` pointers. `agent_env.store` re-exports the config names for compatibility. | -| `providers/` | `providers/sandbox_providers/` holds the sandbox providers `local`, `modal`, `modal_vm`, `e2b`, `sail_vm` (the `sail` extra), `smol_vm` (the `smol` extra), `tensorlake` (the `tensorlake` extra), `tenki` (the `tenki` extra), `vercel` (the `vercel` extra), `boxd` (the `boxd` extra), `coreweave` (the `coreweave` extra), `daytona` (the `daytona` extra), `boat` (the `boat` extra), `agent37` (no extra), `kosa8` (no extra); `[sandbox] default` and `agent_default` accept a comma-separated fallback chain, whose deploys skip a provider that can't run them. A sandbox provider declares what it runs (`ON_THIS_MACHINE`, and for VMs on this machine the address their requests to it arrive at, `REACHES_HOST_AT`; `CONTAINER_ACCEPTS`, `PRIVATE_NETWORK`, `WEBSOCKETS`; `SUPPORTED_SANDBOX_MODES`, derived from whether it implements `create_sandbox` and `create_vm`; and `SANDBOX_ACCEPTS`, the images an agent's sandbox runs, which defaults to those a VM loads when it implements `create_vm` and to `CONTAINER_ACCEPTS` otherwise, so only a provider that implements `create_vm` yet gives an agent a container, like the local one, declares it), each sandbox carries the `platform` of the images it runs (linux/amd64 unless its provider sets another when it creates it; None, any, unchecked, for a local sandbox), and code outside `providers/sandbox_providers/` reads those, never which provider it has. `providers/env_providers/` holds the environment providers: `EnvironmentProvider` (an env's containers and state store), `EnvironmentGatewayProvider` (`gateway`, an env's default), which renders a docker-compose for the gateway and its MCP servers inside the sandbox, and `EnvironmentServerProvider` (`server`), one MCP server in its own container with no gateway in front and no state store; `providers/env_state/` holds env-state providers (`local_postgres` built in). | +| `providers/` | `providers/sandbox_providers/` holds the sandbox providers `local`, `modal`, `modal_vm`, `e2b`, `sail_vm` (the `sail` extra), `smol_vm` (the `smol` extra), `tensorlake` (the `tensorlake` extra), `tenki` (the `tenki` extra), `vercel` (the `vercel` extra), `boxd` (the `boxd` extra), `coreweave` (the `coreweave` extra), `daytona` (the `daytona` extra), `boat` (the `boat` extra), `agent37` (no extra), `kosa8` (no extra), `mirage` (no extra); `[sandbox] default` and `agent_default` accept a comma-separated fallback chain, whose deploys skip a provider that can't run them. A sandbox provider declares what it runs (`ON_THIS_MACHINE`, and for VMs on this machine the address their requests to it arrive at, `REACHES_HOST_AT`; `CONTAINER_ACCEPTS`, `PRIVATE_NETWORK`, `WEBSOCKETS`; `SUPPORTED_SANDBOX_MODES`, derived from whether it implements `create_sandbox` and `create_vm`; and `SANDBOX_ACCEPTS`, the images an agent's sandbox runs, which defaults to those a VM loads when it implements `create_vm` and to `CONTAINER_ACCEPTS` otherwise, so only a provider that implements `create_vm` yet gives an agent a container, like the local one, declares it), each sandbox carries the `platform` of the images it runs (linux/amd64 unless its provider sets another when it creates it; None, any, unchecked, for a local sandbox), and code outside `providers/sandbox_providers/` reads those, never which provider it has. `providers/env_providers/` holds the environment providers: `EnvironmentProvider` (an env's containers and state store), `EnvironmentGatewayProvider` (`gateway`, an env's default), which renders a docker-compose for the gateway and its MCP servers inside the sandbox, and `EnvironmentServerProvider` (`server`), one MCP server in its own container with no gateway in front and no state store; `providers/env_state/` holds env-state providers (`local_postgres` built in). | | `a2a_agent/` | The `A2AAgent` entity (`a2a_agent`), its stores and the validator steps. The protocol package provides the agent-side framework. | | `openenv/` | `build_app(bundle)`: the [OpenEnv](https://github.com/openenv/OpenEnv) server for a bundle's tasks, each session playing one episode through the Episode API, with the envs' MCP tools, an added `end_turn` tool and the task's verifier score as the reward. It prepares bundles as `agent-env run` does (`prepare_bundle(played=True)`, without the agent the client plays) and keeps namespace routing on for the app's life. `openenv` comes with the `openenv` extra, a floor with no cap; this package and `training/` are the only ones that import it. Each task's description in the Task API names its `toolset` (the played agent's envs, role, and whether it gets `bash`). With `token`, every request and WebSocket but `/health` must carry `Authorization: Bearer `, for a server others reach. | | `training/` | One module per outside trainer, each behind its own extra, and the modules they share; [Training helpers](#training-helpers) lists them. | diff --git a/src/agent_env/cli/a2a_agent/deploy.py b/src/agent_env/cli/a2a_agent/deploy.py index 3ce956c66..94fcae404 100644 --- a/src/agent_env/cli/a2a_agent/deploy.py +++ b/src/agent_env/cli/a2a_agent/deploy.py @@ -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): diff --git a/src/agent_env/cli/env/deploy.py b/src/agent_env/cli/env/deploy.py index 708f05958..0ec9271ba 100644 --- a/src/agent_env/cli/env/deploy.py +++ b/src/agent_env/cli/env/deploy.py @@ -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, diff --git a/src/agent_env/providers/sandbox_providers/mirage/README.md b/src/agent_env/providers/sandbox_providers/mirage/README.md new file mode 100644 index 000000000..befdfdd3a --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/mirage/README.md @@ -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 ` 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`. diff --git a/src/agent_env/providers/sandbox_providers/mirage/__init__.py b/src/agent_env/providers/sandbox_providers/mirage/__init__.py new file mode 100644 index 000000000..f40968f42 --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/mirage/__init__.py @@ -0,0 +1 @@ +"""Mirage workspace sandbox provider (no extra: it drives a Mirage daemon's HTTP API with ``httpx``); see README.md.""" diff --git a/src/agent_env/providers/sandbox_providers/mirage/provider.py b/src/agent_env/providers/sandbox_providers/mirage/provider.py new file mode 100644 index 000000000..758d1ce7b --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/mirage/provider.py @@ -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) diff --git a/src/agent_env/providers/sandbox_providers/mirage/sandbox.py b/src/agent_env/providers/sandbox_providers/mirage/sandbox.py new file mode 100644 index 000000000..68a3c67cf --- /dev/null +++ b/src/agent_env/providers/sandbox_providers/mirage/sandbox.py @@ -0,0 +1,182 @@ +"""A Mirage workspace presented through the :class:`VmSandbox` contract. + +Every call goes to the Mirage daemon's HTTP API. Each command runs in a session of its own, as with ``docker exec``, +and the shell has no users, so agent-env's ``sudo`` prefix is dropped. +""" + +from __future__ import annotations + +import asyncio +import base64 +import contextlib +import io +import logging +import shlex +import weakref +from typing import IO, Any + +import httpx + +from agent_env.config import get_config +from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy, VmSandbox +from agent_env.providers.sandbox_providers.sandbox_provider import SANDBOX_MODE_VM, SandboxNotFoundError + +logger = logging.getLogger(__name__) + +# A file call's bytes go base64 in a JSON body, which the daemon caps at 4 MiB. +FILE_PIECE_BYTES = 2 * 1024 * 1024 + + +class MirageError(RuntimeError): + """A failed daemon call, with the code and, for a file call, the errno of Mirage's ``{"error": {...}}`` body.""" + + def __init__(self, response: httpx.Response): + try: + error = dict(response.json()["error"]) + except (ValueError, KeyError, TypeError): + error = {} + self.status_code = response.status_code + self.code = error.get("code", "unknown") + self.errno = error.get("errno") + super().__init__(f"Mirage {response.request.method} {response.request.url.path} answered " + f"{response.status_code} {self.code}: {error.get('message', response.text[:500])}") + + +class MirageApi: + """The daemon calls, the same on the Python and the TypeScript daemon; the token is sent only to ``url``.""" + + def __init__(self, url: str, *, token: str | None = None, transport: httpx.AsyncBaseTransport | None = None): + self.url = url.rstrip("/") + self._token = token + self._transport = transport + # One client per event loop: a client's connections belong to the loop that opened them, and the CLI runs + # several loops in one process. + self._clients: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, httpx.AsyncClient] = ( + weakref.WeakKeyDictionary()) + + def _client(self) -> httpx.AsyncClient: + loop = asyncio.get_running_loop() + client = self._clients.get(loop) + if client is None: + headers = {"User-Agent": "agentenv-framework"} + if self._token: + headers["Authorization"] = f"Bearer {self._token}" + client = self._clients[loop] = httpx.AsyncClient(base_url=self.url, transport=self._transport, + timeout=60.0, headers=headers) + return client + + async def close(self) -> None: + client = self._clients.pop(asyncio.get_running_loop(), None) + if client is not None: + await client.aclose() + + async def _call(self, method: str, path: str, **kwargs: Any) -> httpx.Response: + response = await self._client().request(method, path, **kwargs) + if response.status_code >= 400: + raise MirageError(response) + return response + + async def _workspace_call(self, workspace_id: str, method: str, route: str = "", **kwargs: Any) -> httpx.Response: + try: + return await self._call(method, f"/v1/workspaces/{workspace_id}{route}", **kwargs) + except MirageError as exc: + # A missing workspace is not_found with no errno; a file call's not_found carries ENOENT. + if exc.code == "not_found" and exc.errno is None: + raise SandboxNotFoundError(f"Mirage workspace {workspace_id!r} was not found") from exc + raise + + async def create_workspace(self, workspace_id: str, config: dict[str, Any]) -> None: + await self._call("POST", "/v1/workspaces", json={"id": workspace_id, "config": config}) + + async def get_workspace(self, workspace_id: str) -> None: + await self._workspace_call(workspace_id, "GET") + + async def delete_workspace(self, workspace_id: str) -> None: + """Delete a workspace; one that is already gone is not an error.""" + try: + await self._workspace_call(workspace_id, "DELETE") + except SandboxNotFoundError: + logger.info("Mirage workspace %s was already gone at terminate", workspace_id) + + async def shell(self, workspace_id: str, line: str) -> tuple[int, bytes, bytes]: + """Run ``line`` from ``/`` in a session of its own. One whose answer is lost is exit -1: the daemon cancels a + line whose caller is gone, so nothing of it runs on.""" + try: + # A line's answer comes when the line ends, so only this call has no read timeout. + response = await self._workspace_call(workspace_id, "POST", "/shell", json={"command": line, "cwd": "/"}, + timeout=httpx.Timeout(60.0, read=None)) + except httpx.TransportError as exc: + return -1, b"", f"{type(exc).__name__}: {exc}".encode() + result = response.json() + return result["exit_code"], result["stdout"].encode(), result["stderr"].encode() + + async def write(self, workspace_id: str, path: str, data: bytes, *, append: bool = False) -> None: + await self._workspace_call(workspace_id, "POST", "/vfs/append" if append else "/vfs/write", + json={"path": path, "data": base64.b64encode(data).decode()}) + + +class _BytesReader: + """The small ``StreamReader`` subset consumed by ``Sandbox.exec_with_output``.""" + + def __init__(self, value: bytes): + self._value = value + + async def read(self) -> bytes: + return self._value + + +class _CompletedProcess: + """A finished line in the common process protocol.""" + + def __init__(self, stdout: bytes, stderr: bytes, exit_code: int): + self.stdout = _BytesReader(stdout) + self.stderr = _BytesReader(stderr) + self._exit_code = exit_code + + async def wait(self) -> int: + return self._exit_code + + +class MirageSandbox(VmSandbox): + """A workspace on a Mirage daemon.""" + + type = "mirage" + + def __init__(self, api: MirageApi, workspace_id: str, *, network_policy: NetworkPolicy | None): + self._api = api + self.sandbox_id = workspace_id + self.mode = SANDBOX_MODE_VM + self.vnc_url = None + self.tunnel_urls = {} + self.network_policy = network_policy + + async def terminate(self) -> None: + await self._api.delete_workspace(self.sandbox_id) + + async def exec(self, *command: str) -> _CompletedProcess: + """Run argv as a line of the workspace's shell. A ``bash -c`` runs its script as the line itself.""" + argv = list(command[1:] if command[:1] == ("sudo",) else command) + line = argv[2] if len(argv) == 3 and argv[:2] == ["bash", "-c"] else shlex.join(argv) + exit_code, stdout, stderr = await self._api.shell(self.sandbox_id, line) + return _CompletedProcess(stdout, stderr, exit_code) + + async def wait_for_vm(self) -> None: + """A workspace answers once the daemon has made it.""" + await self._api.get_workspace(self.sandbox_id) + + async def _download_object_to_vm(self, object_url: str, vm_path: str) -> None: + """Read the object here and write it through the daemon's file calls, which need no egress from the + workspace.""" + object_store = get_config().get_object_store_at(object_url) + with contextlib.closing(await asyncio.to_thread(object_store.open, object_url)) as source: + await self._upload(source, vm_path) + + async def _write_bytes_to_vm_path(self, data: bytes, vm_path: str) -> None: + await self._upload(io.BytesIO(data), vm_path) + + async def _upload(self, source: IO[bytes], vm_path: str) -> None: + """Write ``source`` to ``vm_path`` a piece per call: the first replaces the file, the rest append to it.""" + piece = await asyncio.to_thread(source.read, FILE_PIECE_BYTES) + await self._api.write(self.sandbox_id, vm_path, piece) + while piece := await asyncio.to_thread(source.read, FILE_PIECE_BYTES): + await self._api.write(self.sandbox_id, vm_path, piece, append=True) diff --git a/src/agent_env/providers/sandbox_providers/sandbox_provider.py b/src/agent_env/providers/sandbox_providers/sandbox_provider.py index 0d314371c..48f04871f 100644 --- a/src/agent_env/providers/sandbox_providers/sandbox_provider.py +++ b/src/agent_env/providers/sandbox_providers/sandbox_provider.py @@ -384,6 +384,7 @@ def effective_network_policy(cls, policy: Optional[NetworkPolicy]) -> NetworkPol "coreweave": "agent_env.providers.sandbox_providers.coreweave.provider:CoreWeaveSandboxProvider", "agent37": "agent_env.providers.sandbox_providers.agent37.provider:Agent37SandboxProvider", "kosa8": "agent_env.providers.sandbox_providers.kosa8.provider:Kosa8SandboxProvider", + "mirage": "agent_env.providers.sandbox_providers.mirage.provider:MirageSandboxProvider", "local": "agent_env.providers.sandbox_providers.local_docker.provider:LocalSandboxProvider", "lume": "agent_env.providers.sandbox_providers.lume.provider:LumeSandboxProvider", } diff --git a/tst/integration/providers/sandbox_providers/mirage_sandbox_smoke_test.py b/tst/integration/providers/sandbox_providers/mirage_sandbox_smoke_test.py new file mode 100644 index 000000000..dedbf59f3 --- /dev/null +++ b/tst/integration/providers/sandbox_providers/mirage_sandbox_smoke_test.py @@ -0,0 +1,90 @@ +"""Mirage workspace sandbox smoke test. + +Runs when a Mirage daemon answers at the ``mirage`` provider's ``url`` (``[sandbox.providers.mirage.config]``, or +``http://127.0.0.1:8765``), the ``remote_sandbox`` capability, and skips with the declared reason otherwise. Start one +as the provider's README says, with ``python -m pip install mirage-ai`` in a venv of its own. +""" + +from __future__ import annotations + +import asyncio +import hashlib +import os + +import pytest +import pytest_asyncio + +from agent_env.providers.sandbox_providers.sandbox import NetworkMode, NetworkPolicy, read_vm_file +from agent_env.providers.sandbox_providers.sandbox_provider import SandboxNotFoundError, build_sandbox_provider +from tst.util.capabilities import skip_without_remote_sandbox + +pytestmark = [ + pytest.mark.integration, + pytest.mark.int_test_slow, + pytest.mark.asyncio, + skip_without_remote_sandbox("mirage"), +] + + +@pytest.fixture(scope="module") +def mirage_provider(): + return build_sandbox_provider("mirage") + + +@pytest_asyncio.fixture(scope="module") +async def mirage_sandbox(mirage_provider): + """One workspace, always deleted after the module.""" + sandbox = await mirage_provider.create_vm(memory=512) + try: + yield sandbox + finally: + await sandbox.terminate() + + +async def test_mirage_sandbox_commands_files_and_reconnect(mirage_provider, mirage_sandbox, tmp_path): + """Lines as a VM runs them, a file in and out larger than one file call, output no cap cuts, and reconnect.""" + assert (mirage_sandbox.type, mirage_sandbox.mode, mirage_sandbox.tunnel_urls) == ("mirage", "vm", {}) + + assert await mirage_sandbox.exec_with_output("sudo", "bash", "-c", "cd /tmp && pwd; exit 3") == (3, "/tmp\n", "") + assert (await mirage_sandbox.exec_script("pwd")).strip() == "/" + + payload = os.urandom(5 * 1024 * 1024 + 17) + await mirage_sandbox.write_host_file(payload, "/opt/smoke/payload.bin") + digest = await mirage_sandbox.exec_script("sha256sum /opt/smoke/payload.bin") + assert digest.split()[0] == hashlib.sha256(payload).hexdigest() + await read_vm_file(mirage_sandbox, "/opt/smoke/payload.bin", str(tmp_path / "payload.bin")) + assert (tmp_path / "payload.bin").read_bytes() == payload + + await mirage_sandbox.exec_script("seq 5000 > /opt/smoke/lines") + assert len((await mirage_sandbox.exec_script("cat /opt/smoke/lines")).splitlines()) == 5000 + long_script = "printf '%s' " + "y" * 20000 + " | wc -c" + assert (await mirage_sandbox.exec_script(long_script)).strip() == "20000" + + reconnected = await build_sandbox_provider("mirage").get_sandbox(mirage_sandbox.sandbox_id) + assert (reconnected.sandbox_id, reconnected.tunnel_urls) == (mirage_sandbox.sandbox_id, {}) + assert (await reconnected.exec_script("cat /opt/smoke/lines | wc -l")).strip() == "5000" + + +async def test_mirage_concurrent_lines_each_get_their_own_answer(mirage_sandbox): + results = await asyncio.wait_for( + asyncio.gather(*(mirage_sandbox.exec_with_output("bash", "-c", f"cd /tmp; echo {i}") for i in range(6))), 60, + ) + assert [(code, out.strip()) for code, out, _ in results] == [(0, str(i)) for i in range(6)] + + +async def test_mirage_allowlisted_sandbox_reaches_its_hosts_and_nothing_else(mirage_provider): + """An allowlisted workspace reaches an allowed host and nothing else; terminate twice, then it is gone.""" + policy = NetworkPolicy(mode=NetworkMode.ALLOWLIST, allow_hosts=("example.com",)) + sandbox = await mirage_provider.create_vm(network_policy=policy) + try: + async def fetch(url: str) -> int: + return (await sandbox.exec_with_output("curl", "-fsS", "-o", "/dev/null", "--max-time", "15", url))[0] + + assert await fetch("https://example.com") == 0 + assert await fetch("https://www.wikipedia.org") != 0 + assert sandbox.network_policy.restricts_egress + finally: + await sandbox.terminate() + await sandbox.terminate() + with pytest.raises(SandboxNotFoundError): + await mirage_provider.get_sandbox(sandbox.sandbox_id) diff --git a/tst/integration/slow_durations.json b/tst/integration/slow_durations.json index 544da20cf..3281e2c4f 100644 --- a/tst/integration/slow_durations.json +++ b/tst/integration/slow_durations.json @@ -1202,6 +1202,7 @@ "tst/integration/providers/sandbox_providers/daytona_sandbox_smoke_test.py": 0.0, "tst/integration/providers/sandbox_providers/e2b_sandbox_smoke_test.py": 0.0, "tst/integration/providers/sandbox_providers/kosa8_sandbox_smoke_test.py": 0.0, + "tst/integration/providers/sandbox_providers/mirage_sandbox_smoke_test.py": 0.0, "tst/integration/providers/sandbox_providers/sail_vm_sandbox_smoke_test.py": 0.0, "tst/integration/providers/sandbox_providers/tenki_sandbox_smoke_test.py": 0.0, "tst/integration/providers/sandbox_providers/tensorlake_sandbox_smoke_test.py": 0.0, @@ -1575,6 +1576,8 @@ "tst/unit/providers/sandbox_providers/local_sandbox_host_ports_test.py": 0.4, "tst/unit/providers/sandbox_providers/local_sandbox_test.py": 12.9, "tst/unit/providers/sandbox_providers/lume_sandbox_provider_test.py": 12.9, + "tst/unit/providers/sandbox_providers/mirage_sandbox_provider_test.py": 0.3, + "tst/unit/providers/sandbox_providers/mirage_sandbox_test.py": 0.2, "tst/unit/providers/sandbox_providers/modal_context_build_test.py": 0.8, "tst/unit/providers/sandbox_providers/modal_create_signature_test.py": 0.2, "tst/unit/providers/sandbox_providers/modal_gpu_sandbox_test.py": 0.1, diff --git a/tst/unit/providers/sandbox_providers/mirage_fakes.py b/tst/unit/providers/sandbox_providers/mirage_fakes.py new file mode 100644 index 000000000..8ad96b7c7 --- /dev/null +++ b/tst/unit/providers/sandbox_providers/mirage_fakes.py @@ -0,0 +1,94 @@ +"""An in-memory Mirage daemon behind an ``httpx.MockTransport``, for the offline provider and sandbox tests.""" + +from __future__ import annotations + +import base64 +import json +from typing import Any + +import httpx + +from agent_env.providers.sandbox_providers.mirage.sandbox import FILE_PIECE_BYTES + +URL = "http://127.0.0.1:8765" +TOKEN = "mirage-test-token" + +ShellAnswer = httpx.Response | Exception | dict[str, Any] + + +def error(status: int, code: str, errno: str | None = None) -> httpx.Response: + return httpx.Response(status, json={"error": {"code": code, "message": code, **({"errno": errno} if errno else {})}}) + + +class FakeMirage: + """Workspaces, their files and their lines on a daemon at ``URL``. Each line answers with the next of + ``shell_answers`` (a result dict, a response, or an exception to raise), else exit 0. A set ``create_answer`` + refuses a create (a response) or is raised after the workspace is made (an exception).""" + + def __init__(self, token: str | None = None) -> None: + self.token = token + self.workspaces: dict[str, dict[str, Any]] = {} + self.files: dict[tuple[str, str], bytes] = {} + self.file_calls: list[tuple[str, str, int]] = [] + self.lines: list[tuple[str, str, str]] = [] + self.deleted: list[str] = [] + self.requests: list[httpx.Request] = [] + self.shell_answers: list[ShellAnswer] = [] + self.create_answer: httpx.Response | Exception | None = None + self.write_answer: httpx.Response | None = None + + def transport(self) -> httpx.MockTransport: + return httpx.MockTransport(self._handle) + + def _handle(self, request: httpx.Request) -> httpx.Response: + self.requests.append(request) + assert f"{request.url.scheme}://{request.url.netloc.decode()}" == URL + expected = f"Bearer {self.token}" if self.token else None + assert request.headers.get("Authorization") == expected + parts = request.url.path.strip("/").split("/") + if parts == ["v1", "workspaces"] and request.method == "POST": + return self._create(json.loads(request.content)) + workspace_id = parts[2] + if workspace_id not in self.workspaces: + return error(404, "not_found") + route = parts[3:] + if not route and request.method == "DELETE": + del self.workspaces[workspace_id] + self.deleted.append(workspace_id) + return httpx.Response(204) + if not route: + return httpx.Response(200, json={"id": workspace_id}) + if route == ["shell"]: + return self._shell(workspace_id, json.loads(request.content)) + if route in (["vfs", "write"], ["vfs", "append"]): + return self._write(workspace_id, route[1], json.loads(request.content)) + return error(404, "not_found") + + def _create(self, body: dict[str, Any]) -> httpx.Response: + if isinstance(self.create_answer, httpx.Response): + return self.create_answer + if body["id"] in self.workspaces: + return error(409, "conflict") + self.workspaces[body["id"]] = body["config"] + if self.create_answer is not None: + raise self.create_answer + return httpx.Response(201, json={"id": body["id"]}) + + def _shell(self, workspace_id: str, body: dict[str, Any]) -> httpx.Response: + self.lines.append((workspace_id, body["command"], body["cwd"])) + answer = self.shell_answers.pop(0) if self.shell_answers else {} + if isinstance(answer, Exception): + raise answer + if isinstance(answer, httpx.Response): + return answer + return httpx.Response(200, json={"exit_code": 0, "stdout": "", "stderr": "", **answer}) + + def _write(self, workspace_id: str, call: str, body: dict[str, Any]) -> httpx.Response: + if self.write_answer is not None: + return self.write_answer + data = base64.b64decode(body["data"]) + assert len(data) <= FILE_PIECE_BYTES + self.file_calls.append((call, body["path"], len(data))) + key = (workspace_id, body["path"]) + self.files[key] = (self.files.get(key, b"") if call == "append" else b"") + data + return httpx.Response(200, json={}) diff --git a/tst/unit/providers/sandbox_providers/mirage_sandbox_provider_test.py b/tst/unit/providers/sandbox_providers/mirage_sandbox_provider_test.py new file mode 100644 index 000000000..539ab64a6 --- /dev/null +++ b/tst/unit/providers/sandbox_providers/mirage_sandbox_provider_test.py @@ -0,0 +1,246 @@ +"""Offline unit tests for the Mirage workspace sandbox provider.""" + +from __future__ import annotations + +import asyncio +import logging + +import httpx +import pytest + +from agent_env.config.errors import ConfigError +from agent_env.providers.sandbox_providers.mirage.provider import ( + NAME_SUFFIX_LENGTH, + MirageSandboxProvider, + network_setting, + workspace_id, +) +from agent_env.providers.sandbox_providers.mirage.sandbox import MirageError +from agent_env.providers.sandbox_providers.sandbox import NetworkMode, NetworkPolicy +from agent_env.providers.sandbox_providers.sandbox_provider import SandboxNotFoundError +from tst.unit.providers.sandbox_providers.mirage_fakes import TOKEN, URL, FakeMirage, error + +ALLOWLIST = NetworkMode.ALLOWLIST +RAM_ROOT = {"vfs": "ram", "mode": "exec"} +NO_CAPS = {"@all": {"max_lines": None, "max_bytes": None}, "@line": {"timeout_seconds": None}} + + +@pytest.fixture +def api(): + return FakeMirage() + + +def _provider(api: FakeMirage, **kwargs) -> MirageSandboxProvider: + return MirageSandboxProvider(url=URL, transport=api.transport(), **kwargs) + + +def test_workspace_ids_are_unique_and_carry_no_attribution(): + name = workspace_id() + assert name.startswith("agentenv-") and len(name) == len("agentenv-") + NAME_SUFFIX_LENGTH + assert workspace_id() != name + + +def test_network_setting_is_anywhere_nowhere_or_what_the_policy_allows(): + assert network_setting(NetworkPolicy()) is True + assert network_setting(NetworkPolicy(mode=ALLOWLIST)) is False + policy = NetworkPolicy(mode=ALLOWLIST, allow_hosts=("pypi.org", "*.npmjs.org"), allow_cidrs=("10.0.0.0/8",)) + assert network_setting(policy) == {"allowed_domains": ["pypi.org", "*.npmjs.org", "10.0.0.0/8"]} + + +@pytest.mark.parametrize("policy", [ + NetworkPolicy(), + NetworkPolicy(mode=ALLOWLIST), + NetworkPolicy(mode=ALLOWLIST, allow_hosts=("pypi.org", "*.npmjs.org", "203.0.113.7", "api.example.com:443"), + allow_cidrs=("10.0.0.0/8", "2001:db8::/32")), +]) +def test_supports_every_policy(policy): + assert MirageSandboxProvider.supports_network_policy(policy) + + +def test_from_config_takes_the_known_keys(): + workspace = {"mounts": {"/data": {"vfs": "s3", "config": {"bucket": "b"}}}, "env": {"A": "1"}} + provider = MirageSandboxProvider.from_config(url="http://mirage.internal:9000/", token="t", workspace=workspace) + assert (provider._api.url, provider._api._token) == ("http://mirage.internal:9000", "t") + assert provider._workspace == {"command_limits": NO_CAPS, "mounts": {"/": RAM_ROOT, **workspace["mounts"]}, + "env": {"A": "1"}} + assert MirageSandboxProvider.from_config()._api.url == URL + + +@pytest.mark.parametrize(("config", "message"), [ + ({"api_key": "k"}, "unknown key"), + ({"url": " "}, "non-empty string"), + ({"token": 3}, "non-empty string"), + ({"workspace": "mirage.yaml"}, "must be a table"), + ({"workspace": {"network": False}}, r"sets \['network'\]"), + ({"workspace": {"max_memory": "1GB", "workspace_id": "w"}}, r"sets \['max_memory', 'workspace_id'\]"), + ({"workspace": {"mounts": ["/data"]}}, "table of mounts"), +]) +def test_from_config_refuses_bad_config(config, message): + with pytest.raises(ConfigError, match=message): + MirageSandboxProvider.from_config(**config) + + +@pytest.mark.asyncio +async def test_create_vm_makes_a_workspace_with_a_ram_root_a_staging_dir_and_the_requested_memory(api): + sandbox = await _provider(api).create_vm(memory=1024) + + assert sandbox.sandbox_id.startswith("agentenv-") + assert api.workspaces[sandbox.sandbox_id] == { + "command_limits": NO_CAPS, + "mounts": {"/": RAM_ROOT}, + "network": True, + "max_memory": 1024 * 1024 * 1024, + } + assert api.lines == [(sandbox.sandbox_id, "mkdir -p /tmp", "/")] + assert (sandbox.type, sandbox.mode, sandbox.tunnel_urls, sandbox.vnc_url) == ("mirage", "vm", {}, None) + assert sandbox.network_policy == NetworkPolicy() + + +@pytest.mark.asyncio +async def test_create_vm_holds_the_workspace_to_the_allowlist_from_its_first_line(api): + policy = NetworkPolicy(mode=ALLOWLIST, allow_hosts=("pypi.org",), allow_cidrs=("10.0.0.0/8",)) + provider = _provider(api) + + sandbox = await provider.create_vm(network_policy=policy) + + effective = provider.effective_network_policy(policy) + assert sandbox.network_policy == effective + assert api.workspaces[sandbox.sandbox_id]["network"] == { + "allowed_domains": [*effective.allow_hosts, *effective.allow_cidrs]} + assert effective.allow_hosts[0] == "pypi.org" and "10.0.0.0/8" in effective.allow_cidrs + + +@pytest.mark.asyncio +async def test_create_vm_adds_the_configured_workspaces_mounts_and_settings(api): + s3 = {"vfs": "s3", "mode": "read", "config": {"bucket": "data", "access_key_id": "resolved"}} + limits = {"grep": {"max_lines": 50}} + sandbox = await _provider(api, workspace={"mounts": {"/data": s3}, "env": {"TZ": "UTC"}, + "command_limits": limits}).create_vm() + + config = api.workspaces[sandbox.sandbox_id] + assert config["mounts"] == {"/": RAM_ROOT, "/data": s3} + assert (config["env"], config["command_limits"]) == ({"TZ": "UTC"}, limits) + + +@pytest.mark.asyncio +async def test_a_configured_root_mount_replaces_the_ram_root(api): + disk = {"vfs": "disk", "mode": "write", "config": {"root": "/srv/sandboxes"}} + sandbox = await _provider(api, workspace={"mounts": {"/": disk}}).create_vm() + assert api.workspaces[sandbox.sandbox_id]["mounts"] == {"/": disk} + + +@pytest.mark.asyncio +@pytest.mark.parametrize(("kwargs", "message"), [ + ({"image": "ubuntu:24.04"}, "boots no image"), + ({"exposed_ports": [8080]}, r"serves no ports, so it can't expose \[8080\]"), +]) +async def test_create_vm_refuses_an_image_or_ports_before_anything_is_made(api, kwargs, message): + with pytest.raises(ValueError, match=message): + await _provider(api).create_vm(**kwargs) + assert api.requests == [] + + +@pytest.mark.asyncio +async def test_create_vm_ignores_boot_mode_and_env_with_a_warning(api, caplog): + with caplog.at_level(logging.WARNING): + await _provider(api).create_vm(boot_mode="uefi", env={"A": "1"}) + assert "Ignoring boot_mode=uefi" in caplog.text and "Ignoring env" in caplog.text + + +@pytest.mark.asyncio +async def test_a_create_whose_setup_fails_deletes_its_workspace(api): + api.shell_answers = [{"exit_code": 1, "stderr": "mkdir: /tmp: Disk quota exceeded"}] + with pytest.raises(RuntimeError, match="Disk quota exceeded"): + await _provider(api).create_vm() + assert api.workspaces == {} and len(api.deleted) == 1 + + +@pytest.mark.asyncio +async def test_a_create_the_daemon_refuses_raises_its_error_and_deletes_nothing(api): + api.create_answer = error(400, "invalid_value") + with pytest.raises(MirageError, match="400 invalid_value") as raised: + await _provider(api).create_vm() + assert (raised.value.status_code, raised.value.code) == (400, "invalid_value") + assert [request.method for request in api.requests] == ["POST"] + + +@pytest.mark.asyncio +async def test_a_create_whose_answer_is_lost_deletes_the_workspace_it_made(api): + api.create_answer = httpx.ReadError("connection lost") + with pytest.raises(httpx.ReadError): + await _provider(api).create_vm() + assert api.workspaces == {} and len(api.deleted) == 1 + + +@pytest.mark.asyncio +async def test_a_create_cancelled_while_the_daemon_answers_deletes_the_workspace_it_made(api): + arrived, never = asyncio.Event(), asyncio.Event() + + async def slow_create(request: httpx.Request) -> httpx.Response: + response = api._handle(request) + if request.method == "POST" and request.url.path == "/v1/workspaces": + arrived.set() + await never.wait() + return response + + create = asyncio.create_task(MirageSandboxProvider(url=URL, transport=httpx.MockTransport(slow_create)).create_vm()) + await arrived.wait() + create.cancel() + with pytest.raises(asyncio.CancelledError): + await create + assert api.workspaces == {} and len(api.deleted) == 1 + + +@pytest.mark.asyncio +async def test_a_daemon_that_doesnt_answer_deletes_nothing(): + methods = [] + + def refuse(request: httpx.Request) -> httpx.Response: + methods.append(request.method) + raise httpx.ConnectError("connection refused", request=request) + + provider = MirageSandboxProvider(url=URL, transport=httpx.MockTransport(refuse)) + with pytest.raises(httpx.ConnectError): + await provider.create_vm() + assert methods == ["POST"] + + +@pytest.mark.asyncio +async def test_get_sandbox_reconnects_from_a_fresh_provider(api): + created = await _provider(api).create_vm() + api.shell_answers = [{"stdout": "hi\n"}] + + reconnected = await _provider(api).get_sandbox(created.sandbox_id) + + assert (reconnected.sandbox_id, reconnected.network_policy) == (created.sandbox_id, None) + assert await reconnected.exec_with_output("echo", "hi") == (0, "hi\n", "") + + +@pytest.mark.asyncio +async def test_a_gone_workspace_is_not_found_and_terminating_it_is_not_an_error(api): + provider = _provider(api) + sandbox = await provider.create_vm() + + await sandbox.terminate() + await sandbox.terminate() + await provider.terminate_sandbox(sandbox.sandbox_id) + + assert api.deleted == [sandbox.sandbox_id] + with pytest.raises(SandboxNotFoundError): + await provider.get_sandbox(sandbox.sandbox_id) + + +@pytest.mark.asyncio +async def test_a_container_is_refused_before_anything_is_made(api): + with pytest.raises(ValueError, match=r"serves no ports, so it can't expose \[8080\]"): + await _provider(api).create_container(image_name="ghcr.io/acme/agent:1", port=8080, env={}) + assert api.requests == [] + + +@pytest.mark.asyncio +async def test_the_token_goes_to_the_daemon_on_every_call(): + api = FakeMirage(token=TOKEN) + provider = _provider(api, token=TOKEN) + sandbox = await provider.create_vm() + await sandbox.terminate() + assert {request.headers["Authorization"] for request in api.requests} == {f"Bearer {TOKEN}"} diff --git a/tst/unit/providers/sandbox_providers/mirage_sandbox_test.py b/tst/unit/providers/sandbox_providers/mirage_sandbox_test.py new file mode 100644 index 000000000..c97b3ffae --- /dev/null +++ b/tst/unit/providers/sandbox_providers/mirage_sandbox_test.py @@ -0,0 +1,145 @@ +"""Offline unit tests for the Mirage workspace sandbox: lines, file writes and what it refuses.""" + +from __future__ import annotations + +import io +import os +from types import SimpleNamespace + +import httpx +import pytest + +from agent_env.providers.sandbox_providers.mirage import sandbox as sandbox_module +from agent_env.providers.sandbox_providers.mirage.sandbox import ( + FILE_PIECE_BYTES, + MirageApi, + MirageSandbox, +) +from agent_env.providers.sandbox_providers.sandbox import NetworkPolicy +from agent_env.providers.sandbox_providers.sandbox_provider import SandboxNotFoundError +from tst.unit.providers.sandbox_providers.mirage_fakes import URL, FakeMirage, error + +WORKSPACE = "agentenv-0123456789abcdef" + + +@pytest.fixture +def api(): + fake = FakeMirage() + fake.workspaces[WORKSPACE] = {} + return fake + + +def _sandbox(api: FakeMirage) -> MirageSandbox: + return MirageSandbox(MirageApi(URL, transport=api.transport()), WORKSPACE, network_policy=NetworkPolicy()) + + +def _lines(api: FakeMirage) -> list[str]: + return [line for _, line, _ in api.lines] + + +@pytest.mark.asyncio +async def test_exec_runs_argv_as_a_line_from_root_without_sudo(api): + api.shell_answers = [{"stdout": "hi there\n"}] + assert await _sandbox(api).exec_with_output("sudo", "echo", "hi there") == (0, "hi there\n", "") + assert api.lines == [(WORKSPACE, "echo 'hi there'", "/")] + + +@pytest.mark.asyncio +async def test_bash_c_runs_its_script_as_the_line(api): + sandbox = _sandbox(api) + await sandbox.exec_script("cd /app && (bash check.sh\n)") + await sandbox.exec("bash", "-c", 'echo "$0"', "zero") + await sandbox.exec("echo", "sudo") + assert _lines(api) == ["cd /app && (bash check.sh\n)", "bash -c 'echo \"$0\"' zero", "echo sudo"] + + +@pytest.mark.asyncio +async def test_exec_keeps_the_lines_exit_code_and_streams_apart(api): + api.shell_answers = [{"exit_code": 3, "stdout": "out\n", "stderr": "err\n"}] + assert await _sandbox(api).exec_with_output("bash", "-c", "exit 3") == (3, "out\n", "err\n") + + +@pytest.mark.asyncio +async def test_only_a_line_waits_for_its_answer_with_no_read_timeout(api): + timeouts = [] + handle = api._handle + + def record(request: httpx.Request) -> httpx.Response: + timeouts.append((request.url.path.rsplit("/", 1)[-1], request.extensions["timeout"]["read"])) + return handle(request) + + sandbox = MirageSandbox(MirageApi(URL, transport=httpx.MockTransport(record)), WORKSPACE, network_policy=None) + await sandbox.exec("true") + await sandbox.terminate() + assert timeouts == [("shell", None), (WORKSPACE, 60.0)] + + +@pytest.mark.asyncio +async def test_a_lost_answer_is_exit_minus_one(api): + api.shell_answers = [httpx.RemoteProtocolError("closed"), httpx.ConnectError("refused")] + sandbox = _sandbox(api) + + code, stdout, stderr = await sandbox.exec_with_output("true") + assert (code, stdout) == (-1, "") and "RemoteProtocolError: closed" in stderr + with pytest.raises(RuntimeError, match=r"exit -1"): + await sandbox.exec_script("true") + + +@pytest.mark.asyncio +async def test_a_line_in_a_gone_workspace_is_not_found(api): + del api.workspaces[WORKSPACE] + with pytest.raises(SandboxNotFoundError): + await _sandbox(api).exec("true") + + +@pytest.mark.asyncio +async def test_a_file_call_into_a_missing_folder_is_its_errno_not_a_gone_workspace(api): + api.write_answer = error(404, "not_found", errno="ENOENT") + with pytest.raises(sandbox_module.MirageError, match="404 not_found") as raised: + await _sandbox(api)._write_bytes_to_vm_path(b"x", "/no/such/dir/f") + assert raised.value.errno == "ENOENT" + + +@pytest.mark.asyncio +async def test_a_line_the_daemon_refuses_raises_its_error(api): + api.shell_answers = [error(429, "rate_limited")] + with pytest.raises(sandbox_module.MirageError, match="429 rate_limited"): + await _sandbox(api).exec("true") + + +@pytest.mark.asyncio +async def test_load_object_file_writes_the_object_through_file_calls_a_piece_at_a_time(api, monkeypatch): + payload = os.urandom(2 * FILE_PIECE_BYTES + 17) + store = SimpleNamespace(open=lambda url: io.BytesIO(payload) if url == "s3://bucket/blob" else None) + monkeypatch.setattr(sandbox_module, "get_config", lambda: SimpleNamespace(get_object_store_at=lambda url: store)) + + await _sandbox(api).load_object_file("s3://bucket/blob", "/app/blob.bin") + + assert api.files[(WORKSPACE, "/app/blob.bin")] == payload + assert api.file_calls == [("write", "/app/blob.bin", FILE_PIECE_BYTES), ("append", "/app/blob.bin", FILE_PIECE_BYTES), + ("append", "/app/blob.bin", 17)] + assert api.lines == [] + + +@pytest.mark.asyncio +async def test_an_empty_object_is_an_empty_file(api, monkeypatch): + store = SimpleNamespace(open=lambda url: io.BytesIO(b"")) + monkeypatch.setattr(sandbox_module, "get_config", lambda: SimpleNamespace(get_object_store_at=lambda url: store)) + await _sandbox(api).load_object_file("s3://bucket/empty", "/app/empty") + assert api.files[(WORKSPACE, "/app/empty")] == b"" + + +@pytest.mark.asyncio +async def test_a_secret_reaches_its_file_through_file_calls_never_a_line(api): + await _sandbox(api).write_secret_file(b"hunter2", "/run/secrets/password") + assert api.files[(WORKSPACE, "/run/secrets/password")] == b"hunter2" + assert _lines(api) == ["mkdir -p /run/secrets"] + + +@pytest.mark.asyncio +async def test_a_workspace_is_ready_once_the_daemon_has_it(api): + sandbox = _sandbox(api) + await sandbox.setup_vm_for_gateway([]) + del api.workspaces[WORKSPACE] + with pytest.raises(SandboxNotFoundError): + await sandbox.wait_for_vm() diff --git a/tst/unit/providers/sandbox_providers/network_policy_stamping_test.py b/tst/unit/providers/sandbox_providers/network_policy_stamping_test.py index 224e19d82..d761935e0 100644 --- a/tst/unit/providers/sandbox_providers/network_policy_stamping_test.py +++ b/tst/unit/providers/sandbox_providers/network_policy_stamping_test.py @@ -23,6 +23,7 @@ from agent_env.providers.sandbox_providers.kosa8.provider import Kosa8SandboxProvider from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandboxProvider from agent_env.providers.sandbox_providers.lume.provider import LumeSandboxProvider +from agent_env.providers.sandbox_providers.mirage.provider import MirageSandboxProvider from agent_env.providers.sandbox_providers.modal_sandbox import ModalSandboxProvider from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandboxProvider from agent_env.providers.sandbox_providers.sail_vm import _sdk as sail_sdk @@ -33,6 +34,8 @@ from agent_env.providers.sandbox_providers.tensorlake.provider import TensorlakeSandboxProvider from agent_env.providers.sandbox_providers.vercel.provider import VercelSandboxProvider from tst.unit.providers.sandbox_providers.coreweave_fakes import fake_sandbox_cls +from tst.unit.providers.sandbox_providers.mirage_fakes import URL as MIRAGE_URL +from tst.unit.providers.sandbox_providers.mirage_fakes import FakeMirage def _modal_provider(cls): @@ -171,6 +174,11 @@ async def _kosa8() -> Sandbox: return await provider.create_vm(exposed_ports=[], setup_for_gateway=False) +async def _mirage() -> Sandbox: + provider = MirageSandboxProvider(url=MIRAGE_URL, transport=FakeMirage().transport()) + return await provider.create_vm(exposed_ports=[], setup_for_gateway=False) + + async def _smol_vm() -> Sandbox: pytest.importorskip("smol") from agent_env.providers.sandbox_providers.smol_vm import provider as smol_module @@ -210,6 +218,7 @@ async def _lume() -> Sandbox: "boat": _boat, "agent37": _agent37, "kosa8": _kosa8, + "mirage": _mirage, "smol_vm": _smol_vm, "local": _local, "lume": _lume, diff --git a/tst/unit/providers/sandbox_providers/provider_capabilities_test.py b/tst/unit/providers/sandbox_providers/provider_capabilities_test.py index 9a020a7af..56ae2e2d0 100644 --- a/tst/unit/providers/sandbox_providers/provider_capabilities_test.py +++ b/tst/unit/providers/sandbox_providers/provider_capabilities_test.py @@ -27,6 +27,8 @@ from agent_env.providers.sandbox_providers.kosa8.provider import Kosa8SandboxProvider from agent_env.providers.sandbox_providers.kosa8.sandbox import Kosa8Sandbox from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandbox, LocalSandboxProvider +from agent_env.providers.sandbox_providers.mirage.provider import MirageSandboxProvider +from agent_env.providers.sandbox_providers.mirage.sandbox import MirageSandbox from agent_env.providers.sandbox_providers.modal_sandbox import ModalSandbox, ModalSandboxProvider from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandbox, ModalVmSandboxProvider from agent_env.providers.sandbox_providers.sail_vm.provider import SailVmSandboxProvider @@ -68,8 +70,9 @@ (BoatSandboxProvider, False, True, LOADABLE, NAME, False, True), (Agent37SandboxProvider, False, True, LOADABLE, NAME, False, True), (Kosa8SandboxProvider, False, True, LOADABLE, NAME, False, True), + (MirageSandboxProvider, False, True, LOADABLE, NAME, False, False), ], ids=["local", "modal", "modal_vm", "e2b", "sail_vm", "tensorlake", "tenki", "boxd", "coreweave", "daytona", "boat", - "agent37", "kosa8"]) + "agent37", "kosa8", "mirage"]) def test_each_provider_declares_where_it_runs_and_the_images_it_runs(cls, on_this_machine, creates_vms, sandbox, container, private_network, websockets): assert ((cls.ON_THIS_MACHINE, SANDBOX_MODE_VM in cls.SUPPORTED_SANDBOX_MODES, cls.PRIVATE_NETWORK, cls.WEBSOCKETS) @@ -293,7 +296,7 @@ def test_an_image_that_records_no_platform_isnt_checked(): @pytest.mark.parametrize("sandbox", [Sandbox, ModalSandbox, ModalVmSandbox, E2BSandbox, SailVmSandbox, TensorlakeSandbox, TenkiSandbox, BoxdSandbox, CoreWeaveSandbox, DaytonaSandbox, BoatSandbox, - Agent37Sandbox, Kosa8Sandbox]) + Agent37Sandbox, Kosa8Sandbox, MirageSandbox]) def test_a_sandbox_runs_linux_amd64_unless_its_provider_sets_another(sandbox): assert sandbox.platform == "linux/amd64" diff --git a/tst/unit/providers/sandbox_providers/test_config_sandbox_providers.py b/tst/unit/providers/sandbox_providers/test_config_sandbox_providers.py index 94b784986..9a5ee1a0a 100644 --- a/tst/unit/providers/sandbox_providers/test_config_sandbox_providers.py +++ b/tst/unit/providers/sandbox_providers/test_config_sandbox_providers.py @@ -16,6 +16,7 @@ from agent_env.providers.sandbox_providers.e2b.provider import E2BSandboxProvider from agent_env.providers.sandbox_providers.kosa8.provider import Kosa8SandboxProvider from agent_env.providers.sandbox_providers.local_docker.provider import LocalSandboxProvider +from agent_env.providers.sandbox_providers.mirage.provider import MirageSandboxProvider from agent_env.providers.sandbox_providers.modal_vm_sandbox import ModalVmSandboxProvider from agent_env.providers.sandbox_providers.sail_vm.provider import SailVmSandboxProvider from agent_env.providers.sandbox_providers.sandbox import Sandbox @@ -388,6 +389,39 @@ def test_kosa8_missing_api_key_is_a_config_error(monkeypatch, tmp_path): build_sandbox_provider("kosa8") +def test_mirage_builtin_receives_its_url_token_and_a_workspace_with_interpolated_mount_secrets(monkeypatch, tmp_path): + cfg = _write_config(tmp_path, """ + [sandbox.providers.mirage.config] + url = "http://mirage.internal:9000" + token = "env:MIRAGE_TEST_TOKEN" + + [sandbox.providers.mirage.config.workspace.mounts."/data"] + vfs = "s3" + config = { bucket = "datasets", secret_access_key = "env:MIRAGE_TEST_S3_SECRET" } + """) + monkeypatch.setenv("AGENT_ENV_CONFIG", str(cfg)) + monkeypatch.setenv("MIRAGE_TEST_TOKEN", "resolved-token") + monkeypatch.setenv("MIRAGE_TEST_S3_SECRET", "resolved-s3-secret") + + provider = build_sandbox_provider("mirage") + + assert isinstance(provider, MirageSandboxProvider) + assert (provider._api.url, provider._api._token) == ("http://mirage.internal:9000", "resolved-token") + assert provider._workspace["mounts"]["/data"] == {"vfs": "s3", "config": { + "bucket": "datasets", "secret_access_key": "resolved-s3-secret"}} + + +def test_mirage_unknown_key_is_a_config_error(monkeypatch, tmp_path): + cfg = _write_config(tmp_path, """ + [sandbox.providers.mirage.config] + api_key = "not-a-mirage-key" + """) + monkeypatch.setenv("AGENT_ENV_CONFIG", str(cfg)) + + with pytest.raises(ConfigError, match="unknown key"): + build_sandbox_provider("mirage") + + def test_coreweave_builtin_receives_an_interpolated_key(monkeypatch, tmp_path): cfg = _write_config(tmp_path, """ [sandbox.providers.coreweave.config] diff --git a/tst/unit/test_capabilities.py b/tst/unit/test_capabilities.py index a760eb1db..c3413e54c 100644 --- a/tst/unit/test_capabilities.py +++ b/tst/unit/test_capabilities.py @@ -2,6 +2,9 @@ from __future__ import annotations +from types import SimpleNamespace + +import httpx import pytest from agent_env.config.errors import ConfigError @@ -213,3 +216,32 @@ def test_vercel_is_present_with_all_ambient_credential_names(monkeypatch): monkeypatch.setenv(name, "configured") _fake_vercel_config(monkeypatch, {}) assert capabilities.remote_sandbox_is_available("vercel") is True + + +def _fake_mirage_daemon(monkeypatch, outcome): + _fake_builder(monkeypatch, "mirage", SimpleNamespace(_api=SimpleNamespace(url="http://127.0.0.1:8765"))) + + def get(url, timeout): + assert url == "http://127.0.0.1:8765/v1/health" + if isinstance(outcome, Exception): + raise outcome + return httpx.Response(outcome) + + monkeypatch.setattr(httpx, "get", get) + + +def test_mirage_is_present_when_its_daemon_answers(monkeypatch): + _fake_mirage_daemon(monkeypatch, 200) + assert capabilities.remote_sandbox_is_available("mirage") is True + + +@pytest.mark.parametrize("refused", [False, True], ids=["unhealthy", "refused"]) +def test_mirage_is_absent_when_its_daemon_doesnt_answer(monkeypatch, refused): + _fake_mirage_daemon(monkeypatch, httpx.ConnectError("refused") if refused else 503) + assert capabilities.remote_sandbox_is_available("mirage") is False + assert capabilities.skip_without_remote_sandbox("mirage").kwargs["reason"] == "agentenv-capability-missing: remote_sandbox" + + +def test_mirage_is_absent_when_its_config_is_refused(monkeypatch): + _fake_builder(monkeypatch, "mirage", ConfigError("[sandbox.providers.mirage.config] has unknown key(s): ['x']")) + assert capabilities.remote_sandbox_is_available("mirage") is False diff --git a/tst/util/capabilities.py b/tst/util/capabilities.py index 31bef3cfa..104dc2abe 100644 --- a/tst/util/capabilities.py +++ b/tst/util/capabilities.py @@ -15,6 +15,7 @@ import tomllib from pathlib import Path +import httpx import pytest MISSING_CAPABILITY_PREFIX = "agentenv-capability-missing: " @@ -24,7 +25,8 @@ #: The remote sandbox providers (``modal``, ``modal_vm``, ``e2b``, ``sail_vm``, ``tensorlake``, ``tenki``, #: ``vercel``, ``boxd``, ``coreweave``, ``daytona``, ``boat``, ``agent37``, ``kosa8``) need -#: credentials the resolved config may not carry; the local default never does. +#: credentials the resolved config may not carry, and ``mirage`` a Mirage daemon that answers; the local default never +#: does. REMOTE_SANDBOX = "remote_sandbox" #: The A2A agent a ``deploy_agent`` step without an id resolves to (``default_a2a_agent_id``); the @@ -130,26 +132,33 @@ def skip_without_model_endpoint() -> pytest.MarkDecorator: def remote_sandbox_is_available(provider: str) -> bool: """Whether the resolved config can build the ``modal`` / ``modal_vm`` / ``e2b`` / ``sail_vm`` / - ``tensorlake`` / ``tenki`` / ``vercel`` / ``boxd`` / ``coreweave`` / ``daytona`` / ``boat`` / ``agent37`` / ``kosa8`` sandbox provider, credentials included. + ``tensorlake`` / ``tenki`` / ``vercel`` / ``boxd`` / ``coreweave`` / ``daytona`` / ``boat`` / ``agent37`` / ``kosa8`` / + ``mirage`` sandbox provider, credentials included. Modal: any failure to resolve the credentials answers False. E2B, Sail, Tensorlake, Tenki, Vercel, boxd, CoreWeave, Daytona, boat, Agent37 and kosa8: building the provider resolves ``[sandbox.providers..config]`` and its ``secret:`` references; only a ``ConfigError`` (absent or incomplete config, or the provider's extra not installed) answers False, any other failure answers True and lets the test fail on the real problem, as ``model_endpoint_is_configured`` does. Vercel, which builds without credentials, also needs them in - its config or the environment.""" - if provider not in ("modal", "modal_vm", "e2b", "sail_vm", "tensorlake", "tenki", "vercel", "boxd", "coreweave", "daytona", "boat", "agent37", "kosa8"): + its config or the environment. Mirage, which builds without credentials, also needs its daemon to answer + ``/v1/health`` at the provider's ``url``.""" + if provider not in ("modal", "modal_vm", "e2b", "sail_vm", "tensorlake", "tenki", "vercel", "boxd", "coreweave", "daytona", "boat", "agent37", "kosa8", "mirage"): raise ValueError(f"unknown remote sandbox provider {provider!r}") - if provider in ("e2b", "sail_vm", "tensorlake", "tenki", "vercel", "boxd", "coreweave", "daytona", "boat", "agent37", "kosa8"): + if provider in ("e2b", "sail_vm", "tensorlake", "tenki", "vercel", "boxd", "coreweave", "daytona", "boat", "agent37", "kosa8", "mirage"): from agent_env.config.errors import ConfigError from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider try: - build_sandbox_provider(provider) + built = build_sandbox_provider(provider) except ConfigError: return False except Exception: return True + if provider == "mirage": + try: + return httpx.get(f"{built._api.url}/v1/health", timeout=5).status_code == 200 + except httpx.HTTPError: + return False if provider != "vercel": return True from agent_env.config import get_config