Skip to content

automaton.sandbox

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

automaton.sandbox

Sandboxed execution engine for Automaton.

:class:Sandbox runs commands inside a Charliecloud container with a clean, minimal environment and optional memory limits. It provides two entry points:

  • :meth:Sandbox.run_command -- run an arbitrary, non-agentic command inside a container. By default this runs with loopback-only networking and no model proxy. This is the general-purpose "run some code against the deliverable" path (a benchmark orchestrator uses it for environment setup and verification).
  • :meth:Sandbox.run_agent -- run an autonomous agent (a harness driving one or more models) inside the container, brokering all model traffic through a loopback-only :class:~automaton.proxy.ModelProxy. The agent's deliverable is left in the bind-mounted workspace directory. Returns an :class:ExecutionResult; Automaton stays agnostic about the deliverable's contents.

Automaton is content-free: the caller supplies the container image, the harness, the agent, staged file paths, and bind mounts.

MemoryCgroupUnavailable

Bases: RuntimeError

memory_cgroup was requested but a memory-capped scope cannot be created.

BindMount dataclass

BindMount(host_path: Path, container_path: Path)

Host/container bind mount specification for Charliecloud.

CommandRunFailed

CommandRunFailed(returncode: int, log_file: Path, detail: str)

Bases: RuntimeError

A sandboxed command exited non-zero.

Attributes:

Name Type Description
returncode int

Process return code.

log_file Path

Path to the command's log file.

detail str

Human-readable failure detail.

Source code in automaton/sandbox.py
def __init__(self, returncode: int, log_file: Path, detail: str):
    self.returncode = returncode
    self.log_file = log_file
    self.detail = detail
    super().__init__(detail)

ExecutionResult dataclass

ExecutionResult(success: bool, workspace: Path, returncode: int | None = None, endpoint_exhausted: bool = False, context_length_exceeded: bool = False, failure_detail: str | None = None, proxy_error_detail: str | None = None, usage_records: list[dict[str, Any]] = list(), usage_summary: dict[str, Any] = dict(), log_file: Path | None = None, blocked_provider_executed_tools: list[str] = list(), dry_run: bool = False, budget_exhausted: bool = False, interrupted: bool = False, oom_kills: int = 0, memory_limit_bytes: int | None = None)

Result of running an agent in the sandbox.

Automaton is agnostic about the deliverable's contents; it reports only execution facts and the workspace location where the deliverable lives.

Attributes:

Name Type Description
success bool

Whether the harness process exited cleanly.

returncode int | None

Harness process return code (None if not run, e.g. dry-run).

workspace Path

Host path to the deliverable workspace.

endpoint_exhausted bool

True if the model proxy could not obtain a complete upstream response.

context_length_exceeded bool

True if the harness failed because an upstream request exceeded the model's context window (an oversized-prompt HTTP 4xx).

failure_detail str | None

Failure detail when success is False.

proxy_error_detail str | None

Last upstream/model proxy error, if any.

usage_records list[dict]

Per-request usage/cost accounting records from the model proxy.

usage_summary dict

Aggregated usage summary computed from usage_records.

log_file Path | None

Path to the harness process log.

blocked_provider_executed_tools list[str]

Provider-executed tool types the model proxy refused to forward. Non-empty means the agent tried to use a tool that runs on the provider's infrastructure outside the sandbox; the run should not be graded as an ordinary task failure.

dry_run bool

True if this was a dry run (no execution performed).

Sandbox

Sandbox(host_root: Path | None = None, dry_run: bool = False, stream_output: bool = True, harness_memory_limit_bytes: int | None = None, harness_memory_limit_fraction: float | None = 0.9, proxy_api_key_env: str = DEFAULT_PROXY_API_KEY_ENV, proxy_api_key_value: str = DEFAULT_PROXY_API_KEY_VALUE, proxy_provider_id: str = DEFAULT_PROXY_PROVIDER_ID, sandbox_proxy_port: int = DEFAULT_SANDBOX_PROXY_PORT, container_run_root: Path = DEFAULT_CONTAINER_RUN_ROOT, container_workspace_root: Path = DEFAULT_CONTAINER_WORKSPACE_ROOT, container_base_root: Path = Path('/automaton/base'), allowed_provider_executed_tools: frozenset[str] | set[str] | None = None, memory_cgroup: bool = False)

Runs commands and agents inside a Charliecloud container.

Parameters:

Name Type Description Default
host_root Path

Host directory bound into the container as container_base_root when no explicit bind mounts are supplied. Defaults to the current directory.

None
dry_run bool

If True, print commands instead of executing them.

False
stream_output bool

If True, mirror container output to the terminal.

True
harness_memory_limit_bytes int

Fixed harness memory cap in bytes.

None
harness_memory_limit_fraction float

Fraction of available memory to cap the harness at. Default 0.9.

0.9
proxy_api_key_env str

Env var name the harness reads for the proxy auth token.

DEFAULT_PROXY_API_KEY_ENV
proxy_api_key_value str

Proxy auth token value.

DEFAULT_PROXY_API_KEY_VALUE
proxy_provider_id str

Provider id used for proxied model routing (<provider>/<model>).

DEFAULT_PROXY_PROVIDER_ID
sandbox_proxy_port int

Loopback port the sandbox-local proxy listens on.

DEFAULT_SANDBOX_PROXY_PORT
container_run_root Path

In-container root for staged run assets.

DEFAULT_CONTAINER_RUN_ROOT
container_workspace_root Path

In-container workspace mount point.

DEFAULT_CONTAINER_WORKSPACE_ROOT
container_base_root Path

Default in-container mount point for host_root.

Path('/automaton/base')
allowed_provider_executed_tools Iterable[str]

Provider-executed tool types the model proxy may forward. Defaults to none, which blocks them: such tools run on the provider's infrastructure instead of in the sandbox, so the sandbox network namespace cannot confine them and their use leaves no trace in the harness transcript.

None
memory_cgroup bool

If True, enforce memory caps with a cgroup instead of ulimit -v: each capped command runs in its own transient systemd-run --user --scope with MemoryMax, so the cap bounds the command's total memory (all of its processes together) and the kernel OOM-kills inside the scope instead of exhausting the node. OOM kills are counted and reported (ExecutionResult.oom_kills, :attr:last_oom_kills). Requires a user systemd manager with the memory controller delegated; raises :class:MemoryCgroupUnavailable otherwise. Default False keeps the per-process ulimit -v cap.

False
Source code in automaton/sandbox.py
def __init__(
    self,
    host_root: Path | None = None,
    dry_run: bool = False,
    stream_output: bool = True,
    harness_memory_limit_bytes: int | None = None,
    harness_memory_limit_fraction: float | None = 0.9,
    proxy_api_key_env: str = DEFAULT_PROXY_API_KEY_ENV,
    proxy_api_key_value: str = DEFAULT_PROXY_API_KEY_VALUE,
    proxy_provider_id: str = DEFAULT_PROXY_PROVIDER_ID,
    sandbox_proxy_port: int = DEFAULT_SANDBOX_PROXY_PORT,
    container_run_root: Path = DEFAULT_CONTAINER_RUN_ROOT,
    container_workspace_root: Path = DEFAULT_CONTAINER_WORKSPACE_ROOT,
    container_base_root: Path = Path("/automaton/base"),
    allowed_provider_executed_tools: frozenset[str] | set[str] | None = None,
    memory_cgroup: bool = False,
):
    self.host_root = (Path(host_root) if host_root else Path.cwd()).resolve()
    self.dry_run = dry_run
    self.stream_output = stream_output
    self._last_run_interrupted = False
    self.harness_memory_limit_bytes = harness_memory_limit_bytes
    self.harness_memory_limit_fraction = harness_memory_limit_fraction
    self.proxy_api_key_env = proxy_api_key_env
    self.proxy_api_key_value = proxy_api_key_value
    self.proxy_provider_id = proxy_provider_id
    self.sandbox_proxy_port = sandbox_proxy_port
    self.container_run_root = container_run_root
    self.container_workspace_root = container_workspace_root
    self.container_base_root = container_base_root
    self.allowed_provider_executed_tools = frozenset(
        str(name).strip().lower() for name in (allowed_provider_executed_tools or ())
    )
    self.memory_cgroup = memory_cgroup
    #: OOM kills inside the scope of the most recent memory-capped command.
    self.last_oom_kills = 0

sandbox_helper_script

sandbox_helper_script() -> str

Return the sandbox helper script source to stage into a run dir.

Source code in automaton/sandbox.py
def sandbox_helper_script(self) -> str:
    """Return the sandbox helper script source to stage into a run dir."""
    return SANDBOX_HELPER_SCRIPT

harness_models_config

harness_models_config(agent: Agent, *, sandboxed: bool = True) -> dict[str, Any]

Build the harness-facing models config (proxy wiring).

When sandboxed is True, models are routed through the loopback proxy; otherwise the harness talks to the upstream base_url directly.

Source code in automaton/sandbox.py
def harness_models_config(self, agent: Agent, *, sandboxed: bool = True) -> dict[str, Any]:
    """Build the harness-facing models config (proxy wiring).

    When ``sandboxed`` is True, models are routed through the loopback
    proxy; otherwise the harness talks to the upstream base_url directly.
    """
    return {
        "proxy_base_url": self.proxy_base_url if sandboxed else None,
        "api_key_env": self.proxy_api_key_env,
        "models": [
            {
                "name": model.name,
                "model": model.config["model"],
                "base_url": self.proxy_base_url if sandboxed else str(model.config["base_url"]),
                "opencode_model": f"{self.proxy_provider_id}/{model.name}",
                "proxied_base_url": str(model.config["base_url"]),
                # Opaque API-style hint carried verbatim from provider/model
                # config. Automaton assigns no meaning or default; the
                # harness interprets this value.
                "api": model.config.get("api"),
            }
            for model in agent.models
        ],
    }

model_registry

model_registry(agent: Agent) -> dict[str, dict[str, Any]]

Build the upstream model registry consumed by :class:ModelProxy.

Source code in automaton/sandbox.py
def model_registry(self, agent: Agent) -> dict[str, dict[str, Any]]:
    """Build the upstream model registry consumed by :class:`ModelProxy`."""
    registry: dict[str, dict[str, Any]] = {}
    for model in agent.models:
        registry[model.name] = {
            **model.config,
            "api_key": self._model_api_key(model.config),
            "opencode_model": f"{self.proxy_provider_id}/{model.name}",
        }
    return registry

run_command

run_command(container_path: Path, argv: list[str], *, cwd: Path | None = None, env_vars: dict[str, str] | None = None, bind_mounts: list[BindMount] | None = None, log_file: Path | None = None, memory_limit_bytes: int | None = None, network: bool = False, check: bool = True) -> int

Run an arbitrary command inside the container.

By default runs with loopback-only networking (network=False) and no model proxy. This is the general-purpose path for running non-agentic code (setup, verification, tooling) against a workspace.

Parameters:

Name Type Description Default
container_path Path

Path to the built container directory.

required
argv list[str]

Command to run inside the container (e.g. ["bash", script]).

required
cwd Path

Working directory inside the container.

None
env_vars dict[str, str]

Extra environment variables to set inside the container.

None
bind_mounts list[BindMount]

Bind mounts. Defaults to binding host_root at container_base_root.

None
log_file Path

Combined stdout/stderr log path.

None
memory_limit_bytes int

Memory cap for the command.

None
network bool

If False (default), run inside a loopback-only network namespace with no outbound access. If True, run without network isolation.

False
check bool

If True, raise :class:CommandRunFailed on non-zero exit.

True

Returns:

Type Description
int

The command's return code (or 0 in dry-run mode).

Source code in automaton/sandbox.py
def run_command(
    self,
    container_path: Path,
    argv: list[str],
    *,
    cwd: Path | None = None,
    env_vars: dict[str, str] | None = None,
    bind_mounts: list[BindMount] | None = None,
    log_file: Path | None = None,
    memory_limit_bytes: int | None = None,
    network: bool = False,
    check: bool = True,
) -> int:
    """Run an arbitrary command inside the container.

    By default runs with loopback-only networking (``network=False``) and
    no model proxy. This is the general-purpose path for running
    non-agentic code (setup, verification, tooling) against a workspace.

    Parameters
    ----------
    container_path : Path
        Path to the built container directory.
    argv : list[str]
        Command to run inside the container (e.g. ``["bash", script]``).
    cwd : Path, optional
        Working directory inside the container.
    env_vars : dict[str, str], optional
        Extra environment variables to set inside the container.
    bind_mounts : list[BindMount], optional
        Bind mounts. Defaults to binding ``host_root`` at
        ``container_base_root``.
    log_file : Path, optional
        Combined stdout/stderr log path.
    memory_limit_bytes : int, optional
        Memory cap for the command.
    network : bool, optional
        If False (default), run inside a loopback-only network namespace
        with no outbound access. If True, run without network isolation.
    check : bool, optional
        If True, raise :class:`CommandRunFailed` on non-zero exit.

    Returns
    -------
    int
        The command's return code (or 0 in dry-run mode).
    """
    cmd = self._ch_run_prefix(
        container_path, cwd=cwd, env_vars=env_vars, bind_mounts=bind_mounts
    ) + ["--", *argv]

    if self.dry_run:
        print(f"[DRY-RUN] Would execute: {' '.join(cmd)}")
        if cwd:
            print(f"[DRY-RUN]   in directory: {cwd}")
        return 0

    if network:
        result = self._run_logged(
            cmd, log_file, cwd=self.host_root, memory_limit_bytes=memory_limit_bytes
        )
        returncode = result.returncode
    else:
        returncode = self._run_isolated_network_command(
            cmd,
            log_file=log_file if log_file is not None else self.host_root / "automaton-command.log",
            memory_limit_bytes=memory_limit_bytes,
        )

    if returncode != 0 and check:
        detail = self._command_failure_detail(returncode, log_file) if log_file else (
            f"Command failed with exit code {returncode}"
        )
        raise CommandRunFailed(returncode, log_file or Path("/dev/null"), detail)
    return returncode

run_agent

run_agent(container_path: Path, harness: Harness, agent: Agent, *, workspace: Path, run_dir: Path, container_paths: dict[str, Path], bind_mounts: list[BindMount], proxy_log: Path, usage_records_file: Path, harness_output_dir: Path, models_config_file: Path, harness_config_file: Path, extra_env: dict[str, str] | None = None, timeout: int | None = None, sandboxed: bool = True, budget_exhausted_callback: 'Callable[[str], None] | None' = None, stop_check: 'Callable[[], bool] | None' = None) -> ExecutionResult

Run an autonomous agent inside the sandbox.

stop_check (opt-in) is polled while the agent runs; once it returns True the agent's whole process tree is terminated and the result is reported as unsuccessful with interrupted=True. With the default None behaviour is unchanged.

The caller is responsible for staging the workspace, prompt, harness assets, and sandbox helper script into run_dir before calling.

Parameters:

Name Type Description Default
container_path Path

Built runtime container directory.

required
harness Harness

Loaded harness.

required
agent Agent

Configured agent (harness + models).

required
workspace Path

In-container workspace path (where the deliverable is produced).

required
run_dir Path

Host per-run directory (already populated with staged assets).

required
container_paths dict[str, Path]

In-container paths for staged assets. Required keys: prompt, harness_dir, models_config, harness_config, harness_output, sandbox_helper, task_env. Optional key: group_prompt — when present, forwarded to the harness as --group-prompt so it can inject shared task-group instructions between the system prompt and the per-task prompt.

required
bind_mounts list[BindMount]

Bind mounts for the run.

required
proxy_log Path

Model proxy log path.

required
usage_records_file Path

JSONL path for per-request usage records.

required
harness_output_dir Path

Host directory for harness output/logs.

required
models_config_file Path

Host path to write the harness models config to.

required
harness_config_file Path

Host path to write the agent harness config to.

required
extra_env dict[str, str]

Additional environment variables passed into the harness container (e.g. task-facing workspace/env variables the caller defines).

None
timeout int

Per-run timeout in seconds passed to the harness.

None
sandboxed bool

If True (default), route model traffic through the loopback proxy and run the harness in an isolated network namespace. If False, run the harness with direct network access to upstream models.

True

Returns:

Type Description
ExecutionResult

Execution facts and deliverable workspace location.

Source code in automaton/sandbox.py
def run_agent(
    self,
    container_path: Path,
    harness: Harness,
    agent: Agent,
    *,
    workspace: Path,
    run_dir: Path,
    container_paths: dict[str, Path],
    bind_mounts: list[BindMount],
    proxy_log: Path,
    usage_records_file: Path,
    harness_output_dir: Path,
    models_config_file: Path,
    harness_config_file: Path,
    extra_env: dict[str, str] | None = None,
    timeout: int | None = None,
    sandboxed: bool = True,
    budget_exhausted_callback: "Callable[[str], None] | None" = None,
    stop_check: "Callable[[], bool] | None" = None,
) -> ExecutionResult:
    """Run an autonomous agent inside the sandbox.

    ``stop_check`` (opt-in) is polled while the agent runs; once it returns
    True the agent's whole process tree is terminated and the result is
    reported as unsuccessful with ``interrupted=True``. With the default
    ``None`` behaviour is unchanged.

    The caller is responsible for staging the workspace, prompt, harness
    assets, and sandbox helper script into ``run_dir`` before calling.

    Parameters
    ----------
    container_path : Path
        Built runtime container directory.
    harness : Harness
        Loaded harness.
    agent : Agent
        Configured agent (harness + models).
    workspace : Path
        In-container workspace path (where the deliverable is produced).
    run_dir : Path
        Host per-run directory (already populated with staged assets).
    container_paths : dict[str, Path]
        In-container paths for staged assets. Required keys:
        ``prompt``, ``harness_dir``, ``models_config``, ``harness_config``,
        ``harness_output``, ``sandbox_helper``, ``task_env``. Optional key:
        ``group_prompt`` — when present, forwarded to the harness as
        ``--group-prompt`` so it can inject shared task-group instructions
        between the system prompt and the per-task prompt.
    bind_mounts : list[BindMount]
        Bind mounts for the run.
    proxy_log : Path
        Model proxy log path.
    usage_records_file : Path
        JSONL path for per-request usage records.
    harness_output_dir : Path
        Host directory for harness output/logs.
    models_config_file : Path
        Host path to write the harness models config to.
    harness_config_file : Path
        Host path to write the agent harness config to.
    extra_env : dict[str, str], optional
        Additional environment variables passed into the harness container
        (e.g. task-facing workspace/env variables the caller defines).
    timeout : int, optional
        Per-run timeout in seconds passed to the harness.
    sandboxed : bool, optional
        If True (default), route model traffic through the loopback proxy
        and run the harness in an isolated network namespace. If False, run
        the harness with direct network access to upstream models.

    Returns
    -------
    ExecutionResult
        Execution facts and deliverable workspace location.
    """
    harness_output_dir.mkdir(parents=True, exist_ok=True)
    run_script = container_paths["harness_dir"] / "run_benchmark.sh"
    system_prompt = container_paths["harness_dir"] / "system_prompt.md"

    proxy: ModelProxy | None = None
    with ModelProxy(
        self.model_registry(agent),
        proxy_log,
        request_deadline_seconds=MODEL_PROXY_REQUEST_DEADLINE_SECONDS,
        usage_records_file=usage_records_file,
        allowed_provider_executed_tools=self.allowed_provider_executed_tools,
        budget_exhausted_callback=budget_exhausted_callback,
    ) as proxy:
        proxy.stream_errors = self.stream_output
        with open(models_config_file, "w") as f:
            yaml.dump(self.harness_models_config(agent, sandboxed=sandboxed), f)
        with open(harness_config_file, "w") as f:
            yaml.dump(agent.harness_config, f)

        env_vars = self._model_env_vars(models_config_file)
        if extra_env:
            env_vars.update(extra_env)

        harness_cmd = self._ch_run_prefix(container_path, env_vars=env_vars, bind_mounts=bind_mounts) + [
            "--",
            "bash",
            str(run_script),
            "--workspace", str(workspace),
            "--task-prompt", str(container_paths["prompt"]),
            "--system-prompt", str(system_prompt),
            "--models-config", str(container_paths["models_config"]),
            "--harness-config", str(container_paths["harness_config"]),
            "--output-dir", str(container_paths["harness_output"]),
            "--task-env", str(container_paths["task_env"]),
        ]
        group_prompt = container_paths.get("group_prompt")
        if group_prompt is not None:
            harness_cmd.extend(["--group-prompt", str(group_prompt)])
        if timeout is not None:
            harness_cmd.extend(["--timeout-seconds", str(timeout)])

        harness_log = harness_output_dir / "ch-run.log"

        if self.dry_run:
            print("[DRY-RUN] Would execute agent harness")
            print(f"[DRY-RUN] Harness command: {' '.join(harness_cmd)}")
            return ExecutionResult(success=True, workspace=workspace, dry_run=True, log_file=harness_log)

        memory_limit_bytes = self._harness_memory_limit_bytes()
        self._last_run_interrupted = False
        try:
            if sandboxed:
                sock = proxy.sandbox_socket()
                returncode = self._run_single_sandbox_command(
                    sock=sock,
                    command=harness_cmd,
                    log_file=harness_log,
                    helper_script=run_dir / "sandbox_helper.py",
                    memory_limit_bytes=memory_limit_bytes,
                    failure_log=harness_log,
                    stop_check=stop_check,
                )
            else:
                result = self._run_logged(
                    harness_cmd, harness_log, cwd=self.host_root, memory_limit_bytes=memory_limit_bytes,
                    stop_check=stop_check,
                )
                returncode = result.returncode
                if returncode != 0:
                    raise CommandRunFailed(
                        returncode, harness_log, self._command_failure_detail(returncode, harness_log)
                    )
        except CommandRunFailed as exc:
            proxy_error_detail = proxy.last_error_detail
            detail = exc.detail
            if proxy_error_detail and proxy_error_detail not in detail:
                detail = f"{detail} Upstream model error: {proxy_error_detail}"
            usage_records = list(proxy.usage_records)
            return ExecutionResult(
                success=False,
                workspace=workspace,
                returncode=exc.returncode,
                endpoint_exhausted=proxy.endpoint_exhausted,
                context_length_exceeded=proxy.context_length_exceeded,
                failure_detail=detail,
                proxy_error_detail=proxy_error_detail,
                usage_records=usage_records,
                usage_summary=aggregate_usage(usage_records),
                log_file=harness_log,
                blocked_provider_executed_tools=proxy.blocked_provider_executed_tools,
                budget_exhausted=proxy.budget_exhausted,
                interrupted=self._last_run_interrupted,
                oom_kills=self.last_oom_kills,
                memory_limit_bytes=memory_limit_bytes,
            )

        if not harness_log.exists():
            harness_log.write_text("")
        usage_records = list(proxy.usage_records)
        return ExecutionResult(
            success=True,
            workspace=workspace,
            returncode=returncode,
            endpoint_exhausted=proxy.endpoint_exhausted,
            usage_records=usage_records,
            usage_summary=aggregate_usage(usage_records),
            log_file=harness_log,
            # Recorded even on success: an agent may retry without the tool
            # and still exit 0, but the attempt must remain visible.
            blocked_provider_executed_tools=proxy.blocked_provider_executed_tools,
            budget_exhausted=proxy.budget_exhausted,
            oom_kills=self.last_oom_kills,
            memory_limit_bytes=memory_limit_bytes,
        )

memory_limit_bytes

memory_limit_bytes() -> int | None

The memory cap this sandbox applies to the harness, in bytes, if any.

Callers can pass it to :meth:run_command to cap setup and verification commands the same way.

Source code in automaton/sandbox.py
def memory_limit_bytes(self) -> int | None:
    """The memory cap this sandbox applies to the harness, in bytes, if any.

    Callers can pass it to :meth:`run_command` to cap setup and
    verification commands the same way.
    """
    return self._harness_memory_limit_bytes()