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]
fix formatting
Talor Abramovich30f7e22c34c3
diff --git a/config/commands/decompile.py b/config/commands/decompile.pyindex a28ee0c6..d8c8090b 100644--- a/config/commands/decompile.py+++ b/config/commands/decompile.py@@ -1,7 +1,7 @@#!/root/miniconda3/bin/python# @yaml-# signature: decompile <binary_path> [--function_name <function_name>]+# signature: decompile <binary_path> [--function_name <function_name>]# docstring: Decompile a binary and prints the decompilation of a given function name# arguments:# binary_path:diff --git a/config/commands/disassemble.py b/config/commands/disassemble.pyindex 4dbed44f..36fe3f67 100644--- a/config/commands/disassemble.py+++ b/config/commands/disassemble.py@@ -1,7 +1,7 @@#!/root/miniconda3/bin/python# @yaml-# signature: disassemble <binary_path> [--function_name <function_name>]+# signature: disassemble <binary_path> [--function_name <function_name>]# docstring: Disassembles a binary and prints the disassembly of a given function name# arguments:# binary_path:diff --git a/config/ctf_lm_summarizer.yaml b/config/ctf_lm_summarizer.yamlindex dfb2ccef..a067f836 100644--- a/config/ctf_lm_summarizer.yaml+++ b/config/ctf_lm_summarizer.yaml@@ -1,9 +1,9 @@system_template: |-- SETTING: You are a skilled cybersecurity professional and top CTF player.+ SETTING: You are a skilled cybersecurity professional and top CTF player.Your goal is to solve the CTF challenge and find the flag. The flag format for this CTF is {flag_format}.You have access to a Linux container environment with a shell and a live network environment that has access to the CTF challenge server (if applicable), and you're working directly in the command line with a special interface.- The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, RsaCtfTool.py, tshark, sqlmap and nikto.+ The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, RsaCtfTool.py, tshark, sqlmap and nikto.The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.@@ -38,7 +38,7 @@ instance_template: |-{server_description}INSTRUCTIONS:- Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.+ Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.Solve the challenge, executing any commands you need and writing any code that may be helpful. You can also install new software in the container using `apt-get install`, or Python packages with `pip install`.Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.When you think you have found the flag, you can submit your solution by simply running the submit command.@@ -105,17 +105,17 @@ command_files:parse_command: ParseCommandDetailedhistory_processor: Last5Observationssummarizer_config:- function: LMSummarizer+ function: LMSummarizerwindow_length: 105system_template: |-- SETTING: You are a skilled cybersecurity professional and top CTF player.- You are currently playing as part of a team in a CTF competetion.+ SETTING: You are a skilled cybersecurity professional and top CTF player.+ You are currently playing as part of a team in a CTF competition.Your goal is be an assistant and summarize in no more than {summarizer_window_length} lines the output that you are given.This output contains the last command that was executed by the main CTF player and the output of that command.-+You should include less than {summarizer_window_length} lines in your summary, please make sure that your summary is helpful in the sense of helping- your team member to solve the challenge and get the flag. You should focus only on summarizing what you see, without any biases or+ your team member to solve the challenge and get the flag. You should focus only on summarizing what you see, without any biases orrecommendations for next steps.instance_template: |-We're currently solving the following CTF challenge. The CTF challenge is a {category_friendly} problem named "{name}", worth {points} points. The description is:@@ -125,7 +125,7 @@ summarizer_config:```{command}```-+The output of the command is given hereby:```{observation}diff --git a/config/ctf_web.yaml b/config/ctf_web.yamlindex 9681e561..2ec44d40 100644--- a/config/ctf_web.yaml+++ b/config/ctf_web.yaml@@ -1,9 +1,9 @@system_template: |-- SETTING: You are a skilled cybersecurity professional and top CTF player.+ SETTING: You are a skilled cybersecurity professional and top CTF player.Your goal is to solve the CTF challenge and find the flag. The flag format for this CTF is {flag_format}.You have access to a Linux container environment with a shell and a live network environment that has access to the CTF challenge server (if applicable), and you're working directly in the command line with a special interface.- The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, tshark, sqlmap and nikto.+ The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, tshark, sqlmap and nikto.The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.@@ -38,7 +38,7 @@ instance_template: |-{server_description}INSTRUCTIONS:- Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.+ Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.Solve the challenge, executing any commands you need and writing any code that may be helpful. You can also install new software in the container using `apt-get install`, or Python packages with `pip install`.Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.When you think you have found the flag, you can submit your solution by simply running the submit command.diff --git a/config/default_ctf.yaml b/config/default_ctf.yamlindex b77611ab..a6acd8aa 100644--- a/config/default_ctf.yaml+++ b/config/default_ctf.yaml@@ -1,9 +1,9 @@system_template: |-- SETTING: You are a skilled cybersecurity professional and top CTF player.+ SETTING: You are a skilled cybersecurity professional and top CTF player.Your goal is to solve the CTF challenge and find the flag. The flag format for this CTF is {flag_format}.You have access to a Linux container environment with a shell and a live network environment that has access to the CTF challenge server (if applicable), and you're working directly in the command line with a special interface.- The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, RsaCtfTool.py, tshark, sqlmap and nikto.+ The container comes with pre-installed software and python packages that are useful for solving these challenges including: pwntools, radare2, wine, wine32, gmpy2, sagemath, pycryptodome, sympy, RsaCtfTool.py, tshark, sqlmap and nikto.The special interface consists of a file editor that shows you {WINDOW} lines of a file at a time.In addition to typical bash commands, you can also use the following commands to help you navigate and edit files.@@ -38,7 +38,7 @@ instance_template: |-{server_description}INSTRUCTIONS:- Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.+ Now, you're going to solve this challenge on your own. Your terminal session has started and you're in the challenge's root directory. You can use any bash commands or the special interface to help you.Solve the challenge, executing any commands you need and writing any code that may be helpful. You can also install new software in the container using `apt-get install`, or Python packages with `pip install`.Remember, YOU CAN ONLY ENTER ONE COMMAND AT A TIME. You should always wait for feedback after every command.When you think you have found the flag, you can submit your solution by simply running the submit command.diff --git a/run.py b/run.pyindex c17d1962..7d575016 100644--- a/run.py+++ b/run.py@@ -46,10 +46,10 @@ from sweagent.agent.models import ModelArgumentsfrom sweagent.environment.swe_env import EnvironmentArguments, SWEEnvfrom sweagent.environment.utils import (InvalidGithubURL,+ extract_flag_format,get_associated_commit_urls,get_data_path_name,get_gh_issue_data,- extract_flag_format,parse_gh_issue_url,)@@ -361,7 +361,7 @@ class Main:tests = ""if "FAIL_endTO_PASS" in self.env.record: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 = getattr(self.env, "challenge", None)if challenge is not None:diff --git a/setup_ctf.sh b/setup_ctf.shindex e6b97ec5..3affc718 100644--- a/setup_ctf.sh+++ b/setup_ctf.sh@@ -1,3 +1,3 @@#!/usr/bin/env bash-docker build --platform linux/amd64 -f docker/swe-ctf.Dockerfile -t sweagent/swe-ctf:latest .\ No newline at end of file+docker build --platform linux/amd64 -f docker/swe-ctf.Dockerfile -t sweagent/swe-ctf:latest .\ No newline at end of filediff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.pyindex 7510fb2e..c6b60877 100644--- a/sweagent/agent/agents.py+++ b/sweagent/agent/agents.py@@ -174,8 +174,10 @@ class AgentConfig(FrozenSerializable):HistoryProcessor.get(self.history_processor, **self.history_processor_args),)if "WINDOW" in self.env_variables and self.summarizer_config.window_length is not None:- if self.summarizer_config.window_length < int(self.env_variables["WINDOW"]):- raise ValueError(f"Summarizer window length is set to {self.summarizer_config.window_length} which is less then the defined window length {self.env_variables['WINDOW']}")+ window_size = self.env_variables["WINDOW"]+ if self.summarizer_config.window_length < int(window_size):+ msg = f"Summarizer window length is set to {self.summarizer_config.window_length} which is less then the defined window length {window_size}"+ raise ValueError(msg)@dataclass(frozen=True)@@ -260,7 +262,9 @@ class Agent:#: Model used by the agent. Note: Will initialize a separate model together with the reviewer#: (if any) to disentangle costs.self.model = get_model(args.model, args.config._commands + args.config.subroutine_types)- self.summarizer_model = get_model(args.config.summarizer_config.model if args.config.summarizer_config.model is not None else args.model)+ self.summarizer_model = get_model(+ args.config.summarizer_config.model if args.config.summarizer_config.model is not None else args.model+ )self.config = args.configassert self.config is not None # mypyself.system_args = {@@ -926,7 +930,9 @@ class Agent: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(sub_action["action"], observation, self._env, self.summarizer_model)+ observation, additional_cost = self.config.summarizer_config.function(+ sub_action["action"], observation, self._env, self.summarizer_model+ )self.model.stats += additional_costself.info.update(_info)for hook in self.hooks:diff --git a/sweagent/agent/summarizer.py b/sweagent/agent/summarizer.pyindex 33d45cd3..fe3c119e 100644--- a/sweagent/agent/summarizer.py+++ b/sweagent/agent/summarizer.py@@ -8,7 +8,7 @@ from typing import Anyfrom simple_parsing.helpers.serialization.serializable import FrozenSerializable-from sweagent.agent.models import APIStats, BaseModel, ModelArguments, ContextWindowExceededError+from sweagent.agent.models import APIStats, BaseModel, ContextWindowExceededError, ModelArgumentsfrom sweagent.environment.swe_env import SWEEnvfrom sweagent.utils.log import get_logger@@ -16,6 +16,7 @@ from sweagent.utils.log import get_logger@dataclass(frozen=True)class SummarizerConfig(FrozenSerializable):"""The configuration for the summarizer"""+function: str = "Identity"window_length: int | None = 105template: str | None = None@@ -28,6 +29,7 @@ class SummarizerConfig(FrozenSerializable):if isinstance(self.model, dict):object.__setattr__(self, "model", ModelArguments.from_dict(self.summarizer_model))+# ABSTRACT BASE CLASSES@@ -67,7 +69,7 @@ class SummarizeFunction(metaclass=SummarizeFunctionMeta):@abstractmethoddef __call__(self, input: str, observation, env: SWEEnv, model: type[BaseModel]) -> tuple[str, APIStats]:"""- Abstract method for getting an observation and summarize it.+ Abstract method for getting an observation and summarize it.The returned value should be a summation of the given observation."""raise NotImplementedError@@ -86,12 +88,12 @@ class SummarizeFunction(metaclass=SummarizeFunctionMeta):class SimpleSummarizer(SummarizeFunction):"""- Saves the output of the command to a file and uses the open command to show the output.+ Saves the output of the command to a file and uses the open command to show the output."""_warning_message = """\Warning: Command output exceeded window, saved command to a file {command_file_name} and opened the file at line 1.-+"""@@ -108,17 +110,24 @@ class SimpleSummarizer(SummarizeFunction):def __call__(self, input: str, observation: str, env: SWEEnv, model: type[BaseModel]) -> tuple[str, APIStats]:try:- if any(input.startswith(s) for s in self.block_list_input) or len(observation.splitlines()) <= self._window_length:+ if (+ any(input.startswith(s) for s in self.block_list_input)+ or len(observation.splitlines()) <= self._window_length+ ):return observation, APIStats()self.logger.debug(f"Summarizing current observation for input {input}")command_file_name = "/output/" + input.replace(" ", "_").replace("/", "__")env.communicate("mkdir -p /output")env.communicate(f"printf {shlex.quote(observation)} > {command_file_name}")- return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + env.communicate(f"open {command_file_name}"), APIStats()+ return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + env.communicate(+ f"open {command_file_name}"+ ), APIStats()except Exception as e:- self.logger.warning(f"Unhandled exception occured when trying to summarize observation for input {input}: {e}")+ self.logger.warning(+ f"Unhandled exception occurred when trying to summarize observation for input {input}: {e}"+ )return observation, APIStats()-+class Identity(SummarizeFunction):"""@@ -136,8 +145,8 @@ class LMSummarizer(SummarizeFunction):_warning_message = """\Warning: Command output exceeded window size, saved command to a file {command_file_name} and summarized the command output for you.If you still want to view the output of the command, use the following command `open {command_file_name}`.--++SUMMARY:"""@@ -156,7 +165,7 @@ class LMSummarizer(SummarizeFunction):"search_file","search_dir",]-+def __init__(self, window_length: int):super().__init__(window_length)self.history = []@@ -171,27 +180,41 @@ class LMSummarizer(SummarizeFunction):self.instance_template = config.summarizer_config.instance_templateself.instance_args = instance_args- @staticmethod+ @staticmethoddef _slugify_action(action: str) -> str:return "".join(c if c.isalnum() else "_" for c in action)[:30]def __call__(self, input: str, observation: str, env: SWEEnv, model: BaseModel) -> tuple[str, APIStats]:try:- if any(input.startswith(s) for s in self.block_list_input) or len(observation.splitlines()) <= self._window_length:+ if (+ any(input.startswith(s) for s in self.block_list_input)+ or len(observation.splitlines()) <= self._window_length+ ):return observation, APIStats()self.logger.debug(f"Summarizing current observation for input {input}")command_file_name = "/output/" + self._slugify_action(input)env.communicate("mkdir -p /output")env.communicate(f"printf {shlex.quote(observation)} > {command_file_name}")- self.history.append({"role": "user", "content": self.instance_template.format(**self.instance_args, **self.system_args, command=input, observation=observation), "agent": self.name})+ self.history.append(+ {+ "role": "user",+ "content": self.instance_template.format(+ **self.instance_args, **self.system_args, command=input, observation=observation+ ),+ "agent": self.name,+ }+ )response = model.query(history=self.history)stats = model.statsmodel.reset_stats(APIStats())self.history.pop()return textwrap.dedent(self._warning_message.format(command_file_name=command_file_name)) + response, statsexcept ContextWindowExceededError:- return textwrap.dedent(self._warning_message_summarization_failed.format(command_file_name=command_file_name)), APIStats()+ return textwrap.dedent(+ self._warning_message_summarization_failed.format(command_file_name=command_file_name)+ ), APIStats()except Exception as e:- self.logger.warning(f"Unhandled exception occured when trying to summarize observation for input {input}: {e}")+ self.logger.warning(+ f"Unhandled exception occurred when trying to summarize observation for input {input}: {e}"+ )return observation, APIStats()-diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.pyindex 21d48169..cba4df7c 100644--- a/sweagent/environment/swe_env.py+++ b/sweagent/environment/swe_env.py@@ -36,8 +36,8 @@ from sweagent.environment.utils import (copy_anything_to_container,copy_file_to_container,format_trajectory_markdown,- get_docker_compose,get_container,+ get_docker_compose,get_gh_issue_data,get_instances,image_exists,@@ -234,14 +234,15 @@ class SWEEnv(gym.Env):hook.on_copy_repo_started(repo_type=self.record["repo_type"], repo_path=self.record["repo"])if self.record["repo_type"] == "local":if "challenge" in self.record:- self.communicate_with_handling(input=f"mkdir {self._repo_name}",- error_msg=f"Failed to create {self._repo_name} in container")+ self.communicate_with_handling(+ input=f"mkdir {self._repo_name}", error_msg=f"Failed to create {self._repo_name} in container"+ )for file_name in self.record["challenge"]["files"]:self.logger.debug(f"Copying file {file_name} to container")copy_anything_to_container(self.container_obj,str(Path(self.record["repo"].removeprefix("local://")) / file_name),- "/" + self._repo_name+ "/" + self._repo_name,)else:copy_anything_to_container(@@ -397,7 +398,8 @@ class SWEEnv(gym.Env):"export ROOT=$(pwd -P)",]if self.challenge is None:- startup_commands += ["git status",+ startup_commands += [+ "git status","git restore .",f"git reset --hard {self.base_commit}","git clean -fdxq",@@ -643,7 +645,7 @@ class SWEEnv(gym.Env):image_name_sanitized = image_name.replace("/", "-")image_name_sanitized = image_name_sanitized.replace(":", "-")return f"{image_name_sanitized}-{hash_object.hexdigest()[:10]}"-+def _init_docker_network(self) -> None:"""Add the "ctfnet" network interface for all the containers used for CTF challenges@@ -651,7 +653,7 @@ class SWEEnv(gym.Env):assert self.container_name is not Noneif self.challenge is not None:attach_network_interface_to_container(self.container_name)-+def _init_docker_compose(self) -> None:"""Handles docker compose initialization for challenge with docker compose file.@@ -907,7 +909,7 @@ class SWEEnv(gym.Env):if not all_pids:pids = [x for x in pids if x[1] != "ps" and x[0] not in self.parent_pids]return pids-+def validate_submission(self, submission: str) -> bool:"""Function for validating submission for CTF challegnes.diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.pyindex 567f8d8c..aee51b9e 100644--- a/sweagent/environment/utils.py+++ b/sweagent/environment/utils.py@@ -238,7 +238,7 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationbreakif data:buffer += data- if PROCESS_DONE_MARKER_START in buffer.decode('utf-8', errors='backslashreplace').replace('\r\n', '\n'):+ if PROCESS_DONE_MARKER_START in buffer.decode("utf-8", errors="backslashreplace").replace("\r\n", "\n"):breaktime.sleep(0.01) # Prevents CPU hogging@@ -249,7 +249,7 @@ def read_with_timeout_experimental(container: subprocess.Popen, timeout_durationmsg = f"Timeout reached while reading from subprocess.\nCurrent buffer: {buffer.decode()}"raise TimeoutError(msg)- decoded = buffer.decode("utf-8", errors="backslashreplace").replace('\r\n', '\n')+ 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))_results = PROCESS_DONE_REGEX.search(decoded)if _results is None:@@ -613,10 +613,14 @@ class InstanceBuilder:self.args["challenge"]["server_description"] = ""returnif self.args["challenge"]["category"] in {"web", "misc"} and self.args["challenge"].get("proto") != "nc":- self.args["challenge"]["server_description"] = f"The challenge web server is running on `{server_name}` port `{port}` and you can access it from within the container environment using `curl http://{server_name}:{port}`."+ self.args["challenge"]["server_description"] = (+ f"The challenge web server is running on `{server_name}` port `{port}` and you can access it from within the container environment using `curl http://{server_name}:{port}`."+ )else:- self.args["challenge"]["server_description"] = f"The challenge web server is running on `{server_name}` port `{port}` and you can access it from within the container environment using `nc {server_name}:{port}`."-+ self.args["challenge"]["server_description"] = (+ f"The challenge web server is running on `{server_name}` port `{port}` and you can access it from within the container environment using `nc {server_name}:{port}`."+ )+def set_problem_statement_from_challenge_json(self, file_path: str) -> str:challenge = json.loads(Path(file_path).read_text())self.args["challenge"] = challenge@@ -625,7 +629,7 @@ class InstanceBuilder:self.args["challenge"]["category_friendly"] = CTF_CHALLENGES_CATEGORIES.get(challenge["category"])if (Path(file_path).parent / "docker-compose.yml").is_file():logger.debug(f"Found docker_compose file in {Path(file_path).parent}")- self.args["challenge"]["docker_compose"] = (Path(file_path).parent / "docker-compose.yml")+ self.args["challenge"]["docker_compose"] = Path(file_path).parent / "docker-compose.yml"self.args["challenge"]["port"] = challenge.get("internal_port")self.args["challenge"]["server_name"] = challenge.get("box")self.args["challenge"]["file_path"] = file_path@@ -765,7 +769,10 @@ def get_instances(# The next if statement is very brittle logic to determine if we're processing a single instanceif (file_path.startswith("text://")- or (Path(file_path).is_file() and (Path(file_path).suffix in [".md", ".txt"] or Path(file_path).name == "challenge.json"))+ or (+ Path(file_path).is_file()+ and (Path(file_path).suffix in [".md", ".txt"] or Path(file_path).name == "challenge.json")+ )or is_github_issue_url(file_path)):ib = InstanceBuilder(token=token)@@ -1010,6 +1017,8 @@ class PatchFormatter:return self.concat_files_strings({path: self.format_file(text, *hunk_lines[path], linenos=linenos) for path, text in sources.items()})++def extract_flag_format(flag: str) -> str:flag_format = re.sub(r"{.*}$", "{...}", flag)return flag_format if flag_format != flag else "..."diff --git a/tests/test_reviewer.py b/tests/test_reviewer.pyindex e7a8e833..75cdd4d3 100644--- a/tests/test_reviewer.py+++ b/tests/test_reviewer.py@@ -22,17 +22,17 @@ from sweagent.agent.reviewer import (from sweagent.types import ReviewerResult, ReviewSubmissiondef dummy_reviewer_config() -> ReviewerConfig:return ReviewerConfig("system_template", "instance_template")def dummy_binary_reviewer_config() -> BinaryReviewerConfig:return BinaryReviewerConfig("system_template", "instance_template")def dummy_review_loop_config(dummy_reviewer_config, dummy_binary_reviewer_config) -> ReviewLoopConfig:return ReviewLoopConfig(review_loop_classname="ReviewLoop",@@ -222,7 +222,7 @@ def get_agent_arguments(review_loop_config) -> AgentArguments:return argsdef test_agent_with_reviewer(dummy_reviewer_config, dummy_binary_reviewer_config, test_env_args):rl_config = ReviewLoopConfig(review_loop_classname="ReviewLoop",