SWE-agent takes a GitHub issue and tries to automatically fix it, using your LM of choice. It can also be employed for offensive cybersecurity or competitive coding challenges. [NeurIPS 2024]
Remove lots of dead code
Kilian Lieret89aecfcc51ba
diff --git a/run.py b/run.pyindex 3d216918..f5d8e2ef 100644--- a/run.py+++ b/run.py@@ -45,7 +45,6 @@ from sweagent.agent.models import ModelArgumentsfrom sweagent.environment.swe_env import DeploymentConfig, EnvironmentArguments, SWEEnvfrom sweagent.environment.utils import (InvalidGithubURL,- extract_flag_format,get_associated_commit_urls,get_data_path_name,get_gh_issue_data,@@ -370,17 +369,17 @@ class Main:tests = "\n".join([f"- {x}" for x in self.env.record["FAIL_TO_PASS"]])setup_args = {"issue": issue, "files": files, "test_files": test_files, "tests": tests}- challenge = self.env.challenge- if challenge is not None:- setup_args["flag_format"] = extract_flag_format(challenge["flag"])- setup_args["name"] = challenge["name"]- setup_args["description"] = challenge["description"]- setup_args["category_friendly"] = challenge["category_friendly"]- setup_args["points"] = challenge["points"]- setup_args["files"] = challenge["files"] or "No files included in this challenge."- setup_args["box"] = challenge.get("server_name")- setup_args["port"] = challenge.get("port")- setup_args["server_description"] = challenge.get("server_description")+ # challenge = self.env.challenge+ # if challenge is not None:+ # setup_args["flag_format"] = extract_flag_format(challenge["flag"])+ # setup_args["name"] = challenge["name"]+ # setup_args["description"] = challenge["description"]+ # setup_args["category_friendly"] = challenge["category_friendly"]+ # setup_args["points"] = challenge["points"]+ # setup_args["files"] = challenge["files"] or "No files included in this challenge."+ # setup_args["box"] = challenge.get("server_name")+ # setup_args["port"] = challenge.get("port")+ # setup_args["server_description"] = challenge.get("server_description")info, trajectory = self.agent.run(setup_args=setup_args,env=self.env,@@ -388,6 +387,7 @@ class Main:traj_dir=self.traj_dir,return_type="info_trajectory",)+ challenge = Noneself._save_predictions(instance_id, info, challenge)for hook in self.hooks:hook.on_instance_completed(info=info, trajectory=trajectory)diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 5d4b91c5..bf750b80 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -31,20 +31,6 @@ from sweagent.utils.config import convert_paths_to_abspathfrom sweagent.utils.log import get_logger-@dataclass-class Subroutine:- name: str- agent_file: str- # one of "action", "observation", "response", "state", "thought"- return_type: str = None # type: ignore- init_observation: str | None = None- end_name: str | None = None- signature: str | None = None- docstring: str | None = None- model: ModelArguments | None = None- agent_args: Any | None = None--@dataclassclass AgentConfig:system_template: str = ""@@ -852,35 +838,6 @@ class Agent:env_vars[var] = env.communicate(f"echo ${var}").strip()return env_vars- def call_subroutine(self, agent_name: str, sub_action: SubAction, env: SWEEnv):- """Call subroutine"""- assert self.config is not None # mypy- env_vars = self.get_environment_vars(env)- cwd = env.communicate("pwd -P").strip()- init_observation = self.config._subroutines[agent_name].init_observation- if init_observation is not None:- obs, _, _, _ = env.step(init_observation.format(args=sub_action["args"]))- else:- obs = None- if env.returncode != 0:- self._append_history(HistoryItem({"role": "user", "content": obs, "agent": agent_name}))- msg = f"Nonzero return code: {env.returncode} for init_observation in {agent_name}.\n{obs}"- raise RuntimeError(msg)- return_type = self.config._subroutines[agent_name].return_type- sub_agent = Agent(agent_name, self.config._subroutines[agent_name].agent_args)- sub_agent_output = sub_agent.run(- {"issue": sub_action["args"]},- env,- observation=obs,- return_type=return_type,- init_model_stats=self.model.stats,- )- self.history += sub_agent.history- self.set_environment_vars(env, env_vars)- env.communicate(f"cd {cwd}")- self.model.stats.replace(sub_agent.model.stats)- return sub_agent_output-# def _update_summarizer_stats(self, cost: APIStats):# """Update stats for summarizer"""# self.model.stats += cost@@ -896,7 +853,6 @@ class Agent:def _run_sub_action(self, sub_action: SubAction) -> tuple[str | None, bool]:"""Execute a sub-action. If the sub-action is a command, execute it.- If it is a subroutine, call the subroutine.Returns:observation: Observation@@ -904,26 +860,21 @@ class Agent:"""assert self._env is not Noneassert self.config is not None- if sub_action["agent"] == self.name or sub_action["cmd_name"] == self.config.submit_command:- # Normal command, not a subroutine- for hook in self.hooks:- hook.on_sub_action_started(sub_action=sub_action)- observation, _, done, _info = self._env.step(sub_action["action"])- # observation, additional_cost = self.config.summarizer_config.function( # type: ignore- # sub_action["action"], observation, self._env, self.summarizer_model- # )- # self._update_summarizer_stats(additional_cost)- self.info.update(_info)- for hook in self.hooks:- hook.on_sub_action_executed(obs=observation, done=done)- if sub_action["cmd_name"] == self.config.submit_command:- done = True- else:- agent_name = sub_action["agent"]- sub_agent_output = self.call_subroutine(agent_name, sub_action, self._env)- observation = sub_agent_output- assert isinstance(observation, str) or observation is None- done = False++ # Normal command, not a subroutine+ for hook in self.hooks:+ hook.on_sub_action_started(sub_action=sub_action)+ observation, _, done, _info = self._env.step(sub_action["action"])+ # observation, additional_cost = self.config.summarizer_config.function( # type: ignore+ # sub_action["action"], observation, self._env, self.summarizer_model+ # )+ # self._update_summarizer_stats(additional_cost)+ self.info.update(_info)+ for hook in self.hooks:+ hook.on_sub_action_executed(obs=observation, done=done)+ if sub_action["cmd_name"] == self.config.submit_command:+ done = True+return observation, donedef _run_step(self, observation: str | None) -> tuple[str | None, bool]:diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex afcbf795..4831fb54 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -1,50 +1,40 @@from __future__ import annotationsimport asyncio-import hashlibimport logging-import osimport randomimport reimport shlex-import subprocessimport time-import tracebackfrom dataclasses import dataclass, fieldfrom pathlib import Path, PurePathfrom typing import Anyimport gymnasium as gym-import yamlfrom ghapi.all import GhApifrom git import Repo-from swebench.harness.constants import MAP_REPO_VERSION_TO_SPECS-from swebench.harness.utils import get_environment_yml, get_requirementsfrom swerex.deployment import get_deploymentfrom swerex.runtime.abstract import Action, CreateSessionRequest, UploadRequest, WriteFileRequestfrom sweagent import REPO_ROOT-from sweagent.agent.interactive_commands import (- INTERACTIVE_SESSIONS_CONFIG,- InteractiveSession,- InteractiveSessionConfig,-)++# from sweagent.agent.interactive_commands import (+# INTERACTIVE_SESSIONS_CONFIG,+# InteractiveSession,+# InteractiveSessionConfig,+# )from sweagent.environment.utils import (InvalidGithubURL,NoOutputTimeoutError,PatchFormatter,- attach_network_interface_to_container,- copy_file_to_container,format_trajectory_markdown,- get_docker_compose,get_gh_issue_data,get_instances,parse_gh_issue_url,- terminate_docker_compose,)from sweagent.types import AgentInfofrom sweagent.utils.config import keys_config-from sweagent.utils.log import default_logger, get_logger+from sweagent.utils.log import get_loggerLONG_TIMEOUT = float(keys_config.get("SWE_AGENT_ENV_LONG_TIMEOUT", 500))AGENT_ACTION_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_TIMEOUT", 25))@@ -77,14 +67,8 @@ class EnvironmentArguments:# Specify a branch name or a commit hash to checkout before running the task.# Only used when running over a single problem statement/issue.base_commit: str | None = None- # Use a persistent container with this name. After every task, the container will be paused, but not removed.- # This is useful for speedup when running multiple tasks from the same repositories in a row, as the repositories- # will have already been cloned and the conda environments will have been installed.- container_name: str | None = None# Try to install the environment before running the task.install_environment: bool = True- # No effect, kept for backwards compatibility.- timeout: int | None = None# Enable environment logger.verbose: bool = False# Do not use attempt to use a repository mirror from https://github.com/swe-bench.@@ -97,18 +81,9 @@ class EnvironmentArguments:# Only used when running on single issue. Path to local repository or github repository.repo_path: str = ""# Interactive command configuration- interactive_sessions_config: dict[str, InteractiveSessionConfig] = field(- default_factory=lambda: INTERACTIVE_SESSIONS_CONFIG- )- # Container mounts - additional folders to mount into the environment (useful for caching)- container_mounts: list[str] = field(default_factory=list)-- def __post_init__(self):- if self.timeout is not None:- default_logger.warning("The 'timeout' argument is deprecated and has no effect.")- if self.container_name is not None and self.container_name.strip() == "":- msg = "Set container_name to None if you don't want to use a persistent container."- raise ValueError(msg)+ # interactive_sessions_config: dict[str, InteractiveSessionConfig] = field(+ # default_factory=lambda: INTERACTIVE_SESSIONS_CONFIG+ # )class EnvHook:@@ -149,11 +124,8 @@ class SWEEnv(gym.Env):t0 = time.perf_counter()self.args = argsself.base_commit: str | None = None- self.container_name: str | None = args.container_nameself.install_environment = args.install_environmentself.logger = get_logger("SWEEnv")- self.persistent = args.container_name is not None- self.container_mounts = args.container_mountsself.returncode: None | int = Noneif not self.args.verbose:# fixme: This creates problems if we have multiple instances of this class@@ -185,11 +157,11 @@ class SWEEnv(gym.Env):self.logger.info(f"💽 Loaded dataset from {self.data_path}")# Establish connection with execution container- self.docker_compose: Path | None = None- self.challenge: dict[str, Any] | None = None+ # self.docker_compose: Path | None = None+ # self.challenge: dict[str, Any] | None = Noneself._reset_container()- self.interactive_session: InteractiveSession | None = None+ # self.interactive_session: InteractiveSession | None = Noneself.idx = 0self.clean_multi_line_functions = lambda x: x@@ -197,16 +169,6 @@ class SWEEnv(gym.Env):self.logger.debug("Environment initialization took %.2f seconds", time.perf_counter() - t0)- def _get_cached_task_image_name(self) -> str:- assert self.record is not None- inputs: list[str] = [- self.record["repo"],- self.record["base_commit"],- self.args.environment_setup or "no_setup",- ]- tag = hashlib.sha256("".join(inputs).encode()).hexdigest()[:50]- return f"{self.cached_image_prefix}{tag}"-def add_hook(self, hook: EnvHook):"""Add `EnvHook` to the environment.@@ -271,7 +233,7 @@ class SWEEnv(gym.Env):self.logger.info("Trying to clone from non-mirror...")clone_url = f"https://{token_prefix}github.com/{self.record['repo']}.git"clone_method = keys_config.get("SWE_AGENT_CLONE_METHOD", default="shallow", choices=["shallow", "full"])- if len(self.data) > 1 or self.persistent:+ if len(self.data) > 1:msg = "Falling back to full cloning method due to multiple instances or persistent container"clone_method = "full"self.logger.debug(msg)@@ -300,7 +262,7 @@ class SWEEnv(gym.Env):)return self._repo_name- def reset(self, index: int | None = None, apply_test_patch: bool = False) -> tuple[str | None, dict]:+ def reset(self, index: int | None = None) -> tuple[str | None, dict]:"""Function to reset container between each task instance.@@ -327,14 +289,14 @@ class SWEEnv(gym.Env):# Set query, gold commandself.base_commit = self.record["base_commit"]self.query = self.record["problem_statement"]- self.challenge = self.record.get("challenge")+ # self.challenge = self.record.get("challenge")self.reward = None### Reset Container ###- self._init_docker_compose()+ # self._init_docker_compose()# Init docker network- self._init_docker_network()+ # self._init_docker_network()# Clone repository if not already clonedself.communicate(input="cd /")@@ -362,13 +324,11 @@ class SWEEnv(gym.Env):)# Call install environment helper function if specified- if self.install_environment:- self.install_env()+ # if self.install_environment:+ self.on_environment_startup()# Install mypy for linting purposes# self.communicate_with_handling("pip install flake8", error_msg="Failed to install flake8 (lint library)")- if apply_test_patch:- self._apply_test_patch()# Write any metadata to info if necessaryreturn None, info@@ -379,13 +339,13 @@ class SWEEnv(gym.Env):f"cd /{self._repo_name}","export ROOT=$(pwd -P)",]- if self.challenge is None:- startup_commands += [- "git status",- "git restore .",- f"git reset --hard {self.base_commit}",- "git clean -fdxq",- ]+ # if self.challenge is None:+ startup_commands += [+ "git status",+ "git restore .",+ f"git reset --hard {self.base_commit}",+ "git clean -fdxq",+ ]self.communicate_with_handling(input=" && ".join(startup_commands),error_msg="Failed to clean repository",@@ -414,27 +374,6 @@ class SWEEnv(gym.Env):self._reset_repository()self._reset_environment_variables()- def _apply_test_patch(self):- """- Apply test patch for oracle setting- """- # needs updating, but do we really need this?- raise NotImplementedError()- assert self.record is not None- path_to_patch = "test.patch"- with open(path_to_patch, "w") as f:- f.write(self.record["test_patch"])- subprocess.run(- f"docker cp {path_to_patch} {self.container_name}:/root/test.patch",- shell=True,- check=False,- )- self.communicate_with_handling(- input="git apply /root/test.patch",- error_msg="Failed to apply test patch correctly",- )- os.remove(path_to_patch)-def _get_edited_files_with_context(self, patch: str) -> dict[str, str]:"""Get the edited files with context from the patch"""pf = PatchFormatter(patch, read_method=self.read_file) if patch else None@@ -446,20 +385,20 @@ class SWEEnv(gym.Env):out[f"edited_files{context_length}"] = valuereturn out- def _terminate_interactive_session(self, session_name: str):- if not self.interactive_session:- # Maybe fixing #772- return- try:- self.interactive_session.session_process.terminate()- self.communicate(self.interactive_session.config.exit_command)- except Exception as e:- msg = (- f"Failed to terminate interactive session {session_name}: {e}."- "\nHere's the full traceback\n" + traceback.format_exc()- )- self.logger.warning(msg)- self.interactive_session = None+ # def _terminate_interactive_session(self, session_name: str):+ # if not self.interactive_session:+ # # Maybe fixing #772+ # return+ # try:+ # self.interactive_session.session_process.terminate()+ # self.communicate(self.interactive_session.config.exit_command)+ # except Exception as e:+ # msg = (+ # f"Failed to terminate interactive session {session_name}: {e}."+ # "\nHere's the full traceback\n" + traceback.format_exc()+ # )+ # self.logger.warning(msg)+ # self.interactive_session = Nonedef _handle_interactive_commands(self, observation: str) -> str:"""Handle interactive commands in the environment, essentially substituting dummy@@ -629,19 +568,19 @@ class SWEEnv(gym.Env):# Record submission and end episode if `submit` keyword foundsubmission = self.get_submission(observation)if submission is not None:- if self.validate_submission(submission):- self.logger.info(f"Found submission: {submission}")- info["exit_status"] = "submitted"- info["submission"] = submission if submission.strip() != "" else None- info.update(self._get_edited_files_with_context(patch=submission)) # type: ignore- observation = submission if submission.strip() != "" else None- return observation, 0, True, info- else:- # Currently only validating CTF challenges- assert self.challenge is not None- self.logger.warning(f"Wrong submission found: {submission} (real flag is {self.challenge['flag']})")- observation = "Wrong flag!"- return observation, 0, False, info+ # if self.validate_submission(submission):+ self.logger.info(f"Found submission: {submission}")+ info["exit_status"] = "submitted"+ info["submission"] = submission if submission.strip() != "" else None+ info.update(self._get_edited_files_with_context(patch=submission)) # type: ignore+ observation = submission if submission.strip() != "" else None+ return observation, 0, True, info+ # else:+ # # Currently only validating CTF challenges+ # assert self.challenge is not None+ # self.logger.warning(f"Wrong submission found: {submission} (real flag is {self.challenge['flag']})")+ # observation = "Wrong flag!"+ # return observation, 0, False, infoobservation = self._handle_interactive_commands(observation)@@ -659,15 +598,15 @@ class SWEEnv(gym.Env):# MARK: Helper functions #def _reset_container(self) -> None:- if self.docker_compose is not None:- try:- terminate_docker_compose(self.docker_compose)- except KeyboardInterrupt:- raise- except:- self.logger.warning("Failed to terminate docker compose", exc_info=True)- else:- self.logger.debug("Terminated docker compose")+ # if self.docker_compose is not None:+ # try:+ # terminate_docker_compose(self.docker_compose)+ # except KeyboardInterrupt:+ # raise+ # except:+ # self.logger.warning("Failed to terminate docker compose", exc_info=True)+ # else:+ # self.logger.debug("Terminated docker compose")self._init_container()self._init_scripts()@@ -676,22 +615,22 @@ class SWEEnv(gym.Env):self._reset_container()# ctf- def _init_docker_network(self) -> None:- """- Add the "ctfnet" network interface for all the containers used for CTF challenges- """- if self.challenge is not None:- assert self.container_name is not None- attach_network_interface_to_container(self.container_name)+ # def _init_docker_network(self) -> None:+ # """+ # Add the "ctfnet" network interface for all the containers used for CTF challenges+ # """+ # if self.challenge is not None:+ # assert self.container_name is not None+ # attach_network_interface_to_container(self.container_name)# ctf- def _init_docker_compose(self) -> None:- """- Handles docker compose initialization for challenge with docker compose file.- """- if self.challenge is not None and self.challenge.get("docker_compose") is not None:- self.docker_compose = get_docker_compose(self.challenge["docker_compose"])- self.logger.info("🌱 Initialized docker compose for challenge")+ # def _init_docker_compose(self) -> None:+ # """+ # Handles docker compose initialization for challenge with docker compose file.+ # """+ # if self.challenge is not None and self.challenge.get("docker_compose") is not None:+ # self.docker_compose = get_docker_compose(self.challenge["docker_compose"])+ # self.logger.info("🌱 Initialized docker compose for challenge")def _init_container(self, cached_image: str | None = None) -> None:"""@@ -808,33 +747,33 @@ class SWEEnv(gym.Env):return []# ctf- def validate_submission(self, submission: str) -> bool:- """- Function for validating submission for CTF challenges.-- Args:- submission: extracted submission-- Returns:- validation of the submission found against known flag- """- submission = submission.strip()-- def wrap(s: str) -> str:- return f"flag{{{s}}}"-- if self.challenge is not None:- assert "flag" in self.challenge- solution = self.challenge["flag"]- return any(- (- submission == solution,- wrap(submission) == solution,- submission == wrap(solution),- )- )-- return True+ # def validate_submission(self, submission: str) -> bool:+ # """+ # Define this function if you can check whether a submission is correct.++ # Args:+ # submission: extracted submission++ # Returns:+ # validation of the submission found against known flag+ # """+ # submission = submission.strip()++ # def wrap(s: str) -> str:+ # return f"flag{{{s}}}"++ # if self.challenge is not None:+ # assert "flag" in self.challenge+ # solution = self.challenge["flag"]+ # return any(+ # (+ # submission == solution,+ # wrap(submission) == solution,+ # submission == wrap(solution),+ # )+ # )++ # return Truedef get_submission(self, output: str) -> str | None:"""@@ -852,217 +791,11 @@ class SWEEnv(gym.Env):return Nonereturn match.group(1)- def run_shell_script(self, script_path: Path, *, location: str) -> None:- """Run custom script supplied by user at `script_path`-- Args:- script_path: path to script file- location: location of script file 'host' or 'container'- """- if location == "host":- return self._run_shell_script_host(script_path)- elif location == "container":- raise NotImplementedError- msg = f"Invalid 'location': {location}"- raise ValueError(msg)-- def _run_shell_script_host(self, script_path: Path) -> None:- """Run shell script file (located on host) in container"""- if not script_path.is_file():- msg = f"Script not found at {script_path}"- raise FileNotFoundError(msg)- shell_commands = Path(script_path).read_text().splitlines(keepends=True)- for i, cmd in enumerate(shell_commands):- self.communicate_with_handling(- cmd,- error_msg=f"Failed to execute line {i}.",- timeout_duration=LONG_TIMEOUT,- )-- def _get_install_configs(self) -> dict | None:- """Return config for environment setup"""- assert self.record is not None # mypy- if (- self.record["problem_statement_source"] != "swe-bench" or self.record["repo_type"] == "local"- ) and self.args.environment_setup is None:- self.logger.warning(- "install_environment is set to True, but the data path is a GitHub URL "- "without an environment config file (environment_config key/flag). "- "Skipping conda environment installation.",- )- return None- if self.args.environment_setup is not None:- assert isinstance(self.args.environment_setup, (str, os.PathLike))- if Path(self.args.environment_setup).suffix in [".yml", ".yaml"]:- try:- return yaml.safe_load(Path(self.args.environment_setup).read_text())- except Exception as e:- msg = "Environment config file needs to be a yaml file"- raise ValueError(msg) from e- elif Path(self.args.environment_setup).suffix == ".sh":- return {- "shell_script_path": self.args.environment_setup,- }- else:- msg = "Environment config file needs to be a yaml file or shell script"- raise ValueError(msg)- else:- try:- return MAP_REPO_VERSION_TO_SPECS[self.record["repo"]][str(self.record["version"])]- except KeyError as e:- msg = (- "Tried to look up install configs in swe-bench, but failed. "- "You can set a custom environment config with the environment_config key/flag."- )- raise ValueError(msg) from e-- def _conda_environment_exists(self, env_name: str) -> bool:- env_check = self.communicate(f"conda env list | grep {env_name}", timeout_duration=LONG_TIMEOUT)- return env_check.strip() != ""-- def install_env(self) -> None:+ def on_environment_startup(self) -> None:"""Creates conda environment and installs third party dependencies to allow code execution"""- return- t0 = time.perf_counter()- for hook in self.hooks:- hook.on_install_env_started()- install_configs = self._get_install_configs()- if not install_configs:- return- if "shell_script_path" in install_configs:- assert len(install_configs) == 1- self.run_shell_script(Path(install_configs["shell_script_path"]), location="host")- return- assert self.record is not None # mypy- # Create environment if does not exist yet- env_name = f"{self._repo_name}__{self.record['version']}"- if not self._conda_environment_exists(env_name):- self.logger.info(f"{env_name} conda env not found, creating...")- packages = install_configs.get("packages", "")- if packages == "requirements.txt":- # Create conda environment- self.communicate_with_handling(- f"conda create -n {env_name} python={install_configs['python']} -y",- error_msg="Failed to create conda environment",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Created conda environment")- # Write reqs to requirements.txt in docker container- content_reqs = get_requirements(self.record)- copy_file_to_container(self.container_obj, content_reqs, PATH_TO_REQS)- # Create conda environment + install reqs- self.communicate_with_handling(- f"conda activate {env_name}",- error_msg="Failed to activate conda environment",- )- self.communicate_with_handling(- f"pip install -r {PATH_TO_REQS}",- error_msg="Failed to install requirements.txt",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Installed requirements from requirements.txt")- self.communicate(f"rm {PATH_TO_REQS}")- elif packages == "environment.yml":- # Write environment.yml to file- content_env_yml = get_environment_yml(self.record, env_name)- # Hotfix for- if not install_configs.get("no_use_env"):- content_env_yml += f'\n - python={install_configs["python"]}\n'- copy_file_to_container(self.container_obj, content_env_yml, PATH_TO_ENV_YML)- if install_configs.get("no_use_env"):- # Create conda environment- self.communicate_with_handling(- f"conda create -c conda-forge -n {env_name} python={install_configs['python']} -y",- error_msg="Failed to create conda environment",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Created conda environment")- # Install packages- self.communicate_with_handling(- f"conda env update -f {PATH_TO_ENV_YML}",- error_msg="Failed to install environment.yml",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Installed packages from environment.yml")- else:- # Create environment + install packages- self.communicate_with_handling(- f"conda env create --file {PATH_TO_ENV_YML}",- error_msg="Failed to create conda environment with environment.yml",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Created conda environment with environment.yml")- self.communicate(f"rm {PATH_TO_ENV_YML}")- else:- python_env = f"python{install_configs['python']}"- if self._conda_environment_exists(python_env):- self.communicate_with_handling(- f"conda create --name {env_name} --clone {python_env}",- error_msg="Failed to clone conda environment",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Cloned python conda environment")- else:- self.logger.debug(f"Could not find {python_env}, creating new environment")- self.communicate_with_handling(- f"conda create -n {env_name} python={install_configs['python']} -y",- error_msg="Failed to create conda environment",- timeout_duration=LONG_TIMEOUT,- )- self.communicate_with_handling(- f"conda activate {env_name}",- error_msg="Failed to activate conda environment",- )- if packages.strip():- self.communicate_with_handling(- f"conda install {packages} -y",- error_msg="Failed to install packages",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Installed conda packages")- # Install extra pip packages if specified- if install_configs.get("pip_packages"):- self.communicate_with_handling(- f"source activate {env_name} && pip install {' '.join(install_configs['pip_packages'])}",- error_msg="Failed to install pip packages",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Installed extra pip dependencies")-- # Activate environment- self.communicate_with_handling(f"conda activate {env_name}", error_msg="Failed to activate conda environment")-- # Install repo at base commit- if install_configs.get("pre_install"):- self.logger.info("Running pre-install commands...")- for pre_install_cmd in install_configs["pre_install"]:- self.communicate_with_handling(- pre_install_cmd,- error_msg="Pre-install commands failed to execute successfully",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Ran pre-install commands")- self.logger.info(f"Installing {self._repo_name} at base commit...")- if install_configs.get("install"):- install_cmd = install_configs["install"]- self.communicate_with_handling(- install_cmd,- error_msg="Install command failed to execute successfully",- timeout_duration=LONG_TIMEOUT,- )- self.logger.debug("Ran install command")- if install_configs.get("post_install"):- self.logger.info("Running post-install commands...")- for post_install_cmd in install_configs["post_install"]:- self.communicate_with_handling(- post_install_cmd,- error_msg="Post-install commands failed to execute successfully",- )- self.logger.debug("Ran post-install commands")-- self.logger.info("Installation step took %.2f seconds", time.perf_counter() - t0)+ passdef add_commands(self, commands: list[dict]) -> None:"""diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex e0a94436..0bbbf823 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -3,17 +3,8 @@ from __future__ import annotationsimport hashlibimport jsonimport os-import platformimport re-import shlex-import subprocess-import tarfile-import tempfile-import time-import traceback-from io import BytesIOfrom pathlib import Path-from subprocess import PIPE, STDOUTfrom typing import Any, Callablefrom datasets import load_dataset, load_from_disk@@ -21,9 +12,6 @@ from ghapi.all import GhApifrom git import InvalidGitRepositoryError, Repofrom unidiff import PatchSet-import docker-import docker.types-from docker.models.containers import Containerfrom sweagent.utils.config import keys_configfrom sweagent.utils.log import get_logger@@ -73,131 +61,6 @@ def is_github_repo_url(data_path: str) -> bool:return GITHUB_REPO_URL_PATTERN.search(data_path) is not None-# TODO: Why not just use copy_anything_to_container?-def copy_file_to_container(container: Container, contents: str, container_path: str) -> None:- """- Copies a given string into a Docker container at a specified path.-- Args:- container: Docker SDK container object.- contents: The string to copy into the container.- container_path: The path inside the container where the string should be copied to.-- Returns:- None- """- temp_file_name = None-- try:- # Create a temporary file- with tempfile.NamedTemporaryFile(delete=False) as temp_file:- temp_file_name = temp_file.name- # Write the string to the temporary file and ensure it's written to disk- temp_file.write(contents.encode("utf-8"))- temp_file.flush()- os.fsync(temp_file.fileno())-- # Create a TAR archive in memory containing the temporary file- with tempfile.NamedTemporaryFile():- with open(temp_file_name, "rb") as temp_file:- # Prepare the TAR archive- with BytesIO() as tar_stream:- with tarfile.open(fileobj=tar_stream, mode="w") as tar:- tar_info = tarfile.TarInfo(name=Path(container_path).name)- tar_info.size = Path(temp_file_name).stat().st_size- tar.addfile(tarinfo=tar_info, fileobj=temp_file)- tar_stream.seek(0)- # Copy the TAR stream to the container- container.put_archive(path=Path(container_path).parent, data=tar_stream.read())-- except Exception as e:- logger.error(f"An error occurred: {e}")- logger.error(traceback.format_exc())- finally:- # Cleanup: Remove the temporary file if it was created- if temp_file_name and Path(temp_file_name).exists():- os.remove(temp_file_name)---def copy_anything_to_container(container: Container, host_path: str, container_path: str) -> None:- """Copy files or directories from host to container-- Note: Will need to set ownership on the copied files in the container.- """- if not Path(host_path).exists():- msg = f"Path {host_path} does not exist, cannot copy it to container."- raise FileNotFoundError(msg)- cmd = ["docker", "cp", host_path, f"{container.id}:{container_path}"]- logger.debug(f"Copying {host_path} to container at {container_path} with command: {shlex.join(cmd)}")- try:- subprocess.run(cmd, check=True)- except subprocess.CalledProcessError as e:- msg = f"Error copying {host_path} to container at {container_path}: {e}"- raise RuntimeError(msg) from e---def read_with_timeout(container: subprocess.Popen, pid_func: Callable, timeout_duration: int | float) -> str:- """- Read data from a subprocess with a timeout.- This function uses a file descriptor to read data from the subprocess in a non-blocking way.-- Args:- container: The subprocess container.- pid_func: A function that returns a list of process IDs (except the PID of the main process).- timeout_duration: The timeout duration in seconds.-- Returns:- output: The data read from the subprocess, stripped of trailing newline characters.-- Raises:- TimeoutError: If the timeout duration is reached while reading from the subprocess.- """- buffer = b""- fd = container.stdout.fileno()- end_time = time.time() + timeout_duration-- # Select is not available on windows- is_windows = platform.system() == "Windows"- if not is_windows:- import select- else:- os.set_blocking(fd, False)-- def ready_to_read(fd) -> bool:- if is_windows:- # We can't do the extra check- return True- return bool(select.select([fd], [], [], 0.01)[0])-- while time.time() < end_time:- pids = pid_func()- if len(pids) > 0:- # There are still PIDs running- time.sleep(0.05)- continue- if ready_to_read(fd):- data = os.read(fd, 4096)- if data:- buffer += data- else:- # No more data to read- break- time.sleep(0.05) # Prevents CPU hogging-- if container.poll() is not None:- msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {buffer.decode()}"- raise RuntimeError(msg)- if time.time() >= end_time:- msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}\nRunning PIDs: {pids}"- raise TimeoutError(msg)-- decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")- return "\n".join(line for line in decoded.splitlines())---PROCESS_DONE_MARKER_START = "///PROCESS-DONE:"-PROCESS_DONE_MARKER_END = ":PROCESS-DONE///"-PROCESS_DONE_REGEX = re.compile(rf"{PROCESS_DONE_MARKER_START}(.+?){PROCESS_DONE_MARKER_END}")DECODED_BUFFER_FAILURE_THRESHOLD = 0.1@@ -214,423 +77,74 @@ def _check_for_too_many_non_unicode_bytes(buffer: bytes):raise UnicodeError(msg)-def read_with_timeout_experimental(- container: subprocess.Popen, timeout_duration: int | float, no_output_timeout_duration: int | float-) -> tuple[str, str]:- """- Read data from a subprocess with a timeout.- This function uses a file descriptor to read data from the subprocess in a non-blocking way.-- NOTE: This is an experimental implementation that is faster than `read_with_timeout`, but- has not been thoroughly tested.-- Args:- container: The subprocess container.- timeout_duration: The timeout duration in seconds.- no_output_timeout_duration: The timeout duration to wait if no output is produced, in seconds.-- Returns:- Output and exit code, both as strings (!)-- Raises:- TimeoutError: If the timeout duration is reached while reading from the subprocess.- """- buffer = b""- fd = container.stdout.fileno()- start_time = time.time()- end_time = start_time + timeout_duration- end_time_no_output = start_time + no_output_timeout_duration-- # Select is not available on windows- is_windows = platform.system() == "Windows"- if not is_windows:- import select- else:- os.set_blocking(fd, False)-- def ready_to_read(fd) -> bool:- if is_windows:- # We can't do the extra check- return True- return bool(select.select([fd], [], [], 0.01)[0])-- process_done = False-- while time.time() < min(end_time, end_time_no_output):- if ready_to_read(fd):- try:- data = os.read(fd, 4096)- except BlockingIOError:- logger.error("BlockingIOError while reading from subprocess.", exc_info=True)- break- if data:- end_time_no_output = time.time() + no_output_timeout_duration- buffer += data- if PROCESS_DONE_MARKER_START in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):- process_done = True- break- time.sleep(0.01) # Prevents CPU hogging-- decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")- body = "\n".join(line for line in decoded.splitlines() if not line.startswith(PROCESS_DONE_MARKER_START))-- if container.poll() is not None:- msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {decoded}"- raise RuntimeError(msg, body)-- current_time = time.time()- if not process_done and current_time >= min(end_time, end_time_no_output):- if current_time >= end_time:- msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"- raise TimeoutError(msg, body)- else:- msg = f"No output timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"- raise NoOutputTimeoutError(msg, body)-- _check_for_too_many_non_unicode_bytes(buffer=buffer)- _results = PROCESS_DONE_REGEX.search(decoded)- if _results is None:- msg = f"Could not find process done marker in last line: {decoded=}, {body=}"- raise ValueError(msg)- exit_code = _results.group(1)- return body.replace(f"{PROCESS_DONE_MARKER_START}{exit_code}{PROCESS_DONE_MARKER_END}", ""), exit_code---def read_session_with_timeout(- session: subprocess.Popen,- terminal_pattern: str,- timeout_duration: int | float,- no_output_timeout_duration: int | float,-) -> str:- """- Read data from a subprocess with a timeout.- This function uses a file descriptor to read data from the subprocess in a non-blocking way.-- Args:- session: The session subprocess.- terminal_pattern: the terminal pattern to indicate end of output.- timeout_duration: The timeout duration in seconds.-- Returns:- Output-- Raises:- TimeoutError: If the timeout duration is reached while reading from the subprocess.- """- buffer = b""- fd = session.stdout.fileno()- start_time = time.time()- end_time = start_time + timeout_duration- end_time_no_output = start_time + no_output_timeout_duration-- # Select is not available on windows- import select-- def ready_to_read(fd) -> bool:- return bool(select.select([fd], [], [], 0.01)[0])-- command_done = False- while time.time() < min(end_time, end_time_no_output) and session.poll() is None:- if ready_to_read(fd):- try:- data = os.read(fd, 4096)- except BlockingIOError:- logger.error("BlockingIOError while reading from subprocess.", exc_info=True)- break- if data:- end_time_no_output = time.time() + no_output_timeout_duration- buffer += data- if terminal_pattern in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):- command_done = True- break- time.sleep(0.01) # Prevents CPU hogging-- decoded = buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n")- body = "\n".join(line for line in decoded.splitlines() if not line.startswith(terminal_pattern))-- if session.poll() is not None:- msg = f"Subprocess exited unexpectedly.\nCurrent buffer: {decoded}"- raise RuntimeError(msg, body)- current_time = time.time()- if not command_done and current_time >= min(end_time, end_time_no_output):- if current_time >= end_time:- msg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"- raise TimeoutError(msg, body)- else:- msg = f"No output timeout reached while reading from subprocess.\nCurrent buffer: {decoded}"- raise NoOutputTimeoutError(msg, body)-- return body---def get_background_pids(container_obj: Container):- pids = container_obj.exec_run("ps -eo pid,comm --no-headers").output.decode().split("\n")- pids = [x.split() for x in pids if x]- pids = [x for x in pids if x[1] not in {"ps"} and x[0] != "1"]- bash_pids = [x for x in pids if x[1] == "bash"]- other_pids = [x for x in pids if x[1] not in {"bash"}]- return bash_pids, other_pids---def terminate_docker_compose(docker_compose_path: Path) -> None:- terminate_cmd = [- "docker",- "compose",- "-f",- str(docker_compose_path),- "down",- ]- logger.debug("Terminating docker-compose with command: %s", shlex.join(terminate_cmd))- compose = subprocess.Popen(- terminate_cmd,- stdin=PIPE,- stdout=PIPE,- stderr=STDOUT,- text=True,- bufsize=1, # line buffered- )- _, error = compose.communicate(timeout=DOCKER_COMPOSE_TERMINATION_DELAY)- if error:- logger.error(f"Unexpected compose termination error: {error}")---def attach_network_interface_to_container(container_name: str) -> None:- cmd = [- "docker",- "network",- "connect",- "ctfnet",- container_name,- ]- logger.debug("Attaching NIC to container with command: %s", shlex.join(cmd))- compose = subprocess.Popen(- cmd,- stdin=PIPE,- stdout=PIPE,- stderr=STDOUT,- text=True,- bufsize=1, # line buffered- )- _, error = compose.communicate(timeout=DOCKER_START_UP_DELAY)- if error:- logger.error(f"Unexpected compose setup error: {error}")- raise RuntimeError(error)---def get_docker_compose(docker_compose_path: Path) -> Path:- startup_cmd = [- "docker",- "compose",- "-f",- str(docker_compose_path),- "up",- "-d",- "--force-recreate",- ]- logger.debug("Starting docker-compose with command: %s", shlex.join(startup_cmd))- compose = subprocess.Popen(- startup_cmd,- stdin=PIPE,- stdout=PIPE,- stderr=STDOUT,- text=True,- bufsize=1, # line buffered- )- _, error = compose.communicate(timeout=DOCKER_COMPOSE_STARTUP_DELAY)- if error:- logger.error(f"Unexpected compose setup error: {error}")- return docker_compose_path---def _get_container_mounts_list(container_mounts: list[str]) -> list[docker.types.Mount]:- try:- for i in range(len(container_mounts)):- path = Path(container_mounts[i]).absolute()- if path.is_dir():- container_mounts[i] = docker.types.Mount(source=str(path), target=f"/{path.name}")- return container_mounts- except Exception:- logger.warning("Failed to process container mounts, skipping mount.")- return []---def _get_non_persistent_container(- ctr_name: str, image_name: str, container_mounts: list[str]-) -> tuple[subprocess.Popen, set[str]]:- startup_cmd = [- "docker",- "run",- "-i",- "--rm",- *[item for mount in container_mounts for item in ("-v", f"{Path(mount).absolute()}:/{Path(mount).name}")],- "--name",- ctr_name,- image_name,- "/bin/bash",- "-l",- ]- logger.debug("Starting container with command: %s", shlex.join(startup_cmd))- container = subprocess.Popen(- startup_cmd,- stdin=PIPE,- stdout=PIPE,- stderr=STDOUT,- text=True,- bufsize=1, # line buffered- )- time.sleep(DOCKER_START_UP_DELAY)- # try to read output from container setup (usually an error), timeout if no output- output = read_with_timeout(container, lambda: list(), timeout_duration=2)- if output:- logger.error(f"Unexpected container setup output: {output}")- # bash PID is always 1 for non-persistent containers- return container, {- "1",- }---def _get_persistent_container(- ctr_name: str, image_name: str, container_mounts: list[str], persistent: bool = False-) -> tuple[subprocess.Popen, set[str]]:- client = docker.from_env()- containers = client.containers.list(all=True, filters={"name": ctr_name})- if ctr_name in [c.name for c in containers]:- container_obj = client.containers.get(ctr_name)- if container_obj.status in {"created"}:- container_obj.start()- elif container_obj.status in {"running"}:- pass- elif container_obj.status in {"exited"}:- container_obj.restart()- elif container_obj.status in {"paused"}:- container_obj.unpause()- else:- msg = f"Unexpected container status: {container_obj.status}"- raise RuntimeError(msg)- else:- container_mounts = _get_container_mounts_list(container_mounts)- container_obj = client.containers.run(- image_name,- command="/bin/bash -l -m",- name=ctr_name,- stdin_open=True,- tty=True,- detach=True,- auto_remove=not persistent,- mounts=container_mounts,- )- container_obj.start()- startup_cmd = [- "docker",- "exec",- "-i",- ctr_name,- "/bin/bash",- "-l",- ]- logger.debug("Starting container with command: %s", shlex.join(startup_cmd))- container = subprocess.Popen(- startup_cmd,- stdin=PIPE,- stdout=PIPE,- stderr=STDOUT,- text=True,- bufsize=1, # line buffered- )- time.sleep(DOCKER_START_UP_DELAY)- # try to read output from container setup (usually an error), timeout if no output- output = read_with_timeout(container, lambda: list(), timeout_duration=2)- if output:- logger.error(f"Unexpected container setup output: {output}")- # Get the process IDs of the container- # There should be at least a head process and possibly one child bash process- bash_pids, other_pids = get_background_pids(container_obj)- total_time_slept = DOCKER_START_UP_DELAY- # Let's wait for a maximum of 5 x DOCKER_START_UP_DELAY seconds- # and then check again.- while len(bash_pids) > 1 or len(other_pids) > 0:- time.sleep(1)- total_time_slept += 1- bash_pids, other_pids = get_background_pids(container_obj)- if total_time_slept > 5 * DOCKER_START_UP_DELAY:- break- bash_pid = 1- if len(bash_pids) == 1:- bash_pid = bash_pids[0][0]- elif len(bash_pids) > 1 or len(other_pids) > 0:- msg = (- "Detected alien processes attached or running. Please ensure that no other agents "- f"are running on this container. PIDs: {bash_pids}, {other_pids}"- )- raise RuntimeError(msg)- return container, {str(bash_pid), "1"}---def get_container(- ctr_name: str, image_name: str, container_mounts: list[str], persistent: bool = False-) -> tuple[subprocess.Popen, set]:- """- Get a container object for a given container name and image name-- Arguments:- ctr_name (str): Name of container- image_name (str): Name of image- persistent (bool): Whether to use a persistent container or not- Returns:- Container object- """- if not image_exists(image_name):- msg = (- f"Image {image_name} not found. Please ensure it is built and available. "- "Please double-check that you followed all installation/setup instructions from the "- "readme."- )- raise RuntimeError(msg)-- if persistent:- return _get_persistent_container(ctr_name, image_name, container_mounts=container_mounts)- else:- return _get_non_persistent_container(ctr_name, image_name, container_mounts=container_mounts)---def image_exists(image_name: str) -> bool:- """- Check that the image exists and give some better error messages.-- Arguments:- image_name: Name of image- Returns:- bool: True if image exists- """- try:- client = docker.from_env()- except docker.errors.DockerException as e:- docker_not_running = any(- (- "connection aborted" in str(e).lower(),- "connection refused" in str(e).lower(),- "error while fetching server api version" in str(e).lower(),- ),- )- if docker_not_running:- msg = (- "Probably the Docker daemon is not running. Please start the Docker daemon and try again. "- "If Docker issues persist, please check out https://princeton-nlp.github.io/SWE-agent/installation/tips/"- )- raise RuntimeError(msg) from e- raise- filterred_images = client.images.list(filters={"reference": image_name})- if len(filterred_images) == 0:- return False- elif len(filterred_images) > 1:- RuntimeError(f"Multiple images found for {image_name}, that's weird.")- attrs = filterred_images[0].attrs- if attrs is not None:- logger.info(- f"Found image {image_name} with tags: {attrs['RepoTags']}, created: {attrs['Created']} "- f"for {attrs['Os']} {attrs['Architecture']}.",- )- return True+# def terminate_docker_compose(docker_compose_path: Path) -> None:+# terminate_cmd = [+# "docker",+# "compose",+# "-f",+# str(docker_compose_path),+# "down",+# ]+# logger.debug("Terminating docker-compose with command: %s", shlex.join(terminate_cmd))+# compose = subprocess.Popen(+# terminate_cmd,+# stdin=PIPE,+# stdout=PIPE,+# stderr=STDOUT,+# text=True,+# bufsize=1, # line buffered+# )+# _, error = compose.communicate(timeout=DOCKER_COMPOSE_TERMINATION_DELAY)+# if error:+# logger.error(f"Unexpected compose termination error: {error}")+++# def attach_network_interface_to_container(container_name: str) -> None:+# cmd = [+# "docker",+# "network",+# "connect",+# "ctfnet",+# container_name,+# ]+# logger.debug("Attaching NIC to container with command: %s", shlex.join(cmd))+# compose = subprocess.Popen(+# cmd,+# stdin=PIPE,+# stdout=PIPE,+# stderr=STDOUT,+# text=True,+# bufsize=1, # line buffered+# )+# _, error = compose.communicate(timeout=DOCKER_START_UP_DELAY)+# if error:+# logger.error(f"Unexpected compose setup error: {error}")+# raise RuntimeError(error)+++# def get_docker_compose(docker_compose_path: Path) -> Path:+# startup_cmd = [+# "docker",+# "compose",+# "-f",+# str(docker_compose_path),+# "up",+# "-d",+# "--force-recreate",+# ]+# logger.debug("Starting docker-compose with command: %s", shlex.join(startup_cmd))+# compose = subprocess.Popen(+# startup_cmd,+# stdin=PIPE,+# stdout=PIPE,+# stderr=STDOUT,+# text=True,+# bufsize=1, # line buffered+# )+# _, error = compose.communicate(timeout=DOCKER_COMPOSE_STARTUP_DELAY)+# if error:+# logger.error(f"Unexpected compose setup error: {error}")+# return docker_compose_pathdef get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):