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]

Splitting up env utils into separate files

Kilian Lieret76cd0050eda0
diff --git a/run.py b/run.py
index bfb8ef28..056255dd 100644
--- a/run.py
+++ b/run.py
@@ -15,7 +15,7 @@ import traceback
from argparse import ArgumentParser
from pprint import pprint
-from sweagent.main.hooks import MainHook
+from sweagent.main.hooks.abstract import MainHook
from sweagent.utils.log import add_file_handler, get_logger
try:
diff --git a/sweagent/agent/agents.py b/sweagent/agent/agents.py
index 1055a5ab..dbaf80bc 100644
--- a/sweagent/agent/agents.py
+++ b/sweagent/agent/agents.py
@@ -28,10 +28,11 @@ from sweagent.agent.parsing import FormatError, ParseFunction
# from sweagent.agent.summarizer import SummarizerConfig
from sweagent.environment.swe_env import SWEEnv
from sweagent.types import AgentInfo, History, HistoryItem, Trajectory, TrajectoryStep
-from sweagent.utils.config import convert_paths_to_abspath
+from sweagent.utils.config import _convert_paths_to_abspath
from sweagent.utils.log import get_logger
+# todo: factor out tools config and potentially try to only give it to SWEEnv. Agent should only need allow-lists and the final tools documentation
class AgentConfig(BaseModel):
system_template: str = ""
instance_template: str = ""
@@ -117,8 +118,8 @@ class AgentConfig(BaseModel):
return _commands
def model_post_init(self, __context):
- self.command_files = convert_paths_to_abspath(self.command_files)
- self.demonstrations = convert_paths_to_abspath(self.demonstrations)
+ self.command_files = _convert_paths_to_abspath(self.command_files)
+ self.demonstrations = _convert_paths_to_abspath(self.demonstrations)
if self.next_step_template is None:
self.next_step_template = self.instance_template
@@ -217,6 +218,7 @@ class SubAction(TypedDict):
args: str
+# todo: Can this class be split up into separate responsibilities?
class Agent:
"""Agent handles the behaviour of the model and how it interacts with the environment."""
@@ -474,6 +476,7 @@ class Agent:
matches = sorted(matches, key=lambda x: x.start())
return matches[0]
+ #: todo: Should that be a utility function??
def _guard_multiline_input(self, action: str) -> str:
"""Split action by multiline commands, then append the first line in each multiline command with "<< '{end_name}'".
Multiline commands (which are specified by an end_name) are commands that span multiple lines and are terminated by a specific end_name.
@@ -504,6 +507,7 @@ class Agent:
rem_action = ""
return "\n".join(parsed_action)
+ # todo: Do we still need that now that we don't have subroutines
def split_actions(self, action: str, pattern_type="subroutine") -> list[SubAction]:
"""Split an action into a list of actions in a greedy manner, each of which is a subroutine call or a single command."""
parsed_action: list[SubAction] = list()
diff --git a/sweagent/api/hooks.py b/sweagent/api/hooks.py
index 60ab0e43..e6fbcd09 100644
--- a/sweagent/api/hooks.py
+++ b/sweagent/api/hooks.py
@@ -12,7 +12,7 @@ from sweagent.environment.swe_env import EnvHook
# baaaaaaad
sys.path.append(str(PACKAGE_DIR.parent))
-from sweagent.main.hooks import MainHook
+from sweagent.main.hooks.abstract import MainHook
class StreamToSocketIO(io.StringIO):
diff --git a/sweagent/environment/swe_env.py b/sweagent/environment/swe_env.py
index 0bc705f7..1baea65c 100644
--- a/sweagent/environment/swe_env.py
+++ b/sweagent/environment/swe_env.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import logging
import os
import re
@@ -25,13 +26,12 @@ from swerex.runtime.abstract import BashAction, Command, CreateBashSessionReques
# )
from sweagent.environment.utils import (
NoOutputTimeoutError,
- PatchFormatter,
- get_problem_statement_from_github_issue,
- parse_gh_issue_url,
)
from sweagent.types import AgentInfo
+from sweagent.utils._github import get_problem_statement_from_github_issue, parse_gh_issue_url
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
+from sweagent.utils.patch_formatter import PatchFormatter
LONG_TIMEOUT = float(keys_config.get("SWE_AGENT_ENV_LONG_TIMEOUT", 500))
AGENT_ACTION_TIMEOUT = float(keys_config.get("SWE_AGENT_ACTION_TIMEOUT", 25))
@@ -50,8 +50,6 @@ class DockerDeploymentConfig(BaseModel):
class ModalDeploymentConfig(BaseModel):
image: str = "sweagent/swe-agent:latest"
- modal_username: str = "test"
-
type: Literal["modal"] = "modal"
"""Discriminator for serialization. Do not change."""
@@ -70,11 +68,14 @@ class EmptyInstanceConfig(BaseModel):
class TextInstanceConfig(BaseModel):
problem_statement: str = ""
- id: str = ""
type: Literal["text"] = "text"
"""Discriminator for serialization. Do not change."""
+ @property
+ def id(self) -> str:
+ return hashlib.sha256(self.problem_statement.encode()).hexdigest()[:6]
+
def get_problem_statement(self) -> str:
return self.problem_statement
@@ -85,6 +86,10 @@ class TextFileInstanceConfig(BaseModel):
type: Literal["text_file"] = "text_file"
"""Discriminator for serialization. Do not change."""
+ @property
+ def id(self) -> str:
+ return hashlib.sha256(self.get_problem_statement().encode()).hexdigest()[:6]
+
def get_problem_statement(self) -> str:
return Path(self.path).read_text()
@@ -98,7 +103,7 @@ class GithubInstanceConfig(BaseModel):
@property
def id(self) -> str:
org, repo, issue = self.issue_url.split("/")[-3:]
- return f"{org}__{repo}__{issue}"
+ return f"{org}__{repo}-i{issue}"
def get_problem_statement(self) -> str:
owner, repo, issue_number = parse_gh_issue_url(self.issue_url)
diff --git a/sweagent/environment/utils.py b/sweagent/environment/utils.py
index d1663be4..453e6299 100644
--- a/sweagent/environment/utils.py
+++ b/sweagent/environment/utils.py
@@ -2,16 +2,11 @@ from __future__ import annotations
import hashlib
import json
-import os
import re
-from collections.abc import Callable
from pathlib import Path
from typing import Any
from datasets import load_dataset, load_from_disk
-from ghapi.all import GhApi
-from git import InvalidGitRepositoryError, Repo
-from unidiff import PatchSet
from sweagent.utils.config import keys_config
from sweagent.utils.log import get_logger
@@ -50,18 +45,6 @@ def get_data_path_name(data_path: str) -> str:
return Path(data_path).stem
-def is_github_issue_url(data_path: str) -> bool:
- """Check if data_path is an URL pointing to a github issue"""
- return GITHUB_ISSUE_URL_PATTERN.search(data_path) is not None
-
-
-def is_github_repo_url(data_path: str) -> bool:
- """Check if data_path is an URL pointing to a github repository.
- Paths to issues or PRs will also match this pattern.
- """
- return GITHUB_REPO_URL_PATTERN.search(data_path) is not None
-
-
DECODED_BUFFER_FAILURE_THRESHOLD = 0.1
@@ -148,242 +131,9 @@ def _check_for_too_many_non_unicode_bytes(buffer: bytes):
# return docker_compose_path
-def get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
- """Get commit object from github api
-
- Args:
- api (GhApi):
- owner (str): Repo owner, e.g., "princeton-nlp"
- repo (str): Repo, e.g., "SWE-agent"
- ref (str, optional): Branch, tag or commit hash
-
- Returns:
- _type_: _description_
- """
- if ref:
- return api.repos.get_commit(owner, repo, ref)
- return api.repos.list_commits(owner, repo)[0]
-
-
class InvalidGithubURL(ValueError): ...
-def parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:
- """
- Returns:
- owner: Repo owner
- repo: Repo name
- issue number: Issue number as str
-
- Raises:
- InvalidGithubURL: If the URL is not a valid github issue URL
- """
- match = GITHUB_ISSUE_URL_PATTERN.search(issue_url)
- if not match:
- msg = f"Invalid GitHub issue URL: {issue_url}"
- raise InvalidGithubURL(msg)
- res = match.groups()
- assert len(res) == 3
- return tuple(res) # type: ignore
-
-
-def parse_gh_repo_url(repo_url: str) -> tuple[str, str]:
- """
- Returns:
- owner: Repo owner/org
- repo: Repo name
-
- Raises:
- InvalidGithubURL: If the URL is not a valid github repo URL
- """
- match = GITHUB_REPO_URL_PATTERN.search(repo_url)
- if not match:
- msg = f"Invalid GitHub issue URL: {repo_url}"
- raise InvalidGithubURL(msg)
- res = match.groups()
- assert len(res) == 2
- return tuple(res) # type: ignore
-
-
-def get_gh_issue_data(issue_url: str, *, token: str = ""):
- """Returns github issue data in the form of a dictionary.
- See https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
- for return format
- """
- owner, repo, issue_number = parse_gh_issue_url(issue_url)
- api = GhApi(token=token)
- return api.issues.get(owner, repo, issue_number)
-
-
-def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: str | None = "") -> str:
- """Return problem statement from github issue"""
- api = GhApi(token=token)
- issue = api.issues.get(owner, repo, issue_number)
- title = issue.title if issue.title else ""
- body = issue.body if issue.body else ""
- return f"{title}\n{body}\n"
-
-
-class InstanceBuilder:
- def __init__(self, token: str | None = None):
- """This helper class is used to build the data for an instance object,
- retrieving problem statements from github issues or local files and setting
- repo paths from github urls or local paths.
- """
- # Args that will be passed to the Instance constructor
- self.args = {}
- self.token = token
- self._instance_id_problem_suffix = ""
-
- def set_problem_statement_from_gh_issue(self, issue_url: str):
- owner, repo, issue_number = parse_gh_issue_url(issue_url)
- self.args["problem_statement"] = get_problem_statement_from_github_issue(
- owner,
- repo,
- issue_number,
- token=self.token,
- )
- self.args["instance_id"] = f"{owner}__{repo}-i{issue_number}"
- self.args["problem_statement_source"] = "online"
-
- def set_server_description(self, server_name: str | None, port: int | None) -> None:
- """For CTF challenges"""
- if server_name is None or port is None:
- self.args["challenge"]["server_description"] = ""
- return
- if 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}`."
- )
- 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 `connect_start {server_name} {port}`."
- )
-
- def set_problem_statement_from_challenge_json(self, file_path: str) -> None:
- """For CTF challenges"""
- challenge = json.loads(Path(file_path).read_text())
- self.args["challenge"] = challenge
- self.args["challenge"]["files"] = challenge.get("files", [])
- self.args["challenge"]["points"] = challenge.get("points", 10)
- 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"]["port"] = challenge.get("internal_port") or challenge.get("port")
- if "box" in challenge:
- self.args["challenge"]["server_name"] = challenge["box"] or "127.0.0.1"
- else:
- self.args["challenge"]["server_name"] = ""
- self.args["challenge"]["file_path"] = file_path
- self.set_server_description(self.args["challenge"]["server_name"], self.args["challenge"]["port"])
- self.set_problem_statement_from_text(f"{challenge['name']} {challenge['description']}")
- self.args["instance_id"] = (
- # sanitize 'name' to only alphanumeric characters
- challenge.get("category", "misc") + "_" + "".join(a for a in self.args["challenge"]["name"] if a.isalnum())
- )
-
- def set_problem_statement_from_file(self, file_path: str):
- if Path(file_path).name == "challenge.json":
- self.set_problem_statement_from_challenge_json(file_path)
- else:
- self.set_problem_statement_from_text(Path(file_path).read_text())
-
- def set_problem_statement_from_text(self, text: str):
- self.args["problem_statement"] = text
- self.args["instance_id"] = hashlib.sha256(self.args["problem_statement"].encode()).hexdigest()[:6]
- self.args["problem_statement_source"] = "local"
-
- def set_problem_statement(self, data_path: str):
- """Get problem statement for a single instance from a github issue url or a
- path to a markdown or text file.
- """
- if data_path.startswith("text://"):
- return self.set_problem_statement_from_text(data_path.removeprefix("text://"))
- if is_github_issue_url(data_path):
- return self.set_problem_statement_from_gh_issue(data_path)
- if Path(data_path).is_file():
- return self.set_problem_statement_from_file(data_path)
- msg = f"Not sure how to get problem statement from {data_path=}."
- raise ValueError(msg)
-
- def set_repo_info_from_gh_url(self, url: str, base_commit: str | None = None):
- owner, repo = parse_gh_repo_url(url)
- self.args["repo"] = f"{owner}/{repo}"
- self.args["repo_type"] = "github"
- # Always get commit hash, because base_commit can also be branch or tag
- api = GhApi(token=self.token)
- self.args["base_commit"] = get_commit(api, owner, repo, ref=base_commit).sha
- if base_commit != self.args["base_commit"]:
- logger.info(f"Base commit reference {base_commit} resolved to commit hash {self.args['base_commit']}")
- self.args["version"] = self.args["base_commit"][:7]
-
- def set_repo_info_from_local_path(self, path: str, base_commit: str | None = None):
- self.args["repo"] = str(Path(path).resolve())
- self.args["repo_type"] = "local"
- if base_commit:
- self.args["base_commit"] = base_commit
- else:
- try:
- repo = Repo(path, search_parent_directories=True)
- except InvalidGitRepositoryError as e:
- msg = f"Could not find git repository at {path=}."
- raise ValueError(msg) from e
- if repo.is_dirty() and "PYTEST_CURRENT_TEST" not in os.environ:
- msg = f"Local git repository {path} is dirty. Please commit or stash changes."
- raise ValueError(msg)
- self.args["base_commit"] = repo.head.object.hexsha
- self.args["version"] = self.args["base_commit"][:7]
-
- def set_repo_info(self, repo: str, base_commit: str | None = None):
- if is_github_repo_url(repo):
- self.set_repo_info_from_gh_url(repo, base_commit=base_commit)
- elif Path(repo).is_dir():
- self.set_repo_info_from_local_path(repo, base_commit=base_commit)
- else:
- msg = f"Could not determine repo path from {repo=}."
- raise ValueError(msg)
-
- def set_from_dict(self, instance_dict: dict[str, Any]):
- self.args |= instance_dict
-
- def set_missing_fields(self):
- # TODO: This field is only needed while swe_env is using some questionable logic
- # to determine whether to clone from a mirror or not. This should be removed in the future.
- # Values: 'swe-bench' (loaded from json/jsonl for swe-bench style inference),
- # 'online' (loaded from github issue or similar) or 'local' (loaded from local file)
- if "problem_statement_source" not in self.args:
- self.args["problem_statement_source"] = "swe-bench"
- if "repo_type" not in self.args:
- self.args["repo_type"] = "github"
-
- def validate(self):
- required_fields = [
- "problem_statement",
- "instance_id",
- "repo",
- "repo_type",
- "base_commit",
- "version",
- "problem_statement_source",
- ]
- if not all(x in self.args for x in required_fields):
- missing = set(required_fields) - set(self.args.keys())
- msg = f"Missing required fields: {missing=}"
- raise ValueError(msg)
- if self.args["repo_type"] not in {"github", "local"}:
- msg = f"Invalid repo type: {self.args['repo_type']=}"
- raise ValueError(msg)
- if self.args["repo_type"] == "github" and self.args["repo"].count("/") != 1:
- msg = f"Invalid repo format for {self.args['repo_type']=}: {self.args['repo']=}"
- raise ValueError(msg)
-
- def build(self) -> dict[str, Any]:
- self.set_missing_fields()
- self.validate()
- return self.args
-
-
def get_instances(
file_path: str,
base_commit: str | None = None,
@@ -403,9 +153,10 @@ def get_instances(
"""
def instance_from_dict(instances):
- ib = InstanceBuilder(token=token)
- ib.set_from_dict(instances)
- return ib.build()
+ raise NotImplementedError
+ # ib = InstanceBuilder(token=token)
+ # ib.set_from_dict(instances)
+ # return ib.build()
def postproc_instance_list(instances):
if isinstance(instances, dict):
@@ -414,26 +165,6 @@ def get_instances(
return [instance_from_dict(x) for x in instances]
# The next if statement is very brittle logic to determine if we're processing a single instance
- if (
- 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 is_github_issue_url(file_path)
- ):
- ib = InstanceBuilder(token=token)
- ib.set_problem_statement(file_path)
- if repo_path:
- ib.set_repo_info(repo_path, base_commit=base_commit)
- elif is_github_repo_url(file_path):
- ib.set_repo_info_from_gh_url(file_path, base_commit=base_commit)
- else:
- msg = f"Could not determine repo path from {file_path=}, {repo_path=}"
- raise ValueError(msg)
-
- return [ib.build()]
-
if base_commit:
msg = "base_commit must be empty if running over multiple problem statements"
raise ValueError(msg)
@@ -476,206 +207,3 @@ def get_instances(
"Please ensure --data_path is a GitHub URL, a SWE-bench HuggingFace dataset, or a JSON/JSONL file."
)
raise ValueError(msg) from e
-
-
-def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token: str = "") -> list[str]:
- """Return the URLs of commits that would close an issue."""
- api = GhApi(token=token)
- # Strangely the "pull_request" field of api.issues.get is often not set
- # so we have to go through the events to check if there's a commit
- events = api.issues.list_events(org, repo, issue_number)
- commit_urls = []
- for event in events:
- if event.event != "referenced":
- continue
- if not event.commit_id:
- continue
- commit = api.repos.get_commit(org, repo, event.commit_id)
- message = commit.commit.message
- if f"fixes #{issue_number}" in message.lower() or f"closes #{issue_number}" in message.lower():
- commit_urls.append(commit.html_url)
- return commit_urls
-
-
-def remove_triple_backticks(text: str) -> str:
- return "\n".join(line.removeprefix("```") for line in text.splitlines())
-
-
-def format_trajectory_markdown(trajectory: list[dict[str, str]]):
- """Format a trajectory as a markdown string for use in gh PR description."""
- prefix = [
- "<details>",
- "<summary>Thought process ('trajectory') of SWE-agent (click to expand)</summary>",
- "",
- "",
- ]
- steps = []
- for i, step in enumerate(trajectory):
- step_strs = [
- f"**πŸ§‘β€πŸš’ Response ({i})**: ",
- f"{step['response'].strip()}",
- f"**πŸ‘€β€ Observation ({i})**:",
- "```",
- f"{remove_triple_backticks(step['observation']).strip()}",
- "```",
- ]
- steps.append("\n".join(step_strs))
- suffix = [
- "",
- "</details>",
- ]
- return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
-
-
-class PatchFormatter:
- def __init__(
- self,
- patch: str,
- read_method: Callable[[str], str],
- ):
- """Given the final patch and access to the container that contains the repository,
- extract relevant lines from the modified file.
-
- Args:
- patch: The patch as a string.
- read_method: Callable with path to file (relative to repository root) as argument
- that returns the file content as a string.
- """
- self._patch = PatchSet(patch)
- self._patched_files: dict[str, str] = {}
- self._original_files: dict[str, str] = {}
- self._patch_applied = True
- self._read_file = read_method
- self._read_files(original=False)
-
- @staticmethod
- def _merge_intervals(starts: list[int], stops: list[int]) -> tuple[list[int], list[int]]:
- """Given two lists of integers, starts and stops, merges all overlapping intervals.
-
- For example `starts=[1, 5, 18]`, `stops=[10, 13, 20]`
- should return `starts=[1, 18]`, `stops=[13, 20]`
- """
- if not starts:
- assert not stops
- return [], []
-
- intervals = sorted(zip(starts, stops))
- merged = []
- for start, stop in intervals:
- if not merged or merged[-1][1] < start:
- # No overlap
- merged.append([start, stop])
- else:
- # Overlap
- merged[-1][1] = max(merged[-1][1], stop)
- # Unzip again
- merged_starts, merged_stops = zip(*merged)
- return list(merged_starts), list(merged_stops)
-
- def format_file(self, text: str, starts: list[int], stops: list[int], *, linenos: bool = True) -> str:
- """Reads file and returns string representation of the relevant lines.
-
- Args:
- path: The path to the file within the repo location
- starts: The starting line numbers of the relevant lines. The first line is line 1.
- stops: The stopping line numbers of the relevant lines. The stop is not inclusive.
- The first line is line 1.
- linenos: Whether to include line numbers
- """
- if not starts:
- assert not stops
- return ""
-
- assert len(starts) == len(stops)
- assert all(start >= 1 for start in starts)
- assert all(start < stop for start, stop in zip(starts, stops))
- starts, stops = self._merge_intervals(starts, stops)
- assert all(hunk1_start < hunk2_start for hunk1_start, hunk2_start in zip(starts, starts[1:]))
- out: list[str] = []
- if starts[0] > 1:
- # Count from 1
- out.append(f"[{starts[0]-1} lines above omitted]")
- last_stop: int | None = None
- lines = text.splitlines()
- for start, stop in zip(starts, stops):
- assert start >= 1
- if last_stop is not None:
- n_omitted = start - last_stop
- # Check that we have non-overlapping hunks
- assert n_omitted >= 0
- if n_omitted:
- out.append(f"\n[{n_omitted} lines omitted]\n")
- # Count from 1
- these_lines = lines[start - 1 : stop - 1]
- if linenos:
- out.append("\n".join([f"{i:6d}: {l}" for i, l in enumerate(these_lines, start=start)]))
- else:
- out.append("\n".join(these_lines))
- last_stop = stop
- if last_stop < len(lines):
- # Stop is not inclusive
- omitted = len(lines) - last_stop
- assert omitted > 0
- out.append(f"[{omitted} lines below omitted]")
- return "\n".join(out)
-
- def _get_hunk_lines(self, original: bool, *, context_length: int) -> dict[str, tuple[list[int], list[int]]]:
- """Get the starts and stops for all files in the patch.
-
- Args:
- original: Whether to read the original file or the patched file
- context_length: The number of lines to include above and below the hunk
-
- Returns:
- A dictionary with the file path as key and a tuple of lists of starts and stops as value.
- """
- out: dict[str, tuple[list[int], list[int]]] = {}
- for patch in self._patch:
- if not patch.is_modified_file:
- continue
- starts: list[int] = []
- stops: list[int] = []
- for hunk in patch:
- if original:
- # 1 is the lowest line number
- start = max(1, hunk.source_start - context_length)
- stop = hunk.source_start + hunk.source_length + context_length
- else:
- start = max(1, hunk.target_start - context_length)
- stop = hunk.target_start + hunk.target_length + context_length
- starts.append(start)
- stops.append(stop)
- out[patch.path] = (starts, stops)
- return out
-
- def _read_files(self, original: bool) -> None:
- for patch in self._patch:
- path = patch.path
- if not patch.is_modified_file:
- continue
- if original:
- msg = "Original file reading not implemented"
- raise NotImplementedError(msg)
- else:
- assert self._patch_applied
- self._patched_files[path] = self._read_file(path)
-
- @staticmethod
- def concat_files_strings(files: dict[str, str]) -> str:
- """Concatenate multiple `read_files` outputs into a single string."""
- out = []
- for path, content in files.items():
- out.append(f"[File: {path}]\n{content}")
- return "\n\n".join(out)
-
- def get_files_str(self, *, original: bool, context_length: int | None = 50, linenos: bool = True) -> str:
- hunk_lines = self._get_hunk_lines(original=original, context_length=context_length)
- sources = self._original_files if original else self._patched_files
- 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/sweagent/main/hooks.py b/sweagent/main/hooks.py
deleted file mode 100644
index de595b58..00000000
--- a/sweagent/main/hooks.py
+++ /dev/null
@@ -1,186 +0,0 @@
-import subprocess
-from pathlib import Path
-from typing import Any
-
-import rich
-
-from run import ScriptArguments, logger
-from sweagent.agent.agents import Agent
-from sweagent.environment.swe_env import SWEEnv
-from sweagent.environment.utils import (
- InvalidGithubURL,
- get_associated_commit_urls,
- get_gh_issue_data,
- parse_gh_issue_url,
-)
-
-
-class MainHook:
- """Hook structure for the web server or other addons to interface with"""
-
- @staticmethod
- def _is_promising_patch(info: dict[str, Any]) -> bool:
- """Do we actually believe that the patch will solve the issue?
- Or are we just submitting the last patch we generated before hitting an error?
- """
- # The exit status can also be `submitted (exit_cost)` etc.
- return info["exit_status"] == "submitted" and info.get("submission") is not None
-
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- """Called when hook is initialized"""
-
- def on_start(self):
- """Called at the beginning of `Main.main`"""
-
- def on_end(self):
- """Called at the end of `Main.main`"""
-
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- """Called at the beginning of each instance loop in `Main.run`"""
-
- def on_instance_skipped(
- self,
- ):
- """Called when an instance is skipped in `Main.run`"""
-
- def on_instance_completed(self, *, info, trajectory):
- """Called when an instance is completed in `Main.run`"""
-
-
-class SaveApplyPatchHook(MainHook):
- """This hook saves patches to a separate directory and optionally applies them to a local repository."""
-
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- self._traj_dir = traj_dir
- self._apply_patch_locally = args.actions.apply_patch_locally
- self._instance = None
-
- def on_instance_start(self, *, index: int, instance: dict[str, Any]):
- self._instance = instance
-
- def on_instance_completed(self, *, info, trajectory):
- assert self._instance is not None # mypy
- instance_id = self._instance["instance_id"]
- patch_path = self._save_patch(instance_id, info)
- if patch_path:
- if not self._apply_patch_locally:
- return
- if not self._is_promising_patch(info):
- return
- assert self._instance # mypy
- if self._instance["repo_type"] != "local":
- return
- local_dir = Path(self._instance["repo"])
- self._apply_patch(patch_path, local_dir)
-
- @staticmethod
- def _print_patch_message(patch_output_file: Path):
- console = rich.console.Console()
- msg = [
- "SWE-agent has produced a patch that it believes will solve the issue you submitted!",
- "Use the code snippet below to inspect or apply it!",
- ]
- panel = rich.panel.Panel.fit(
- "\n".join(msg),
- title="πŸŽ‰ Submission successful πŸŽ‰",
- )
- console.print(panel)
- content = [
- "```bash",
- "# The patch has been saved to your local filesystem at:",
- f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
- "# Inspect it:",
- 'cat "${PATCH_FILE_PATH}"',
- "# Apply it to a local repository:",
- "cd <your local repo root>",
- 'git apply "${PATCH_FILE_PATH}"',
- "```",
- ]
- console.print(rich.markdown.Markdown("\n".join(content)))
-
- def _save_patch(self, instance_id: str, info) -> Path | None:
- """Create patch files that can be applied with `git am`.
-
- Returns:
- The path to the patch file, if it was saved. Otherwise, returns None.
- """
- patch_output_dir = self._traj_dir / "patches"
- patch_output_dir.mkdir(exist_ok=True, parents=True)
- patch_output_file = patch_output_dir / f"{instance_id}.patch"
- if info.get("submission") is None:
- logger.info("No patch to save.")
- return None
- model_patch = info["submission"]
- patch_output_file.write_text(model_patch)
- if self._is_promising_patch(info):
- # Only print big congratulations if we actually believe
- # the patch will solve the issue
- self._print_patch_message(patch_output_file)
- return patch_output_file
-
- def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:
- """Apply a patch to a local directory."""
-
- assert local_dir.is_dir()
- assert patch_file.exists()
- # The resolve() is important, because we're gonna run the cmd
- # somewhere else
- cmd = ["git", "apply", str(patch_file.resolve())]
- try:
- subprocess.run(cmd, cwd=local_dir, check=True)
- except subprocess.CalledProcessError as e:
- logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")
- return
- logger.info(f"Applied patch {patch_file} to {local_dir}")
-
-
-class OpenPRHook(MainHook):
- """This hook opens a PR if the issue is solved and the user has enabled the option."""
-
- def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
- self._env = env
- self._token: str = env._github_token
- self._data_path = args.environment.data_path
- self._open_pr = args.actions.open_pr
- self._skip_if_commits_reference_issue = args.actions.skip_if_commits_reference_issue
-
- def on_instance_completed(self, *, info, trajectory):
- if self._open_pr and self.should_open_pr(info):
- self._env.open_pr(trajectory=trajectory)
-
- def should_open_pr(self, info: dict[str, Any]) -> bool:
- """Does opening a PR make sense?"""
- if not info.get("submission"):
- logger.info("Not opening PR because no submission was made.")
- return False
- if info["exit_status"] != "submitted":
- logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])
- return False
- try:
- issue = get_gh_issue_data(self._data_path, token=self._token)
- except InvalidGithubURL:
- logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
- return False
- if issue.state != "open":
- logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
- return False
- if issue.assignee:
- logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
- return False
- if issue.locked:
- logger.info("Issue is locked. Skipping PR creation.")
- return False
- org, repo, issue_number = parse_gh_issue_url(self._data_path)
- associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)
- if associated_commits:
- commit_url_strs = ", ".join(associated_commits)
- if self._skip_if_commits_reference_issue:
- logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
- return False
- else:
- logger.warning(
- "Proceeding with PR creation even though there are already commits "
- f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
- "or after verifying that the existing commits do not fix the issue.",
- )
- return True
diff --git a/sweagent/main/hooks/__init__.py b/sweagent/main/hooks/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/sweagent/main/hooks/abstract.py b/sweagent/main/hooks/abstract.py
new file mode 100644
index 00000000..e83976dd
--- /dev/null
+++ b/sweagent/main/hooks/abstract.py
@@ -0,0 +1,38 @@
+from pathlib import Path
+from typing import Any
+
+from run import ScriptArguments
+from sweagent.agent.agents import Agent
+from sweagent.environment.swe_env import SWEEnv
+
+
+class MainHook:
+ """Hook structure for the web server or other addons to interface with"""
+
+ @staticmethod
+ def _is_promising_patch(info: dict[str, Any]) -> bool:
+ """Do we actually believe that the patch will solve the issue?
+ Or are we just submitting the last patch we generated before hitting an error?
+ """
+ # The exit status can also be `submitted (exit_cost)` etc.
+ return info["exit_status"] == "submitted" and info.get("submission") is not None
+
+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
+ """Called when hook is initialized"""
+
+ def on_start(self):
+ """Called at the beginning of `Main.main`"""
+
+ def on_end(self):
+ """Called at the end of `Main.main`"""
+
+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):
+ """Called at the beginning of each instance loop in `Main.run`"""
+
+ def on_instance_skipped(
+ self,
+ ):
+ """Called when an instance is skipped in `Main.run`"""
+
+ def on_instance_completed(self, *, info, trajectory):
+ """Called when an instance is completed in `Main.run`"""
diff --git a/sweagent/main/hooks/apply_patch.py b/sweagent/main/hooks/apply_patch.py
new file mode 100644
index 00000000..e0217c69
--- /dev/null
+++ b/sweagent/main/hooks/apply_patch.py
@@ -0,0 +1,97 @@
+import subprocess
+from pathlib import Path
+from typing import Any
+
+import rich
+
+from run import ScriptArguments, logger
+from sweagent.agent.agents import Agent
+from sweagent.environment.swe_env import SWEEnv
+from sweagent.main.hooks.abstract import MainHook
+
+
+class SaveApplyPatchHook(MainHook):
+ """This hook saves patches to a separate directory and optionally applies them to a local repository."""
+
+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
+ self._traj_dir = traj_dir
+ self._apply_patch_locally = args.actions.apply_patch_locally
+ self._instance = None
+
+ def on_instance_start(self, *, index: int, instance: dict[str, Any]):
+ self._instance = instance
+
+ def on_instance_completed(self, *, info, trajectory):
+ assert self._instance is not None # mypy
+ instance_id = self._instance["instance_id"]
+ patch_path = self._save_patch(instance_id, info)
+ if patch_path:
+ if not self._apply_patch_locally:
+ return
+ if not self._is_promising_patch(info):
+ return
+ assert self._instance # mypy
+ if self._instance["repo_type"] != "local":
+ return
+ local_dir = Path(self._instance["repo"])
+ self._apply_patch(patch_path, local_dir)
+
+ @staticmethod
+ def _print_patch_message(patch_output_file: Path):
+ console = rich.console.Console()
+ msg = [
+ "SWE-agent has produced a patch that it believes will solve the issue you submitted!",
+ "Use the code snippet below to inspect or apply it!",
+ ]
+ panel = rich.panel.Panel.fit(
+ "\n".join(msg),
+ title="πŸŽ‰ Submission successful πŸŽ‰",
+ )
+ console.print(panel)
+ content = [
+ "```bash",
+ "# The patch has been saved to your local filesystem at:",
+ f"PATCH_FILE_PATH='{patch_output_file.resolve()}'",
+ "# Inspect it:",
+ 'cat "${PATCH_FILE_PATH}"',
+ "# Apply it to a local repository:",
+ "cd <your local repo root>",
+ 'git apply "${PATCH_FILE_PATH}"',
+ "```",
+ ]
+ console.print(rich.markdown.Markdown("\n".join(content)))
+
+ def _save_patch(self, instance_id: str, info) -> Path | None:
+ """Create patch files that can be applied with `git am`.
+
+ Returns:
+ The path to the patch file, if it was saved. Otherwise, returns None.
+ """
+ patch_output_dir = self._traj_dir / "patches"
+ patch_output_dir.mkdir(exist_ok=True, parents=True)
+ patch_output_file = patch_output_dir / f"{instance_id}.patch"
+ if info.get("submission") is None:
+ logger.info("No patch to save.")
+ return None
+ model_patch = info["submission"]
+ patch_output_file.write_text(model_patch)
+ if self._is_promising_patch(info):
+ # Only print big congratulations if we actually believe
+ # the patch will solve the issue
+ self._print_patch_message(patch_output_file)
+ return patch_output_file
+
+ def _apply_patch(self, patch_file: Path, local_dir: Path) -> None:
+ """Apply a patch to a local directory."""
+
+ assert local_dir.is_dir()
+ assert patch_file.exists()
+ # The resolve() is important, because we're gonna run the cmd
+ # somewhere else
+ cmd = ["git", "apply", str(patch_file.resolve())]
+ try:
+ subprocess.run(cmd, cwd=local_dir, check=True)
+ except subprocess.CalledProcessError as e:
+ logger.error(f"Failed to apply patch {patch_file} to {local_dir}: {e}")
+ return
+ logger.info(f"Applied patch {patch_file} to {local_dir}")
diff --git a/sweagent/main/hooks/open_pr.py b/sweagent/main/hooks/open_pr.py
new file mode 100644
index 00000000..c4b0800b
--- /dev/null
+++ b/sweagent/main/hooks/open_pr.py
@@ -0,0 +1,91 @@
+from pathlib import Path
+from typing import Any
+
+from run import ScriptArguments, logger
+from sweagent.agent.agents import Agent
+from sweagent.environment.swe_env import SWEEnv
+from sweagent.environment.utils import InvalidGithubURL
+from sweagent.main.hooks.abstract import MainHook
+from sweagent.utils._github import get_associated_commit_urls, get_gh_issue_data, parse_gh_issue_url
+
+
+class OpenPRHook(MainHook):
+ """This hook opens a PR if the issue is solved and the user has enabled the option."""
+
+ def on_init(self, *, args: ScriptArguments, agent: Agent, env: SWEEnv, traj_dir: Path):
+ self._env = env
+ self._token: str = env._github_token
+ self._data_path = args.environment.data_path
+ self._open_pr = args.actions.open_pr
+ self._skip_if_commits_reference_issue = args.actions.skip_if_commits_reference_issue
+
+ def on_instance_completed(self, *, info, trajectory):
+ if self._open_pr and self.should_open_pr(info):
+ self._env.open_pr(trajectory=trajectory)
+
+ def should_open_pr(self, info: dict[str, Any]) -> bool:
+ """Does opening a PR make sense?"""
+ if not info.get("submission"):
+ logger.info("Not opening PR because no submission was made.")
+ return False
+ if info["exit_status"] != "submitted":
+ logger.info("Not opening PR because exit status was %s and not submitted.", info["exit_status"])
+ return False
+ try:
+ issue = get_gh_issue_data(self._data_path, token=self._token)
+ except InvalidGithubURL:
+ logger.info("Currently only GitHub is supported to open PRs to. Skipping PR creation.")
+ return False
+ if issue.state != "open":
+ logger.info(f"Issue is not open (state={issue.state}. Skipping PR creation.")
+ return False
+ if issue.assignee:
+ logger.info("Issue is already assigned. Skipping PR creation. Be nice :)")
+ return False
+ if issue.locked:
+ logger.info("Issue is locked. Skipping PR creation.")
+ return False
+ org, repo, issue_number = parse_gh_issue_url(self._data_path)
+ associated_commits = get_associated_commit_urls(org, repo, issue_number, token=self._token)
+ if associated_commits:
+ commit_url_strs = ", ".join(associated_commits)
+ if self._skip_if_commits_reference_issue:
+ logger.info(f"Issue already has associated commits (see {commit_url_strs}). Skipping PR creation.")
+ return False
+ else:
+ logger.warning(
+ "Proceeding with PR creation even though there are already commits "
+ f"({commit_url_strs}) associated with the issue. Please only do this for your own repositories "
+ "or after verifying that the existing commits do not fix the issue.",
+ )
+ return True
+
+
+def _remove_triple_backticks(text: str) -> str:
+ return "\n".join(line.removeprefix("```") for line in text.splitlines())
+
+
+def format_trajectory_markdown(trajectory: list[dict[str, str]]):
+ """Format a trajectory as a markdown string for use in gh PR description."""
+ prefix = [
+ "<details>",
+ "<summary>Thought process ('trajectory') of SWE-agent (click to expand)</summary>",
+ "",
+ "",
+ ]
+ steps = []
+ for i, step in enumerate(trajectory):
+ step_strs = [
+ f"**πŸ§‘β€πŸš’ Response ({i})**: ",
+ f"{step['response'].strip()}",
+ f"**πŸ‘€β€ Observation ({i})**:",
+ "```",
+ f"{_remove_triple_backticks(step['observation']).strip()}",
+ "```",
+ ]
+ steps.append("\n".join(step_strs))
+ suffix = [
+ "",
+ "</details>",
+ ]
+ return "\n".join(prefix) + "\n\n---\n\n".join(steps) + "\n".join(suffix)
diff --git a/sweagent/utils/_github.py b/sweagent/utils/_github.py
new file mode 100644
index 00000000..a25d1637
--- /dev/null
+++ b/sweagent/utils/_github.py
@@ -0,0 +1,107 @@
+from ghapi.all import GhApi
+
+from sweagent.environment.utils import GITHUB_ISSUE_URL_PATTERN, GITHUB_REPO_URL_PATTERN, InvalidGithubURL
+
+
+def is_github_issue_url(data_path: str) -> bool:
+ """Check if data_path is an URL pointing to a github issue"""
+ return GITHUB_ISSUE_URL_PATTERN.search(data_path) is not None
+
+
+def is_github_repo_url(data_path: str) -> bool:
+ """Check if data_path is an URL pointing to a github repository.
+ Paths to issues or PRs will also match this pattern.
+ """
+ return GITHUB_REPO_URL_PATTERN.search(data_path) is not None
+
+
+def get_commit(api: GhApi, owner: str, repo: str, ref: str | None = None):
+ """Get commit object from github api
+
+ Args:
+ api (GhApi):
+ owner (str): Repo owner, e.g., "princeton-nlp"
+ repo (str): Repo, e.g., "SWE-agent"
+ ref (str, optional): Branch, tag or commit hash
+
+ Returns:
+ _type_: _description_
+ """
+ if ref:
+ return api.repos.get_commit(owner, repo, ref) # type: ignore
+ return api.repos.list_commits(owner, repo)[0] # type: ignore
+
+
+def parse_gh_issue_url(issue_url: str) -> tuple[str, str, str]:
+ """
+ Returns:
+ owner: Repo owner
+ repo: Repo name
+ issue number: Issue number as str
+
+ Raises:
+ InvalidGithubURL: If the URL is not a valid github issue URL
+ """
+ match = GITHUB_ISSUE_URL_PATTERN.search(issue_url)
+ if not match:
+ msg = f"Invalid GitHub issue URL: {issue_url}"
+ raise InvalidGithubURL(msg)
+ res = match.groups()
+ assert len(res) == 3
+ return tuple(res) # type: ignore
+
+
+def parse_gh_repo_url(repo_url: str) -> tuple[str, str]:
+ """
+ Returns:
+ owner: Repo owner/org
+ repo: Repo name
+
+ Raises:
+ InvalidGithubURL: If the URL is not a valid github repo URL
+ """
+ match = GITHUB_REPO_URL_PATTERN.search(repo_url)
+ if not match:
+ msg = f"Invalid GitHub issue URL: {repo_url}"
+ raise InvalidGithubURL(msg)
+ res = match.groups()
+ assert len(res) == 2
+ return tuple(res) # type: ignore
+
+
+def get_gh_issue_data(issue_url: str, *, token: str = ""):
+ """Returns github issue data in the form of a dictionary.
+ See https://docs.github.com/en/rest/issues/issues?apiVersion=2022-11-28#get-an-issue
+ for return format
+ """
+ owner, repo, issue_number = parse_gh_issue_url(issue_url)
+ api = GhApi(token=token)
+ return api.issues.get(owner, repo, issue_number)
+
+
+def get_problem_statement_from_github_issue(owner: str, repo: str, issue_number: str, *, token: str | None = "") -> str:
+ """Return problem statement from github issue"""
+ api = GhApi(token=token)
+ issue = api.issues.get(owner, repo, issue_number) # type: ignore
+ title = issue.title if issue.title else ""
+ body = issue.body if issue.body else ""
+ return f"{title}\n{body}\n"
+
+
+def get_associated_commit_urls(org: str, repo: str, issue_number: str, *, token: str = "") -> list[str]:
+ """Return the URLs of commits that would close an issue."""
+ api = GhApi(token=token)
+ # Strangely the "pull_request" field of api.issues.get is often not set
+ # so we have to go through the events to check if there's a commit
+ events = api.issues.list_events(org, repo, issue_number)
+ commit_urls = []
+ for event in events:
+ if event.event != "referenced":
+ continue
+ if not event.commit_id:
+ continue
+ commit = api.repos.get_commit(org, repo, event.commit_id)
+ message = commit.commit.message
+ if f"fixes #{issue_number}" in message.lower() or f"closes #{issue_number}" in message.lower():
+ commit_urls.append(commit.html_url)
+ return commit_urls
diff --git a/sweagent/utils/config.py b/sweagent/utils/config.py
index d1ffb872..9afbb60f 100644
--- a/sweagent/utils/config.py
+++ b/sweagent/utils/config.py
@@ -11,7 +11,7 @@ from sweagent.utils.log import get_logger
logger = get_logger("config")
-def convert_path_to_abspath(path: Path | str) -> Path:
+def _convert_path_to_abspath(path: Path | str) -> Path:
"""If path is not absolute, convert it to an absolute path
using the SWE_AGENT_CONFIG_ROOT environment variable (if set) or
REPO_ROOT as base.
@@ -25,8 +25,8 @@ def convert_path_to_abspath(path: Path | str) -> Path:
return path.resolve()
-def convert_paths_to_abspath(paths: list[Path] | list[str]) -> list[str]:
- return [str(convert_path_to_abspath(p)) for p in paths]
+def _convert_paths_to_abspath(paths: list[Path] | list[str]) -> list[str]:
+ return [str(_convert_path_to_abspath(p)) for p in paths]
class Config:
diff --git a/sweagent/utils/patch_formatter.py b/sweagent/utils/patch_formatter.py
new file mode 100644
index 00000000..a730eabc
--- /dev/null
+++ b/sweagent/utils/patch_formatter.py
@@ -0,0 +1,152 @@
+from collections.abc import Callable
+
+from unidiff import PatchSet
+
+
+class PatchFormatter:
+ def __init__(
+ self,
+ patch: str,
+ read_method: Callable[[str], str],
+ ):
+ """Given the final patch and access to the container that contains the repository,
+ extract relevant lines from the modified file.
+
+ Args:
+ patch: The patch as a string.
+ read_method: Callable with path to file (relative to repository root) as argument
+ that returns the file content as a string.
+ """
+ self._patch = PatchSet(patch)
+ self._patched_files: dict[str, str] = {}
+ self._original_files: dict[str, str] = {}
+ self._patch_applied = True
+ self._read_file = read_method
+ self._read_files(original=False)
+
+ @staticmethod
+ def _merge_intervals(starts: list[int], stops: list[int]) -> tuple[list[int], list[int]]:
+ """Given two lists of integers, starts and stops, merges all overlapping intervals.
+
+ For example `starts=[1, 5, 18]`, `stops=[10, 13, 20]`
+ should return `starts=[1, 18]`, `stops=[13, 20]`
+ """
+ if not starts:
+ assert not stops
+ return [], []
+
+ intervals = sorted(zip(starts, stops))
+ merged = []
+ for start, stop in intervals:
+ if not merged or merged[-1][1] < start:
+ # No overlap
+ merged.append([start, stop])
+ else:
+ # Overlap
+ merged[-1][1] = max(merged[-1][1], stop)
+ # Unzip again
+ merged_starts, merged_stops = zip(*merged)
+ return list(merged_starts), list(merged_stops)
+
+ def format_file(self, text: str, starts: list[int], stops: list[int], *, linenos: bool = True) -> str:
+ """Reads file and returns string representation of the relevant lines.
+
+ Args:
+ path: The path to the file within the repo location
+ starts: The starting line numbers of the relevant lines. The first line is line 1.
+ stops: The stopping line numbers of the relevant lines. The stop is not inclusive.
+ The first line is line 1.
+ linenos: Whether to include line numbers
+ """
+ if not starts:
+ assert not stops
+ return ""
+
+ assert len(starts) == len(stops)
+ assert all(start >= 1 for start in starts)
+ assert all(start < stop for start, stop in zip(starts, stops))
+ starts, stops = self._merge_intervals(starts, stops)
+ assert all(hunk1_start < hunk2_start for hunk1_start, hunk2_start in zip(starts, starts[1:]))
+ out: list[str] = []
+ if starts[0] > 1:
+ # Count from 1
+ out.append(f"[{starts[0]-1} lines above omitted]")
+ last_stop: int | None = None
+ lines = text.splitlines()
+ for start, stop in zip(starts, stops):
+ assert start >= 1
+ if last_stop is not None:
+ n_omitted = start - last_stop
+ # Check that we have non-overlapping hunks
+ assert n_omitted >= 0
+ if n_omitted:
+ out.append(f"\n[{n_omitted} lines omitted]\n")
+ # Count from 1
+ these_lines = lines[start - 1 : stop - 1]
+ if linenos:
+ out.append("\n".join([f"{i:6d}: {l}" for i, l in enumerate(these_lines, start=start)]))
+ else:
+ out.append("\n".join(these_lines))
+ last_stop = stop
+ if last_stop < len(lines):
+ # Stop is not inclusive
+ omitted = len(lines) - last_stop
+ assert omitted > 0
+ out.append(f"[{omitted} lines below omitted]")
+ return "\n".join(out)
+
+ def _get_hunk_lines(self, original: bool, *, context_length: int) -> dict[str, tuple[list[int], list[int]]]:
+ """Get the starts and stops for all files in the patch.
+
+ Args:
+ original: Whether to read the original file or the patched file
+ context_length: The number of lines to include above and below the hunk
+
+ Returns:
+ A dictionary with the file path as key and a tuple of lists of starts and stops as value.
+ """
+ out: dict[str, tuple[list[int], list[int]]] = {}
+ for patch in self._patch:
+ if not patch.is_modified_file:
+ continue
+ starts: list[int] = []
+ stops: list[int] = []
+ for hunk in patch:
+ if original:
+ # 1 is the lowest line number
+ start = max(1, hunk.source_start - context_length)
+ stop = hunk.source_start + hunk.source_length + context_length
+ else:
+ start = max(1, hunk.target_start - context_length)
+ stop = hunk.target_start + hunk.target_length + context_length
+ starts.append(start)
+ stops.append(stop)
+ out[patch.path] = (starts, stops)
+ return out
+
+ def _read_files(self, original: bool) -> None:
+ for patch in self._patch:
+ path = patch.path
+ if not patch.is_modified_file:
+ continue
+ if original:
+ msg = "Original file reading not implemented"
+ raise NotImplementedError(msg)
+ else:
+ assert self._patch_applied
+ self._patched_files[path] = self._read_file(path)
+
+ @staticmethod
+ def concat_files_strings(files: dict[str, str]) -> str:
+ """Concatenate multiple `read_files` outputs into a single string."""
+ out = []
+ for path, content in files.items():
+ out.append(f"[File: {path}]\n{content}")
+ return "\n\n".join(out)
+
+ def get_files_str(self, *, original: bool, context_length: int | None = 50, linenos: bool = True) -> str:
+ hunk_lines = self._get_hunk_lines(original=original, context_length=context_length)
+ sources = self._original_files if original else self._patched_files
+ return self.concat_files_strings(
+ {path: self.format_file(text, *hunk_lines[path], linenos=linenos) for path, text in sources.items()}
+ )
diff --git a/tests/test_env_utils.py b/tests/test_env_utils.py
index dc2b06e3..53b1fdd1 100644
--- a/tests/test_env_utils.py
+++ b/tests/test_env_utils.py
@@ -8,14 +8,15 @@ import pytest
from sweagent.environment.utils import (
InvalidGithubURL,
- format_trajectory_markdown,
- get_associated_commit_urls,
get_instances,
+)
+from sweagent.main.hooks.open_pr import _remove_triple_backticks, format_trajectory_markdown
+from sweagent.utils._github import (
+ get_associated_commit_urls,
is_github_issue_url,
is_github_repo_url,
parse_gh_issue_url,
parse_gh_repo_url,
- remove_triple_backticks,
)
from sweagent.utils.config import keys_config
@@ -29,7 +30,7 @@ def test_format_trajectory_markdown(test_trajectory):
def test_remove_triple_backticks():
- assert remove_triple_backticks("```") == ""
+ assert _remove_triple_backticks("```") == ""
def test_is_github_repo_url():
diff --git a/tests/test_run.py b/tests/test_run.py
index 4bf405e8..1f3f7d77 100644
--- a/tests/test_run.py
+++ b/tests/test_run.py
@@ -15,7 +15,8 @@ from run import ActionsArguments, Main, ScriptArguments
from sweagent.agent.agents import Agent, AgentConfig, AgentHook
from sweagent.agent.models import ModelArguments
from sweagent.environment.swe_env import EnvironmentConfig, SWEEnv
-from sweagent.main.hooks import MainHook, OpenPRHook
+from sweagent.main.hooks.abstract import MainHook
+from sweagent.main.hooks.open_pr import OpenPRHook
@pytest.mark.slow
diff --git a/tests/test_utils.py b/tests/test_utils.py
index ee260c9f..d9194bfc 100644
--- a/tests/test_utils.py
+++ b/tests/test_utils.py
@@ -6,7 +6,7 @@ from unittest import mock
import pytest
from sweagent import REPO_ROOT
-from sweagent.utils.config import Config, convert_path_to_abspath, convert_paths_to_abspath
+from sweagent.utils.config import Config, _convert_path_to_abspath, _convert_paths_to_abspath
def test_config_retrieval_fails():
@@ -56,9 +56,9 @@ def test_retrieve_choices_config_file(tmp_path):
def test_convert_path_to_abspath():
- assert convert_path_to_abspath("sadf") == REPO_ROOT / "sadf"
- assert convert_path_to_abspath("/sadf") == Path("/sadf")
+ assert _convert_path_to_abspath("sadf") == REPO_ROOT / "sadf"
+ assert _convert_path_to_abspath("/sadf") == Path("/sadf")
def test_convert_paths_to_abspath():
- assert convert_paths_to_abspath([Path("sadf"), "/sadf"]) == [REPO_ROOT / "sadf", Path("/sadf")]
+ assert _convert_paths_to_abspath([Path("sadf"), "/sadf"]) == [REPO_ROOT / "sadf", Path("/sadf")]