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]
CombinedEnvHook; require_zero->check; fix output_dir in replay
Kilian Lieretffe107c443b8
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 3b437713..24d7c83d 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -671,7 +671,7 @@ class Agent:def _make_state_command_available(self) -> None:"""Define state command in the container"""assert self._env is not None- self._env.communicate(self.config.state_command.code, require_zero=True)+ self._env.communicate(self.config.state_command.code, check=True)def _make_commands_available(self) -> None:"""Make sure all commands are available in the container"""@@ -714,7 +714,7 @@ class Agent:commands = " && ".join(_env_setters)assert self._env is not Nonetry:- self._env.communicate(commands, require_zero=True)+ self._env.communicate(commands, check=True)except KeyboardInterrupt:raiseexcept Exception as e:@@ -728,7 +728,7 @@ class Agent:if not self.config.state_command:return {}assert self._env is not None- state = self._env.communicate(self.config.state_command.name, require_zero=True)+ state = self._env.communicate(self.config.state_command.name, check=True)try:return json.loads(state)except json.JSONDecodeError as e:diff --git a/sweagent/environment/hooks/abstract.py b/sweagent/environment/hooks/abstract.pyindex ba7e001c..1db69fe2 100644--- a/sweagent/environment/hooks/abstract.py+++ b/sweagent/environment/hooks/abstract.py@@ -1,4 +1,4 @@-from sweagent.environment.config.repo import RepoConfig+from sweagent.environment.config.repo import Repo, RepoConfigclass EnvHook:@@ -12,7 +12,7 @@ class EnvHook:def on_init(self, *, env) -> None:"""Gets called when the hook is added"""- def on_copy_repo_started(self, repo: RepoConfig) -> None:+ def on_copy_repo_started(self, repo: RepoConfig | Repo) -> None:"""Gets called when the repository is being cloned to the container"""def on_install_env_started(self) -> None:@@ -23,3 +23,31 @@ class EnvHook:def on_environment_startup(self) -> None:"""Called when the environment is started"""+++class CombinedEnvHooks(EnvHook):+ def __init__(self):+ self._hooks = []++ def add_hook(self, hook: EnvHook) -> None:+ self._hooks.append(hook)++ def on_init(self, *, env) -> None:+ for hook in self._hooks:+ hook.on_init(env=env)++ def on_copy_repo_started(self, repo: RepoConfig | Repo) -> None:+ for hook in self._hooks:+ hook.on_copy_repo_started(repo=repo)++ def on_install_env_started(self) -> None:+ for hook in self._hooks:+ hook.on_install_env_started()++ def on_close(self):+ for hook in self._hooks:+ hook.on_close()++ def on_environment_startup(self) -> None:+ for hook in self._hooks:+ hook.on_environment_startup()diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 3d3a7fe6..1f6609db 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -13,7 +13,7 @@ from swerex.runtime.abstract import BashAction, CreateBashSessionRequest, WriteFfrom sweagent.environment.config.deployment import DeploymentConfig, DockerDeploymentConfigfrom sweagent.environment.config.repo import Repo, RepoConfig-from sweagent.environment.hooks.abstract import EnvHook+from sweagent.environment.hooks.abstract import CombinedEnvHooks, EnvHookfrom sweagent.types import AgentInfofrom sweagent.utils.config import keys_configfrom sweagent.utils.log import get_logger@@ -58,15 +58,10 @@ class SWEEnv:self.logger = get_logger("swe_env", emoji="🌱")self.clean_multi_line_functions = lambda x: x- self._hooks: list[EnvHook] = []+ self._chook = CombinedEnvHooks()for hook in hooks or []:self.add_hook(hook)- def start(self) -> None:- """Start the environment"""- self._init_deployment()- self._init_scripts()-@classmethoddef from_config(cls, config: EnvironmentConfig) -> Self:return cls(@@ -75,10 +70,6 @@ class SWEEnv:startup_commands=config.startup_commands,)- @property- def hooks(self) -> list[EnvHook]:- return self._hooks-def add_hook(self, hook: EnvHook) -> None:"""Add `EnvHook` to the environment.@@ -86,22 +77,23 @@ class SWEEnv:lifecycle, in particular to connect SWE-agent to a new interface (like a GUI)."""hook.on_init(env=self)- self._hooks.append(hook)+ self._chook.add_hook(hook)- def _fire_hooks(self, hook_name: str, *args, **kwargs) -> None:- for hook in self.hooks:- getattr(hook, hook_name)(*args, **kwargs)+ def start(self) -> None:+ """Start the environment"""+ self._init_deployment()+ self._init_scripts()def _copy_repo(self) -> None:"""Clone/copy repository/codebase in container"""if self.repo is None:return- folders = self.communicate(input="ls").split("\n")+ folders = self.communicate(input="ls", check=True).split("\n")if self.repo.repo_name in folders:return- self._fire_hooks("on_copy_repo_started", self.repo)+ self._chook.on_copy_repo_started(repo=self.repo)self.repo.copy(self.deployment)# todo: Get rid of return type here?@@ -145,7 +137,7 @@ class SWEEnv:]self.communicate(input=" && ".join(startup_commands),- require_zero=True,+ check=True,error_msg="Failed to clean repository",)@@ -158,7 +150,7 @@ class SWEEnv:]self.communicate(input=" && ".join(cmd),- require_zero=True,+ check=True,error_msg="Failed to reset environment variables",)@@ -272,7 +264,7 @@ class SWEEnv:"""Shoutdown SWE-ReX deployment etc."""self.logger.info("Beginning environment shutdown...")asyncio.run(self.deployment.stop())- self._fire_hooks("on_close")+ self._chook.on_close()# MARK: Helper functions #@@ -296,17 +288,17 @@ class SWEEnv:"""Initialize custom commands within container"""self.communicate("mkdir -p /root/commands",- require_zero=True,+ check=True,error_msg="Failed to create commands directory",)self.communicate("touch /root/commands/__init__.py",- require_zero=True,+ check=True,error_msg="Failed to create __init__.py",)self.communicate("export PATH=$PATH:/root/commands",- require_zero=True,+ check=True,error_msg="Failed to add commands directory to PATH",)@@ -316,7 +308,7 @@ class SWEEnv:timeout: int | float = 25,*,set_last_action: bool = False,- require_zero: bool = False,+ check: bool = False,error_msg: str = "Command failed",) -> str:"""Executes a command in the running shell. The details of this are handled by@@ -326,7 +318,7 @@ class SWEEnv:input: input to send to containertimeout_duration: duration to wait for outputset_last_action: whether to set the LAST_ACTION environment variable- require_zero: whether to raise an error if the exit code is non-zero+ check: whether to raise an error if the exit code is non-zeroerror_msg: error message to raise if the command failsReturns:@@ -340,7 +332,7 @@ class SWEEnv:r = asyncio.run(self.deployment.runtime.run_in_session(BashAction(command=input, timeout=timeout)))output = r.outputself.logger.log(logging.TRACE, "Output:\n%s", output) # type: ignore- if (self._require_zero_exit_code or require_zero) and r.exit_code != 0:+ if (self._require_zero_exit_code or check) and r.exit_code != 0:self.logger.error(f"{error_msg}: {output}")self.close()msg = f"{error_msg} (command: {input})"@@ -378,7 +370,7 @@ class SWEEnv:def on_environment_startup(self) -> None:"""Creates conda environment and installs third party dependencies to allow code execution"""- self._fire_hooks("on_environment_startup")+ self._chook.on_environment_startup()def add_commands(self, commands: list[dict]) -> None:"""Adds custom commands to container"""@@ -391,7 +383,7 @@ class SWEEnv:if command["type"] == "source_file":self.communicate(f"source /root/commands/{name}",- require_zero=True,+ check=True,error_msg=(f"Failed to source {name}. If you meant to make a script,"" start the file with a shebang (e.g. #!/usr/bin/env python)."@@ -400,7 +392,7 @@ class SWEEnv:elif command["type"] == "script":self.communicate(f"chmod +x /root/commands/{name}",- require_zero=True,+ check=True,error_msg=f"Failed to chmod {name}",)elif command["type"] == "utility":diff --git a/sweagent/run/hooks/abstract.py b/sweagent/run/hooks/abstract.pyindex e349504f..ce89c6d0 100644--- a/sweagent/run/hooks/abstract.py+++ b/sweagent/run/hooks/abstract.py@@ -30,8 +30,8 @@ class RunHook:class CombinedRunHooks(RunHook):- def __init__(self, hooks: list[RunHook] | None = None):- self._hooks = hooks or []+ def __init__(self):+ self._hooks = []def add_hook(self, hook: RunHook) -> None:self._hooks.append(hook)diff --git a/sweagent/run/run_replay.py b/sweagent/run/run_replay.pyindex 2ac2bf94..1bcda19b 100644--- a/sweagent/run/run_replay.py+++ b/sweagent/run/run_replay.py@@ -90,7 +90,12 @@ class RunReplay:return Agent("replay", agent_config)def _get_run_single(self) -> RunSingle:- return RunSingle(self._get_env(), self._get_agent(), problem_statement=EmptyProblemStatement())+ return RunSingle(+ self._get_env(),+ self._get_agent(),+ problem_statement=EmptyProblemStatement(),+ traj_dir=Path(self.output_dir),+ )def main(self):self._create_actions_file()diff --git a/tests/test_env.py b/tests/test_env.pyindex 33c92d13..942cf3f2 100644--- a/tests/test_env.py+++ b/tests/test_env.py@@ -51,7 +51,7 @@ def test_env_with_hook(test_env_args):def test_env_communicate_with_handling(test_env_args):with swe_env_context(test_env_args) as env:env.reset()- env.communicate("echo 'hello world'", require_zero=True, error_msg="Failed to echo")+ env.communicate("echo 'hello world'", check=True, error_msg="Failed to echo")@pytest.mark.slow@@ -59,7 +59,7 @@ def test_env_communicate_with_handling_timeout(test_env_args):with swe_env_context(test_env_args) as env:env.reset()with pytest.raises(CommandTimeoutError):- env.communicate("sleep 10", require_zero=True, error_msg="Failed to sleep", timeout=0.2)+ env.communicate("sleep 10", check=True, error_msg="Failed to sleep", timeout=0.2)@pytest.mark.slow