ADAPT-Chase commited on
Commit
ae9b203
·
verified ·
1 Parent(s): af1432a

Add files using upload-large-folder tool

Browse files
projects/ui/serena-new/.github/workflows/junie.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Junie
2
+ run-name: Junie run ${{ inputs.run_id }}
3
+
4
+ permissions:
5
+ contents: write
6
+
7
+ on:
8
+ workflow_dispatch:
9
+ inputs:
10
+ run_id:
11
+ description: "id of workflow process"
12
+ required: true
13
+ workflow_params:
14
+ description: "stringified params"
15
+ required: true
16
+
17
+ jobs:
18
+ call-workflow-passing-data:
19
+ uses: jetbrains-junie/junie-workflows/.github/workflows/ej-issue.yml@main
20
+ with:
21
+ workflow_params: ${{ inputs.workflow_params }}
projects/ui/serena-new/.github/workflows/lint_and_docs.yaml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Linting, Types and Docs Check
2
+
3
+ on:
4
+ workflow_dispatch: # Manual trigger only - workflow disabled from auto-running
5
+
6
+ jobs:
7
+ check:
8
+ runs-on: ubuntu-latest
9
+ timeout-minutes: 5
10
+ permissions:
11
+ id-token: write
12
+ pages: write
13
+ actions: write
14
+ contents: read
15
+ steps:
16
+ - uses: actions/checkout@v3
17
+ - name: Set up Python
18
+ uses: actions/setup-python@v4
19
+ with:
20
+ python-version: 3.11
21
+
22
+
23
+ # use uv package manager
24
+ - name: Install uv
25
+ run: pip install uv
26
+ - uses: actions/cache@v3
27
+ name: Cache dependencies
28
+ with:
29
+ path: ~/.cache/uv
30
+ key: uv-${{ hashFiles('pyproject.toml') }}
31
+ - name: Install dependencies
32
+ run: |
33
+ uv venv
34
+ uv pip install -e ".[dev]"
35
+ - name: Lint
36
+ run: uv run poe lint
37
+ - name: Types
38
+ run: uv run poe type-check
39
+ - name: Docs
40
+ run: uv run poe doc-build
41
+ - name: Upload artifact
42
+ uses: actions/upload-pages-artifact@v2
43
+ with:
44
+ path: "docs/_build"
45
+ - name: Deploy to GitHub Pages
46
+ id: deployment
47
+ uses: actions/deploy-pages@v2
projects/ui/serena-new/.github/workflows/publish.yml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish Python Package
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+
7
+ workflow_dispatch:
8
+ inputs:
9
+ tag:
10
+ description: 'Tag name for the release (e.g., v0.1.0)'
11
+ required: true
12
+ default: 'v0.1.0'
13
+
14
+ env:
15
+ # Set this to true manually in the GitHub workflow UI if you want to publish to PyPI
16
+ # Will always publish to testpypi
17
+ PUBLISH_TO_PYPI: true
18
+
19
+ jobs:
20
+ publish:
21
+ name: Publish the serena-agent package
22
+ runs-on: ubuntu-latest
23
+
24
+ permissions:
25
+ id-token: write # Required for trusted publishing
26
+ contents: write # Required for updating artifact
27
+
28
+ steps:
29
+ - name: Checkout code
30
+ uses: actions/checkout@v4
31
+
32
+ - name: Install the latest version of uv
33
+ uses: astral-sh/setup-uv@v6
34
+ with:
35
+ version: "latest"
36
+
37
+ - name: Build package
38
+ run: uv build
39
+
40
+ - name: Upload artifacts to GitHub Release
41
+ if: env.PUBLISH_TO_PYPI == 'true'
42
+ uses: softprops/action-gh-release@v2
43
+ with:
44
+ tag_name: ${{ github.event.inputs.tag || github.ref_name }}
45
+ files: |
46
+ dist/*.tar.gz
47
+ dist/*.whl
48
+
49
+ - name: Publish to TestPyPI
50
+ run: uv publish --index testpypi
51
+
52
+ - name: Publish to PyPI (conditional)
53
+ if: env.PUBLISH_TO_PYPI == 'true'
54
+ run: uv publish
projects/ui/serena-new/.github/workflows/pytest.yml ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Tests on CI
2
+
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches:
7
+ - main
8
+
9
+ concurrency:
10
+ group: ci-${{ github.workflow }}-${{ github.ref }}
11
+ cancel-in-progress: true
12
+
13
+ jobs:
14
+ cpu:
15
+ name: Tests on ${{ matrix.os }}
16
+ runs-on: ${{ matrix.os }}
17
+ strategy:
18
+ fail-fast: false
19
+ matrix:
20
+ os: [ubuntu-latest, windows-latest, macos-latest]
21
+ python-version: ["3.11"]
22
+ steps:
23
+ - uses: actions/checkout@v3
24
+ - name: Set up Python ${{ matrix.python-version }}
25
+ uses: actions/setup-python@v4
26
+ with:
27
+ python-version: "${{ matrix.python-version }}"
28
+ - uses: actions/setup-go@v5
29
+ with:
30
+ go-version: ">=1.17.0"
31
+ - name: Ensure cached directory exist before calling cache-related actions
32
+ shell: bash
33
+ run: |
34
+ mkdir -p $HOME/.serena/language_servers/static
35
+ mkdir -p $HOME/.cache/go-build
36
+ mkdir -p $HOME/go/bin
37
+ # Add Go bin directory to PATH for this workflow
38
+ # GITHUB_PATH is a special file that GitHub Actions uses to modify PATH
39
+ # Writing to this file adds the directory to the PATH for subsequent steps
40
+ - name: Cache Go binaries
41
+ id: cache-go-binaries
42
+ uses: actions/cache@v3
43
+ with:
44
+ path: |
45
+ ~/go/bin
46
+ ~/.cache/go-build
47
+ key: go-binaries-${{ runner.os }}-gopls-latest
48
+ - name: Install gopls
49
+ if: steps.cache-go-binaries.outputs.cache-hit != 'true'
50
+ shell: bash
51
+ run: go install golang.org/x/tools/gopls@latest
52
+ - name: Set up Elixir
53
+ if: runner.os != 'Windows'
54
+ uses: erlef/setup-beam@v1
55
+ with:
56
+ elixir-version: "1.18.4"
57
+ otp-version: "26.1"
58
+ # Erlang currently not tested in CI, random hangings on macos, always hangs on ubuntu
59
+ # In local tests, erlang seems to work though
60
+ # - name: Install Erlang Language Server
61
+ # if: runner.os != 'Windows'
62
+ # shell: bash
63
+ # run: |
64
+ # # Install rebar3 if not already available
65
+ # which rebar3 || (curl -fsSL https://github.com/erlang/rebar3/releases/download/3.23.0/rebar3 -o /tmp/rebar3 && chmod +x /tmp/rebar3 && sudo mv /tmp/rebar3 /usr/local/bin/rebar3)
66
+ # # Clone and build erlang_ls
67
+ # git clone https://github.com/erlang-ls/erlang_ls.git /tmp/erlang_ls
68
+ # cd /tmp/erlang_ls
69
+ # make install PREFIX=/usr/local
70
+ # # Ensure erlang_ls is in PATH
71
+ # echo "$HOME/.local/bin" >> $GITHUB_PATH
72
+ - name: Install clojure tools
73
+ uses: DeLaGuardo/setup-clojure@13.4
74
+ with:
75
+ cli: latest
76
+ - name: Setup Java (for JVM based languages)
77
+ uses: actions/setup-java@v4
78
+ with:
79
+ distribution: 'temurin'
80
+ java-version: '17'
81
+ - name: Install Terraform
82
+ uses: hashicorp/setup-terraform@v3
83
+ with:
84
+ terraform_version: "1.5.0"
85
+ terraform_wrapper: false
86
+ # - name: Install swift
87
+ # if: runner.os != 'Windows'
88
+ # uses: swift-actions/setup-swift@v2
89
+ # Installation of swift with the action screws with installation of ruby on macOS for some reason
90
+ # We can try again when version 3 of the action is released, where they will also use swiftly
91
+ # Until then, we use custom code to install swift. Sourcekit-lsp is installed automatically with swift
92
+ - name: Install Swift with swiftly (macOS)
93
+ if: runner.os == 'macOS'
94
+ run: |
95
+ echo "=== Installing swiftly on macOS ==="
96
+ curl -O https://download.swift.org/swiftly/darwin/swiftly.pkg && \
97
+ installer -pkg swiftly.pkg -target CurrentUserHomeDirectory && \
98
+ ~/.swiftly/bin/swiftly init --quiet-shell-followup && \
99
+ . "${SWIFTLY_HOME_DIR:-$HOME/.swiftly}/env.sh" && \
100
+ hash -r
101
+ swiftly install --use 6.1.2
102
+ swiftly use 6.1.2
103
+ echo "~/.swiftly/bin" >> $GITHUB_PATH
104
+ echo "Swiftly installed successfully"
105
+ - name: Install Swift with swiftly (Ubuntu)
106
+ if: runner.os == 'Linux'
107
+ run: |
108
+ echo "=== Installing swiftly on Ubuntu ==="
109
+ curl -O https://download.swift.org/swiftly/linux/swiftly-$(uname -m).tar.gz && \
110
+ tar zxf swiftly-$(uname -m).tar.gz && \
111
+ ./swiftly init --quiet-shell-followup && \
112
+ . "${SWIFTLY_HOME_DIR:-$HOME/.local/share/swiftly}/env.sh" && \
113
+ hash -r
114
+ swiftly install --use 6.1.2
115
+ swiftly use 6.1.2
116
+ sudo apt-get -y install libcurl4-openssl-dev
117
+ echo "=== Adding Swift toolchain to PATH ==="
118
+ echo "$HOME/.local/share/swiftly/bin" >> $GITHUB_PATH
119
+ echo "Swiftly installed successfully!"
120
+ - name: Install Ruby
121
+ uses: ruby/setup-ruby@v1
122
+ with:
123
+ ruby-version: '3.4'
124
+ - name: Install Ruby language server
125
+ shell: bash
126
+ run: gem install ruby-lsp
127
+ - name: Install R
128
+ uses: r-lib/actions/setup-r@v2
129
+ with:
130
+ r-version: '4.4.2'
131
+ use-public-rspm: true
132
+ - name: Install R language server
133
+ shell: bash
134
+ run: |
135
+ Rscript -e "install.packages('languageserver', repos='https://cloud.r-project.org')"
136
+ - name: Install Zig
137
+ uses: goto-bus-stop/setup-zig@v2
138
+ with:
139
+ version: 0.14.1
140
+ - name: Install ZLS (Zig Language Server)
141
+ shell: bash
142
+ run: |
143
+ if [[ "${{ runner.os }}" == "Linux" ]]; then
144
+ wget https://github.com/zigtools/zls/releases/download/0.14.0/zls-x86_64-linux.tar.xz
145
+ tar -xf zls-x86_64-linux.tar.xz
146
+ sudo mv zls /usr/local/bin/
147
+ rm zls-x86_64-linux.tar.xz
148
+ elif [[ "${{ runner.os }}" == "macOS" ]]; then
149
+ wget https://github.com/zigtools/zls/releases/download/0.14.0/zls-x86_64-macos.tar.xz
150
+ tar -xf zls-x86_64-macos.tar.xz
151
+ sudo mv zls /usr/local/bin/
152
+ rm zls-x86_64-macos.tar.xz
153
+ elif [[ "${{ runner.os }}" == "Windows" ]]; then
154
+ curl -L -o zls.zip https://github.com/zigtools/zls/releases/download/0.14.0/zls-x86_64-windows.zip
155
+ unzip -o zls.zip
156
+ mkdir -p "$HOME/bin"
157
+ mv zls.exe "$HOME/bin/"
158
+ echo "$HOME/bin" >> $GITHUB_PATH
159
+ rm zls.zip
160
+ fi
161
+ - name: Install Lua Language Server
162
+ shell: bash
163
+ run: |
164
+ LUA_LS_VERSION="3.15.0"
165
+ LUA_LS_DIR="$HOME/.serena/language_servers/lua"
166
+ mkdir -p "$LUA_LS_DIR"
167
+
168
+ if [[ "${{ runner.os }}" == "Linux" ]]; then
169
+ if [[ "$(uname -m)" == "x86_64" ]]; then
170
+ wget https://github.com/LuaLS/lua-language-server/releases/download/${LUA_LS_VERSION}/lua-language-server-${LUA_LS_VERSION}-linux-x64.tar.gz
171
+ tar -xzf lua-language-server-${LUA_LS_VERSION}-linux-x64.tar.gz -C "$LUA_LS_DIR"
172
+ else
173
+ wget https://github.com/LuaLS/lua-language-server/releases/download/${LUA_LS_VERSION}/lua-language-server-${LUA_LS_VERSION}-linux-arm64.tar.gz
174
+ tar -xzf lua-language-server-${LUA_LS_VERSION}-linux-arm64.tar.gz -C "$LUA_LS_DIR"
175
+ fi
176
+ chmod +x "$LUA_LS_DIR/bin/lua-language-server"
177
+ # Create wrapper script instead of symlink to ensure supporting files are found
178
+ echo '#!/bin/bash' | sudo tee /usr/local/bin/lua-language-server > /dev/null
179
+ echo 'cd "${HOME}/.serena/language_servers/lua/bin"' | sudo tee -a /usr/local/bin/lua-language-server > /dev/null
180
+ echo 'exec ./lua-language-server "$@"' | sudo tee -a /usr/local/bin/lua-language-server > /dev/null
181
+ sudo chmod +x /usr/local/bin/lua-language-server
182
+ rm lua-language-server-*.tar.gz
183
+ elif [[ "${{ runner.os }}" == "macOS" ]]; then
184
+ if [[ "$(uname -m)" == "x86_64" ]]; then
185
+ wget https://github.com/LuaLS/lua-language-server/releases/download/${LUA_LS_VERSION}/lua-language-server-${LUA_LS_VERSION}-darwin-x64.tar.gz
186
+ tar -xzf lua-language-server-${LUA_LS_VERSION}-darwin-x64.tar.gz -C "$LUA_LS_DIR"
187
+ else
188
+ wget https://github.com/LuaLS/lua-language-server/releases/download/${LUA_LS_VERSION}/lua-language-server-${LUA_LS_VERSION}-darwin-arm64.tar.gz
189
+ tar -xzf lua-language-server-${LUA_LS_VERSION}-darwin-arm64.tar.gz -C "$LUA_LS_DIR"
190
+ fi
191
+ chmod +x "$LUA_LS_DIR/bin/lua-language-server"
192
+ # Create wrapper script instead of symlink to ensure supporting files are found
193
+ echo '#!/bin/bash' | sudo tee /usr/local/bin/lua-language-server > /dev/null
194
+ echo 'cd "${HOME}/.serena/language_servers/lua/bin"' | sudo tee -a /usr/local/bin/lua-language-server > /dev/null
195
+ echo 'exec ./lua-language-server "$@"' | sudo tee -a /usr/local/bin/lua-language-server > /dev/null
196
+ sudo chmod +x /usr/local/bin/lua-language-server
197
+ rm lua-language-server-*.tar.gz
198
+ elif [[ "${{ runner.os }}" == "Windows" ]]; then
199
+ curl -L -o lua-ls.zip https://github.com/LuaLS/lua-language-server/releases/download/${LUA_LS_VERSION}/lua-language-server-${LUA_LS_VERSION}-win32-x64.zip
200
+ unzip -o lua-ls.zip -d "$LUA_LS_DIR"
201
+ # For Windows, we'll add the bin directory directly to PATH
202
+ # The lua-language-server.exe can find its supporting files relative to its location
203
+ echo "$LUA_LS_DIR/bin" >> $GITHUB_PATH
204
+ rm lua-ls.zip
205
+ fi
206
+ - name: Install Nix
207
+ if: runner.os != 'Windows' # Nix doesn't support Windows natively
208
+ uses: cachix/install-nix-action@v30
209
+ with:
210
+ nix_path: nixpkgs=channel:nixos-unstable
211
+ - name: Install nixd (Nix Language Server)
212
+ if: runner.os != 'Windows' # Skip on Windows since Nix isn't available
213
+ shell: bash
214
+ run: |
215
+ # Install nixd using nix
216
+ nix profile install github:nix-community/nixd
217
+
218
+ # Verify nixd is installed and working
219
+ if ! command -v nixd &> /dev/null; then
220
+ echo "nixd installation failed or not in PATH"
221
+ exit 1
222
+ fi
223
+
224
+ echo "$HOME/.nix-profile/bin" >> $GITHUB_PATH
225
+ - name: Install uv
226
+ shell: bash
227
+ run: curl -LsSf https://astral.sh/uv/install.sh | sh
228
+ - name: Cache uv virtualenv
229
+ id: cache-uv
230
+ uses: actions/cache@v3
231
+ with:
232
+ path: .venv
233
+ key: uv-venv-${{ runner.os }}-${{ matrix.python-version }}-${{ hashFiles('uv.lock') }}
234
+ - name: Cache language servers
235
+ id: cache-language-servers
236
+ uses: actions/cache@v3
237
+ with:
238
+ path: ~/.serena/language_servers/static
239
+ key: language-servers-${{ runner.os }}-v1
240
+ restore-keys: |
241
+ language-servers-${{ runner.os }}-
242
+ - name: Create virtual environment
243
+ shell: bash
244
+ run: |
245
+ if [ ! -d ".venv" ]; then
246
+ uv venv
247
+ fi
248
+ - name: Install dependencies
249
+ shell: bash
250
+ run: uv pip install -e ".[dev]"
251
+ - name: Check formatting
252
+ shell: bash
253
+ run: uv run poe lint
254
+ - name: Test with pytest
255
+ shell: bash
256
+ run: uv run poe test
projects/ui/serena-new/.serena/memories/adding_new_language_support_guide.md ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adding New Language Support to Serena
2
+
3
+ This guide explains how to add support for a new programming language to Serena.
4
+
5
+ ## Overview
6
+
7
+ Adding a new language involves:
8
+
9
+ 1. **Language Server Implementation** - Creating a language-specific server class
10
+ 2. **Language Registration** - Adding the language to enums and configurations
11
+ 3. **Test Repository** - Creating a minimal test project
12
+ 4. **Test Suite** - Writing comprehensive tests
13
+ 5. **Runtime Dependencies** - Configuring automatic language server downloads
14
+
15
+ ## Step 1: Language Server Implementation
16
+
17
+ ### 1.1 Create Language Server Class
18
+
19
+ Create a new file in `src/solidlsp/language_servers/` (e.g., `new_language_server.py`).
20
+ Have a look at `intelephense.py` for a reference implementation of a language server which downloads all its dependencies, at `gopls.py` for an LS that needs some preinstalled
21
+ dependencies, and on `pyright_server.py` that does not need any additional dependencies
22
+ because the language server can be installed directly as python package.
23
+
24
+
25
+ ```python
26
+ from solidlsp.ls import SolidLanguageServer
27
+ from solidlsp.ls_config import LanguageServerConfig
28
+ from solidlsp.ls_logger import LanguageServerLogger
29
+ from solidlsp.lsp_protocol_handler.server import ProcessLaunchInfo
30
+
31
+ class NewLanguageServer(SolidLanguageServer):
32
+ """
33
+ Language server implementation for NewLanguage.
34
+ """
35
+
36
+ def __init__(self, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str):
37
+ # Determine language server command
38
+ cmd = self._get_language_server_command()
39
+
40
+ super().__init__(
41
+ config,
42
+ logger,
43
+ repository_root_path,
44
+ ProcessLaunchInfo(cmd=cmd, cwd=repository_root_path),
45
+ "new_language", # Language ID for LSP
46
+ )
47
+
48
+ def _get_language_server_command(self) -> list[str]:
49
+ """Get the command to start the language server."""
50
+ # Example: return ["new-language-server", "--stdio"]
51
+ pass
52
+
53
+ @override
54
+ def is_ignored_dirname(self, dirname: str) -> bool:
55
+ """Define language-specific directories to ignore."""
56
+ return super().is_ignored_dirname(dirname) or dirname in ["build", "dist", "target"]
57
+ ```
58
+
59
+ ### 1.2 Language Server Discovery and Installation
60
+
61
+ For languages requiring automatic installation, implement download logic similar to C#:
62
+
63
+ ```python
64
+ @classmethod
65
+ def _ensure_server_installed(cls, logger: LanguageServerLogger) -> str:
66
+ """Ensure language server is installed and return path."""
67
+ # Check system installation first
68
+ system_server = shutil.which("new-language-server")
69
+ if system_server:
70
+ return system_server
71
+
72
+ # Download and install if needed
73
+ server_path = cls._download_and_install_server(logger)
74
+ return server_path
75
+
76
+ def _download_and_install_server(cls, logger: LanguageServerLogger) -> str:
77
+ """Download and install the language server."""
78
+ # Implementation specific to your language server
79
+ pass
80
+ ```
81
+
82
+ ### 1.3 LSP Initialization
83
+
84
+ Override initialization methods if needed:
85
+
86
+ ```python
87
+ def _get_initialize_params(self) -> InitializeParams:
88
+ """Return language-specific initialization parameters."""
89
+ return {
90
+ "processId": os.getpid(),
91
+ "rootUri": PathUtils.path_to_uri(self.repository_root_path),
92
+ "capabilities": {
93
+ # Language-specific capabilities
94
+ }
95
+ }
96
+
97
+ def _start_server(self):
98
+ """Start the language server with custom handlers."""
99
+ # Set up notification handlers
100
+ self.server.on_notification("window/logMessage", self._handle_log_message)
101
+
102
+ # Start server and initialize
103
+ self.server.start()
104
+ init_response = self.server.send.initialize(self._get_initialize_params())
105
+ self.server.notify.initialized({})
106
+ ```
107
+
108
+ ## Step 2: Language Registration
109
+
110
+ ### 2.1 Add to Language Enum
111
+
112
+ In `src/solidlsp/ls_config.py`, add your language to the `Language` enum:
113
+
114
+ ```python
115
+ class Language(str, Enum):
116
+ # Existing languages...
117
+ NEW_LANGUAGE = "new_language"
118
+
119
+ def get_source_fn_matcher(self) -> FilenameMatcher:
120
+ match self:
121
+ # Existing cases...
122
+ case self.NEW_LANGUAGE:
123
+ return FilenameMatcher("*.newlang", "*.nl") # File extensions
124
+ ```
125
+
126
+ ### 2.2 Update Language Server Factory
127
+
128
+ In `src/solidlsp/ls.py`, add your language to the `create` method:
129
+
130
+ ```python
131
+ @classmethod
132
+ def create(cls, config: LanguageServerConfig, logger: LanguageServerLogger, repository_root_path: str) -> "SolidLanguageServer":
133
+ match config.code_language:
134
+ # Existing cases...
135
+ case Language.NEW_LANGUAGE:
136
+ from solidlsp.language_servers.new_language_server import NewLanguageServer
137
+ return NewLanguageServer(config, logger, repository_root_path)
138
+ ```
139
+
140
+ ## Step 3: Test Repository
141
+
142
+ ### 3.1 Create Test Project
143
+
144
+ Create a minimal project in `test/resources/repos/new_language/test_repo/`:
145
+
146
+ ```
147
+ test/resources/repos/new_language/test_repo/
148
+ ├── main.newlang # Main source file
149
+ ├── lib/
150
+ │ └── helper.newlang # Additional source for testing
151
+ ├── project.toml # Project configuration (if applicable)
152
+ └── .gitignore # Ignore build artifacts
153
+ ```
154
+
155
+ ### 3.2 Example Source Files
156
+
157
+ Create meaningful source files that demonstrate:
158
+
159
+ - **Classes/Types** - For symbol testing
160
+ - **Functions/Methods** - For reference finding
161
+ - **Imports/Dependencies** - For cross-file operations
162
+ - **Nested Structures** - For hierarchical symbol testing
163
+
164
+ Example `main.newlang`:
165
+ ```
166
+ import lib.helper
167
+
168
+ class Calculator {
169
+ func add(a: Int, b: Int) -> Int {
170
+ return a + b
171
+ }
172
+
173
+ func subtract(a: Int, b: Int) -> Int {
174
+ return helper.subtract(a, b) // Reference to imported function
175
+ }
176
+ }
177
+
178
+ class Program {
179
+ func main() {
180
+ let calc = Calculator()
181
+ let result = calc.add(5, 3) // Reference to add method
182
+ print(result)
183
+ }
184
+ }
185
+ ```
186
+
187
+ ## Step 4: Test Suite
188
+
189
+ Testing the language server implementation is of crucial importance, and the tests will
190
+ form the main part of the review process. Make sure that the tests are up to the standard
191
+ of Serena to make the review go smoother.
192
+
193
+ General rules for tests:
194
+
195
+ 1. Tests for symbols and references should always check that the expected symbol names and references were actually found.
196
+ Just testing that a list came back or that the result is not None is insufficient.
197
+ 2. Tests should never be skipped, the only exception is skipping based on some package being available or on an unsupported OS.
198
+ 3. Tests should run in CI, check if there is a suitable GitHub action for installing the dependencies.
199
+
200
+ ### 4.1 Basic Tests
201
+
202
+ Create `test/solidlsp/new_language/test_new_language_basic.py`.
203
+ Have a look at the structure of existing tests, for example, in `test/solidlsp/php/test_php_basic.py`
204
+ You should at least test:
205
+
206
+ 1. Finding symbols
207
+ 2. Finding within-file references
208
+ 3. Finding cross-file references
209
+
210
+ Have a look at `test/solidlsp/php/test_php_basic.py` as an example for what should be tested.
211
+ Don't forget to add a new language marker to `pytest.ini`.
212
+
213
+ ### 4.2 Integration Tests
214
+
215
+ Consider adding new cases to the parametrized tests in `test_serena_agent.py` for the new language.
216
+
217
+
218
+ ### 5 Documentation
219
+
220
+ Update:
221
+
222
+ - **README.md** - Add language to supported languages list
223
+ - **CHANGELOG.md** - Document the new language support
224
+ - **Language-specific docs** - Installation requirements, known issues
projects/ui/serena-new/.serena/memories/serena_core_concepts_and_architecture.md ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Serena Core Concepts and Architecture
2
+
3
+ ## High-Level Architecture
4
+
5
+ Serena is built around a dual-layer architecture:
6
+
7
+ 1. **SerenaAgent** - The main orchestrator that manages projects, tools, and user interactions
8
+ 2. **SolidLanguageServer** - A unified wrapper around Language Server Protocol (LSP) implementations
9
+
10
+ ## Core Components
11
+
12
+ ### 1. SerenaAgent (`src/serena/agent.py`)
13
+
14
+ The central coordinator that:
15
+ - Manages active projects and their configurations
16
+ - Coordinates between different tools and contexts
17
+ - Handles language server lifecycle
18
+ - Manages memory persistence
19
+ - Provides MCP (Model Context Protocol) server interface
20
+
21
+ Key responsibilities:
22
+ - **Project Management** - Activating, switching between projects
23
+ - **Tool Registry** - Loading and managing available tools based on context/mode
24
+ - **Language Server Integration** - Starting/stopping language servers per project
25
+ - **Memory Management** - Persistent storage of project knowledge
26
+ - **Task Execution** - Coordinating complex multi-step operations
27
+
28
+ ### 2. SolidLanguageServer (`src/solidlsp/ls.py`)
29
+
30
+ A unified abstraction over multiple language servers that provides:
31
+ - **Language-agnostic interface** for symbol operations
32
+ - **Caching layer** for performance optimization
33
+ - **Error handling and recovery** for unreliable language servers
34
+ - **Uniform API** regardless of underlying LSP implementation
35
+
36
+ Core capabilities:
37
+ - Symbol discovery and navigation
38
+ - Code completion and hover information
39
+ - Find references and definitions
40
+ - Document and workspace symbol search
41
+ - File watching and change notifications
42
+
43
+ ### 3. Tool System (`src/serena/tools/`)
44
+
45
+ Modular tool architecture with several categories:
46
+
47
+ #### File Tools (`file_tools.py`)
48
+ - File system operations (read, write, list directories)
49
+ - Text search and pattern matching
50
+ - Regex-based replacements
51
+
52
+ #### Symbol Tools (`symbol_tools.py`)
53
+ - Language-aware symbol finding and navigation
54
+ - Symbol body replacement and insertion
55
+ - Reference finding across codebase
56
+
57
+ #### Memory Tools (`memory_tools.py`)
58
+ - Project knowledge persistence
59
+ - Memory retrieval and management
60
+ - Onboarding information storage
61
+
62
+ #### Configuration Tools (`config_tools.py`)
63
+ - Project activation and switching
64
+ - Mode and context management
65
+ - Tool inclusion/exclusion
66
+
67
+ ### 4. Configuration System (`src/serena/config/`)
68
+
69
+ Multi-layered configuration supporting:
70
+ - **Contexts** - Define available tools and their behavior
71
+ - **Modes** - Specify operational patterns (interactive, editing, etc.)
72
+ - **Projects** - Per-project settings and language server configs
73
+ - **Tool Sets** - Grouped tool collections for different use cases
74
+
75
+ ## Language Server Integration
76
+
77
+ ### Language Support Model
78
+
79
+ Each supported language has:
80
+ 1. **Language Server Implementation** (`src/solidlsp/language_servers/`)
81
+ 2. **Runtime Dependencies** - Managed downloads of language servers
82
+ 3. **Test Repository** (`test/resources/repos/<language>/`)
83
+ 4. **Test Suite** (`test/solidlsp/<language>/`)
84
+
85
+ ### Language Server Lifecycle
86
+
87
+ 1. **Discovery** - Find language servers or download them automatically
88
+ 2. **Initialization** - Start server process and perform LSP handshake
89
+ 3. **Project Setup** - Open workspace and configure language-specific settings
90
+ 4. **Operation** - Handle requests/responses with caching and error recovery
91
+ 5. **Shutdown** - Clean shutdown of server processes
92
+
93
+ ### Supported Languages
94
+
95
+ Current language support includes:
96
+ - **C#** - Microsoft.CodeAnalysis.LanguageServer (.NET 9)
97
+ - **Python** - Pyright or Jedi
98
+ - **TypeScript/JavaScript** - TypeScript Language Server
99
+ - **Rust** - rust-analyzer
100
+ - **Go** - gopls
101
+ - **Java** - Eclipse JDT Language Server
102
+ - **Kotlin** - Kotlin Language Server
103
+ - **PHP** - Intelephense
104
+ - **Ruby** - Solargraph
105
+ - **Clojure** - clojure-lsp
106
+ - **Elixir** - ElixirLS
107
+ - **Dart** - Dart Language Server
108
+ - **C/C++** - clangd
109
+ - **Terraform** - terraform-ls
110
+
111
+ ## Memory and Knowledge Management
112
+
113
+ ### Memory System
114
+ - **Markdown-based storage** in `.serena/memories/` directory
115
+ - **Contextual retrieval** - memories loaded based on relevance
116
+ - **Project-specific** knowledge persistence
117
+ - **Onboarding support** - guided setup for new projects
118
+
119
+ ### Knowledge Categories
120
+ - **Project Structure** - Directory layouts, build systems
121
+ - **Architecture Patterns** - How the codebase is organized
122
+ - **Development Workflows** - Testing, building, deployment
123
+ - **Domain Knowledge** - Business logic and requirements
124
+
125
+ ## MCP Server Interface
126
+
127
+ Serena exposes its functionality through Model Context Protocol:
128
+ - **Tool Discovery** - AI agents can enumerate available tools
129
+ - **Context-Aware Operations** - Tools behave based on active project/mode
130
+ - **Stateful Sessions** - Maintains project state across interactions
131
+ - **Error Handling** - Graceful degradation when tools fail
132
+
133
+ ## Error Handling and Resilience
134
+
135
+ ### Language Server Reliability
136
+ - **Timeout Management** - Configurable timeouts for LSP requests
137
+ - **Process Recovery** - Automatic restart of crashed language servers
138
+ - **Fallback Behavior** - Graceful degradation when LSP unavailable
139
+ - **Caching Strategy** - Reduces impact of server failures
140
+
141
+ ### Project Activation Safety
142
+ - **Validation** - Verify project structure before activation
143
+ - **Error Isolation** - Project failures don't affect other projects
144
+ - **Recovery Mechanisms** - Automatic cleanup and retry logic
145
+
146
+ ## Performance Considerations
147
+
148
+ ### Caching Strategy
149
+ - **Symbol Cache** - In-memory caching of expensive symbol operations
150
+ - **File System Cache** - Reduced disk I/O for repeated operations
151
+ - **Language Server Cache** - Persistent cache across sessions
152
+
153
+ ### Resource Management
154
+ - **Language Server Pooling** - Reuse servers across projects when possible
155
+ - **Memory Management** - Automatic cleanup of unused resources
156
+ - **Background Operations** - Async operations don't block user interactions
157
+
158
+ ## Extension Points
159
+
160
+ ### Adding New Languages
161
+ 1. Implement language server class in `src/solidlsp/language_servers/`
162
+ 2. Add runtime dependencies configuration
163
+ 3. Create test repository and test suite
164
+ 4. Update language enumeration and configuration
165
+
166
+ ### Adding New Tools
167
+ 1. Inherit from `Tool` base class in `tools_base.py`
168
+ 2. Implement required methods and parameter validation
169
+ 3. Register tool in appropriate tool registry
170
+ 4. Add to context/mode configurations as needed
171
+
172
+ ### Custom Contexts and Modes
173
+ - Define new contexts in YAML configuration files
174
+ - Specify tool sets and operational patterns
175
+ - Configure for specific development workflows
projects/ui/serena-new/.serena/memories/serena_repository_structure.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Serena Repository Structure
2
+
3
+ ## Overview
4
+ Serena is a multi-language code assistant that combines two main components:
5
+ 1. **Serena Core** - The main agent framework with tools and MCP server
6
+ 2. **SolidLSP** - A unified Language Server Protocol wrapper for multiple programming languages
7
+
8
+ ## Top-Level Structure
9
+
10
+ ```
11
+ serena/
12
+ ├── src/ # Main source code
13
+ │ ├── serena/ # Serena agent framework
14
+ │ ├── solidlsp/ # LSP wrapper library
15
+ │ └── interprompt/ # Multi-language prompt templates
16
+ ├── test/ # Test suites
17
+ │ ├── serena/ # Serena agent tests
18
+ │ ├── solidlsp/ # Language server tests
19
+ │ └── resources/repos/ # Test repositories for each language
20
+ ├── scripts/ # Build and utility scripts
21
+ ├── resources/ # Static resources and configurations
22
+ ├── pyproject.toml # Python project configuration
23
+ ├── README.md # Project documentation
24
+ └── CHANGELOG.md # Version history
25
+ ```
26
+
27
+ ## Source Code Organization
28
+
29
+ ### Serena Core (`src/serena/`)
30
+ - **`agent.py`** - Main SerenaAgent class that orchestrates everything
31
+ - **`tools/`** - MCP tools for file operations, symbols, memory, etc.
32
+ - `file_tools.py` - File system operations (read, write, search)
33
+ - `symbol_tools.py` - Symbol-based code operations (find, edit)
34
+ - `memory_tools.py` - Knowledge persistence and retrieval
35
+ - `config_tools.py` - Project and mode management
36
+ - `workflow_tools.py` - Onboarding and meta-operations
37
+ - **`config/`** - Configuration management
38
+ - `serena_config.py` - Main configuration classes
39
+ - `context_mode.py` - Context and mode definitions
40
+ - **`util/`** - Utility modules
41
+ - **`mcp.py`** - MCP server implementation
42
+ - **`cli.py`** - Command-line interface
43
+
44
+ ### SolidLSP (`src/solidlsp/`)
45
+ - **`ls.py`** - Main SolidLanguageServer class
46
+ - **`language_servers/`** - Language-specific implementations
47
+ - `csharp_language_server.py` - C# (Microsoft.CodeAnalysis.LanguageServer)
48
+ - `python_server.py` - Python (Pyright)
49
+ - `typescript_language_server.py` - TypeScript
50
+ - `rust_analyzer.py` - Rust
51
+ - `gopls.py` - Go
52
+ - And many more...
53
+ - **`ls_config.py`** - Language server configuration
54
+ - **`ls_types.py`** - LSP type definitions
55
+ - **`ls_utils.py`** - Utilities for working with LSP data
56
+
57
+ ### Interprompt (`src/interprompt/`)
58
+ - Multi-language prompt template system
59
+ - Jinja2-based templating with language fallbacks
60
+
61
+ ## Test Structure
62
+
63
+ ### Language Server Tests (`test/solidlsp/`)
64
+ Each language has its own test directory:
65
+ ```
66
+ test/solidlsp/
67
+ ├── csharp/
68
+ │ └── test_csharp_basic.py
69
+ ├── python/
70
+ │ └── test_python_basic.py
71
+ ├── typescript/
72
+ │ └── test_typescript_basic.py
73
+ └── ...
74
+ ```
75
+
76
+ ### Test Resources (`test/resources/repos/`)
77
+ Contains minimal test projects for each language:
78
+ ```
79
+ test/resources/repos/
80
+ ├── csharp/test_repo/
81
+ │ ├── serena.sln
82
+ │ ├── TestProject.csproj
83
+ │ ├── Program.cs
84
+ │ └── Models/Person.cs
85
+ ├── python/test_repo/
86
+ ├── typescript/test_repo/
87
+ └── ...
88
+ ```
89
+
90
+ ### Test Infrastructure
91
+ - **`test/conftest.py`** - Shared test fixtures and utilities
92
+ - **`create_ls()`** function - Creates language server instances for testing
93
+ - **`language_server` fixture** - Parametrized fixture for multi-language tests
94
+
95
+ ## Key Configuration Files
96
+
97
+ - **`pyproject.toml`** - Python dependencies, build config, and tool settings
98
+ - **`.serena/`** directories - Project-specific Serena configuration and memories
99
+ - **`CLAUDE.md`** - Instructions for AI assistants working on the project
100
+
101
+ ## Dependencies Management
102
+
103
+ The project uses modern Python tooling:
104
+ - **uv** for fast dependency resolution and virtual environments
105
+ - **pytest** for testing with language-specific markers (`@pytest.mark.csharp`)
106
+ - **ruff** for linting and formatting
107
+ - **mypy** for type checking
108
+
109
+ ## Build and Development
110
+
111
+ - **Docker support** - Full containerized development environment
112
+ - **GitHub Actions** - CI/CD with language server testing
113
+ - **Development scripts** in `scripts/` directory
projects/ui/serena-new/.serena/memories/suggested_commands.md ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Suggested Commands
2
+
3
+ ## Development Tasks (using uv and poe)
4
+
5
+ The following tasks should generally be executed using `uv run poe <task_name>`.
6
+
7
+ - `format`: This is the **only** allowed command for formatting. Run as `uv run poe format`.
8
+ - `type-check`: This is the **only** allowed command for type checking. Run as `uv run poe type-check`.
9
+ - `test`: This is the preferred command for running tests (`uv run poe test [args]`). You can select subsets of tests with markers,
10
+ the current markers are
11
+ ```toml
12
+ markers = [
13
+ "python: language server running for Python",
14
+ "go: language server running for Go",
15
+ "java: language server running for Java",
16
+ "rust: language server running for Rust",
17
+ "typescript: language server running for TypeScript",
18
+ "php: language server running for PHP",
19
+ "snapshot: snapshot tests for symbolic editing operations",
20
+ ]
21
+ ```
22
+ By default, `uv run poe test` uses the markers set in the env var `PYTEST_MARKERS`, or, if it unset, uses `-m "not java and not rust and not isolated process"`.
23
+ You can override this behavior by simply passing the `-m` option to `uv run poe test`, e.g. `uv run poe test -m "python or go"`.
24
+
25
+ For finishing a task, make sure format, type-check and test pass! Run them at the end of the task
26
+ and if needed fix any issues that come up and run them again until they pass.
projects/ui/serena-new/src/interprompt/.syncCommitId.remote ADDED
@@ -0,0 +1 @@
 
 
1
+ 6bdf19b0fd0fa5a809e1989b334bbfe9d8a7051a
projects/ui/serena-new/src/interprompt/.syncCommitId.this ADDED
@@ -0,0 +1 @@
 
 
1
+ 6d9d3adac8e77fa72e55e2675c1bcd3a7331cde1
projects/ui/serena-new/src/interprompt/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .prompt_factory import autogenerate_prompt_factory_module
2
+
3
+ __all__ = ["autogenerate_prompt_factory_module"]
projects/ui/serena-new/src/interprompt/jinja_template.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any
2
+
3
+ import jinja2
4
+ import jinja2.meta
5
+ import jinja2.nodes
6
+ import jinja2.visitor
7
+
8
+ from interprompt.util.class_decorators import singleton
9
+
10
+
11
+ class ParameterizedTemplateInterface:
12
+ def get_parameters(self) -> list[str]: ...
13
+
14
+
15
+ @singleton
16
+ class _JinjaEnvProvider:
17
+ def __init__(self) -> None:
18
+ self._env: jinja2.Environment | None = None
19
+
20
+ def get_env(self) -> jinja2.Environment:
21
+ if self._env is None:
22
+ self._env = jinja2.Environment()
23
+ return self._env
24
+
25
+
26
+ class JinjaTemplate(ParameterizedTemplateInterface):
27
+ def __init__(self, template_string: str) -> None:
28
+ self._template_string = template_string
29
+ self._template = _JinjaEnvProvider().get_env().from_string(self._template_string)
30
+ parsed_content = self._template.environment.parse(self._template_string)
31
+ self._parameters = sorted(jinja2.meta.find_undeclared_variables(parsed_content))
32
+
33
+ def render(self, **params: Any) -> str:
34
+ """Renders the template with the given kwargs. You can find out which parameters are required by calling get_parameter_names()."""
35
+ return self._template.render(**params)
36
+
37
+ def get_parameters(self) -> list[str]:
38
+ """A sorted list of parameter names that are extracted from the template string. It is impossible to know the types of the parameter
39
+ values, they can be primitives, dicts or dict-like objects.
40
+
41
+ :return: the list of parameter names
42
+ """
43
+ return self._parameters
projects/ui/serena-new/src/interprompt/multilang_prompt.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from enum import Enum
4
+ from typing import Any, Generic, Literal, TypeVar
5
+
6
+ import yaml
7
+ from sensai.util.string import ToStringMixin
8
+
9
+ from .jinja_template import JinjaTemplate, ParameterizedTemplateInterface
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ class PromptTemplate(ToStringMixin, ParameterizedTemplateInterface):
15
+ def __init__(self, name: str, jinja_template_string: str) -> None:
16
+ self.name = name
17
+ self._jinja_template = JinjaTemplate(jinja_template_string.strip())
18
+
19
+ def _tostring_exclude_private(self) -> bool:
20
+ return True
21
+
22
+ def render(self, **params: Any) -> str:
23
+ return self._jinja_template.render(**params)
24
+
25
+ def get_parameters(self) -> list[str]:
26
+ return self._jinja_template.get_parameters()
27
+
28
+
29
+ class PromptList:
30
+ def __init__(self, items: list[str]) -> None:
31
+ self.items = [x.strip() for x in items]
32
+
33
+ def to_string(self) -> str:
34
+ bullet = " * "
35
+ indent = " " * len(bullet)
36
+ items = [x.replace("\n", "\n" + indent) for x in self.items]
37
+ return "\n * ".join(items)
38
+
39
+
40
+ T = TypeVar("T")
41
+ DEFAULT_LANG_CODE = "default"
42
+
43
+
44
+ class LanguageFallbackMode(Enum):
45
+ """
46
+ Defines what to do if there is no item for the given language.
47
+ """
48
+
49
+ ANY = "any"
50
+ """
51
+ Return the item for any language (the first one found)
52
+ """
53
+ EXCEPTION = "exception"
54
+ """
55
+ If the requested language is not found, raise an exception
56
+ """
57
+ USE_DEFAULT_LANG = "use_default_lang"
58
+ """
59
+ If the requested language is not found, use the default language
60
+ """
61
+
62
+
63
+ class _MultiLangContainer(Generic[T], ToStringMixin):
64
+ """
65
+ A container of items (usually, all having the same semantic meaning) which are associated with different languages.
66
+ Can also be used for single-language purposes by always using the default language code.
67
+ """
68
+
69
+ def __init__(self, name: str) -> None:
70
+ self.name = name
71
+ self._lang2item: dict[str, T] = {}
72
+ """Maps language codes to items"""
73
+
74
+ def _tostring_excludes(self) -> list[str]:
75
+ return ["lang2item"]
76
+
77
+ def _tostring_additional_entries(self) -> dict[str, Any]:
78
+ return dict(languages=list(self._lang2item.keys()))
79
+
80
+ def get_language_codes(self) -> list[str]:
81
+ """The language codes for which items are registered in the container."""
82
+ return list(self._lang2item.keys())
83
+
84
+ def add_item(self, item: T, lang_code: str = DEFAULT_LANG_CODE, allow_overwrite: bool = False) -> None:
85
+ """Adds an item to the container, representing the same semantic entity as the other items in the container but in a different language.
86
+
87
+ :param item: the item to add
88
+ :param lang_code: the language shortcode for which to add the item. Use the default for single-language use cases.
89
+ :param allow_overwrite: if True, allow overwriting an existing entry for the same language
90
+ """
91
+ if not allow_overwrite and lang_code in self._lang2item:
92
+ raise KeyError(f"Item for language '{lang_code}' already registered for name '{self.name}'")
93
+ self._lang2item[lang_code] = item
94
+
95
+ def has_item(self, lang_code: str = DEFAULT_LANG_CODE) -> bool:
96
+ return lang_code in self._lang2item
97
+
98
+ def get_item(self, lang: str = DEFAULT_LANG_CODE, fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION) -> T:
99
+ """
100
+ Gets the item for the given language.
101
+
102
+ :param lang: the language shortcode for which to obtain the prompt template. A default language can be specified.
103
+ :param fallback_mode: defines what to do if there is no item for the given language
104
+ :return: the item
105
+ """
106
+ try:
107
+ return self._lang2item[lang]
108
+ except KeyError as outer_e:
109
+ if fallback_mode == LanguageFallbackMode.EXCEPTION:
110
+ raise KeyError(f"Item for language '{lang}' not found for name '{self.name}'") from outer_e
111
+ if fallback_mode == LanguageFallbackMode.ANY:
112
+ try:
113
+ return next(iter(self._lang2item.values()))
114
+ except StopIteration as e:
115
+ raise KeyError(f"No items registered for any language in container '{self.name}'") from e
116
+ if fallback_mode == LanguageFallbackMode.USE_DEFAULT_LANG:
117
+ try:
118
+ return self._lang2item[DEFAULT_LANG_CODE]
119
+ except KeyError as e:
120
+ raise KeyError(
121
+ f"Item not found neither for {lang=} nor for the default language '{DEFAULT_LANG_CODE}' in container '{self.name}'"
122
+ ) from e
123
+
124
+ def __len__(self) -> int:
125
+ return len(self._lang2item)
126
+
127
+
128
+ class MultiLangPromptTemplate(ParameterizedTemplateInterface):
129
+ """
130
+ Represents a prompt template with support for multiple languages.
131
+ The parameters of all prompt templates (for all languages) are (must be) the same.
132
+ """
133
+
134
+ def __init__(self, name: str) -> None:
135
+ self._prompts_container = _MultiLangContainer[PromptTemplate](name)
136
+
137
+ def __len__(self) -> int:
138
+ return len(self._prompts_container)
139
+
140
+ @property
141
+ def name(self) -> str:
142
+ return self._prompts_container.name
143
+
144
+ def add_prompt_template(
145
+ self, prompt_template: PromptTemplate, lang_code: str = DEFAULT_LANG_CODE, allow_overwrite: bool = False
146
+ ) -> None:
147
+ """
148
+ Adds a prompt template for a new language.
149
+ The parameters of all prompt templates (for all languages) are (must be) the same, so if a prompt template is already registered,
150
+ the parameters of the new prompt template should be the same as the existing ones.
151
+
152
+ :param prompt_template: the prompt template to add
153
+ :param lang_code: the language code for which to add the prompt template. For single-language use cases, you should always use the default language code.
154
+ :param allow_overwrite: whether to allow overwriting an existing entry for the same language
155
+ """
156
+ incoming_parameters = prompt_template.get_parameters()
157
+ if len(self) > 0:
158
+ parameters = self.get_parameters()
159
+ if parameters != incoming_parameters:
160
+ raise ValueError(
161
+ f"Cannot add prompt template for language '{lang_code}' to MultiLangPromptTemplate '{self.name}'"
162
+ f"because the parameters are inconsistent: {parameters} vs {prompt_template.get_parameters()}"
163
+ )
164
+
165
+ self._prompts_container.add_item(prompt_template, lang_code, allow_overwrite)
166
+
167
+ def get_prompt_template(
168
+ self, lang_code: str = DEFAULT_LANG_CODE, fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION
169
+ ) -> PromptTemplate:
170
+ return self._prompts_container.get_item(lang_code, fallback_mode)
171
+
172
+ def get_parameters(self) -> list[str]:
173
+ if len(self) == 0:
174
+ raise RuntimeError(
175
+ f"No prompt templates registered for MultiLangPromptTemplate '{self.name}', make sure to register a prompt template before accessing the parameters"
176
+ )
177
+ first_prompt_template = next(iter(self._prompts_container._lang2item.values()))
178
+ return first_prompt_template.get_parameters()
179
+
180
+ def render(
181
+ self,
182
+ params: dict[str, Any],
183
+ lang_code: str = DEFAULT_LANG_CODE,
184
+ fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION,
185
+ ) -> str:
186
+ prompt_template = self.get_prompt_template(lang_code, fallback_mode)
187
+ return prompt_template.render(**params)
188
+
189
+ def has_item(self, lang_code: str = DEFAULT_LANG_CODE) -> bool:
190
+ return self._prompts_container.has_item(lang_code)
191
+
192
+
193
+ class MultiLangPromptList(_MultiLangContainer[PromptList]):
194
+ pass
195
+
196
+
197
+ class MultiLangPromptCollection:
198
+ """
199
+ Main class for managing a collection of prompt templates and prompt lists, with support for multiple languages.
200
+ All data will be read from the yamls directly contained in the given directory on initialization.
201
+ It is thus assumed that you manage one directory per prompt collection.
202
+
203
+ The yamls are assumed to be either of the form
204
+
205
+ ```yaml
206
+ lang: <language_code> # optional, defaults to "default"
207
+ prompts:
208
+ <prompt_name>:
209
+ <prompt_template_string>
210
+ <prompt_list_name>: [<prompt_string_1>, <prompt_string_2>, ...]
211
+
212
+ ```
213
+
214
+ When specifying prompt templates for multiple languages, make sure that the Jinja template parameters
215
+ (inferred from the things inside the `{{ }}` in the template strings) are the same for all languages
216
+ (you will get an exception otherwise).
217
+
218
+ The prompt names must be unique (for the same language) within the collection.
219
+ """
220
+
221
+ def __init__(self, prompts_dir: str | list[str], fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION) -> None:
222
+ """
223
+ :param prompts_dir: the directory containing the prompt templates and prompt lists.
224
+ If a list is provided, will look for prompt templates in the dirs from left to right
225
+ (first one containing the desired template wins).
226
+ :param fallback_mode: the fallback mode to use when a prompt template or prompt list is not found for the requested language.
227
+ May be reset after initialization.
228
+ """
229
+ self._multi_lang_prompt_templates: dict[str, MultiLangPromptTemplate] = {}
230
+ self._multi_lang_prompt_lists: dict[str, MultiLangPromptList] = {}
231
+ if isinstance(prompts_dir, str):
232
+ prompts_dir = [prompts_dir]
233
+
234
+ # Add prompts from multiple directories, prioritizing names from the left.
235
+ # If name collisions appear in the first directory, an error is raised (so the first directory should have no
236
+ # internal collisions, this helps in avoiding errors)
237
+ # For all following directories, on a collision the new value will be ignored.
238
+ # This also means that for the following directories, there is no error check on collisions internal to them.
239
+ # We assume that they are correct (i.e., they have no internal collisions).
240
+ first_prompts_dir, fallback_prompt_dirs = prompts_dir[0], prompts_dir[1:]
241
+ self._load_from_disc(first_prompts_dir, on_name_collision="raise")
242
+ for fallback_prompt_dir in fallback_prompt_dirs:
243
+ # already loaded prompts have priority
244
+ self._load_from_disc(fallback_prompt_dir, on_name_collision="skip")
245
+
246
+ self.fallback_mode = fallback_mode
247
+
248
+ def _add_prompt_template(
249
+ self,
250
+ name: str,
251
+ template_str: str,
252
+ lang_code: str = DEFAULT_LANG_CODE,
253
+ on_name_collision: Literal["skip", "overwrite", "raise"] = "raise",
254
+ ) -> None:
255
+ """
256
+ :param name: name of the prompt template
257
+ :param template_str: the Jinja template string
258
+ :param lang_code: the language code for which to add the prompt template.
259
+ :param on_name_collision: how to deal with name/lang_code collisions
260
+ """
261
+ allow_overwrite = False
262
+ prompt_template = PromptTemplate(name, template_str)
263
+ mlpt = self._multi_lang_prompt_templates.get(name)
264
+ if mlpt is None:
265
+ mlpt = MultiLangPromptTemplate(name)
266
+ self._multi_lang_prompt_templates[name] = mlpt
267
+ if mlpt.has_item(lang_code):
268
+ if on_name_collision == "raise":
269
+ raise KeyError(f"Prompt '{name}' for {lang_code} already exists!")
270
+ if on_name_collision == "skip":
271
+ log.debug(f"Skipping prompt '{name}' since it already exists.")
272
+ return
273
+ elif on_name_collision == "overwrite":
274
+ allow_overwrite = True
275
+ mlpt.add_prompt_template(prompt_template, lang_code=lang_code, allow_overwrite=allow_overwrite)
276
+
277
+ def _add_prompt_list(
278
+ self,
279
+ name: str,
280
+ prompt_list: list[str],
281
+ lang_code: str = DEFAULT_LANG_CODE,
282
+ on_name_collision: Literal["skip", "overwrite", "raise"] = "raise",
283
+ ) -> None:
284
+ """
285
+ :param name: name of the prompt list
286
+ :param prompt_list: a list of prompts
287
+ :param lang_code: the language code for which to add the prompt list.
288
+ :param on_name_collision: how to deal with name/lang_code collisions
289
+ """
290
+ allow_overwrite = False
291
+ multilang_prompt_list = self._multi_lang_prompt_lists.get(name)
292
+ if multilang_prompt_list is None:
293
+ multilang_prompt_list = MultiLangPromptList(name)
294
+ self._multi_lang_prompt_lists[name] = multilang_prompt_list
295
+ if multilang_prompt_list.has_item(lang_code):
296
+ if on_name_collision == "raise":
297
+ raise KeyError(f"Prompt '{name}' for {lang_code} already exists!")
298
+ if on_name_collision == "skip":
299
+ log.debug(f"Skipping prompt '{name}' since it already exists.")
300
+ return
301
+ elif on_name_collision == "overwrite":
302
+ allow_overwrite = True
303
+ multilang_prompt_list.add_item(PromptList(prompt_list), lang_code=lang_code, allow_overwrite=allow_overwrite)
304
+
305
+ def _load_from_disc(self, prompts_dir: str, on_name_collision: Literal["skip", "overwrite", "raise"] = "raise") -> None:
306
+ """Loads all prompt templates and prompt lists from yaml files in the given directory.
307
+
308
+ :param prompts_dir:
309
+ :param on_name_collision: how to deal with name/lang_code collisions
310
+ """
311
+ for fn in os.listdir(prompts_dir):
312
+ if not fn.endswith((".yml", ".yaml")):
313
+ log.debug(f"Skipping non-YAML file: {fn}")
314
+ continue
315
+ path = os.path.join(prompts_dir, fn)
316
+ with open(path, encoding="utf-8") as f:
317
+ data = yaml.safe_load(f)
318
+ try:
319
+ prompts_data = data["prompts"]
320
+ except KeyError as e:
321
+ raise KeyError(f"Invalid yaml structure (missing 'prompts' key) in file {path}") from e
322
+
323
+ lang_code = prompts_data.get("lang", DEFAULT_LANG_CODE)
324
+ # add the data to the collection
325
+ for prompt_name, prompt_template_or_list in prompts_data.items():
326
+ if isinstance(prompt_template_or_list, list):
327
+ self._add_prompt_list(prompt_name, prompt_template_or_list, lang_code=lang_code, on_name_collision=on_name_collision)
328
+ elif isinstance(prompt_template_or_list, str):
329
+ self._add_prompt_template(
330
+ prompt_name, prompt_template_or_list, lang_code=lang_code, on_name_collision=on_name_collision
331
+ )
332
+ else:
333
+ raise ValueError(
334
+ f"Invalid prompt type for {prompt_name} in file {path} (should be str or list): {prompt_template_or_list}"
335
+ )
336
+
337
+ def get_prompt_template_names(self) -> list[str]:
338
+ return list(self._multi_lang_prompt_templates.keys())
339
+
340
+ def get_prompt_list_names(self) -> list[str]:
341
+ return list(self._multi_lang_prompt_lists.keys())
342
+
343
+ def __len__(self) -> int:
344
+ return len(self._multi_lang_prompt_templates)
345
+
346
+ def get_multilang_prompt_template(self, prompt_name: str) -> MultiLangPromptTemplate:
347
+ """The MultiLangPromptTemplate object for the given prompt name. For single-language use cases, you should use the `get_prompt_template` method instead."""
348
+ return self._multi_lang_prompt_templates[prompt_name]
349
+
350
+ def get_multilang_prompt_list(self, prompt_name: str) -> MultiLangPromptList:
351
+ return self._multi_lang_prompt_lists[prompt_name]
352
+
353
+ def get_prompt_template(
354
+ self,
355
+ prompt_name: str,
356
+ lang_code: str = DEFAULT_LANG_CODE,
357
+ ) -> PromptTemplate:
358
+ """The PromptTemplate object for the given prompt name and language code."""
359
+ return self.get_multilang_prompt_template(prompt_name).get_prompt_template(lang_code=lang_code, fallback_mode=self.fallback_mode)
360
+
361
+ def get_prompt_template_parameters(self, prompt_name: str) -> list[str]:
362
+ """The parameters of the PromptTemplate object for the given prompt name."""
363
+ return self.get_multilang_prompt_template(prompt_name).get_parameters()
364
+
365
+ def get_prompt_list(self, prompt_name: str, lang_code: str = DEFAULT_LANG_CODE) -> PromptList:
366
+ """The PromptList object for the given prompt name and language code."""
367
+ return self.get_multilang_prompt_list(prompt_name).get_item(lang_code)
368
+
369
+ def _has_prompt_list(self, prompt_name: str, lang_code: str = DEFAULT_LANG_CODE) -> bool:
370
+ multi_lang_prompt_list = self._multi_lang_prompt_lists.get(prompt_name)
371
+ if multi_lang_prompt_list is None:
372
+ return False
373
+ return multi_lang_prompt_list.has_item(lang_code)
374
+
375
+ def _has_prompt_template(self, prompt_name: str, lang_code: str = DEFAULT_LANG_CODE) -> bool:
376
+ multi_lang_prompt_template = self._multi_lang_prompt_templates.get(prompt_name)
377
+ if multi_lang_prompt_template is None:
378
+ return False
379
+ return multi_lang_prompt_template.has_item(lang_code)
380
+
381
+ def render_prompt_template(
382
+ self,
383
+ prompt_name: str,
384
+ params: dict[str, Any],
385
+ lang_code: str = DEFAULT_LANG_CODE,
386
+ ) -> str:
387
+ """Renders the prompt template for the given prompt name and language code."""
388
+ return self.get_prompt_template(prompt_name, lang_code=lang_code).render(**params)
projects/ui/serena-new/src/interprompt/prompt_factory.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ from typing import Any
4
+
5
+ from .multilang_prompt import DEFAULT_LANG_CODE, LanguageFallbackMode, MultiLangPromptCollection, PromptList
6
+
7
+ log = logging.getLogger(__name__)
8
+
9
+
10
+ class PromptFactoryBase:
11
+ """Base class for auto-generated prompt factory classes."""
12
+
13
+ def __init__(self, prompts_dir: str | list[str], lang_code: str = DEFAULT_LANG_CODE, fallback_mode=LanguageFallbackMode.EXCEPTION):
14
+ """
15
+ :param prompts_dir: the directory containing the prompt templates and prompt lists.
16
+ If a list is provided, will look for prompt templates in the dirs from left to right
17
+ (first one containing the desired template wins).
18
+ :param lang_code: the language code to use for retrieving the prompt templates and prompt lists.
19
+ Leave as `default` for single-language use cases.
20
+ :param fallback_mode: the fallback mode to use when a prompt template or prompt list is not found for the requested language.
21
+ Irrelevant for single-language use cases.
22
+ """
23
+ self.lang_code = lang_code
24
+ self._prompt_collection = MultiLangPromptCollection(prompts_dir, fallback_mode=fallback_mode)
25
+
26
+ def _render_prompt(self, prompt_name: str, params: dict[str, Any]) -> str:
27
+ del params["self"]
28
+ return self._prompt_collection.render_prompt_template(prompt_name, params, lang_code=self.lang_code)
29
+
30
+ def _get_prompt_list(self, prompt_name: str) -> PromptList:
31
+ return self._prompt_collection.get_prompt_list(prompt_name, self.lang_code)
32
+
33
+
34
+ def autogenerate_prompt_factory_module(prompts_dir: str, target_module_path: str) -> None:
35
+ """
36
+ Auto-generates a prompt factory module for the given prompt directory.
37
+ The generated `PromptFactory` class is meant to be the central entry class for retrieving and rendering prompt templates and prompt
38
+ lists in your application.
39
+ It will contain one method per prompt template and prompt list, and is useful for both single- and multi-language use cases.
40
+
41
+ :param prompts_dir: the directory containing the prompt templates and prompt lists
42
+ :param target_module_path: the path to the target module file (.py). Important: The module will be overwritten!
43
+ """
44
+ generated_code = """
45
+ # ruff: noqa
46
+ # black: skip
47
+ # mypy: ignore-errors
48
+
49
+ # NOTE: This module is auto-generated from interprompt.autogenerate_prompt_factory_module, do not edit manually!
50
+
51
+ from interprompt.multilang_prompt import PromptList
52
+ from interprompt.prompt_factory import PromptFactoryBase
53
+ from typing import Any
54
+
55
+
56
+ class PromptFactory(PromptFactoryBase):
57
+ \"""
58
+ A class for retrieving and rendering prompt templates and prompt lists.
59
+ \"""
60
+ """
61
+ # ---- add methods based on prompt template names and parameters and prompt list names ----
62
+ prompt_collection = MultiLangPromptCollection(prompts_dir)
63
+
64
+ for template_name in prompt_collection.get_prompt_template_names():
65
+ template_parameters = prompt_collection.get_prompt_template_parameters(template_name)
66
+ if len(template_parameters) == 0:
67
+ method_params_str = ""
68
+ else:
69
+ method_params_str = ", *, " + ", ".join([f"{param}: Any" for param in template_parameters])
70
+ generated_code += f"""
71
+ def create_{template_name}(self{method_params_str}) -> str:
72
+ return self._render_prompt('{template_name}', locals())
73
+ """
74
+ for prompt_list_name in prompt_collection.get_prompt_list_names():
75
+ generated_code += f"""
76
+ def get_list_{prompt_list_name}(self) -> PromptList:
77
+ return self._get_prompt_list('{prompt_list_name}')
78
+ """
79
+ os.makedirs(os.path.dirname(target_module_path), exist_ok=True)
80
+ with open(target_module_path, "w", encoding="utf-8") as f:
81
+ f.write(generated_code)
82
+ log.info(f"Prompt factory generated successfully in {target_module_path}")
projects/ui/serena-new/src/serena/__init__.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __version__ = "0.1.4"
2
+
3
+ import logging
4
+
5
+ log = logging.getLogger(__name__)
6
+
7
+
8
+ def serena_version() -> str:
9
+ """
10
+ :return: the version of the package, including git status if available.
11
+ """
12
+ from serena.util.git import get_git_status
13
+
14
+ version = __version__
15
+ try:
16
+ git_status = get_git_status()
17
+ if git_status is not None:
18
+ version += f"-{git_status.commit[:8]}"
19
+ if not git_status.is_clean:
20
+ version += "-dirty"
21
+ except:
22
+ pass
23
+ return version
projects/ui/serena-new/src/serena/agent.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The Serena Model Context Protocol (MCP) Server
3
+ """
4
+
5
+ import multiprocessing
6
+ import os
7
+ import platform
8
+ import sys
9
+ import threading
10
+ import webbrowser
11
+ from collections import defaultdict
12
+ from collections.abc import Callable
13
+ from concurrent.futures import Future, ThreadPoolExecutor
14
+ from logging import Logger
15
+ from pathlib import Path
16
+ from typing import TYPE_CHECKING, Any, Optional, TypeVar
17
+
18
+ from sensai.util import logging
19
+ from sensai.util.logging import LogTime
20
+
21
+ from interprompt.jinja_template import JinjaTemplate
22
+ from serena import serena_version
23
+ from serena.analytics import RegisteredTokenCountEstimator, ToolUsageStats
24
+ from serena.config.context_mode import RegisteredContext, SerenaAgentContext, SerenaAgentMode
25
+ from serena.config.serena_config import SerenaConfig, ToolInclusionDefinition, ToolSet, get_serena_managed_in_project_dir
26
+ from serena.dashboard import SerenaDashboardAPI
27
+ from serena.project import Project
28
+ from serena.prompt_factory import SerenaPromptFactory
29
+ from serena.tools import ActivateProjectTool, Tool, ToolMarker, ToolRegistry
30
+ from serena.util.inspection import iter_subclasses
31
+ from serena.util.logging import MemoryLogHandler
32
+ from solidlsp import SolidLanguageServer
33
+
34
+ if TYPE_CHECKING:
35
+ from serena.gui_log_viewer import GuiLogViewer
36
+
37
+ log = logging.getLogger(__name__)
38
+ TTool = TypeVar("TTool", bound="Tool")
39
+ T = TypeVar("T")
40
+ SUCCESS_RESULT = "OK"
41
+
42
+
43
+ class ProjectNotFoundError(Exception):
44
+ pass
45
+
46
+
47
+ class LinesRead:
48
+ def __init__(self) -> None:
49
+ self.files: dict[str, set[tuple[int, int]]] = defaultdict(lambda: set())
50
+
51
+ def add_lines_read(self, relative_path: str, lines: tuple[int, int]) -> None:
52
+ self.files[relative_path].add(lines)
53
+
54
+ def were_lines_read(self, relative_path: str, lines: tuple[int, int]) -> bool:
55
+ lines_read_in_file = self.files[relative_path]
56
+ return lines in lines_read_in_file
57
+
58
+ def invalidate_lines_read(self, relative_path: str) -> None:
59
+ if relative_path in self.files:
60
+ del self.files[relative_path]
61
+
62
+
63
+ class MemoriesManager:
64
+ def __init__(self, project_root: str):
65
+ self._memory_dir = Path(get_serena_managed_in_project_dir(project_root)) / "memories"
66
+ self._memory_dir.mkdir(parents=True, exist_ok=True)
67
+
68
+ def _get_memory_file_path(self, name: str) -> Path:
69
+ # strip all .md from the name. Models tend to get confused, sometimes passing the .md extension and sometimes not.
70
+ name = name.replace(".md", "")
71
+ filename = f"{name}.md"
72
+ return self._memory_dir / filename
73
+
74
+ def load_memory(self, name: str) -> str:
75
+ memory_file_path = self._get_memory_file_path(name)
76
+ if not memory_file_path.exists():
77
+ return f"Memory file {name} not found, consider creating it with the `write_memory` tool if you need it."
78
+ with open(memory_file_path, encoding="utf-8") as f:
79
+ return f.read()
80
+
81
+ def save_memory(self, name: str, content: str) -> str:
82
+ memory_file_path = self._get_memory_file_path(name)
83
+ with open(memory_file_path, "w", encoding="utf-8") as f:
84
+ f.write(content)
85
+ return f"Memory {name} written."
86
+
87
+ def list_memories(self) -> list[str]:
88
+ return [f.name.replace(".md", "") for f in self._memory_dir.iterdir() if f.is_file()]
89
+
90
+ def delete_memory(self, name: str) -> str:
91
+ memory_file_path = self._get_memory_file_path(name)
92
+ memory_file_path.unlink()
93
+ return f"Memory {name} deleted."
94
+
95
+
96
+ class AvailableTools:
97
+ def __init__(self, tools: list[Tool]):
98
+ """
99
+ :param tools: the list of available tools
100
+ """
101
+ self.tools = tools
102
+ self.tool_names = [tool.get_name_from_cls() for tool in tools]
103
+ self.tool_marker_names = set()
104
+ for marker_class in iter_subclasses(ToolMarker):
105
+ for tool in tools:
106
+ if isinstance(tool, marker_class):
107
+ self.tool_marker_names.add(marker_class.__name__)
108
+
109
+ def __len__(self) -> int:
110
+ return len(self.tools)
111
+
112
+
113
+ class SerenaAgent:
114
+ def __init__(
115
+ self,
116
+ project: str | None = None,
117
+ project_activation_callback: Callable[[], None] | None = None,
118
+ serena_config: SerenaConfig | None = None,
119
+ context: SerenaAgentContext | None = None,
120
+ modes: list[SerenaAgentMode] | None = None,
121
+ memory_log_handler: MemoryLogHandler | None = None,
122
+ ):
123
+ """
124
+ :param project: the project to load immediately or None to not load any project; may be a path to the project or a name of
125
+ an already registered project;
126
+ :param project_activation_callback: a callback function to be called when a project is activated.
127
+ :param serena_config: the Serena configuration or None to read the configuration from the default location.
128
+ :param context: the context in which the agent is operating, None for default context.
129
+ The context may adjust prompts, tool availability, and tool descriptions.
130
+ :param modes: list of modes in which the agent is operating (they will be combined), None for default modes.
131
+ The modes may adjust prompts, tool availability, and tool descriptions.
132
+ :param memory_log_handler: a MemoryLogHandler instance from which to read log messages; if None, a new one will be created
133
+ if necessary.
134
+ """
135
+ # obtain serena configuration using the decoupled factory function
136
+ self.serena_config = serena_config or SerenaConfig.from_config_file()
137
+
138
+ # adjust log level
139
+ serena_log_level = self.serena_config.log_level
140
+ if Logger.root.level > serena_log_level:
141
+ log.info(f"Changing the root logger level to {serena_log_level}")
142
+ Logger.root.setLevel(serena_log_level)
143
+
144
+ def get_memory_log_handler() -> MemoryLogHandler:
145
+ nonlocal memory_log_handler
146
+ if memory_log_handler is None:
147
+ memory_log_handler = MemoryLogHandler(level=serena_log_level)
148
+ Logger.root.addHandler(memory_log_handler)
149
+ return memory_log_handler
150
+
151
+ # open GUI log window if enabled
152
+ self._gui_log_viewer: Optional["GuiLogViewer"] = None
153
+ if self.serena_config.gui_log_window_enabled:
154
+ if platform.system() == "Darwin":
155
+ log.warning("GUI log window is not supported on macOS")
156
+ else:
157
+ # even importing on macOS may fail if tkinter dependencies are unavailable (depends on Python interpreter installation
158
+ # which uv used as a base, unfortunately)
159
+ from serena.gui_log_viewer import GuiLogViewer
160
+
161
+ self._gui_log_viewer = GuiLogViewer("dashboard", title="Serena Logs", memory_log_handler=get_memory_log_handler())
162
+ self._gui_log_viewer.start()
163
+
164
+ # set the agent context
165
+ if context is None:
166
+ context = SerenaAgentContext.load_default()
167
+ self._context = context
168
+
169
+ # instantiate all tool classes
170
+ self._all_tools: dict[type[Tool], Tool] = {tool_class: tool_class(self) for tool_class in ToolRegistry().get_all_tool_classes()}
171
+ tool_names = [tool.get_name_from_cls() for tool in self._all_tools.values()]
172
+
173
+ # If GUI log window is enabled, set the tool names for highlighting
174
+ if self._gui_log_viewer is not None:
175
+ self._gui_log_viewer.set_tool_names(tool_names)
176
+
177
+ self._tool_usage_stats: ToolUsageStats | None = None
178
+ if self.serena_config.record_tool_usage_stats:
179
+ token_count_estimator = RegisteredTokenCountEstimator[self.serena_config.token_count_estimator]
180
+ log.info(f"Tool usage statistics recording is enabled with token count estimator: {token_count_estimator.name}.")
181
+ self._tool_usage_stats = ToolUsageStats(token_count_estimator)
182
+
183
+ # start the dashboard (web frontend), registering its log handler
184
+ if self.serena_config.web_dashboard:
185
+ self._dashboard_thread, port = SerenaDashboardAPI(
186
+ get_memory_log_handler(), tool_names, tool_usage_stats=self._tool_usage_stats
187
+ ).run_in_thread()
188
+ dashboard_url = f"http://127.0.0.1:{port}/dashboard/index.html"
189
+ log.info("Serena web dashboard started at %s", dashboard_url)
190
+ if self.serena_config.web_dashboard_open_on_launch:
191
+ # open the dashboard URL in the default web browser (using a separate process to control
192
+ # output redirection)
193
+ process = multiprocessing.Process(target=self._open_dashboard, args=(dashboard_url,))
194
+ process.start()
195
+ process.join(timeout=1)
196
+
197
+ # log fundamental information
198
+ log.info(f"Starting Serena server (version={serena_version()}, process id={os.getpid()}, parent process id={os.getppid()})")
199
+ log.info("Configuration file: %s", self.serena_config.config_file_path)
200
+ log.info("Available projects: {}".format(", ".join(self.serena_config.project_names)))
201
+ log.info(f"Loaded tools ({len(self._all_tools)}): {', '.join([tool.get_name_from_cls() for tool in self._all_tools.values()])}")
202
+
203
+ self._check_shell_settings()
204
+
205
+ # determine the base toolset defining the set of exposed tools (which e.g. the MCP shall see),
206
+ # limited by the Serena config, the context (which is fixed for the session) and JetBrains mode
207
+ tool_inclusion_definitions: list[ToolInclusionDefinition] = [self.serena_config, self._context]
208
+ if self._context.name == RegisteredContext.IDE_ASSISTANT.value:
209
+ tool_inclusion_definitions.extend(self._ide_context_tool_inclusion_definitions(project))
210
+ if self.serena_config.jetbrains:
211
+ tool_inclusion_definitions.append(SerenaAgentMode.from_name_internal("jetbrains"))
212
+
213
+ self._base_tool_set = ToolSet.default().apply(*tool_inclusion_definitions)
214
+ self._exposed_tools = AvailableTools([t for t in self._all_tools.values() if self._base_tool_set.includes_name(t.get_name())])
215
+ log.info(f"Number of exposed tools: {len(self._exposed_tools)}")
216
+
217
+ # create executor for starting the language server and running tools in another thread
218
+ # This executor is used to achieve linear task execution, so it is important to use a single-threaded executor.
219
+ self._task_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="SerenaAgentExecutor")
220
+ self._task_executor_lock = threading.Lock()
221
+ self._task_executor_task_index = 1
222
+
223
+ # Initialize the prompt factory
224
+ self.prompt_factory = SerenaPromptFactory()
225
+ self._project_activation_callback = project_activation_callback
226
+
227
+ # project-specific instances, which will be initialized upon project activation
228
+ self._active_project: Project | None = None
229
+ self._active_project_root: str | None = None
230
+ self.language_server: SolidLanguageServer | None = None
231
+ self.memories_manager: MemoriesManager | None = None
232
+ self.lines_read: LinesRead | None = None
233
+
234
+ # set the active modes
235
+ if modes is None:
236
+ modes = SerenaAgentMode.load_default_modes()
237
+ self._modes = modes
238
+
239
+ self._active_tools: dict[type[Tool], Tool] = {}
240
+ self._update_active_tools()
241
+
242
+ # activate a project configuration (if provided or if there is only a single project available)
243
+ if project is not None:
244
+ try:
245
+ self.activate_project_from_path_or_name(project)
246
+ except Exception as e:
247
+ log.error(f"Error activating project '{project}' at startup: {e}", exc_info=e)
248
+
249
+ def get_context(self) -> SerenaAgentContext:
250
+ return self._context
251
+
252
+ def get_tool_description_override(self, tool_name: str) -> str | None:
253
+ return self._context.tool_description_overrides.get(tool_name, None)
254
+
255
+ def _check_shell_settings(self) -> None:
256
+ # On Windows, Claude Code sets COMSPEC to Git-Bash (often even with a path containing spaces),
257
+ # which causes all sorts of trouble, preventing language servers from being launched correctly.
258
+ # So we make sure that COMSPEC is unset if it has been set to bash specifically.
259
+ if platform.system() == "Windows":
260
+ comspec = os.environ.get("COMSPEC", "")
261
+ if "bash" in comspec:
262
+ os.environ["COMSPEC"] = "" # force use of default shell
263
+ log.info("Adjusting COMSPEC environment variable to use the default shell instead of '%s'", comspec)
264
+
265
+ def _ide_context_tool_inclusion_definitions(self, project_root_or_name: str | None) -> list[ToolInclusionDefinition]:
266
+ """
267
+ In the IDE assistant context, the agent is assumed to work on a single project, and we thus
268
+ want to apply that project's tool exclusions/inclusions from the get-go, limiting the set
269
+ of tools that will be exposed to the client.
270
+ So if the project exists, we apply all the aforementioned exclusions.
271
+
272
+ :param project_root_or_name: the project root path or project name
273
+ :return:
274
+ """
275
+ tool_inclusion_definitions = []
276
+ if project_root_or_name is not None:
277
+ # Note: Auto-generation is disabled, because the result must be returned instantaneously
278
+ # (project generation could take too much time), so as not to delay MCP server startup
279
+ # and provide responses to the client immediately.
280
+ project = self.load_project_from_path_or_name(project_root_or_name, autogenerate=False)
281
+ if project is not None:
282
+ tool_inclusion_definitions.append(ToolInclusionDefinition(excluded_tools=[ActivateProjectTool.get_name_from_cls()]))
283
+ tool_inclusion_definitions.append(project.project_config)
284
+ return tool_inclusion_definitions
285
+
286
+ def record_tool_usage_if_enabled(self, input_kwargs: dict, tool_result: str | dict, tool: Tool) -> None:
287
+ """
288
+ Record the usage of a tool with the given input and output strings if tool usage statistics recording is enabled.
289
+ """
290
+ tool_name = tool.get_name()
291
+ if self._tool_usage_stats is not None:
292
+ input_str = str(input_kwargs)
293
+ output_str = str(tool_result)
294
+ log.debug(f"Recording tool usage for tool '{tool_name}'")
295
+ self._tool_usage_stats.record_tool_usage(tool_name, input_str, output_str)
296
+ else:
297
+ log.debug(f"Tool usage statistics recording is disabled, not recording usage of '{tool_name}'.")
298
+
299
+ @staticmethod
300
+ def _open_dashboard(url: str) -> None:
301
+ # Redirect stdout and stderr file descriptors to /dev/null,
302
+ # making sure that nothing can be written to stdout/stderr, even by subprocesses
303
+ null_fd = os.open(os.devnull, os.O_WRONLY)
304
+ os.dup2(null_fd, sys.stdout.fileno())
305
+ os.dup2(null_fd, sys.stderr.fileno())
306
+ os.close(null_fd)
307
+
308
+ # open the dashboard URL in the default web browser
309
+ webbrowser.open(url)
310
+
311
+ def get_project_root(self) -> str:
312
+ """
313
+ :return: the root directory of the active project (if any); raises a ValueError if there is no active project
314
+ """
315
+ project = self.get_active_project()
316
+ if project is None:
317
+ raise ValueError("Cannot get project root if no project is active.")
318
+ return project.project_root
319
+
320
+ def get_exposed_tool_instances(self) -> list["Tool"]:
321
+ """
322
+ :return: the tool instances which are exposed (e.g. to the MCP client).
323
+ Note that the set of exposed tools is fixed for the session, as
324
+ clients don't react to changes in the set of tools, so this is the superset
325
+ of tools that can be offered during the session.
326
+ If a client should attempt to use a tool that is dynamically disabled
327
+ (e.g. because a project is activated that disables it), it will receive an error.
328
+ """
329
+ return list(self._exposed_tools.tools)
330
+
331
+ def get_active_project(self) -> Project | None:
332
+ """
333
+ :return: the active project or None if no project is active
334
+ """
335
+ return self._active_project
336
+
337
+ def get_active_project_or_raise(self) -> Project:
338
+ """
339
+ :return: the active project or raises an exception if no project is active
340
+ """
341
+ project = self.get_active_project()
342
+ if project is None:
343
+ raise ValueError("No active project. Please activate a project first.")
344
+ return project
345
+
346
+ def set_modes(self, modes: list[SerenaAgentMode]) -> None:
347
+ """
348
+ Set the current mode configurations.
349
+
350
+ :param modes: List of mode names or paths to use
351
+ """
352
+ self._modes = modes
353
+ self._update_active_tools()
354
+
355
+ log.info(f"Set modes to {[mode.name for mode in modes]}")
356
+
357
+ def get_active_modes(self) -> list[SerenaAgentMode]:
358
+ """
359
+ :return: the list of active modes
360
+ """
361
+ return list(self._modes)
362
+
363
+ def _format_prompt(self, prompt_template: str) -> str:
364
+ template = JinjaTemplate(prompt_template)
365
+ return template.render(available_tools=self._exposed_tools.tool_names, available_markers=self._exposed_tools.tool_marker_names)
366
+
367
+ def create_system_prompt(self) -> str:
368
+ available_markers = self._exposed_tools.tool_marker_names
369
+ log.info("Generating system prompt with available_tools=(see exposed tools), available_markers=%s", available_markers)
370
+ system_prompt = self.prompt_factory.create_system_prompt(
371
+ context_system_prompt=self._format_prompt(self._context.prompt),
372
+ mode_system_prompts=[self._format_prompt(mode.prompt) for mode in self._modes],
373
+ available_tools=self._exposed_tools.tool_names,
374
+ available_markers=available_markers,
375
+ )
376
+ log.info("System prompt:\n%s", system_prompt)
377
+ return system_prompt
378
+
379
+ def _update_active_tools(self) -> None:
380
+ """
381
+ Update the active tools based on enabled modes and the active project.
382
+ The base tool set already takes the Serena configuration and the context into account
383
+ (as well as any internal modes that are not handled dynamically, such as JetBrains mode).
384
+ """
385
+ tool_set = self._base_tool_set.apply(*self._modes)
386
+ if self._active_project is not None:
387
+ tool_set = tool_set.apply(self._active_project.project_config)
388
+ if self._active_project.project_config.read_only:
389
+ tool_set = tool_set.without_editing_tools()
390
+
391
+ self._active_tools = {
392
+ tool_class: tool_instance
393
+ for tool_class, tool_instance in self._all_tools.items()
394
+ if tool_set.includes_name(tool_instance.get_name())
395
+ }
396
+
397
+ log.info(f"Active tools ({len(self._active_tools)}): {', '.join(self.get_active_tool_names())}")
398
+
399
+ def issue_task(self, task: Callable[[], Any], name: str | None = None) -> Future:
400
+ """
401
+ Issue a task to the executor for asynchronous execution.
402
+ It is ensured that tasks are executed in the order they are issued, one after another.
403
+
404
+ :param task: the task to execute
405
+ :param name: the name of the task for logging purposes; if None, use the task function's name
406
+ :return: a Future object representing the execution of the task
407
+ """
408
+ with self._task_executor_lock:
409
+ task_name = f"Task-{self._task_executor_task_index}[{name or task.__name__}]"
410
+ self._task_executor_task_index += 1
411
+
412
+ def task_execution_wrapper() -> Any:
413
+ with LogTime(task_name, logger=log):
414
+ return task()
415
+
416
+ log.info(f"Scheduling {task_name}")
417
+ return self._task_executor.submit(task_execution_wrapper)
418
+
419
+ def execute_task(self, task: Callable[[], T]) -> T:
420
+ """
421
+ Executes the given task synchronously via the agent's task executor.
422
+ This is useful for tasks that need to be executed immediately and whose results are needed right away.
423
+
424
+ :param task: the task to execute
425
+ :return: the result of the task execution
426
+ """
427
+ future = self.issue_task(task)
428
+ return future.result()
429
+
430
+ def is_using_language_server(self) -> bool:
431
+ """
432
+ :return: whether this agent uses language server-based code analysis
433
+ """
434
+ return not self.serena_config.jetbrains
435
+
436
+ def _activate_project(self, project: Project) -> None:
437
+ log.info(f"Activating {project.project_name} at {project.project_root}")
438
+ self._active_project = project
439
+ self._update_active_tools()
440
+
441
+ # initialize project-specific instances which do not depend on the language server
442
+ self.memories_manager = MemoriesManager(project.project_root)
443
+ self.lines_read = LinesRead()
444
+
445
+ def init_language_server() -> None:
446
+ # start the language server
447
+ with LogTime("Language server initialization", logger=log):
448
+ self.reset_language_server()
449
+ assert self.language_server is not None
450
+
451
+ # initialize the language server in the background (if in language server mode)
452
+ if self.is_using_language_server():
453
+ self.issue_task(init_language_server)
454
+
455
+ if self._project_activation_callback is not None:
456
+ self._project_activation_callback()
457
+
458
+ def load_project_from_path_or_name(self, project_root_or_name: str, autogenerate: bool) -> Project | None:
459
+ """
460
+ Get a project instance from a path or a name.
461
+
462
+ :param project_root_or_name: the path to the project root or the name of the project
463
+ :param autogenerate: whether to autogenerate the project for the case where first argument is a directory
464
+ which does not yet contain a Serena project configuration file
465
+ :return: the project instance if it was found/could be created, None otherwise
466
+ """
467
+ project_instance: Project | None = self.serena_config.get_project(project_root_or_name)
468
+ if project_instance is not None:
469
+ log.info(f"Found registered project '{project_instance.project_name}' at path {project_instance.project_root}")
470
+ elif autogenerate and os.path.isdir(project_root_or_name):
471
+ project_instance = self.serena_config.add_project_from_path(project_root_or_name)
472
+ log.info(f"Added new project {project_instance.project_name} for path {project_instance.project_root}")
473
+ return project_instance
474
+
475
+ def activate_project_from_path_or_name(self, project_root_or_name: str) -> Project:
476
+ """
477
+ Activate a project from a path or a name.
478
+ If the project was already registered, it will just be activated.
479
+ If the argument is a path at which no Serena project previously existed, the project will be created beforehand.
480
+ Raises ProjectNotFoundError if the project could neither be found nor created.
481
+
482
+ :return: a tuple of the project instance and a Boolean indicating whether the project was newly
483
+ created
484
+ """
485
+ project_instance: Project | None = self.load_project_from_path_or_name(project_root_or_name, autogenerate=True)
486
+ if project_instance is None:
487
+ raise ProjectNotFoundError(
488
+ f"Project '{project_root_or_name}' not found: Not a valid project name or directory. "
489
+ f"Existing project names: {self.serena_config.project_names}"
490
+ )
491
+ self._activate_project(project_instance)
492
+ return project_instance
493
+
494
+ def get_active_tool_classes(self) -> list[type["Tool"]]:
495
+ """
496
+ :return: the list of active tool classes for the current project
497
+ """
498
+ return list(self._active_tools.keys())
499
+
500
+ def get_active_tool_names(self) -> list[str]:
501
+ """
502
+ :return: the list of names of the active tools for the current project
503
+ """
504
+ return sorted([tool.get_name_from_cls() for tool in self.get_active_tool_classes()])
505
+
506
+ def tool_is_active(self, tool_class: type["Tool"] | str) -> bool:
507
+ """
508
+ :param tool_class: the class or name of the tool to check
509
+ :return: True if the tool is active, False otherwise
510
+ """
511
+ if isinstance(tool_class, str):
512
+ return tool_class in self.get_active_tool_names()
513
+ else:
514
+ return tool_class in self.get_active_tool_classes()
515
+
516
+ def get_current_config_overview(self) -> str:
517
+ """
518
+ :return: a string overview of the current configuration, including the active and available configuration options
519
+ """
520
+ result_str = "Current configuration:\n"
521
+ result_str += f"Serena version: {serena_version()}\n"
522
+ result_str += f"Loglevel: {self.serena_config.log_level}, trace_lsp_communication={self.serena_config.trace_lsp_communication}\n"
523
+ if self._active_project is not None:
524
+ result_str += f"Active project: {self._active_project.project_name}\n"
525
+ else:
526
+ result_str += "No active project\n"
527
+ result_str += "Available projects:\n" + "\n".join(list(self.serena_config.project_names)) + "\n"
528
+ result_str += f"Active context: {self._context.name}\n"
529
+
530
+ # Active modes
531
+ active_mode_names = [mode.name for mode in self.get_active_modes()]
532
+ result_str += "Active modes: {}\n".format(", ".join(active_mode_names)) + "\n"
533
+
534
+ # Available but not active modes
535
+ all_available_modes = SerenaAgentMode.list_registered_mode_names()
536
+ inactive_modes = [mode for mode in all_available_modes if mode not in active_mode_names]
537
+ if inactive_modes:
538
+ result_str += "Available but not active modes: {}\n".format(", ".join(inactive_modes)) + "\n"
539
+
540
+ # Active tools
541
+ result_str += "Active tools (after all exclusions from the project, context, and modes):\n"
542
+ active_tool_names = self.get_active_tool_names()
543
+ # print the tool names in chunks
544
+ chunk_size = 4
545
+ for i in range(0, len(active_tool_names), chunk_size):
546
+ chunk = active_tool_names[i : i + chunk_size]
547
+ result_str += " " + ", ".join(chunk) + "\n"
548
+
549
+ # Available but not active tools
550
+ all_tool_names = sorted([tool.get_name_from_cls() for tool in self._all_tools.values()])
551
+ inactive_tool_names = [tool for tool in all_tool_names if tool not in active_tool_names]
552
+ if inactive_tool_names:
553
+ result_str += "Available but not active tools:\n"
554
+ for i in range(0, len(inactive_tool_names), chunk_size):
555
+ chunk = inactive_tool_names[i : i + chunk_size]
556
+ result_str += " " + ", ".join(chunk) + "\n"
557
+
558
+ return result_str
559
+
560
+ def is_language_server_running(self) -> bool:
561
+ return self.language_server is not None and self.language_server.is_running()
562
+
563
+ def reset_language_server(self) -> None:
564
+ """
565
+ Starts/resets the language server for the current project
566
+ """
567
+ tool_timeout = self.serena_config.tool_timeout
568
+ if tool_timeout is None or tool_timeout < 0:
569
+ ls_timeout = None
570
+ else:
571
+ if tool_timeout < 10:
572
+ raise ValueError(f"Tool timeout must be at least 10 seconds, but is {tool_timeout} seconds")
573
+ ls_timeout = tool_timeout - 5 # the LS timeout is for a single call, it should be smaller than the tool timeout
574
+
575
+ # stop the language server if it is running
576
+ if self.is_language_server_running():
577
+ assert self.language_server is not None
578
+ log.info(f"Stopping the current language server at {self.language_server.repository_root_path} ...")
579
+ self.language_server.stop()
580
+ self.language_server = None
581
+
582
+ # instantiate and start the language server
583
+ assert self._active_project is not None
584
+ self.language_server = self._active_project.create_language_server(
585
+ log_level=self.serena_config.log_level,
586
+ ls_timeout=ls_timeout,
587
+ trace_lsp_communication=self.serena_config.trace_lsp_communication,
588
+ )
589
+ log.info(f"Starting the language server for {self._active_project.project_name}")
590
+ self.language_server.start()
591
+ if not self.language_server.is_running():
592
+ raise RuntimeError(
593
+ f"Failed to start the language server for {self._active_project.project_name} at {self._active_project.project_root}"
594
+ )
595
+
596
+ def get_tool(self, tool_class: type[TTool]) -> TTool:
597
+ return self._all_tools[tool_class] # type: ignore
598
+
599
+ def print_tool_overview(self) -> None:
600
+ ToolRegistry().print_tool_overview(self._active_tools.values())
601
+
602
+ def mark_file_modified(self, relative_path: str) -> None:
603
+ assert self.lines_read is not None
604
+ self.lines_read.invalidate_lines_read(relative_path)
605
+
606
+ def __del__(self) -> None:
607
+ """
608
+ Destructor to clean up the language server instance and GUI logger
609
+ """
610
+ if not hasattr(self, "_is_initialized"):
611
+ return
612
+ log.info("SerenaAgent is shutting down ...")
613
+ if self.is_language_server_running():
614
+ log.info("Stopping the language server ...")
615
+ assert self.language_server is not None
616
+ self.language_server.save_cache()
617
+ self.language_server.stop()
618
+ if self._gui_log_viewer:
619
+ log.info("Stopping the GUI log window ...")
620
+ self._gui_log_viewer.stop()
621
+
622
+ def get_tool_by_name(self, tool_name: str) -> Tool:
623
+ tool_class = ToolRegistry().get_tool_class_by_name(tool_name)
624
+ return self.get_tool(tool_class)
projects/ui/serena-new/src/serena/agno.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import threading
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ from agno.agent import Agent
9
+ from agno.memory import AgentMemory
10
+ from agno.models.base import Model
11
+ from agno.storage.sqlite import SqliteStorage
12
+ from agno.tools.function import Function
13
+ from agno.tools.toolkit import Toolkit
14
+ from dotenv import load_dotenv
15
+ from sensai.util.logging import LogTime
16
+
17
+ from serena.agent import SerenaAgent, Tool
18
+ from serena.config.context_mode import SerenaAgentContext
19
+ from serena.constants import REPO_ROOT
20
+ from serena.util.exception import show_fatal_exception_safe
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+
25
+ class SerenaAgnoToolkit(Toolkit):
26
+ def __init__(self, serena_agent: SerenaAgent):
27
+ super().__init__("Serena")
28
+ for tool in serena_agent.get_exposed_tool_instances():
29
+ self.functions[tool.get_name_from_cls()] = self._create_agno_function(tool)
30
+ log.info("Agno agent functions: %s", list(self.functions.keys()))
31
+
32
+ @staticmethod
33
+ def _create_agno_function(tool: Tool) -> Function:
34
+ def entrypoint(**kwargs: Any) -> str:
35
+ if "kwargs" in kwargs:
36
+ # Agno sometimes passes a kwargs argument explicitly, so we merge it
37
+ kwargs.update(kwargs["kwargs"])
38
+ del kwargs["kwargs"]
39
+ log.info(f"Calling tool {tool}")
40
+ return tool.apply_ex(log_call=True, catch_exceptions=True, **kwargs)
41
+
42
+ function = Function.from_callable(tool.get_apply_fn())
43
+ function.name = tool.get_name_from_cls()
44
+ function.entrypoint = entrypoint
45
+ function.skip_entrypoint_processing = True
46
+ return function
47
+
48
+
49
+ class SerenaAgnoAgentProvider:
50
+ _agent: Agent | None = None
51
+ _lock = threading.Lock()
52
+
53
+ @classmethod
54
+ def get_agent(cls, model: Model) -> Agent:
55
+ """
56
+ Returns the singleton instance of the Serena agent or creates it with the given parameters if it doesn't exist.
57
+
58
+ NOTE: This is very ugly with poor separation of concerns, but the way in which the Agno UI works (reloading the
59
+ module that defines the `app` variable) essentially forces us to do something like this.
60
+
61
+ :param model: the large language model to use for the agent
62
+ :return: the agent instance
63
+ """
64
+ with cls._lock:
65
+ if cls._agent is not None:
66
+ return cls._agent
67
+
68
+ # change to Serena root
69
+ os.chdir(REPO_ROOT)
70
+
71
+ load_dotenv()
72
+
73
+ parser = argparse.ArgumentParser(description="Serena coding assistant")
74
+
75
+ # Create a mutually exclusive group
76
+ group = parser.add_mutually_exclusive_group()
77
+
78
+ # Add arguments to the group, both pointing to the same destination
79
+ group.add_argument(
80
+ "--project-file",
81
+ required=False,
82
+ help="Path to the project (or project.yml file).",
83
+ )
84
+ group.add_argument(
85
+ "--project",
86
+ required=False,
87
+ help="Path to the project (or project.yml file).",
88
+ )
89
+ args = parser.parse_args()
90
+
91
+ args_project_file = args.project or args.project_file
92
+
93
+ if args_project_file:
94
+ project_file = Path(args_project_file).resolve()
95
+ # If project file path is relative, make it absolute by joining with project root
96
+ if not project_file.is_absolute():
97
+ # Get the project root directory (parent of scripts directory)
98
+ project_root = Path(REPO_ROOT)
99
+ project_file = project_root / args_project_file
100
+
101
+ # Ensure the path is normalized and absolute
102
+ project_file = str(project_file.resolve())
103
+ else:
104
+ project_file = None
105
+
106
+ with LogTime("Loading Serena agent"):
107
+ try:
108
+ serena_agent = SerenaAgent(project_file, context=SerenaAgentContext.load("agent"))
109
+ except Exception as e:
110
+ show_fatal_exception_safe(e)
111
+ raise
112
+
113
+ # Even though we don't want to keep history between sessions,
114
+ # for agno-ui to work as a conversation, we use a persistent storage on disk.
115
+ # This storage should be deleted between sessions.
116
+ # Note that this might collide with custom options for the agent, like adding vector-search based tools.
117
+ # See here for an explanation: https://www.reddit.com/r/agno/comments/1jk6qea/regarding_the_built_in_memory/
118
+ sql_db_path = (Path("temp") / "agno_agent_storage.db").absolute()
119
+ sql_db_path.parent.mkdir(exist_ok=True)
120
+ # delete the db file if it exists
121
+ log.info(f"Deleting DB from PID {os.getpid()}")
122
+ if sql_db_path.exists():
123
+ sql_db_path.unlink()
124
+
125
+ agno_agent = Agent(
126
+ name="Serena",
127
+ model=model,
128
+ # See explanation above on why storage is needed
129
+ storage=SqliteStorage(table_name="serena_agent_sessions", db_file=str(sql_db_path)),
130
+ description="A fully-featured coding assistant",
131
+ tools=[SerenaAgnoToolkit(serena_agent)],
132
+ # The tool calls will be shown in the UI anyway since whether to show them is configurable per tool
133
+ # To see detailed logs, you should use the serena logger (configure it in the project file path)
134
+ show_tool_calls=False,
135
+ markdown=True,
136
+ system_message=serena_agent.create_system_prompt(),
137
+ telemetry=False,
138
+ memory=AgentMemory(),
139
+ add_history_to_messages=True,
140
+ num_history_responses=100, # you might want to adjust this (expense vs. history awareness)
141
+ )
142
+ cls._agent = agno_agent
143
+ log.info(f"Agent instantiated: {agno_agent}")
144
+
145
+ return agno_agent
projects/ui/serena-new/src/serena/analytics.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import logging
4
+ import threading
5
+ from abc import ABC, abstractmethod
6
+ from collections import defaultdict
7
+ from copy import copy
8
+ from dataclasses import asdict, dataclass
9
+ from enum import Enum
10
+
11
+ from anthropic.types import MessageParam, MessageTokensCount
12
+ from dotenv import load_dotenv
13
+
14
+ log = logging.getLogger(__name__)
15
+
16
+
17
+ class TokenCountEstimator(ABC):
18
+ @abstractmethod
19
+ def estimate_token_count(self, text: str) -> int:
20
+ """
21
+ Estimate the number of tokens in the given text.
22
+ This is an abstract method that should be implemented by subclasses.
23
+ """
24
+
25
+
26
+ class TiktokenCountEstimator(TokenCountEstimator):
27
+ """
28
+ Approximate token count using tiktoken.
29
+ """
30
+
31
+ def __init__(self, model_name: str = "gpt-4o"):
32
+ """
33
+ The tokenizer will be downloaded on the first initialization, which may take some time.
34
+
35
+ :param model_name: see `tiktoken.model` to see available models.
36
+ """
37
+ import tiktoken
38
+
39
+ log.info(f"Loading tiktoken encoding for model {model_name}, this may take a while on the first run.")
40
+ self._encoding = tiktoken.encoding_for_model(model_name)
41
+
42
+ def estimate_token_count(self, text: str) -> int:
43
+ return len(self._encoding.encode(text))
44
+
45
+
46
+ class AnthropicTokenCount(TokenCountEstimator):
47
+ """
48
+ The exact count using the Anthropic API.
49
+ Counting is free, but has a rate limit and will require an API key,
50
+ (typically, set through an env variable).
51
+ See https://docs.anthropic.com/en/docs/build-with-claude/token-counting
52
+ """
53
+
54
+ def __init__(self, model_name: str = "claude-sonnet-4-20250514", api_key: str | None = None):
55
+ import anthropic
56
+
57
+ self._model_name = model_name
58
+ if api_key is None:
59
+ load_dotenv()
60
+ self._anthropic_client = anthropic.Anthropic(api_key=api_key)
61
+
62
+ def _send_count_tokens_request(self, text: str) -> MessageTokensCount:
63
+ return self._anthropic_client.messages.count_tokens(
64
+ model=self._model_name,
65
+ messages=[MessageParam(role="user", content=text)],
66
+ )
67
+
68
+ def estimate_token_count(self, text: str) -> int:
69
+ return self._send_count_tokens_request(text).input_tokens
70
+
71
+
72
+ _registered_token_estimator_instances_cache: dict[RegisteredTokenCountEstimator, TokenCountEstimator] = {}
73
+
74
+
75
+ class RegisteredTokenCountEstimator(Enum):
76
+ TIKTOKEN_GPT4O = "TIKTOKEN_GPT4O"
77
+ ANTHROPIC_CLAUDE_SONNET_4 = "ANTHROPIC_CLAUDE_SONNET_4"
78
+
79
+ @classmethod
80
+ def get_valid_names(cls) -> list[str]:
81
+ """
82
+ Get a list of all registered token count estimator names.
83
+ """
84
+ return [estimator.name for estimator in cls]
85
+
86
+ def _create_estimator(self) -> TokenCountEstimator:
87
+ match self:
88
+ case RegisteredTokenCountEstimator.TIKTOKEN_GPT4O:
89
+ return TiktokenCountEstimator(model_name="gpt-4o")
90
+ case RegisteredTokenCountEstimator.ANTHROPIC_CLAUDE_SONNET_4:
91
+ return AnthropicTokenCount(model_name="claude-sonnet-4-20250514")
92
+ case _:
93
+ raise ValueError(f"Unknown token count estimator: {self.value}")
94
+
95
+ def load_estimator(self) -> TokenCountEstimator:
96
+ estimator_instance = _registered_token_estimator_instances_cache.get(self)
97
+ if estimator_instance is None:
98
+ estimator_instance = self._create_estimator()
99
+ _registered_token_estimator_instances_cache[self] = estimator_instance
100
+ return estimator_instance
101
+
102
+
103
+ class ToolUsageStats:
104
+ """
105
+ A class to record and manage tool usage statistics.
106
+ """
107
+
108
+ def __init__(self, token_count_estimator: RegisteredTokenCountEstimator = RegisteredTokenCountEstimator.TIKTOKEN_GPT4O):
109
+ self._token_count_estimator = token_count_estimator.load_estimator()
110
+ self._token_estimator_name = token_count_estimator.value
111
+ self._tool_stats: dict[str, ToolUsageStats.Entry] = defaultdict(ToolUsageStats.Entry)
112
+ self._tool_stats_lock = threading.Lock()
113
+
114
+ @property
115
+ def token_estimator_name(self) -> str:
116
+ """
117
+ Get the name of the registered token count estimator used.
118
+ """
119
+ return self._token_estimator_name
120
+
121
+ @dataclass(kw_only=True)
122
+ class Entry:
123
+ num_times_called: int = 0
124
+ input_tokens: int = 0
125
+ output_tokens: int = 0
126
+
127
+ def update_on_call(self, input_tokens: int, output_tokens: int) -> None:
128
+ """
129
+ Update the entry with the number of tokens used for a single call.
130
+ """
131
+ self.num_times_called += 1
132
+ self.input_tokens += input_tokens
133
+ self.output_tokens += output_tokens
134
+
135
+ def _estimate_token_count(self, text: str) -> int:
136
+ return self._token_count_estimator.estimate_token_count(text)
137
+
138
+ def get_stats(self, tool_name: str) -> ToolUsageStats.Entry:
139
+ """
140
+ Get (a copy of) the current usage statistics for a specific tool.
141
+ """
142
+ with self._tool_stats_lock:
143
+ return copy(self._tool_stats[tool_name])
144
+
145
+ def record_tool_usage(self, tool_name: str, input_str: str, output_str: str) -> None:
146
+ input_tokens = self._estimate_token_count(input_str)
147
+ output_tokens = self._estimate_token_count(output_str)
148
+ with self._tool_stats_lock:
149
+ entry = self._tool_stats[tool_name]
150
+ entry.update_on_call(input_tokens, output_tokens)
151
+
152
+ def get_tool_stats_dict(self) -> dict[str, dict[str, int]]:
153
+ with self._tool_stats_lock:
154
+ return {name: asdict(entry) for name, entry in self._tool_stats.items()}
155
+
156
+ def clear(self) -> None:
157
+ with self._tool_stats_lock:
158
+ self._tool_stats.clear()
projects/ui/serena-new/src/serena/cli.py ADDED
@@ -0,0 +1,831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import glob
2
+ import json
3
+ import os
4
+ import shutil
5
+ import subprocess
6
+ import sys
7
+ from logging import Logger
8
+ from pathlib import Path
9
+ from typing import Any, Literal
10
+
11
+ import click
12
+ from sensai.util import logging
13
+ from sensai.util.logging import FileLoggerContext, datetime_tag
14
+ from tqdm import tqdm
15
+
16
+ from serena.agent import SerenaAgent
17
+ from serena.config.context_mode import SerenaAgentContext, SerenaAgentMode
18
+ from serena.config.serena_config import ProjectConfig, SerenaConfig, SerenaPaths
19
+ from serena.constants import (
20
+ DEFAULT_CONTEXT,
21
+ DEFAULT_MODES,
22
+ PROMPT_TEMPLATES_DIR_IN_USER_HOME,
23
+ PROMPT_TEMPLATES_DIR_INTERNAL,
24
+ SERENA_LOG_FORMAT,
25
+ SERENA_MANAGED_DIR_IN_HOME,
26
+ SERENAS_OWN_CONTEXT_YAMLS_DIR,
27
+ SERENAS_OWN_MODE_YAMLS_DIR,
28
+ USER_CONTEXT_YAMLS_DIR,
29
+ USER_MODE_YAMLS_DIR,
30
+ )
31
+ from serena.mcp import SerenaMCPFactory, SerenaMCPFactorySingleProcess
32
+ from serena.project import Project
33
+ from serena.tools import FindReferencingSymbolsTool, FindSymbolTool, GetSymbolsOverviewTool, SearchForPatternTool, ToolRegistry
34
+ from serena.util.logging import MemoryLogHandler
35
+ from solidlsp.ls_config import Language
36
+ from solidlsp.util.subprocess_util import subprocess_kwargs
37
+
38
+ log = logging.getLogger(__name__)
39
+
40
+ # --------------------- Utilities -------------------------------------
41
+
42
+
43
+ def _open_in_editor(path: str) -> None:
44
+ """Open the given file in the system's default editor or viewer."""
45
+ editor = os.environ.get("EDITOR")
46
+ run_kwargs = subprocess_kwargs()
47
+ try:
48
+ if editor:
49
+ subprocess.run([editor, path], check=False, **run_kwargs)
50
+ elif sys.platform.startswith("win"):
51
+ try:
52
+ os.startfile(path)
53
+ except OSError:
54
+ subprocess.run(["notepad.exe", path], check=False, **run_kwargs)
55
+ elif sys.platform == "darwin":
56
+ subprocess.run(["open", path], check=False, **run_kwargs)
57
+ else:
58
+ subprocess.run(["xdg-open", path], check=False, **run_kwargs)
59
+ except Exception as e:
60
+ print(f"Failed to open {path}: {e}")
61
+
62
+
63
+ class ProjectType(click.ParamType):
64
+ """ParamType allowing either a project name or a path to a project directory."""
65
+
66
+ name = "[PROJECT_NAME|PROJECT_PATH]"
67
+
68
+ def convert(self, value: str, param: Any, ctx: Any) -> str:
69
+ path = Path(value).resolve()
70
+ if path.exists() and path.is_dir():
71
+ return str(path)
72
+ return value
73
+
74
+
75
+ PROJECT_TYPE = ProjectType()
76
+
77
+
78
+ class AutoRegisteringGroup(click.Group):
79
+ """
80
+ A click.Group subclass that automatically registers any click.Command
81
+ attributes defined on the class into the group.
82
+
83
+ After initialization, it inspects its own class for attributes that are
84
+ instances of click.Command (typically created via @click.command) and
85
+ calls self.add_command(cmd) on each. This lets you define your commands
86
+ as static methods on the subclass for IDE-friendly organization without
87
+ manual registration.
88
+ """
89
+
90
+ def __init__(self, name: str, help: str):
91
+ super().__init__(name=name, help=help)
92
+ # Scan class attributes for click.Command instances and register them.
93
+ for attr in dir(self.__class__):
94
+ cmd = getattr(self.__class__, attr)
95
+ if isinstance(cmd, click.Command):
96
+ self.add_command(cmd)
97
+
98
+
99
+ class TopLevelCommands(AutoRegisteringGroup):
100
+ """Root CLI group containing the core Serena commands."""
101
+
102
+ def __init__(self) -> None:
103
+ super().__init__(name="serena", help="Serena CLI commands. You can run `<command> --help` for more info on each command.")
104
+
105
+ @staticmethod
106
+ @click.command("start-mcp-server", help="Starts the Serena MCP server.")
107
+ @click.option("--project", "project", type=PROJECT_TYPE, default=None, help="Path or name of project to activate at startup.")
108
+ @click.option("--project-file", "project", type=PROJECT_TYPE, default=None, help="[DEPRECATED] Use --project instead.")
109
+ @click.argument("project_file_arg", type=PROJECT_TYPE, required=False, default=None, metavar="")
110
+ @click.option(
111
+ "--context", type=str, default=DEFAULT_CONTEXT, show_default=True, help="Built-in context name or path to custom context YAML."
112
+ )
113
+ @click.option(
114
+ "--mode",
115
+ "modes",
116
+ type=str,
117
+ multiple=True,
118
+ default=DEFAULT_MODES,
119
+ show_default=True,
120
+ help="Built-in mode names or paths to custom mode YAMLs.",
121
+ )
122
+ @click.option("--transport", type=click.Choice(["stdio", "sse"]), default="stdio", show_default=True, help="Transport protocol.")
123
+ @click.option("--host", type=str, default="0.0.0.0", show_default=True)
124
+ @click.option("--port", type=int, default=8000, show_default=True)
125
+ @click.option("--enable-web-dashboard", type=bool, is_flag=False, default=None, help="Override dashboard setting in config.")
126
+ @click.option("--enable-gui-log-window", type=bool, is_flag=False, default=None, help="Override GUI log window setting in config.")
127
+ @click.option(
128
+ "--log-level",
129
+ type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
130
+ default=None,
131
+ help="Override log level in config.",
132
+ )
133
+ @click.option("--trace-lsp-communication", type=bool, is_flag=False, default=None, help="Whether to trace LSP communication.")
134
+ @click.option("--tool-timeout", type=float, default=None, help="Override tool execution timeout in config.")
135
+ def start_mcp_server(
136
+ project: str | None,
137
+ project_file_arg: str | None,
138
+ context: str,
139
+ modes: tuple[str, ...],
140
+ transport: Literal["stdio", "sse"],
141
+ host: str,
142
+ port: int,
143
+ enable_web_dashboard: bool | None,
144
+ enable_gui_log_window: bool | None,
145
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] | None,
146
+ trace_lsp_communication: bool | None,
147
+ tool_timeout: float | None,
148
+ ) -> None:
149
+ # initialize logging, using INFO level initially (will later be adjusted by SerenaAgent according to the config)
150
+ # * memory log handler (for use by GUI/Dashboard)
151
+ # * stream handler for stderr (for direct console output, which will also be captured by clients like Claude Desktop)
152
+ # * file handler
153
+ # (Note that stdout must never be used for logging, as it is used by the MCP server to communicate with the client.)
154
+ Logger.root.setLevel(logging.INFO)
155
+ formatter = logging.Formatter(SERENA_LOG_FORMAT)
156
+ memory_log_handler = MemoryLogHandler()
157
+ Logger.root.addHandler(memory_log_handler)
158
+ stderr_handler = logging.StreamHandler(stream=sys.stderr)
159
+ stderr_handler.formatter = formatter
160
+ Logger.root.addHandler(stderr_handler)
161
+ log_path = SerenaPaths().get_next_log_file_path("mcp")
162
+ file_handler = logging.FileHandler(log_path, mode="w")
163
+ file_handler.formatter = formatter
164
+ Logger.root.addHandler(file_handler)
165
+
166
+ log.info("Initializing Serena MCP server")
167
+ log.info("Storing logs in %s", log_path)
168
+ project_file = project_file_arg or project
169
+ factory = SerenaMCPFactorySingleProcess(context=context, project=project_file, memory_log_handler=memory_log_handler)
170
+ server = factory.create_mcp_server(
171
+ host=host,
172
+ port=port,
173
+ modes=modes,
174
+ enable_web_dashboard=enable_web_dashboard,
175
+ enable_gui_log_window=enable_gui_log_window,
176
+ log_level=log_level,
177
+ trace_lsp_communication=trace_lsp_communication,
178
+ tool_timeout=tool_timeout,
179
+ )
180
+ if project_file_arg:
181
+ log.warning(
182
+ "Positional project arg is deprecated; use --project instead. Used: %s",
183
+ project_file,
184
+ )
185
+ log.info("Starting MCP server …")
186
+ server.run(transport=transport)
187
+
188
+ @staticmethod
189
+ @click.command("print-system-prompt", help="Print the system prompt for a project.")
190
+ @click.argument("project", type=click.Path(exists=True), default=os.getcwd(), required=False)
191
+ @click.option(
192
+ "--log-level",
193
+ type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
194
+ default="WARNING",
195
+ help="Log level for prompt generation.",
196
+ )
197
+ @click.option("--only-instructions", is_flag=True, help="Print only the initial instructions, without prefix/postfix.")
198
+ @click.option(
199
+ "--context", type=str, default=DEFAULT_CONTEXT, show_default=True, help="Built-in context name or path to custom context YAML."
200
+ )
201
+ @click.option(
202
+ "--mode",
203
+ "modes",
204
+ type=str,
205
+ multiple=True,
206
+ default=DEFAULT_MODES,
207
+ show_default=True,
208
+ help="Built-in mode names or paths to custom mode YAMLs.",
209
+ )
210
+ def print_system_prompt(project: str, log_level: str, only_instructions: bool, context: str, modes: tuple[str, ...]) -> None:
211
+ prefix = "You will receive access to Serena's symbolic tools. Below are instructions for using them, take them into account."
212
+ postfix = "You begin by acknowledging that you understood the above instructions and are ready to receive tasks."
213
+ from serena.tools.workflow_tools import InitialInstructionsTool
214
+
215
+ lvl = logging.getLevelNamesMapping()[log_level.upper()]
216
+ logging.configure(level=lvl)
217
+ context_instance = SerenaAgentContext.load(context)
218
+ mode_instances = [SerenaAgentMode.load(mode) for mode in modes]
219
+ agent = SerenaAgent(
220
+ project=os.path.abspath(project),
221
+ serena_config=SerenaConfig(web_dashboard=False, log_level=lvl),
222
+ context=context_instance,
223
+ modes=mode_instances,
224
+ )
225
+ tool = agent.get_tool(InitialInstructionsTool)
226
+ instr = tool.apply()
227
+ if only_instructions:
228
+ print(instr)
229
+ else:
230
+ print(f"{prefix}\n{instr}\n{postfix}")
231
+
232
+
233
+ class ModeCommands(AutoRegisteringGroup):
234
+ """Group for 'mode' subcommands."""
235
+
236
+ def __init__(self) -> None:
237
+ super().__init__(name="mode", help="Manage Serena modes. You can run `mode <command> --help` for more info on each command.")
238
+
239
+ @staticmethod
240
+ @click.command("list", help="List available modes.")
241
+ def list() -> None:
242
+ mode_names = SerenaAgentMode.list_registered_mode_names()
243
+ max_len_name = max(len(name) for name in mode_names) if mode_names else 20
244
+ for name in mode_names:
245
+ mode_yml_path = SerenaAgentMode.get_path(name)
246
+ is_internal = Path(mode_yml_path).is_relative_to(SERENAS_OWN_MODE_YAMLS_DIR)
247
+ descriptor = "(internal)" if is_internal else f"(at {mode_yml_path})"
248
+ name_descr_string = f"{name:<{max_len_name + 4}}{descriptor}"
249
+ click.echo(name_descr_string)
250
+
251
+ @staticmethod
252
+ @click.command("create", help="Create a new mode or copy an internal one.")
253
+ @click.option(
254
+ "--name",
255
+ "-n",
256
+ type=str,
257
+ default=None,
258
+ help="Name for the new mode. If --from-internal is passed may be left empty to create a mode of the same name, which will then override the internal mode.",
259
+ )
260
+ @click.option("--from-internal", "from_internal", type=str, default=None, help="Copy from an internal mode.")
261
+ def create(name: str, from_internal: str) -> None:
262
+ if not (name or from_internal):
263
+ raise click.UsageError("Provide at least one of --name or --from-internal.")
264
+ mode_name = name or from_internal
265
+ dest = os.path.join(USER_MODE_YAMLS_DIR, f"{mode_name}.yml")
266
+ src = (
267
+ os.path.join(SERENAS_OWN_MODE_YAMLS_DIR, f"{from_internal}.yml")
268
+ if from_internal
269
+ else os.path.join(SERENAS_OWN_MODE_YAMLS_DIR, "mode.template.yml")
270
+ )
271
+ if not os.path.exists(src):
272
+ raise FileNotFoundError(
273
+ f"Internal mode '{from_internal}' not found in {SERENAS_OWN_MODE_YAMLS_DIR}. Available modes: {SerenaAgentMode.list_registered_mode_names()}"
274
+ )
275
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
276
+ shutil.copyfile(src, dest)
277
+ click.echo(f"Created mode '{mode_name}' at {dest}")
278
+ _open_in_editor(dest)
279
+
280
+ @staticmethod
281
+ @click.command("edit", help="Edit a custom mode YAML file.")
282
+ @click.argument("mode_name")
283
+ def edit(mode_name: str) -> None:
284
+ path = os.path.join(USER_MODE_YAMLS_DIR, f"{mode_name}.yml")
285
+ if not os.path.exists(path):
286
+ if mode_name in SerenaAgentMode.list_registered_mode_names(include_user_modes=False):
287
+ click.echo(
288
+ f"Mode '{mode_name}' is an internal mode and cannot be edited directly. "
289
+ f"Use 'mode create --from-internal {mode_name}' to create a custom mode that overrides it before editing."
290
+ )
291
+ else:
292
+ click.echo(f"Custom mode '{mode_name}' not found. Create it with: mode create --name {mode_name}.")
293
+ return
294
+ _open_in_editor(path)
295
+
296
+ @staticmethod
297
+ @click.command("delete", help="Delete a custom mode file.")
298
+ @click.argument("mode_name")
299
+ def delete(mode_name: str) -> None:
300
+ path = os.path.join(USER_MODE_YAMLS_DIR, f"{mode_name}.yml")
301
+ if not os.path.exists(path):
302
+ click.echo(f"Custom mode '{mode_name}' not found.")
303
+ return
304
+ os.remove(path)
305
+ click.echo(f"Deleted custom mode '{mode_name}'.")
306
+
307
+
308
+ class ContextCommands(AutoRegisteringGroup):
309
+ """Group for 'context' subcommands."""
310
+
311
+ def __init__(self) -> None:
312
+ super().__init__(
313
+ name="context", help="Manage Serena contexts. You can run `context <command> --help` for more info on each command."
314
+ )
315
+
316
+ @staticmethod
317
+ @click.command("list", help="List available contexts.")
318
+ def list() -> None:
319
+ context_names = SerenaAgentContext.list_registered_context_names()
320
+ max_len_name = max(len(name) for name in context_names) if context_names else 20
321
+ for name in context_names:
322
+ context_yml_path = SerenaAgentContext.get_path(name)
323
+ is_internal = Path(context_yml_path).is_relative_to(SERENAS_OWN_CONTEXT_YAMLS_DIR)
324
+ descriptor = "(internal)" if is_internal else f"(at {context_yml_path})"
325
+ name_descr_string = f"{name:<{max_len_name + 4}}{descriptor}"
326
+ click.echo(name_descr_string)
327
+
328
+ @staticmethod
329
+ @click.command("create", help="Create a new context or copy an internal one.")
330
+ @click.option(
331
+ "--name",
332
+ "-n",
333
+ type=str,
334
+ default=None,
335
+ help="Name for the new context. If --from-internal is passed may be left empty to create a context of the same name, which will then override the internal context",
336
+ )
337
+ @click.option("--from-internal", "from_internal", type=str, default=None, help="Copy from an internal context.")
338
+ def create(name: str, from_internal: str) -> None:
339
+ if not (name or from_internal):
340
+ raise click.UsageError("Provide at least one of --name or --from-internal.")
341
+ ctx_name = name or from_internal
342
+ dest = os.path.join(USER_CONTEXT_YAMLS_DIR, f"{ctx_name}.yml")
343
+ src = (
344
+ os.path.join(SERENAS_OWN_CONTEXT_YAMLS_DIR, f"{from_internal}.yml")
345
+ if from_internal
346
+ else os.path.join(SERENAS_OWN_CONTEXT_YAMLS_DIR, "context.template.yml")
347
+ )
348
+ if not os.path.exists(src):
349
+ raise FileNotFoundError(
350
+ f"Internal context '{from_internal}' not found in {SERENAS_OWN_CONTEXT_YAMLS_DIR}. Available contexts: {SerenaAgentContext.list_registered_context_names()}"
351
+ )
352
+ os.makedirs(os.path.dirname(dest), exist_ok=True)
353
+ shutil.copyfile(src, dest)
354
+ click.echo(f"Created context '{ctx_name}' at {dest}")
355
+ _open_in_editor(dest)
356
+
357
+ @staticmethod
358
+ @click.command("edit", help="Edit a custom context YAML file.")
359
+ @click.argument("context_name")
360
+ def edit(context_name: str) -> None:
361
+ path = os.path.join(USER_CONTEXT_YAMLS_DIR, f"{context_name}.yml")
362
+ if not os.path.exists(path):
363
+ if context_name in SerenaAgentContext.list_registered_context_names(include_user_contexts=False):
364
+ click.echo(
365
+ f"Context '{context_name}' is an internal context and cannot be edited directly. "
366
+ f"Use 'context create --from-internal {context_name}' to create a custom context that overrides it before editing."
367
+ )
368
+ else:
369
+ click.echo(f"Custom context '{context_name}' not found. Create it with: context create --name {context_name}.")
370
+ return
371
+ _open_in_editor(path)
372
+
373
+ @staticmethod
374
+ @click.command("delete", help="Delete a custom context file.")
375
+ @click.argument("context_name")
376
+ def delete(context_name: str) -> None:
377
+ path = os.path.join(USER_CONTEXT_YAMLS_DIR, f"{context_name}.yml")
378
+ if not os.path.exists(path):
379
+ click.echo(f"Custom context '{context_name}' not found.")
380
+ return
381
+ os.remove(path)
382
+ click.echo(f"Deleted custom context '{context_name}'.")
383
+
384
+
385
+ class SerenaConfigCommands(AutoRegisteringGroup):
386
+ """Group for 'config' subcommands."""
387
+
388
+ def __init__(self) -> None:
389
+ super().__init__(name="config", help="Manage Serena configuration.")
390
+
391
+ @staticmethod
392
+ @click.command(
393
+ "edit", help="Edit serena_config.yml in your default editor. Will create a config file from the template if no config is found."
394
+ )
395
+ def edit() -> None:
396
+ config_path = os.path.join(SERENA_MANAGED_DIR_IN_HOME, "serena_config.yml")
397
+ if not os.path.exists(config_path):
398
+ SerenaConfig.generate_config_file(config_path)
399
+ _open_in_editor(config_path)
400
+
401
+
402
+ class ProjectCommands(AutoRegisteringGroup):
403
+ """Group for 'project' subcommands."""
404
+
405
+ def __init__(self) -> None:
406
+ super().__init__(
407
+ name="project", help="Manage Serena projects. You can run `project <command> --help` for more info on each command."
408
+ )
409
+
410
+ @staticmethod
411
+ @click.command("generate-yml", help="Generate a project.yml file.")
412
+ @click.argument("project_path", type=click.Path(exists=True, file_okay=False), default=os.getcwd())
413
+ @click.option("--language", type=str, default=None, help="Programming language; inferred if not specified.")
414
+ def generate_yml(project_path: str, language: str | None = None) -> None:
415
+ yml_path = os.path.join(project_path, ProjectConfig.rel_path_to_project_yml())
416
+ if os.path.exists(yml_path):
417
+ raise FileExistsError(f"Project file {yml_path} already exists.")
418
+ lang_inst = None
419
+ if language:
420
+ try:
421
+ lang_inst = Language[language.upper()]
422
+ except KeyError:
423
+ all_langs = [l.name.lower() for l in Language.iter_all(include_experimental=True)]
424
+ raise ValueError(f"Unknown language '{language}'. Supported: {all_langs}")
425
+ generated_conf = ProjectConfig.autogenerate(project_root=project_path, project_language=lang_inst)
426
+ print(f"Generated project.yml with language {generated_conf.language.value} at {yml_path}.")
427
+
428
+ @staticmethod
429
+ @click.command("index", help="Index a project by saving symbols to the LSP cache.")
430
+ @click.argument("project", type=click.Path(exists=True), default=os.getcwd(), required=False)
431
+ @click.option(
432
+ "--log-level",
433
+ type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]),
434
+ default="WARNING",
435
+ help="Log level for indexing.",
436
+ )
437
+ @click.option("--timeout", type=float, default=10, help="Timeout for indexing a single file.")
438
+ def index(project: str, log_level: str, timeout: float) -> None:
439
+ ProjectCommands._index_project(project, log_level, timeout=timeout)
440
+
441
+ @staticmethod
442
+ @click.command("index-deprecated", help="Deprecated alias for 'serena project index'.")
443
+ @click.argument("project", type=click.Path(exists=True), default=os.getcwd(), required=False)
444
+ @click.option("--log-level", type=click.Choice(["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]), default="WARNING")
445
+ @click.option("--timeout", type=float, default=10, help="Timeout for indexing a single file.")
446
+ def index_deprecated(project: str, log_level: str, timeout: float) -> None:
447
+ click.echo("Deprecated! Use `serena project index` instead.")
448
+ ProjectCommands._index_project(project, log_level, timeout=timeout)
449
+
450
+ @staticmethod
451
+ def _index_project(project: str, log_level: str, timeout: float) -> None:
452
+ lvl = logging.getLevelNamesMapping()[log_level.upper()]
453
+ logging.configure(level=lvl)
454
+ proj = Project.load(os.path.abspath(project))
455
+ click.echo(f"Indexing symbols in project {project}…")
456
+ ls = proj.create_language_server(log_level=lvl, ls_timeout=timeout)
457
+ log_file = os.path.join(project, ".serena", "logs", "indexing.txt")
458
+
459
+ collected_exceptions: list[Exception] = []
460
+ files_failed = []
461
+ with ls.start_server():
462
+ files = proj.gather_source_files()
463
+ for i, f in enumerate(tqdm(files, desc="Indexing")):
464
+ try:
465
+ ls.request_document_symbols(f, include_body=False)
466
+ ls.request_document_symbols(f, include_body=True)
467
+ except Exception as e:
468
+ log.error(f"Failed to index {f}, continuing.")
469
+ collected_exceptions.append(e)
470
+ files_failed.append(f)
471
+ if (i + 1) % 10 == 0:
472
+ ls.save_cache()
473
+ ls.save_cache()
474
+ click.echo(f"Symbols saved to {ls.cache_path}")
475
+ if len(files_failed) > 0:
476
+ os.makedirs(os.path.dirname(log_file), exist_ok=True)
477
+ with open(log_file, "w") as f:
478
+ for file, exception in zip(files_failed, collected_exceptions, strict=True):
479
+ f.write(f"{file}\n")
480
+ f.write(f"{exception}\n")
481
+ click.echo(f"Failed to index {len(files_failed)} files, see:\n{log_file}")
482
+
483
+ @staticmethod
484
+ @click.command("is_ignored_path", help="Check if a path is ignored by the project configuration.")
485
+ @click.argument("path", type=click.Path(exists=False, file_okay=True, dir_okay=True))
486
+ @click.argument("project", type=click.Path(exists=True, file_okay=False, dir_okay=True), default=os.getcwd())
487
+ def is_ignored_path(path: str, project: str) -> None:
488
+ """
489
+ Check if a given path is ignored by the project configuration.
490
+
491
+ :param path: The path to check.
492
+ :param project: The path to the project directory, defaults to the current working directory.
493
+ """
494
+ proj = Project.load(os.path.abspath(project))
495
+ if os.path.isabs(path):
496
+ path = os.path.relpath(path, start=proj.project_root)
497
+ is_ignored = proj.is_ignored_path(path)
498
+ click.echo(f"Path '{path}' IS {'ignored' if is_ignored else 'IS NOT ignored'} by the project configuration.")
499
+
500
+ @staticmethod
501
+ @click.command("index-file", help="Index a single file by saving its symbols to the LSP cache.")
502
+ @click.argument("file", type=click.Path(exists=True, file_okay=True, dir_okay=False))
503
+ @click.argument("project", type=click.Path(exists=True, file_okay=False, dir_okay=True), default=os.getcwd())
504
+ @click.option("--verbose", "-v", is_flag=True, help="Print detailed information about the indexed symbols.")
505
+ def index_file(file: str, project: str, verbose: bool) -> None:
506
+ """
507
+ Index a single file by saving its symbols to the LSP cache, useful for debugging.
508
+ :param file: path to the file to index, must be inside the project directory.
509
+ :param project: path to the project directory, defaults to the current working directory.
510
+ :param verbose: if set, prints detailed information about the indexed symbols.
511
+ """
512
+ proj = Project.load(os.path.abspath(project))
513
+ if os.path.isabs(file):
514
+ file = os.path.relpath(file, start=proj.project_root)
515
+ if proj.is_ignored_path(file, ignore_non_source_files=True):
516
+ click.echo(f"'{file}' is ignored or declared as non-code file by the project configuration, won't index.")
517
+ exit(1)
518
+ ls = proj.create_language_server()
519
+ with ls.start_server():
520
+ symbols, _ = ls.request_document_symbols(file, include_body=False)
521
+ ls.request_document_symbols(file, include_body=True)
522
+ if verbose:
523
+ click.echo(f"Symbols in file '{file}':")
524
+ for symbol in symbols:
525
+ click.echo(f" - {symbol['name']} at line {symbol['selectionRange']['start']['line']} of kind {symbol['kind']}")
526
+ ls.save_cache()
527
+ click.echo(f"Successfully indexed file '{file}', {len(symbols)} symbols saved to {ls.cache_path}.")
528
+
529
+ @staticmethod
530
+ @click.command("health-check", help="Perform a comprehensive health check of the project's tools and language server.")
531
+ @click.argument("project", type=click.Path(exists=True, file_okay=False, dir_okay=True), default=os.getcwd())
532
+ def health_check(project: str) -> None:
533
+ """
534
+ Perform a comprehensive health check of the project's tools and language server.
535
+
536
+ :param project: path to the project directory, defaults to the current working directory.
537
+ """
538
+ # NOTE: completely written by Claude Code, only functionality was reviewed, not implementation
539
+ logging.configure(level=logging.INFO)
540
+ project_path = os.path.abspath(project)
541
+ proj = Project.load(project_path)
542
+
543
+ # Create log file with timestamp
544
+ timestamp = datetime_tag()
545
+ log_dir = os.path.join(project_path, ".serena", "logs", "health-checks")
546
+ os.makedirs(log_dir, exist_ok=True)
547
+ log_file = os.path.join(log_dir, f"health_check_{timestamp}.log")
548
+
549
+ with FileLoggerContext(log_file, append=False, enabled=True):
550
+ log.info("Starting health check for project: %s", project_path)
551
+
552
+ try:
553
+ # Create SerenaAgent with dashboard disabled
554
+ log.info("Creating SerenaAgent with disabled dashboard...")
555
+ config = SerenaConfig(gui_log_window_enabled=False, web_dashboard=False)
556
+ agent = SerenaAgent(project=project_path, serena_config=config)
557
+ log.info("SerenaAgent created successfully")
558
+
559
+ # Find first non-empty file that can be analyzed
560
+ log.info("Searching for analyzable files...")
561
+ files = proj.gather_source_files()
562
+ target_file = None
563
+
564
+ for file_path in files:
565
+ try:
566
+ full_path = os.path.join(project_path, file_path)
567
+ if os.path.getsize(full_path) > 0:
568
+ target_file = file_path
569
+ log.info("Found analyzable file: %s", target_file)
570
+ break
571
+ except (OSError, FileNotFoundError):
572
+ continue
573
+
574
+ if not target_file:
575
+ log.error("No analyzable files found in project")
576
+ click.echo("❌ Health check failed: No analyzable files found")
577
+ click.echo(f"Log saved to: {log_file}")
578
+ return
579
+
580
+ # Get tools from agent
581
+ overview_tool = agent.get_tool(GetSymbolsOverviewTool)
582
+ find_symbol_tool = agent.get_tool(FindSymbolTool)
583
+ find_refs_tool = agent.get_tool(FindReferencingSymbolsTool)
584
+ search_pattern_tool = agent.get_tool(SearchForPatternTool)
585
+
586
+ # Test 1: Get symbols overview
587
+ log.info("Testing GetSymbolsOverviewTool on file: %s", target_file)
588
+ overview_result = agent.execute_task(lambda: overview_tool.apply(target_file))
589
+ overview_data = json.loads(overview_result)
590
+ log.info("GetSymbolsOverviewTool returned %d symbols", len(overview_data))
591
+
592
+ if not overview_data:
593
+ log.error("No symbols found in file %s", target_file)
594
+ click.echo("❌ Health check failed: No symbols found in target file")
595
+ click.echo(f"Log saved to: {log_file}")
596
+ return
597
+
598
+ # Extract suitable symbol (prefer class or function over variables)
599
+ # LSP symbol kinds: 5=class, 12=function, 6=method, 9=constructor
600
+ preferred_kinds = [5, 12, 6, 9] # class, function, method, constructor
601
+
602
+ selected_symbol = None
603
+ for symbol in overview_data:
604
+ if symbol.get("kind") in preferred_kinds:
605
+ selected_symbol = symbol
606
+ break
607
+
608
+ # If no preferred symbol found, use first available
609
+ if not selected_symbol:
610
+ selected_symbol = overview_data[0]
611
+ log.info("No class or function found, using first available symbol")
612
+
613
+ symbol_name = selected_symbol.get("name_path", "unknown")
614
+ symbol_kind = selected_symbol.get("kind", "unknown")
615
+ log.info("Using symbol for testing: %s (kind: %d)", symbol_name, symbol_kind)
616
+
617
+ # Test 2: FindSymbolTool
618
+ log.info("Testing FindSymbolTool for symbol: %s", symbol_name)
619
+ find_symbol_result = agent.execute_task(
620
+ lambda: find_symbol_tool.apply(symbol_name, relative_path=target_file, include_body=True)
621
+ )
622
+ find_symbol_data = json.loads(find_symbol_result)
623
+ log.info("FindSymbolTool found %d matches for symbol %s", len(find_symbol_data), symbol_name)
624
+
625
+ # Test 3: FindReferencingSymbolsTool
626
+ log.info("Testing FindReferencingSymbolsTool for symbol: %s", symbol_name)
627
+ try:
628
+ find_refs_result = agent.execute_task(lambda: find_refs_tool.apply(symbol_name, relative_path=target_file))
629
+ find_refs_data = json.loads(find_refs_result)
630
+ log.info("FindReferencingSymbolsTool found %d references for symbol %s", len(find_refs_data), symbol_name)
631
+ except Exception as e:
632
+ log.warning("FindReferencingSymbolsTool failed for symbol %s: %s", symbol_name, str(e))
633
+ find_refs_data = []
634
+
635
+ # Test 4: SearchForPatternTool to verify references
636
+ log.info("Testing SearchForPatternTool for pattern: %s", symbol_name)
637
+ try:
638
+ search_result = agent.execute_task(
639
+ lambda: search_pattern_tool.apply(substring_pattern=symbol_name, restrict_search_to_code_files=True)
640
+ )
641
+ search_data = json.loads(search_result)
642
+ pattern_matches = sum(len(matches) for matches in search_data.values())
643
+ log.info("SearchForPatternTool found %d pattern matches for %s", pattern_matches, symbol_name)
644
+ except Exception as e:
645
+ log.warning("SearchForPatternTool failed for pattern %s: %s", symbol_name, str(e))
646
+ pattern_matches = 0
647
+
648
+ # Verify tools worked as expected
649
+ tools_working = True
650
+ if not find_symbol_data:
651
+ log.error("FindSymbolTool returned no results")
652
+ tools_working = False
653
+
654
+ if len(find_refs_data) == 0 and pattern_matches == 0:
655
+ log.warning("Both FindReferencingSymbolsTool and SearchForPatternTool found no matches - this might indicate an issue")
656
+
657
+ log.info("Health check completed successfully")
658
+
659
+ if tools_working:
660
+ click.echo("✅ Health check passed - All tools working correctly")
661
+ else:
662
+ click.echo("⚠️ Health check completed with warnings - Check log for details")
663
+
664
+ except Exception as e:
665
+ log.exception("Health check failed with exception: %s", str(e))
666
+ click.echo(f"❌ Health check failed: {e!s}")
667
+
668
+ finally:
669
+ click.echo(f"Log saved to: {log_file}")
670
+
671
+
672
+ class ToolCommands(AutoRegisteringGroup):
673
+ """Group for 'tool' subcommands."""
674
+
675
+ def __init__(self) -> None:
676
+ super().__init__(
677
+ name="tools",
678
+ help="Commands related to Serena's tools. You can run `serena tools <command> --help` for more info on each command.",
679
+ )
680
+
681
+ @staticmethod
682
+ @click.command(
683
+ "list",
684
+ help="Prints an overview of the tools that are active by default (not just the active ones for your project). For viewing all tools, pass `--all / -a`",
685
+ )
686
+ @click.option("--quiet", "-q", is_flag=True)
687
+ @click.option("--all", "-a", "include_optional", is_flag=True, help="List all tools, including those not enabled by default.")
688
+ @click.option("--only-optional", is_flag=True, help="List only optional tools (those not enabled by default).")
689
+ def list(quiet: bool = False, include_optional: bool = False, only_optional: bool = False) -> None:
690
+ tool_registry = ToolRegistry()
691
+ if quiet:
692
+ if only_optional:
693
+ tool_names = tool_registry.get_tool_names_optional()
694
+ elif include_optional:
695
+ tool_names = tool_registry.get_tool_names()
696
+ else:
697
+ tool_names = tool_registry.get_tool_names_default_enabled()
698
+ for tool_name in tool_names:
699
+ click.echo(tool_name)
700
+ else:
701
+ ToolRegistry().print_tool_overview(include_optional=include_optional, only_optional=only_optional)
702
+
703
+ @staticmethod
704
+ @click.command(
705
+ "description",
706
+ help="Print the description of a tool, optionally with a specific context (the latter may modify the default description).",
707
+ )
708
+ @click.argument("tool_name", type=str)
709
+ @click.option("--context", type=str, default=None, help="Context name or path to context file.")
710
+ def description(tool_name: str, context: str | None = None) -> None:
711
+ # Load the context
712
+ serena_context = None
713
+ if context:
714
+ serena_context = SerenaAgentContext.load(context)
715
+
716
+ agent = SerenaAgent(
717
+ project=None,
718
+ serena_config=SerenaConfig(web_dashboard=False, log_level=logging.INFO),
719
+ context=serena_context,
720
+ )
721
+ tool = agent.get_tool_by_name(tool_name)
722
+ mcp_tool = SerenaMCPFactory.make_mcp_tool(tool)
723
+ click.echo(mcp_tool.description)
724
+
725
+
726
+ class PromptCommands(AutoRegisteringGroup):
727
+ def __init__(self) -> None:
728
+ super().__init__(name="prompts", help="Commands related to Serena's prompts that are outside of contexts and modes.")
729
+
730
+ @staticmethod
731
+ def _get_user_prompt_yaml_path(prompt_yaml_name: str) -> str:
732
+ os.makedirs(PROMPT_TEMPLATES_DIR_IN_USER_HOME, exist_ok=True)
733
+ return os.path.join(PROMPT_TEMPLATES_DIR_IN_USER_HOME, prompt_yaml_name)
734
+
735
+ @staticmethod
736
+ @click.command("list", help="Lists yamls that are used for defining prompts.")
737
+ def list() -> None:
738
+ serena_prompt_yaml_names = [os.path.basename(f) for f in glob.glob(PROMPT_TEMPLATES_DIR_INTERNAL + "/*.yml")]
739
+ for prompt_yaml_name in serena_prompt_yaml_names:
740
+ user_prompt_yaml_path = PromptCommands._get_user_prompt_yaml_path(prompt_yaml_name)
741
+ if os.path.exists(user_prompt_yaml_path):
742
+ click.echo(f"{user_prompt_yaml_path} merged with default prompts in {prompt_yaml_name}")
743
+ else:
744
+ click.echo(prompt_yaml_name)
745
+
746
+ @staticmethod
747
+ @click.command("create-override", help="Create an override of an internal prompts yaml for customizing Serena's prompts")
748
+ @click.argument("prompt_yaml_name")
749
+ def create_override(prompt_yaml_name: str) -> None:
750
+ """
751
+ :param prompt_yaml_name: The yaml name of the prompt you want to override. Call the `list` command for discovering valid prompt yaml names.
752
+ :return:
753
+ """
754
+ # for convenience, we can pass names without .yml
755
+ if not prompt_yaml_name.endswith(".yml"):
756
+ prompt_yaml_name = prompt_yaml_name + ".yml"
757
+ user_prompt_yaml_path = PromptCommands._get_user_prompt_yaml_path(prompt_yaml_name)
758
+ if os.path.exists(user_prompt_yaml_path):
759
+ raise FileExistsError(f"{user_prompt_yaml_path} already exists.")
760
+ serena_prompt_yaml_path = os.path.join(PROMPT_TEMPLATES_DIR_INTERNAL, prompt_yaml_name)
761
+ shutil.copyfile(serena_prompt_yaml_path, user_prompt_yaml_path)
762
+ _open_in_editor(user_prompt_yaml_path)
763
+
764
+ @staticmethod
765
+ @click.command("edit-override", help="Edit an existing prompt override file")
766
+ @click.argument("prompt_yaml_name")
767
+ def edit_override(prompt_yaml_name: str) -> None:
768
+ """
769
+ :param prompt_yaml_name: The yaml name of the prompt override to edit.
770
+ :return:
771
+ """
772
+ # for convenience, we can pass names without .yml
773
+ if not prompt_yaml_name.endswith(".yml"):
774
+ prompt_yaml_name = prompt_yaml_name + ".yml"
775
+ user_prompt_yaml_path = PromptCommands._get_user_prompt_yaml_path(prompt_yaml_name)
776
+ if not os.path.exists(user_prompt_yaml_path):
777
+ click.echo(f"Override file '{prompt_yaml_name}' not found. Create it with: prompts create-override {prompt_yaml_name}")
778
+ return
779
+ _open_in_editor(user_prompt_yaml_path)
780
+
781
+ @staticmethod
782
+ @click.command("list-overrides", help="List existing prompt override files")
783
+ def list_overrides() -> None:
784
+ os.makedirs(PROMPT_TEMPLATES_DIR_IN_USER_HOME, exist_ok=True)
785
+ serena_prompt_yaml_names = [os.path.basename(f) for f in glob.glob(PROMPT_TEMPLATES_DIR_INTERNAL + "/*.yml")]
786
+ override_files = glob.glob(os.path.join(PROMPT_TEMPLATES_DIR_IN_USER_HOME, "*.yml"))
787
+ for file_path in override_files:
788
+ if os.path.basename(file_path) in serena_prompt_yaml_names:
789
+ click.echo(file_path)
790
+
791
+ @staticmethod
792
+ @click.command("delete-override", help="Delete a prompt override file")
793
+ @click.argument("prompt_yaml_name")
794
+ def delete_override(prompt_yaml_name: str) -> None:
795
+ """
796
+
797
+ :param prompt_yaml_name: The yaml name of the prompt override to delete."
798
+ :return:
799
+ """
800
+ # for convenience, we can pass names without .yml
801
+ if not prompt_yaml_name.endswith(".yml"):
802
+ prompt_yaml_name = prompt_yaml_name + ".yml"
803
+ user_prompt_yaml_path = PromptCommands._get_user_prompt_yaml_path(prompt_yaml_name)
804
+ if not os.path.exists(user_prompt_yaml_path):
805
+ click.echo(f"Override file '{prompt_yaml_name}' not found.")
806
+ return
807
+ os.remove(user_prompt_yaml_path)
808
+ click.echo(f"Deleted override file '{prompt_yaml_name}'.")
809
+
810
+
811
+ # Expose groups so we can reference them in pyproject.toml
812
+ mode = ModeCommands()
813
+ context = ContextCommands()
814
+ project = ProjectCommands()
815
+ config = SerenaConfigCommands()
816
+ tools = ToolCommands()
817
+ prompts = PromptCommands()
818
+
819
+ # Expose toplevel commands for the same reason
820
+ top_level = TopLevelCommands()
821
+ start_mcp_server = top_level.start_mcp_server
822
+ index_project = project.index_deprecated
823
+
824
+ # needed for the help script to work - register all subcommands to the top-level group
825
+ for subgroup in (mode, context, project, config, tools, prompts):
826
+ top_level.add_command(subgroup)
827
+
828
+
829
+ def get_help() -> str:
830
+ """Retrieve the help text for the top-level Serena CLI."""
831
+ return top_level.get_help(click.Context(top_level, info_name="serena"))
projects/ui/serena-new/src/serena/code_editor.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ from abc import ABC, abstractmethod
5
+ from collections.abc import Iterable, Iterator, Reversible
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING, Generic, Optional, TypeVar
8
+
9
+ from serena.symbol import JetBrainsSymbol, LanguageServerSymbol, LanguageServerSymbolRetriever, PositionInFile, Symbol
10
+ from solidlsp import SolidLanguageServer
11
+ from solidlsp.ls import LSPFileBuffer
12
+ from solidlsp.ls_utils import TextUtils
13
+
14
+ from .project import Project
15
+ from .tools.jetbrains_plugin_client import JetBrainsPluginClient
16
+
17
+ if TYPE_CHECKING:
18
+ from .agent import SerenaAgent
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+ TSymbol = TypeVar("TSymbol", bound=Symbol)
23
+
24
+
25
+ class CodeEditor(Generic[TSymbol], ABC):
26
+ def __init__(self, project_root: str, agent: Optional["SerenaAgent"] = None) -> None:
27
+ self.project_root = project_root
28
+ self.agent = agent
29
+
30
+ class EditedFile(ABC):
31
+ @abstractmethod
32
+ def get_contents(self) -> str:
33
+ """
34
+ :return: the contents of the file.
35
+ """
36
+
37
+ @abstractmethod
38
+ def delete_text_between_positions(self, start_pos: PositionInFile, end_pos: PositionInFile) -> None:
39
+ pass
40
+
41
+ @abstractmethod
42
+ def insert_text_at_position(self, pos: PositionInFile, text: str) -> None:
43
+ pass
44
+
45
+ @contextmanager
46
+ def _open_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]:
47
+ """
48
+ Context manager for opening a file
49
+ """
50
+ raise NotImplementedError("This method must be overridden for each subclass")
51
+
52
+ @contextmanager
53
+ def _edited_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]:
54
+ """
55
+ Context manager for editing a file.
56
+ """
57
+ with self._open_file_context(relative_path) as edited_file:
58
+ yield edited_file
59
+ # save the file
60
+ abs_path = os.path.join(self.project_root, relative_path)
61
+ with open(abs_path, "w", encoding="utf-8") as f:
62
+ f.write(edited_file.get_contents())
63
+ # notify agent (if provided)
64
+ if self.agent is not None:
65
+ self.agent.mark_file_modified(relative_path)
66
+
67
+ @abstractmethod
68
+ def _find_unique_symbol(self, name_path: str, relative_file_path: str) -> TSymbol:
69
+ """
70
+ Finds the unique symbol with the given name in the given file.
71
+ If no such symbol exists, raises a ValueError.
72
+
73
+ :param name_path: the name path
74
+ :param relative_file_path: the relative path of the file in which to search for the symbol.
75
+ :return: the unique symbol
76
+ """
77
+
78
+ def replace_body(self, name_path: str, relative_file_path: str, body: str) -> None:
79
+ """
80
+ Replaces the body of the symbol with the given name_path in the given file.
81
+
82
+ :param name_path: the name path of the symbol to replace.
83
+ :param relative_file_path: the relative path of the file in which the symbol is defined.
84
+ :param body: the new body
85
+ """
86
+ symbol = self._find_unique_symbol(name_path, relative_file_path)
87
+ start_pos = symbol.get_body_start_position_or_raise()
88
+ end_pos = symbol.get_body_end_position_or_raise()
89
+
90
+ with self._edited_file_context(relative_file_path) as edited_file:
91
+ # make sure the replacement adds no additional newlines (before or after) - all newlines
92
+ # and whitespace before/after should remain the same, so we strip it entirely
93
+ body = body.strip()
94
+
95
+ edited_file.delete_text_between_positions(start_pos, end_pos)
96
+ edited_file.insert_text_at_position(start_pos, body)
97
+
98
+ @staticmethod
99
+ def _count_leading_newlines(text: Iterable) -> int:
100
+ cnt = 0
101
+ for c in text:
102
+ if c == "\n":
103
+ cnt += 1
104
+ elif c == "\r":
105
+ continue
106
+ else:
107
+ break
108
+ return cnt
109
+
110
+ @classmethod
111
+ def _count_trailing_newlines(cls, text: Reversible) -> int:
112
+ return cls._count_leading_newlines(reversed(text))
113
+
114
+ def insert_after_symbol(self, name_path: str, relative_file_path: str, body: str) -> None:
115
+ """
116
+ Inserts content after the symbol with the given name in the given file.
117
+ """
118
+ symbol = self._find_unique_symbol(name_path, relative_file_path)
119
+
120
+ # make sure body always ends with at least one newline
121
+ if not body.endswith("\n"):
122
+ body += "\n"
123
+
124
+ pos = symbol.get_body_end_position_or_raise()
125
+
126
+ # start at the beginning of the next line
127
+ col = 0
128
+ line = pos.line + 1
129
+
130
+ # make sure a suitable number of leading empty lines is used (at least 0/1 depending on the symbol type,
131
+ # otherwise as many as the caller wanted to insert)
132
+ original_leading_newlines = self._count_leading_newlines(body)
133
+ body = body.lstrip("\r\n")
134
+ min_empty_lines = 0
135
+ if symbol.is_neighbouring_definition_separated_by_empty_line():
136
+ min_empty_lines = 1
137
+ num_leading_empty_lines = max(min_empty_lines, original_leading_newlines)
138
+ if num_leading_empty_lines:
139
+ body = ("\n" * num_leading_empty_lines) + body
140
+
141
+ # make sure the one line break succeeding the original symbol, which we repurposed as prefix via
142
+ # `line += 1`, is replaced
143
+ body = body.rstrip("\r\n") + "\n"
144
+
145
+ with self._edited_file_context(relative_file_path) as edited_file:
146
+ edited_file.insert_text_at_position(PositionInFile(line, col), body)
147
+
148
+ def insert_before_symbol(self, name_path: str, relative_file_path: str, body: str) -> None:
149
+ """
150
+ Inserts content before the symbol with the given name in the given file.
151
+ """
152
+ symbol = self._find_unique_symbol(name_path, relative_file_path)
153
+ symbol_start_pos = symbol.get_body_start_position_or_raise()
154
+
155
+ # insert position is the start of line where the symbol is defined
156
+ line = symbol_start_pos.line
157
+ col = 0
158
+
159
+ original_trailing_empty_lines = self._count_trailing_newlines(body) - 1
160
+
161
+ # ensure eol is present at end
162
+ body = body.rstrip() + "\n"
163
+
164
+ # add suitable number of trailing empty lines after the body (at least 0/1 depending on the symbol type,
165
+ # otherwise as many as the caller wanted to insert)
166
+ min_trailing_empty_lines = 0
167
+ if symbol.is_neighbouring_definition_separated_by_empty_line():
168
+ min_trailing_empty_lines = 1
169
+ num_trailing_newlines = max(min_trailing_empty_lines, original_trailing_empty_lines)
170
+ body += "\n" * num_trailing_newlines
171
+
172
+ # apply edit
173
+ with self._edited_file_context(relative_file_path) as edited_file:
174
+ edited_file.insert_text_at_position(PositionInFile(line=line, col=col), body)
175
+
176
+ def insert_at_line(self, relative_path: str, line: int, content: str) -> None:
177
+ """
178
+ Inserts content at the given line in the given file.
179
+
180
+ :param relative_path: the relative path of the file in which to insert content
181
+ :param line: the 0-based index of the line to insert content at
182
+ :param content: the content to insert
183
+ """
184
+ with self._edited_file_context(relative_path) as edited_file:
185
+ edited_file.insert_text_at_position(PositionInFile(line, 0), content)
186
+
187
+ def delete_lines(self, relative_path: str, start_line: int, end_line: int) -> None:
188
+ """
189
+ Deletes lines in the given file.
190
+
191
+ :param relative_path: the relative path of the file in which to delete lines
192
+ :param start_line: the 0-based index of the first line to delete (inclusive)
193
+ :param end_line: the 0-based index of the last line to delete (inclusive)
194
+ """
195
+ start_col = 0
196
+ end_line_for_delete = end_line + 1
197
+ end_col = 0
198
+ with self._edited_file_context(relative_path) as edited_file:
199
+ start_pos = PositionInFile(line=start_line, col=start_col)
200
+ end_pos = PositionInFile(line=end_line_for_delete, col=end_col)
201
+ edited_file.delete_text_between_positions(start_pos, end_pos)
202
+
203
+ def delete_symbol(self, name_path: str, relative_file_path: str) -> None:
204
+ """
205
+ Deletes the symbol with the given name in the given file.
206
+ """
207
+ symbol = self._find_unique_symbol(name_path, relative_file_path)
208
+ start_pos = symbol.get_body_start_position_or_raise()
209
+ end_pos = symbol.get_body_end_position_or_raise()
210
+ with self._edited_file_context(relative_file_path) as edited_file:
211
+ edited_file.delete_text_between_positions(start_pos, end_pos)
212
+
213
+
214
+ class LanguageServerCodeEditor(CodeEditor[LanguageServerSymbol]):
215
+ def __init__(self, symbol_retriever: LanguageServerSymbolRetriever, agent: Optional["SerenaAgent"] = None):
216
+ super().__init__(project_root=symbol_retriever.get_language_server().repository_root_path, agent=agent)
217
+ self._symbol_retriever = symbol_retriever
218
+
219
+ @property
220
+ def _lang_server(self) -> SolidLanguageServer:
221
+ return self._symbol_retriever.get_language_server()
222
+
223
+ class EditedFile(CodeEditor.EditedFile):
224
+ def __init__(self, lang_server: SolidLanguageServer, relative_path: str, file_buffer: LSPFileBuffer):
225
+ self._lang_server = lang_server
226
+ self._relative_path = relative_path
227
+ self._file_buffer = file_buffer
228
+
229
+ def get_contents(self) -> str:
230
+ return self._file_buffer.contents
231
+
232
+ def delete_text_between_positions(self, start_pos: PositionInFile, end_pos: PositionInFile) -> None:
233
+ self._lang_server.delete_text_between_positions(self._relative_path, start_pos.to_lsp_position(), end_pos.to_lsp_position())
234
+
235
+ def insert_text_at_position(self, pos: PositionInFile, text: str) -> None:
236
+ self._lang_server.insert_text_at_position(self._relative_path, pos.line, pos.col, text)
237
+
238
+ @contextmanager
239
+ def _open_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]:
240
+ with self._lang_server.open_file(relative_path) as file_buffer:
241
+ yield self.EditedFile(self._lang_server, relative_path, file_buffer)
242
+
243
+ def _get_code_file_content(self, relative_path: str) -> str:
244
+ """Get the content of a file using the language server."""
245
+ return self._lang_server.language_server.retrieve_full_file_content(relative_path)
246
+
247
+ def _find_unique_symbol(self, name_path: str, relative_file_path: str) -> LanguageServerSymbol:
248
+ symbol_candidates = self._symbol_retriever.find_by_name(name_path, within_relative_path=relative_file_path)
249
+ if len(symbol_candidates) == 0:
250
+ raise ValueError(f"No symbol with name {name_path} found in file {relative_file_path}")
251
+ if len(symbol_candidates) > 1:
252
+ raise ValueError(
253
+ f"Found multiple {len(symbol_candidates)} symbols with name {name_path} in file {relative_file_path}. "
254
+ "Their locations are: \n " + json.dumps([s.location.to_dict() for s in symbol_candidates], indent=2)
255
+ )
256
+ return symbol_candidates[0]
257
+
258
+
259
+ class JetBrainsCodeEditor(CodeEditor[JetBrainsSymbol]):
260
+ def __init__(self, project: Project, agent: Optional["SerenaAgent"] = None) -> None:
261
+ self._project = project
262
+ super().__init__(project_root=project.project_root, agent=agent)
263
+
264
+ class EditedFile(CodeEditor.EditedFile):
265
+ def __init__(self, relative_path: str, project: Project):
266
+ path = os.path.join(project.project_root, relative_path)
267
+ log.info("Editing file: %s", path)
268
+ with open(path, encoding=project.project_config.encoding) as f:
269
+ self._content = f.read()
270
+
271
+ def get_contents(self) -> str:
272
+ return self._content
273
+
274
+ def delete_text_between_positions(self, start_pos: PositionInFile, end_pos: PositionInFile) -> None:
275
+ self._content, _ = TextUtils.delete_text_between_positions(
276
+ self._content, start_pos.line, start_pos.col, end_pos.line, end_pos.col
277
+ )
278
+
279
+ def insert_text_at_position(self, pos: PositionInFile, text: str) -> None:
280
+ self._content, _, _ = TextUtils.insert_text_at_position(self._content, pos.line, pos.col, text)
281
+
282
+ @contextmanager
283
+ def _open_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]:
284
+ yield self.EditedFile(relative_path, self._project)
285
+
286
+ def _find_unique_symbol(self, name_path: str, relative_file_path: str) -> JetBrainsSymbol:
287
+ with JetBrainsPluginClient.from_project(self._project) as client:
288
+ result = client.find_symbol(name_path, relative_path=relative_file_path, include_body=False, depth=0, include_location=True)
289
+ symbols = result["symbols"]
290
+ if not symbols:
291
+ raise ValueError(f"No symbol with name {name_path} found in file {relative_file_path}")
292
+ if len(symbols) > 1:
293
+ raise ValueError(
294
+ f"Found multiple {len(symbols)} symbols with name {name_path} in file {relative_file_path}. "
295
+ "Their locations are: \n " + json.dumps([s["location"] for s in symbols], indent=2)
296
+ )
297
+ return JetBrainsSymbol(symbols[0], self._project)