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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions app/nullius/catalogue/agents/mini-swe-agent/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,14 @@
task = sys.argv[1]
out = os.path.join(tempfile.mkdtemp(prefix="mini-"), "trajectory.json")
mini = os.path.join(os.path.dirname(sys.executable), "mini")
# the run's reasoning effort, mini's own model.model_kwargs.reasoning_effort; -c replaces mini's config list, so its
# own mini.yaml is named first (drop_params kept). default: none, as mini sends on its own.
# Load the benchmark's published config before transport and explicit run options.
config = ["-c", os.environ.get("MSWEA_MINI_CONFIG_PATH", "mini.yaml")]
effort = os.environ.get("NULLIUS_REASONING_EFFORT", "default")
config = ["-c", "mini.yaml", "-c", f"model.model_kwargs.reasoning_effort={effort}"] if effort not in ("", "default") else []
rc = subprocess.run([mini, "--task", task, "--yolo", "--exit-immediately", "--cost-limit", "0", "--output", out, *config],
if effort not in ("", "default"):
config += ["-c", f"model.model_kwargs.reasoning_effort={effort}"]
rc = subprocess.run([mini, "--task", task, "--yolo", "--exit-immediately",
"--environment-class", "local", "--model", os.environ["MSWEA_MODEL_NAME"],
"--output", out, *config],
stdin=subprocess.DEVNULL, stdout=sys.stderr, stderr=sys.stderr).returncode
try:
with open(out) as f:
Expand Down
11 changes: 9 additions & 2 deletions app/nullius/catalogue/agents/swe-agent/agent.json
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@
"smmap==5.0.3",
"sniffio==1.3.1",
"starlette==1.10.0",
"swe-rex==1.2.1",
"swe-rex==1.4.0",
"tabulate==0.10.0",
"tenacity==9.2.1",
"textual==8.2.8",
Expand Down Expand Up @@ -156,6 +156,13 @@
}
},
"only_for": [
"swe-bench-verified"
"swe-bench-verified",
"swe-bench-multilingual"
],
"prepare_image": [
"{install}/.venv/bin/python",
"{here}/run.py",
"image",
"{image}"
]
}
18 changes: 15 additions & 3 deletions app/nullius/catalogue/agents/swe-agent/run.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""Start SWE-agent v1.1.0 through its public configuration and environment APIs.

Preparation calls its ToolHandler.install without creating a model. Execution
uses its default configuration and RunSingle, including its normal tool setup.
uses the benchmark's upstream configuration and RunSingle, including its normal tool setup.
"""
import os
import importlib.util
from pathlib import Path
import sys
import subprocess
import json
import logging
import shutil
import shlex
from contextlib import contextmanager
Expand Down Expand Up @@ -44,7 +45,18 @@ def tool_staging(root=Path("/root/tools")):


def main():
check_tool_python()
config_path = os.environ.get("SWE_AGENT_CONFIG_PATH", "config/default.yaml")
if sys.argv[1] == "image":
if config_path == "config/benchmarks/anthropic_filemap_multilingual.yaml":
from swerex.deployment.docker import DockerDeployment
deployment = DockerDeployment(image=sys.argv[2], python_standalone_dir="/root",
logger=logging.getLogger("nullius.swe-image"))
# The pinned upstream recipe, with its own BASE_IMAGE build argument resolved.
print(deployment.glibc_dockerfile.replace("ARG BASE_IMAGE", "ARG BASE_IMAGE=" + sys.argv[2], 1))
return
os.environ["PATH"] = os.environ.get("NULLIUS_TASK_PATH", os.environ["PATH"])
if shutil.which("python") or config_path == "config/default.yaml":
check_tool_python()
os.environ["PIP_CONSTRAINT"] = str(Path(__file__).with_name("tools.constraints.txt"))
# The pinned checkout is mounted read-only and owned by the host user.
# Permit GitPython's provenance lookup for this one path, process-locally.
Expand All @@ -58,7 +70,7 @@ def main():
from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
from sweagent.tools.tools import ToolConfig, ToolHandler

config = yaml.safe_load((REPO_ROOT / 'config/default.yaml').read_text())
config = yaml.safe_load((REPO_ROOT / config_path).read_text())
# SWE-ReX intentionally starts shells with a fresh environment. Use the
# upstream tool environment option for pip constraints and preparation's
# temporary proxy; normal execution receives no proxy variables.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@
SOLVE_SECONDS = 300
RESULTS = "/tmp/nullius-swebench-verifier"
# What the images keep under root's home, where the tests find it: an agent's home is the run's, not root's.
AGENT_ENV = {"GOPATH": "/root/go", "GOCACHE": "/root/.cache/go-build", "COREPACK_HOME": "/root/.cache/node/corepack"}
AGENT_ENV = {"MSWEA_MINI_CONFIG_PATH": "swebench.yaml",
"SWE_AGENT_CONFIG_PATH": "config/benchmarks/anthropic_filemap_multilingual.yaml", "GOPATH": "/root/go", "GOCACHE": "/root/.cache/go-build", "COREPACK_HOME": "/root/.cache/node/corepack"}

with open(os.path.join(HERE, "images.json")) as f:
IMAGES = json.load(f)
Expand Down
3 changes: 3 additions & 0 deletions app/nullius/catalogue/benchmarks/swe-bench-pro/driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,12 +152,15 @@ def setup(unit, dir):
apply = (f"cp {CAPTURED} {LOGS}/model.patch; "
f"if [ -s {CAPTURED} ]; then cp {CAPTURED} /tmp/replay.patch; {replay()}; fi; {check}")
return {"prompt": prompt, "environment": "task", "image": image,
"env": {"MSWEA_MINI_CONFIG_PATH": "/tmp/nullius-mini-config/mini_toolcall.yaml"},
"mount": {"v2/tooling/configs": "/tmp/nullius-mini-config"},
**({"agent_seconds": int(agent)} if agent else {}),
"verify": {**common, "run": ["bash", "-c", apply],
"capture": {"run": ["bash", "-c", capture()], "collect": os.path.dirname(CAPTURED), "seconds": 300},
"in_place": {**common, "run": ["bash", "-c", check]}}}



def score(unit, dir, transcript, answer, verified=None):
if not verified:
return {"reward": 0.0, "passed": False, "detail": {"why": "the task's check did not run"}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def setup(unit, dir):
f"git diff --cached --binary --no-ext-diff --no-textconv {shlex.quote(r['base_commit'])} -- "
f"> {RESULTS}/model.patch && exec /bin/bash /eval.sh")
return {"prompt": r["problem_statement"], "environment": "task", "image": {"pull": IMAGES[unit]}, "workdir": WORKDIR,
"env": {"PATH": "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/condabin",
"env": {"MSWEA_MINI_CONFIG_PATH": "swebench.yaml", "PATH": "/opt/miniconda3/envs/testbed/bin:/opt/miniconda3/condabin",
"CONDA_DEFAULT_ENV": "testbed", "CONDA_PREFIX": "/opt/miniconda3/envs/testbed",
"CONDA_SHLVL": "1", "CONDA_EXE": "/opt/miniconda3/bin/conda",
"CONDA_PYTHON_EXE": "/opt/miniconda3/bin/python", "_CE_CONDA": "", "_CE_M": "",
Expand Down
2 changes: 2 additions & 0 deletions app/nullius/standard/contract/definitions.py
Original file line number Diff line number Diff line change
Expand Up @@ -1883,6 +1883,8 @@ def problems(d: dict, kind: str) -> List[str]:
elif kind == "agent" and "driver" in (d.get("start") or {}):
bad += _driver_agent(d)
elif kind == "agent":
if "prepare_image" in d:
bad += _command("prepare_image", d["prepare_image"], {"here", "install", "image"})
if "prepare" in d:
bad += ["prepare." + p for p in step_problems(d["prepare"], collect=False)]
if isinstance(d["prepare"], dict):
Expand Down
32 changes: 32 additions & 0 deletions app/nullius/standard/runner/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -2653,6 +2653,8 @@ def place(self, rl, cmd: List[str], env: dict, workdir: str, home: str, interact
**getattr(box, "agent_proxy", {})}
path = ":".join(([box.env["PATH"]] if "PATH" in box.env else []) + [box.path]
+ install.bin_dirs(self.inst) + [d + "/bin" for _, d in box.runtimes.values()])
inside["NULLIUS_TASK_PATH"] = ":".join(p for p in (box.env.get("PATH"), box.path) if p)
inside["IS_SANDBOX"] = "1" # Harbor's marker: root agents are inside a task sandbox.
argv = box.exec_argv(container.in_runtime(cmd, box.runtimes), inside, path, interactive=interactive)
return argv, container.program_env(inside)
if self.backend == "local":
Expand Down Expand Up @@ -2778,6 +2780,8 @@ def own_box(self, tag: str, setup: dict, rl, home: str):
box = None
try:
image = self.own_image(spec)
if self.other["_kind"] == "agent" and self.other.get("prepare_image"):
image = self.prepare_agent_image(image, setup, os.path.dirname(home))
cfg = container.image_config(image)
volumes = {container.within(self.up or self.bench["_here"], src): inside for src, inside in (setup.get("mount") or {}).items()}
mounted, runtimes = [], {}
Expand Down Expand Up @@ -2805,6 +2809,34 @@ def own_box(self, tag: str, setup: dict, rl, home: str):
box.stop()
raise

def prepare_agent_image(self, image: str, setup: dict, trial: str) -> str:
"""Build the agent's upstream Dockerfile before starting an own-image unit."""
out = os.path.join(trial, "agent")
os.makedirs(out, exist_ok=True)
command = install.words(self.other["prepare_image"],
{"here": self.other["_here"], "install": self.inst, "image": image})
# Only the task's configuration, not the run's model environment or credentials.
env = {"PATH": os.defpath, **{k: v for k, v in setup.get("env", {}).items() if k != "PATH"}}
try:
result = run_group(command, 60, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, stopped=self.cancellation)
with open(os.path.join(out, "prepare-image.txt"), "w") as f:
f.write(result.stderr)
if result.returncode:
raise container.Unavailable(f"agent image configuration exited {result.returncode}: {result.stderr[-1000:]}")
if not result.stdout.strip():
return image
# Use the existing content-addressed image builder and retain its exact input.
with tempfile.TemporaryDirectory() as root:
context = os.path.join(root, "image")
os.mkdir(context)
for folder in (context, out):
with open(os.path.join(folder, "Dockerfile"), "w") as f:
f.write(result.stdout)
return container.own_image(self.other, {"build": "image"}, root, out)
except subprocess.TimeoutExpired as e:
raise container.Unavailable("agent image configuration timed out") from e

@staticmethod
def box_changes(box) -> Optional[str]:
"""What changed in the unit's container since its image - the work
Expand Down
56 changes: 56 additions & 0 deletions app/tests/test_agent_preparation.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,59 @@ def test_preexisting_directory_or_symlink_is_preserved(self):
self.fail('preexisting uploads accepted')
self.assertEqual(marker.read_text(), 'benchmark data')
self.assertTrue(link.is_symlink())


class AgentImagePreparation(unittest.TestCase):
def test_upstream_recipe_is_built_and_recorded_without_model_credentials(self):
from pathlib import Path
from types import SimpleNamespace
with tempfile.TemporaryDirectory() as folder:
r = run.Run.__new__(run.Run)
r.other = {"key": "example", "_here": "/definition",
"prepare_image": ["{install}/python", "{here}/image.py", "{image}"]}
r.inst, r._stopped = "/install", None
recipe = "FROM task@sha256:" + "a" * 64 + "\n"
def build(agent, spec, root, log):
self.assertEqual(Path(root, "image", "Dockerfile").read_text(), recipe)
self.assertEqual(Path(log, "Dockerfile").read_text(), recipe)
return "prepared"
with mock.patch.object(run, "run_group", return_value=SimpleNamespace(
returncode=0, stdout=recipe, stderr="")) as emit, \
mock.patch.object(container, "own_image", side_effect=build), \
mock.patch.dict(os.environ, {"ANTHROPIC_API_KEY": "must-not-reach-hook"}):
self.assertEqual(r.prepare_agent_image("task", {"env": {"CONFIG": "upstream"}}, folder), "prepared")
self.assertEqual(emit.call_args.args[0], ["/install/python", "/definition/image.py", "task"])
self.assertEqual(emit.call_args.kwargs["env"], {"PATH": os.defpath, "CONFIG": "upstream"})
with mock.patch.object(run, "run_group", return_value=SimpleNamespace(
returncode=0, stdout="", stderr="")), mock.patch.object(container, "own_image") as build:
self.assertEqual(r.prepare_agent_image("task", {}, folder), "task")
build.assert_not_called()
with mock.patch.object(run, "run_group", return_value=SimpleNamespace(
returncode=1, stdout=recipe, stderr="failed")), mock.patch.object(container, "own_image") as build:
with self.assertRaisesRegex(container.Unavailable, "exited 1"):
r.prepare_agent_image("task", {}, folder)
build.assert_not_called()


class MiniBenchmarkConfig(unittest.TestCase):
def test_benchmark_config_and_effort_reach_cli_without_overriding_limits(self):
import runpy
from pathlib import Path
from types import SimpleNamespace
wrapper = Path(__file__).parents[1] / 'nullius/catalogue/agents/mini-swe-agent/run.py'
for config in ("swebench.yaml", "/benchmark/mini_toolcall.yaml"):
for effort in ("default", "high"):
with self.subTest(config=config, effort=effort), tempfile.TemporaryDirectory() as folder, \
mock.patch.dict(os.environ, {"MSWEA_MINI_CONFIG_PATH": config, "MSWEA_MODEL_NAME": "openai/test",
"NULLIUS_REASONING_EFFORT": effort}), \
mock.patch('sys.argv', [str(wrapper), "Fix the bug"]), \
mock.patch('tempfile.mkdtemp', return_value=folder), \
mock.patch('subprocess.run', return_value=SimpleNamespace(returncode=0)) as called:
with self.assertRaises(SystemExit):
runpy.run_path(str(wrapper))
argv = called.call_args.args[0]
self.assertEqual(argv[argv.index('-c') + 1], config)
self.assertEqual(argv[argv.index('--model') + 1], 'openai/test')
self.assertEqual(argv[argv.index('--environment-class') + 1], 'local')
self.assertNotIn('--cost-limit', argv)
self.assertEqual('model.model_kwargs.reasoning_effort=high' in argv, effort == 'high')
4 changes: 3 additions & 1 deletion app/tests/test_standard_own_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,8 @@ def test_task_environment_reaches_agent_and_runner_variables_win(self):
{"PATH": "/host/bin", "HOME": "/run/home", "OPENAI_BASE_URL": "http://relay/v1"},
"/testbed", "/run/home", box=b)
self.assertIn("PATH=/task/bin:/image/bin", argv)
self.assertEqual(env["NULLIUS_TASK_PATH"], "/task/bin:/image/bin")
self.assertEqual(env["IS_SANDBOX"], "1")
self.assertEqual(env["CONDA_DEFAULT_ENV"], "testbed")
self.assertEqual(env["HOME"], "/run/home")
self.assertEqual(env["OPENAI_BASE_URL"], "http://relay/v1")
Expand Down Expand Up @@ -252,7 +254,7 @@ def test_on_podman_the_agent_in_its_own_image_gets_its_home_by_value(self):
b = container.Box("job", "u0001", "img", workdir="/app", runtimes={})
argv, env = r.place(None, ["sh", "x"], {"HOME": "/h", "NULLIUS_RELAY_KEY": "placeholder", "PATH": "/p"}, "/app", "/h", box=b)
self.assertEqual(argv[:2], ["podman", "exec"])
self.assertEqual([argv[i + 1] for i, w in enumerate(argv) if w == "-e"][1:], ["HOME=/h", "NULLIUS_RELAY_KEY"])
self.assertEqual([argv[i + 1] for i, w in enumerate(argv) if w == "-e"][1:], ["HOME=/h", "IS_SANDBOX", "NULLIUS_RELAY_KEY", "NULLIUS_TASK_PATH"])
self.assertEqual((env.get("HOME"), env["NULLIUS_RELAY_KEY"]), (os.environ.get("HOME"), "placeholder"))

def _docker_ready() -> str:
Expand Down
8 changes: 6 additions & 2 deletions app/tests/test_swebench_patch.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ def git(self, *args):
return subprocess.check_output(["git", "-C", str(self.repo), *args], text=True)

def capture(self, env=None):
step = self.driver.setup("unit", str(self.root))["verify"]
setup = self.driver.setup("unit", str(self.root))
self.assertEqual(container.task_env_problems(setup.get("env", {})), [])
step = setup["verify"]
command = step["run"][-1].replace("/eval.sh", str(self.eval))
subprocess.run([*step["run"][:-1], command], check=True, capture_output=True, env=env)
self.assertEqual(step["collect"], self.driver.RESULTS)
Expand Down Expand Up @@ -168,7 +170,9 @@ def capture_is(self, command):
def check(self, tests):
"""The check's command run here, with ``tests`` as the task's test.sh: its exit code."""
self.tests.write_text(tests)
step = self.driver.setup("unit", str(self.root))["verify"]
setup = self.driver.setup("unit", str(self.root))
self.assertEqual(container.task_env_problems(setup.get("env", {})), [])
step = setup["verify"]
self.assertEqual(step["collect"], str(self.logs))
subprocess.run(step["capture"]["run"], check=True, capture_output=True)
self.git("reset", "--hard", "HEAD")
Expand Down
Loading