diff --git a/src/agent_env/task_step/task_steps/computer/computer_exec.py b/src/agent_env/task_step/task_steps/computer/computer_exec.py index 6e828eb70..7d93d8c5a 100644 --- a/src/agent_env/task_step/task_steps/computer/computer_exec.py +++ b/src/agent_env/task_step/task_steps/computer/computer_exec.py @@ -18,15 +18,14 @@ from agentenv_protocol.computer import COMPUTER, COMPUTER_EXEC from agent_env.entity.refs import EntityRef -from agent_env.env.env import DeployedEnv, DeployedSandboxEnv -from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.env import DeployedSandboxEnv from agent_env.env.envs.computer.utils import inside from agent_env.env.envs.computer.utils.sites import RootChannel -from agent_env.env.envs.multi_env import MultiEnv from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider from agent_env.task_step.context import TaskStepContext from agent_env.task_step.preflight import stored_env from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.computer.lookup import computer_problem, find_computer logger = logging.getLogger(__name__) @@ -101,8 +100,9 @@ def background_script() -> str: class ComputerExecTaskStep(TaskStep): """Run ``command`` inside the computer of the env ``env_id`` as its session user, in ``cwd`` (relative to the home, the home by default), with ``env`` added to its environment, for at most ``timeout_s``. ``command`` is a program and - its arguments, or a string run by ``sh -c``. For a multi env, ``computer`` names the computer, by its environment - name, and may be left out when the env has one. + its arguments, or a string run by ``sh -c``. For a multi env, ``computer_name`` names the computer by its + environment name there (its key in the deploy's ``child_envs``, not its env id), and may be left out when the env + has one. With ``scope: "system"`` it runs as root instead, through the computer's sandbox rather than its driver, in the same folder and with the session user's ``HOME``; a computer booted from a disk has no such route. @@ -118,14 +118,14 @@ class ComputerExecTaskStep(TaskStep): entity_refs = (EntityRef.env("env_id"),) def __init__(self, id: str, version: Optional[int], env_id: str, command: Command, - computer: Optional[str] = None, cwd: Optional[str] = None, env: Optional[dict[str, str]] = None, + computer_name: Optional[str] = None, cwd: Optional[str] = None, env: Optional[dict[str, str]] = None, timeout_s: float = DEFAULT_TIMEOUT_S, background: bool = False, check: bool = True, scope: str = "session", depends_on: Optional[list[TaskStepDependency]] = None, fail_task_on_error: bool = True): super().__init__(id, version, depends_on=depends_on, fail_task_on_error=fail_task_on_error) self.env_id = env_id self.command = command - self.computer = computer + self.computer_name = computer_name self.cwd = cwd self.env = env self.timeout_s = timeout_s @@ -142,8 +142,8 @@ def config_problems(self) -> list[str]: problems.append(f"step {self.id!r}: command must not be blank") elif not (isinstance(self.command, list) and self.command and all(isinstance(a, str) for a in self.command)): problems.append(f"step {self.id!r}: command must be a non-empty list of strings, or a string run by sh -c") - if self.computer is not None and (not isinstance(self.computer, str) or not self.computer): - problems.append(f"step {self.id!r}: computer, when given, must be a non-empty string") + if self.computer_name is not None and (not isinstance(self.computer_name, str) or not self.computer_name): + problems.append(f"step {self.id!r}: computer_name, when given, must be a non-empty string") if self.cwd is not None and (not isinstance(self.cwd, str) or self.cwd.startswith("/")): problems.append(f"step {self.id!r}: cwd is a folder relative to the session user's home, not {self.cwd!r}") if self.env is not None and not (isinstance(self.env, dict) and all( @@ -171,21 +171,22 @@ def preflight(self) -> list[str]: problems = super().preflight() if not isinstance(self.env_id, str) or not self.env_id or (env := stored_env(self.env_id)) is None: return problems - if problem := _computer_problem(env, self.computer): + if problem := computer_problem(env, self.computer_name): problems.append(f"step {self.id!r}: {problem}") return problems def to_dict(self) -> dict: - return {**super().to_dict(), "env_id": self.env_id, "command": self.command, "computer": self.computer, - "cwd": self.cwd, "env": self.env, "timeout_s": self.timeout_s, "background": self.background, - "check": self.check, "scope": self.scope} + return {**super().to_dict(), "env_id": self.env_id, "command": self.command, + "computer_name": self.computer_name, "cwd": self.cwd, "env": self.env, "timeout_s": self.timeout_s, + "background": self.background, "check": self.check, "scope": self.scope} @classmethod def from_dict(cls, data: dict) -> ComputerExecTaskStep: return cls(**cls._base_from_dict(data), env_id=data["env_id"], command=data["command"], - computer=data.get("computer"), cwd=data.get("cwd"), env=data.get("env"), - timeout_s=data.get("timeout_s", DEFAULT_TIMEOUT_S), background=data.get("background", False), - check=data.get("check", True), scope=data.get("scope", "session")) + computer_name=data.get("computer_name", data.get("computer")), cwd=data.get("cwd"), + env=data.get("env"), timeout_s=data.get("timeout_s", DEFAULT_TIMEOUT_S), + background=data.get("background", False), check=data.get("check", True), + scope=data.get("scope", "session")) def command_argv(self) -> list[str]: """The command as a program and its arguments: through ``sh -c`` when it's a string.""" @@ -197,7 +198,7 @@ def argv(self) -> list[str]: return ["sh", "-c", background_script(), "computer_exec", *argv] if self.background else argv async def execute(self, context: TaskStepContext) -> TaskStepContext: - deployed = find_computer(context, self.env_id, self.computer) + deployed = find_computer(context, self.env_id, self.computer_name) if missing := [m for m in inside.missing(deployed) if m.startswith(COMPUTER_EXEC)]: raise RuntimeError(f"{self.type} {self.id!r}: env {self.env_id!r}'s computer serves no {missing[0]}") if self.timeout_s > (limit := inside.max_timeout_s(deployed)): @@ -212,7 +213,7 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: answer = await self._as_root(deployed, argv) else: answer = await inside.run(deployed, argv, timeout_s=self.timeout_s, env=self.env, cwd=self.cwd) - record = {"env_id": self.env_id, "computer": self.computer, "argv": argv, "scope": self.scope, + record = {"env_id": self.env_id, "computer_name": self.computer_name, "argv": argv, "scope": self.scope, "background": self.background, "exit_code": answer.get("exit_code"), "timed_out": bool(answer.get("timed_out")), "truncated": bool(answer.get("truncated")), @@ -259,43 +260,6 @@ async def _as_root(self, deployed: DeployedSandboxEnv, argv: list[str]) -> dict: "stdout": out.decode("utf-8", errors="replace"), "stderr": err.decode("utf-8", errors="replace")} -def find_computer(context: TaskStepContext, env_id: str, computer: Optional[str]) -> DeployedSandboxEnv: - """The deploy record of the computer in ``env_id`` that serves computer-exec/v1 ``run``: the env's own, or one of a - multi env's computers' (``DeployedGatewayEnv.child_envs``), the one ``computer`` names else its only one.""" - deployed = next((d for d in context.deployed_envs if d.env_id == env_id), None) - if deployed is None: - raise RuntimeError(f"env {env_id!r} isn't in context.deployed_envs") - children = {name: DeployedEnv.from_dict(data) - for name, data in (getattr(deployed, "child_envs", None) or {}).items()} - if computer is not None: - found = children.get(computer) - if found is None: - raise RuntimeError(f"env {env_id!r} has no computer named {computer!r} (it has {sorted(children)})") - return found - if deployed.supports(COMPUTER_EXEC, "run"): - return deployed - computers = [record for record in children.values() if record.supports(COMPUTER_EXEC, "run")] - if len(computers) != 1: - raise RuntimeError(f"env {env_id!r} has {len(computers) or 'no'} computers serving {COMPUTER_EXEC} run" - + (f": name one as computer, of {sorted(children)}" if computers else "")) - return computers[0] - - -def _computer_problem(env: object, computer: Optional[str]) -> Optional[str]: - if isinstance(env, ComputerEnv): - return None if computer is None else f"env {env.id!r} is a computer env, so it takes no computer name" - if not isinstance(env, MultiEnv): - return f"env {getattr(env, 'id', '?')!r} is no computer env, nor a multi env with one" - browser = env.website_browser().computer - names = [computer_env.environment_name for computer_env in (*env.computer_envs, *([browser] if browser else []))] - if computer is not None and computer not in names: - return f"env {env.id!r} has no computer named {computer!r} (it has {names})" - if computer is None and len(names) != 1: - return (f"env {env.id!r} has {len(names) or 'no'} computers" + - (f": name one as computer, of {names}" if names else "")) - return None - - def _os(deployed: DeployedSandboxEnv) -> Optional[str]: """The computer's OS, as its card's computer/v1 platform says.""" return (protocol_v1.extension_params(deployed.environment_card or {}, COMPUTER).get("platform") or {}).get("os") diff --git a/src/agent_env/task_step/task_steps/computer/lookup.py b/src/agent_env/task_step/task_steps/computer/lookup.py new file mode 100644 index 000000000..8a7370597 --- /dev/null +++ b/src/agent_env/task_step/task_steps/computer/lookup.py @@ -0,0 +1,58 @@ +"""Finding a computer in an env, for the steps that reach inside one: its deploy record in a run, by its name in a multi +env or as the only computer there, and whether a stored env has it.""" + +from __future__ import annotations + +from typing import Optional + +from agentenv_protocol.computer import COMPUTER_EXEC + +from agent_env.env.env import DeployedEnv, DeployedSandboxEnv +from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.task_step.context import TaskStepContext + + +def find_computer(context: TaskStepContext, env_id: str, computer_name: Optional[str]) -> DeployedSandboxEnv: + """The deploy record of the computer in ``env_id`` that serves computer-exec/v1 ``run``: the env's own, or one of a + multi env's computers' (``child_computer``).""" + deployed = next((d for d in context.deployed_envs if d.env_id == env_id), None) + if deployed is None: + raise RuntimeError(f"env {env_id!r} isn't in context.deployed_envs") + if computer_name is None and deployed.supports(COMPUTER_EXEC, "run"): + return deployed + return child_computer(deployed, computer_name)[1] + + +def child_computer(deployed: DeployedEnv, computer_name: Optional[str]) -> tuple[str, DeployedSandboxEnv]: + """A multi env's computer in its deployment (``DeployedGatewayEnv.child_envs``, keyed by each computer's + environment name), by that name and with its deploy record: the one ``computer_name`` names, else its only one + serving computer-exec/v1 ``run``.""" + children = {name: DeployedEnv.from_dict(data) + for name, data in (getattr(deployed, "child_envs", None) or {}).items()} + if computer_name is not None: + found = children.get(computer_name) + if found is None: + raise RuntimeError(f"env {deployed.env_id!r} has no computer named {computer_name!r} " + f"(it has {sorted(children)})") + return computer_name, found + computers = [(name, record) for name, record in children.items() if record.supports(COMPUTER_EXEC, "run")] + if len(computers) != 1: + raise RuntimeError(f"env {deployed.env_id!r} has {len(computers) or 'no'} computers serving {COMPUTER_EXEC} run" + + (f": name one as computer_name, of {sorted(children)}" if computers else "")) + return computers[0] + + +def computer_problem(env: object, computer_name: Optional[str]) -> Optional[str]: + if isinstance(env, ComputerEnv): + return None if computer_name is None else f"env {env.id!r} is a computer env, so it takes no computer_name" + if not isinstance(env, MultiEnv): + return f"env {getattr(env, 'id', '?')!r} is no computer env, nor a multi env with one" + browser = env.website_browser().computer + names = [computer_env.environment_name for computer_env in (*env.computer_envs, *([browser] if browser else []))] + if computer_name is not None and computer_name not in names: + return f"env {env.id!r} has no computer named {computer_name!r} (it has {names})" + if computer_name is None and len(names) != 1: + return (f"env {env.id!r} has {len(names) or 'no'} computers" + + (f": name one as computer_name, of {names}" if names else "")) + return None diff --git a/src/agent_env/task_step/task_steps/computer/snapshot_computer_env.py b/src/agent_env/task_step/task_steps/computer/snapshot_computer_env.py index cebe70606..c34cc11b9 100644 --- a/src/agent_env/task_step/task_steps/computer/snapshot_computer_env.py +++ b/src/agent_env/task_step/task_steps/computer/snapshot_computer_env.py @@ -1,5 +1,6 @@ -"""snapshot_computer_env: a computer env's files, kept by their paths in its environment artifact, and each of its apps' -exports in theirs, which load_artifact loads back into a computer.""" +"""snapshot_computer_env: a computer's files, kept by their paths in its environment artifact, and each of its apps' +exports in theirs, beside a multi env's other environments, which load_artifact loads back into a computer or stages +as files for a judge.""" from __future__ import annotations @@ -10,23 +11,27 @@ from pydantic import TypeAdapter, ValidationError from agent_env.entity.refs import EntityRef, RefRole -from agent_env.env.env import Env -from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.env import Env, gateway_url_of +from agent_env.env.envs.multi_env import MultiEnv from agent_env.store.ids import is_local_id, validate_local_id from agent_env.task_step.context import TaskStepContext from agent_env.task_step.preflight import stored_env from agent_env.task_step.task_step import TaskStep, TaskStepDependency +from agent_env.task_step.task_steps.computer.lookup import child_computer, computer_problem from agent_env.task_step.task_steps.snapshot_env import DEFAULT_EXPORT_TIMEOUT_SECONDS, SnapshotEnvTaskStep _PATHS = TypeAdapter(list[RelativePath]) class SnapshotComputerEnvTaskStep(SnapshotEnvTaskStep): - """Snapshot a deployed computer env's files into a new environment universe, as ``snapshot_env`` snapshots an env, + """Snapshot a deployed computer's files into a new environment universe, as ``snapshot_env`` snapshots an env, each file under its path relative to the session user's home in the computer's environment artifact: those under ``file_paths``, by default the folders its card declares, leaving out each app's paths. Each app that exports is - kept beside it in an environment artifact under the app's name. ``load_artifact`` loads the snapshot back into a - computer, through ``data/add``. + kept beside it in an environment artifact under the app's name. The computer is a computer env, or the one + ``computer_name`` names in a multi env by its environment name there (its key in the deploy's ``child_envs``, not + its env id; the env's only computer when unnamed), whose other environments are kept beside it as ``snapshot_env`` + keeps them. ``load_artifact`` loads the snapshot back into a computer, through ``data/add``, or + stages it as files in an agent, a judge's sandbox for one. Output: ``context.metadata["env_snapshotted_universes"][self.id]`` = ``{"id", "version"}``.""" @@ -44,6 +49,7 @@ def __init__( env_instance_id: Optional[str] = None, env_step_id: Optional[str] = None, snapshot_id: Optional[str] = None, + computer_name: Optional[str] = None, file_paths: Optional[list[str]] = None, export_timeout_seconds: int = DEFAULT_EXPORT_TIMEOUT_SECONDS, depends_on: Optional[list[TaskStepDependency]] = None, @@ -52,18 +58,20 @@ def __init__( super().__init__(id, version, env_id=env_id, env_instance_id=env_instance_id, env_step_id=env_step_id, snapshot_id=snapshot_id, export_timeout_seconds=export_timeout_seconds, depends_on=depends_on, fail_task_on_error=fail_task_on_error) + self.computer_name = computer_name self.file_paths = file_paths def to_dict(self) -> dict: return {**TaskStep.to_dict(self), "env_id": self.env_id, "env_instance_id": self.env_instance_id, - "env_step_id": self.env_step_id, "snapshot_id": self.snapshot_id, "file_paths": self.file_paths, + "env_step_id": self.env_step_id, "snapshot_id": self.snapshot_id, "computer_name": self.computer_name, + "file_paths": self.file_paths, "export_timeout_seconds": self.export_timeout_seconds} @classmethod def from_dict(cls, data: dict) -> SnapshotComputerEnvTaskStep: return cls(**cls._base_from_dict(data), env_id=data.get("env_id"), env_instance_id=data.get("env_instance_id"), env_step_id=data.get("env_step_id"), snapshot_id=data.get("snapshot_id"), - file_paths=data.get("file_paths"), + computer_name=data.get("computer_name"), file_paths=data.get("file_paths"), export_timeout_seconds=data.get("export_timeout_seconds", DEFAULT_EXPORT_TIMEOUT_SECONDS)) def config_problems(self) -> list[str]: @@ -77,14 +85,16 @@ def config_problems(self) -> list[str]: return problems def preflight(self) -> list[str]: - """The env this step names when it isn't a computer env.""" + """The env this step names when it isn't a computer env, nor a multi env with the computer + ``computer_name`` picks.""" problems = super().preflight() if self.env_id is None: return problems env = stored_env(self.env_id) if env is None: # what the run reports return problems - return problems if isinstance(env, ComputerEnv) else [*problems, _not_a_computer(env)] + problem = computer_problem(env, self.computer_name) + return [*problems, f"snapshot_computer_env {self.id!r}: {problem}"] if problem else problems async def execute(self, context: TaskStepContext) -> TaskStepContext: snapshot_id = self._derive_snapshot_id(context) @@ -92,16 +102,16 @@ async def execute(self, context: TaskStepContext) -> TaskStepContext: validate_local_id(snapshot_id) deployed = self._resolve_deployed_env(context) env = await asyncio.to_thread(Env.get, deployed.env_id, deployed.env_version) - if not isinstance(env, ComputerEnv): - raise RuntimeError(_not_a_computer(env)) + if isinstance(env, MultiEnv): + name = child_computer(deployed, self.computer_name)[0] + elif problem := computer_problem(env, self.computer_name): + raise RuntimeError(f"snapshot_computer_env {self.id!r}: {problem}") + else: + name = env.computer_name result = await self.snapshot_env_state( - env=env, gateway_url=None, snapshot_id=snapshot_id, deployed=deployed, + env=env, gateway_url=gateway_url_of(deployed), snapshot_id=snapshot_id, deployed=deployed, export_timeout_seconds=self.export_timeout_seconds, - data_get_params=None if self.file_paths is None else {env.computer_name: {"paths": self.file_paths}}) + data_get_params=None if self.file_paths is None else {name: {"paths": self.file_paths}}) context.metadata.setdefault("env_snapshotted_universes", {})[self.id] = { "id": result.environment_universe_artifact_id, "version": result.environment_universe_artifact_version} return context - - -def _not_a_computer(env: Env) -> str: - return f"snapshot_computer_env snapshots a computer env, and {env.id} is a {env.type} env" diff --git a/tst/integration/computer/computer_grading/artifacts/golden/budget.csv b/tst/integration/computer/computer_grading/artifacts/golden/budget.csv new file mode 100644 index 000000000..59d5aab02 --- /dev/null +++ b/tst/integration/computer/computer_grading/artifacts/golden/budget.csv @@ -0,0 +1,4 @@ +item,amount +rent,1200 +food,300 +total,1500 diff --git a/tst/integration/computer/computer_grading/artifacts/golden/notes.txt b/tst/integration/computer/computer_grading/artifacts/golden/notes.txt new file mode 100644 index 000000000..cd32ca658 --- /dev/null +++ b/tst/integration/computer/computer_grading/artifacts/golden/notes.txt @@ -0,0 +1 @@ +Budget done: the total is 1500. diff --git a/tst/integration/computer/computer_grading/envs/desk/env.toml b/tst/integration/computer/computer_grading/envs/desk/env.toml new file mode 100644 index 000000000..e1dca97f8 --- /dev/null +++ b/tst/integration/computer/computer_grading/envs/desk/env.toml @@ -0,0 +1,3 @@ +type = "computer" +computer = "ubuntu-24.04" +driver = "reference" diff --git a/tst/integration/computer/computer_grading/envs/office/env.toml b/tst/integration/computer/computer_grading/envs/office/env.toml new file mode 100644 index 000000000..7cc53b8c6 --- /dev/null +++ b/tst/integration/computer/computer_grading/envs/office/env.toml @@ -0,0 +1,2 @@ +type = "multi" +computer_envs = ["desk"] diff --git a/tst/integration/computer/computer_grading/tasks/grade.json b/tst/integration/computer/computer_grading/tasks/grade.json new file mode 100644 index 000000000..9c87477ae --- /dev/null +++ b/tst/integration/computer/computer_grading/tasks/grade.json @@ -0,0 +1,21 @@ +[ + {"id": "env", "type": "deploy_env", "env_id": "office"}, + {"id": "agent", "type": "deploy_agent", "env_ids": [], "a2a_agent_id": "computer-grading-echo", "sandbox_type": "local"}, + {"id": "judge", "type": "deploy_agent", "agent_name": "judge", "env_ids": [], "a2a_agent_id": "computer-grading-echo", + "sandbox_type": "local"}, + {"id": "ask", "type": "prompt_agent", "prompt_id": "ask", "depends_on": ["agent"], + "prompt": "Write ~/Desktop/budget.csv with rent 1200 and food 300 and their total, and leave a note in ~/notes.txt stating the total."}, + {"id": "work", "type": "computer_exec", "env_id": "office", "depends_on": ["env"], + "command": "mkdir -p Desktop && printf 'item,amount\\nrent,1200\\nfood,300\\ntotal,1500\\n' > Desktop/budget.csv && echo 'Budget done.' > notes.txt"}, + {"id": "snapshot", "type": "snapshot_computer_env", "env_id": "office", "computer_name": "desk", "depends_on": ["work"], + "file_paths": ["Desktop/budget.csv", "notes.txt"]}, + {"id": "result", "type": "load_artifact", "artifact_from_step_id": "snapshot", "agent_name": "judge", + "destination_path": "/tmp/grading/result", "depends_on": ["snapshot", "judge"]}, + {"id": "golden", "type": "load_artifact", "artifact_id": "golden", "agent_name": "judge", + "destination_path": "/tmp/grading/golden", "depends_on": ["judge"]}, + {"id": "grade", "type": "rubrics_verifier", "verifier_id": "files", "prompt_id": "ask", "agent_name": "judge", + "use_agent_judge": true, "use_trajectory": false, "score_aggregator": "weighted_average", + "depends_on": ["ask", "result", "golden"], + "criteria": [{"id": "budget", "description": "~/Desktop/budget.csv matches the golden budget.csv."}, + {"id": "note", "description": "~/notes.txt matches the golden notes.txt, stating the total."}]} +] diff --git a/tst/integration/computer/computer_grading_test.py b/tst/integration/computer/computer_grading_test.py new file mode 100644 index 000000000..63614925b --- /dev/null +++ b/tst/integration/computer/computer_grading_test.py @@ -0,0 +1,73 @@ +"""Grading a multi env's computer with a judge agent, end to end, composed of the steps each part takes: a multi env of +one ubuntu-24.04 computer with the reference driver deployed, files left in it as an agent would leave them (by +computer_exec), one in its home outside the folders a snapshot takes by default; snapshot_computer_env keeps those +files by their paths; load_artifact stages that snapshot and the task's golden files in the judge's sandbox; and +rubrics_verifier grades with that judge, which it tells where each was staged. The judge is faked at its call +boundary: it reads each file and its golden file in its own container, as a judge with Bash would, so the CSV matches +and the note, which leaves out the total, doesn't.""" + +import json +from pathlib import Path + +import pytest +from click.testing import CliRunner + +from agent_env.cli import cli +from agent_env.providers.sandbox_providers.sandbox import VmSandbox +from agent_env.providers.sandbox_providers.sandbox_provider import build_sandbox_provider, get_agent_sandbox_provider +from agent_env.task_step.task_steps.verifiers.rubrics_verifier import RubricsVerifierTaskStep +from tst.integration.computer.conftest import run_context +from tst.util.a2a_test_agent import put_test_agent + +pytestmark = [pytest.mark.integration, pytest.mark.int_test_slow] + +BUNDLE = Path(__file__).parent / "computer_grading" +RESULT, GOLDEN = "/tmp/grading/result", "/tmp/grading/golden" +# Each criterion, by the key the judge sees it under, and the file it compares with its golden file. +COMPARED = {"c1": ("desk/Desktop/budget.csv", "budget.csv"), "c2": ("desk/notes.txt", "notes.txt")} + + +def test_a_judge_grades_a_computers_files_against_golden_files_staged_in_its_sandbox(state, monkeypatch): + prompts: list[str] = [] + monkeypatch.setattr(RubricsVerifierTaskStep, "_invoke_judge_a2a", _comparing_judge(prompts)) + put_test_agent("computer-grading-echo") + + ran = CliRunner().invoke(cli, ["run", str(BUNDLE), "--task", "grade", "--no-emulate"]) + + assert ran.exit_code == 0, ran.output + [prompt] = prompts + staged = {line.split("`")[3]: set(line.split("contains: ")[1].split(", ")) + for line in prompt.splitlines() if line.startswith("- `") and "contains: " in line} + assert staged == {f"{RESULT}/": {"desk/Desktop/budget.csv", "desk/notes.txt"}, + f"{GOLDEN}/": {"budget.csv", "notes.txt"}}, prompt + grade = run_context(ran.output)["metadata"]["grades"]["grade"] + assert {row["id"]: row["score"] for row in grade["verifier_criteria"]} == {"budget": 1.0, "note": 0.0}, ( + grade["verifier_criteria"]) + assert grade["score"] == 0.5, grade + + +def _comparing_judge(prompts: list[str]): + """Meets each criterion whose file reads the same as its golden file, both read in the judge's own container.""" + + async def judge(self, *, eval_prompt: str, judge_agent, **_) -> dict: + prompts.append(eval_prompt) + provider = (build_sandbox_provider(judge_agent.sandbox_type) if judge_agent.sandbox_type + else get_agent_sandbox_provider()) + sandbox = await provider.get_sandbox(judge_agent.sandbox_id) + rows = [] + for key, (left, golden) in COMPARED.items(): + read = [await _read_in_judge(sandbox, judge_agent, path) + for path in (f"{RESULT}/{left}", f"{GOLDEN}/{golden}")] + rows.append({"id": key, "score": 1.0 if read[0] == read[1] and read[0][0] == 0 else 0.0, + "justification": f"read {left} as {read[0]!r} and golden {golden} as {read[1]!r}"}) + return {"response": json.dumps({"results": rows})} + + return judge + + +async def _read_in_judge(sandbox, judge_agent, path: str) -> tuple[int, str, str]: + """``cat path`` where load_artifact staged it: in the judge's container on a VM-backed sandbox.""" + if isinstance(sandbox, VmSandbox): + container = judge_agent.installed_container or sandbox.container_name + return await sandbox.exec_with_output("docker", "exec", container, "cat", path) + return await sandbox.exec_with_output("cat", path) diff --git a/tst/unit/task_step/computer_exec_test.py b/tst/unit/task_step/computer_exec_test.py index 872022071..adafdf8e0 100644 --- a/tst/unit/task_step/computer_exec_test.py +++ b/tst/unit/task_step/computer_exec_test.py @@ -282,13 +282,13 @@ async def test_a_multi_envs_only_computer_is_found_by_itself_and_one_of_several_ ctx = await _step("echo one", env_id="multi").execute(_context(_multi(computer, "desk"))) assert ctx.metadata[RECORDS_KEY]["exec"]["stdout"] == "one\n" - ctx = await _step("echo two", env_id="multi", computer="b").execute(_context(_multi(computer, "a", "b"))) + ctx = await _step("echo two", env_id="multi", computer_name="b").execute(_context(_multi(computer, "a", "b"))) assert ctx.metadata[RECORDS_KEY]["exec"]["stdout"] == "two\n" - with pytest.raises(RuntimeError, match=r"has 2 computers .*: name one as computer"): + with pytest.raises(RuntimeError, match=r"has 2 computers .*: name one as computer_name"): await _step("true", env_id="multi").execute(_context(_multi(computer, "a", "b"))) with pytest.raises(RuntimeError, match=r"has no computer named 'c'"): - await _step("true", env_id="multi", computer="c").execute(_context(_multi(computer, "a", "b"))) + await _step("true", env_id="multi", computer_name="c").execute(_context(_multi(computer, "a", "b"))) @pytest.mark.asyncio @@ -313,7 +313,7 @@ def computer_env(name): (("desk",), None, None, None), ((), "chromium", None, None), (("desk",), "chromium", "chromium", None), - (("desk",), "chromium", None, "has 2 computers: name one as computer, of ['desk', 'chromium']"), + (("desk",), "chromium", None, "has 2 computers: name one as computer_name, of ['desk', 'chromium']"), (("desk",), None, "chromium", "has no computer named 'chromium' (it has ['desk'])"), ((), None, None, "has no computers"), ], ids=["its-only-computer", "its-browser-computer-alone", "its-browser-computer-by-name", "two-unnamed", @@ -324,7 +324,7 @@ def test_preflight_finds_a_multi_envs_computers_and_its_browser_computer(monkeyp lambda id: _stored_multi(*computers, browser=browser)) monkeypatch.setattr(TaskStep, "preflight", lambda self: []) - problems = _step("true", env_id="office", computer=named).preflight() + problems = _step("true", env_id="office", computer_name=named).preflight() assert problems == ([] if problem is None else [f"step 'exec': env 'office' {problem}"]) @@ -346,9 +346,11 @@ def test_bad_configs_are_named(fields, problem): def test_it_round_trips_through_the_registry(): - step = _step(["open", "x.xlsx"], computer="desk", cwd="Desktop", env={"A": "1"}, timeout_s=30, background=True, + step = _step(["open", "x.xlsx"], computer_name="desk", cwd="Desktop", env={"A": "1"}, timeout_s=30, background=True, check=False) again = get_task_step_registry()["computer_exec"].from_dict(step.to_dict()) assert again.to_dict() == step.to_dict() + stored = {key: value for key, value in step.to_dict().items() if key != "computer_name"} + assert get_task_step_registry()["computer_exec"].from_dict({**stored, "computer": "desk"}).computer_name == "desk" root = _step("apt-get install -y jq", scope="system") assert get_task_step_registry()["computer_exec"].from_dict(root.to_dict()).scope == "system" diff --git a/tst/unit/task_step/snapshot_computer_env_test.py b/tst/unit/task_step/snapshot_computer_env_test.py index 6c6085cd0..f50d228d9 100644 --- a/tst/unit/task_step/snapshot_computer_env_test.py +++ b/tst/unit/task_step/snapshot_computer_env_test.py @@ -1,26 +1,36 @@ """snapshot_computer_env: a computer env's files kept by their paths in its environment artifact, in a new environment universe beside each of its apps' exports, returned inline or uploaded under the grant and written where they were put, the computer asked again without the grant when it fails under it, file_paths sent to its data/get alone, and an app -that keeps nothing yet left out; refused for an env that isn't a computer, for paths that aren't relative, and with no -files to keep.""" +that keeps nothing yet left out; a multi env's computer, the one named or its only one, kept so beside the multi env's +other environments; refused for an env that isn't a computer nor a multi env with the one named, for paths that aren't +relative, and with no files to keep.""" from __future__ import annotations +import dataclasses from pathlib import Path +from types import SimpleNamespace import pytest from agentenv_protocol import uploaded_file_part +from agentenv_protocol.computer import COMPUTER_EXEC from agent_env.artifact import EnvironmentArtifact, EnvironmentUniverseArtifact from agent_env.config import set_object_store +from agent_env.env.env import DeployedGatewayEnv, DeployedSandboxEnv from agent_env.env.envs.computer.env import ComputerEnv +from agent_env.env.envs.multi_env import MultiEnv +from agent_env.env.gateway.constants import WELL_KNOWN_PATH from agent_env.task_step.registry import get_task_step_registry from agent_env.task_step.task_steps.computer.snapshot_computer_env import SnapshotComputerEnvTaskStep +from tst.unit.task_step.computer_exec_test import _stored_multi from tst.unit.task_step.snapshot_env_without_gateway_test import (DATA_OBJECTS, FILE_TREE, UNREACHABLE, _computer, _inline, _record, _serve) from tst.unit.task_step.test_snapshot_env import _ctx from tst.util.granting_object_store import GrantingObjectStore +GATEWAY = "http://gateway.test" + class _Desk(ComputerEnv): """A stored computer env, as far as a snapshot reads one.""" @@ -32,6 +42,34 @@ def __init__(self): class _Mail: id, version, type, environment_name = "mail", 1, "mcp_server", "mail" + +class _Office(MultiEnv): + """A stored multi env, as far as a snapshot reads one: the MCP server mail beside its computers.""" + + def __init__(self): + self.id, self.version = "office", 1 + self.mcp_server_envs, self.website_envs = [SimpleNamespace(environment_name="mail")], [] + + +def _office(*computers: str) -> DeployedGatewayEnv: + """The multi env deployed behind a gateway fronting mail, each of ``computers`` on a sandbox of its own, its data + plane at ``//agentenv``.""" + def computer(name: str) -> dict: + card = {**_computer(), "name": name, "url": f"/{name}/agentenv"} + card["capabilities"] = {"operations": ["data/add", "data/get"], "extensions": [ + FILE_TREE, {"uri": COMPUTER_EXEC, "params": {"methods": {"run": {}}}}]} + return dataclasses.asdict(DeployedSandboxEnv( + env_id=name, env_version=1, sandbox_id=f"sb-{name}", instance_id=f"{name}-abc", sandbox_type="local", + environment_card_url=f"http://{name}.test{WELL_KNOWN_PATH}", environment_card=card)) + + card = {"name": "office", "children_environments": [ + {"name": "mail", "url": "/svc/mcp-mail/agentenv", "capabilities": {"operations": ["data/get"]}}]} + return DeployedGatewayEnv(env_id="office", env_version=1, gateway_url=GATEWAY, sandbox_id="sb-gw", + instance_id="office-abc", environment_card_url=f"{GATEWAY}{WELL_KNOWN_PATH}", + environment_card=card, sandbox_type="local", + child_envs={name: computer(name) for name in computers}) + + async def _snapshot(monkeypatch, card: dict, env=None, **fields) -> EnvironmentArtifact: """The computer's environment artifact in the universe the step snapshots it into.""" monkeypatch.setattr("agent_env.env.env.Env.get", classmethod(lambda cls, id, version=None: env or _Desk())) @@ -48,15 +86,15 @@ def _kept(desktop: EnvironmentArtifact) -> dict[str, bytes]: def test_its_fields_round_trip_and_its_type_is_registered(): - step = SnapshotComputerEnvTaskStep(id="snap", version=None, env_id="desk", file_paths=["Documents", "Desktop/a.pdf"], - export_timeout_seconds=60) + step = SnapshotComputerEnvTaskStep(id="snap", version=None, env_id="office", computer_name="desk", + file_paths=["Documents", "Desktop/a.pdf"], export_timeout_seconds=60) data = step.to_dict() restored = get_task_step_registry()["snapshot_computer_env"].from_dict(data) assert isinstance(restored, SnapshotComputerEnvTaskStep) and data["type"] == "snapshot_computer_env" - assert (restored.env_id, restored.file_paths, restored.export_timeout_seconds) == ( - "desk", ["Documents", "Desktop/a.pdf"], 60) + assert (restored.env_id, restored.computer_name, restored.file_paths, restored.export_timeout_seconds) == ( + "office", "desk", ["Documents", "Desktop/a.pdf"], 60) assert not {"gateway_url", "include_env_trajectory", "include_env_changes"} & set(data) @@ -68,14 +106,25 @@ def test_file_paths_not_relative_to_the_home_are_refused_before_a_run(paths): assert [problem for problem in step.config_problems() if "file_paths are normalized paths" in problem] -@pytest.mark.parametrize("stored, refused", [(_Mail(), True), (_Desk(), False)], ids=["mcp-server", "computer"]) -def test_an_env_that_isnt_a_computer_is_refused_before_a_run(monkeypatch, stored, refused): +@pytest.mark.parametrize("stored, computer, problem", [ + (_Mail(), None, "env 'mail' is no computer env, nor a multi env with one"), + (_Desk(), None, None), + (_Desk(), "desktop", "env 'desk' is a computer env, so it takes no computer_name"), + (_stored_multi("desk"), None, None), + (_stored_multi("desk", "laptop"), "laptop", None), + (_stored_multi("desk", "laptop"), None, + "env 'office' has 2 computers: name one as computer_name, of ['desk', 'laptop']"), + (_stored_multi("desk"), "kiosk", "env 'office' has no computer named 'kiosk' (it has ['desk'])"), +], ids=["mcp-server", "computer", "computer-named", "multi-only-computer", "multi-named", "multi-two-unnamed", + "multi-unknown-name"]) +def test_an_env_that_isnt_a_computer_nor_a_multi_env_with_the_one_named_is_refused_before_a_run( + monkeypatch, stored, computer, problem): monkeypatch.setattr("agent_env.env.env.Env.get", classmethod(lambda cls, id, version=None: stored)) - problems = SnapshotComputerEnvTaskStep(id="snap", version=None, env_id=stored.id).preflight() + problems = SnapshotComputerEnvTaskStep(id="snap", version=None, env_id=stored.id, + computer_name=computer).preflight() - assert problems == (["snapshot_computer_env snapshots a computer env, and mail is a mcp_server env"] - if refused else []) + assert problems == ([] if problem is None else [f"snapshot_computer_env 'snap': {problem}"]) @pytest.mark.asyncio @@ -102,6 +151,44 @@ async def test_a_computer_with_apps_keeps_its_files_beside_each_apps_export_send ("/svc/notes/agentenv", [])] +@pytest.mark.asyncio +@pytest.mark.parametrize("computers, computer", [(("desk", "laptop"), "laptop"), (("laptop",), None)], + ids=["the-one-named", "its-only-one"]) +async def test_a_multi_envs_computer_is_kept_beside_its_other_environments_with_file_paths_sent_to_it_alone( + local_stores, monkeypatch, computers, computer): + sent = _serve(monkeypatch, {"/svc/mcp-mail/agentenv": lambda params: [{"kind": "data", "data": {"inbox": 2}}], + "/desk/agentenv": lambda params: [_inline("Documents/d.txt", b"d")], + "/laptop/agentenv": lambda params: [_inline("notes.txt", b"n")]}) + monkeypatch.setattr("agent_env.env.env.Env.get", classmethod(lambda cls, id, version=None: _Office())) + context = _ctx(_office(*computers)) + + await SnapshotComputerEnvTaskStep(id="snap", version=None, env_id="office", computer_name=computer, + file_paths=["notes.txt"]).execute(context) + + snapshotted = context.metadata["env_snapshotted_universes"]["snap"] + kept = {environment.environment_name: environment for environment in EnvironmentUniverseArtifact.get( + snapshotted["id"], version=snapshotted["version"]).get_environment_artifacts()} + assert sorted(kept) == sorted(["mail", *computers]) and _kept(kept["laptop"]) == {"notes.txt": b"n"} + assert sorted(sent) == sorted([("/svc/mcp-mail/agentenv", {}), ("/laptop/agentenv", {"paths": ["notes.txt"]}), + *([("/desk/agentenv", {})] if "desk" in computers else [])]) + + +@pytest.mark.asyncio +@pytest.mark.parametrize("computers, computer, refused", [ + (("desk", "laptop"), None, r"env 'office' has 2 computers serving .* run: name one as computer_name"), + (("desk",), "kiosk", r"env 'office' has no computer named 'kiosk' \(it has \['desk'\]\)"), +], ids=["two-unnamed", "an-unknown-name"]) +async def test_a_multi_env_without_the_computer_named_is_refused(local_stores, monkeypatch, computers, computer, + refused): + sent = _serve(monkeypatch, {}) + monkeypatch.setattr("agent_env.env.env.Env.get", classmethod(lambda cls, id, version=None: _Office())) + + with pytest.raises(RuntimeError, match=refused): + await SnapshotComputerEnvTaskStep(id="snap", version=None, env_id="office", computer_name=computer, + file_paths=["notes.txt"]).execute(_ctx(_office(*computers))) + assert sent == [] + + @pytest.mark.asyncio @pytest.mark.parametrize("file_paths, params", [(["Documents"], {"paths": ["Documents"]}), (None, {})], ids=["file-paths", "the-cards-folders"]) @@ -155,7 +242,7 @@ async def test_a_computer_that_fails_under_the_grant_is_asked_again_without_one( @pytest.mark.asyncio @pytest.mark.parametrize("env, answers, refused", [ - (_Mail(), {}, "snapshots a computer env, and mail is a mcp_server env"), + (_Mail(), {}, "env 'mail' is no computer env, nor a multi env with one"), (None, {"/agentenv": lambda params: []}, "'desktop' returned no files to snapshot"), ], ids=["not-a-computer", "no-files"]) async def test_a_run_with_nothing_a_computer_snapshot_can_keep_is_refused(local_stores, monkeypatch, env, answers,