Skip to content

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]

Merge branch 'talor-branch' into gdb

talorabrcc84b465621c
diff --cc config/default_ctf.yaml
index df733942,3532131d..790333a4
--- a/config/default_ctf.yaml
+++ b/config/default_ctf.yaml
@@@ -112,6 -107,6 +112,7 @@@ command_files
- config/commands/submit_ctf.sh
- config/commands/decompile.py
- config/commands/disassemble.py
+- config/commands/debug.sh
+ - config/commands/forfeit.sh
parse_command: ParseCommandDetailed
history_processor: Last5Observations
diff --cc sweagent/environment/swe_env.py
index 1f95ac95,50460a55..c399e5e3
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@@ -102,10 -95,8 +102,12 @@@ class EnvironmentArguments(FrozenSerial
environment_setup: str | None = None
# 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:
@@@ -634,12 -556,9 +642,12 @@@ class SWEEnv(gym.Env)
observation = submission if submission.strip() != "" else None
return observation, 0, True, info
else:
- self.logger.warning(f"Wrong submission found: {submission}")
+ self.logger.warning(f"Wrong submission found: {submission} (real flag is {self.challenge['flag']})")
observation = "Wrong flag!"
return observation, 0, False, info
+
+ observation = self._handle_interactive_commands(observation)
+
return observation, 0, False, info
def close(self) -> None:
@@@ -1075,41 -933,24 +1085,54 @@@
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
- return submission.strip() == self.challenge["flag"]
+ solution = self.challenge["flag"]
+ return any(
+ (
+ submission == solution,
+ wrap(submission) == solution,
+ submission == wrap(solution),
+ )
+ )
+
return True
+ def get_interactive_commands(self, output: str):
+ """
+ Function for extracting interactive session commands.
+
+ Args:
+ output: observation
+
+ Returns:
+ session: session name for the commands or None if no commands found.
+ commands: list of commands extracted from observation.
+ """
+ pattern = r"\<\<INTERACTIVE\|\|(.*)\|\|INTERACTIVE\>\>"
+ session_pattern = r"SESSION=(.*)"
+ session_name = ""
+ commands = []
+ for line in output.split("\n"):
+ match = re.search(pattern, line, re.DOTALL)
+ if match is None:
+ continue
+ command = match.group(1)
+ match = re.search(session_pattern, command, re.DOTALL)
+ if match is None:
+ commands.append(command)
+ else:
+ session_name = match.group(1)
+ if not session_name:
+ return None, []
+ else:
+ return session_name, commands
+
def get_submission(self, output: str) -> str | None:
"""
Function for extracting diff patch submission at the end of an episode.
diff --cc sweagent/environment/utils.py
index 71b1d66f,99156d87..cb93757f
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@@ -22,8 -22,8 +22,9 @@@ from git import InvalidGitRepositoryErr
from unidiff import PatchSet
import docker
+ import docker.types
from docker.models.containers import Container
+from sweagent.agent.interactive_commands import InteractiveSession
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
@@@ -407,20 -354,21 +408,34 @@@ def get_docker_compose(docker_compose_p
return docker_compose_path
+def get_interactive_session(ctr_name: str, cwd: str, session_name: str, *args) -> InteractiveSession:
+ """
+ Starts a new interacitve session on the given container name.
+ Returns a subprocess.Popen object that is available for further read/writes for submitting commands and reading output.
+ """
+ startup_cmd = ["docker", "exec", "-i", "-w", cwd, ctr_name, session_name, *args]
+ logger.debug(f"Starting interactive session {session_name} with command: {shlex.join(startup_cmd)}")
+ session = subprocess.Popen(startup_cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT, text=True, bufsize=1)
+ time.sleep(DOCKER_START_UP_DELAY)
+ _ = read_with_timeout(session, lambda: list(), timeout_duration=1)
+ return InteractiveSession(name=session_name, session_process=session)
+
+
- def _get_non_persistent_container(ctr_name: str, image_name: str) -> tuple[subprocess.Popen, set[str]]:
+ 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",