Add files using upload-large-folder tool
Browse files- projects/ui/serena-new/src/interprompt/util/class_decorators.py +13 -0
- projects/ui/serena-new/src/serena/config/__init__.py +0 -0
- projects/ui/serena-new/src/serena/config/context_mode.py +232 -0
- projects/ui/serena-new/src/serena/config/serena_config.py +575 -0
- projects/ui/serena-new/src/serena/generated/generated_prompt_factory.py +38 -0
- projects/ui/serena-new/src/serena/resources/project.template.yml +68 -0
- projects/ui/serena-new/src/serena/resources/serena_config.template.yml +77 -0
- projects/ui/serena-new/src/serena/tools/__init__.py +9 -0
- projects/ui/serena-new/src/serena/tools/cmd_tools.py +36 -0
- projects/ui/serena-new/src/serena/tools/config_tools.py +83 -0
- projects/ui/serena-new/src/serena/tools/file_tools.py +403 -0
- projects/ui/serena-new/src/serena/tools/jetbrains_plugin_client.py +185 -0
- projects/ui/serena-new/src/serena/tools/jetbrains_tools.py +132 -0
- projects/ui/serena-new/src/serena/tools/memory_tools.py +64 -0
- projects/ui/serena-new/src/serena/tools/symbol_tools.py +290 -0
- projects/ui/serena-new/src/serena/tools/tools_base.py +418 -0
- projects/ui/serena-new/src/serena/tools/workflow_tools.py +139 -0
- projects/ui/serena-new/src/serena/util/class_decorators.py +15 -0
- projects/ui/serena-new/src/serena/util/exception.py +65 -0
- projects/ui/serena-new/src/serena/util/file_system.py +346 -0
projects/ui/serena-new/src/interprompt/util/class_decorators.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def singleton(cls: type[Any]) -> Any:
|
| 5 |
+
instance = None
|
| 6 |
+
|
| 7 |
+
def get_instance(*args: Any, **kwargs: Any) -> Any:
|
| 8 |
+
nonlocal instance
|
| 9 |
+
if instance is None:
|
| 10 |
+
instance = cls(*args, **kwargs)
|
| 11 |
+
return instance
|
| 12 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Context and Mode configuration loader
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from dataclasses import dataclass, field
|
| 7 |
+
from enum import Enum
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import TYPE_CHECKING, Self
|
| 10 |
+
|
| 11 |
+
import yaml
|
| 12 |
+
from sensai.util import logging
|
| 13 |
+
from sensai.util.string import ToStringMixin
|
| 14 |
+
|
| 15 |
+
from serena.config.serena_config import ToolInclusionDefinition
|
| 16 |
+
from serena.constants import (
|
| 17 |
+
DEFAULT_CONTEXT,
|
| 18 |
+
DEFAULT_MODES,
|
| 19 |
+
INTERNAL_MODE_YAMLS_DIR,
|
| 20 |
+
SERENAS_OWN_CONTEXT_YAMLS_DIR,
|
| 21 |
+
SERENAS_OWN_MODE_YAMLS_DIR,
|
| 22 |
+
USER_CONTEXT_YAMLS_DIR,
|
| 23 |
+
USER_MODE_YAMLS_DIR,
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
if TYPE_CHECKING:
|
| 27 |
+
pass
|
| 28 |
+
|
| 29 |
+
log = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(kw_only=True)
|
| 33 |
+
class SerenaAgentMode(ToolInclusionDefinition, ToStringMixin):
|
| 34 |
+
"""Represents a mode of operation for the agent, typically read off a YAML file.
|
| 35 |
+
An agent can be in multiple modes simultaneously as long as they are not mutually exclusive.
|
| 36 |
+
The modes can be adjusted after the agent is running, for example for switching from planning to editing.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
name: str
|
| 40 |
+
prompt: str
|
| 41 |
+
"""
|
| 42 |
+
a Jinja2 template for the generation of the system prompt.
|
| 43 |
+
It is formatted by the agent (see SerenaAgent._format_prompt()).
|
| 44 |
+
"""
|
| 45 |
+
description: str = ""
|
| 46 |
+
|
| 47 |
+
def _tostring_includes(self) -> list[str]:
|
| 48 |
+
return ["name"]
|
| 49 |
+
|
| 50 |
+
def print_overview(self) -> None:
|
| 51 |
+
"""Print an overview of the mode."""
|
| 52 |
+
print(f"{self.name}:\n {self.description}")
|
| 53 |
+
if self.excluded_tools:
|
| 54 |
+
print(" excluded tools:\n " + ", ".join(sorted(self.excluded_tools)))
|
| 55 |
+
|
| 56 |
+
@classmethod
|
| 57 |
+
def from_yaml(cls, yaml_path: str | Path) -> Self:
|
| 58 |
+
"""Load a mode from a YAML file."""
|
| 59 |
+
with open(yaml_path, encoding="utf-8") as f:
|
| 60 |
+
data = yaml.safe_load(f)
|
| 61 |
+
name = data.pop("name", Path(yaml_path).stem)
|
| 62 |
+
return cls(name=name, **data)
|
| 63 |
+
|
| 64 |
+
@classmethod
|
| 65 |
+
def get_path(cls, name: str) -> str:
|
| 66 |
+
"""Get the path to the YAML file for a mode."""
|
| 67 |
+
fname = f"{name}.yml"
|
| 68 |
+
custom_mode_path = os.path.join(USER_MODE_YAMLS_DIR, fname)
|
| 69 |
+
if os.path.exists(custom_mode_path):
|
| 70 |
+
return custom_mode_path
|
| 71 |
+
|
| 72 |
+
own_yaml_path = os.path.join(SERENAS_OWN_MODE_YAMLS_DIR, fname)
|
| 73 |
+
if not os.path.exists(own_yaml_path):
|
| 74 |
+
raise FileNotFoundError(
|
| 75 |
+
f"Mode {name} not found in {USER_MODE_YAMLS_DIR} or in {SERENAS_OWN_MODE_YAMLS_DIR}."
|
| 76 |
+
f"Available modes:\n{cls.list_registered_mode_names()}"
|
| 77 |
+
)
|
| 78 |
+
return own_yaml_path
|
| 79 |
+
|
| 80 |
+
@classmethod
|
| 81 |
+
def from_name(cls, name: str) -> Self:
|
| 82 |
+
"""Load a registered Serena mode."""
|
| 83 |
+
mode_path = cls.get_path(name)
|
| 84 |
+
return cls.from_yaml(mode_path)
|
| 85 |
+
|
| 86 |
+
@classmethod
|
| 87 |
+
def from_name_internal(cls, name: str) -> Self:
|
| 88 |
+
"""Loads an internal Serena mode"""
|
| 89 |
+
yaml_path = os.path.join(INTERNAL_MODE_YAMLS_DIR, f"{name}.yml")
|
| 90 |
+
if not os.path.exists(yaml_path):
|
| 91 |
+
raise FileNotFoundError(f"Internal mode '{name}' not found in {INTERNAL_MODE_YAMLS_DIR}")
|
| 92 |
+
return cls.from_yaml(yaml_path)
|
| 93 |
+
|
| 94 |
+
@classmethod
|
| 95 |
+
def list_registered_mode_names(cls, include_user_modes: bool = True) -> list[str]:
|
| 96 |
+
"""Names of all registered modes (from the corresponding YAML files in the serena repo)."""
|
| 97 |
+
modes = [f.stem for f in Path(SERENAS_OWN_MODE_YAMLS_DIR).glob("*.yml") if f.name != "mode.template.yml"]
|
| 98 |
+
if include_user_modes:
|
| 99 |
+
modes += cls.list_custom_mode_names()
|
| 100 |
+
return sorted(set(modes))
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def list_custom_mode_names(cls) -> list[str]:
|
| 104 |
+
"""Names of all custom modes defined by the user."""
|
| 105 |
+
return [f.stem for f in Path(USER_MODE_YAMLS_DIR).glob("*.yml")]
|
| 106 |
+
|
| 107 |
+
@classmethod
|
| 108 |
+
def load_default_modes(cls) -> list[Self]:
|
| 109 |
+
"""Load the default modes (interactive and editing)."""
|
| 110 |
+
return [cls.from_name(mode) for mode in DEFAULT_MODES]
|
| 111 |
+
|
| 112 |
+
@classmethod
|
| 113 |
+
def load(cls, name_or_path: str | Path) -> Self:
|
| 114 |
+
if str(name_or_path).endswith(".yml"):
|
| 115 |
+
return cls.from_yaml(name_or_path)
|
| 116 |
+
return cls.from_name(str(name_or_path))
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
@dataclass(kw_only=True)
|
| 120 |
+
class SerenaAgentContext(ToolInclusionDefinition, ToStringMixin):
|
| 121 |
+
"""Represents a context where the agent is operating (an IDE, a chat, etc.), typically read off a YAML file.
|
| 122 |
+
An agent can only be in a single context at a time.
|
| 123 |
+
The contexts cannot be changed after the agent is running.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
name: str
|
| 127 |
+
prompt: str
|
| 128 |
+
"""
|
| 129 |
+
a Jinja2 template for the generation of the system prompt.
|
| 130 |
+
It is formatted by the agent (see SerenaAgent._format_prompt()).
|
| 131 |
+
"""
|
| 132 |
+
description: str = ""
|
| 133 |
+
tool_description_overrides: dict[str, str] = field(default_factory=dict)
|
| 134 |
+
"""Maps tool names to custom descriptions, default descriptions are extracted from the tool docstrings."""
|
| 135 |
+
|
| 136 |
+
def _tostring_includes(self) -> list[str]:
|
| 137 |
+
return ["name"]
|
| 138 |
+
|
| 139 |
+
@classmethod
|
| 140 |
+
def from_yaml(cls, yaml_path: str | Path) -> Self:
|
| 141 |
+
"""Load a context from a YAML file."""
|
| 142 |
+
with open(yaml_path, encoding="utf-8") as f:
|
| 143 |
+
data = yaml.safe_load(f)
|
| 144 |
+
name = data.pop("name", Path(yaml_path).stem)
|
| 145 |
+
# Ensure backwards compatibility for tool_description_overrides
|
| 146 |
+
if "tool_description_overrides" not in data:
|
| 147 |
+
data["tool_description_overrides"] = {}
|
| 148 |
+
return cls(name=name, **data)
|
| 149 |
+
|
| 150 |
+
@classmethod
|
| 151 |
+
def get_path(cls, name: str) -> str:
|
| 152 |
+
"""Get the path to the YAML file for a context."""
|
| 153 |
+
fname = f"{name}.yml"
|
| 154 |
+
custom_context_path = os.path.join(USER_CONTEXT_YAMLS_DIR, fname)
|
| 155 |
+
if os.path.exists(custom_context_path):
|
| 156 |
+
return custom_context_path
|
| 157 |
+
|
| 158 |
+
own_yaml_path = os.path.join(SERENAS_OWN_CONTEXT_YAMLS_DIR, fname)
|
| 159 |
+
if not os.path.exists(own_yaml_path):
|
| 160 |
+
raise FileNotFoundError(
|
| 161 |
+
f"Context {name} not found in {USER_CONTEXT_YAMLS_DIR} or in {SERENAS_OWN_CONTEXT_YAMLS_DIR}."
|
| 162 |
+
f"Available contexts:\n{cls.list_registered_context_names()}"
|
| 163 |
+
)
|
| 164 |
+
return own_yaml_path
|
| 165 |
+
|
| 166 |
+
@classmethod
|
| 167 |
+
def from_name(cls, name: str) -> Self:
|
| 168 |
+
"""Load a registered Serena context."""
|
| 169 |
+
context_path = cls.get_path(name)
|
| 170 |
+
return cls.from_yaml(context_path)
|
| 171 |
+
|
| 172 |
+
@classmethod
|
| 173 |
+
def load(cls, name_or_path: str | Path) -> Self:
|
| 174 |
+
if str(name_or_path).endswith(".yml"):
|
| 175 |
+
return cls.from_yaml(name_or_path)
|
| 176 |
+
return cls.from_name(str(name_or_path))
|
| 177 |
+
|
| 178 |
+
@classmethod
|
| 179 |
+
def list_registered_context_names(cls, include_user_contexts: bool = True) -> list[str]:
|
| 180 |
+
"""Names of all registered contexts (from the corresponding YAML files in the serena repo)."""
|
| 181 |
+
contexts = [f.stem for f in Path(SERENAS_OWN_CONTEXT_YAMLS_DIR).glob("*.yml")]
|
| 182 |
+
if include_user_contexts:
|
| 183 |
+
contexts += cls.list_custom_context_names()
|
| 184 |
+
return sorted(set(contexts))
|
| 185 |
+
|
| 186 |
+
@classmethod
|
| 187 |
+
def list_custom_context_names(cls) -> list[str]:
|
| 188 |
+
"""Names of all custom contexts defined by the user."""
|
| 189 |
+
return [f.stem for f in Path(USER_CONTEXT_YAMLS_DIR).glob("*.yml")]
|
| 190 |
+
|
| 191 |
+
@classmethod
|
| 192 |
+
def load_default(cls) -> Self:
|
| 193 |
+
"""Load the default context."""
|
| 194 |
+
return cls.from_name(DEFAULT_CONTEXT)
|
| 195 |
+
|
| 196 |
+
def print_overview(self) -> None:
|
| 197 |
+
"""Print an overview of the mode."""
|
| 198 |
+
print(f"{self.name}:\n {self.description}")
|
| 199 |
+
if self.excluded_tools:
|
| 200 |
+
print(" excluded tools:\n " + ", ".join(sorted(self.excluded_tools)))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class RegisteredContext(Enum):
|
| 204 |
+
"""A registered context."""
|
| 205 |
+
|
| 206 |
+
IDE_ASSISTANT = "ide-assistant"
|
| 207 |
+
"""For Serena running within an assistant that already has basic tools, like Claude Code, Cline, Cursor, etc."""
|
| 208 |
+
DESKTOP_APP = "desktop-app"
|
| 209 |
+
"""For Serena running within Claude Desktop or a similar app which does not have built-in tools for code editing."""
|
| 210 |
+
AGENT = "agent"
|
| 211 |
+
"""For Serena running as a standalone agent, e.g. through agno."""
|
| 212 |
+
|
| 213 |
+
def load(self) -> SerenaAgentContext:
|
| 214 |
+
"""Load the context."""
|
| 215 |
+
return SerenaAgentContext.from_name(self.value)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class RegisteredMode(Enum):
|
| 219 |
+
"""A registered mode."""
|
| 220 |
+
|
| 221 |
+
INTERACTIVE = "interactive"
|
| 222 |
+
"""Interactive mode, for multi-turn interactions."""
|
| 223 |
+
EDITING = "editing"
|
| 224 |
+
"""Editing tools are activated."""
|
| 225 |
+
PLANNING = "planning"
|
| 226 |
+
"""Editing tools are deactivated."""
|
| 227 |
+
ONE_SHOT = "one-shot"
|
| 228 |
+
"""Non-interactive mode, where the goal is to finish a task autonomously."""
|
| 229 |
+
|
| 230 |
+
def load(self) -> SerenaAgentMode:
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
The Serena Model Context Protocol (MCP) Server
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import shutil
|
| 7 |
+
from collections.abc import Iterable
|
| 8 |
+
from copy import deepcopy
|
| 9 |
+
from dataclasses import dataclass, field
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from functools import cached_property
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import TYPE_CHECKING, Any, Optional, Self, TypeVar
|
| 14 |
+
|
| 15 |
+
import yaml
|
| 16 |
+
from ruamel.yaml.comments import CommentedMap
|
| 17 |
+
from sensai.util import logging
|
| 18 |
+
from sensai.util.logging import LogTime, datetime_tag
|
| 19 |
+
from sensai.util.string import ToStringMixin
|
| 20 |
+
|
| 21 |
+
from serena.constants import (
|
| 22 |
+
DEFAULT_ENCODING,
|
| 23 |
+
PROJECT_TEMPLATE_FILE,
|
| 24 |
+
REPO_ROOT,
|
| 25 |
+
SERENA_CONFIG_TEMPLATE_FILE,
|
| 26 |
+
SERENA_MANAGED_DIR_IN_HOME,
|
| 27 |
+
SERENA_MANAGED_DIR_NAME,
|
| 28 |
+
)
|
| 29 |
+
from serena.util.general import load_yaml, save_yaml
|
| 30 |
+
from serena.util.inspection import determine_programming_language_composition
|
| 31 |
+
from solidlsp.ls_config import Language
|
| 32 |
+
|
| 33 |
+
from ..analytics import RegisteredTokenCountEstimator
|
| 34 |
+
from ..util.class_decorators import singleton
|
| 35 |
+
|
| 36 |
+
if TYPE_CHECKING:
|
| 37 |
+
from ..project import Project
|
| 38 |
+
|
| 39 |
+
log = logging.getLogger(__name__)
|
| 40 |
+
T = TypeVar("T")
|
| 41 |
+
DEFAULT_TOOL_TIMEOUT: float = 240
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@singleton
|
| 45 |
+
class SerenaPaths:
|
| 46 |
+
"""
|
| 47 |
+
Provides paths to various Serena-related directories and files.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
def __init__(self) -> None:
|
| 51 |
+
self.user_config_dir: str = SERENA_MANAGED_DIR_IN_HOME
|
| 52 |
+
"""
|
| 53 |
+
the path to the user's Serena configuration directory, which is typically ~/.serena
|
| 54 |
+
"""
|
| 55 |
+
|
| 56 |
+
def get_next_log_file_path(self, prefix: str) -> str:
|
| 57 |
+
"""
|
| 58 |
+
:param prefix: the filename prefix indicating the type of the log file
|
| 59 |
+
:return: the full path to the log file to use
|
| 60 |
+
"""
|
| 61 |
+
log_dir = os.path.join(self.user_config_dir, "logs", datetime.now().strftime("%Y-%m-%d"))
|
| 62 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 63 |
+
return os.path.join(log_dir, prefix + "_" + datetime_tag() + ".txt")
|
| 64 |
+
|
| 65 |
+
# TODO: Paths from constants.py should be moved here
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class ToolSet:
|
| 69 |
+
def __init__(self, tool_names: set[str]) -> None:
|
| 70 |
+
self._tool_names = tool_names
|
| 71 |
+
|
| 72 |
+
@classmethod
|
| 73 |
+
def default(cls) -> "ToolSet":
|
| 74 |
+
"""
|
| 75 |
+
:return: the default tool set, which contains all tools that are enabled by default
|
| 76 |
+
"""
|
| 77 |
+
from serena.tools import ToolRegistry
|
| 78 |
+
|
| 79 |
+
return cls(set(ToolRegistry().get_tool_names_default_enabled()))
|
| 80 |
+
|
| 81 |
+
def apply(self, *tool_inclusion_definitions: "ToolInclusionDefinition") -> "ToolSet":
|
| 82 |
+
"""
|
| 83 |
+
:param tool_inclusion_definitions: the definitions to apply
|
| 84 |
+
:return: a new tool set with the definitions applied
|
| 85 |
+
"""
|
| 86 |
+
from serena.tools import ToolRegistry
|
| 87 |
+
|
| 88 |
+
registry = ToolRegistry()
|
| 89 |
+
tool_names = set(self._tool_names)
|
| 90 |
+
for definition in tool_inclusion_definitions:
|
| 91 |
+
included_tools = []
|
| 92 |
+
excluded_tools = []
|
| 93 |
+
for included_tool in definition.included_optional_tools:
|
| 94 |
+
if not registry.is_valid_tool_name(included_tool):
|
| 95 |
+
raise ValueError(f"Invalid tool name '{included_tool}' provided for inclusion")
|
| 96 |
+
if included_tool not in tool_names:
|
| 97 |
+
tool_names.add(included_tool)
|
| 98 |
+
included_tools.append(included_tool)
|
| 99 |
+
for excluded_tool in definition.excluded_tools:
|
| 100 |
+
if not registry.is_valid_tool_name(excluded_tool):
|
| 101 |
+
raise ValueError(f"Invalid tool name '{excluded_tool}' provided for exclusion")
|
| 102 |
+
if excluded_tool in self._tool_names:
|
| 103 |
+
tool_names.remove(excluded_tool)
|
| 104 |
+
excluded_tools.append(excluded_tool)
|
| 105 |
+
if included_tools:
|
| 106 |
+
log.info(f"{definition} included {len(included_tools)} tools: {', '.join(included_tools)}")
|
| 107 |
+
if excluded_tools:
|
| 108 |
+
log.info(f"{definition} excluded {len(excluded_tools)} tools: {', '.join(excluded_tools)}")
|
| 109 |
+
return ToolSet(tool_names)
|
| 110 |
+
|
| 111 |
+
def without_editing_tools(self) -> "ToolSet":
|
| 112 |
+
"""
|
| 113 |
+
:return: a new tool set that excludes all tools that can edit
|
| 114 |
+
"""
|
| 115 |
+
from serena.tools import ToolRegistry
|
| 116 |
+
|
| 117 |
+
registry = ToolRegistry()
|
| 118 |
+
tool_names = set(self._tool_names)
|
| 119 |
+
for tool_name in self._tool_names:
|
| 120 |
+
if registry.get_tool_class_by_name(tool_name).can_edit():
|
| 121 |
+
tool_names.remove(tool_name)
|
| 122 |
+
return ToolSet(tool_names)
|
| 123 |
+
|
| 124 |
+
def get_tool_names(self) -> set[str]:
|
| 125 |
+
"""
|
| 126 |
+
Returns the names of the tools that are currently included in the tool set.
|
| 127 |
+
"""
|
| 128 |
+
return self._tool_names
|
| 129 |
+
|
| 130 |
+
def includes_name(self, tool_name: str) -> bool:
|
| 131 |
+
return tool_name in self._tool_names
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@dataclass
|
| 135 |
+
class ToolInclusionDefinition:
|
| 136 |
+
excluded_tools: Iterable[str] = ()
|
| 137 |
+
included_optional_tools: Iterable[str] = ()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class SerenaConfigError(Exception):
|
| 141 |
+
pass
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def get_serena_managed_in_project_dir(project_root: str | Path) -> str:
|
| 145 |
+
return os.path.join(project_root, SERENA_MANAGED_DIR_NAME)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def is_running_in_docker() -> bool:
|
| 149 |
+
"""Check if we're running inside a Docker container."""
|
| 150 |
+
# Check for Docker-specific files
|
| 151 |
+
if os.path.exists("/.dockerenv"):
|
| 152 |
+
return True
|
| 153 |
+
# Check cgroup for docker references
|
| 154 |
+
try:
|
| 155 |
+
with open("/proc/self/cgroup") as f:
|
| 156 |
+
return "docker" in f.read()
|
| 157 |
+
except FileNotFoundError:
|
| 158 |
+
return False
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@dataclass(kw_only=True)
|
| 162 |
+
class ProjectConfig(ToolInclusionDefinition, ToStringMixin):
|
| 163 |
+
project_name: str
|
| 164 |
+
language: Language
|
| 165 |
+
ignored_paths: list[str] = field(default_factory=list)
|
| 166 |
+
read_only: bool = False
|
| 167 |
+
ignore_all_files_in_gitignore: bool = True
|
| 168 |
+
initial_prompt: str = ""
|
| 169 |
+
encoding: str = DEFAULT_ENCODING
|
| 170 |
+
|
| 171 |
+
SERENA_DEFAULT_PROJECT_FILE = "project.yml"
|
| 172 |
+
|
| 173 |
+
def _tostring_includes(self) -> list[str]:
|
| 174 |
+
return ["project_name"]
|
| 175 |
+
|
| 176 |
+
@classmethod
|
| 177 |
+
def autogenerate(
|
| 178 |
+
cls, project_root: str | Path, project_name: str | None = None, project_language: Language | None = None, save_to_disk: bool = True
|
| 179 |
+
) -> Self:
|
| 180 |
+
"""
|
| 181 |
+
Autogenerate a project configuration for a given project root.
|
| 182 |
+
|
| 183 |
+
:param project_root: the path to the project root
|
| 184 |
+
:param project_name: the name of the project; if None, the name of the project will be the name of the directory
|
| 185 |
+
containing the project
|
| 186 |
+
:param project_language: the programming language of the project; if None, it will be determined automatically
|
| 187 |
+
:param save_to_disk: whether to save the project configuration to disk
|
| 188 |
+
:return: the project configuration
|
| 189 |
+
"""
|
| 190 |
+
project_root = Path(project_root).resolve()
|
| 191 |
+
if not project_root.exists():
|
| 192 |
+
raise FileNotFoundError(f"Project root not found: {project_root}")
|
| 193 |
+
with LogTime("Project configuration auto-generation", logger=log):
|
| 194 |
+
project_name = project_name or project_root.name
|
| 195 |
+
if project_language is None:
|
| 196 |
+
language_composition = determine_programming_language_composition(str(project_root))
|
| 197 |
+
if len(language_composition) == 0:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"No source files found in {project_root}\n\n"
|
| 200 |
+
f"To use Serena with this project, you need to either:\n"
|
| 201 |
+
f"1. Add source files in one of the supported languages (Python, JavaScript/TypeScript, Java, C#, Rust, Go, Ruby, C++, PHP, Swift, Elixir, Terraform, Bash)\n"
|
| 202 |
+
f"2. Create a project configuration file manually at:\n"
|
| 203 |
+
f" {os.path.join(project_root, cls.rel_path_to_project_yml())}\n\n"
|
| 204 |
+
f"Example project.yml:\n"
|
| 205 |
+
f" project_name: {project_name}\n"
|
| 206 |
+
f" language: python # or typescript, java, csharp, rust, go, ruby, cpp, php, swift, elixir, terraform, bash\n"
|
| 207 |
+
)
|
| 208 |
+
# find the language with the highest percentage
|
| 209 |
+
dominant_language = max(language_composition.keys(), key=lambda lang: language_composition[lang])
|
| 210 |
+
else:
|
| 211 |
+
dominant_language = project_language.value
|
| 212 |
+
config_with_comments = load_yaml(PROJECT_TEMPLATE_FILE, preserve_comments=True)
|
| 213 |
+
config_with_comments["project_name"] = project_name
|
| 214 |
+
config_with_comments["language"] = dominant_language
|
| 215 |
+
if save_to_disk:
|
| 216 |
+
save_yaml(str(project_root / cls.rel_path_to_project_yml()), config_with_comments, preserve_comments=True)
|
| 217 |
+
return cls._from_dict(config_with_comments)
|
| 218 |
+
|
| 219 |
+
@classmethod
|
| 220 |
+
def rel_path_to_project_yml(cls) -> str:
|
| 221 |
+
return os.path.join(SERENA_MANAGED_DIR_NAME, cls.SERENA_DEFAULT_PROJECT_FILE)
|
| 222 |
+
|
| 223 |
+
@classmethod
|
| 224 |
+
def _from_dict(cls, data: dict[str, Any]) -> Self:
|
| 225 |
+
"""
|
| 226 |
+
Create a ProjectConfig instance from a configuration dictionary
|
| 227 |
+
"""
|
| 228 |
+
language_str = data["language"].lower()
|
| 229 |
+
project_name = data["project_name"]
|
| 230 |
+
# backwards compatibility
|
| 231 |
+
if language_str == "javascript":
|
| 232 |
+
log.warning(f"Found deprecated project language `javascript` in project {project_name}, please change to `typescript`")
|
| 233 |
+
language_str = "typescript"
|
| 234 |
+
try:
|
| 235 |
+
language = Language(language_str)
|
| 236 |
+
except ValueError as e:
|
| 237 |
+
raise ValueError(f"Invalid language: {data['language']}.\nValid languages are: {[l.value for l in Language]}") from e
|
| 238 |
+
return cls(
|
| 239 |
+
project_name=project_name,
|
| 240 |
+
language=language,
|
| 241 |
+
ignored_paths=data.get("ignored_paths", []),
|
| 242 |
+
excluded_tools=data.get("excluded_tools", []),
|
| 243 |
+
included_optional_tools=data.get("included_optional_tools", []),
|
| 244 |
+
read_only=data.get("read_only", False),
|
| 245 |
+
ignore_all_files_in_gitignore=data.get("ignore_all_files_in_gitignore", True),
|
| 246 |
+
initial_prompt=data.get("initial_prompt", ""),
|
| 247 |
+
encoding=data.get("encoding", DEFAULT_ENCODING),
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
@classmethod
|
| 251 |
+
def load(cls, project_root: Path | str, autogenerate: bool = False) -> Self:
|
| 252 |
+
"""
|
| 253 |
+
Load a ProjectConfig instance from the path to the project root.
|
| 254 |
+
"""
|
| 255 |
+
project_root = Path(project_root)
|
| 256 |
+
yaml_path = project_root / cls.rel_path_to_project_yml()
|
| 257 |
+
if not yaml_path.exists():
|
| 258 |
+
if autogenerate:
|
| 259 |
+
return cls.autogenerate(project_root)
|
| 260 |
+
else:
|
| 261 |
+
raise FileNotFoundError(f"Project configuration file not found: {yaml_path}")
|
| 262 |
+
with open(yaml_path, encoding="utf-8") as f:
|
| 263 |
+
yaml_data = yaml.safe_load(f)
|
| 264 |
+
if "project_name" not in yaml_data:
|
| 265 |
+
yaml_data["project_name"] = project_root.name
|
| 266 |
+
return cls._from_dict(yaml_data)
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
class RegisteredProject(ToStringMixin):
|
| 270 |
+
def __init__(self, project_root: str, project_config: "ProjectConfig", project_instance: Optional["Project"] = None) -> None:
|
| 271 |
+
"""
|
| 272 |
+
Represents a registered project in the Serena configuration.
|
| 273 |
+
|
| 274 |
+
:param project_root: the root directory of the project
|
| 275 |
+
:param project_config: the configuration of the project
|
| 276 |
+
"""
|
| 277 |
+
self.project_root = Path(project_root).resolve()
|
| 278 |
+
self.project_config = project_config
|
| 279 |
+
self._project_instance = project_instance
|
| 280 |
+
|
| 281 |
+
def _tostring_exclude_private(self) -> bool:
|
| 282 |
+
return True
|
| 283 |
+
|
| 284 |
+
@property
|
| 285 |
+
def project_name(self) -> str:
|
| 286 |
+
return self.project_config.project_name
|
| 287 |
+
|
| 288 |
+
@classmethod
|
| 289 |
+
def from_project_instance(cls, project_instance: "Project") -> "RegisteredProject":
|
| 290 |
+
return RegisteredProject(
|
| 291 |
+
project_root=project_instance.project_root,
|
| 292 |
+
project_config=project_instance.project_config,
|
| 293 |
+
project_instance=project_instance,
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
def matches_root_path(self, path: str | Path) -> bool:
|
| 297 |
+
"""
|
| 298 |
+
Check if the given path matches the project root path.
|
| 299 |
+
|
| 300 |
+
:param path: the path to check
|
| 301 |
+
:return: True if the path matches the project root, False otherwise
|
| 302 |
+
"""
|
| 303 |
+
return self.project_root == Path(path).resolve()
|
| 304 |
+
|
| 305 |
+
def get_project_instance(self) -> "Project":
|
| 306 |
+
"""
|
| 307 |
+
Returns the project instance for this registered project, loading it if necessary.
|
| 308 |
+
"""
|
| 309 |
+
if self._project_instance is None:
|
| 310 |
+
from ..project import Project
|
| 311 |
+
|
| 312 |
+
with LogTime(f"Loading project instance for {self}", logger=log):
|
| 313 |
+
self._project_instance = Project(project_root=str(self.project_root), project_config=self.project_config)
|
| 314 |
+
return self._project_instance
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@dataclass(kw_only=True)
|
| 318 |
+
class SerenaConfig(ToolInclusionDefinition, ToStringMixin):
|
| 319 |
+
"""
|
| 320 |
+
Holds the Serena agent configuration, which is typically loaded from a YAML configuration file
|
| 321 |
+
(when instantiated via :method:`from_config_file`), which is updated when projects are added or removed.
|
| 322 |
+
For testing purposes, it can also be instantiated directly with the desired parameters.
|
| 323 |
+
"""
|
| 324 |
+
|
| 325 |
+
projects: list[RegisteredProject] = field(default_factory=list)
|
| 326 |
+
gui_log_window_enabled: bool = False
|
| 327 |
+
log_level: int = logging.INFO
|
| 328 |
+
trace_lsp_communication: bool = False
|
| 329 |
+
web_dashboard: bool = True
|
| 330 |
+
web_dashboard_open_on_launch: bool = True
|
| 331 |
+
tool_timeout: float = DEFAULT_TOOL_TIMEOUT
|
| 332 |
+
loaded_commented_yaml: CommentedMap | None = None
|
| 333 |
+
config_file_path: str | None = None
|
| 334 |
+
"""
|
| 335 |
+
the path to the configuration file to which updates of the configuration shall be saved;
|
| 336 |
+
if None, the configuration is not saved to disk
|
| 337 |
+
"""
|
| 338 |
+
jetbrains: bool = False
|
| 339 |
+
"""
|
| 340 |
+
whether to apply JetBrains mode
|
| 341 |
+
"""
|
| 342 |
+
record_tool_usage_stats: bool = False
|
| 343 |
+
"""Whether to record tool usage statistics, they will be shown in the web dashboard if recording is active.
|
| 344 |
+
"""
|
| 345 |
+
token_count_estimator: str = RegisteredTokenCountEstimator.TIKTOKEN_GPT4O.name
|
| 346 |
+
"""Only relevant if `record_tool_usage` is True; the name of the token count estimator to use for tool usage statistics.
|
| 347 |
+
See the `RegisteredTokenCountEstimator` enum for available options.
|
| 348 |
+
|
| 349 |
+
Note: some token estimators (like tiktoken) may require downloading data files
|
| 350 |
+
on the first run, which can take some time and require internet access. Others, like the Anthropic ones, may require an API key
|
| 351 |
+
and rate limits may apply.
|
| 352 |
+
"""
|
| 353 |
+
default_max_tool_answer_chars: int = 150_000
|
| 354 |
+
"""Used as default for tools where the apply method has a default maximal answer length.
|
| 355 |
+
Even though the value of the max_answer_chars can be changed when calling the tool, it may make sense to adjust this default
|
| 356 |
+
through the global configuration.
|
| 357 |
+
"""
|
| 358 |
+
|
| 359 |
+
CONFIG_FILE = "serena_config.yml"
|
| 360 |
+
CONFIG_FILE_DOCKER = "serena_config.docker.yml" # Docker-specific config file; auto-generated if missing, mounted via docker-compose for user customization
|
| 361 |
+
|
| 362 |
+
def _tostring_includes(self) -> list[str]:
|
| 363 |
+
return ["config_file_path"]
|
| 364 |
+
|
| 365 |
+
@classmethod
|
| 366 |
+
def generate_config_file(cls, config_file_path: str) -> None:
|
| 367 |
+
"""
|
| 368 |
+
Generates a Serena configuration file at the specified path from the template file.
|
| 369 |
+
|
| 370 |
+
:param config_file_path: the path where the configuration file should be generated
|
| 371 |
+
"""
|
| 372 |
+
log.info(f"Auto-generating Serena configuration file in {config_file_path}")
|
| 373 |
+
loaded_commented_yaml = load_yaml(SERENA_CONFIG_TEMPLATE_FILE, preserve_comments=True)
|
| 374 |
+
save_yaml(config_file_path, loaded_commented_yaml, preserve_comments=True)
|
| 375 |
+
|
| 376 |
+
@classmethod
|
| 377 |
+
def _determine_config_file_path(cls) -> str:
|
| 378 |
+
"""
|
| 379 |
+
:return: the location where the Serena configuration file is stored/should be stored
|
| 380 |
+
"""
|
| 381 |
+
if is_running_in_docker():
|
| 382 |
+
return os.path.join(REPO_ROOT, cls.CONFIG_FILE_DOCKER)
|
| 383 |
+
else:
|
| 384 |
+
config_path = os.path.join(SERENA_MANAGED_DIR_IN_HOME, cls.CONFIG_FILE)
|
| 385 |
+
|
| 386 |
+
# if the config file does not exist, check if we can migrate it from the old location
|
| 387 |
+
if not os.path.exists(config_path):
|
| 388 |
+
old_config_path = os.path.join(REPO_ROOT, cls.CONFIG_FILE)
|
| 389 |
+
if os.path.exists(old_config_path):
|
| 390 |
+
log.info(f"Moving Serena configuration file from {old_config_path} to {config_path}")
|
| 391 |
+
os.makedirs(os.path.dirname(config_path), exist_ok=True)
|
| 392 |
+
shutil.move(old_config_path, config_path)
|
| 393 |
+
|
| 394 |
+
return config_path
|
| 395 |
+
|
| 396 |
+
@classmethod
|
| 397 |
+
def from_config_file(cls, generate_if_missing: bool = True) -> "SerenaConfig":
|
| 398 |
+
"""
|
| 399 |
+
Static constructor to create SerenaConfig from the configuration file
|
| 400 |
+
"""
|
| 401 |
+
config_file_path = cls._determine_config_file_path()
|
| 402 |
+
|
| 403 |
+
# create the configuration file from the template if necessary
|
| 404 |
+
if not os.path.exists(config_file_path):
|
| 405 |
+
if not generate_if_missing:
|
| 406 |
+
raise FileNotFoundError(f"Serena configuration file not found: {config_file_path}")
|
| 407 |
+
log.info(f"Serena configuration file not found at {config_file_path}, autogenerating...")
|
| 408 |
+
cls.generate_config_file(config_file_path)
|
| 409 |
+
|
| 410 |
+
# load the configuration
|
| 411 |
+
log.info(f"Loading Serena configuration from {config_file_path}")
|
| 412 |
+
try:
|
| 413 |
+
loaded_commented_yaml = load_yaml(config_file_path, preserve_comments=True)
|
| 414 |
+
except Exception as e:
|
| 415 |
+
raise ValueError(f"Error loading Serena configuration from {config_file_path}: {e}") from e
|
| 416 |
+
|
| 417 |
+
# create the configuration instance
|
| 418 |
+
instance = cls(loaded_commented_yaml=loaded_commented_yaml, config_file_path=config_file_path)
|
| 419 |
+
|
| 420 |
+
# read projects
|
| 421 |
+
if "projects" not in loaded_commented_yaml:
|
| 422 |
+
raise SerenaConfigError("`projects` key not found in Serena configuration. Please update your `serena_config.yml` file.")
|
| 423 |
+
|
| 424 |
+
# load list of known projects
|
| 425 |
+
instance.projects = []
|
| 426 |
+
num_project_migrations = 0
|
| 427 |
+
for path in loaded_commented_yaml["projects"]:
|
| 428 |
+
path = Path(path).resolve()
|
| 429 |
+
if not path.exists() or (path.is_dir() and not (path / ProjectConfig.rel_path_to_project_yml()).exists()):
|
| 430 |
+
log.warning(f"Project path {path} does not exist or does not contain a project configuration file, skipping.")
|
| 431 |
+
continue
|
| 432 |
+
if path.is_file():
|
| 433 |
+
path = cls._migrate_out_of_project_config_file(path)
|
| 434 |
+
if path is None:
|
| 435 |
+
continue
|
| 436 |
+
num_project_migrations += 1
|
| 437 |
+
project_config = ProjectConfig.load(path)
|
| 438 |
+
project = RegisteredProject(
|
| 439 |
+
project_root=str(path),
|
| 440 |
+
project_config=project_config,
|
| 441 |
+
)
|
| 442 |
+
instance.projects.append(project)
|
| 443 |
+
|
| 444 |
+
# set other configuration parameters
|
| 445 |
+
if is_running_in_docker():
|
| 446 |
+
instance.gui_log_window_enabled = False # not supported in Docker
|
| 447 |
+
else:
|
| 448 |
+
instance.gui_log_window_enabled = loaded_commented_yaml.get("gui_log_window", False)
|
| 449 |
+
instance.log_level = loaded_commented_yaml.get("log_level", loaded_commented_yaml.get("gui_log_level", logging.INFO))
|
| 450 |
+
instance.web_dashboard = loaded_commented_yaml.get("web_dashboard", True)
|
| 451 |
+
instance.web_dashboard_open_on_launch = loaded_commented_yaml.get("web_dashboard_open_on_launch", True)
|
| 452 |
+
instance.tool_timeout = loaded_commented_yaml.get("tool_timeout", DEFAULT_TOOL_TIMEOUT)
|
| 453 |
+
instance.trace_lsp_communication = loaded_commented_yaml.get("trace_lsp_communication", False)
|
| 454 |
+
instance.excluded_tools = loaded_commented_yaml.get("excluded_tools", [])
|
| 455 |
+
instance.included_optional_tools = loaded_commented_yaml.get("included_optional_tools", [])
|
| 456 |
+
instance.jetbrains = loaded_commented_yaml.get("jetbrains", False)
|
| 457 |
+
instance.record_tool_usage_stats = loaded_commented_yaml.get("record_tool_usage_stats", False)
|
| 458 |
+
instance.token_count_estimator = loaded_commented_yaml.get(
|
| 459 |
+
"token_count_estimator", RegisteredTokenCountEstimator.TIKTOKEN_GPT4O.name
|
| 460 |
+
)
|
| 461 |
+
instance.default_max_tool_answer_chars = loaded_commented_yaml.get("default_max_tool_answer_chars", 150_000)
|
| 462 |
+
|
| 463 |
+
# re-save the configuration file if any migrations were performed
|
| 464 |
+
if num_project_migrations > 0:
|
| 465 |
+
log.info(
|
| 466 |
+
f"Migrated {num_project_migrations} project configurations from legacy format to in-project configuration; re-saving configuration"
|
| 467 |
+
)
|
| 468 |
+
instance.save()
|
| 469 |
+
|
| 470 |
+
return instance
|
| 471 |
+
|
| 472 |
+
@classmethod
|
| 473 |
+
def _migrate_out_of_project_config_file(cls, path: Path) -> Path | None:
|
| 474 |
+
"""
|
| 475 |
+
Migrates a legacy project configuration file (which is a YAML file containing the project root) to the
|
| 476 |
+
in-project configuration file (project.yml) inside the project root directory.
|
| 477 |
+
|
| 478 |
+
:param path: the path to the legacy project configuration file
|
| 479 |
+
:return: the project root path if the migration was successful, None otherwise.
|
| 480 |
+
"""
|
| 481 |
+
log.info(f"Found legacy project configuration file {path}, migrating to in-project configuration.")
|
| 482 |
+
try:
|
| 483 |
+
with open(path, encoding="utf-8") as f:
|
| 484 |
+
project_config_data = yaml.safe_load(f)
|
| 485 |
+
if "project_name" not in project_config_data:
|
| 486 |
+
project_name = path.stem
|
| 487 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 488 |
+
f.write(f"\nproject_name: {project_name}")
|
| 489 |
+
project_root = project_config_data["project_root"]
|
| 490 |
+
shutil.move(str(path), str(Path(project_root) / ProjectConfig.rel_path_to_project_yml()))
|
| 491 |
+
return Path(project_root).resolve()
|
| 492 |
+
except Exception as e:
|
| 493 |
+
log.error(f"Error migrating configuration file: {e}")
|
| 494 |
+
return None
|
| 495 |
+
|
| 496 |
+
@cached_property
|
| 497 |
+
def project_paths(self) -> list[str]:
|
| 498 |
+
return sorted(str(project.project_root) for project in self.projects)
|
| 499 |
+
|
| 500 |
+
@cached_property
|
| 501 |
+
def project_names(self) -> list[str]:
|
| 502 |
+
return sorted(project.project_config.project_name for project in self.projects)
|
| 503 |
+
|
| 504 |
+
def get_project(self, project_root_or_name: str) -> Optional["Project"]:
|
| 505 |
+
# look for project by name
|
| 506 |
+
project_candidates = []
|
| 507 |
+
for project in self.projects:
|
| 508 |
+
if project.project_config.project_name == project_root_or_name:
|
| 509 |
+
project_candidates.append(project)
|
| 510 |
+
if len(project_candidates) == 1:
|
| 511 |
+
return project_candidates[0].get_project_instance()
|
| 512 |
+
elif len(project_candidates) > 1:
|
| 513 |
+
raise ValueError(
|
| 514 |
+
f"Multiple projects found with name '{project_root_or_name}'. Please activate it by location instead. "
|
| 515 |
+
f"Locations: {[p.project_root for p in project_candidates]}"
|
| 516 |
+
)
|
| 517 |
+
# no project found by name; check if it's a path
|
| 518 |
+
if os.path.isdir(project_root_or_name):
|
| 519 |
+
for project in self.projects:
|
| 520 |
+
if project.matches_root_path(project_root_or_name):
|
| 521 |
+
return project.get_project_instance()
|
| 522 |
+
return None
|
| 523 |
+
|
| 524 |
+
def add_project_from_path(self, project_root: Path | str) -> "Project":
|
| 525 |
+
"""
|
| 526 |
+
Add a project to the Serena configuration from a given path. Will raise a FileExistsError if a
|
| 527 |
+
project already exists at the path.
|
| 528 |
+
|
| 529 |
+
:param project_root: the path to the project to add
|
| 530 |
+
:return: the project that was added
|
| 531 |
+
"""
|
| 532 |
+
from ..project import Project
|
| 533 |
+
|
| 534 |
+
project_root = Path(project_root).resolve()
|
| 535 |
+
if not project_root.exists():
|
| 536 |
+
raise FileNotFoundError(f"Error: Path does not exist: {project_root}")
|
| 537 |
+
if not project_root.is_dir():
|
| 538 |
+
raise FileNotFoundError(f"Error: Path is not a directory: {project_root}")
|
| 539 |
+
|
| 540 |
+
for already_registered_project in self.projects:
|
| 541 |
+
if str(already_registered_project.project_root) == str(project_root):
|
| 542 |
+
raise FileExistsError(
|
| 543 |
+
f"Project with path {project_root} was already added with name '{already_registered_project.project_name}'."
|
| 544 |
+
)
|
| 545 |
+
|
| 546 |
+
project_config = ProjectConfig.load(project_root, autogenerate=True)
|
| 547 |
+
|
| 548 |
+
new_project = Project(project_root=str(project_root), project_config=project_config, is_newly_created=True)
|
| 549 |
+
self.projects.append(RegisteredProject.from_project_instance(new_project))
|
| 550 |
+
self.save()
|
| 551 |
+
|
| 552 |
+
return new_project
|
| 553 |
+
|
| 554 |
+
def remove_project(self, project_name: str) -> None:
|
| 555 |
+
# find the index of the project with the desired name and remove it
|
| 556 |
+
for i, project in enumerate(list(self.projects)):
|
| 557 |
+
if project.project_name == project_name:
|
| 558 |
+
del self.projects[i]
|
| 559 |
+
break
|
| 560 |
+
else:
|
| 561 |
+
raise ValueError(f"Project '{project_name}' not found in Serena configuration; valid project names: {self.project_names}")
|
| 562 |
+
self.save()
|
| 563 |
+
|
| 564 |
+
def save(self) -> None:
|
| 565 |
+
"""
|
| 566 |
+
Saves the configuration to the file from which it was loaded (if any)
|
| 567 |
+
"""
|
| 568 |
+
if self.config_file_path is None:
|
| 569 |
+
return
|
| 570 |
+
assert self.loaded_commented_yaml is not None, "Cannot save configuration without loaded YAML"
|
| 571 |
+
loaded_original_yaml = deepcopy(self.loaded_commented_yaml)
|
| 572 |
+
# projects are unique absolute paths
|
| 573 |
+
# we also canonicalize them before saving
|
| 574 |
+
loaded_original_yaml["projects"] = sorted({str(project.project_root) for project in self.projects})
|
| 575 |
+
save_yaml(self.config_file_path, loaded_original_yaml, preserve_comments=True)
|
projects/ui/serena-new/src/serena/generated/generated_prompt_factory.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ruff: noqa
|
| 2 |
+
# black: skip
|
| 3 |
+
# mypy: ignore-errors
|
| 4 |
+
|
| 5 |
+
# NOTE: This module is auto-generated from interprompt.autogenerate_prompt_factory_module, do not edit manually!
|
| 6 |
+
|
| 7 |
+
from interprompt.multilang_prompt import PromptList
|
| 8 |
+
from interprompt.prompt_factory import PromptFactoryBase
|
| 9 |
+
from typing import Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class PromptFactory(PromptFactoryBase):
|
| 13 |
+
"""
|
| 14 |
+
A class for retrieving and rendering prompt templates and prompt lists.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
def create_onboarding_prompt(self, *, system: Any) -> str:
|
| 18 |
+
return self._render_prompt("onboarding_prompt", locals())
|
| 19 |
+
|
| 20 |
+
def create_think_about_collected_information(self) -> str:
|
| 21 |
+
return self._render_prompt("think_about_collected_information", locals())
|
| 22 |
+
|
| 23 |
+
def create_think_about_task_adherence(self) -> str:
|
| 24 |
+
return self._render_prompt("think_about_task_adherence", locals())
|
| 25 |
+
|
| 26 |
+
def create_think_about_whether_you_are_done(self) -> str:
|
| 27 |
+
return self._render_prompt("think_about_whether_you_are_done", locals())
|
| 28 |
+
|
| 29 |
+
def create_summarize_changes(self) -> str:
|
| 30 |
+
return self._render_prompt("summarize_changes", locals())
|
| 31 |
+
|
| 32 |
+
def create_prepare_for_new_conversation(self) -> str:
|
| 33 |
+
return self._render_prompt("prepare_for_new_conversation", locals())
|
| 34 |
+
|
| 35 |
+
def create_system_prompt(
|
| 36 |
+
self, *, available_markers: Any, available_tools: Any, context_system_prompt: Any, mode_system_prompts: Any
|
| 37 |
+
) -> str:
|
| 38 |
+
return self._render_prompt("system_prompt", locals())
|
projects/ui/serena-new/src/serena/resources/project.template.yml
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
|
| 2 |
+
# * For C, use cpp
|
| 3 |
+
# * For JavaScript, use typescript
|
| 4 |
+
# Special requirements:
|
| 5 |
+
# * csharp: Requires the presence of a .sln file in the project folder.
|
| 6 |
+
language: python
|
| 7 |
+
|
| 8 |
+
# whether to use the project's gitignore file to ignore files
|
| 9 |
+
# Added on 2025-04-07
|
| 10 |
+
ignore_all_files_in_gitignore: true
|
| 11 |
+
# list of additional paths to ignore
|
| 12 |
+
# same syntax as gitignore, so you can use * and **
|
| 13 |
+
# Was previously called `ignored_dirs`, please update your config if you are using that.
|
| 14 |
+
# Added (renamed) on 2025-04-07
|
| 15 |
+
ignored_paths: []
|
| 16 |
+
|
| 17 |
+
# whether the project is in read-only mode
|
| 18 |
+
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
|
| 19 |
+
# Added on 2025-04-18
|
| 20 |
+
read_only: false
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
|
| 24 |
+
# Below is the complete list of tools for convenience.
|
| 25 |
+
# To make sure you have the latest list of tools, and to view their descriptions,
|
| 26 |
+
# execute `uv run scripts/print_tool_overview.py`.
|
| 27 |
+
#
|
| 28 |
+
# * `activate_project`: Activates a project by name.
|
| 29 |
+
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
|
| 30 |
+
# * `create_text_file`: Creates/overwrites a file in the project directory.
|
| 31 |
+
# * `delete_lines`: Deletes a range of lines within a file.
|
| 32 |
+
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
|
| 33 |
+
# * `execute_shell_command`: Executes a shell command.
|
| 34 |
+
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
|
| 35 |
+
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
| 36 |
+
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
| 37 |
+
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
| 38 |
+
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
|
| 39 |
+
# * `initial_instructions`: Gets the initial instructions for the current project.
|
| 40 |
+
# Should only be used in settings where the system prompt cannot be set,
|
| 41 |
+
# e.g. in clients you have no control over, like Claude Desktop.
|
| 42 |
+
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
|
| 43 |
+
# * `insert_at_line`: Inserts content at a given line in a file.
|
| 44 |
+
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
|
| 45 |
+
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
|
| 46 |
+
# * `list_memories`: Lists memories in Serena's project-specific memory store.
|
| 47 |
+
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
| 48 |
+
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
| 49 |
+
# * `read_file`: Reads a file within the project directory.
|
| 50 |
+
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
|
| 51 |
+
# * `remove_project`: Removes a project from the Serena configuration.
|
| 52 |
+
# * `replace_lines`: Replaces a range of lines within a file with new content.
|
| 53 |
+
# * `replace_symbol_body`: Replaces the full definition of a symbol.
|
| 54 |
+
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
|
| 55 |
+
# * `search_for_pattern`: Performs a search for a pattern in the project.
|
| 56 |
+
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
|
| 57 |
+
# * `switch_modes`: Activates modes by providing a list of their names
|
| 58 |
+
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
|
| 59 |
+
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
|
| 60 |
+
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
|
| 61 |
+
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
|
| 62 |
+
excluded_tools: []
|
| 63 |
+
|
| 64 |
+
# initial prompt for the project. It will always be given to the LLM upon activating the project
|
| 65 |
+
# (contrary to the memories, which are loaded on demand).
|
| 66 |
+
initial_prompt: ""
|
| 67 |
+
|
| 68 |
+
project_name: "project_name"
|
projects/ui/serena-new/src/serena/resources/serena_config.template.yml
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gui_log_window: False
|
| 2 |
+
# whether to open a graphical window with Serena's logs.
|
| 3 |
+
# This is mainly supported on Windows and (partly) on Linux; not available on macOS.
|
| 4 |
+
# If you want to see the logs in a web browser, use the `web_dashboard` option instead.
|
| 5 |
+
# Limitations: doesn't seem to work with the community version of Claude Desktop for Linux
|
| 6 |
+
# Might also cause problems with some MCP clients - if you have any issues, try disabling this
|
| 7 |
+
|
| 8 |
+
# Being able to inspect logs is useful both for troubleshooting and for monitoring the tool calls,
|
| 9 |
+
# especially when using the agno playground, since the tool calls are not always shown,
|
| 10 |
+
# and the input params are never shown in the agno UI.
|
| 11 |
+
# When used as MCP server for Claude Desktop, the logs are primarily for troubleshooting.
|
| 12 |
+
# Note: unfortunately, the various entities starting the Serena server or agent do so in
|
| 13 |
+
# mysterious ways, often starting multiple instances of the process without shutting down
|
| 14 |
+
# previous instances. This can lead to multiple log windows being opened, and only the last
|
| 15 |
+
# window being updated. Since we can't control how agno or Claude Desktop start Serena,
|
| 16 |
+
# we have to live with this limitation for now.
|
| 17 |
+
|
| 18 |
+
web_dashboard: True
|
| 19 |
+
# whether to open the Serena web dashboard (which will be accessible through your web browser) that
|
| 20 |
+
# shows Serena's current session logs - as an alternative to the GUI log window which
|
| 21 |
+
# is supported on all platforms.
|
| 22 |
+
|
| 23 |
+
web_dashboard_open_on_launch: True
|
| 24 |
+
# whether to open a browser window with the web dashboard when Serena starts (provided that web_dashboard
|
| 25 |
+
# is enabled). If set to False, you can still open the dashboard manually by navigating to
|
| 26 |
+
# http://localhost:24282/dashboard/ in your web browser (24282 = 0x5EDA, SErena DAshboard).
|
| 27 |
+
# If you have multiple instances running, a higher port will be used; try port 24283, 24284, etc.
|
| 28 |
+
|
| 29 |
+
log_level: 20
|
| 30 |
+
# the minimum log level for the GUI log window and the dashboard (10 = debug, 20 = info, 30 = warning, 40 = error)
|
| 31 |
+
|
| 32 |
+
trace_lsp_communication: False
|
| 33 |
+
# whether to trace the communication between Serena and the language servers.
|
| 34 |
+
# This is useful for debugging language server issues.
|
| 35 |
+
|
| 36 |
+
tool_timeout: 240
|
| 37 |
+
# timeout, in seconds, after which tool executions are terminated
|
| 38 |
+
|
| 39 |
+
excluded_tools: []
|
| 40 |
+
# list of tools to be globally excluded
|
| 41 |
+
|
| 42 |
+
included_optional_tools: []
|
| 43 |
+
# list of optional tools (which are disabled by default) to be included
|
| 44 |
+
|
| 45 |
+
jetbrains: False
|
| 46 |
+
# whether to enable JetBrains mode and use tools based on the Serena JetBrains IDE plugin
|
| 47 |
+
# instead of language server-based tools
|
| 48 |
+
# NOTE: The plugin is yet unreleased. This is for Serena developers only.
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
default_max_tool_answer_chars: 150000
|
| 52 |
+
# Used as default for tools where the apply method has a default maximal answer length.
|
| 53 |
+
# Even though the value of the max_answer_chars can be changed when calling the tool, it may make sense to adjust this default
|
| 54 |
+
# through the global configuration.
|
| 55 |
+
|
| 56 |
+
record_tool_usage_stats: False
|
| 57 |
+
# whether to record tool usage statistics, they will be shown in the web dashboard if recording is active.
|
| 58 |
+
|
| 59 |
+
token_count_estimator: TIKTOKEN_GPT4O
|
| 60 |
+
# Only relevant if `record_tool_usage` is True; the name of the token count estimator to use for tool usage statistics.
|
| 61 |
+
# See the `RegisteredTokenCountEstimator` enum for available options.
|
| 62 |
+
#
|
| 63 |
+
# Note: some token estimators (like tiktoken) may require downloading data files
|
| 64 |
+
# on the first run, which can take some time and require internet access. Others, like the Anthropic ones, may require an API key
|
| 65 |
+
# and rate limits may apply.
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# MANAGED BY SERENA, KEEP AT THE BOTTOM OF THE YAML AND DON'T EDIT WITHOUT NEED
|
| 69 |
+
# The list of registered projects.
|
| 70 |
+
# To add a project, within a chat, simply ask Serena to "activate the project /path/to/project" or,
|
| 71 |
+
# if the project was previously added, "activate the project <project name>".
|
| 72 |
+
# By default, the project's name will be the name of the directory containing the project, but you may change it
|
| 73 |
+
# by editing the (auto-generated) project configuration file `/path/project/project/.serena/project.yml` file.
|
| 74 |
+
# If you want to maintain full control of the project configuration, create the project.yml file manually and then
|
| 75 |
+
# instruct Serena to activate the project by its path for first-time activation.
|
| 76 |
+
# NOTE: Make sure there are no name collisions in the names of registered projects.
|
| 77 |
+
projects: []
|
projects/ui/serena-new/src/serena/tools/__init__.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ruff: noqa
|
| 2 |
+
from .tools_base import *
|
| 3 |
+
from .file_tools import *
|
| 4 |
+
from .symbol_tools import *
|
| 5 |
+
from .memory_tools import *
|
| 6 |
+
from .cmd_tools import *
|
| 7 |
+
from .config_tools import *
|
| 8 |
+
from .workflow_tools import *
|
| 9 |
+
from .jetbrains_tools import *
|
projects/ui/serena-new/src/serena/tools/cmd_tools.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tools supporting the execution of (external) commands
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from serena.tools import Tool, ToolMarkerCanEdit
|
| 6 |
+
from serena.util.shell import execute_shell_command
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ExecuteShellCommandTool(Tool, ToolMarkerCanEdit):
|
| 10 |
+
"""
|
| 11 |
+
Executes a shell command.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
def apply(
|
| 15 |
+
self,
|
| 16 |
+
command: str,
|
| 17 |
+
cwd: str | None = None,
|
| 18 |
+
capture_stderr: bool = True,
|
| 19 |
+
max_answer_chars: int = -1,
|
| 20 |
+
) -> str:
|
| 21 |
+
"""
|
| 22 |
+
Execute a shell command and return its output. If there is a memory about suggested commands, read that first.
|
| 23 |
+
Never execute unsafe shell commands like `rm -rf /` or similar!
|
| 24 |
+
|
| 25 |
+
:param command: the shell command to execute
|
| 26 |
+
:param cwd: the working directory to execute the command in. If None, the project root will be used.
|
| 27 |
+
:param capture_stderr: whether to capture and return stderr output
|
| 28 |
+
:param max_answer_chars: if the output is longer than this number of characters,
|
| 29 |
+
no content will be returned. -1 means using the default value, don't adjust unless there is no other way to get the content
|
| 30 |
+
required for the task.
|
| 31 |
+
:return: a JSON object containing the command's stdout and optionally stderr output
|
| 32 |
+
"""
|
| 33 |
+
_cwd = cwd or self.get_project_root()
|
| 34 |
+
result = execute_shell_command(command, cwd=_cwd, capture_stderr=capture_stderr)
|
| 35 |
+
result = result.json()
|
| 36 |
+
return self._limit_length(result, max_answer_chars)
|
projects/ui/serena-new/src/serena/tools/config_tools.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from serena.config.context_mode import SerenaAgentMode
|
| 4 |
+
from serena.tools import Tool, ToolMarkerDoesNotRequireActiveProject, ToolMarkerOptional
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ActivateProjectTool(Tool, ToolMarkerDoesNotRequireActiveProject):
|
| 8 |
+
"""
|
| 9 |
+
Activates a project by name.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def apply(self, project: str) -> str:
|
| 13 |
+
"""
|
| 14 |
+
Activates the project with the given name.
|
| 15 |
+
|
| 16 |
+
:param project: the name of a registered project to activate or a path to a project directory
|
| 17 |
+
"""
|
| 18 |
+
active_project = self.agent.activate_project_from_path_or_name(project)
|
| 19 |
+
if active_project.is_newly_created:
|
| 20 |
+
result_str = (
|
| 21 |
+
f"Created and activated a new project with name '{active_project.project_name}' at {active_project.project_root}, language: {active_project.project_config.language.value}. "
|
| 22 |
+
"You can activate this project later by name.\n"
|
| 23 |
+
f"The project's Serena configuration is in {active_project.path_to_project_yml()}. In particular, you may want to edit the project name and the initial prompt."
|
| 24 |
+
)
|
| 25 |
+
else:
|
| 26 |
+
result_str = f"Activated existing project with name '{active_project.project_name}' at {active_project.project_root}, language: {active_project.project_config.language.value}"
|
| 27 |
+
|
| 28 |
+
if active_project.project_config.initial_prompt:
|
| 29 |
+
result_str += f"\nAdditional project information:\n {active_project.project_config.initial_prompt}"
|
| 30 |
+
result_str += (
|
| 31 |
+
f"\nAvailable memories:\n {json.dumps(list(self.memories_manager.list_memories()))}"
|
| 32 |
+
+ "You should not read these memories directly, but rather use the `read_memory` tool to read them later if needed for the task."
|
| 33 |
+
)
|
| 34 |
+
result_str += f"\nAvailable tools:\n {json.dumps(self.agent.get_active_tool_names())}"
|
| 35 |
+
return result_str
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class RemoveProjectTool(Tool, ToolMarkerDoesNotRequireActiveProject, ToolMarkerOptional):
|
| 39 |
+
"""
|
| 40 |
+
Removes a project from the Serena configuration.
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def apply(self, project_name: str) -> str:
|
| 44 |
+
"""
|
| 45 |
+
Removes a project from the Serena configuration.
|
| 46 |
+
|
| 47 |
+
:param project_name: Name of the project to remove
|
| 48 |
+
"""
|
| 49 |
+
self.agent.serena_config.remove_project(project_name)
|
| 50 |
+
return f"Successfully removed project '{project_name}' from configuration."
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class SwitchModesTool(Tool, ToolMarkerOptional):
|
| 54 |
+
"""
|
| 55 |
+
Activates modes by providing a list of their names
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def apply(self, modes: list[str]) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Activates the desired modes, like ["editing", "interactive"] or ["planning", "one-shot"]
|
| 61 |
+
|
| 62 |
+
:param modes: the names of the modes to activate
|
| 63 |
+
"""
|
| 64 |
+
mode_instances = [SerenaAgentMode.load(mode) for mode in modes]
|
| 65 |
+
self.agent.set_modes(mode_instances)
|
| 66 |
+
|
| 67 |
+
# Inform the Agent about the activated modes and the currently active tools
|
| 68 |
+
result_str = f"Successfully activated modes: {', '.join([mode.name for mode in mode_instances])}" + "\n"
|
| 69 |
+
result_str += "\n".join([mode_instance.prompt for mode_instance in mode_instances]) + "\n"
|
| 70 |
+
result_str += f"Currently active tools: {', '.join(self.agent.get_active_tool_names())}"
|
| 71 |
+
return result_str
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class GetCurrentConfigTool(Tool, ToolMarkerOptional):
|
| 75 |
+
"""
|
| 76 |
+
Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def apply(self) -> str:
|
| 80 |
+
"""
|
| 81 |
+
Print the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
|
| 82 |
+
"""
|
| 83 |
+
return self.agent.get_current_config_overview()
|
projects/ui/serena-new/src/serena/tools/file_tools.py
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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at the file level
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
from collections import defaultdict
|
| 13 |
+
from fnmatch import fnmatch
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
from serena.text_utils import search_files
|
| 17 |
+
from serena.tools import SUCCESS_RESULT, EditedFileContext, Tool, ToolMarkerCanEdit, ToolMarkerOptional
|
| 18 |
+
from serena.util.file_system import scan_directory
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ReadFileTool(Tool):
|
| 22 |
+
"""
|
| 23 |
+
Reads a file within the project directory.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
def apply(self, relative_path: str, start_line: int = 0, end_line: int | None = None, max_answer_chars: int = -1) -> str:
|
| 27 |
+
"""
|
| 28 |
+
Reads the given file or a chunk of it. Generally, symbolic operations
|
| 29 |
+
like find_symbol or find_referencing_symbols should be preferred if you know which symbols you are looking for.
|
| 30 |
+
|
| 31 |
+
:param relative_path: the relative path to the file to read
|
| 32 |
+
:param start_line: the 0-based index of the first line to be retrieved.
|
| 33 |
+
:param end_line: the 0-based index of the last line to be retrieved (inclusive). If None, read until the end of the file.
|
| 34 |
+
:param max_answer_chars: if the file (chunk) is longer than this number of characters,
|
| 35 |
+
no content will be returned. Don't adjust unless there is really no other way to get the content
|
| 36 |
+
required for the task.
|
| 37 |
+
:return: the full text of the file at the given relative path
|
| 38 |
+
"""
|
| 39 |
+
self.project.validate_relative_path(relative_path)
|
| 40 |
+
|
| 41 |
+
result = self.project.read_file(relative_path)
|
| 42 |
+
result_lines = result.splitlines()
|
| 43 |
+
if end_line is None:
|
| 44 |
+
result_lines = result_lines[start_line:]
|
| 45 |
+
else:
|
| 46 |
+
self.lines_read.add_lines_read(relative_path, (start_line, end_line))
|
| 47 |
+
result_lines = result_lines[start_line : end_line + 1]
|
| 48 |
+
result = "\n".join(result_lines)
|
| 49 |
+
|
| 50 |
+
return self._limit_length(result, max_answer_chars)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class CreateTextFileTool(Tool, ToolMarkerCanEdit):
|
| 54 |
+
"""
|
| 55 |
+
Creates/overwrites a file in the project directory.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def apply(self, relative_path: str, content: str) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Write a new file or overwrite an existing file.
|
| 61 |
+
|
| 62 |
+
:param relative_path: the relative path to the file to create
|
| 63 |
+
:param content: the (utf-8-encoded) content to write to the file
|
| 64 |
+
:return: a message indicating success or failure
|
| 65 |
+
"""
|
| 66 |
+
project_root = self.get_project_root()
|
| 67 |
+
abs_path = (Path(project_root) / relative_path).resolve()
|
| 68 |
+
will_overwrite_existing = abs_path.exists()
|
| 69 |
+
|
| 70 |
+
if will_overwrite_existing:
|
| 71 |
+
self.project.validate_relative_path(relative_path)
|
| 72 |
+
else:
|
| 73 |
+
assert abs_path.is_relative_to(
|
| 74 |
+
self.get_project_root()
|
| 75 |
+
), f"Cannot create file outside of the project directory, got {relative_path=}"
|
| 76 |
+
|
| 77 |
+
abs_path.parent.mkdir(parents=True, exist_ok=True)
|
| 78 |
+
abs_path.write_text(content, encoding="utf-8")
|
| 79 |
+
answer = f"File created: {relative_path}."
|
| 80 |
+
if will_overwrite_existing:
|
| 81 |
+
answer += " Overwrote existing file."
|
| 82 |
+
return json.dumps(answer)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ListDirTool(Tool):
|
| 86 |
+
"""
|
| 87 |
+
Lists files and directories in the given directory (optionally with recursion).
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
def apply(self, relative_path: str, recursive: bool, max_answer_chars: int = -1) -> str:
|
| 91 |
+
"""
|
| 92 |
+
Lists all non-gitignored files and directories in the given directory (optionally with recursion).
|
| 93 |
+
|
| 94 |
+
:param relative_path: the relative path to the directory to list; pass "." to scan the project root
|
| 95 |
+
:param recursive: whether to scan subdirectories recursively
|
| 96 |
+
:param max_answer_chars: if the output is longer than this number of characters,
|
| 97 |
+
no content will be returned. -1 means the default value from the config will be used.
|
| 98 |
+
Don't adjust unless there is really no other way to get the content required for the task.
|
| 99 |
+
:return: a JSON object with the names of directories and files within the given directory
|
| 100 |
+
"""
|
| 101 |
+
# Check if the directory exists before validation
|
| 102 |
+
if not self.project.relative_path_exists(relative_path):
|
| 103 |
+
error_info = {
|
| 104 |
+
"error": f"Directory not found: {relative_path}",
|
| 105 |
+
"project_root": self.get_project_root(),
|
| 106 |
+
"hint": "Check if the path is correct relative to the project root",
|
| 107 |
+
}
|
| 108 |
+
return json.dumps(error_info)
|
| 109 |
+
|
| 110 |
+
self.project.validate_relative_path(relative_path)
|
| 111 |
+
|
| 112 |
+
dirs, files = scan_directory(
|
| 113 |
+
os.path.join(self.get_project_root(), relative_path),
|
| 114 |
+
relative_to=self.get_project_root(),
|
| 115 |
+
recursive=recursive,
|
| 116 |
+
is_ignored_dir=self.project.is_ignored_path,
|
| 117 |
+
is_ignored_file=self.project.is_ignored_path,
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
result = json.dumps({"dirs": dirs, "files": files})
|
| 121 |
+
return self._limit_length(result, max_answer_chars)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class FindFileTool(Tool):
|
| 125 |
+
"""
|
| 126 |
+
Finds files in the given relative paths
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def apply(self, file_mask: str, relative_path: str) -> str:
|
| 130 |
+
"""
|
| 131 |
+
Finds non-gitignored files matching the given file mask within the given relative path
|
| 132 |
+
|
| 133 |
+
:param file_mask: the filename or file mask (using the wildcards * or ?) to search for
|
| 134 |
+
:param relative_path: the relative path to the directory to search in; pass "." to scan the project root
|
| 135 |
+
:return: a JSON object with the list of matching files
|
| 136 |
+
"""
|
| 137 |
+
self.project.validate_relative_path(relative_path)
|
| 138 |
+
|
| 139 |
+
dir_to_scan = os.path.join(self.get_project_root(), relative_path)
|
| 140 |
+
|
| 141 |
+
# find the files by ignoring everything that doesn't match
|
| 142 |
+
def is_ignored_file(abs_path: str) -> bool:
|
| 143 |
+
if self.project.is_ignored_path(abs_path):
|
| 144 |
+
return True
|
| 145 |
+
filename = os.path.basename(abs_path)
|
| 146 |
+
return not fnmatch(filename, file_mask)
|
| 147 |
+
|
| 148 |
+
dirs, files = scan_directory(
|
| 149 |
+
path=dir_to_scan,
|
| 150 |
+
recursive=True,
|
| 151 |
+
is_ignored_dir=self.project.is_ignored_path,
|
| 152 |
+
is_ignored_file=is_ignored_file,
|
| 153 |
+
relative_to=self.get_project_root(),
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
result = json.dumps({"files": files})
|
| 157 |
+
return result
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
class ReplaceRegexTool(Tool, ToolMarkerCanEdit):
|
| 161 |
+
"""
|
| 162 |
+
Replaces content in a file by using regular expressions.
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
def apply(
|
| 166 |
+
self,
|
| 167 |
+
relative_path: str,
|
| 168 |
+
regex: str,
|
| 169 |
+
repl: str,
|
| 170 |
+
allow_multiple_occurrences: bool = False,
|
| 171 |
+
) -> str:
|
| 172 |
+
r"""
|
| 173 |
+
Replaces one or more occurrences of the given regular expression.
|
| 174 |
+
This is the preferred way to replace content in a file whenever the symbol-level
|
| 175 |
+
tools are not appropriate.
|
| 176 |
+
Even large sections of code can be replaced by providing a concise regular expression of
|
| 177 |
+
the form "beginning.*?end-of-text-to-be-replaced".
|
| 178 |
+
Always try to use wildcards to avoid specifying the exact content of the code to be replaced,
|
| 179 |
+
especially if it spans several lines.
|
| 180 |
+
|
| 181 |
+
IMPORTANT: REMEMBER TO USE WILDCARDS WHEN APPROPRIATE! I WILL BE VERY UNHAPPY IF YOU WRITE LONG REGEXES WITHOUT USING WILDCARDS INSTEAD!
|
| 182 |
+
|
| 183 |
+
:param relative_path: the relative path to the file
|
| 184 |
+
:param regex: a Python-style regular expression, matches of which will be replaced.
|
| 185 |
+
Dot matches all characters, multi-line matching is enabled.
|
| 186 |
+
:param repl: the string to replace the matched content with, which may contain
|
| 187 |
+
backreferences like \1, \2, etc.
|
| 188 |
+
Make sure to escape special characters appropriately, e.g., use `\\n` for a literal `\n`.
|
| 189 |
+
:param allow_multiple_occurrences: if True, the regex may match multiple occurrences in the file
|
| 190 |
+
and all of them will be replaced.
|
| 191 |
+
If this is set to False and the regex matches multiple occurrences, an error will be returned
|
| 192 |
+
(and you may retry with a revised, more specific regex).
|
| 193 |
+
"""
|
| 194 |
+
self.project.validate_relative_path(relative_path)
|
| 195 |
+
with EditedFileContext(relative_path, self.agent) as context:
|
| 196 |
+
original_content = context.get_original_content()
|
| 197 |
+
updated_content, n = re.subn(regex, repl, original_content, flags=re.DOTALL | re.MULTILINE)
|
| 198 |
+
if n == 0:
|
| 199 |
+
return f"Error: No matches found for regex '{regex}' in file '{relative_path}'."
|
| 200 |
+
if not allow_multiple_occurrences and n > 1:
|
| 201 |
+
return (
|
| 202 |
+
f"Error: Regex '{regex}' matches {n} occurrences in file '{relative_path}'. "
|
| 203 |
+
"Please revise the regex to be more specific or enable allow_multiple_occurrences if this is expected."
|
| 204 |
+
)
|
| 205 |
+
context.set_updated_content(updated_content)
|
| 206 |
+
return SUCCESS_RESULT
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class DeleteLinesTool(Tool, ToolMarkerCanEdit, ToolMarkerOptional):
|
| 210 |
+
"""
|
| 211 |
+
Deletes a range of lines within a file.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def apply(
|
| 215 |
+
self,
|
| 216 |
+
relative_path: str,
|
| 217 |
+
start_line: int,
|
| 218 |
+
end_line: int,
|
| 219 |
+
) -> str:
|
| 220 |
+
"""
|
| 221 |
+
Deletes the given lines in the file.
|
| 222 |
+
Requires that the same range of lines was previously read using the `read_file` tool to verify correctness
|
| 223 |
+
of the operation.
|
| 224 |
+
|
| 225 |
+
:param relative_path: the relative path to the file
|
| 226 |
+
:param start_line: the 0-based index of the first line to be deleted
|
| 227 |
+
:param end_line: the 0-based index of the last line to be deleted
|
| 228 |
+
"""
|
| 229 |
+
if not self.lines_read.were_lines_read(relative_path, (start_line, end_line)):
|
| 230 |
+
read_lines_tool = self.agent.get_tool(ReadFileTool)
|
| 231 |
+
return f"Error: Must call `{read_lines_tool.get_name_from_cls()}` first to read exactly the affected lines."
|
| 232 |
+
code_editor = self.create_code_editor()
|
| 233 |
+
code_editor.delete_lines(relative_path, start_line, end_line)
|
| 234 |
+
return SUCCESS_RESULT
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class ReplaceLinesTool(Tool, ToolMarkerCanEdit, ToolMarkerOptional):
|
| 238 |
+
"""
|
| 239 |
+
Replaces a range of lines within a file with new content.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
def apply(
|
| 243 |
+
self,
|
| 244 |
+
relative_path: str,
|
| 245 |
+
start_line: int,
|
| 246 |
+
end_line: int,
|
| 247 |
+
content: str,
|
| 248 |
+
) -> str:
|
| 249 |
+
"""
|
| 250 |
+
Replaces the given range of lines in the given file.
|
| 251 |
+
Requires that the same range of lines was previously read using the `read_file` tool to verify correctness
|
| 252 |
+
of the operation.
|
| 253 |
+
|
| 254 |
+
:param relative_path: the relative path to the file
|
| 255 |
+
:param start_line: the 0-based index of the first line to be deleted
|
| 256 |
+
:param end_line: the 0-based index of the last line to be deleted
|
| 257 |
+
:param content: the content to insert
|
| 258 |
+
"""
|
| 259 |
+
if not content.endswith("\n"):
|
| 260 |
+
content += "\n"
|
| 261 |
+
result = self.agent.get_tool(DeleteLinesTool).apply(relative_path, start_line, end_line)
|
| 262 |
+
if result != SUCCESS_RESULT:
|
| 263 |
+
return result
|
| 264 |
+
self.agent.get_tool(InsertAtLineTool).apply(relative_path, start_line, content)
|
| 265 |
+
return SUCCESS_RESULT
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class InsertAtLineTool(Tool, ToolMarkerCanEdit, ToolMarkerOptional):
|
| 269 |
+
"""
|
| 270 |
+
Inserts content at a given line in a file.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def apply(
|
| 274 |
+
self,
|
| 275 |
+
relative_path: str,
|
| 276 |
+
line: int,
|
| 277 |
+
content: str,
|
| 278 |
+
) -> str:
|
| 279 |
+
"""
|
| 280 |
+
Inserts the given content at the given line in the file, pushing existing content of the line down.
|
| 281 |
+
In general, symbolic insert operations like insert_after_symbol or insert_before_symbol should be preferred if you know which
|
| 282 |
+
symbol you are looking for.
|
| 283 |
+
However, this can also be useful for small targeted edits of the body of a longer symbol (without replacing the entire body).
|
| 284 |
+
|
| 285 |
+
:param relative_path: the relative path to the file
|
| 286 |
+
:param line: the 0-based index of the line to insert content at
|
| 287 |
+
:param content: the content to be inserted
|
| 288 |
+
"""
|
| 289 |
+
if not content.endswith("\n"):
|
| 290 |
+
content += "\n"
|
| 291 |
+
code_editor = self.create_code_editor()
|
| 292 |
+
code_editor.insert_at_line(relative_path, line, content)
|
| 293 |
+
return SUCCESS_RESULT
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class SearchForPatternTool(Tool):
|
| 297 |
+
"""
|
| 298 |
+
Performs a search for a pattern in the project.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
def apply(
|
| 302 |
+
self,
|
| 303 |
+
substring_pattern: str,
|
| 304 |
+
context_lines_before: int = 0,
|
| 305 |
+
context_lines_after: int = 0,
|
| 306 |
+
paths_include_glob: str = "",
|
| 307 |
+
paths_exclude_glob: str = "",
|
| 308 |
+
relative_path: str = "",
|
| 309 |
+
restrict_search_to_code_files: bool = False,
|
| 310 |
+
max_answer_chars: int = -1,
|
| 311 |
+
) -> str:
|
| 312 |
+
"""
|
| 313 |
+
Offers a flexible search for arbitrary patterns in the codebase, including the
|
| 314 |
+
possibility to search in non-code files.
|
| 315 |
+
Generally, symbolic operations like find_symbol or find_referencing_symbols
|
| 316 |
+
should be preferred if you know which symbols you are looking for.
|
| 317 |
+
|
| 318 |
+
Pattern Matching Logic:
|
| 319 |
+
For each match, the returned result will contain the full lines where the
|
| 320 |
+
substring pattern is found, as well as optionally some lines before and after it. The pattern will be compiled with
|
| 321 |
+
DOTALL, meaning that the dot will match all characters including newlines.
|
| 322 |
+
This also means that it never makes sense to have .* at the beginning or end of the pattern,
|
| 323 |
+
but it may make sense to have it in the middle for complex patterns.
|
| 324 |
+
If a pattern matches multiple lines, all those lines will be part of the match.
|
| 325 |
+
Be careful to not use greedy quantifiers unnecessarily, it is usually better to use non-greedy quantifiers like .*? to avoid
|
| 326 |
+
matching too much content.
|
| 327 |
+
|
| 328 |
+
File Selection Logic:
|
| 329 |
+
The files in which the search is performed can be restricted very flexibly.
|
| 330 |
+
Using `restrict_search_to_code_files` is useful if you are only interested in code symbols (i.e., those
|
| 331 |
+
symbols that can be manipulated with symbolic tools like find_symbol).
|
| 332 |
+
You can also restrict the search to a specific file or directory,
|
| 333 |
+
and provide glob patterns to include or exclude certain files on top of that.
|
| 334 |
+
The globs are matched against relative file paths from the project root (not to the `relative_path` parameter that
|
| 335 |
+
is used to further restrict the search).
|
| 336 |
+
Smartly combining the various restrictions allows you to perform very targeted searches.
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
:param substring_pattern: Regular expression for a substring pattern to search for
|
| 340 |
+
:param context_lines_before: Number of lines of context to include before each match
|
| 341 |
+
:param context_lines_after: Number of lines of context to include after each match
|
| 342 |
+
:param paths_include_glob: optional glob pattern specifying files to include in the search.
|
| 343 |
+
Matches against relative file paths from the project root (e.g., "*.py", "src/**/*.ts").
|
| 344 |
+
Only matches files, not directories. If left empty, all non-ignored files will be included.
|
| 345 |
+
:param paths_exclude_glob: optional glob pattern specifying files to exclude from the search.
|
| 346 |
+
Matches against relative file paths from the project root (e.g., "*test*", "**/*_generated.py").
|
| 347 |
+
Takes precedence over paths_include_glob. Only matches files, not directories. If left empty, no files are excluded.
|
| 348 |
+
:param relative_path: only subpaths of this path (relative to the repo root) will be analyzed. If a path to a single
|
| 349 |
+
file is passed, only that will be searched. The path must exist, otherwise a `FileNotFoundError` is raised.
|
| 350 |
+
:param max_answer_chars: if the output is longer than this number of characters,
|
| 351 |
+
no content will be returned.
|
| 352 |
+
-1 means the default value from the config will be used.
|
| 353 |
+
Don't adjust unless there is really no other way to get the content
|
| 354 |
+
required for the task. Instead, if the output is too long, you should
|
| 355 |
+
make a stricter query.
|
| 356 |
+
:param restrict_search_to_code_files: whether to restrict the search to only those files where
|
| 357 |
+
analyzed code symbols can be found. Otherwise, will search all non-ignored files.
|
| 358 |
+
Set this to True if your search is only meant to discover code that can be manipulated with symbolic tools.
|
| 359 |
+
For example, for finding classes or methods from a name pattern.
|
| 360 |
+
Setting to False is a better choice if you also want to search in non-code files, like in html or yaml files,
|
| 361 |
+
which is why it is the default.
|
| 362 |
+
:return: A mapping of file paths to lists of matched consecutive lines.
|
| 363 |
+
"""
|
| 364 |
+
abs_path = os.path.join(self.get_project_root(), relative_path)
|
| 365 |
+
if not os.path.exists(abs_path):
|
| 366 |
+
raise FileNotFoundError(f"Relative path {relative_path} does not exist.")
|
| 367 |
+
|
| 368 |
+
if restrict_search_to_code_files:
|
| 369 |
+
matches = self.project.search_source_files_for_pattern(
|
| 370 |
+
pattern=substring_pattern,
|
| 371 |
+
relative_path=relative_path,
|
| 372 |
+
context_lines_before=context_lines_before,
|
| 373 |
+
context_lines_after=context_lines_after,
|
| 374 |
+
paths_include_glob=paths_include_glob.strip(),
|
| 375 |
+
paths_exclude_glob=paths_exclude_glob.strip(),
|
| 376 |
+
)
|
| 377 |
+
else:
|
| 378 |
+
if os.path.isfile(abs_path):
|
| 379 |
+
rel_paths_to_search = [relative_path]
|
| 380 |
+
else:
|
| 381 |
+
dirs, rel_paths_to_search = scan_directory(
|
| 382 |
+
path=abs_path,
|
| 383 |
+
recursive=True,
|
| 384 |
+
is_ignored_dir=self.project.is_ignored_path,
|
| 385 |
+
is_ignored_file=self.project.is_ignored_path,
|
| 386 |
+
relative_to=self.get_project_root(),
|
| 387 |
+
)
|
| 388 |
+
# TODO (maybe): not super efficient to walk through the files again and filter if glob patterns are provided
|
| 389 |
+
# but it probably never matters and this version required no further refactoring
|
| 390 |
+
matches = search_files(
|
| 391 |
+
rel_paths_to_search,
|
| 392 |
+
substring_pattern,
|
| 393 |
+
root_path=self.get_project_root(),
|
| 394 |
+
paths_include_glob=paths_include_glob,
|
| 395 |
+
paths_exclude_glob=paths_exclude_glob,
|
| 396 |
+
)
|
| 397 |
+
# group matches by file
|
| 398 |
+
file_to_matches: dict[str, list[str]] = defaultdict(list)
|
| 399 |
+
for match in matches:
|
| 400 |
+
assert match.source_file_path is not None
|
| 401 |
+
file_to_matches[match.source_file_path].append(match.to_display_string())
|
| 402 |
+
result = json.dumps(file_to_matches)
|
| 403 |
+
return self._limit_length(result, max_answer_chars)
|
projects/ui/serena-new/src/serena/tools/jetbrains_plugin_client.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Client for the Serena JetBrains Plugin
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import logging
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from typing import Any, Optional, Self, TypeVar
|
| 9 |
+
|
| 10 |
+
import requests
|
| 11 |
+
from sensai.util.string import ToStringMixin
|
| 12 |
+
|
| 13 |
+
from serena.project import Project
|
| 14 |
+
|
| 15 |
+
T = TypeVar("T")
|
| 16 |
+
log = logging.getLogger(__name__)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SerenaClientError(Exception):
|
| 20 |
+
"""Base exception for Serena client errors."""
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class ConnectionError(SerenaClientError):
|
| 24 |
+
"""Raised when connection to the service fails."""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class APIError(SerenaClientError):
|
| 28 |
+
"""Raised when the API returns an error response."""
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ServerNotFoundError(Exception):
|
| 32 |
+
"""Raised when the plugin's service is not found."""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class JetBrainsPluginClient(ToStringMixin):
|
| 36 |
+
"""
|
| 37 |
+
Python client for the Serena Backend Service.
|
| 38 |
+
|
| 39 |
+
Provides simple methods to interact with all available endpoints.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
BASE_PORT = 0x5EA2
|
| 43 |
+
last_port: int | None = None
|
| 44 |
+
|
| 45 |
+
def __init__(self, port: int, timeout: int = 30):
|
| 46 |
+
self.base_url = f"http://127.0.0.1:{port}"
|
| 47 |
+
self.timeout = timeout
|
| 48 |
+
self.session = requests.Session()
|
| 49 |
+
self.session.headers.update({"Content-Type": "application/json", "Accept": "application/json"})
|
| 50 |
+
|
| 51 |
+
def _tostring_includes(self) -> list[str]:
|
| 52 |
+
return ["base_url", "timeout"]
|
| 53 |
+
|
| 54 |
+
@classmethod
|
| 55 |
+
def from_project(cls, project: Project) -> Self:
|
| 56 |
+
resolved_path = Path(project.project_root).resolve()
|
| 57 |
+
|
| 58 |
+
if cls.last_port is not None:
|
| 59 |
+
client = JetBrainsPluginClient(cls.last_port)
|
| 60 |
+
if client.matches(resolved_path):
|
| 61 |
+
return client
|
| 62 |
+
|
| 63 |
+
for port in range(cls.BASE_PORT, cls.BASE_PORT + 20):
|
| 64 |
+
client = JetBrainsPluginClient(port)
|
| 65 |
+
if client.matches(resolved_path):
|
| 66 |
+
log.info("Found JetBrains IDE service at port %d for project %s", port, resolved_path)
|
| 67 |
+
cls.last_port = port
|
| 68 |
+
return client
|
| 69 |
+
|
| 70 |
+
raise ServerNotFoundError("Found no Serena service in a JetBrains IDE instance for the project at " + str(resolved_path))
|
| 71 |
+
|
| 72 |
+
def matches(self, resolved_path: Path) -> bool:
|
| 73 |
+
try:
|
| 74 |
+
return Path(self.project_root()).resolve() == resolved_path
|
| 75 |
+
except ConnectionError:
|
| 76 |
+
return False
|
| 77 |
+
|
| 78 |
+
def _make_request(self, method: str, endpoint: str, data: Optional[dict] = None) -> dict[str, Any]:
|
| 79 |
+
url = f"{self.base_url}{endpoint}"
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
if method.upper() == "GET":
|
| 83 |
+
response = self.session.get(url, timeout=self.timeout)
|
| 84 |
+
elif method.upper() == "POST":
|
| 85 |
+
json_data = json.dumps(data) if data else None
|
| 86 |
+
response = self.session.post(url, data=json_data, timeout=self.timeout)
|
| 87 |
+
else:
|
| 88 |
+
raise ValueError(f"Unsupported HTTP method: {method}")
|
| 89 |
+
|
| 90 |
+
response.raise_for_status()
|
| 91 |
+
|
| 92 |
+
# Try to parse JSON response
|
| 93 |
+
try:
|
| 94 |
+
return self._pythonify_response(response.json())
|
| 95 |
+
except json.JSONDecodeError:
|
| 96 |
+
# If response is not JSON, return raw text
|
| 97 |
+
return {"response": response.text}
|
| 98 |
+
|
| 99 |
+
except requests.exceptions.ConnectionError as e:
|
| 100 |
+
raise ConnectionError(f"Failed to connect to Serena service at {url}: {e}")
|
| 101 |
+
except requests.exceptions.Timeout as e:
|
| 102 |
+
raise ConnectionError(f"Request to {url} timed out: {e}")
|
| 103 |
+
except requests.exceptions.HTTPError:
|
| 104 |
+
raise APIError(f"API request failed with status {response.status_code}: {response.text}")
|
| 105 |
+
except requests.exceptions.RequestException as e:
|
| 106 |
+
raise SerenaClientError(f"Request failed: {e}")
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _pythonify_response(response: T) -> T:
|
| 110 |
+
"""
|
| 111 |
+
Converts dictionary keys from camelCase to snake_case recursively.
|
| 112 |
+
|
| 113 |
+
:response: the response in which to convert keys (dictionary or list)
|
| 114 |
+
"""
|
| 115 |
+
to_snake_case = lambda s: "".join(["_" + c.lower() if c.isupper() else c for c in s])
|
| 116 |
+
|
| 117 |
+
def convert(x): # type: ignore
|
| 118 |
+
if isinstance(x, dict):
|
| 119 |
+
return {to_snake_case(k): convert(v) for k, v in x.items()}
|
| 120 |
+
elif isinstance(x, list):
|
| 121 |
+
return [convert(item) for item in x]
|
| 122 |
+
else:
|
| 123 |
+
return x
|
| 124 |
+
|
| 125 |
+
return convert(response)
|
| 126 |
+
|
| 127 |
+
def project_root(self) -> str:
|
| 128 |
+
response = self._make_request("GET", "/status")
|
| 129 |
+
return response["project_root"]
|
| 130 |
+
|
| 131 |
+
def find_symbol(
|
| 132 |
+
self, name_path: str, relative_path: str | None = None, include_body: bool = False, depth: int = 0, include_location: bool = False
|
| 133 |
+
) -> dict[str, Any]:
|
| 134 |
+
"""
|
| 135 |
+
Find symbols by name.
|
| 136 |
+
|
| 137 |
+
:param name_path: the name path to match
|
| 138 |
+
:param relative_path: the relative path to which to restrict the search
|
| 139 |
+
:param include_body: whether to include symbol body content
|
| 140 |
+
:param depth: depth of children to include (0 = no children)
|
| 141 |
+
|
| 142 |
+
:return: Dictionary containing 'symbols' list with matching symbols
|
| 143 |
+
"""
|
| 144 |
+
request_data = {
|
| 145 |
+
"namePath": name_path,
|
| 146 |
+
"relativePath": relative_path,
|
| 147 |
+
"includeBody": include_body,
|
| 148 |
+
"depth": depth,
|
| 149 |
+
"includeLocation": include_location,
|
| 150 |
+
}
|
| 151 |
+
return self._make_request("POST", "/findSymbol", request_data)
|
| 152 |
+
|
| 153 |
+
def find_references(self, name_path: str, relative_path: str) -> dict[str, Any]:
|
| 154 |
+
"""
|
| 155 |
+
Find references to a symbol.
|
| 156 |
+
|
| 157 |
+
:param name_path: the name path of the symbol
|
| 158 |
+
:param relative_path: the relative path
|
| 159 |
+
:return: dictionary containing 'symbols' list with symbol references
|
| 160 |
+
"""
|
| 161 |
+
request_data = {"namePath": name_path, "relativePath": relative_path}
|
| 162 |
+
return self._make_request("POST", "/findReferences", request_data)
|
| 163 |
+
|
| 164 |
+
def get_symbols_overview(self, relative_path: str) -> dict[str, Any]:
|
| 165 |
+
"""
|
| 166 |
+
:param relative_path: the relative path to a source file
|
| 167 |
+
"""
|
| 168 |
+
request_data = {"relativePath": relative_path}
|
| 169 |
+
return self._make_request("POST", "/getSymbolsOverview", request_data)
|
| 170 |
+
|
| 171 |
+
def is_service_available(self) -> bool:
|
| 172 |
+
try:
|
| 173 |
+
response = self.heartbeat()
|
| 174 |
+
return response.get("status") == "OK"
|
| 175 |
+
except (ConnectionError, APIError):
|
| 176 |
+
return False
|
| 177 |
+
|
| 178 |
+
def close(self) -> None:
|
| 179 |
+
self.session.close()
|
| 180 |
+
|
| 181 |
+
def __enter__(self) -> Self:
|
| 182 |
+
return self
|
| 183 |
+
|
| 184 |
+
def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore
|
| 185 |
+
self.close()
|
projects/ui/serena-new/src/serena/tools/jetbrains_tools.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from serena.tools import Tool, ToolMarkerOptional, ToolMarkerSymbolicRead
|
| 4 |
+
from serena.tools.jetbrains_plugin_client import JetBrainsPluginClient
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class JetBrainsFindSymbolTool(Tool, ToolMarkerSymbolicRead, ToolMarkerOptional):
|
| 8 |
+
"""
|
| 9 |
+
Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def apply(
|
| 13 |
+
self,
|
| 14 |
+
name_path: str,
|
| 15 |
+
depth: int = 0,
|
| 16 |
+
relative_path: str | None = None,
|
| 17 |
+
include_body: bool = False,
|
| 18 |
+
max_answer_chars: int = -1,
|
| 19 |
+
) -> str:
|
| 20 |
+
"""
|
| 21 |
+
Retrieves information on all symbols/code entities (classes, methods, etc.) based on the given `name_path`,
|
| 22 |
+
which represents a pattern for the symbol's path within the symbol tree of a single file.
|
| 23 |
+
The returned symbol location can be used for edits or further queries.
|
| 24 |
+
Specify `depth > 0` to retrieve children (e.g., methods of a class).
|
| 25 |
+
|
| 26 |
+
The matching behavior is determined by the structure of `name_path`, which can
|
| 27 |
+
either be a simple name (e.g. "method") or a name path like "class/method" (relative name path)
|
| 28 |
+
or "/class/method" (absolute name path).
|
| 29 |
+
Note that the name path is not a path in the file system but rather a path in the symbol tree
|
| 30 |
+
**within a single file**. Thus, file or directory names should never be included in the `name_path`.
|
| 31 |
+
For restricting the search to a single file or directory, pass the `relative_path` parameter.
|
| 32 |
+
The retrieved symbols' `name_path` attribute will always be composed of symbol names, never file
|
| 33 |
+
or directory names.
|
| 34 |
+
|
| 35 |
+
Key aspects of the name path matching behavior:
|
| 36 |
+
- The name of the retrieved symbols will match the last segment of `name_path`, while preceding segments
|
| 37 |
+
will restrict the search to symbols that have a desired sequence of ancestors.
|
| 38 |
+
- If there is no `/` in `name_path`, there is no restriction on the ancestor symbols.
|
| 39 |
+
For example, passing `method` will match against all symbols with name paths like `method`,
|
| 40 |
+
`class/method`, `class/nested_class/method`, etc.
|
| 41 |
+
- If `name_path` contains at least one `/`, the matching is restricted to symbols
|
| 42 |
+
with the respective ancestors. For example, passing `class/method` will match against
|
| 43 |
+
`class/method` as well as `nested_class/class/method` but not `other_class/method`.
|
| 44 |
+
- If `name_path` starts with a `/`, it will be treated as an absolute name path pattern, i.e.
|
| 45 |
+
all ancestors are provided and must match.
|
| 46 |
+
For example, passing `/class` will match only against top-level symbols named `class` but
|
| 47 |
+
will not match `nested_class/class`. Passing `/class/method` will match `class/method` but
|
| 48 |
+
not `outer_class/class/method`.
|
| 49 |
+
|
| 50 |
+
:param name_path: The name path pattern to search for, see above for details.
|
| 51 |
+
:param depth: Depth to retrieve descendants (e.g., 1 for class methods/attributes).
|
| 52 |
+
:param relative_path: Optional. Restrict search to this file or directory.
|
| 53 |
+
If None, searches entire codebase.
|
| 54 |
+
If a directory is passed, the search will be restricted to the files in that directory.
|
| 55 |
+
If a file is passed, the search will be restricted to that file.
|
| 56 |
+
If you have some knowledge about the codebase, you should use this parameter, as it will significantly
|
| 57 |
+
speed up the search as well as reduce the number of results.
|
| 58 |
+
:param include_body: If True, include the symbol's source code. Use judiciously.
|
| 59 |
+
:param max_answer_chars: max characters for the JSON result. If exceeded, no content is returned.
|
| 60 |
+
-1 means the default value from the config will be used.
|
| 61 |
+
:return: JSON string: a list of symbols (with locations) matching the name.
|
| 62 |
+
"""
|
| 63 |
+
with JetBrainsPluginClient.from_project(self.project) as client:
|
| 64 |
+
response_dict = client.find_symbol(
|
| 65 |
+
name_path=name_path,
|
| 66 |
+
relative_path=relative_path,
|
| 67 |
+
depth=depth,
|
| 68 |
+
include_body=include_body,
|
| 69 |
+
)
|
| 70 |
+
result = json.dumps(response_dict)
|
| 71 |
+
return self._limit_length(result, max_answer_chars)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class JetBrainsFindReferencingSymbolsTool(Tool, ToolMarkerSymbolicRead, ToolMarkerOptional):
|
| 75 |
+
"""
|
| 76 |
+
Finds symbols that reference the given symbol
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
def apply(
|
| 80 |
+
self,
|
| 81 |
+
name_path: str,
|
| 82 |
+
relative_path: str,
|
| 83 |
+
max_answer_chars: int = -1,
|
| 84 |
+
) -> str:
|
| 85 |
+
"""
|
| 86 |
+
Finds symbols that reference the symbol at the given `name_path`.
|
| 87 |
+
The result will contain metadata about the referencing symbols.
|
| 88 |
+
|
| 89 |
+
:param name_path: name path of the symbol for which to find references; matching logic as described in find symbol tool.
|
| 90 |
+
:param relative_path: the relative path to the file containing the symbol for which to find references.
|
| 91 |
+
Note that here you can't pass a directory but must pass a file.
|
| 92 |
+
:param max_answer_chars: max characters for the JSON result. If exceeded, no content is returned. -1 means the
|
| 93 |
+
default value from the config will be used.
|
| 94 |
+
:return: a list of JSON objects with the symbols referencing the requested symbol
|
| 95 |
+
"""
|
| 96 |
+
with JetBrainsPluginClient.from_project(self.project) as client:
|
| 97 |
+
response_dict = client.find_references(
|
| 98 |
+
name_path=name_path,
|
| 99 |
+
relative_path=relative_path,
|
| 100 |
+
)
|
| 101 |
+
result = json.dumps(response_dict)
|
| 102 |
+
return self._limit_length(result, max_answer_chars)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
class JetBrainsGetSymbolsOverviewTool(Tool, ToolMarkerSymbolicRead, ToolMarkerOptional):
|
| 106 |
+
"""
|
| 107 |
+
Retrieves an overview of the top-level symbols within a specified file
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def apply(
|
| 111 |
+
self,
|
| 112 |
+
relative_path: str,
|
| 113 |
+
max_answer_chars: int = -1,
|
| 114 |
+
) -> str:
|
| 115 |
+
"""
|
| 116 |
+
Gets an overview of the top-level symbols in the given file.
|
| 117 |
+
Calling this is often a good idea before more targeted reading, searching or editing operations on the code symbols.
|
| 118 |
+
Before requesting a symbol overview, it is usually a good idea to narrow down the scope of the overview
|
| 119 |
+
by first understanding the basic directory structure of the repository that you can get from memories
|
| 120 |
+
or by using the `list_dir` and `find_file` tools (or similar).
|
| 121 |
+
|
| 122 |
+
:param relative_path: the relative path to the file to get the overview of
|
| 123 |
+
:param max_answer_chars: max characters for the JSON result. If exceeded, no content is returned.
|
| 124 |
+
-1 means the default value from the config will be used.
|
| 125 |
+
:return: a JSON object containing the symbols
|
| 126 |
+
"""
|
| 127 |
+
with JetBrainsPluginClient.from_project(self.project) as client:
|
| 128 |
+
response_dict = client.get_symbols_overview(
|
| 129 |
+
relative_path=relative_path,
|
| 130 |
+
)
|
| 131 |
+
result = json.dumps(response_dict)
|
| 132 |
+
return self._limit_length(result, max_answer_chars)
|
projects/ui/serena-new/src/serena/tools/memory_tools.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
|
| 3 |
+
from serena.tools import Tool
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class WriteMemoryTool(Tool):
|
| 7 |
+
"""
|
| 8 |
+
Writes a named memory (for future reference) to Serena's project-specific memory store.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
def apply(self, memory_name: str, content: str, max_answer_chars: int = -1) -> str:
|
| 12 |
+
"""
|
| 13 |
+
Write some information about this project that can be useful for future tasks to a memory in md format.
|
| 14 |
+
The memory name should be meaningful.
|
| 15 |
+
"""
|
| 16 |
+
if max_answer_chars == -1:
|
| 17 |
+
max_answer_chars = self.agent.serena_config.default_max_tool_answer_chars
|
| 18 |
+
if len(content) > max_answer_chars:
|
| 19 |
+
raise ValueError(
|
| 20 |
+
f"Content for {memory_name} is too long. Max length is {max_answer_chars} characters. " + "Please make the content shorter."
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
return self.memories_manager.save_memory(memory_name, content)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class ReadMemoryTool(Tool):
|
| 27 |
+
"""
|
| 28 |
+
Reads the memory with the given name from Serena's project-specific memory store.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def apply(self, memory_file_name: str, max_answer_chars: int = -1) -> str:
|
| 32 |
+
"""
|
| 33 |
+
Read the content of a memory file. This tool should only be used if the information
|
| 34 |
+
is relevant to the current task. You can infer whether the information
|
| 35 |
+
is relevant from the memory file name.
|
| 36 |
+
You should not read the same memory file multiple times in the same conversation.
|
| 37 |
+
"""
|
| 38 |
+
return self.memories_manager.load_memory(memory_file_name)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class ListMemoriesTool(Tool):
|
| 42 |
+
"""
|
| 43 |
+
Lists memories in Serena's project-specific memory store.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def apply(self) -> str:
|
| 47 |
+
"""
|
| 48 |
+
List available memories. Any memory can be read using the `read_memory` tool.
|
| 49 |
+
"""
|
| 50 |
+
return json.dumps(self.memories_manager.list_memories())
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class DeleteMemoryTool(Tool):
|
| 54 |
+
"""
|
| 55 |
+
Deletes a memory from Serena's project-specific memory store.
|
| 56 |
+
"""
|
| 57 |
+
|
| 58 |
+
def apply(self, memory_file_name: str) -> str:
|
| 59 |
+
"""
|
| 60 |
+
Delete a memory file. Should only happen if a user asks for it explicitly,
|
| 61 |
+
for example by saying that the information retrieved from a memory file is no longer correct
|
| 62 |
+
or no longer relevant for the project.
|
| 63 |
+
"""
|
| 64 |
+
return self.memories_manager.delete_memory(memory_file_name)
|
projects/ui/serena-new/src/serena/tools/symbol_tools.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Language server-related tools
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import dataclasses
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from collections.abc import Sequence
|
| 9 |
+
from copy import copy
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
from serena.tools import (
|
| 13 |
+
SUCCESS_RESULT,
|
| 14 |
+
Tool,
|
| 15 |
+
ToolMarkerSymbolicEdit,
|
| 16 |
+
ToolMarkerSymbolicRead,
|
| 17 |
+
)
|
| 18 |
+
from serena.tools.tools_base import ToolMarkerOptional
|
| 19 |
+
from solidlsp.ls_types import SymbolKind
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _sanitize_symbol_dict(symbol_dict: dict[str, Any]) -> dict[str, Any]:
|
| 23 |
+
"""
|
| 24 |
+
Sanitize a symbol dictionary inplace by removing unnecessary information.
|
| 25 |
+
"""
|
| 26 |
+
# We replace the location entry, which repeats line information already included in body_location
|
| 27 |
+
# and has unnecessary information on column, by just the relative path.
|
| 28 |
+
symbol_dict = copy(symbol_dict)
|
| 29 |
+
s_relative_path = symbol_dict.get("location", {}).get("relative_path")
|
| 30 |
+
if s_relative_path is not None:
|
| 31 |
+
symbol_dict["relative_path"] = s_relative_path
|
| 32 |
+
symbol_dict.pop("location", None)
|
| 33 |
+
# also remove name, name_path should be enough
|
| 34 |
+
symbol_dict.pop("name")
|
| 35 |
+
return symbol_dict
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class RestartLanguageServerTool(Tool, ToolMarkerOptional):
|
| 39 |
+
"""Restarts the language server, may be necessary when edits not through Serena happen."""
|
| 40 |
+
|
| 41 |
+
def apply(self) -> str:
|
| 42 |
+
"""Use this tool only on explicit user request or after confirmation.
|
| 43 |
+
It may be necessary to restart the language server if it hangs.
|
| 44 |
+
"""
|
| 45 |
+
self.agent.reset_language_server()
|
| 46 |
+
return SUCCESS_RESULT
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class GetSymbolsOverviewTool(Tool, ToolMarkerSymbolicRead):
|
| 50 |
+
"""
|
| 51 |
+
Gets an overview of the top-level symbols defined in a given file.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def apply(self, relative_path: str, max_answer_chars: int = -1) -> str:
|
| 55 |
+
"""
|
| 56 |
+
Use this tool to get a high-level understanding of the code symbols in a file.
|
| 57 |
+
This should be the first tool to call when you want to understand a new file, unless you already know
|
| 58 |
+
what you are looking for.
|
| 59 |
+
|
| 60 |
+
:param relative_path: the relative path to the file to get the overview of
|
| 61 |
+
:param max_answer_chars: if the overview is longer than this number of characters,
|
| 62 |
+
no content will be returned. -1 means the default value from the config will be used.
|
| 63 |
+
Don't adjust unless there is really no other way to get the content required for the task.
|
| 64 |
+
:return: a JSON object containing info about top-level symbols in the file
|
| 65 |
+
"""
|
| 66 |
+
symbol_retriever = self.create_language_server_symbol_retriever()
|
| 67 |
+
file_path = os.path.join(self.project.project_root, relative_path)
|
| 68 |
+
|
| 69 |
+
# The symbol overview is capable of working with both files and directories,
|
| 70 |
+
# but we want to ensure that the user provides a file path.
|
| 71 |
+
if not os.path.exists(file_path):
|
| 72 |
+
raise FileNotFoundError(f"File or directory {relative_path} does not exist in the project.")
|
| 73 |
+
if os.path.isdir(file_path):
|
| 74 |
+
raise ValueError(f"Expected a file path, but got a directory path: {relative_path}. ")
|
| 75 |
+
result = symbol_retriever.get_symbol_overview(relative_path)[relative_path]
|
| 76 |
+
result_json_str = json.dumps([dataclasses.asdict(i) for i in result])
|
| 77 |
+
return self._limit_length(result_json_str, max_answer_chars)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class FindSymbolTool(Tool, ToolMarkerSymbolicRead):
|
| 81 |
+
"""
|
| 82 |
+
Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def apply(
|
| 86 |
+
self,
|
| 87 |
+
name_path: str,
|
| 88 |
+
depth: int = 0,
|
| 89 |
+
relative_path: str = "",
|
| 90 |
+
include_body: bool = False,
|
| 91 |
+
include_kinds: list[int] = [], # noqa: B006
|
| 92 |
+
exclude_kinds: list[int] = [], # noqa: B006
|
| 93 |
+
substring_matching: bool = False,
|
| 94 |
+
max_answer_chars: int = -1,
|
| 95 |
+
) -> str:
|
| 96 |
+
"""
|
| 97 |
+
Retrieves information on all symbols/code entities (classes, methods, etc.) based on the given `name_path`,
|
| 98 |
+
which represents a pattern for the symbol's path within the symbol tree of a single file.
|
| 99 |
+
The returned symbol location can be used for edits or further queries.
|
| 100 |
+
Specify `depth > 0` to retrieve children (e.g., methods of a class).
|
| 101 |
+
|
| 102 |
+
The matching behavior is determined by the structure of `name_path`, which can
|
| 103 |
+
either be a simple name (e.g. "method") or a name path like "class/method" (relative name path)
|
| 104 |
+
or "/class/method" (absolute name path). Note that the name path is not a path in the file system
|
| 105 |
+
but rather a path in the symbol tree **within a single file**. Thus, file or directory names should never
|
| 106 |
+
be included in the `name_path`. For restricting the search to a single file or directory,
|
| 107 |
+
the `within_relative_path` parameter should be used instead. The retrieved symbols' `name_path` attribute
|
| 108 |
+
will always be composed of symbol names, never file or directory names.
|
| 109 |
+
|
| 110 |
+
Key aspects of the name path matching behavior:
|
| 111 |
+
- Trailing slashes in `name_path` play no role and are ignored.
|
| 112 |
+
- The name of the retrieved symbols will match (either exactly or as a substring)
|
| 113 |
+
the last segment of `name_path`, while other segments will restrict the search to symbols that
|
| 114 |
+
have a desired sequence of ancestors.
|
| 115 |
+
- If there is no starting or intermediate slash in `name_path`, there is no
|
| 116 |
+
restriction on the ancestor symbols. For example, passing `method` will match
|
| 117 |
+
against symbols with name paths like `method`, `class/method`, `class/nested_class/method`, etc.
|
| 118 |
+
- If `name_path` contains a `/` but doesn't start with a `/`, the matching is restricted to symbols
|
| 119 |
+
with the same ancestors as the last segment of `name_path`. For example, passing `class/method` will match against
|
| 120 |
+
`class/method` as well as `nested_class/class/method` but not `method`.
|
| 121 |
+
- If `name_path` starts with a `/`, it will be treated as an absolute name path pattern, meaning
|
| 122 |
+
that the first segment of it must match the first segment of the symbol's name path.
|
| 123 |
+
For example, passing `/class` will match only against top-level symbols like `class` but not against `nested_class/class`.
|
| 124 |
+
Passing `/class/method` will match against `class/method` but not `nested_class/class/method` or `method`.
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
:param name_path: The name path pattern to search for, see above for details.
|
| 128 |
+
:param depth: Depth to retrieve descendants (e.g., 1 for class methods/attributes).
|
| 129 |
+
:param relative_path: Optional. Restrict search to this file or directory. If None, searches entire codebase.
|
| 130 |
+
If a directory is passed, the search will be restricted to the files in that directory.
|
| 131 |
+
If a file is passed, the search will be restricted to that file.
|
| 132 |
+
If you have some knowledge about the codebase, you should use this parameter, as it will significantly
|
| 133 |
+
speed up the search as well as reduce the number of results.
|
| 134 |
+
:param include_body: If True, include the symbol's source code. Use judiciously.
|
| 135 |
+
:param include_kinds: Optional. List of LSP symbol kind integers to include. (e.g., 5 for Class, 12 for Function).
|
| 136 |
+
Valid kinds: 1=file, 2=module, 3=namespace, 4=package, 5=class, 6=method, 7=property, 8=field, 9=constructor, 10=enum,
|
| 137 |
+
11=interface, 12=function, 13=variable, 14=constant, 15=string, 16=number, 17=boolean, 18=array, 19=object,
|
| 138 |
+
20=key, 21=null, 22=enum member, 23=struct, 24=event, 25=operator, 26=type parameter.
|
| 139 |
+
If not provided, all kinds are included.
|
| 140 |
+
:param exclude_kinds: Optional. List of LSP symbol kind integers to exclude. Takes precedence over `include_kinds`.
|
| 141 |
+
If not provided, no kinds are excluded.
|
| 142 |
+
:param substring_matching: If True, use substring matching for the last segment of `name`.
|
| 143 |
+
:param max_answer_chars: Max characters for the JSON result. If exceeded, no content is returned.
|
| 144 |
+
-1 means the default value from the config will be used.
|
| 145 |
+
:return: a list of symbols (with locations) matching the name.
|
| 146 |
+
"""
|
| 147 |
+
parsed_include_kinds: Sequence[SymbolKind] | None = [SymbolKind(k) for k in include_kinds] if include_kinds else None
|
| 148 |
+
parsed_exclude_kinds: Sequence[SymbolKind] | None = [SymbolKind(k) for k in exclude_kinds] if exclude_kinds else None
|
| 149 |
+
symbol_retriever = self.create_language_server_symbol_retriever()
|
| 150 |
+
symbols = symbol_retriever.find_by_name(
|
| 151 |
+
name_path,
|
| 152 |
+
include_body=include_body,
|
| 153 |
+
include_kinds=parsed_include_kinds,
|
| 154 |
+
exclude_kinds=parsed_exclude_kinds,
|
| 155 |
+
substring_matching=substring_matching,
|
| 156 |
+
within_relative_path=relative_path,
|
| 157 |
+
)
|
| 158 |
+
symbol_dicts = [_sanitize_symbol_dict(s.to_dict(kind=True, location=True, depth=depth, include_body=include_body)) for s in symbols]
|
| 159 |
+
result = json.dumps(symbol_dicts)
|
| 160 |
+
return self._limit_length(result, max_answer_chars)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
class FindReferencingSymbolsTool(Tool, ToolMarkerSymbolicRead):
|
| 164 |
+
"""
|
| 165 |
+
Finds symbols that reference the symbol at the given location (optionally filtered by type).
|
| 166 |
+
"""
|
| 167 |
+
|
| 168 |
+
def apply(
|
| 169 |
+
self,
|
| 170 |
+
name_path: str,
|
| 171 |
+
relative_path: str,
|
| 172 |
+
include_kinds: list[int] = [], # noqa: B006
|
| 173 |
+
exclude_kinds: list[int] = [], # noqa: B006
|
| 174 |
+
max_answer_chars: int = -1,
|
| 175 |
+
) -> str:
|
| 176 |
+
"""
|
| 177 |
+
Finds references to the symbol at the given `name_path`. The result will contain metadata about the referencing symbols
|
| 178 |
+
as well as a short code snippet around the reference.
|
| 179 |
+
|
| 180 |
+
:param name_path: for finding the symbol to find references for, same logic as in the `find_symbol` tool.
|
| 181 |
+
:param relative_path: the relative path to the file containing the symbol for which to find references.
|
| 182 |
+
Note that here you can't pass a directory but must pass a file.
|
| 183 |
+
:param include_kinds: same as in the `find_symbol` tool.
|
| 184 |
+
:param exclude_kinds: same as in the `find_symbol` tool.
|
| 185 |
+
:param max_answer_chars: same as in the `find_symbol` tool.
|
| 186 |
+
:return: a list of JSON objects with the symbols referencing the requested symbol
|
| 187 |
+
"""
|
| 188 |
+
include_body = False # It is probably never a good idea to include the body of the referencing symbols
|
| 189 |
+
parsed_include_kinds: Sequence[SymbolKind] | None = [SymbolKind(k) for k in include_kinds] if include_kinds else None
|
| 190 |
+
parsed_exclude_kinds: Sequence[SymbolKind] | None = [SymbolKind(k) for k in exclude_kinds] if exclude_kinds else None
|
| 191 |
+
symbol_retriever = self.create_language_server_symbol_retriever()
|
| 192 |
+
references_in_symbols = symbol_retriever.find_referencing_symbols(
|
| 193 |
+
name_path,
|
| 194 |
+
relative_file_path=relative_path,
|
| 195 |
+
include_body=include_body,
|
| 196 |
+
include_kinds=parsed_include_kinds,
|
| 197 |
+
exclude_kinds=parsed_exclude_kinds,
|
| 198 |
+
)
|
| 199 |
+
reference_dicts = []
|
| 200 |
+
for ref in references_in_symbols:
|
| 201 |
+
ref_dict = ref.symbol.to_dict(kind=True, location=True, depth=0, include_body=include_body)
|
| 202 |
+
ref_dict = _sanitize_symbol_dict(ref_dict)
|
| 203 |
+
if not include_body:
|
| 204 |
+
ref_relative_path = ref.symbol.location.relative_path
|
| 205 |
+
assert ref_relative_path is not None, f"Referencing symbol {ref.symbol.name} has no relative path, this is likely a bug."
|
| 206 |
+
content_around_ref = self.project.retrieve_content_around_line(
|
| 207 |
+
relative_file_path=ref_relative_path, line=ref.line, context_lines_before=1, context_lines_after=1
|
| 208 |
+
)
|
| 209 |
+
ref_dict["content_around_reference"] = content_around_ref.to_display_string()
|
| 210 |
+
reference_dicts.append(ref_dict)
|
| 211 |
+
result = json.dumps(reference_dicts)
|
| 212 |
+
return self._limit_length(result, max_answer_chars)
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class ReplaceSymbolBodyTool(Tool, ToolMarkerSymbolicEdit):
|
| 216 |
+
"""
|
| 217 |
+
Replaces the full definition of a symbol.
|
| 218 |
+
"""
|
| 219 |
+
|
| 220 |
+
def apply(
|
| 221 |
+
self,
|
| 222 |
+
name_path: str,
|
| 223 |
+
relative_path: str,
|
| 224 |
+
body: str,
|
| 225 |
+
) -> str:
|
| 226 |
+
r"""
|
| 227 |
+
Replaces the body of the symbol with the given `name_path`.
|
| 228 |
+
|
| 229 |
+
:param name_path: for finding the symbol to replace, same logic as in the `find_symbol` tool.
|
| 230 |
+
:param relative_path: the relative path to the file containing the symbol
|
| 231 |
+
:param body: the new symbol body. Important: Begin directly with the symbol definition and provide no
|
| 232 |
+
leading indentation for the first line (but do indent the rest of the body according to the context).
|
| 233 |
+
"""
|
| 234 |
+
code_editor = self.create_code_editor()
|
| 235 |
+
code_editor.replace_body(
|
| 236 |
+
name_path,
|
| 237 |
+
relative_file_path=relative_path,
|
| 238 |
+
body=body,
|
| 239 |
+
)
|
| 240 |
+
return SUCCESS_RESULT
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
class InsertAfterSymbolTool(Tool, ToolMarkerSymbolicEdit):
|
| 244 |
+
"""
|
| 245 |
+
Inserts content after the end of the definition of a given symbol.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
def apply(
|
| 249 |
+
self,
|
| 250 |
+
name_path: str,
|
| 251 |
+
relative_path: str,
|
| 252 |
+
body: str,
|
| 253 |
+
) -> str:
|
| 254 |
+
"""
|
| 255 |
+
Inserts the given body/content after the end of the definition of the given symbol (via the symbol's location).
|
| 256 |
+
A typical use case is to insert a new class, function, method, field or variable assignment.
|
| 257 |
+
|
| 258 |
+
:param name_path: name path of the symbol after which to insert content (definitions in the `find_symbol` tool apply)
|
| 259 |
+
:param relative_path: the relative path to the file containing the symbol
|
| 260 |
+
:param body: the body/content to be inserted. The inserted code shall begin with the next line after
|
| 261 |
+
the symbol.
|
| 262 |
+
"""
|
| 263 |
+
code_editor = self.create_code_editor()
|
| 264 |
+
code_editor.insert_after_symbol(name_path, relative_file_path=relative_path, body=body)
|
| 265 |
+
return SUCCESS_RESULT
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
class InsertBeforeSymbolTool(Tool, ToolMarkerSymbolicEdit):
|
| 269 |
+
"""
|
| 270 |
+
Inserts content before the beginning of the definition of a given symbol.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def apply(
|
| 274 |
+
self,
|
| 275 |
+
name_path: str,
|
| 276 |
+
relative_path: str,
|
| 277 |
+
body: str,
|
| 278 |
+
) -> str:
|
| 279 |
+
"""
|
| 280 |
+
Inserts the given content before the beginning of the definition of the given symbol (via the symbol's location).
|
| 281 |
+
A typical use case is to insert a new class, function, method, field or variable assignment; or
|
| 282 |
+
a new import statement before the first symbol in the file.
|
| 283 |
+
|
| 284 |
+
:param name_path: name path of the symbol before which to insert content (definitions in the `find_symbol` tool apply)
|
| 285 |
+
:param relative_path: the relative path to the file containing the symbol
|
| 286 |
+
:param body: the body/content to be inserted before the line in which the referenced symbol is defined
|
| 287 |
+
"""
|
| 288 |
+
code_editor = self.create_code_editor()
|
| 289 |
+
code_editor.insert_before_symbol(name_path, relative_file_path=relative_path, body=body)
|
| 290 |
+
return SUCCESS_RESULT
|
projects/ui/serena-new/src/serena/tools/tools_base.py
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import inspect
|
| 2 |
+
import os
|
| 3 |
+
from abc import ABC
|
| 4 |
+
from collections.abc import Iterable
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from types import TracebackType
|
| 7 |
+
from typing import TYPE_CHECKING, Any, Protocol, Self, TypeVar
|
| 8 |
+
|
| 9 |
+
from mcp.server.fastmcp.utilities.func_metadata import FuncMetadata, func_metadata
|
| 10 |
+
from sensai.util import logging
|
| 11 |
+
from sensai.util.string import dict_string
|
| 12 |
+
|
| 13 |
+
from serena.project import Project
|
| 14 |
+
from serena.prompt_factory import PromptFactory
|
| 15 |
+
from serena.symbol import LanguageServerSymbolRetriever
|
| 16 |
+
from serena.util.class_decorators import singleton
|
| 17 |
+
from serena.util.inspection import iter_subclasses
|
| 18 |
+
from solidlsp.ls_exceptions import SolidLSPException
|
| 19 |
+
|
| 20 |
+
if TYPE_CHECKING:
|
| 21 |
+
from serena.agent import LinesRead, MemoriesManager, SerenaAgent
|
| 22 |
+
from serena.code_editor import CodeEditor
|
| 23 |
+
|
| 24 |
+
log = logging.getLogger(__name__)
|
| 25 |
+
T = TypeVar("T")
|
| 26 |
+
SUCCESS_RESULT = "OK"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Component(ABC):
|
| 30 |
+
def __init__(self, agent: "SerenaAgent"):
|
| 31 |
+
self.agent = agent
|
| 32 |
+
|
| 33 |
+
def get_project_root(self) -> str:
|
| 34 |
+
"""
|
| 35 |
+
:return: the root directory of the active project, raises a ValueError if no active project configuration is set
|
| 36 |
+
"""
|
| 37 |
+
return self.agent.get_project_root()
|
| 38 |
+
|
| 39 |
+
@property
|
| 40 |
+
def prompt_factory(self) -> PromptFactory:
|
| 41 |
+
return self.agent.prompt_factory
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def memories_manager(self) -> "MemoriesManager":
|
| 45 |
+
assert self.agent.memories_manager is not None
|
| 46 |
+
return self.agent.memories_manager
|
| 47 |
+
|
| 48 |
+
def create_language_server_symbol_retriever(self) -> LanguageServerSymbolRetriever:
|
| 49 |
+
if not self.agent.is_using_language_server():
|
| 50 |
+
raise Exception("Cannot create LanguageServerSymbolRetriever; agent is not in language server mode.")
|
| 51 |
+
language_server = self.agent.language_server
|
| 52 |
+
assert language_server is not None
|
| 53 |
+
return LanguageServerSymbolRetriever(language_server, agent=self.agent)
|
| 54 |
+
|
| 55 |
+
@property
|
| 56 |
+
def project(self) -> Project:
|
| 57 |
+
return self.agent.get_active_project_or_raise()
|
| 58 |
+
|
| 59 |
+
def create_code_editor(self) -> "CodeEditor":
|
| 60 |
+
from ..code_editor import JetBrainsCodeEditor, LanguageServerCodeEditor
|
| 61 |
+
|
| 62 |
+
if self.agent.is_using_language_server():
|
| 63 |
+
return LanguageServerCodeEditor(self.create_language_server_symbol_retriever(), agent=self.agent)
|
| 64 |
+
else:
|
| 65 |
+
return JetBrainsCodeEditor(project=self.project, agent=self.agent)
|
| 66 |
+
|
| 67 |
+
@property
|
| 68 |
+
def lines_read(self) -> "LinesRead":
|
| 69 |
+
assert self.agent.lines_read is not None
|
| 70 |
+
return self.agent.lines_read
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ToolMarker:
|
| 74 |
+
"""
|
| 75 |
+
Base class for tool markers.
|
| 76 |
+
"""
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class ToolMarkerCanEdit(ToolMarker):
|
| 80 |
+
"""
|
| 81 |
+
Marker class for all tools that can perform editing operations on files.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class ToolMarkerDoesNotRequireActiveProject(ToolMarker):
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class ToolMarkerOptional(ToolMarker):
|
| 90 |
+
"""
|
| 91 |
+
Marker class for optional tools that are disabled by default.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ToolMarkerSymbolicRead(ToolMarker):
|
| 96 |
+
"""
|
| 97 |
+
Marker class for tools that perform symbol read operations.
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class ToolMarkerSymbolicEdit(ToolMarkerCanEdit):
|
| 102 |
+
"""
|
| 103 |
+
Marker class for tools that perform symbolic edit operations.
|
| 104 |
+
"""
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class ApplyMethodProtocol(Protocol):
|
| 108 |
+
"""Callable protocol for the apply method of a tool."""
|
| 109 |
+
|
| 110 |
+
def __call__(self, *args: Any, **kwargs: Any) -> str:
|
| 111 |
+
pass
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class Tool(Component):
|
| 115 |
+
# NOTE: each tool should implement the apply method, which is then used in
|
| 116 |
+
# the central method of the Tool class `apply_ex`.
|
| 117 |
+
# Failure to do so will result in a RuntimeError at tool execution time.
|
| 118 |
+
# The apply method is not declared as part of the base Tool interface since we cannot
|
| 119 |
+
# know the signature of the (input parameters of the) method in advance.
|
| 120 |
+
#
|
| 121 |
+
# The docstring and types of the apply method are used to generate the tool description
|
| 122 |
+
# (which is use by the LLM, so a good description is important)
|
| 123 |
+
# and to validate the tool call arguments.
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
def get_name_from_cls(cls) -> str:
|
| 127 |
+
name = cls.__name__
|
| 128 |
+
if name.endswith("Tool"):
|
| 129 |
+
name = name[:-4]
|
| 130 |
+
# convert to snake_case
|
| 131 |
+
name = "".join(["_" + c.lower() if c.isupper() else c for c in name]).lstrip("_")
|
| 132 |
+
return name
|
| 133 |
+
|
| 134 |
+
def get_name(self) -> str:
|
| 135 |
+
return self.get_name_from_cls()
|
| 136 |
+
|
| 137 |
+
def get_apply_fn(self) -> ApplyMethodProtocol:
|
| 138 |
+
apply_fn = getattr(self, "apply")
|
| 139 |
+
if apply_fn is None:
|
| 140 |
+
raise RuntimeError(f"apply not defined in {self}. Did you forget to implement it?")
|
| 141 |
+
return apply_fn
|
| 142 |
+
|
| 143 |
+
@classmethod
|
| 144 |
+
def can_edit(cls) -> bool:
|
| 145 |
+
"""
|
| 146 |
+
Returns whether this tool can perform editing operations on code.
|
| 147 |
+
|
| 148 |
+
:return: True if the tool can edit code, False otherwise
|
| 149 |
+
"""
|
| 150 |
+
return issubclass(cls, ToolMarkerCanEdit)
|
| 151 |
+
|
| 152 |
+
@classmethod
|
| 153 |
+
def get_tool_description(cls) -> str:
|
| 154 |
+
docstring = cls.__doc__
|
| 155 |
+
if docstring is None:
|
| 156 |
+
return ""
|
| 157 |
+
return docstring.strip()
|
| 158 |
+
|
| 159 |
+
@classmethod
|
| 160 |
+
def get_apply_docstring_from_cls(cls) -> str:
|
| 161 |
+
"""Get the docstring for the apply method from the class (static metadata).
|
| 162 |
+
Needed for creating MCP tools in a separate process without running into serialization issues.
|
| 163 |
+
"""
|
| 164 |
+
# First try to get from __dict__ to handle dynamic docstring changes
|
| 165 |
+
if "apply" in cls.__dict__:
|
| 166 |
+
apply_fn = cls.__dict__["apply"]
|
| 167 |
+
else:
|
| 168 |
+
# Fall back to getattr for inherited methods
|
| 169 |
+
apply_fn = getattr(cls, "apply", None)
|
| 170 |
+
if apply_fn is None:
|
| 171 |
+
raise AttributeError(f"apply method not defined in {cls}. Did you forget to implement it?")
|
| 172 |
+
|
| 173 |
+
docstring = apply_fn.__doc__
|
| 174 |
+
if not docstring:
|
| 175 |
+
raise AttributeError(f"apply method has no (or empty) docstring in {cls}. Did you forget to implement it?")
|
| 176 |
+
return docstring.strip()
|
| 177 |
+
|
| 178 |
+
def get_apply_docstring(self) -> str:
|
| 179 |
+
"""Gets the docstring for the tool application, used by the MCP server."""
|
| 180 |
+
return self.get_apply_docstring_from_cls()
|
| 181 |
+
|
| 182 |
+
def get_apply_fn_metadata(self) -> FuncMetadata:
|
| 183 |
+
"""Gets the metadata for the tool application function, used by the MCP server."""
|
| 184 |
+
return self.get_apply_fn_metadata_from_cls()
|
| 185 |
+
|
| 186 |
+
@classmethod
|
| 187 |
+
def get_apply_fn_metadata_from_cls(cls) -> FuncMetadata:
|
| 188 |
+
"""Get the metadata for the apply method from the class (static metadata).
|
| 189 |
+
Needed for creating MCP tools in a separate process without running into serialization issues.
|
| 190 |
+
"""
|
| 191 |
+
# First try to get from __dict__ to handle dynamic docstring changes
|
| 192 |
+
if "apply" in cls.__dict__:
|
| 193 |
+
apply_fn = cls.__dict__["apply"]
|
| 194 |
+
else:
|
| 195 |
+
# Fall back to getattr for inherited methods
|
| 196 |
+
apply_fn = getattr(cls, "apply", None)
|
| 197 |
+
if apply_fn is None:
|
| 198 |
+
raise AttributeError(f"apply method not defined in {cls}. Did you forget to implement it?")
|
| 199 |
+
|
| 200 |
+
return func_metadata(apply_fn, skip_names=["self", "cls"])
|
| 201 |
+
|
| 202 |
+
def _log_tool_application(self, frame: Any) -> None:
|
| 203 |
+
params = {}
|
| 204 |
+
ignored_params = {"self", "log_call", "catch_exceptions", "args", "apply_fn"}
|
| 205 |
+
for param, value in frame.f_locals.items():
|
| 206 |
+
if param in ignored_params:
|
| 207 |
+
continue
|
| 208 |
+
if param == "kwargs":
|
| 209 |
+
params.update(value)
|
| 210 |
+
else:
|
| 211 |
+
params[param] = value
|
| 212 |
+
log.info(f"{self.get_name_from_cls()}: {dict_string(params)}")
|
| 213 |
+
|
| 214 |
+
def _limit_length(self, result: str, max_answer_chars: int) -> str:
|
| 215 |
+
if max_answer_chars == -1:
|
| 216 |
+
max_answer_chars = self.agent.serena_config.default_max_tool_answer_chars
|
| 217 |
+
if max_answer_chars <= 0:
|
| 218 |
+
raise ValueError(f"Must be positive or the default (-1), got: {max_answer_chars=}")
|
| 219 |
+
if (n_chars := len(result)) > max_answer_chars:
|
| 220 |
+
result = (
|
| 221 |
+
f"The answer is too long ({n_chars} characters). "
|
| 222 |
+
+ "Please try a more specific tool query or raise the max_answer_chars parameter."
|
| 223 |
+
)
|
| 224 |
+
return result
|
| 225 |
+
|
| 226 |
+
def is_active(self) -> bool:
|
| 227 |
+
return self.agent.tool_is_active(self.__class__)
|
| 228 |
+
|
| 229 |
+
def apply_ex(self, log_call: bool = True, catch_exceptions: bool = True, **kwargs) -> str: # type: ignore
|
| 230 |
+
"""
|
| 231 |
+
Applies the tool with logging and exception handling, using the given keyword arguments
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
def task() -> str:
|
| 235 |
+
apply_fn = self.get_apply_fn()
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
if not self.is_active():
|
| 239 |
+
return f"Error: Tool '{self.get_name_from_cls()}' is not active. Active tools: {self.agent.get_active_tool_names()}"
|
| 240 |
+
except Exception as e:
|
| 241 |
+
return f"RuntimeError while checking if tool {self.get_name_from_cls()} is active: {e}"
|
| 242 |
+
|
| 243 |
+
if log_call:
|
| 244 |
+
self._log_tool_application(inspect.currentframe())
|
| 245 |
+
try:
|
| 246 |
+
# check whether the tool requires an active project and language server
|
| 247 |
+
if not isinstance(self, ToolMarkerDoesNotRequireActiveProject):
|
| 248 |
+
if self.agent._active_project is None:
|
| 249 |
+
return (
|
| 250 |
+
"Error: No active project. Ask to user to select a project from this list: "
|
| 251 |
+
+ f"{self.agent.serena_config.project_names}"
|
| 252 |
+
)
|
| 253 |
+
if self.agent.is_using_language_server() and not self.agent.is_language_server_running():
|
| 254 |
+
log.info("Language server is not running. Starting it ...")
|
| 255 |
+
self.agent.reset_language_server()
|
| 256 |
+
|
| 257 |
+
# apply the actual tool
|
| 258 |
+
try:
|
| 259 |
+
result = apply_fn(**kwargs)
|
| 260 |
+
except SolidLSPException as e:
|
| 261 |
+
if e.is_language_server_terminated():
|
| 262 |
+
log.error(f"Language server terminated while executing tool ({e}). Restarting the language server and retrying ...")
|
| 263 |
+
self.agent.reset_language_server()
|
| 264 |
+
result = apply_fn(**kwargs)
|
| 265 |
+
else:
|
| 266 |
+
raise
|
| 267 |
+
|
| 268 |
+
# record tool usage
|
| 269 |
+
self.agent.record_tool_usage_if_enabled(kwargs, result, self)
|
| 270 |
+
|
| 271 |
+
except Exception as e:
|
| 272 |
+
if not catch_exceptions:
|
| 273 |
+
raise
|
| 274 |
+
msg = f"Error executing tool: {e}"
|
| 275 |
+
log.error(f"Error executing tool: {e}", exc_info=e)
|
| 276 |
+
result = msg
|
| 277 |
+
|
| 278 |
+
if log_call:
|
| 279 |
+
log.info(f"Result: {result}")
|
| 280 |
+
|
| 281 |
+
try:
|
| 282 |
+
if self.agent.language_server is not None:
|
| 283 |
+
self.agent.language_server.save_cache()
|
| 284 |
+
except Exception as e:
|
| 285 |
+
log.error(f"Error saving language server cache: {e}")
|
| 286 |
+
|
| 287 |
+
return result
|
| 288 |
+
|
| 289 |
+
future = self.agent.issue_task(task, name=self.__class__.__name__)
|
| 290 |
+
return future.result(timeout=self.agent.serena_config.tool_timeout)
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class EditedFileContext:
|
| 294 |
+
"""
|
| 295 |
+
Context manager for file editing.
|
| 296 |
+
|
| 297 |
+
Create the context, then use `set_updated_content` to set the new content, the original content
|
| 298 |
+
being provided in `original_content`.
|
| 299 |
+
When exiting the context without an exception, the updated content will be written back to the file.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def __init__(self, relative_path: str, agent: "SerenaAgent"):
|
| 303 |
+
self._project = agent.get_active_project()
|
| 304 |
+
assert self._project is not None
|
| 305 |
+
self._abs_path = os.path.join(self._project.project_root, relative_path)
|
| 306 |
+
if not os.path.isfile(self._abs_path):
|
| 307 |
+
raise FileNotFoundError(f"File {self._abs_path} does not exist.")
|
| 308 |
+
with open(self._abs_path, encoding=self._project.project_config.encoding) as f:
|
| 309 |
+
self._original_content = f.read()
|
| 310 |
+
self._updated_content: str | None = None
|
| 311 |
+
|
| 312 |
+
def __enter__(self) -> Self:
|
| 313 |
+
return self
|
| 314 |
+
|
| 315 |
+
def get_original_content(self) -> str:
|
| 316 |
+
"""
|
| 317 |
+
:return: the original content of the file before any modifications.
|
| 318 |
+
"""
|
| 319 |
+
return self._original_content
|
| 320 |
+
|
| 321 |
+
def set_updated_content(self, content: str) -> None:
|
| 322 |
+
"""
|
| 323 |
+
Sets the updated content of the file, which will be written back to the file
|
| 324 |
+
when the context is exited without an exception.
|
| 325 |
+
|
| 326 |
+
:param content: the updated content of the file
|
| 327 |
+
"""
|
| 328 |
+
self._updated_content = content
|
| 329 |
+
|
| 330 |
+
def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None:
|
| 331 |
+
if self._updated_content is not None and exc_type is None:
|
| 332 |
+
assert self._project is not None
|
| 333 |
+
with open(self._abs_path, "w", encoding=self._project.project_config.encoding) as f:
|
| 334 |
+
f.write(self._updated_content)
|
| 335 |
+
log.info(f"Updated content written to {self._abs_path}")
|
| 336 |
+
# Language servers should automatically detect the change and update its state accordingly.
|
| 337 |
+
# If they do not, we may have to add a call to notify it.
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
@dataclass(kw_only=True)
|
| 341 |
+
class RegisteredTool:
|
| 342 |
+
tool_class: type[Tool]
|
| 343 |
+
is_optional: bool
|
| 344 |
+
tool_name: str
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@singleton
|
| 348 |
+
class ToolRegistry:
|
| 349 |
+
def __init__(self) -> None:
|
| 350 |
+
self._tool_dict: dict[str, RegisteredTool] = {}
|
| 351 |
+
for cls in iter_subclasses(Tool):
|
| 352 |
+
if not cls.__module__.startswith("serena.tools"):
|
| 353 |
+
continue
|
| 354 |
+
is_optional = issubclass(cls, ToolMarkerOptional)
|
| 355 |
+
name = cls.get_name_from_cls()
|
| 356 |
+
if name in self._tool_dict:
|
| 357 |
+
raise ValueError(f"Duplicate tool name found: {name}. Tool classes must have unique names.")
|
| 358 |
+
self._tool_dict[name] = RegisteredTool(tool_class=cls, is_optional=is_optional, tool_name=name)
|
| 359 |
+
|
| 360 |
+
def get_tool_class_by_name(self, tool_name: str) -> type[Tool]:
|
| 361 |
+
return self._tool_dict[tool_name].tool_class
|
| 362 |
+
|
| 363 |
+
def get_all_tool_classes(self) -> list[type[Tool]]:
|
| 364 |
+
return list(t.tool_class for t in self._tool_dict.values())
|
| 365 |
+
|
| 366 |
+
def get_tool_classes_default_enabled(self) -> list[type[Tool]]:
|
| 367 |
+
"""
|
| 368 |
+
:return: the list of tool classes that are enabled by default (i.e. non-optional tools).
|
| 369 |
+
"""
|
| 370 |
+
return [t.tool_class for t in self._tool_dict.values() if not t.is_optional]
|
| 371 |
+
|
| 372 |
+
def get_tool_classes_optional(self) -> list[type[Tool]]:
|
| 373 |
+
"""
|
| 374 |
+
:return: the list of tool classes that are optional (i.e. disabled by default).
|
| 375 |
+
"""
|
| 376 |
+
return [t.tool_class for t in self._tool_dict.values() if t.is_optional]
|
| 377 |
+
|
| 378 |
+
def get_tool_names_default_enabled(self) -> list[str]:
|
| 379 |
+
"""
|
| 380 |
+
:return: the list of tool names that are enabled by default (i.e. non-optional tools).
|
| 381 |
+
"""
|
| 382 |
+
return [t.tool_name for t in self._tool_dict.values() if not t.is_optional]
|
| 383 |
+
|
| 384 |
+
def get_tool_names_optional(self) -> list[str]:
|
| 385 |
+
"""
|
| 386 |
+
:return: the list of tool names that are optional (i.e. disabled by default).
|
| 387 |
+
"""
|
| 388 |
+
return [t.tool_name for t in self._tool_dict.values() if t.is_optional]
|
| 389 |
+
|
| 390 |
+
def get_tool_names(self) -> list[str]:
|
| 391 |
+
"""
|
| 392 |
+
:return: the list of all tool names.
|
| 393 |
+
"""
|
| 394 |
+
return list(self._tool_dict.keys())
|
| 395 |
+
|
| 396 |
+
def print_tool_overview(
|
| 397 |
+
self, tools: Iterable[type[Tool] | Tool] | None = None, include_optional: bool = False, only_optional: bool = False
|
| 398 |
+
) -> None:
|
| 399 |
+
"""
|
| 400 |
+
Print a summary of the tools. If no tools are passed, a summary of the selection of tools (all, default or only optional) is printed.
|
| 401 |
+
"""
|
| 402 |
+
if tools is None:
|
| 403 |
+
if only_optional:
|
| 404 |
+
tools = self.get_tool_classes_optional()
|
| 405 |
+
elif include_optional:
|
| 406 |
+
tools = self.get_all_tool_classes()
|
| 407 |
+
else:
|
| 408 |
+
tools = self.get_tool_classes_default_enabled()
|
| 409 |
+
|
| 410 |
+
tool_dict: dict[str, type[Tool] | Tool] = {}
|
| 411 |
+
for tool_class in tools:
|
| 412 |
+
tool_dict[tool_class.get_name_from_cls()] = tool_class
|
| 413 |
+
for tool_name in sorted(tool_dict.keys()):
|
| 414 |
+
tool_class = tool_dict[tool_name]
|
| 415 |
+
print(f" * `{tool_name}`: {tool_class.get_tool_description().strip()}")
|
| 416 |
+
|
| 417 |
+
def is_valid_tool_name(self, tool_name: str) -> bool:
|
| 418 |
+
return tool_name in self._tool_dict
|
projects/ui/serena-new/src/serena/tools/workflow_tools.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Tools supporting the general workflow of the agent
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import platform
|
| 7 |
+
|
| 8 |
+
from serena.tools import Tool, ToolMarkerDoesNotRequireActiveProject, ToolMarkerOptional
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class CheckOnboardingPerformedTool(Tool):
|
| 12 |
+
"""
|
| 13 |
+
Checks whether project onboarding was already performed.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
def apply(self) -> str:
|
| 17 |
+
"""
|
| 18 |
+
Checks whether project onboarding was already performed.
|
| 19 |
+
You should always call this tool before beginning to actually work on the project/after activating a project,
|
| 20 |
+
but after calling the initial instructions tool.
|
| 21 |
+
"""
|
| 22 |
+
from .memory_tools import ListMemoriesTool
|
| 23 |
+
|
| 24 |
+
list_memories_tool = self.agent.get_tool(ListMemoriesTool)
|
| 25 |
+
memories = json.loads(list_memories_tool.apply())
|
| 26 |
+
if len(memories) == 0:
|
| 27 |
+
return (
|
| 28 |
+
"Onboarding not performed yet (no memories available). "
|
| 29 |
+
+ "You should perform onboarding by calling the `onboarding` tool before proceeding with the task."
|
| 30 |
+
)
|
| 31 |
+
else:
|
| 32 |
+
return f"""The onboarding was already performed, below is the list of available memories.
|
| 33 |
+
Do not read them immediately, just remember that they exist and that you can read them later, if it is necessary
|
| 34 |
+
for the current task.
|
| 35 |
+
Some memories may be based on previous conversations, others may be general for the current project.
|
| 36 |
+
You should be able to tell which one you need based on the name of the memory.
|
| 37 |
+
|
| 38 |
+
{memories}"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class OnboardingTool(Tool):
|
| 42 |
+
"""
|
| 43 |
+
Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def apply(self) -> str:
|
| 47 |
+
"""
|
| 48 |
+
Call this tool if onboarding was not performed yet.
|
| 49 |
+
You will call this tool at most once per conversation.
|
| 50 |
+
|
| 51 |
+
:return: instructions on how to create the onboarding information
|
| 52 |
+
"""
|
| 53 |
+
system = platform.system()
|
| 54 |
+
return self.prompt_factory.create_onboarding_prompt(system=system)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class ThinkAboutCollectedInformationTool(Tool):
|
| 58 |
+
"""
|
| 59 |
+
Thinking tool for pondering the completeness of collected information.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def apply(self) -> str:
|
| 63 |
+
"""
|
| 64 |
+
Think about the collected information and whether it is sufficient and relevant.
|
| 65 |
+
This tool should ALWAYS be called after you have completed a non-trivial sequence of searching steps like
|
| 66 |
+
find_symbol, find_referencing_symbols, search_files_for_pattern, read_file, etc.
|
| 67 |
+
"""
|
| 68 |
+
return self.prompt_factory.create_think_about_collected_information()
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class ThinkAboutTaskAdherenceTool(Tool):
|
| 72 |
+
"""
|
| 73 |
+
Thinking tool for determining whether the agent is still on track with the current task.
|
| 74 |
+
"""
|
| 75 |
+
|
| 76 |
+
def apply(self) -> str:
|
| 77 |
+
"""
|
| 78 |
+
Think about the task at hand and whether you are still on track.
|
| 79 |
+
Especially important if the conversation has been going on for a while and there
|
| 80 |
+
has been a lot of back and forth.
|
| 81 |
+
|
| 82 |
+
This tool should ALWAYS be called before you insert, replace, or delete code.
|
| 83 |
+
"""
|
| 84 |
+
return self.prompt_factory.create_think_about_task_adherence()
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class ThinkAboutWhetherYouAreDoneTool(Tool):
|
| 88 |
+
"""
|
| 89 |
+
Thinking tool for determining whether the task is truly completed.
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
def apply(self) -> str:
|
| 93 |
+
"""
|
| 94 |
+
Whenever you feel that you are done with what the user has asked for, it is important to call this tool.
|
| 95 |
+
"""
|
| 96 |
+
return self.prompt_factory.create_think_about_whether_you_are_done()
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class SummarizeChangesTool(Tool, ToolMarkerOptional):
|
| 100 |
+
"""
|
| 101 |
+
Provides instructions for summarizing the changes made to the codebase.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def apply(self) -> str:
|
| 105 |
+
"""
|
| 106 |
+
Summarize the changes you have made to the codebase.
|
| 107 |
+
This tool should always be called after you have fully completed any non-trivial coding task,
|
| 108 |
+
but only after the think_about_whether_you_are_done call.
|
| 109 |
+
"""
|
| 110 |
+
return self.prompt_factory.create_summarize_changes()
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class PrepareForNewConversationTool(Tool):
|
| 114 |
+
"""
|
| 115 |
+
Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
def apply(self) -> str:
|
| 119 |
+
"""
|
| 120 |
+
Instructions for preparing for a new conversation. This tool should only be called on explicit user request.
|
| 121 |
+
"""
|
| 122 |
+
return self.prompt_factory.create_prepare_for_new_conversation()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class InitialInstructionsTool(Tool, ToolMarkerDoesNotRequireActiveProject, ToolMarkerOptional):
|
| 126 |
+
"""
|
| 127 |
+
Gets the initial instructions for the current project.
|
| 128 |
+
Should only be used in settings where the system prompt cannot be set,
|
| 129 |
+
e.g. in clients you have no control over, like Claude Desktop.
|
| 130 |
+
"""
|
| 131 |
+
|
| 132 |
+
def apply(self) -> str:
|
| 133 |
+
"""
|
| 134 |
+
Get the initial instructions for the current coding project.
|
| 135 |
+
If you haven't received instructions on how to use Serena's tools in the system prompt,
|
| 136 |
+
you should always call this tool before starting to work (including using any other tool) on any programming task,
|
| 137 |
+
the only exception being when you are asked to call `activate_project`, which you should then call before.
|
| 138 |
+
"""
|
| 139 |
+
return self.agent.create_system_prompt()
|
projects/ui/serena-new/src/serena/util/class_decorators.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
# duplicate of interprompt.class_decorators
|
| 5 |
+
# We don't want to depend on interprompt for this in serena, so we duplicate it here
|
| 6 |
+
def singleton(cls: type[Any]) -> Any:
|
| 7 |
+
instance = None
|
| 8 |
+
|
| 9 |
+
def get_instance(*args: Any, **kwargs: Any) -> Any:
|
| 10 |
+
nonlocal instance
|
| 11 |
+
if instance is None:
|
| 12 |
+
instance = cls(*args, **kwargs)
|
| 13 |
+
return instance
|
| 14 |
+
|
| 15 |
+
return get_instance
|
projects/ui/serena-new/src/serena/util/exception.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
|
| 4 |
+
from serena.agent import log
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def is_headless_environment() -> bool:
|
| 8 |
+
"""
|
| 9 |
+
Detect if we're running in a headless environment where GUI operations would fail.
|
| 10 |
+
|
| 11 |
+
Returns True if:
|
| 12 |
+
- No DISPLAY variable on Linux/Unix
|
| 13 |
+
- Running in SSH session
|
| 14 |
+
- Running in WSL without X server
|
| 15 |
+
- Running in Docker container
|
| 16 |
+
"""
|
| 17 |
+
# Check if we're on Windows - GUI usually works there
|
| 18 |
+
if sys.platform == "win32":
|
| 19 |
+
return False
|
| 20 |
+
|
| 21 |
+
# Check for DISPLAY variable (required for X11)
|
| 22 |
+
if not os.environ.get("DISPLAY"): # type: ignore
|
| 23 |
+
return True
|
| 24 |
+
|
| 25 |
+
# Check for SSH session
|
| 26 |
+
if os.environ.get("SSH_CONNECTION") or os.environ.get("SSH_CLIENT"):
|
| 27 |
+
return True
|
| 28 |
+
|
| 29 |
+
# Check for common CI/container environments
|
| 30 |
+
if os.environ.get("CI") or os.environ.get("CONTAINER") or os.path.exists("/.dockerenv"):
|
| 31 |
+
return True
|
| 32 |
+
|
| 33 |
+
# Check for WSL (only on Unix-like systems where os.uname exists)
|
| 34 |
+
if hasattr(os, "uname"):
|
| 35 |
+
if "microsoft" in os.uname().release.lower():
|
| 36 |
+
# In WSL, even with DISPLAY set, X server might not be running
|
| 37 |
+
# This is a simplified check - could be improved
|
| 38 |
+
return True
|
| 39 |
+
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def show_fatal_exception_safe(e: Exception) -> None:
|
| 44 |
+
"""
|
| 45 |
+
Shows the given exception in the GUI log viewer on the main thread and ensures that the exception is logged or at
|
| 46 |
+
least printed to stderr.
|
| 47 |
+
"""
|
| 48 |
+
# Log the error and print it to stderr
|
| 49 |
+
log.error(f"Fatal exception: {e}", exc_info=e)
|
| 50 |
+
print(f"Fatal exception: {e}", file=sys.stderr)
|
| 51 |
+
|
| 52 |
+
# Don't attempt GUI in headless environments
|
| 53 |
+
if is_headless_environment():
|
| 54 |
+
log.debug("Skipping GUI error display in headless environment")
|
| 55 |
+
return
|
| 56 |
+
|
| 57 |
+
# attempt to show the error in the GUI
|
| 58 |
+
try:
|
| 59 |
+
# NOTE: The import can fail on macOS if Tk is not available (depends on Python interpreter installation, which uv
|
| 60 |
+
# used as a base); while tkinter as such is always available, its dependencies can be unavailable on macOS.
|
| 61 |
+
from serena.gui_log_viewer import show_fatal_exception
|
| 62 |
+
|
| 63 |
+
show_fatal_exception(e)
|
| 64 |
+
except Exception as gui_error:
|
| 65 |
+
log.debug(f"Failed to show GUI error dialog: {gui_error}")
|
projects/ui/serena-new/src/serena/util/file_system.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import os
|
| 3 |
+
from collections.abc import Callable, Iterator
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import NamedTuple
|
| 7 |
+
|
| 8 |
+
import pathspec
|
| 9 |
+
from pathspec import PathSpec
|
| 10 |
+
from sensai.util.logging import LogTime
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ScanResult(NamedTuple):
|
| 16 |
+
"""Result of scanning a directory."""
|
| 17 |
+
|
| 18 |
+
directories: list[str]
|
| 19 |
+
files: list[str]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def scan_directory(
|
| 23 |
+
path: str,
|
| 24 |
+
recursive: bool = False,
|
| 25 |
+
relative_to: str | None = None,
|
| 26 |
+
is_ignored_dir: Callable[[str], bool] = lambda x: False,
|
| 27 |
+
is_ignored_file: Callable[[str], bool] = lambda x: False,
|
| 28 |
+
) -> ScanResult:
|
| 29 |
+
"""
|
| 30 |
+
:param path: the path to scan
|
| 31 |
+
:param recursive: whether to recursively scan subdirectories
|
| 32 |
+
:param relative_to: the path to which the results should be relative to; if None, provide absolute paths
|
| 33 |
+
:param is_ignored_dir: a function with which to determine whether the given directory (abs. path) shall be ignored
|
| 34 |
+
:param is_ignored_file: a function with which to determine whether the given file (abs. path) shall be ignored
|
| 35 |
+
:return: the list of directories and files
|
| 36 |
+
"""
|
| 37 |
+
files = []
|
| 38 |
+
directories = []
|
| 39 |
+
|
| 40 |
+
abs_path = os.path.abspath(path)
|
| 41 |
+
rel_base = os.path.abspath(relative_to) if relative_to else None
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
with os.scandir(abs_path) as entries:
|
| 45 |
+
for entry in entries:
|
| 46 |
+
try:
|
| 47 |
+
entry_path = entry.path
|
| 48 |
+
|
| 49 |
+
if rel_base:
|
| 50 |
+
result_path = os.path.relpath(entry_path, rel_base)
|
| 51 |
+
else:
|
| 52 |
+
result_path = entry_path
|
| 53 |
+
|
| 54 |
+
if entry.is_file():
|
| 55 |
+
if not is_ignored_file(entry_path):
|
| 56 |
+
files.append(result_path)
|
| 57 |
+
elif entry.is_dir():
|
| 58 |
+
if not is_ignored_dir(entry_path):
|
| 59 |
+
directories.append(result_path)
|
| 60 |
+
if recursive:
|
| 61 |
+
sub_result = scan_directory(
|
| 62 |
+
entry_path,
|
| 63 |
+
recursive=True,
|
| 64 |
+
relative_to=relative_to,
|
| 65 |
+
is_ignored_dir=is_ignored_dir,
|
| 66 |
+
is_ignored_file=is_ignored_file,
|
| 67 |
+
)
|
| 68 |
+
files.extend(sub_result.files)
|
| 69 |
+
directories.extend(sub_result.directories)
|
| 70 |
+
except PermissionError as ex:
|
| 71 |
+
# Skip files/directories that cannot be accessed due to permission issues
|
| 72 |
+
log.debug(f"Skipping entry due to permission error: {entry.path}", exc_info=ex)
|
| 73 |
+
continue
|
| 74 |
+
except PermissionError as ex:
|
| 75 |
+
# Skip the entire directory if it cannot be accessed
|
| 76 |
+
log.debug(f"Skipping directory due to permission error: {abs_path}", exc_info=ex)
|
| 77 |
+
return ScanResult([], [])
|
| 78 |
+
|
| 79 |
+
return ScanResult(directories, files)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def find_all_non_ignored_files(repo_root: str) -> list[str]:
|
| 83 |
+
"""
|
| 84 |
+
Find all non-ignored files in the repository, respecting all gitignore files in the repository.
|
| 85 |
+
|
| 86 |
+
:param repo_root: The root directory of the repository
|
| 87 |
+
:return: A list of all non-ignored files in the repository
|
| 88 |
+
"""
|
| 89 |
+
gitignore_parser = GitignoreParser(repo_root)
|
| 90 |
+
_, files = scan_directory(
|
| 91 |
+
repo_root, recursive=True, is_ignored_dir=gitignore_parser.should_ignore, is_ignored_file=gitignore_parser.should_ignore
|
| 92 |
+
)
|
| 93 |
+
return files
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@dataclass
|
| 97 |
+
class GitignoreSpec:
|
| 98 |
+
file_path: str
|
| 99 |
+
"""Path to the gitignore file."""
|
| 100 |
+
patterns: list[str] = field(default_factory=list)
|
| 101 |
+
"""List of patterns from the gitignore file.
|
| 102 |
+
The patterns are adjusted based on the gitignore file location.
|
| 103 |
+
"""
|
| 104 |
+
pathspec: PathSpec = field(init=False)
|
| 105 |
+
"""Compiled PathSpec object for pattern matching."""
|
| 106 |
+
|
| 107 |
+
def __post_init__(self) -> None:
|
| 108 |
+
"""Initialize the PathSpec from patterns."""
|
| 109 |
+
self.pathspec = PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, self.patterns)
|
| 110 |
+
|
| 111 |
+
def matches(self, relative_path: str) -> bool:
|
| 112 |
+
"""
|
| 113 |
+
Check if the given path matches any pattern in this gitignore spec.
|
| 114 |
+
|
| 115 |
+
:param relative_path: Path to check (should be relative to repo root)
|
| 116 |
+
:return: True if path matches any pattern
|
| 117 |
+
"""
|
| 118 |
+
return match_path(relative_path, self.pathspec, root_path=os.path.dirname(self.file_path))
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class GitignoreParser:
|
| 122 |
+
"""
|
| 123 |
+
Parser for gitignore files in a repository.
|
| 124 |
+
|
| 125 |
+
This class handles parsing multiple gitignore files throughout a repository
|
| 126 |
+
and provides methods to check if paths should be ignored.
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
def __init__(self, repo_root: str) -> None:
|
| 130 |
+
"""
|
| 131 |
+
Initialize the parser for a repository.
|
| 132 |
+
|
| 133 |
+
:param repo_root: Root directory of the repository
|
| 134 |
+
"""
|
| 135 |
+
self.repo_root = os.path.abspath(repo_root)
|
| 136 |
+
self.ignore_specs: list[GitignoreSpec] = []
|
| 137 |
+
self._load_gitignore_files()
|
| 138 |
+
|
| 139 |
+
def _load_gitignore_files(self) -> None:
|
| 140 |
+
"""Load all gitignore files from the repository."""
|
| 141 |
+
with LogTime("Loading of .gitignore files", logger=log):
|
| 142 |
+
for gitignore_path in self._iter_gitignore_files():
|
| 143 |
+
log.info("Processing .gitignore file: %s", gitignore_path)
|
| 144 |
+
spec = self._create_ignore_spec(gitignore_path)
|
| 145 |
+
if spec.patterns: # Only add non-empty specs
|
| 146 |
+
self.ignore_specs.append(spec)
|
| 147 |
+
|
| 148 |
+
def _iter_gitignore_files(self, follow_symlinks: bool = False) -> Iterator[str]:
|
| 149 |
+
"""
|
| 150 |
+
Iteratively discover .gitignore files in a top-down fashion, starting from the repository root.
|
| 151 |
+
Directory paths are skipped if they match any already loaded ignore patterns.
|
| 152 |
+
|
| 153 |
+
:return: an iterator yielding paths to .gitignore files (top-down)
|
| 154 |
+
"""
|
| 155 |
+
queue: list[str] = [self.repo_root]
|
| 156 |
+
|
| 157 |
+
def scan(abs_path: str | None):
|
| 158 |
+
for entry in os.scandir(abs_path):
|
| 159 |
+
if entry.is_dir(follow_symlinks=follow_symlinks):
|
| 160 |
+
queue.append(entry.path)
|
| 161 |
+
elif entry.is_file(follow_symlinks=follow_symlinks) and entry.name == ".gitignore":
|
| 162 |
+
yield entry.path
|
| 163 |
+
|
| 164 |
+
while queue:
|
| 165 |
+
next_abs_path = queue.pop(0)
|
| 166 |
+
if next_abs_path != self.repo_root:
|
| 167 |
+
rel_path = os.path.relpath(next_abs_path, self.repo_root)
|
| 168 |
+
if self.should_ignore(rel_path):
|
| 169 |
+
continue
|
| 170 |
+
yield from scan(next_abs_path)
|
| 171 |
+
|
| 172 |
+
def _create_ignore_spec(self, gitignore_file_path: str) -> GitignoreSpec:
|
| 173 |
+
"""
|
| 174 |
+
Create a GitignoreSpec from a single gitignore file.
|
| 175 |
+
|
| 176 |
+
:param gitignore_file_path: Path to the .gitignore file
|
| 177 |
+
:return: GitignoreSpec object for the gitignore patterns
|
| 178 |
+
"""
|
| 179 |
+
try:
|
| 180 |
+
with open(gitignore_file_path, encoding="utf-8") as f:
|
| 181 |
+
content = f.read()
|
| 182 |
+
except (OSError, UnicodeDecodeError):
|
| 183 |
+
# If we can't read the file, return an empty spec
|
| 184 |
+
return GitignoreSpec(gitignore_file_path, [])
|
| 185 |
+
|
| 186 |
+
gitignore_dir = os.path.dirname(gitignore_file_path)
|
| 187 |
+
patterns = self._parse_gitignore_content(content, gitignore_dir)
|
| 188 |
+
|
| 189 |
+
return GitignoreSpec(gitignore_file_path, patterns)
|
| 190 |
+
|
| 191 |
+
def _parse_gitignore_content(self, content: str, gitignore_dir: str) -> list[str]:
|
| 192 |
+
"""
|
| 193 |
+
Parse gitignore content and adjust patterns based on the gitignore file location.
|
| 194 |
+
|
| 195 |
+
:param content: Content of the .gitignore file
|
| 196 |
+
:param gitignore_dir: Directory containing the .gitignore file (absolute path)
|
| 197 |
+
:return: List of adjusted patterns
|
| 198 |
+
"""
|
| 199 |
+
patterns = []
|
| 200 |
+
|
| 201 |
+
# Get the relative path from repo root to the gitignore directory
|
| 202 |
+
rel_dir = os.path.relpath(gitignore_dir, self.repo_root)
|
| 203 |
+
if rel_dir == ".":
|
| 204 |
+
rel_dir = ""
|
| 205 |
+
|
| 206 |
+
for line in content.splitlines():
|
| 207 |
+
# Strip trailing whitespace (but preserve leading whitespace for now)
|
| 208 |
+
line = line.rstrip()
|
| 209 |
+
|
| 210 |
+
# Skip empty lines and comments
|
| 211 |
+
if not line or line.lstrip().startswith("#"):
|
| 212 |
+
continue
|
| 213 |
+
|
| 214 |
+
# Store whether this is a negation pattern
|
| 215 |
+
is_negation = line.startswith("!")
|
| 216 |
+
if is_negation:
|
| 217 |
+
line = line[1:]
|
| 218 |
+
|
| 219 |
+
# Strip leading/trailing whitespace after removing negation
|
| 220 |
+
line = line.strip()
|
| 221 |
+
|
| 222 |
+
if not line:
|
| 223 |
+
continue
|
| 224 |
+
|
| 225 |
+
# Handle escaped characters at the beginning
|
| 226 |
+
if line.startswith(("\\#", "\\!")):
|
| 227 |
+
line = line[1:]
|
| 228 |
+
|
| 229 |
+
# Determine if pattern is anchored to the gitignore directory and remove leading slash for processing
|
| 230 |
+
is_anchored = line.startswith("/")
|
| 231 |
+
if is_anchored:
|
| 232 |
+
line = line[1:]
|
| 233 |
+
|
| 234 |
+
# Adjust pattern based on gitignore file location
|
| 235 |
+
if rel_dir:
|
| 236 |
+
if is_anchored:
|
| 237 |
+
# Anchored patterns are relative to the gitignore directory
|
| 238 |
+
adjusted_pattern = os.path.join(rel_dir, line)
|
| 239 |
+
else:
|
| 240 |
+
# Non-anchored patterns can match anywhere below the gitignore directory
|
| 241 |
+
# We need to preserve this behavior
|
| 242 |
+
if line.startswith("**/"):
|
| 243 |
+
# Even if pattern starts with **, it should still be scoped to the subdirectory
|
| 244 |
+
adjusted_pattern = os.path.join(rel_dir, line)
|
| 245 |
+
else:
|
| 246 |
+
# Add the directory prefix but also allow matching in subdirectories
|
| 247 |
+
adjusted_pattern = os.path.join(rel_dir, "**", line)
|
| 248 |
+
else:
|
| 249 |
+
if is_anchored:
|
| 250 |
+
# Anchored patterns in root should only match at root level
|
| 251 |
+
# Add leading slash back to indicate root-only matching
|
| 252 |
+
adjusted_pattern = "/" + line
|
| 253 |
+
else:
|
| 254 |
+
# Non-anchored patterns can match anywhere
|
| 255 |
+
adjusted_pattern = line
|
| 256 |
+
|
| 257 |
+
# Re-add negation if needed
|
| 258 |
+
if is_negation:
|
| 259 |
+
adjusted_pattern = "!" + adjusted_pattern
|
| 260 |
+
|
| 261 |
+
# Normalize path separators to forward slashes (gitignore uses forward slashes)
|
| 262 |
+
adjusted_pattern = adjusted_pattern.replace(os.sep, "/")
|
| 263 |
+
|
| 264 |
+
patterns.append(adjusted_pattern)
|
| 265 |
+
|
| 266 |
+
return patterns
|
| 267 |
+
|
| 268 |
+
def should_ignore(self, path: str) -> bool:
|
| 269 |
+
"""
|
| 270 |
+
Check if a path should be ignored based on the gitignore rules.
|
| 271 |
+
|
| 272 |
+
:param path: Path to check (absolute or relative to repo_root)
|
| 273 |
+
:return: True if the path should be ignored, False otherwise
|
| 274 |
+
"""
|
| 275 |
+
# Convert to relative path from repo root
|
| 276 |
+
if os.path.isabs(path):
|
| 277 |
+
try:
|
| 278 |
+
rel_path = os.path.relpath(path, self.repo_root)
|
| 279 |
+
except Exception as e:
|
| 280 |
+
# If the path could not be converted to a relative path,
|
| 281 |
+
# it is outside the repository root, so we ignore it
|
| 282 |
+
log.info("Ignoring path '%s' which is outside of the repository root (%s)", path, e)
|
| 283 |
+
return True
|
| 284 |
+
else:
|
| 285 |
+
rel_path = path
|
| 286 |
+
|
| 287 |
+
# Ignore paths inside .git
|
| 288 |
+
rel_path_first_path = Path(rel_path).parts[0]
|
| 289 |
+
if rel_path_first_path == ".git":
|
| 290 |
+
return True
|
| 291 |
+
|
| 292 |
+
abs_path = os.path.join(self.repo_root, rel_path)
|
| 293 |
+
|
| 294 |
+
# Normalize path separators
|
| 295 |
+
rel_path = rel_path.replace(os.sep, "/")
|
| 296 |
+
|
| 297 |
+
if os.path.exists(abs_path) and os.path.isdir(abs_path) and not rel_path.endswith("/"):
|
| 298 |
+
rel_path = rel_path + "/"
|
| 299 |
+
|
| 300 |
+
# Check against each ignore spec
|
| 301 |
+
for spec in self.ignore_specs:
|
| 302 |
+
if spec.matches(rel_path):
|
| 303 |
+
return True
|
| 304 |
+
|
| 305 |
+
return False
|
| 306 |
+
|
| 307 |
+
def get_ignore_specs(self) -> list[GitignoreSpec]:
|
| 308 |
+
"""
|
| 309 |
+
Get all loaded gitignore specs.
|
| 310 |
+
|
| 311 |
+
:return: List of GitignoreSpec objects
|
| 312 |
+
"""
|
| 313 |
+
return self.ignore_specs
|
| 314 |
+
|
| 315 |
+
def reload(self) -> None:
|
| 316 |
+
"""Reload all gitignore files from the repository."""
|
| 317 |
+
self.ignore_specs.clear()
|
| 318 |
+
self._load_gitignore_files()
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def match_path(relative_path: str, path_spec: PathSpec, root_path: str = "") -> bool:
|
| 322 |
+
"""
|
| 323 |
+
Match a relative path against a given pathspec. Just pathspec.match_file() is not enough,
|
| 324 |
+
we need to do some massaging to fix issues with pathspec matching.
|
| 325 |
+
|
| 326 |
+
:param relative_path: relative path to match against the pathspec
|
| 327 |
+
:param path_spec: the pathspec to match against
|
| 328 |
+
:param root_path: the root path from which the relative path is derived
|
| 329 |
+
:return:
|
| 330 |
+
"""
|
| 331 |
+
normalized_path = str(relative_path).replace(os.path.sep, "/")
|
| 332 |
+
|
| 333 |
+
# We can have patterns like /src/..., which would only match corresponding paths from the repo root
|
| 334 |
+
# Unfortunately, pathspec can't know whether a relative path is relative to the repo root or not,
|
| 335 |
+
# so it will never match src/...
|
| 336 |
+
# The fix is to just always assume that the input path is relative to the repo root and to
|
| 337 |
+
# prefix it with /.
|
| 338 |
+
if not normalized_path.startswith("/"):
|
| 339 |
+
normalized_path = "/" + normalized_path
|
| 340 |
+
|
| 341 |
+
# pathspec can't handle the matching of directories if they don't end with a slash!
|
| 342 |
+
# see https://github.com/cpburnz/python-pathspec/issues/89
|
| 343 |
+
abs_path = os.path.abspath(os.path.join(root_path, relative_path))
|
| 344 |
+
if os.path.isdir(abs_path) and not normalized_path.endswith("/"):
|
| 345 |
+
normalized_path = normalized_path + "/"
|
| 346 |
+
return path_spec.match_file(normalized_path)
|