AIStoreHub Package Vault: Serena Coding Agent MCP Server
Package Slug: serena
Archetype: mcp_server
Upstream Repository: https://github.com/oraios/serena
Workspace Files & Specifications (67 files)
- AGENTS.md (436 bytes)
This project uses Serena for development. Make sure that you read the project's `critical_info` memory before working on it. * When using Serena, the memory is provided either - along with the result of the `initial_instructions` tool, or - upon activating the project with `activate_project`. Be sure to always call the `initial_instructions` tool! * When not using Serena, read `./.serena/memories/critical_info.md` manually.
- aistorehub.json (547 bytes)
{ "name": "Serena Coding Agent MCP Server", "slug": "serena", "version": "1.0.0", "type": "mcp_server", "description": "Autonomous coding agent MCP server that navigates codebases, performs intelligent semantic refactoring, and executes build verification.", "owner": "community", "repository": "catalog", "github_repo_url": "https://github.com/oraios/serena", "tags": [ "mcp", "coding-agent", "mcp-server", "cursor", "refactoring", "codebase-navigation" ], "imported_at": "2026-11-24T20:32:31.206Z" } - CHANGELOG.md (106654 bytes)
# Unreleased (main) Status of the `main` branch. Changes prior to the next official version change will appear here. * General: - Fix: project activation commands could hang on Windows when Serena uses the stdio transport (#2270) - More flexible inclusion/exclusion definitions: - Allow tool exclusions/inclusions to use tool marker names (e.g. `ToolMarkerCanEdit`) - Allow API exclusions to include `marker:editing` to exclude all editing functionality - Add new modes `ext-full` and `ext-readonly` to conveniently enable external project access when using the REPL interface. - Remove unnecessary sections from Claude Code system prompt override, which will be phased out (#2259) - Fix: `planning` mode now correctly excludes all editing tools/functions (#2210) - Fix: `read_file`, `search_for_pattern` and `replace_in_files` failed with a `UnicodeDecodeError` on a project file whose encoding differs from the project's configured `encoding` (e.g. a UTF-16 file saved by Notepad or PowerShell, or a latin-1 export), although Serena documents a fallback to detected encoding for such files. These tools now use the documented read path, so the file is read instead of rejected (#2274) - Fix: project-level `ls_specific_settings` replaced the global settings for the same language server silently. Since the replacement is per language rather than per key, a project block that only set `ls_path`, for example, dropped every global key such as `ls_extra_args`, leaving no trace. The replacement behaviour is unchanged, but the global keys hidden by a project block are now logged (#2188). - Fix: under the `sse` and `streamable-http` transports, stopping the MCP server with SIGINT/SIGTERM did not shut the agent down, so language servers were left to be killed and the symbol caches they had built were never saved (the server lifespan runs per connection under these transports, and uvicorn re-raises the signal right after its loop ends). The CLI now shuts the agent down on the signal and when the server loop ends for any other reason, as the `stdio` transport already did (#2221). - Fix: on macOS, cleaning up a language server that had already exited logged a spurious "Permission denied signaling process group" warning; an exited process group is now treated as already clean (#2237) - Performance: the symbol caches were rewritten in full after every tool call that fetched new symbols, which takes noticeable time for large projects; they are now saved at most every 30 s, and always when language servers are stopped or restarted - Fix: the default connection prompt made some agents call `initial_instructions` again for every new task in a conversation, although the Serena Instructions Manual was still in context (#2293) * JetBrains: - Fix: When applying a non-symbolic edit, do not raise a post-edit exception during IDE file refresh if the IDE's plugin server is not reachable. * Language Servers: - Fix: `find_implementations` can now find TypeScript interface implementations in Vue projects (#2218) - Fix: detect Elixir installed via a Windows batch launcher - Fix: a language server process that exited while its child processes kept running (e.g. after being killed) was still considered running, so it was not restarted and the next request hung until the tool timeout - Extend allowed types in persisted symbol caches, fixing cache loading issues with `clangd` when overriding values like `ls_path`, `clangd_version` or `compile_commands_dir` - Add GraphQL language server support (experimental) via `graphql-language-service-cli` (`graphql-lsp`) for `.graphql`/`.gql` files. Document symbols, hover and cross-file go-to-definition require a graphql-config file (`.graphqlrc.yml` / `graphql.config.*`) at the repository root; without one, Serena logs an actionable message instead of waiting out the startup timeout. Find-references is unsupported (not implemented by the upstream server) - Fix: tsserver reports the range of a single top-level `const`/`let`/`var` declaration starting at the identifier and ending before the statement's semicolon, excluding a leading `export`, the keyword, and the trailing `;` (unlike `function`/`class` declarations, whose range already includes their keyword). `replace_symbol_body` then dropped the prefix and the semicolon from the body and replacement range, so re-supplying them in a full-statement edit either duplicated the prefix and produced invalid syntax (`export const twice = ...` became `export const export const twice = ...`, returned as `OK`) or, once only the prefix was fixed, left a harmless but incorrect double semicolon behind (`... n * 3;;`). Mirrors the range-start fix already applied to Go's `type`/`var`/`const` declarations, and the range-end fix already applied to Nix's attribute declarations (#1956) - Fix: `rename_symbol` did not wait for the language server to be ready for cross-file requests, so with the TypeScript language server a rename issued before any reference lookup could change only the open files (often just the definition) while still reporting success. Renames now wait the same way reference lookups do. - Fix: C# solution discovery aborted with ``ValueError: path is on mount '\\.\nul'`` when the repository contained a file with a reserved DOS device name (e.g. ``nul``, typically created accidentally by `... > nul` in Git Bash), failing the C# language server startup. Reserved-name entries are now skipped per entry instead of aborting the whole directory scan - Fix: C/C++ (clangd) reference searches returned at most 1000 references; clangd is now started with `--limit-references=0` unless `ls_extra_args` already sets a limit - C/C++ (clangd) logs errors only (`--log=error`) instead of a line for every request and parse, unless `ls_extra_args` sets `--log` or Serena logs at debug level - Fix: every line a language server wrote to stderr was followed by an empty line in Serena's log - BSL: upgrade to bsl-language-server 1.0.7; wait for the server's initial indexing instead of a fixed delay before the first cross-file request; add `jvm_options` setting (e.g. `-Xmx`). - Fix: with `typescript_tsgo`, reference searches missed imports, re-exports and implementing members, so `safe_delete_symbol` could delete a symbol that was still re-exported (#2286) * CLI: - health-check: Remove the "find references" step, as it is not universally supported by language servers (#2253) * Dashboard: - Show REPL function usage below tool usage when using the REPL interface, including facade methods and `info`, `vars`, `clear`, and `overview`, with separately normalized bar charts. - On Windows, change the default interface to `tray_manager` (better in case of many instances, which is becoming increasingly common) (#2212) - Fix: on macOS, the tray icon stayed white on a light menu bar instead of adapting to the menu bar's appearance like other menu bar icons (#2263) - Fix: on macOS, the tray icon was blurry on Retina displays # v2.1.0 (2026-10-19) * General: - Fix: Re-establish compatibility with the Claude Desktop client in chat mode (code mode was not affected). The client filters out the parameter `session_id`, which was introduced for several tools with v2.0.0. The parameter was renamed to `session`. - Fix: the MCP registry manifest (`server.json`) declared Serena's own CLI arguments as runtime arguments, so clients installing Serena from the MCP registry generated a launch command with a stray package spec, and project auto-activation failed - Fix: logs stopped updating when using SSE or streamable HTTP because Uvicorn's logging configuration closed the Serena's log handlers. This is due to a bug in the MCP SDK, in which the logging configuration override was effectively hard-coded. We now patch Uvicorn's log config constructor to prevent this. This affected both dashboard log retrieval and file logs written by Serena. * Dashboard: - Add a welcome pane for users with an unset `web_dashboard_open_on_launch` preference, allowing them to choose whether the dashboard opens whenever Serena starts. The dashboard continues to open automatically until a preference is configured. - Show an `[untrusted]` indicator beside the active project name for untrusted projects, with a formatted tooltip explaining the limitations and a link to the trusted-projects documentation. Add reusable tooltip support for hover and keyboard interaction. * Security: - Fix: typescript-language-server loaded `node_modules/typescript/lib/tsserver.js` from the project whenever the project provided one, so merely opening an untrusted repository executed JavaScript supplied by that repository. tsserver is now pinned to the TypeScript installation managed by Serena unless the project is trusted; loading the project's own TypeScript has become a trust-gated feature (#2129) * Language Servers: - Add VB.NET language server support (via the Roslyn-based `Microsoft.CodeAnalysis.LanguageServer`, also shared with the C# language server) - Fix: the Intelephense settings `maxMemory` and `maxFileSize` had no effect, because they were passed as initialization options, which Intelephense does not read; `maxMemory` now limits the heap of the server process, and `maxFileSize` is passed as `intelephense.files.maxSize` - Fix: Explicit symbol and diagnostics requests now validate their input paths against the project's trust policy. Symlinks to files outside the project root are rejected in untrusted projects; links within the project and outside-root links in trusted projects remain supported (#2163). - Fix: Project-wide symbol discovery now skips file and directory symlinks in untrusted projects. In trusted projects, ignore rules consistently apply to unresolved alias paths, and symlinks to targets outside the project root no longer cause discovery to fail (#2163). - Scala: add opt-in setting `terminate_bloop_on_stop` to terminate the Bloop build-server daemons that Metals leaves running after shutdown (#1816) - Performance: Speed up project-wide symbol discovery by reusing directory-entry metadata for ignore checks and avoiding repeated ancestor-directory checks for files. - Add `typescript_tsgo`, which uses the native language server of TypeScript 7 (`tsc --lsp`) and installs the `typescript` package automatically (#1402) # v2.0.0 (2026-10-13) * Licensing: - **Serena is now GPL-licensed**: The Serena application is now licensed under GPL-3.0-or-later. SolidLSP (`src/solidlsp`) remains MIT-licensed. See `LICENSE` for the overview, the historical cutoff and the rationale. The change is not retroactive: earlier releases and commits remain available under MIT. - Source files now carry `SPDX-License-Identifier` headers - Contributions require acceptance of the new Contributor License Agreement (`CLA.md`), enforced via CLA assistant; see `CONTRIBUTING.md` * General: - **Introducing the Serena REPL**: Add the Serena REPL as a new agent interface, reducing the tool set to a minimum and providing a general code execution environment for all Serena operations. This has several significant advantages over regular tool executions. Please refer to our [documentation](https://oraios.github.io/serena/01-about/035_tools.html) for details. - Add `auth_secret` to `serena_config.yml` for authenticating communication between Serena components and services. When missing, null, or empty, a random UUID is generated and persisted; existing values are preserved - Fix: Tiktoken usage counting now treats special-token literals in tool input and output as ordinary text - Improve speed of file system operations, particularly enumeration of all source files of a project, which is particularly relevant for file system refresh operations when using the LSP backend. - Fix: Repeated comments in `serena_config.yml` - Fix: MCP server now reports Serena's version instead of the installed MCP SDK version (#1889) - Fix: importing Serena no longer loads the `anthropic` package unless the Anthropic token counter is actually used; the unconditional import added seconds to CLI/MCP startup on some machines (#2012) - Fix: Parallel agents auto-registering projects could overwrite each other's changes to the global project list in `serena_config.yml` - Fix: the reload-merge-write in `_persist_projects` (the residual half of the fix above) had no cross-process lock, so two Serena instances could still lose a registration change if their persist calls overlapped; it is now wrapped in a `filelock.FileLock` (#2101) - Perf: `search_for_pattern` resolved each match's line number by rescanning the file from the beginning (O(n) per match, O(n*m) total for m matches); coordinates are now resolved via the new `TextCoordinates` abstraction (cached line starts + binary search) - Fix: `replace_lines` deleted the line range and inserted the replacement as two separate writes, so a failure while inserting left the file with the range already removed; the replacement is now applied within a single edit, like `replace_symbol_body` and `replace_content` - Fix: `TextUtils.insert_text_at_position` returned a wrong position when the inserted text merged with an adjacent character into a single newline sequence (e.g. a `\n` inserted directly after an existing `\r`); the position is now determined from the resulting text - Fix: `search_for_pattern` reported "no matches" for a regular expression that does not compile, because the compilation happened inside the per-file error handling that exists to skip unreadable files; an invalid pattern is now rejected up front, as `search_text` documents and as the replacement tools already do - Fix: process-tree cleanup signaled descendant language-server processes without waiting for them, which could leave grandchildren as zombies; cleanup now waits for the discovered descendants (#1464) - Fix: `read_only` restriction in project definition was not applied to base tool set when in single-project context (#1938) - Fix: a tsserver crash was only surfaced by the first cross-file query of a TypeScript language server instance; later queries skipped the check together with the indexing wait and returned an empty result as if the symbol had no references. Every cross-file query now raises `TypeScriptServerCrashedError` once a crash has been observed - Fix: `MultiFileContentReplacer` accounted for the exclusivity of the match end in neither `ReplacementOccurrence.end_line` nor the region rendered by `render_occurrence_diff`, so a replacem - CLA.md (6522 bytes)
# Serena Contributor License Agreement Thank you for your interest in contributing to Serena (the "Project"), maintained by Jain & Panchenko IT-Berater Partnerschaft, operating under the brand "Oraios AI" ("Oraios", "we", "us"). This Contributor License Agreement ("Agreement") sets out the terms under which you submit Contributions to the Project. Please read it carefully. By accepting this Agreement (for example via the CLA assistant on GitHub), you agree to the terms below for all of your past, present and future Contributions to the Project. If you have questions about this Agreement, contact us at [email protected]. ## 1. Definitions - **"You"** (or **"Your"**) means the individual or legal entity accepting this Agreement. If You are accepting on behalf of a legal entity, "You" includes that entity and all entities that control, are controlled by, or are under common control with it. - **"Contribution"** means any work of authorship, including source code, object code, documentation, configuration, tests, data, designs, or other material, that You intentionally submit to the Project in any form and by any means (including pull requests, patches, issues, and discussions), excluding material that You conspicuously mark as "Not a Contribution". - **"Project"** means the Serena repository and any associated repositories, packages, distributions and documentation maintained by Oraios, including the SolidLSP library contained therein. ## 2. Copyright ownership You retain all right, title and interest in and to Your Contributions. Nothing in this Agreement transfers Your copyright to Oraios. This Agreement is a license, not an assignment. ## 3. Copyright license Subject to the terms of this Agreement, You hereby grant to Oraios, and to recipients of software distributed by Oraios, a perpetual, worldwide, non-exclusive, irrevocable, royalty-free, fully paid-up, transferable copyright license to: - reproduce, prepare derivative works of, publicly display, publicly perform, use, modify, distribute and otherwise exploit Your Contributions and such derivative works, in whole or in part, in any form and by any means now known or later developed; - sublicense any or all of the foregoing rights through multiple tiers of sublicensees; and - **license and relicense** Your Contributions and derivative works thereof **under any terms of Oraios' choosing**, including open-source licenses (such as the GNU General Public License or the MIT License) **and proprietary, closed-source, or commercial licenses**, and to change such terms from time to time. For the avoidance of doubt, Oraios may distribute the Project, including Your Contributions, both under free and open-source licenses (such as GPL-3.0-or-later or MIT) and under commercial or proprietary licenses, and may offer it as a hosted or paid service. This Agreement does not require Oraios to compensate You for any such use. ## 4. Patent license Subject to the terms of this Agreement, You hereby grant to Oraios, and to recipients of software distributed by Oraios, a perpetual, worldwide, non-exclusive, irrevocable (except as stated in this section), royalty-free, fully paid-up, transferable patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Project, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution alone or by the combination of Your Contribution with the Project to which it was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that Your Contribution, or the Project to which You have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Project shall terminate as of the date such litigation is filed. ## 5. Your representations You represent that: 1. You are legally entitled to grant the above licenses. If Your employer or another party has rights to intellectual property that You create that includes Your Contributions, You represent that You have received permission to make the Contributions on behalf of that party, that such party has waived such rights for Your Contributions, or that such party has accepted this Agreement (or a corporate version of it) on Your behalf. 2. Each of Your Contributions is Your original creation, or You have clearly identified the parts that are not Your original creation, together with their source, license and any other restrictions (including related patents, trademarks and license agreements) of which You are aware. 3. Your Contributions do not, to Your knowledge, violate any third-party rights or applicable law. 4. If You are accepting this Agreement on behalf of a legal entity, You are authorized to bind that entity to this Agreement. You agree to notify Oraios of any facts or circumstances of which You become aware that would make these representations inaccurate in any respect. ## 6. No obligation to use; no warranty Oraios is under no obligation to accept, use, or include any Contribution in the Project. Except for the representations in Section 5, Your Contributions are provided **"AS IS"**, without warranties or conditions of any kind, either express or implied, including any warranties of merchantability, fitness for a particular purpose, or non-infringement, unless required by applicable law or agreed to in writing. ## 7. Scope and relation to the Project's public licenses This Agreement governs the rights You grant to Oraios. It does not limit or alter the rights that any person, including You, has under the public licenses of the Project (GPL-3.0-or-later for the Serena application and MIT for SolidLSP; see `LICENSE`). Acceptance of this Agreement is required for contributions to the whole repository, including SolidLSP; this does not change SolidLSP's MIT license. ## 8. Miscellaneous This Agreement is governed by the laws of the Federal Republic of Germany, excluding its conflict-of-law rules and the UN Convention on Contracts for the International Sale of Goods. If any provision of this Agreement is held unenforceable, the remaining provisions remain in full force and effect. This Agreement constitutes the entire agreement between You and Oraios regarding Your Contributions and supersedes any prior agreements on the same subject. - CLAUDE.md (11 bytes)
@AGENTS.md
- compose.yaml (764 bytes)
services: serena: image: serena:latest # To work with projects, you must mount them into /workspace/ in the container: # volumes: # - ./my-project:/workspace/my-project # - /path/to/another/project:/workspace/another-project build: context: ./ dockerfile: Dockerfile target: production ports: - "127.0.0.1:${SERENA_PORT:-9121}:9121" - "127.0.0.1:${SERENA_DASHBOARD_PORT:-24282}:24282" environment: - SERENA_DOCKER=1 command: - "uv run --directory . serena-mcp-server --transport sse --port 9121 --host 0.0.0.0" # Alternatively add further arguments, e.g. a context # - "uv run --directory . serena-mcp-server --transport sse --port 9121 --host 0.0.0.0 --context ide" - CONTRIBUTING.md (4658 bytes)
# Contributing to Serena Thank you for your interest in contributing to Serena! ## Scope of Contributions The following types of contributions can be submitted directly via pull requests: * isolated additions which do not change the behaviour of Serena and only extend it along existing lines (e.g., adding support for a new language server) * small bug fixes * documentation improvements For other changes, always open an issue first to discuss your ideas with the maintainers and do not submit a PR until a solution has been agreed upon. Fixes to "problems" in the code that are uncovered by AI via theoretical code analysis or by applying components in a way that does not reflect their actual usage in Serena are not considered valuable contributions. Problems being fixed must be real problems that have either been observed in practice or that can indeed be expected to occur in practice. Do not work on beta features (unless they are trivial bug fixes); instead, provide feedback via issues or discussions. ### Adding Support for a New Language Server See the corresponding [memory](.serena/memories/adding_new_language_support_guide.md). ## Licensing and Contributor License Agreement (CLA) Serena is multi-licensed by component (see [LICENSE](LICENSE)): the Serena application is licensed under GPL-3.0-or-later, while SolidLSP (`src/solidlsp`) is licensed under MIT. All contributions to this repository require acceptance of our [Contributor License Agreement](CLA.md). The CLA lets you keep the copyright to your work while granting Jain & Panchenko IT-Berater Partnerschaft (Oraios AI) the rights needed to maintain and distribute Serena under different terms in the future (including the free community edition and possible commercial editions). Acceptance is handled automatically by [CLA assistant](https://cla-assistant.io/): * When you open your first pull request, the CLA assistant bot comments on it with a link to accept the CLA. * You accept it once, authenticated with your GitHub account; the acceptance is remembered for all future PRs (you will only be asked again if the CLA text changes). * PRs cannot be merged until the `license/cla` status check passes. The CLA is required repository-wide for operational simplicity, i.e. also for SolidLSP-only changes. This does not change SolidLSP's MIT license. When adding new source files, include the SPDX identifier that matches the component: `# SPDX-License-Identifier: GPL-3.0-or-later` for Serena application code and `# SPDX-License-Identifier: MIT` for SolidLSP. ## Submitting Pull Requests When submitting a PR, ensure a well-defined scope. Every PR should cover a single logical change or a set of closely related changes. Before submitting a PR, be sure to document your relevant changes (i.e. new features, fixes) in `CHANGELOG.md`. Use a concise style and add your change to the appropriate section ("Language Servers", "Tools", "JetBrains", "CLI", "Memories", "Dashboard", "Hooks", "General", "Security"). The change log is for users to understand how the changes affect them; technical details belong in the commit message/PR description. No changelog entry for documentation changes or fixes for problems weren't present in the last release. If you are using AI to generate your contribution, it is expected that you add value by reviewing it carefully and/or testing it in practice before submitting it. Submission limit: No more than 3 PRs per contributor can be open simultaneously. If you try to open additional PRs, you will get a permission error (which, unfortunately, does not explain this limit). ## Python Environment Setup You can install a virtual environment with the required as follows 1. Create a new virtual environment: `uv venv -p 3.13` 2. Activate the environment: * On Linux/Unix/macOS or Windows with Git Bash: `source .venv/bin/activate` * On Windows outside of Git Bash: `.venv\Scripts\activate.bat` (in cmd/ps) or `source .venv/Scripts/activate` (in git-bash) 3. Install the required packages with all extras: `uv sync --extra dev` ## Local Installation as Tool To install Serena from the local source, run ```shell uv tool install --reinstall -p 3.13 . ``` ## Poe Tasks We use poe to execute development tasks: - `poe format` - run code auto-formatters - `poe type-check` - run type checkers ## Testing Tool Executions The Serena tools (and in fact all Serena code) can be executed without an LLM, and also without any MCP specifics (though you can use the mcp inspector, if you want). An example script for running tools is provided in [scripts/demo_run_tools.py](scripts/demo_run_tools.py). - docker_build_and_run.sh (93 bytes)
#!/usr/bin/bash docker build -t serena . docker run -it --rm -v "$(pwd)":/workspace serena
- DOCKER.md (5866 bytes)
# Docker Setup for Serena (Experimental) ⚠️ **EXPERIMENTAL FEATURE**: The Docker setup for Serena is still experimental and has some limitations. Please read this entire document before using Docker with Serena. ## Overview Docker support allows you to run Serena in an isolated container environment, which provides better security isolation for the shell tool and consistent dependencies across different systems. ## Benefits - **Safer shell tool execution**: Commands run in an isolated container environment - **Consistent dependencies**: No need to manage language servers and dependencies on your host system - **Cross-platform support**: Works consistently across Windows, macOS, and Linux ## Important Usage Pointers ### Configuration Serena's configuration and log files are stored in the container in `/workspaces/serena/config/`. Any local configuration you may have for Serena will not apply; the container uses its own separate configuration. You can mount a local configuration/data directory to persist settings across container restarts (which will also contain session log files). Simply mount your local directory to `/workspaces/serena/config` in the container. Initially, be sure to add a `serena_config.yml` file to the mounted directory which applies the following special settings for Docker usage: ``` # Disable the GUI log window since it's not supported in Docker gui_log_window: False # Listen on all interfaces for the web dashboard to be accessible from outside the container web_dashboard_listen_address: 0.0.0.0 # Disable opening the web dashboard on launch (not possible within the container) web_dashboard_open_on_launch: False ``` Set other configuration options as needed. ### Project Activation Limitations - **Only mounted directories work**: Projects must be mounted as volumes to be accessible - Projects outside the mounted directories cannot be activated or accessed - Since projects are not remembered across container restarts (unless you mount a local configuration as described above), activate them using the full path (e.g. `/workspaces/projects/my-project`) when using dynamic project activation ### Language Support Limitations The default Docker image does not include dependencies for languages that require explicit system-level installations. Only languages that install their requirements on the fly will work out of the box. ### Dashboard Port Configuration The web dashboard runs on port 24282 (0x5EDA) by default. You can configure this using environment variables: ```bash # Use default ports docker-compose up serena # Use custom ports SERENA_DASHBOARD_PORT=8080 docker-compose up serena ``` ⚠️ **Note**: If the local port is occupied, you'll need to specify a different port using the environment variable. ### Line Ending Issues on Windows ⚠️ **Windows Users**: Be aware of potential line ending inconsistencies: - Files edited within the Docker container may use Unix line endings (LF) - Your Windows system may expect Windows line endings (CRLF) - This can cause issues with version control and text editors - Configure your Git settings appropriately: `git config core.autocrlf true` ## Quick Start ### Using Docker Compose (Recommended) 1. **Production mode** (for using Serena as MCP server): ```bash docker-compose up serena ``` 2. **Development mode** (with source code mounted): ```bash docker-compose up serena-dev ``` Note: Edit the `compose.yaml` file to customize volume mounts for your projects. ### Building the Docker Image Manually ```bash # Build the image docker build -t serena . # Run with current directory mounted docker run -it --rm \ -v "$(pwd)":/workspace \ -p 9121:9121 \ -p 24282:24282 \ -e SERENA_DOCKER=1 \ serena ``` ### Using Docker Compose with Merge Compose files To use Docker Compose with merge files, you can create a `compose.override.yml` file to customize the configuration: ```yaml services: serena: # To work with projects, you must mount them as volumes: volumes: - ./my-project:/workspace/my-project - /path/to/another/project:/workspace/another-project # Add the context for the IDE assistant option: command: - "uv run --directory . serena-mcp-server --transport sse --port 9121 --host 0.0.0.0 --context claude-code" ``` See the [Docker Merge Compose files documentation](https://docs.docker.com/compose/how-tos/multiple-compose-files/merge/) for more details on using merge files. ## Accessing the Dashboard Once running, access the web dashboard at: - Default: http://localhost:24282/dashboard - Custom port: http://localhost:${SERENA_DASHBOARD_PORT}/dashboard ## Volume Mounting To work with projects, you must mount them as volumes: ```yaml # In compose.yaml volumes: - ./my-project:/workspace/my-project - /path/to/another/project:/workspace/another-project ``` ## Environment Variables - `SERENA_DOCKER=1`: Set automatically to indicate Docker environment - `SERENA_PORT`: MCP server port (default: 9121) - `SERENA_DASHBOARD_PORT`: Web dashboard port (default: 24282) - `INTELEPHENSE_LICENSE_KEY`: License key for Intelephense PHP LSP premium features (optional) ## Troubleshooting ### Port Already in Use If you see "port already in use" errors: ```bash # Check what's using the port lsof -i :24282 # macOS/Linux netstat -ano | findstr :24282 # Windows # Use a different port SERENA_DASHBOARD_PORT=8080 docker-compose up serena ``` ### Configuration Issues If you need to reset Docker configuration: ```bash # Remove Docker-specific config rm serena_config.docker.yml # Serena will auto-generate a new one on next run ``` ### Project Access Issues Ensure projects are properly mounted: - Check volume mounts in `docker-compose.yaml` - Use absolute paths for external projects - Verify permissions on mounted directories - Dockerfile (2603 bytes)
# Base stage with common dependencies FROM python:3.11-slim AS base SHELL ["/bin/bash", "-c"] # Set environment variables to make Python print directly to the terminal and avoid .pyc files. ENV PYTHONUNBUFFERED=1 ENV PYTHONDONTWRITEBYTECODE=1 # Install system dependencies required for package manager and build tools. # sudo, wget, zip needed for some assistants, like junie RUN apt-get update && apt-get install -y --no-install-recommends \ curl \ build-essential \ git \ ssh \ sudo \ wget \ zip \ unzip \ git \ && rm -rf /var/lib/apt/lists/* # Install pipx. RUN python3 -m pip install --no-cache-dir pipx \ && pipx ensurepath # Install nodejs ENV NVM_VERSION=0.40.3 ENV NODE_VERSION=22.18.0 RUN curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v${NVM_VERSION}/install.sh | bash # standard location ENV NVM_DIR=/root/.nvm RUN . "$NVM_DIR/nvm.sh" && nvm install ${NODE_VERSION} RUN . "$NVM_DIR/nvm.sh" && nvm use v${NODE_VERSION} RUN . "$NVM_DIR/nvm.sh" && nvm alias default v${NODE_VERSION} ENV PATH="${NVM_DIR}/versions/node/v${NODE_VERSION}/bin/:${PATH}" # Add local bin to the path ENV PATH="${PATH}:/root/.local/bin" # Install the latest version of uv RUN curl -LsSf https://astral.sh/uv/install.sh | sh # Install Rust and rustup for rust-analyzer support (minimal profile) ENV RUSTUP_HOME=/usr/local/rustup ENV CARGO_HOME=/usr/local/cargo ENV PATH="${CARGO_HOME}/bin:${PATH}" RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y \ --default-toolchain stable \ --profile minimal \ && rustup component add rust-analyzer # Set the working directory WORKDIR /workspaces/serena # Copy all files for development COPY . /workspaces/serena/ # Install sed RUN apt-get update && apt-get install -y sed # Create Serena configuration ENV SERENA_HOME=/workspaces/serena/config RUN mkdir -p $SERENA_HOME RUN cp src/serena/resources/serena_config.template.yml $SERENA_HOME/serena_config.yml RUN sed -i 's/^gui_log_window: .*/gui_log_window: False/' $SERENA_HOME/serena_config.yml RUN sed -i 's/^web_dashboard_listen_address: .*/web_dashboard_listen_address: 0.0.0.0/' $SERENA_HOME/serena_config.yml RUN sed -i 's/^web_dashboard_open_on_launch: .*/web_dashboard_open_on_launch: False/' $SERENA_HOME/serena_config.yml # Create virtual environment and install dependencies RUN uv venv RUN . .venv/bin/activate RUN uv pip install -r pyproject.toml -e . ENV PATH="/workspaces/serena/.venv/bin:${PATH}" # Entrypoint to ensure environment is activated ENTRYPOINT ["/bin/bash", "-c", "source .venv/bin/activate && $0 $@"] - INSTRUCTIONS.md (72 bytes)
aihub pull @community/catalog/serena aihub run @community/catalog/serena
- LICENSE (3470 bytes)
Serena Licensing Overview ========================= This repository is licensed per component: SolidLSP under the MIT License and the Serena application under GPL-3.0-or-later. Because MIT is compatible with the GPL, any distribution that combines both - such as the `serena-agent` package - is as a whole subject to the terms of GPL-3.0-or-later. This does not change the license of the SolidLSP files themselves: they remain MIT-licensed and may be obtained, extracted and used separately under MIT terms. The full license texts are in the LICENSES/ directory and are not modified in any way: LICENSES/MIT.txt The MIT License LICENSES/GPL-3.0-or-later.txt The GNU General Public License, version 3 Components ---------- SolidLSP (src/solidlsp/, test/solidlsp/, test/resources/) License: MIT (SPDX: MIT) Copyright (c) 2025-2026 Jain & Panchenko IT-Berater Partnerschaft (Oraios AI) and contributors SolidLSP is the language-server client library that provides the basis for Serena's free code-intelligence backend. It is permissive, reusable infrastructure and remains MIT-licensed so that it can be used independently of Serena under MIT terms. This is unaffected by the licensing of the Serena application. Some files in src/solidlsp/lsp_protocol_handler/ are derived from OLSP (https://github.com/predragnikolic/OLSP), MIT-licensed; the original notices are retained in those files. Serena application (src/serena/, src/interprompt/, scripts/, test/serena/, docs/ and everything else in this repository that is not listed above) License: GPL-3.0-or-later (SPDX: GPL-3.0-or-later) Copyright (c) 2025-2026 Jain & Panchenko IT-Berater Partnerschaft (Oraios AI) and contributors Serena is the application built on top of SolidLSP. Starting with the v2 licensing transition (see "Historical cutoff" below), Serena application code is licensed under the GNU General Public License, version 3 or (at your option) any later version. Source files carry an "SPDX-License-Identifier" line indicating which of the two licenses applies to that file. Historical cutoff ----------------- The license change is NOT retroactive. * Serena originally began under the GNU General Public License (version 2). It was changed to the MIT License on 2025-05-01 (commit 3e9384f5). * All Serena releases and commits from that point up to and including the cutoff below were released under the MIT License and remain available under the MIT License. * Serena v2 and all later application code are licensed under GPL-3.0-or-later. Last MIT-licensed release: v1.7.0 Last MIT-licensed commit: 74c38a65f03fc0764d7ee4b3016ef6a07572ed64 Marker tag: mit-final Contributions that entered the Serena application under the MIT License before the cutoff remain incorporated in the GPL-licensed application; the MIT copyright and permission notice (LICENSES/MIT.txt) continues to apply to that historical code as required by its terms. Contributions ------------- Contributions to this repository require acceptance of the Contributor License Agreement in CLA.md. See CONTRIBUTING.md for details. Why GPL? -------- We want the best version of Serena to remain free. The GPL ensures that anyone who redistributes a derivative version of Serena must preserve the same software freedoms for its users. - pyproject.toml (14291 bytes)
[build-system] build-backend = "hatchling.build" requires = ["hatchling"] [project] name = "serena-agent" version = "2.1.1.dev0" description = "A powerful MCP toolkit for coding, providing semantic retrieval and editing capabilities - the IDE for your agent" authors = [{ name = "Oraios AI", email = "[email protected]" }] readme = "README.md" requires-python = ">=3.11, <3.15" license = "GPL-3.0-or-later" license-files = ["LICENSE", "LICENSES/*"] classifiers = [ "Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.13", "Programming Language :: Python :: 3.14", ] dependencies = [ "requests==2.33.0", "overrides==7.7.0", "python-dotenv==1.2.2", "mcp==2.2.0", "click==8.3.1", "flask==3.1.3", # bumped from 3.1.1 for CVE fix (also fixes werkzeug alert) "sensai-utils==1.5.0", "pydantic==2.12.5", "types-pyyaml==6.0.12.20250516", "pyyaml==6.0.2", "ruamel.yaml==0.18.14", "jinja2==3.1.6", "pathspec==0.12.1", "psutil==7.0.0", "docstring_parser==0.17.0", "joblib==1.5.1", "tqdm==4.67.1", "tiktoken==0.12.0", "anthropic==0.117.0", "beautifulsoup4==4.14.2", "pywebview==6.2", "pystray==0.19.5", "pygls==2.1.1", # used to implement an msl language server "lsprotocol==2025.0.0", # Transitive deps pinned for security (dependabot alerts). # Exact pins because uvx installs from git, ignoring the lock file. "urllib3==2.8.0", "werkzeug==3.1.7", "starlette==1.3.1", "python-multipart==0.0.31", "filelock==3.25.2", "cryptography==50.0.0", "regex==2026.2.28", "pythonnet==3.1.0 ; sys_platform == 'win32'", "oslex==2.0.0", "pillow==13.0.0", "anyio==4.14.2", "certifi==2026.10.18", ] [[tool.uv.index]] name = "testpypi" url = "https://test.pypi.org/simple/" publish-url = "https://test.pypi.org/legacy/" explicit = true [project.scripts] serena = "serena.cli:top_level" serena-agent = "serena.cli:top_level" serena-hooks = "serena.hooks:hook_commands" [project.optional-dependencies] dev = [ "jinja2==3.1.6", # In version 1.0.4 we get a NoneType error related to some config conversion (yml_analytics is None and should be a list) "ty==0.0.24", "poethepoet==0.36.0", "pytest==8.4.1", "pytest-xdist==3.8.0", "ruff==0.12.5", "toml-sort==0.24.2", "types-pyyaml==6.0.12.20250516", "syrupy==4.9.1", "types-requests==2.32.4.20250809", # docs "sphinx==7.4.7", "sphinx_rtd_theme==2.0.0", "sphinx_book_theme==1.1.4", "sphinx-toolbox==3.7.0", "jupyter-book==1.0.4.post1", "pyinstrument==5.1.1", "pytest-timeout==2.4.0", # Transitive dev deps pinned for security (dependabot alerts). # Exact pins because uvx installs from git, ignoring the lock file. "tornado==6.5.8", "wheel==0.46.3", "pyasn1==0.6.4", "PyJWT==2.13.0", ] agno = ["agno==2.6.6", "sqlalchemy==2.0.41"] # agno bumped for session state overwrite CVE google = ["google-genai==1.27.0"] [project.urls] Homepage = "https://github.com/oraios/serena" [tool.hatch.build.targets.wheel] packages = ["src/serena", "src/interprompt", "src/solidlsp"] [tool.doc8] max-line-length = 1000 [tool.ty.environment] python-version = "3.11" # We configure the oldest Python version supported by Serena # Analyze for all platforms rather than defaulting to the OS ty happens to run on. This keeps the # check deterministic across the CI matrix (Linux/Windows/macOS) and lets platform-conditional stdlib # members (e.g. subprocess.CREATE_NO_WINDOW, ctypes.windll, pwd) resolve without per-OS type-ignores. python-platform = "all" [tool.ty.rules] # Unresolvable imports do fail the type check (catching broken first-party imports); the exceptions for # optional extras and platform-specific modules are handled per file/line below. possibly-missing-submodule = "ignore" [tool.ty.src] # NOTE: test/resources is intentionally NOT excluded here. This config is also discovered by the ty # language server (used by the PYTHON_TY diagnostics provider) when it analyzes the sample fixture # repos under test/resources; excluding them here would suppress the diagnostics those tests rely on. # test/resources is instead excluded from the `ty check test` CLI task via its --exclude flag. exclude = ["build/", "docs/"] [[tool.ty.overrides]] # Modules whose imports cannot be resolved in the default dev environment: the agno integration depends # on the optional extra `agno`, and the pywebview integration imports macOS-only modules (AppKit, PyObjCTools) # in several places. Elsewhere, individual platform-specific imports are suppressed inline. include = ["src/serena/agno.py", "src/serena/util/pywebview.py"] [tool.ty.overrides.rules] unresolved-import = "ignore" [[tool.ty.overrides]] # Test code is heavily dynamic (pytest fixtures, MagicMock, intentionally loose Optionals). ty models # pytest's fail/skip helpers and MagicMock far more strictly than mypy did (mypy inferred `Any` for # these), which produces hundreds of diagnostics that are not real bugs. We therefore relax these # specific type rules for tests only, while still catching genuinely broken test code (undefined # names, syntax errors, unused type-ignore comments, etc.). The sample fixture repos under # test/resources are excluded so the ty language server still reports real diagnostics on them. include = ["test/**"] exclude = ["test/resources/"] [tool.ty.overrides.rules] invalid-argument-type = "ignore" invalid-key = "ignore" invalid-return-type = "ignore" no-matching-overload = "ignore" not-subscriptable = "ignore" parameter-already-assigned = "ignore" too-many-positional-arguments = "ignore" unsupported-operator = "ignore" [tool.poe.env] PYDEVD_DISABLE_FILE_VALIDATION = "1" [tool.poe.executor] # This is important when using poe with uv, because otherwise poe will try to run commands through # uv, which in turn will try to recreate the environment, which in turn will fail if any process # using the environment is already running! Naturally, processes using the env are running all the # time (e.g. a Serena MCP server), so using the default executor (uv) is not an option! type = "simple" [tool.poe.tasks] # For custom markers, use poe test -m ... test = "pytest test -vv" _ruff_check = "ruff check src scripts test" _ruff_format_check = "ruff format --check src scripts test" _ruff_fix = "ruff check --fix src scripts test" _ruff_format = "ruff format src scripts test" lint = ["_ruff_format_check", "_ruff_check"] format = ["_ruff_fix", "_ruff_format"] _ty_core = "ty check src/serena src/solidlsp" _ty_test = "ty check test --exclude test/resources" type-check = ["_ty_core", "_ty_test"] ty = ["type-check"] # docs _autogen_docs = "python docs/autogen_docs.py" _sphinx_build = "sphinx-build -b html docs docs/_build -W --keep-going" _jb_generate_toc = "python docs/create_toc.py" _jb_generate_config = "jupyter-book config sphinx docs/" doc-clean = "rm -rf docs/_build docs/03_api" doc-generate-files = ["_autogen_docs", "_jb_generate_toc", "_jb_generate_config"] doc-build = ["doc-clean", "doc-generate-files", "_sphinx_build"] [tool.ruff] target-version = "py311" line-length = 140 exclude = ["src/solidlsp/language_servers/**/static", "src/multilspy", "test/resources/repos"] [tool.ruff.format] quote-style = "double" indent-style = "space" line-ending = "auto" skip-magic-trailing-comma = false docstring-code-format = true [tool.ruff.lint] select = [ "ASYNC", "B", "C4", "C90", "COM", "D", "DTZ", "E", "F", "FLY", "G", "I", "ISC", "PIE", "PLC", "PLE", "PLW", "RET", "RUF", "RSE", "SIM", "TID", "UP", "W", "YTT", ] ignore = [ "PLC0415", "RUF002", "RUF005", "RUF059", "SIM118", "SIM108", "E501", "E741", "B008", "B011", "B028", "D100", "D101", "D102", "D103", "D104", "D105", "D107", "D200", "D203", "D213", "D401", "D402", "DTZ005", "E402", "E501", "E701", "E731", "C408", "E203", "G004", "RET505", "D106", "D205", "D212", "PLW2901", "B027", "D404", "D407", "D408", "D409", "D400", "D415", "COM812", "RET503", "RET504", "F403", "F405", "C401", "C901", "ASYNC230", "ISC003", "B024", "B007", "SIM102", "W291", "W293", "B009", "SIM103", # forbids multiple returns "SIM110", # requires use of any(...) instead of for-loop "G001", # forbids str.format in log statements "E722", # forbids unspecific except clause "SIM105", # forbids empty/general except clause "SIM113", # wants to enforce use of enumerate "E712", # forbids equality comparison with True/False "UP007", # forbids some uses of Union "TID252", # forbids relative imports "B904", # forces use of raise from other_exception "RUF012", # forbids mutable attributes as ClassVar "SIM117", # forbids nested with statements "C400", # wants to unnecessarily force use of list comprehension "UP037", # can incorrectly (!) convert quoted type to unquoted type, causing an error "UP045", # imposes T | None instead of Optional[T] "UP031", # forbids % operator to format strings "UP042", # wants str,Enum -> StrEnum (breaking change) "PLW0108", # unnecessary lambda (style preference) "PLC0207", # split vs rsplit optimization (style preference) "RSE102", # wants to force use of raise with class instead of instance (style preference) ] unfixable = ["F841", "F601", "F602", "B018"] extend-fixable = ["F401", "B905", "W291"] [tool.ruff.lint.mccabe] max-complexity = 20 [tool.ruff.lint.per-file-ignores] "tests/**" = ["D103"] "scripts/**" = ["D103"] # BSL integration tests deliberately contain Cyrillic identifiers (1C:Enterprise metadata # object names and procedure names). ruff's ambiguous-unicode rules flag every such char. "test/solidlsp/bsl/**" = ["RUF001", "RUF002", "RUF003"] [tool.pytest.ini_options] markers = [ "clojure: language server running for Clojure", "crystal: language server running for Crystal", "cue: language server running for CUE", "python: language server running for Python", "go: language server running for Go", "java: language server running for Java", "kotlin: language server running for kotlin", "groovy: language server running for Groovy", "rust: language server running for Rust", "typescript: language server running for TypeScript", "deno: language server running for Deno (uses the built-in deno lsp)", "svelte: language server running for Svelte (uses svelte-language-server)", "vue: language server running for Vue (uses TypeScript LSP)", "php: language server running for PHP", "perl: language server running for Perl", "csharp: language server running for C#", "vbnet: language server running for VB.NET", "elixir: language server running for Elixir", "elm: language server running for Elm", "terraform: language server running for Terraform", "swift: language server running for Swift", "bash: language server running for Bash", "r: language server running for R", "snapshot: snapshot tests for symbolic editing operations", "ruby: language server running for Ruby (uses ruby-lsp)", "zig: language server running for Zig", "lua: language server running for Lua", "luau: language server running for Luau", "nextflow: language server running for Nextflow", "nix: language server running for Nix", "dart: language server running for Dart", "erlang: language server running for Erlang", "ocaml: language server running for OCaml and Reason", "scala: language server running for Scala", "al: language server running for AL (Microsoft Dynamics 365 Business Central)", "fsharp: language server running for F#", "rego: language server running for Rego", "markdown: language server running for Markdown", "latex: language server running for LaTeX", "julia: Julia language server tests", "fortran: language server running for Fortran", "haskell: Haskell language server tests", "haxe: Haxe language server tests", "yaml: language server running for YAML", "json: language server running for JSON (uses vscode-json-languageserver)", "powershell: language server running for PowerShell", "pascal: language server running for Pascal (Free Pascal/Lazarus)", "cpp: language server running for C/C++", "slow: tests that require additional Expert instances and have long startup times (~60-90s each)", "toml: language server running for TOML", "matlab: language server running for MATLAB (requires MATLAB R2021b+)", "systemverilog: language server running for SystemVerilog (uses verible-verilog-ls)", "hlsl: language server running for HLSL shaders (uses shader-language-server)", "lean4: language server running for Lean 4", "solidity: language server running for Solidity (uses @nomicfoundation/solidity-language-server)", "ansible: language server running for Ansible (uses @ansible/ansible-language-server)", "msl: language server running for mSL (mIRC Scripting Language)", "bsl: language server running for BSL (1C:Enterprise / OneScript)", "html: language server running for HTML (vscode-html-language-server, used as companion by Angular)", "scss: language server running for SCSS / Sass / CSS (some-sass-language-server)", "angular: language server running for Angular (uses @angular/language-server + @angular/language-service tsserver plugin)", "ada: language server running for Ada / SPARK (uses AdaCore Ada Language Server)", "qml: language server running for QML (uses Qt's qmlls)", "gleam: language server running for Gleam (uses the Gleam compiler's bundled `gleam lsp`)", "wolfram: language server running for Wolfram Language (requires Mathematica 13.0+ or Wolfram Engine 12.1+)", "graphql: language server running for GraphQL (uses graphql-language-service-cli / graphql-lsp)", "astro: language server running for Astro (uses @astrojs/language-server)", ] [tool.codespell] # Ref: https://github.com/codespell-project/codespell#using-a-config-file # We skip third-party test fixture repositories entirely (they contain # external package lockfiles, minified code, and arbitrary dependency strings). skip = '.git*,*.svg,*.lock,*.min.*,*test_memories_manager.py,./test/resources/repos' check-hidden = true ignore-regex = '\.\w+' ignore-words-list = 'paket,EDN,als,ue' - README-dev.md (1955 bytes)
# Developer Instructions ## Python Environment & Development Tools See [the contributing guide](CONTRIBUTING.md) for instructions on setting up your development environment and tools for formatting and type checking. ## Release Process 1. Ensure clean git status. 2. Set the version for release. Normally, the version to be released is the one already reserved by the current `.dev0` version (e.g. `1.8.0` when the repository is at `1.8.0.dev0`): python scripts/bump_version.py release current To release a version beyond the reserved one, name the part to bump instead, e.g. python scripts/bump_version.py release patch python scripts/bump_version.py release minor This updates `CHANGELOG.md`, commits the release version, creates the git tag, and then commits the subsequent `.dev0` version for the next iteration. 3. Push to GitHub: git push git push --tags Important: This must push a single tag only! Pushing the single tag triggers the `create-release` workflow for the tag, which creates a **draft release** on GitHub. 4. Review the draft release on the [GitHub Releases page](https://github.com/oraios/serena/releases). When ready, publish it (click *Publish release*). This triggers the `publish` workflow, which builds and publishes the package to PyPI. ### Bumping the Development Version Independently of a release, the development version can be bumped, e.g. when work on `main` begins to target a new minor or major version: python scripts/bump_version.py dev minor python scripts/bump_version.py dev major This sets the version to the respective new `.dev0` version (e.g. `1.8.0.dev0`) and commits it as "Set version to vX"; it creates no tag and does not modify `CHANGELOG.md`. The subsequent release of that version is then performed with `release current`. Both commands require a clean git status and support `--dry-run` to preview the changes. - README.md (15472 bytes)
<p align="center" style="text-align:center;"> <img src="resources/serena-logo.svg#gh-light-mode-only" style="width:500px"> <img src="resources/serena-logo-dark-mode.svg#gh-dark-mode-only" style="width:500px"> </p> <h3 align="center"> The IDE for Your Coding Agent </h3> <div align="center"> <a href="https://discord.com/invite/cVUNQmnV4r"><img src="https://img.shields.io/badge/discord-join-5865F2?style=flat-square&labelColor=0a0e14&logo=discord&logoColor=5865F2" alt="discord"></a> <a href="https://github.com/oraios/serena/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-GPL--3.0--or--later-b0e8ff?style=flat-square&labelColor=0a0e14" alt="license: GPL-3.0-or-later"></a> </div> <br> * Serena provides essential **semantic code retrieval, editing, refactoring and debugging tools** that are akin to an IDE's capabilities, operating at the symbol level and exploiting relational structure. * It integrates with any client/LLM via the model context protocol (**MCP**). Serena's **agent-first tool design** involves robust high-level abstractions, distinguishing it from approaches that rely on low-level concepts like line numbers or primitive search patterns. Practically, this means that your agent operates **faster, more efficiently and more reliably**, especially in larger and more complex codebases. > [!TIP] > Serena v2 with the new **REPL-based agent interface** has been released. > [Learn more](https://oraios.github.io/serena/01-about/035_tools.html#serena-s-repl-code-execution-based-interface) > about the new interface and how to [configure it](https://oraios.github.io/serena/02-usage/050_configuration.html#agent-interfaces). ## Video <a href="https://www.youtube.com/watch?v=5QN7gN1KYLA"><img src="resources/serena-video-placeholder.png" style="width:500px"></a> ## What Our "End Users" Say While it is humans who download and set up Serena, our end users are essentially AI agents. As the ones actually applying Serena's tools, they are in the best position to evaluate Serena. We crafted an unbiased evaluation prompt that leads the agent to perform ~20 routine coding tasks, representative of everyday development work, in order to estimate the value added by Serena's tools when used alongside its own built-ins. Here's a one-sentence summary of what the agents had to say: **Opus 4.6 (high) in Claude Code on a large Python codebase:** > "Serena's IDE-backed semantic tools are the single most impactful addition to my toolkit – cross-file renames, moves, and reference lookups that would cost me 8–12 careful, error-prone steps collapse into one atomic call, and I would absolutely ask any developer I work with to set them up." **GPT 5.4 (high) in Codex CLI on a Java codebase:** > "As a coding AI agent, I would ask my owner to add Serena because it gives me the missing IDE-level understanding of symbols, references, and refactorings, turning fragile text surgery into calmer, faster, more confident code changes where semantics matter." **GPT 5.4 (medium) in Copilot CLI on a large, multi-language monorepo:** > "As a coding agent, I’d absolutely ask my owner to add Serena because it makes me noticeably sharper and calmer on real code – especially symbol-aware navigation, cross-file refactors, and monorepo dependency jumps – while I still lean on built-ins for tiny text edits and non-code work." Different agents in different settings independently converge on the same verdict. _Give your agent the tools it has been asking for and add Serena MCP to your client!_ See our [documentation](https://oraios.github.io/serena/04-evaluation/000_evaluation-intro.html) for the full methodology and much more detailed evaluation results, or run your own evaluation on a project of your choice. ## How Serena Works Serena provides the necessary [tools](https://oraios.github.io/serena/01-about/035_tools.html) for coding workflows, but an LLM is required to do the actual work, orchestrating tool use. Serena can extend the functionality of your existing AI client via the **model context protocol (MCP)**. Most modern AI chat clients directly support MCP, including * terminal-based clients like Claude Code, Codex, OpenCode, or Gemini-CLI, * IDEs and IDE assistant plugins for VSCode, Cursor and JetBrains IDEs (Copilot, Junie, JetBrains AI Assistant, etc.), * desktop and web clients like Claude Desktop, Codex App, or OpenWebUI. <img src="resources/serena-block-diagram.svg"> :tv: See also: [Introduction to Serena in 5 Minutes (YouTube)](https://www.youtube.com/watch?v=5QN7gN1KYLA) To connect the Serena MCP server to your client, you either * provide the client with a launch command that allows it to start the MCP server, or * start the Serena MCP server yourself in HTTP mode and provide the client with the URL. See the [Quick Start](#quick-start) section below for information on how to get started. ## Programming Language Support & Semantic Analysis Capabilities Serena provides a set of versatile code querying and editing functionalities based on symbolic understanding of the code. Equipped with these capabilities, your agent discovers and edits code just like a seasoned developer making use of an IDE's capabilities would. Serena can efficiently find the right context and do the right thing even in very large and complex projects! There are two alternative technologies powering these capabilities: * **Language servers** implementing the language server protocol (LSP) — the free/open-source alternative which is used by default. * **The Serena JetBrains Plugin**, which leverages the powerful code analysis and editing capabilities of your JetBrains IDE (paid plugin; free trial available). You can choose either of these backends depending on your preferences and requirements. ### Language Servers Serena incorporates a powerful abstraction layer for the integration of language servers that implement the language server protocol (LSP). The underlying language servers are typically open-source projects or at least freely available for use. When using Serena's language server backend, we provide **support for over 40 programming languages**, including Ada / SPARK, AL, Angular, Ansible, Astro, Bash, BSL, C#, C/C++, Clojure, Crystal, CUE, Dart, Deno, Elixir, Elm, Erlang, Fortran, F#, GDScript, Gleam, GLSL, Go, GraphQL, Groovy, Haskell, Haxe, HLSL, HTML, Java, JavaScript, JSON, Julia, Kotlin, LaTeX, Lean 4, Lua, Luau, Markdown, MATLAB, mSL, Nextflow, Nix, OCaml, Pascal, Perl, PHP, PowerShell, Python, QML, R, Rego, Ruby, Rust, Scala, SCSS / Sass / CSS, Solidity, Svelte, Swift, SystemVerilog, Terraform, TOML, TypeScript, VB.NET, Vue, WGSL, Wolfram Language, YAML, and Zig. ### The Serena JetBrains Plugin The paid Serena JetBrains Plugin (free trial available) leverages the powerful code analysis capabilities of your JetBrains IDE. The plugin naturally supports all programming languages and frameworks that are supported by JetBrains IDEs, including IntelliJ IDEA, PyCharm, Android Studio, WebStorm, PhpStorm, RubyMine, GoLand, and potentially others (Rider and CLion are unsupported though). <a href="https://plugins.jetbrains.com/plugin/28946-serena/"><img src="docs/_static/images/jetbrains-marketplace-button.png"></a> See our [documentation page](https://oraios.github.io/serena/02-usage/025_jetbrains_plugin.html) for further details and instructions on how to apply the plugin. ## Features Serena provides a wide range of tools for efficient code retrieval, editing and refactoring, as well as a memory system for long-lived agent workflows. Given its large scope, Serena adapts to your needs by offering a multi-layered configuration system. <details> <summary>Details</summary> ### Retrieval Serena's retrieval tools allow agents to explore codebases at the symbol level, understanding structure and relationships without reading entire files. | Capability | Language Servers | JetBrains Plugin | |----------------------------------|------------------|------------------| | find symbol | yes | yes | | symbol overview (file outline) | yes | yes | | find referencing symbols | yes | yes | | search in project dependencies | -- | yes | | type hierarchy | -- | yes | | find declaration | yes* | yes | | find implementations | yes** | yes | | query external projects | yes | yes | | diagnostics/inspections | yes | yes | *: Will generally not work for declarations in external dependencies. <br> **: Only available for some languages, limited by the language server functionality. ### Refactoring Without precise refactoring tools, agents are forced to resort to unreliable and expensive search and replace operations. | Capability | Language Servers | JetBrains Plugin | |-------------------------------------------|--------------------|-----------------------------------| | rename | yes (only symbols) | yes (symbols, files, directories) | | move (symbol, file, directory) | -- | yes | | inline | -- | yes | | propagate deletions (remove unused code) | -- | yes | ### Symbolic Editing Serena's symbolic editing tools are less error-prone and much more token-efficient than typical alternatives. | Capability | Language Servers | JetBrains Plugin | |------------------------|-------------------|------------------| | replace symbol body | yes | yes | | insert after symbol | yes | yes | | insert before symbol | yes | yes | | safe delete | yes | yes | ### Interactive Debugging Exclusive to the JetBrains plugin, Serena supports a highly general debugging tool, which allows an agent to set breakpoints, inspect variables, evaluate expressions and control execution flow via a persistent REPL-style interface. ### Basic Features Beyond its semantic capabilities, Serena includes a set of basic utilities for completeness. When Serena is used inside an agentic harness such as Claude Code or Codex, these tools are typically disabled by default, since the surrounding harness already provides overlapping file, search, and shell capabilities. - **`search_for_pattern`** – flexible regex search across the codebase - **`replace_content`** – agent-optimised regex-based and literal text replacement - **`list_dir` / `find_file`** – directory listing and file search - **`read_file`** – read files or file chunks - **`execute_shell_command`** – run shell commands (e.g. builds, tests, linters) ### Memory Management A memory system is elemental to long-lived agent workflows, especially when knowledge is to be shared across sessions, users and projects. Despite its simplicity, we received positive feedback from many users who tend to combine Serena's memory management system with their agent's internal system (e.g., `AGENTS.md` files). It can easily be disabled if you prefer to use something else. ### Configurability Active tools, tool descriptions, prompts, language backend details and many other aspects of Serena can be flexibly configured on a per-case basis by simply adjusting a few lines of YAML. To achieve this, Serena offers multiple levels of (composable) configuration: * global configuration * MCP launch command (CLI) configuration * per-project configuration (with local overrides) * execution context-specific configuration (e.g. for particular clients) * dynamically composable configuration fragments (modes) </details> ## Quick Start > [!IMPORTANT] > Do not install Serena via an MCP or plugin marketplace! They contain outdated and suboptimal installation commands. **Prerequisites**. Serena is managed by *uv*, and [installing uv](https://docs.astral.sh/uv/getting-started/installation/) is the only required prerequisite. **Install Serena**. Serena is installed via uv as follows: ```bash uv tool install -p 3.13 serena-agent ``` After successful installation, the command `serena` should be available in your shell. > [!NOTE] > When using the language server backend, some additional dependencies may need to be installed to support certain languages; > see the [Language Support](https://oraios.github.io/serena/01-about/020_programming-languages.html) page for details. **Initialise Serena**. To initialise Serena and verify that your setup works correctly, simply run: ```bash serena init ``` By default, this will set up Serena to use the language server backend. To use the JetBrains backend instead, add the parameters `-b JetBrains` (see the [JetBrains Plugin documentation page](https://oraios.github.io/serena/02-usage/025_jetbrains_plugin.html) for additional usage details). Either way, you should receive a success message indicating that Serena has been initialised successfully. **Configuring Your Client**. To connect Serena to your preferred MCP client, you typically need to [configure a launch command in your client](https://oraios.github.io/serena/02-usage/030_clients.html). Follow the link for specific instructions on how to set up Serena for Claude Code, Codex, Claude Desktop, MCP-enabled IDEs and other clients (such as local and web-based GUIs). > [!TIP] > While getting started quickly is easy, Serena is a powerful toolkit with many configuration options. > We highly recommend reading through the [user guide](https://oraios.github.io/serena/02-usage/000_intro.html) to get the most out of Serena. > > Specifically, we recommend to read about ... > * [Serena's project-based workflow](https://oraios.github.io/serena/02-usage/040_workflow.html) and > * [configuring Serena](https://oraios.github.io/serena/02-usage/050_configuration.html). ## User Guide Please refer to the [user guide](https://oraios.github.io/serena/02-usage/000_intro.html) for detailed instructions on how to use Serena effectively. ## Partner Offerings <a href="https://infistar.cc/register?aff=SERENA&ref_source=link"><img src="resources/infistar.png" alt="Infistar"></a> ## Acknowledgements A significant part of Serena, especially support for various languages, was contributed by the open source community. We are very grateful for the many contributors who made this possible and who played an important role in making Serena what it is today. ## License Serena is licensed per component: **SolidLSP** (`src/solidlsp`) under the [MIT License](LICENSES/MIT.txt), the **Serena applicat - repo_dir_sync.py (15260 bytes)
# -*- coding: utf-8 -*- import glob import os import shutil from subprocess import Popen, PIPE import re import sys from typing import List, Optional, Sequence import platform def popen(cmd): shell = platform.system() != "Windows" p = Popen(cmd, shell=shell, stdin=PIPE, stdout=PIPE) return p def call(cmd): p = popen(cmd) return p.stdout.read().decode("utf-8") def execute(cmd, exceptionOnError=True): """ :param cmd: the command to execute :param exceptionOnError: if True, raise on exception on error (return code not 0); if False return whether the call was successful :return: True if the call was successful, False otherwise (if exceptionOnError==False) """ p = popen(cmd) p.wait() success = p.returncode == 0 if exceptionOnError: if not success: raise Exception("Command failed: %s" % cmd) else: return success def gitLog(path, arg): oldPath = os.getcwd() os.chdir(path) lg = call("git log --no-merges " + arg) os.chdir(oldPath) return lg def gitCommit(msg): with open(COMMIT_MSG_FILENAME, "wb") as f: f.write(msg.encode("utf-8")) gitCommitWithMessageFromFile(COMMIT_MSG_FILENAME) def gitCommitWithMessageFromFile(commitMsgFilename): if not os.path.exists(commitMsgFilename): raise FileNotFoundError(f"{commitMsgFilename} not found in {os.path.abspath(os.getcwd())}") os.system(f"git commit --file={commitMsgFilename}") os.unlink(commitMsgFilename) COMMIT_MSG_FILENAME = "commitmsg.txt" class OtherRepo: SYNC_COMMIT_ID_FILE_LIB_REPO = ".syncCommitId.remote" SYNC_COMMIT_ID_FILE_THIS_REPO = ".syncCommitId.this" SYNC_COMMIT_MESSAGE = f"Updated %s sync commit identifiers" SYNC_BACKUP_DIR = ".syncBackup" def __init__(self, name, branch, pathToLib): self.pathToLibInThisRepo = os.path.abspath(pathToLib) if not os.path.exists(self.pathToLibInThisRepo): raise ValueError(f"Repository directory '{self.pathToLibInThisRepo}' does not exist") self.name = name self.branch = branch self.libRepo: Optional[LibRepo] = None def isSyncEstablished(self): return os.path.exists(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO)) def lastSyncIdThisRepo(self): with open(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_THIS_REPO), "r") as f: commitId = f.read().strip() return commitId def lastSyncIdLibRepo(self): with open(os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO), "r") as f: commitId = f.read().strip() return commitId def gitLogThisRepoSinceLastSync(self): lg = gitLog(self.pathToLibInThisRepo, '--name-only HEAD "^%s" .' % self.lastSyncIdThisRepo()) lg = re.sub(r'commit [0-9a-z]{8,40}\n.*\n.*\n\s*\n.*\n\s*(\n.*\.syncCommitId\.(this|remote))+', r"", lg, flags=re.MULTILINE) # remove commits with sync commit id update indent = " " lg = indent + lg.replace("\n", "\n" + indent) return lg def gitLogLibRepoSinceLastSync(self, libRepo: "LibRepo"): syncIdFile = os.path.join(self.pathToLibInThisRepo, self.SYNC_COMMIT_ID_FILE_LIB_REPO) if not os.path.exists(syncIdFile): return "" with open(syncIdFile, "r") as f: syncId = f.read().strip() lg = gitLog(libRepo.libPath, '--name-only HEAD "^%s" .' % syncId) lg = re.sub(r"Sync (\w+)\n\s*\n", r"Sync\n\n", lg, flags=re.MULTILINE) indent = " " lg = indent + lg.replace("\n", "\n" + indent) return "\n\n" + lg def _userInputYesNo(self, question) -> bool: result = None while result not in ("y", "n"): result = input(question + " [y|n]: ").strip() return result == "y" def pull(self, libRepo: "LibRepo"): """ Pulls in changes from this repository into the lib repo """ # switch to branch in lib repo os.chdir(libRepo.rootPath) execute("git checkout %s" % self.branch) # check if the branch contains the commit that is referenced as the remote commit remoteCommitId = self.lastSyncIdLibRepo() remoteCommitExists = execute("git rev-list HEAD..%s" % remoteCommitId, exceptionOnError=False) if not remoteCommitExists: if not self._userInputYesNo(f"\nWARNING: The referenced remote commit {remoteCommitId} does not exist " f"in your {self.libRepo.name} branch '{self.branch}'!\nSomeone else may have " f"pulled/pushed in the meantime.\nIt is recommended that you do not continue. " f"Continue?"): return # check if this branch is clean lgLib = self.gitLogLibRepoSinceLastSync(libRepo).strip() if lgLib != "": print(f"The following changes have been added to this branch in the library:\n\n{lgLib}\n\n") print(f"ERROR: You must push these changes before you can pull or reset this branch to {remoteCommitId}") sys.exit(1) # get log with relevant commits in this repo that are to be pulled lg = self.gitLogThisRepoSinceLastSync() os.chdir(libRepo.rootPath) # create commit message file commitMsg = f"Sync {self.name}\n\n" + lg with open(COMMIT_MSG_FILENAME, "w") as f: f.write(commitMsg) # ask whether to commit these changes print("Relevant commits:\n\n" + lg + "\n\n") if not self._userInputYesNo(f"The above changes will be pulled from {self.name}.\n" f"You may change the commit message by editing {os.path.abspath(COMMIT_MSG_FILENAME)}.\n" "Continue?"): os.unlink(COMMIT_MSG_FILENAME) return # prepare restoration of ignored files self.prepare_restoration_of_ignored_files(libRepo.rootPath) # remove library tree in lib repo shutil.rmtree(self.libRepo.libDirectory) # copy tree from this repo to lib repo (but drop the sync commit id files) shutil.copytree(self.pathToLibInThisRepo, self.libRepo.libDirectory) for fn in (self.SYNC_COMMIT_ID_FILE_LIB_REPO, self.SYNC_COMMIT_ID_FILE_THIS_REPO): p = os.path.join(self.libRepo.libDirectory, fn) if os.path.exists(p): os.unlink(p) # restore ignored directories/files self.restore_ignored_files(libRepo.rootPath) # make commit in lib repo os.system("git add %s" % self.libRepo.libDirectory) gitCommitWithMessageFromFile(COMMIT_MSG_FILENAME) newSyncCommitIdLibRepo = call("git rev-parse HEAD").strip() # update commit ids in this repo os.chdir(self.pathToLibInThisRepo) newSyncCommitIdThisRepo = call("git rev-parse HEAD").strip() with open(self.SYNC_COMMIT_ID_FILE_LIB_REPO, "w") as f: f.write(newSyncCommitIdLibRepo) with open(self.SYNC_COMMIT_ID_FILE_THIS_REPO, "w") as f: f.write(newSyncCommitIdThisRepo) execute('git add %s %s' % (self.SYNC_COMMIT_ID_FILE_LIB_REPO, self.SYNC_COMMIT_ID_FILE_THIS_REPO)) execute(f'git commit -m "{self.SYNC_COMMIT_MESSAGE % self.libRepo.name} (pull)"') print(f"\n\nIf everything was successful, you should now push your changes to branch " f"'{self.branch}'\nand get your branch merged into develop (issuing a pull request where appropriate)") def push(self, libRepo: "LibRepo"): """ Pushes changes from the lib repo to this repo """ os.chdir(libRepo.rootPath) # switch to the source repo branch execute(f"git checkout {self.branch}") if self.isSyncEstablished(): # check if there are any commits that have not yet been pulled unpulledCommits = self.gitLogThisRepoSinceLastSync().strip() if unpulledCommits != "": print(f"\n{unpulledCommits}\n\n") if not self._userInputYesNo(f"WARNING: The above changes in repository '{self.name}' have not" f" yet been pulled.\nYou might want to pull them.\n" f"If you continue with the push, they will be lost. Continue?"): return # get change log in lib repo since last sync libLogSinceLastSync = self.gitLogLibRepoSinceLastSync(libRepo) print("Relevant commits:\n\n" + libLogSinceLastSync + "\n\n") if not self._userInputYesNo("The above changes will be pushed. Continue?"): return print() else: libLogSinceLastSync = "" # prepare restoration of ignored files in target repo base_dir_this_repo = os.path.join(self.pathToLibInThisRepo, "..") self.prepare_restoration_of_ignored_files(base_dir_this_repo) # remove the target repo tree and update it with the tree from the source repo shutil.rmtree(self.pathToLibInThisRepo) shutil.copytree(libRepo.libPath, self.pathToLibInThisRepo) # get the commit id of the source repo we just copied commitId = call("git rev-parse HEAD").strip() # restore ignored directories and files self.restore_ignored_files(base_dir_this_repo) # go to the target repo os.chdir(self.pathToLibInThisRepo) # commit new version in this repo execute("git add .") with open(self.SYNC_COMMIT_ID_FILE_LIB_REPO, "w") as f: f.write(commitId) execute("git add %s" % self.SYNC_COMMIT_ID_FILE_LIB_REPO) gitCommit(f"{self.libRepo.name} {commitId}" + libLogSinceLastSync) commitId = call("git rev-parse HEAD").strip() # update information on the commit id we just added with open(self.SYNC_COMMIT_ID_FILE_THIS_REPO, "w") as f: f.write(commitId) execute("git add %s" % self.SYNC_COMMIT_ID_FILE_THIS_REPO) execute(f'git commit -m "{self.SYNC_COMMIT_MESSAGE % self.libRepo.name} (push)"') os.chdir(libRepo.rootPath) print(f"\n\nIf everything was successful, you should now update the remote branch:\ngit push") def prepare_restoration_of_ignored_files(self, base_dir: str): """ :param base_dir: the directory containing the lib directory, to which ignored paths are relative """ cwd = os.getcwd() os.chdir(base_dir) # ensure backup dir exists and is empty if os.path.exists(self.SYNC_BACKUP_DIR): shutil.rmtree(self.SYNC_BACKUP_DIR) os.mkdir(self.SYNC_BACKUP_DIR) # backup ignored, unversioned directories for d in self.libRepo.fullyIgnoredUnversionedDirectories: if os.path.exists(d): shutil.copytree(d, os.path.join(self.SYNC_BACKUP_DIR, d)) os.chdir(cwd) def restore_ignored_files(self, base_dir: str): """ :param base_dir: the directory containing the lib directory, to which ignored paths are relative """ cwd = os.getcwd() os.chdir(base_dir) # remove fully ignored directories that were overwritten by the sync for d in self.libRepo.fullyIgnoredVersionedDirectories + self.libRepo.fullyIgnoredUnversionedDirectories: if os.path.exists(d): print("Removing overwritten content: %s" % d) shutil.rmtree(d) # restore directories and files that can be restored via git for d in self.libRepo.ignoredDirectories + self.libRepo.fullyIgnoredVersionedDirectories: restoration_cmd = "git checkout %s" % d print("Restoring: %s" % restoration_cmd) os.system(restoration_cmd) for pattern in self.libRepo.ignoredFileGlobPatterns: for path in glob.glob(pattern, recursive=True): print("Restoring via git: %s" % path) os.system("git checkout %s" % path) # restore directories that were backed up for d in self.libRepo.fullyIgnoredUnversionedDirectories: if os.path.exists(os.path.join(self.SYNC_BACKUP_DIR, d)): print("Restoring from backup: %s" % d) shutil.copytree(os.path.join(self.SYNC_BACKUP_DIR, d), d) # remove backup dir shutil.rmtree(self.SYNC_BACKUP_DIR) os.chdir(cwd) class LibRepo: def __init__(self, name: str, libDirectory: str, ignoredDirectories: Sequence[str] = (), fullyIgnoredVersionedDirectories: Sequence[str] = (), fullyIgnoredUnversionedDirectories: Sequence[str] = (), ignoredFileGlobPatterns: Sequence[str] = () ): """ :param name: name of the library being synced :param libDirectory: relative path to the library directory within this repo :param ignoredDirectories: ignored directories; existing files in ignored directories will be restored via 'git checkout' on pull/push, but new files will be added. This is useful for configuration-like files, where users may have local changes that should not be overwritten, but new files should still be added. :param fullyIgnoredVersionedDirectories: fully ignored versioned directories will be restored to original state after push/pull via git checkout :param fullyIgnoredUnversionedDirectories: fully ignored unversioned directories will be backed up and restored to original state after push/pull :param ignoredFileGlobPatterns: files matching ignored glob patterns will be restored via 'git checkout' on pull/push """ self.name = name self.rootPath = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) self.libDirectory = libDirectory self.libPath = os.path.join(self.rootPath, self.libDirectory) self.ignoredDirectories: List[str] = list(ignoredDirectories) self.fullyIgnoredVersionedDirectories: List[str] = list(fullyIgnoredVersionedDirectories) self.fullyIgnoredUnversionedDirectories: List[str] = list(fullyIgnoredUnversionedDirectories) self.ignoredFileGlobPatterns: List[str] = list(ignoredFileGlobPatterns) self.otherRepos: List[OtherRepo] = [] def add(self, repo: OtherRepo): repo.libRepo = self self.otherRepos.append(repo) def runMain(self): repos = self.otherRepos args = sys.argv[1:] if len(args) != 2: print(f"usage: sync.py <{'|'.join([repo.name for repo in repos])}> <push|pull>") else: repo = [r for r in repos if r.name == args[0]] if len(repo) != 1: raise ValueError(f"Unknown repo - server.json (1520 bytes)
{ "$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json", "name": "io.github.oraios/serena", "title": "Serena MCP: the IDE for your agent", "description": "A powerful toolkit for coding, providing semantic retrieval and editing capabilities.", "version": "2.1.0", "repository": { "source": "github", "url": "https://github.com/oraios/serena" }, "packages": [ { "registryType": "pypi", "identifier": "serena-agent", "version": "2.1.0", "transport": { "type": "stdio" }, "runtimeHint": "uvx", "runtimeArguments": [ { "description": "Select the python version", "name": "-p", "value": "3.13", "type": "named" } ], "packageArguments": [ { "type": "positional", "value": "start-mcp-server" }, { "type": "positional", "value": "--project-from-cwd", "isRequired": false }, { "type": "named", "name": "--context", "isRequired": false, "default": "desktop-app", "description": "The name of a markdown file representing Serena's execution context, typically related to the executing client. Allowed values are: agent, antigravity, chatgpt, claude-code, codex, context.template, copilot-cli, desktop-app, ide, jb-ai-assistant, jb-copilot-plugin, junie, oaicompat-agent, vscode " } ] } ] } - src/interprompt/__init__.py (158 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from .prompt_factory import autogenerate_prompt_factory_module __all__ = ["autogenerate_prompt_factory_module"]
- src/interprompt/jinja_template.py (1666 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from typing import Any import jinja2 import jinja2.meta import jinja2.nodes import jinja2.visitor from jinja2.sandbox import SandboxedEnvironment from .util.class_decorators import singleton class ParameterizedTemplateInterface: def get_parameters(self) -> list[str]: ... @singleton class _JinjaEnvProvider: def __init__(self) -> None: self._env: jinja2.Environment | None = None def get_env(self) -> jinja2.Environment: if self._env is None: self._env = SandboxedEnvironment() return self._env class JinjaTemplate(ParameterizedTemplateInterface): def __init__(self, template_string: str) -> None: self._template_string = template_string self._template = _JinjaEnvProvider().get_env().from_string(self._template_string) parsed_content = self._template.environment.parse(self._template_string) self._parameters = sorted(jinja2.meta.find_undeclared_variables(parsed_content)) def get_template_string(self) -> str: return self._template_string def render(self, **params: Any) -> str: """Renders the template with the given kwargs. You can find out which parameters are required by calling get_parameter_names().""" return self._template.render(**params) def get_parameters(self) -> list[str]: """A sorted list of parameter names that are extracted from the template string. It is impossible to know the types of the parameter values, they can be primitives, dicts or dict-like objects. :return: the list of parameter names """ return self._parameters - src/interprompt/multilang_prompt.py (17639 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import os from enum import Enum from typing import Any, Generic, Literal, TypeVar import yaml from sensai.util.string import ToStringMixin from .jinja_template import JinjaTemplate, ParameterizedTemplateInterface log = logging.getLogger(__name__) class PromptTemplate(ToStringMixin, ParameterizedTemplateInterface): def __init__(self, name: str, jinja_template_string: str, path: str) -> None: self.name = name self.path = path self._jinja_template = JinjaTemplate(jinja_template_string.strip()) def _tostring_exclude_private(self) -> bool: return True def get_template_string(self) -> str: return self._jinja_template.get_template_string() def render(self, **params: Any) -> str: return self._jinja_template.render(**params) def get_parameters(self) -> list[str]: return self._jinja_template.get_parameters() class PromptList: def __init__(self, items: list[str]) -> None: self.items = [x.strip() for x in items] def to_string(self) -> str: bullet = " * " indent = " " * len(bullet) items = [x.replace("\n", "\n" + indent) for x in self.items] return "\n * ".join(items) T = TypeVar("T") DEFAULT_LANG_CODE = "default" class LanguageFallbackMode(Enum): """ Defines what to do if there is no item for the given language. """ ANY = "any" """ Return the item for any language (the first one found) """ EXCEPTION = "exception" """ If the requested language is not found, raise an exception """ USE_DEFAULT_LANG = "use_default_lang" """ If the requested language is not found, use the default language """ class _MultiLangContainer(Generic[T], ToStringMixin): """ A container of items (usually, all having the same semantic meaning) which are associated with different languages. Can also be used for single-language purposes by always using the default language code. """ def __init__(self, name: str) -> None: self.name = name self._lang2item: dict[str, T] = {} """Maps language codes to items""" def _tostring_excludes(self) -> list[str]: return ["lang2item"] def _tostring_additional_entries(self) -> dict[str, Any]: return dict(languages=list(self._lang2item.keys())) def get_language_codes(self) -> list[str]: """The language codes for which items are registered in the container.""" return list(self._lang2item.keys()) def add_item(self, item: T, lang_code: str = DEFAULT_LANG_CODE, allow_overwrite: bool = False) -> None: """Adds an item to the container, representing the same semantic entity as the other items in the container but in a different language. :param item: the item to add :param lang_code: the language shortcode for which to add the item. Use the default for single-language use cases. :param allow_overwrite: if True, allow overwriting an existing entry for the same language """ if not allow_overwrite and lang_code in self._lang2item: raise KeyError(f"Item for language '{lang_code}' already registered for name '{self.name}'") self._lang2item[lang_code] = item def has_item(self, lang_code: str = DEFAULT_LANG_CODE) -> bool: return lang_code in self._lang2item def get_item(self, lang: str = DEFAULT_LANG_CODE, fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION) -> T: """ Gets the item for the given language. :param lang: the language shortcode for which to obtain the prompt template. A default language can be specified. :param fallback_mode: defines what to do if there is no item for the given language :return: the item """ try: return self._lang2item[lang] except KeyError as outer_e: if fallback_mode == LanguageFallbackMode.EXCEPTION: raise KeyError(f"Item for language '{lang}' not found for name '{self.name}'") from outer_e if fallback_mode == LanguageFallbackMode.ANY: try: return next(iter(self._lang2item.values())) except StopIteration as e: raise KeyError(f"No items registered for any language in container '{self.name}'") from e if fallback_mode == LanguageFallbackMode.USE_DEFAULT_LANG: try: return self._lang2item[DEFAULT_LANG_CODE] except KeyError as e: raise KeyError( f"Item not found neither for {lang=} nor for the default language '{DEFAULT_LANG_CODE}' in container '{self.name}'" ) from e def __len__(self) -> int: return len(self._lang2item) class MultiLangPromptTemplate(ParameterizedTemplateInterface): """ Represents a prompt template with support for multiple languages. The parameters of all prompt templates (for all languages) are (must be) the same. """ def __init__(self, name: str) -> None: self._prompts_container = _MultiLangContainer[PromptTemplate](name) def __len__(self) -> int: return len(self._prompts_container) @property def name(self) -> str: return self._prompts_container.name def add_prompt_template( self, prompt_template: PromptTemplate, lang_code: str = DEFAULT_LANG_CODE, allow_overwrite: bool = False ) -> None: """ Adds a prompt template for a new language. The parameters of all prompt templates (for all languages) are (must be) the same, so if a prompt template is already registered, the parameters of the new prompt template should be the same as the existing ones. :param prompt_template: the prompt template to add :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. :param allow_overwrite: whether to allow overwriting an existing entry for the same language """ incoming_parameters = prompt_template.get_parameters() if len(self) > 0: parameters = self.get_parameters() if parameters != incoming_parameters: raise ValueError( f"Cannot add prompt template for language '{lang_code}' to MultiLangPromptTemplate '{self.name}'" f"because the parameters are inconsistent: {parameters} vs {prompt_template.get_parameters()}" ) self._prompts_container.add_item(prompt_template, lang_code, allow_overwrite) def get_prompt_template( self, lang_code: str = DEFAULT_LANG_CODE, fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION ) -> PromptTemplate: return self._prompts_container.get_item(lang_code, fallback_mode) def get_parameters(self) -> list[str]: if len(self) == 0: raise RuntimeError( f"No prompt templates registered for MultiLangPromptTemplate '{self.name}', make sure to register a prompt template before accessing the parameters" ) first_prompt_template = next(iter(self._prompts_container._lang2item.values())) return first_prompt_template.get_parameters() def render( self, params: dict[str, Any], lang_code: str = DEFAULT_LANG_CODE, fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION, ) -> str: prompt_template = self.get_prompt_template(lang_code, fallback_mode) return prompt_template.render(**params) def has_item(self, lang_code: str = DEFAULT_LANG_CODE) -> bool: return self._prompts_container.has_item(lang_code) class MultiLangPromptList(_MultiLangContainer[PromptList]): pass class MultiLangPromptCollection: """ Main class for managing a collection of prompt templates and prompt lists, with support for multiple languages. All data will be read from the yamls directly contained in the given directory on initialization. It is thus assumed that you manage one directory per prompt collection. The yamls are assumed to be either of the form ```yaml lang: <language_code> # optional, defaults to "default" prompts: <prompt_name>: <prompt_template_string> <prompt_list_name>: [<prompt_string_1>, <prompt_string_2>, ...] ``` When specifying prompt templates for multiple languages, make sure that the Jinja template parameters (inferred from the things inside the `{{ }}` in the template strings) are the same for all languages (you will get an exception otherwise). The prompt names must be unique (for the same language) within the collection. """ def __init__(self, prompts_dir: str | list[str], fallback_mode: LanguageFallbackMode = LanguageFallbackMode.EXCEPTION) -> None: """ :param prompts_dir: the directory containing the prompt templates and prompt lists. If a list is provided, will look for prompt templates in the dirs from left to right (first one containing the desired template wins). :param fallback_mode: the fallback mode to use when a prompt template or prompt list is not found for the requested language. May be reset after initialization. """ self._multi_lang_prompt_templates: dict[str, MultiLangPromptTemplate] = {} self._multi_lang_prompt_lists: dict[str, MultiLangPromptList] = {} if isinstance(prompts_dir, str): prompts_dir = [prompts_dir] # Add prompts from multiple directories, prioritizing names from the left. # If name collisions appear in the first directory, an error is raised (so the first directory should have no # internal collisions, this helps in avoiding errors) # For all following directories, on a collision the new value will be ignored. # This also means that for the following directories, there is no error check on collisions internal to them. # We assume that they are correct (i.e., they have no internal collisions). first_prompts_dir, fallback_prompt_dirs = prompts_dir[0], prompts_dir[1:] self._load_from_disc(first_prompts_dir, on_name_collision="raise") for fallback_prompt_dir in fallback_prompt_dirs: # already loaded prompts have priority self._load_from_disc(fallback_prompt_dir, on_name_collision="skip") self.fallback_mode = fallback_mode def _add_prompt_template( self, name: str, template_str: str, path: str, lang_code: str = DEFAULT_LANG_CODE, on_name_collision: Literal["skip", "overwrite", "raise"] = "raise", ) -> None: """ :param name: name of the prompt template :param template_str: the Jinja template string :param lang_code: the language code for which to add the prompt template. :param on_name_collision: how to deal with name/lang_code collisions """ allow_overwrite = False prompt_template = PromptTemplate(name, template_str, path=path) mlpt = self._multi_lang_prompt_templates.get(name) if mlpt is None: mlpt = MultiLangPromptTemplate(name) self._multi_lang_prompt_templates[name] = mlpt if mlpt.has_item(lang_code): if on_name_collision == "raise": raise KeyError(f"Prompt '{name}' for {lang_code} already exists!") if on_name_collision == "skip": log.debug(f"Skipping prompt '{name}' since it already exists.") return elif on_name_collision == "overwrite": allow_overwrite = True mlpt.add_prompt_template(prompt_template, lang_code=lang_code, allow_overwrite=allow_overwrite) def _add_prompt_list( self, name: str, prompt_list: list[str], lang_code: str = DEFAULT_LANG_CODE, on_name_collision: Literal["skip", "overwrite", "raise"] = "raise", ) -> None: """ :param name: name of the prompt list :param prompt_list: a list of prompts :param lang_code: the language code for which to add the prompt list. :param on_name_collision: how to deal with name/lang_code collisions """ allow_overwrite = False multilang_prompt_list = self._multi_lang_prompt_lists.get(name) if multilang_prompt_list is None: multilang_prompt_list = MultiLangPromptList(name) self._multi_lang_prompt_lists[name] = multilang_prompt_list if multilang_prompt_list.has_item(lang_code): if on_name_collision == "raise": raise KeyError(f"Prompt '{name}' for {lang_code} already exists!") if on_name_collision == "skip": log.debug(f"Skipping prompt '{name}' since it already exists.") return elif on_name_collision == "overwrite": allow_overwrite = True multilang_prompt_list.add_item(PromptList(prompt_list), lang_code=lang_code, allow_overwrite=allow_overwrite) def _load_from_disc(self, prompts_dir: str, on_name_collision: Literal["skip", "overwrite", "raise"] = "raise") -> None: """Loads all prompt templates and prompt lists from yaml files in the given directory. :param prompts_dir: :param on_name_collision: how to deal with name/lang_code collisions """ for fn in os.listdir(prompts_dir): if not fn.endswith((".yml", ".yaml")): log.debug(f"Skipping non-YAML file: {fn}") continue path = os.path.join(prompts_dir, fn) with open(path, encoding="utf-8") as f: data = yaml.safe_load(f) try: prompts_data = data["prompts"] except KeyError as e: raise KeyError(f"Invalid yaml structure (missing 'prompts' key) in file {path}") from e lang_code = data.get("lang", DEFAULT_LANG_CODE) # add the data to the collection for prompt_name, prompt_template_or_list in prompts_data.items(): if isinstance(prompt_template_or_list, list): self._add_prompt_list(prompt_name, prompt_template_or_list, lang_code=lang_code, on_name_collision=on_name_collision) elif isinstance(prompt_template_or_list, str): self._add_prompt_template( prompt_name, prompt_template_or_list, lang_code=lang_code, path=path, on_name_collision=on_name_collision ) else: raise ValueError( f"Invalid prompt type for {prompt_name} in file {path} (should be str or list): {prompt - src/interprompt/prompt_factory.py (4621 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import os from typing import Any from .multilang_prompt import DEFAULT_LANG_CODE, LanguageFallbackMode, MultiLangPromptCollection, PromptList, PromptTemplate log = logging.getLogger(__name__) class PromptFactoryBase: """Base class for auto-generated prompt factory classes.""" def __init__(self, prompts_dir: str | list[str], lang_code: str = DEFAULT_LANG_CODE, fallback_mode=LanguageFallbackMode.EXCEPTION): """ :param prompts_dir: the directory containing the prompt templates and prompt lists. If a list is provided, will look for prompt templates in the dirs from left to right (first one containing the desired template wins). :param lang_code: the language code to use for retrieving the prompt templates and prompt lists. Leave as `default` for single-language use cases. :param fallback_mode: the fallback mode to use when a prompt template or prompt list is not found for the requested language. Irrelevant for single-language use cases. """ self.lang_code = lang_code self._prompt_collection = MultiLangPromptCollection(prompts_dir, fallback_mode=fallback_mode) def get_prompt_names(self) -> list[str]: return self._prompt_collection.get_prompt_template_names() def get_prompt_template(self, prompt_name: str) -> PromptTemplate: return self._prompt_collection.get_prompt_template(prompt_name, lang_code=self.lang_code) def get_prompt_template_string(self, prompt_name: str) -> str: return self.get_prompt_template(prompt_name).get_template_string() def _render_prompt(self, prompt_name: str, params: dict[str, Any]) -> str: del params["self"] return self.get_prompt_template(prompt_name).render(**params) def _get_prompt_list(self, prompt_name: str) -> PromptList: return self._prompt_collection.get_prompt_list(prompt_name, self.lang_code) def autogenerate_prompt_factory_module( prompts_dir: str, target_module_path: str, interprompt_library_package: str = "interprompt", class_name: str = "PromptFactory" ) -> None: """ Auto-generates a prompt factory module for the given prompt directory. The generated `PromptFactory` class is meant to be the central entry class for retrieving and rendering prompt templates and prompt lists in your application. It will contain one method per prompt template and prompt list, and is useful for both single- and multi-language use cases. :param prompts_dir: the directory containing the prompt templates and prompt lists :param target_module_path: the path to the target module file (.py). Important: The module will be overwritten! :param interprompt_library_package: the package name of the interprompt library :param class_name: the name of the generated prompt factory class """ generated_code = f"""# ruff: noqa # black: skip # mypy: ignore-errors # NOTE: This module is auto-generated from interprompt.autogenerate_prompt_factory_module, do not edit manually! from {interprompt_library_package}.prompt_factory import * from typing import Any class {class_name}(PromptFactoryBase): \""" A class for retrieving and rendering prompt templates and prompt lists. \""" """ # ---- add methods based on prompt template names and parameters and prompt list names ---- prompt_collection = MultiLangPromptCollection(prompts_dir) for template_name in prompt_collection.get_prompt_template_names(): template_parameters = prompt_collection.get_prompt_template_parameters(template_name) if len(template_parameters) == 0: method_params_str = "" else: method_params_str = ", *, " + ", ".join([f"{param}: Any" for param in template_parameters]) generated_code += f""" def get_{template_name}_template_string(self) -> str: return self.get_prompt_template_string('{template_name}') def create_{template_name}(self{method_params_str}) -> str: return self._render_prompt('{template_name}', locals()) """ for prompt_list_name in prompt_collection.get_prompt_list_names(): generated_code += f""" def get_list_{prompt_list_name}(self) -> PromptList: return self._get_prompt_list('{prompt_list_name}') """ os.makedirs(os.path.dirname(target_module_path), exist_ok=True) with open(target_module_path, "w", encoding="utf-8") as f: f.write(generated_code) log.info(f"Prompt factory generated successfully in {target_module_path}") - src/interprompt/util/__init__.py (0 bytes)
- src/interprompt/util/class_decorators.py (333 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from typing import Any def singleton(cls: type[Any]) -> Any: instance = None def get_instance(*args: Any, **kwargs: Any) -> Any: nonlocal instance if instance is None: instance = cls(*args, **kwargs) return instance return get_instance - src/README.md (290 bytes)
Serena uses (modified) versions of other libraries/packages: * solidlsp (our fork of [microsoft/multilspy](https://github.com/microsoft/multilspy) for fully synchronous language server communication) * [interprompt](https://github.com/oraios/interprompt) (our prompt templating library)
- src/serena/__init__.py (816 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later __version__ = "2.1.1.dev0" import logging log = logging.getLogger(__name__) def serena_version() -> str: """ :return: the version of the package, including git status if available. """ from serena.util.git import get_git_status version = __version__ try: git_status = get_git_status() if git_status is not None: version += f"-{git_status.commit[:8]}" if not git_status.is_clean: version += "-dirty" except: pass return version def _init_log_configuration() -> None: from sensai.util import logging def _configure() -> None: logging.getLogger("PIL").setLevel(logging.WARNING) logging.set_configure_callback(_configure) _init_log_configuration() - src/serena/agent.py (85383 bytes)
""" The Serena Model Context Protocol (MCP) Server """ # SPDX-License-Identifier: GPL-3.0-or-later import json import multiprocessing import os import platform import signal import subprocess import threading from collections import defaultdict from collections.abc import Callable, Iterator, Sequence from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime from enum import Enum from logging import Logger from typing import TYPE_CHECKING, Optional, TypeVar, cast import requests import webview from sensai.util import logging from sensai.util.helper import mark_used from sensai.util.logging import LogTime from sensai.util.string import ToStringMixin, dict_string, list_string from interprompt.jinja_template import JinjaTemplate from serena import serena_version from serena.analytics import RegisteredTokenCountEstimator, ReplFacadeMethodUsageStats, ToolUsageStats from serena.config.context_mode import SerenaAgentContext, SerenaAgentMode from serena.config.serena_config import ( AgentInterface, ModeSelectionDefinition, ModeSelectionDefinitionWithAddedModes, ModeSelectionDefinitionWithBaseModes, NamedApiInclusionDefinition, NamedToolInclusionDefinition, RegisteredProject, SerenaConfig, SerenaPaths, ToolInclusionDefinition, ) from serena.dashboard.dashboard_api import SerenaDashboardAPI from serena.dashboard.dashboard_tray_manager import SerenaDashboardTrayManager from serena.dashboard.dashboard_viewer import SerenaDashboardViewer, open_url_in_browser from serena.language_backend import BuiltinLanguageBackend, LanguageBackend from serena.ls_manager import LanguageServerManager from serena.memories.memory_manager import MemoryManager from serena.project import Project from serena.prompt_factory import SerenaPromptFactory from serena.repl.api.cfg_api import ConfigApi from serena.repl.api.edit_api import EditApi from serena.repl.api.ext_api import ExternalProjectsApi from serena.repl.api.fs_api import FsApi from serena.repl.api.mem_api import MemoryApi from serena.repl.api.shell_api import ShellApi from serena.repl.facade import ApiScope, Facade from serena.repl.repl import SerenaRepl from serena.session import SerenaSession, SessionRegistry from serena.task_executor import TaskExecutor from serena.tools import ( ActivateProjectTool, GetCurrentConfigTool, InitialInstructionsTool, OnboardingTool, OpenDashboardTool, ReadMemoryTool, ReplaceContentTool, SerenaReplTool, Tool, ToolMarker, ToolRegistry, tools_base, ) from serena.util.gui import system_has_usable_display from serena.util.inspection import iter_subclasses from serena.util.logging import MemoryLogHandler from solidlsp.ls_config import LanguageServerIdLike from solidlsp.util import subprocess_util from solidlsp.util.subprocess_util import subprocess_run if TYPE_CHECKING: from serena.gui_log_viewer import GuiLogViewer log = logging.getLogger(__name__) TTool = TypeVar("TTool", bound="Tool") T = TypeVar("T") SUCCESS_RESULT = "OK" class ProjectNotFoundError(Exception): pass class AvailableTools(ToStringMixin): """ Represents the set of available/exposed tools of a SerenaAgent. """ def __init__(self, tools: list[Tool]): """ :param tools: the list of available tools """ self.tools = tools self.tool_names = sorted([tool.get_name_from_cls() for tool in tools]) """ the list of available tool names, sorted alphabetically """ self._tool_name_set = set(self.tool_names) self.tool_marker_names = set() for marker_class in iter_subclasses(ToolMarker): for tool in tools: if isinstance(tool, marker_class): self.tool_marker_names.add(marker_class.__name__) def __len__(self) -> int: return len(self.tools) def _tostring_object_info(self) -> str: return list_string(self.tool_names, brackets=None) def contains_tool_name(self, tool_name: str) -> bool: return tool_name in self._tool_name_set def contains_tool_class(self, tool_class: type[Tool]) -> bool: return self.contains_tool_name(tool_class.get_name_from_cls()) class ToolSet: """ Represents a set of tools by their names. """ LEGACY_TOOL_NAME_MAPPING = {"replace_regex": ReplaceContentTool.get_name_from_cls()} """ maps legacy tool names to their new names for backward compatibility """ def __init__(self, tool_names: set[str]) -> None: self._tool_names = tool_names def __len__(self) -> int: return len(self._tool_names) @classmethod def default(cls) -> "ToolSet": """ :return: the default tool set, which contains all tools that are enabled by default """ from serena.tools import ToolRegistry return cls(set(ToolRegistry().get_tool_names_default_enabled())) def apply(self, *tool_inclusion_definitions: "ToolInclusionDefinition") -> "ToolSet": """ Applies one or more tool inclusion definitions to this tool set, resulting in a new tool set. :param tool_inclusion_definitions: the definitions to apply :return: a new tool set with the definitions applied """ from serena.tools import ToolRegistry def get_updated_tool_name(tool_name: str) -> str: """Retrieves the updated tool name if the provided tool name is deprecated, logging a warning.""" if tool_name in self.LEGACY_TOOL_NAME_MAPPING: new_tool_name = self.LEGACY_TOOL_NAME_MAPPING[tool_name] log.warning("Tool name '%s' is deprecated, please use '%s' instead", tool_name, new_tool_name) return new_tool_name return tool_name def is_marker(name: str) -> bool: return name.startswith("ToolMarker") def get_marker(name: str) -> type[ToolMarker] | None: marker_cls = getattr(tools_base, name, None) if marker_cls is not None and issubclass(marker_cls, ToolMarker): return marker_cls return None registry = ToolRegistry() tool_names = set(self._tool_names) for definition in tool_inclusion_definitions: if definition.is_fixed_tool_set(): tool_names = set() for fixed_tool in definition.fixed_tools: fixed_tool = get_updated_tool_name(fixed_tool) if registry.check_valid_tool_name(fixed_tool, " (in fixed tools set)"): tool_names.add(fixed_tool) log.info(f"{definition} defined a fixed tool set with {len(tool_names)} tools: {', '.join(tool_names)}") else: included_tools = [] excluded_tools = [] for included_tool in definition.included_optional_tools: if is_marker(included_tool): marker_class = get_marker(included_tool) if marker_class is None: log.warning(f"Tool marker '{included_tool}' not found; skipping inclusion.") continue for reg_tool in registry.iter_registered_tools(): if reg_tool.has_marker(marker_class) and reg_tool.tool_name not in tool_names: tool_names.add(reg_tool.tool_name) included_tools.append(reg_tool.tool_name) else: included_tool = get_updated_tool_name(included_tool) if ( registry.check_valid_tool_name(included_tool, " (in included optional tools)") and included_tool not in tool_names ): tool_names.add(included_tool) included_tools.append(included_tool) for excluded_tool in definition.excluded_tools: if is_marker(excluded_tool): marker_class = get_marker(excluded_tool) if marker_class is None: log.warning(f"Tool marker '{excluded_tool}' not found; skipping exclusion.") continue for tool_name in list(tool_names): reg_tool = registry.get_registered_tool_by_name(tool_name) if reg_tool.has_marker(marker_class): tool_names.remove(tool_name) excluded_tools.append(tool_name) else: excluded_tool = get_updated_tool_name(excluded_tool) registry.check_valid_tool_name(excluded_tool, " (in excluded tools)") if excluded_tool in tool_names: tool_names.remove(excluded_tool) excluded_tools.append(excluded_tool) if included_tools: log.info(f"{definition} included {len(included_tools)} tools: {', '.join(included_tools)}") if excluded_tools: log.info(f"{definition} excluded {len(excluded_tools)} tools: {', '.join(excluded_tools)}") return ToolSet(tool_names) def without_editing_tools(self) -> "ToolSet": """ :return: a new tool set that excludes all tools that can edit """ from serena.tools import ToolRegistry registry = ToolRegistry() tool_names = set(self._tool_names) for tool_name in self._tool_names: if registry.get_tool_class_by_name(tool_name).can_edit(): tool_names.remove(tool_name) return ToolSet(tool_names) def get_tool_names(self) -> set[str]: """ Returns the names of the tools that are currently included in the tool set. """ return self._tool_names def includes_name(self, tool_name: str) -> bool: return tool_name in self._tool_names def to_available_tools(self, all_tools: dict[type[Tool], Tool]) -> AvailableTools: return AvailableTools([t for t in all_tools.values() if self.includes_name(t.get_name())]) class ActiveModes: _mode_instances: dict[str, SerenaAgentMode] = {} def __init__(self, background_base_modes: Sequence[SerenaAgentMode] | None = None) -> None: """ :param background_base_modes: base modes that are always active in the background and will not be removed by applications of mode selection definitions via method `apply` """ self._background_base_modes = background_base_modes or [] self._configured_base_modes: Sequence[str] | None = None self._configured_default_modes: Sequence[str] | None = None self._added_modes: set[str] = set() self._dynamically_activated_mode_names: set[str] = set() """ the subset of active mode names that are dynamically activated (not necessarily enabled after project change) """ self._active_mode_names: Sequence[str] = [] """ the full list of active mode names (not including background base modes) """ def apply(self, mode_selection: ModeSelectionDefinition) -> None: log.debug("Applying mode selection definition %s", mode_selection) # apply overrides if isinstance(mode_selection, ModeSelectionDefinitionWithBaseModes): if mode_selection.base_modes is not None: self._configured_base_modes = mode_selection.base_modes if mode_selection.default_modes is not None: self._configured_default_modes = mode_selection.default_modes log.debug("Current mode selection: base_modes=%s, default_modes=%s", self._configured_base_modes, self._configured_default_modes) # apply added modes (if any) if isinstance(mode_selection, ModeSelectionDefinitionWithAddedModes): if mode_selection.added_modes: log.debug("Adding modes: %s", mode_selection.added_modes) self._added_modes.update(mode_selection.added_modes) log.debug("Current added modes: %s", self._added_modes) self._dynamically_activated_mode_names = set(self._configured_default_modes or []) | self._added_modes self._active_mode_names = sorted(set(self._configured_base_modes or []) | self._dynamically_activated_mode_names) def get_mode_names(self) -> Sequence[str]: """ :return: the ordered list of active mode names (not including the non-user-facing background base modes) """ return self._active_mode_names @classmethod def get_mode_instance(cls, mode_name: str) -> SerenaAgentMode: if mode_name not in cls._mode_instances: cls._mode_instances[mode_name] = SerenaAgentMode.load(mode_name) return cls._mode_instances[mode_name] def get_modes(self, include_background_base_modes: bool = False) -> Sequence[SerenaAgentMode]: result: list[SerenaAgentMode] = [] if include_background_base_modes: result.extend(self._background_base_modes) result.extend([self.get_mode_instance(mode_name) for mode_name in self._active_mode_names]) return result def get_dynamically_activated_modes(self) -> Sequence[SerenaAgentMode]: return [self.get_mode_instance(mode_name) for mode_name in self._dynamically_activated_mode_names] def get_base_modes(self, include_background_base_modes: bool = False) -> Sequence[SerenaAgentMode]: result: list[SerenaAgentMode] = [] if include_background_base_modes: result.extend(self._background_base_modes) result.extend([self.get_mode_instance(mode_name) for mode_name in self._configured_base_modes or []]) return result class ProjectPromptProvisionStatus: """ Manages the status of the provision of project-specific prompts """ @dataclass class SessionStatus: mode_prompts_provided: bool = False project_activation_message_provided: bool = False def __init__(self, newly_activated_mode_names: set[str] | None = None): """ :param newly_activated_mode_names: list of mode names that have been newly activated (by dynamic project activation) and for which prompts must still be provided (either in the system prompt or via the activation message) """ if newly_activated_mode_names is None: newly_activated_mode_names = set() self._newly_activated_mode_names: set[str] = newly_activated_mode_names self._session_status_dict: dict[str, ProjectPromptProvisionStatus.SessionStatus] = defaultdict(lambda: self.SessionStatus()) def _get_session_status(self, session_id: st - src/serena/agno.py (5976 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import argparse import logging import os import threading from pathlib import Path from typing import Any from agno.agent import Agent from agno.db.sqlite import SqliteDb from agno.memory import MemoryManager from agno.models.base import Model from agno.tools.function import Function from agno.tools.toolkit import Toolkit from dotenv import load_dotenv from sensai.util.logging import LogTime from serena.agent import SerenaAgent, Tool from serena.config.context_mode import SerenaAgentContext from serena.constants import REPO_ROOT from serena.util.exception import show_fatal_exception_safe log = logging.getLogger(__name__) class SerenaAgnoToolkit(Toolkit): def __init__(self, serena_agent: SerenaAgent): super().__init__("Serena") for tool in serena_agent.get_exposed_tool_instances(): self.functions[tool.get_name_from_cls()] = self._create_agno_function(tool) log.info("Agno agent functions: %s", list(self.functions.keys())) @staticmethod def _create_agno_function(tool: Tool) -> Function: def entrypoint(**kwargs: Any) -> str: if "kwargs" in kwargs: # Agno sometimes passes a kwargs argument explicitly, so we merge it kwargs.update(kwargs["kwargs"]) del kwargs["kwargs"] log.info(f"Calling tool {tool}") return tool.apply_ex(log_call=True, catch_exceptions=True, **kwargs) function = Function.from_callable(tool.get_apply_fn()) function.name = tool.get_name_from_cls() function.entrypoint = entrypoint function.skip_entrypoint_processing = True return function class SerenaAgnoAgentProvider: _agent: Agent | None = None _lock = threading.Lock() @classmethod def get_agent(cls, model: Model) -> Agent: """ Returns the singleton instance of the Serena agent or creates it with the given parameters if it doesn't exist. NOTE: This is very ugly with poor separation of concerns, but the way in which the Agno UI works (reloading the module that defines the `app` variable) essentially forces us to do something like this. :param model: the large language model to use for the agent :return: the agent instance """ with cls._lock: if cls._agent is not None: return cls._agent # change to Serena root os.chdir(REPO_ROOT) load_dotenv() parser = argparse.ArgumentParser(description="Serena coding assistant") # Create a mutually exclusive group group = parser.add_mutually_exclusive_group() # Add arguments to the group, both pointing to the same destination group.add_argument( "--project-file", required=False, help="Path to the project (or project.yml file).", ) group.add_argument( "--project", required=False, help="Path to the project (or project.yml file).", ) args = parser.parse_args() args_project_file = args.project or args.project_file if args_project_file: project_file = Path(args_project_file).resolve() # If project file path is relative, make it absolute by joining with project root if not project_file.is_absolute(): # Get the project root directory (parent of scripts directory) project_root = Path(REPO_ROOT) project_file = project_root / args_project_file # Ensure the path is normalized and absolute project_file = str(project_file.resolve()) else: project_file = None with LogTime("Loading Serena agent"): try: serena_agent = SerenaAgent(project_file, context=SerenaAgentContext.load("agent")) except Exception as e: show_fatal_exception_safe(e) raise # Even though we don't want to keep history between sessions, # for agno-ui to work as a conversation, we use a persistent database on disk. # This database should be deleted between sessions. # Note that this might collide with custom options for the agent, like adding vector-search based tools. sql_db_path = (Path("temp") / "agno_agent_storage.db").absolute() sql_db_path.parent.mkdir(exist_ok=True) # delete the db file if it exists log.info(f"Deleting DB from PID {os.getpid()}") if sql_db_path.exists(): sql_db_path.unlink() agno_agent = Agent( name="Serena", model=model, # See explanation above on why database is needed db=SqliteDb(db_file=str(sql_db_path)), description="A fully-featured coding assistant", tools=[SerenaAgnoToolkit(serena_agent)], # Tool calls will be shown in the UI since that's configurable per tool # To see detailed logs, you should use the serena logger (configure it in the project file path) markdown=True, system_message=serena_agent.create_system_prompt(), telemetry=False, memory_manager=MemoryManager(), add_history_to_context=True, num_history_runs=100, # you might want to adjust this (expense vs. history awareness) ) cls._agent = agno_agent log.info(f"Agent instantiated: {agno_agent}") return agno_agent - src/serena/analytics.py (6977 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from __future__ import annotations import logging import threading from abc import ABC, abstractmethod from collections import defaultdict from copy import copy from dataclasses import asdict, dataclass from enum import Enum from typing import TYPE_CHECKING from dotenv import load_dotenv if TYPE_CHECKING: # Imported for annotations only: loading the anthropic package costs seconds on some # machines (see #2012) and is only needed when the Anthropic token counter is used. from anthropic.types import MessageTokensCount log = logging.getLogger(__name__) class TokenCountEstimator(ABC): @abstractmethod def estimate_token_count(self, text: str) -> int: """ Estimate the number of tokens in the given text. This is an abstract method that should be implemented by subclasses. """ class TiktokenCountEstimator(TokenCountEstimator): """ Approximate token count using tiktoken. """ def __init__(self, model_name: str = "gpt-4o"): """ The tokenizer will be downloaded on the first initialization, which may take some time. :param model_name: see `tiktoken.model` to see available models. """ import tiktoken log.info(f"Loading tiktoken encoding for model {model_name}, this may take a while on the first run.") self._encoding = tiktoken.encoding_for_model(model_name) def estimate_token_count(self, text: str) -> int: return len(self._encoding.encode_ordinary(text)) class AnthropicTokenCount(TokenCountEstimator): """ The exact count using the Anthropic API. Counting is free, but has a rate limit and will require an API key, (typically, set through an env variable). See https://docs.anthropic.com/en/docs/build-with-claude/token-counting """ def __init__(self, model_name: str, api_key: str | None = None): import anthropic self._model_name = model_name if api_key is None: load_dotenv() self._anthropic_client = anthropic.Anthropic(api_key=api_key) def _send_count_tokens_request(self, text: str) -> MessageTokensCount: return self._anthropic_client.messages.count_tokens( model=self._model_name, messages=[{"role": "user", "content": text}], ) def estimate_token_count(self, text: str) -> int: return self._send_count_tokens_request(text).input_tokens class CharCountEstimator(TokenCountEstimator): """ A naive character count estimator that estimates tokens based on character count. """ def __init__(self, avg_chars_per_token: int = 4): self._avg_chars_per_token = avg_chars_per_token def estimate_token_count(self, text: str) -> int: # Assuming an average of 4 characters per token return len(text) // self._avg_chars_per_token _registered_token_estimator_instances_cache: dict[RegisteredTokenCountEstimator, TokenCountEstimator] = {} class RegisteredTokenCountEstimator(Enum): TIKTOKEN_GPT4O = "TIKTOKEN_GPT4O" ANTHROPIC_CLAUDE_SONNET_4 = "ANTHROPIC_CLAUDE_SONNET_4" CHAR_COUNT = "CHAR_COUNT" @classmethod def get_valid_names(cls) -> list[str]: """ Get a list of all registered token count estimator names. """ return [estimator.name for estimator in cls] def _create_estimator(self) -> TokenCountEstimator: match self: case RegisteredTokenCountEstimator.TIKTOKEN_GPT4O: return TiktokenCountEstimator(model_name="gpt-4o") case RegisteredTokenCountEstimator.ANTHROPIC_CLAUDE_SONNET_4: return AnthropicTokenCount(model_name="claude-sonnet-4-6") case RegisteredTokenCountEstimator.CHAR_COUNT: return CharCountEstimator(avg_chars_per_token=4) case _: raise ValueError(f"Unknown token count estimator: {self}") def load_estimator(self) -> TokenCountEstimator: estimator_instance = _registered_token_estimator_instances_cache.get(self) if estimator_instance is None: estimator_instance = self._create_estimator() _registered_token_estimator_instances_cache[self] = estimator_instance return estimator_instance class ToolUsageStats: """ A class to record and manage tool usage statistics. """ def __init__(self, token_count_estimator: RegisteredTokenCountEstimator = RegisteredTokenCountEstimator.TIKTOKEN_GPT4O): self._token_count_estimator = token_count_estimator.load_estimator() self._token_estimator_name = token_count_estimator.value self._tool_stats: dict[str, ToolUsageStats.Entry] = defaultdict(ToolUsageStats.Entry) self._tool_stats_lock = threading.Lock() @property def token_estimator_name(self) -> str: """ Get the name of the registered token count estimator used. """ return self._token_estimator_name @dataclass(kw_only=True) class Entry: num_times_called: int = 0 input_tokens: int = 0 output_tokens: int = 0 def update_on_call(self, input_tokens: int, output_tokens: int) -> None: """ Update the entry with the number of tokens used for a single call. """ self.num_times_called += 1 self.input_tokens += input_tokens self.output_tokens += output_tokens def _estimate_token_count(self, text: str) -> int: return self._token_count_estimator.estimate_token_count(text) def get_stats(self, tool_name: str) -> ToolUsageStats.Entry: """ Get (a copy of) the current usage statistics for a specific tool. """ with self._tool_stats_lock: return copy(self._tool_stats[tool_name]) def record_tool_usage(self, tool_name: str, input_str: str, output_str: str) -> None: input_tokens = self._estimate_token_count(input_str) output_tokens = self._estimate_token_count(output_str) with self._tool_stats_lock: entry = self._tool_stats[tool_name] entry.update_on_call(input_tokens, output_tokens) def get_tool_stats_dict(self) -> dict[str, dict[str, int]]: with self._tool_stats_lock: return {name: asdict(entry) for name, entry in self._tool_stats.items()} def clear(self) -> None: with self._tool_stats_lock: self._tool_stats.clear() class ReplFacadeMethodUsageStats: def __init__(self): self._method_stats = defaultdict(lambda: 0) def record_method_call(self, qualified_method_name: str) -> None: self._method_stats[qualified_method_name] += 1 def get_counts(self) -> dict[str, int]: """ :return: a dictionary mapping qualified facade method names to the number of times they have been called. """ return dict(self._method_stats) - src/serena/cli.py (75919 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import collections import glob import json import os import shutil import signal import subprocess import sys import tempfile import time from collections.abc import Iterator, Sequence from contextlib import contextmanager from logging import Logger from pathlib import Path from typing import TYPE_CHECKING, Any, Literal import click from sensai.util import logging from sensai.util.logging import FileLoggerContext, datetime_tag from sensai.util.string import dict_string from tqdm import tqdm from serena import serena_version from serena.config.client_setup import client_setup_handlers from serena.config.context_mode import SerenaAgentContext, SerenaAgentMode from serena.config.serena_config import ( AgentInterface, ModeSelectionDefinition, ModeSelectionDefinitionWithAddedModes, ProjectConfig, RegisteredProject, SerenaConfig, SerenaPaths, ) from serena.constants import ( DEFAULT_CONTEXT, PROMPT_TEMPLATES_DIR_INTERNAL, SERENA_LOG_FORMAT, SERENAS_OWN_CONTEXT_YAMLS_DIR, SERENAS_OWN_MODE_YAMLS_DIR, ) from serena.language_backend import BuiltinLanguageBackend, LanguageBackendRegistry from serena.project import Project from serena.prompt_factory import SerenaPromptFactory from serena.tools import ActivateProjectTool from serena.util.cli_util import AutoRegisteringGroup from serena.util.logging import MemoryLogHandler from solidlsp.ls_config import LanguageServerIdLike, LanguageServerRegistry from solidlsp.ls_types import SymbolKind from solidlsp.util.subprocess_util import subprocess_kwargs if TYPE_CHECKING: from serena.mcp import SerenaMCPFactory from serena.memories.memory_manager import MemoryManager log = logging.getLogger(__name__) _MAX_CONTENT_WIDTH = 200 _MODES_EXPLANATION = """\b\nBuilt-in mode names or paths to custom mode YAMLs with which to override the default_modes defined in the global Serena configuration or the active project. For details on mode configuration, see https://oraios.github.io/serena/02-usage/050_configuration.html#modes. """ _ADD_MODES_EXPLANATION = """\b\nMode names or paths to custom mode YAMLs which shall be added on top of the other modes specified by the global/project configuration. For details on mode configuration, see https://oraios.github.io/serena/02-usage/050_configuration.html#modes. """ def find_project_root(root: str | Path | None = None) -> str | None: """Find project root by walking up from CWD. Returns the nearest ancestor that is either an explicit Serena project (contains .serena/project.yml) or a git root (contains .git, which may be a directory or, for git worktrees and submodules, a pointer file). The nearest such directory wins; a .serena/project.yml at the same level takes priority over .git only because they resolve to the same directory. Walking up with a single pass (rather than searching all levels for .serena/project.yml first and only then for .git) ensures a git worktree nested under another Serena project resolves to the worktree itself, instead of being hijacked by the ancestor project's .serena/project.yml. :param root: If provided, constrains the search to this directory and below (acts as a virtual filesystem root). Search stops at this boundary. :return: absolute path to project root or None if not suitable root is found """ current = Path.cwd().resolve() boundary = Path(root).resolve() if root is not None else None def ancestors() -> Iterator[Path]: """Yield current directory and ancestors up to boundary.""" yield current for parent in current.parents: yield parent if boundary is not None and parent == boundary: return # Single pass: the nearest project boundary wins, whether it is an explicit # Serena project (.serena/project.yml) or a git root (.git, a dir or a worktree # pointer file). This keeps a nested git worktree from being hijacked by an # ancestor's .serena/project.yml. for directory in ancestors(): if (directory / ".serena" / "project.yml").is_file() or (directory / ".git").exists(): return str(directory) return None def _open_in_editor(path: str) -> None: """Open the given file in the system's default editor or viewer.""" editor = os.environ.get("EDITOR") run_kwargs = subprocess_kwargs() try: if editor: subprocess.run([editor, path], check=False, **run_kwargs) elif sys.platform.startswith("win"): try: os.startfile(path) except OSError: subprocess.run(["notepad.exe", path], check=False, **run_kwargs) elif sys.platform == "darwin": subprocess.run(["open", path], check=False, **run_kwargs) else: subprocess.run(["xdg-open", path], check=False, **run_kwargs) except Exception as e: print(f"Failed to open {path}: {e}") def _download_ls_dependencies(ls_id: LanguageServerIdLike, ls_specific_settings: dict, repository_root_path: str) -> None: """Download dependencies for one language server without starting it.""" from solidlsp import SolidLanguageServer from solidlsp.ls_config import LanguageServerConfig from solidlsp.settings import SolidLSPSettings language_server = SolidLanguageServer.create( LanguageServerConfig(ls_id=ls_id), repository_root_path, solidlsp_settings=SolidLSPSettings( solidlsp_dir=SerenaPaths().serena_user_home_dir, project_data_path=os.path.join(repository_root_path, ".solidlsp"), ls_specific_settings=ls_specific_settings, ), ) language_server.install_dependencies() class ProjectType(click.ParamType): """ParamType allowing either a project name or a path to a project directory.""" name = "[PROJECT_NAME|PROJECT_PATH]" def convert(self, value: str, param: Any, ctx: Any) -> str: path = Path(value).resolve() if path.exists() and path.is_dir(): return str(path) return value PROJECT_TYPE = ProjectType() @contextmanager def agent_shutdown_on_signal(factory: "SerenaMCPFactory") -> Iterator[None]: """ Shuts the factory's agent down when the process is told to stop while an SSE/streamable-HTTP server is running. uvicorn captures SIGINT/SIGTERM while it serves, restores the handlers it found once its loop has ended, and then re-raises the captured signal — so with the default handlers in place the process dies right after the server stops and nothing after `server.run` ever runs. The handler installed here is what uvicorn restores and re-raises into: it shuts the agent down (stopping language servers and saving their caches, like the stdio lifespan does), then hands the signal to the default handler so the process still exits the conventional way. """ def handler(signum: int, _frame: object) -> None: factory.shutdown_agent() signal.signal(signum, signal.SIG_DFL) signal.raise_signal(signum) previous = {sig: signal.signal(sig, handler) for sig in (signal.SIGINT, signal.SIGTERM)} try: yield finally: for sig, previous_handler in previous.items(): signal.signal(sig, previous_handler) class TopLevelCommands(AutoRegisteringGroup): """Root CLI group containing the core Serena commands.""" def __init__(self) -> None: super().__init__( name="serena", help="Main serena CLI commands. " "Note that you also have access to `serena-hooks` CLI commands which are kept under " "that separate entrypoint for performance reasons, see `serena-hooks --help`. You can run `<command> --help` for more info on each command.", ) # register --version / -V flag self.params.append( click.Option( ["--version", "-V"], is_flag=True, expose_value=False, is_eager=True, callback=self._print_version, help="Show the version and exit.", ) ) @staticmethod def _print_version(ctx: click.Context, _param: click.Parameter, value: bool) -> None: """Print version string and exit if the flag is set.""" if not value: return click.echo(f"Serena {serena_version()}") ctx.exit() @staticmethod @click.command( "init", help="Initialize Serena by creating a global config file with the specified default language backend.", context_settings={"max_content_width": _MAX_CONTENT_WIDTH}, ) @click.option( "--language-backend", "-b", type=click.Choice([b.value for b in BuiltinLanguageBackend]), default=BuiltinLanguageBackend.LSP.value, show_default=True, help="Default code intelligence backend (can be overridden in the project config).", ) def init(language_backend: Literal["LSP", "JetBrains"] = "LSP") -> None: click.echo(f"\nSerena version: {serena_version()}\n") serena_config = SerenaConfig.init(builtin_language_backend=BuiltinLanguageBackend(language_backend)) click.echo(f"Configuration file: {serena_config.config_file_path}") click.echo(f"Language backend: {language_backend}") # check for auto-configurable clients applicable_setup_handlers = [] for setup_handler in client_setup_handlers: if setup_handler.is_applicable(): applicable_setup_handlers.append(setup_handler) if len(applicable_setup_handlers) > 0: click.echo( "\nAuto-configurable clients detected.\nApply the following commands to configure the Serena MCP server (in a default configuration):" ) for setup_handler in applicable_setup_handlers: click.echo(f" serena setup {setup_handler.name}") click.echo("\nSerena has been initialised successfully.\n") @staticmethod @click.command( "setup", help="Set up Serena for use with a specific client by registering it as an MCP server.", context_settings={"max_content_width": _MAX_CONTENT_WIDTH}, ) @click.argument( "client", type=click.Choice([h.name for h in client_setup_handlers]), ) def setup(client: str) -> None: # find the matching handler handler = next(h for h in client_setup_handlers if h.name == client) # check applicability if not handler.is_applicable(): click.echo(f"\nCannot apply setup for client '{client}' (not found or not functional).\n") raise SystemExit(1) # apply the setup if handler.apply(): click.echo(f"\nSerena has been successfully set up for {client}.\n") else: click.echo(f"\nFailed to set up Serena for {client}.\n") raise SystemExit(1) @staticmethod @click.command( "download-ls-dependencies", help="Download language-server dependencies ahead of time for environments with restricted network access.", context_settings={"max_content_width": _MAX_CONTENT_WIDTH}, ) @click.argument("language_servers", type=str, nargs=-1, required=True) def download_ls_dependencies(language_servers: tuple[str, ...]) -> None: """Download dependencies without starting any language server.""" logging.configure(level=logging.INFO) # resolve the language server names registry = LanguageServerRegistry.get_instance() ls_ids: list[LanguageServerIdLike] = [] for name in language_servers: try: ls_ids.append(registry.resolve(name.lower())) except ValueError as exc: raise click.UsageError(f"Unknown language server '{name}'. Supported: {', '.join(registry.get_keys())}") from exc # load the user's language server settings, if a configuration exists try: ls_specific_settings = dict(SerenaConfig.from_config_file(generate_if_missing=False).ls_specific_settings) except FileNotFoundError: ls_specific_settings = {} # download the dependencies, continuing with the remaining language servers upon failure failures: list[tuple[LanguageServerIdLike, Exception]] = [] with tempfile.TemporaryDirectory() as temp_dir: for index, ls_id in enumerate(ls_ids, start=1): click.echo(f"[{index}/{len(ls_ids)}] Downloading dependencies for '{ls_id.get_key()}' ...") try: _download_ls_dependencies(ls_id, ls_specific_settings, temp_dir) except Exception as exc: log.exception("Failed to download dependencies for '%s'", ls_id.get_key()) failures.append((ls_id, exc)) # report the outcome if failures: click.echo(f"Failed to download dependencies for {len(failures)} of {len(ls_ids)} language server(s):", err=True) for ls_id, exc in failures: click.echo(f" {ls_id.get_key()}: {exc}", err=True) raise click.exceptions.Exit(1) click.echo(f"Successfully downloaded dependencies for {len(ls_ids)} language server(s).") @staticmethod @click.command("start-mcp-server", help="Starts the Serena MCP server.", context_settings={"max_content_width": _MAX_CONTENT_WIDTH}) @click.option("--project", "project", type=PROJECT_TYPE, default=None, help="Path or name of project to activate at startup.") @click.option("--project-file", "project", type=PROJECT_TYPE, default=None, help="[DEPRECATED] Use --project instead.") @click.argument("project_file_arg", type=PROJECT_TYPE, required=False, default=None, metavar="") @click.option( "--context", type=str, default=DEFAULT_CONTEXT, show_default=True, help="Built-in context name or path to custom context YAML." ) @click.option( "--mode", "default_modes", type=str, multiple=True, default=(), show_default=False, help=_MODES_EXPLANATION, ) @click.option( "--add-mode", "added_modes", type=str, multiple=True, default=(), show_default=False, help=_ADD_MODES_EXPLANATION, ) @click.option( "--language-backend", type=click.Choice(LanguageBackendRegistry.get_instance().get_keys()), default=None, help="Override the configured language backend.", ) @click.option( "--agent-interface", type=click.Choice([i.value for i in AgentInterface], case_sensitive=False), default=None, help="Override the configured agent interface: 'tools' (one tool per operation) or " "'REPL' (Pyth - src/serena/code_editor.py (25867 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json import logging import os from abc import ABC, abstractmethod from collections.abc import Iterable, Iterator, Reversible from contextlib import contextmanager from types import TracebackType from typing import Any, Generic, Self, TypeVar, cast from serena.jetbrains.jetbrains_plugin_client import JetBrainsPluginClient, ServerNotFoundError from serena.symbol import JetBrainsSymbol, LanguageServerSymbol, LanguageServerSymbolRetriever, PositionInFile, Symbol from solidlsp import SolidLanguageServer, ls_types from solidlsp.ls import LSPFileBuffer from solidlsp.ls_utils import PathUtils, TextStepper, TextUtils from .project import Project from .util.file_proxy import FileProxy from .util.file_system import write_file_atomic log = logging.getLogger(__name__) TSymbol = TypeVar("TSymbol", bound=Symbol) class CodeEditor(Generic[TSymbol], ABC): def __init__(self, project: Project) -> None: self.project = project self.project_root = project.project_root self.encoding = project.project_config.encoding self.newline = project.line_ending.newline_str class EditedFile(ABC): def __init__(self, relative_path: str) -> None: self.relative_path = relative_path @abstractmethod def get_contents(self) -> str: """ :return: the contents of the file. """ @abstractmethod def set_contents(self, contents: str) -> None: """ Fully resets the contents of the file. :param contents: the new contents """ @abstractmethod def delete_text_between_positions(self, start_pos: PositionInFile, end_pos: PositionInFile) -> None: pass @abstractmethod def insert_text_at_position(self, pos: PositionInFile, text: str) -> None: pass @contextmanager def _open_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]: """ Context manager for opening a file """ raise NotImplementedError("This method must be overridden for each subclass") def read_file(self, relative_path: str, lines: tuple[int, int] | None = None) -> str: """ Reads the content of a file. :param relative_path: the relative path of the file to read :param lines: tuple of (first_line, last_line) to read only a specific line range (0-based, inclusive) :return: the content of the file """ with self._open_file_context(relative_path) as file: contents = file.get_contents() if lines is None: return contents else: first_line, last_line = lines return TextUtils.get_text_in_lines_range(contents, first_line, last_line) @contextmanager def edited_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]: """ Context manager for editing a file. """ if FileProxy.is_external_path(relative_path, self.project): raise ValueError(f"Cannot edit external file: {relative_path}") with self._open_file_context(relative_path) as edited_file: yield edited_file # save the file self._save_edited_file(edited_file) def _save_edited_file(self, edited_file: "CodeEditor.EditedFile") -> None: abs_path = os.path.join(self.project_root, edited_file.relative_path) new_contents = edited_file.get_contents() write_file_atomic(abs_path, new_contents, encoding=self.encoding, newline=self.newline) @abstractmethod def _find_unique_symbol(self, name_path: str, relative_file_path: str) -> TSymbol: """ Finds the unique symbol with the given name in the given file. If no such symbol exists, raises a ValueError. :param name_path: the name path :param relative_file_path: the relative path of the file in which to search for the symbol. :return: the unique symbol """ def replace_body(self, name_path: str, relative_file_path: str, body: str) -> None: """ Replaces the body of the symbol with the given name_path in the given file. :param name_path: the name path of the symbol to replace. :param relative_file_path: the relative path of the file in which the symbol is defined. :param body: the new body """ symbol = self._find_unique_symbol(name_path, relative_file_path) start_pos = symbol.get_body_start_position_or_raise() end_pos = symbol.get_body_end_position_or_raise() with self.edited_file_context(relative_file_path) as edited_file: # make sure the replacement adds no additional newlines (before or after) - all newlines # and whitespace before/after should remain the same, so we strip it entirely body = body.strip() edited_file.delete_text_between_positions(start_pos, end_pos) edited_file.insert_text_at_position(start_pos, body) @staticmethod def _count_leading_newlines(text: Iterable) -> int: cnt = 0 for c in text: if c == "\n": cnt += 1 elif c == "\r": continue else: break return cnt @classmethod def _count_trailing_newlines(cls, text: Reversible) -> int: return cls._count_leading_newlines(reversed(text)) def insert_after_symbol(self, name_path: str, relative_file_path: str, body: str) -> None: """ Inserts content after the symbol with the given name in the given file. """ symbol = self._find_unique_symbol(name_path, relative_file_path) # Note: for body to be available, the symbol dto that the symbol instance is built from # must have been retrieved either with body or at least with location. # since _find_unique_symbol passes include_location=True, it works here if symbol.body == symbol.name: raise ValueError( f"Cannot insert after this symbol (not a function, class or method): {symbol}. Consider using insert_before_symbol instead." ) # make sure body always ends with at least one newline if not body.endswith("\n"): body += "\n" pos = symbol.get_body_end_position_or_raise() # start at the beginning of the next line col = 0 line = pos.line + 1 # make sure a suitable number of leading empty lines is used (at least 0/1 depending on the symbol type, # otherwise as many as the caller wanted to insert) original_leading_newlines = self._count_leading_newlines(body) body = body.lstrip("\r\n") min_empty_lines = 0 if symbol.is_neighbouring_definition_separated_by_empty_line(): min_empty_lines = 1 num_leading_empty_lines = max(min_empty_lines, original_leading_newlines) if num_leading_empty_lines: body = ("\n" * num_leading_empty_lines) + body # make sure the one line break succeeding the original symbol, which we repurposed as prefix via # `line += 1`, is replaced body = body.rstrip("\r\n") + "\n" with self.edited_file_context(relative_file_path) as edited_file: edited_file.insert_text_at_position(PositionInFile(line, col), body) def insert_before_symbol(self, name_path: str, relative_file_path: str, body: str) -> None: """ Inserts content before the symbol with the given name in the given file. """ symbol = self._find_unique_symbol(name_path, relative_file_path) symbol_start_pos = symbol.get_body_start_position_or_raise() # insert position is the start of line where the symbol is defined line = symbol_start_pos.line col = 0 original_trailing_empty_lines = self._count_trailing_newlines(body) - 1 # ensure eol is present at end body = body.rstrip() + "\n" # add suitable number of trailing empty lines after the body (at least 0/1 depending on the symbol type, # otherwise as many as the caller wanted to insert) min_trailing_empty_lines = 0 if symbol.is_neighbouring_definition_separated_by_empty_line(): min_trailing_empty_lines = 1 num_trailing_newlines = max(min_trailing_empty_lines, original_trailing_empty_lines) body += "\n" * num_trailing_newlines # apply edit with self.edited_file_context(relative_file_path) as edited_file: edited_file.insert_text_at_position(PositionInFile(line=line, col=col), body) def insert_at_line(self, relative_path: str, line: int, content: str) -> None: """ Inserts content at the given line in the given file. :param relative_path: the relative path of the file in which to insert content :param line: the 0-based index of the line to insert content at :param content: the content to insert """ with self.edited_file_context(relative_path) as edited_file: edited_file.insert_text_at_position(PositionInFile(line, 0), content) def delete_lines(self, relative_path: str, start_line: int, end_line: int) -> None: """ Deletes lines in the given file. :param relative_path: the relative path of the file in which to delete lines :param start_line: the 0-based index of the first line to delete (inclusive) :param end_line: the 0-based index of the last line to delete (inclusive) """ with self.edited_file_context(relative_path) as edited_file: self._delete_line_range(edited_file, start_line, end_line) def replace_lines(self, relative_path: str, start_line: int, end_line: int, content: str) -> None: """ Replaces a range of lines in the given file, writing the file once. Deleting the range and inserting the replacement as two separate operations would persist the deletion even if the insertion failed, leaving the file without the lines the caller asked to replace. :param relative_path: the relative path of the file in which to replace the lines :param start_line: the 0-based index of the first line to replace (inclusive) :param end_line: the 0-based index of the last line to replace (inclusive) :param content: the content to insert in place of the range """ with self.edited_file_context(relative_path) as edited_file: self._delete_line_range(edited_file, start_line, end_line) edited_file.insert_text_at_position(PositionInFile(line=start_line, col=0), content) def _delete_line_range(self, edited_file: "CodeEditor.EditedFile", start_line: int, end_line: int) -> None: """ Deletes the given inclusive line range from an open edited file. :param edited_file: the open file to delete from :param start_line: the 0-based index of the first line to delete (inclusive) :param end_line: the 0-based index of the last line to delete (inclusive) """ start_pos = PositionInFile(line=start_line, col=0) end_pos = PositionInFile(line=end_line + 1, col=0) edited_file.delete_text_between_positions(start_pos, end_pos) def delete_symbol(self, name_path: str, relative_file_path: str) -> None: """ Deletes the symbol with the given name in the given file. """ symbol = self._find_unique_symbol(name_path, relative_file_path) start_pos = symbol.get_body_start_position_or_raise() end_pos = symbol.get_body_end_position_or_raise() with self.edited_file_context(relative_file_path) as edited_file: # do the actual deletion edited_file.delete_text_between_positions(start_pos, end_pos) # empty line removal heuristic: # After the deletion, go to the line where the deleted symbol started, # check whether it and any subsequent lines are empty, and if so, delete them. # The empty lines preceding the deleted symbol's body should normally suffice as a separator # between the symbols before and after the deleted symbol. start_pos.col = 0 stepper = TextStepper(edited_file.get_contents()) stepper.step_to(start_pos.line, start_pos.col) apply_empty_line_deletion = False while stepper.step_line(): line = stepper.get_last_line(with_end=False) if line.strip() == "": end_pos.line = stepper.line end_pos.col = stepper.col apply_empty_line_deletion = True else: break if apply_empty_line_deletion: edited_file.delete_text_between_positions(start_pos, end_pos) @abstractmethod def rename_symbol(self, name_path: str, relative_path: str, new_name: str) -> str: pass class LanguageServerCodeEditor(CodeEditor[LanguageServerSymbol]): def __init__(self, symbol_retriever: LanguageServerSymbolRetriever): super().__init__(project=symbol_retriever.project) self._symbol_retriever = symbol_retriever def _get_language_server(self, relative_path: str) -> SolidLanguageServer: return self._symbol_retriever.get_language_server(relative_path) class EditedFile(CodeEditor.EditedFile): def __init__(self, lang_server: SolidLanguageServer, relative_path: str, file_buffer: LSPFileBuffer): super().__init__(relative_path) self._lang_server = lang_server self._file_buffer = file_buffer def get_contents(self) -> str: return self._file_buffer.contents def set_contents(self, contents: str) -> None: self._file_buffer.contents = contents def delete_text_between_positions(self, start_pos: PositionInFile, end_pos: PositionInFile) -> None: self._lang_server.delete_text_between_positions(self.relative_path, start_pos.to_lsp_position(), end_pos.to_lsp_position()) def insert_text_at_position(self, pos: PositionInFile, text: str) -> None: self._lang_server.insert_text_at_position(self.relative_path, pos.line, pos.col, text) def apply_text_edits(self, text_edits: list[ls_types.TextEdit]) -> None: return self._lang_server.apply_text_edits_to_file(self.relative_path, text_edits) @contextmanager def _open_file_context(self, relative_path: str) -> Iterator["CodeEditor.EditedFile"]: lang_server = self._get_language_server(relative_path) with lang_server.open_file(relative_path) as file_buffer: yield self.EditedFile(lang_server, relative_path, file_buffer) def _get_ - src/serena/config/__init__.py (0 bytes)
- src/serena/config/client_setup.py (5282 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from abc import ABC, abstractmethod import click from serena.util.shell import execute_shell_command class ClientSetupHandler(ABC): def __init__(self, name: str) -> None: self.name = name @abstractmethod def is_applicable(self) -> bool: """ :return: whether the client setup can applied (respective client is available) """ @abstractmethod def get_mcp_server_options(self) -> list[str]: pass def get_mcp_server_command(self) -> str: return f"serena start-mcp-server {' '.join(self.get_mcp_server_options())}" def _run_shell_command(self, cmd: str) -> bool: """ Runs the given shell command. If the command fails (i.e., with non-zero exit code), prints the stdout and stderr of the command for debugging. :param cmd: the shell command to execute :return: whether the command executed successfully (i.e., with exit code 0) """ click.echo("Running command:") click.echo(cmd) result = execute_shell_command(cmd) is_success = result.return_code == 0 if not is_success: if result.stdout: click.echo(result.stdout) if result.stderr: click.echo(result.stderr) return is_success @abstractmethod def apply(self) -> bool: """ Applies the client setup """ class ClientSetupHandlerClaudeCode(ClientSetupHandler): def __init__(self) -> None: super().__init__("claude-code") def is_applicable(self) -> bool: result = execute_shell_command("claude --version", capture_stderr=True) return result.return_code == 0 and "Claude" in result.stdout def get_mcp_server_options(self) -> list[str]: return ["--context=claude-code", "--project-from-cwd"] def apply(self) -> bool: cmd = f"claude mcp add --scope user serena -- {self.get_mcp_server_command()}" is_success = self._run_shell_command(cmd) if is_success: click.echo("\nIMPORTANT: We additionally recommend to set up hooks for Claude Code to ensure the best experience.") click.echo(" Please read the instructions here:") click.echo(" https://oraios.github.io/serena/02-usage/030_clients.html#claude-code") return is_success class ClientSetupHandlerCodex(ClientSetupHandler): """ Setup for Codex CLI and Codex App (shared config) """ def __init__(self) -> None: super().__init__("codex") def is_applicable(self) -> bool: result = execute_shell_command("codex --version", capture_stderr=True) return result.return_code == 0 and "codex-cli" in result.stdout def get_mcp_server_options(self) -> list[str]: return ["--context=codex", "--project-from-cwd"] def apply(self) -> bool: return self._run_shell_command(f"codex mcp add serena -- {self.get_mcp_server_command()}") class ClientSetupHandlerCodeBuddy(ClientSetupHandler): def __init__(self) -> None: super().__init__("codebuddy") def is_applicable(self) -> bool: result = execute_shell_command("codebuddy --version", capture_stderr=True) return result.return_code == 0 def get_mcp_server_options(self) -> list[str]: return ["--context=codebuddy", "--project-from-cwd"] def apply(self) -> bool: cmd = f"codebuddy mcp add --scope user serena -- {self.get_mcp_server_command()}" is_success = self._run_shell_command(cmd) if is_success: click.echo("\nIMPORTANT: We additionally recommend to set up hooks for CodeBuddy to ensure the best experience.") click.echo(" Please read the instructions here:") click.echo(" https://oraios.github.io/serena/02-usage/030_clients.html#codebuddy") return is_success class ClientSetupHandlerGrok(ClientSetupHandler): """ Setup for xAI Grok Build. """ def __init__(self) -> None: super().__init__("grok") def is_applicable(self) -> bool: version_result = execute_shell_command("grok --version", capture_stderr=True) if version_result.return_code != 0 or not version_result.stdout.lower().startswith("grok "): return False mcp_result = execute_shell_command("grok mcp add --help", capture_stderr=True) return mcp_result.return_code == 0 and "Add or update an MCP server" in mcp_result.stdout def get_mcp_server_options(self) -> list[str]: return ["--context=grok", "--project-from-cwd"] def apply(self) -> bool: cmd = f"grok mcp add --scope user serena -- {self.get_mcp_server_command()}" is_success = self._run_shell_command(cmd) if is_success: click.echo("\nIMPORTANT: We additionally recommend to set up hooks for Grok to ensure the best experience.") click.echo(" Please read the instructions here:") click.echo(" https://oraios.github.io/serena/02-usage/030_clients.html#grok") return is_success client_setup_handlers = [ ClientSetupHandlerClaudeCode(), ClientSetupHandlerCodeBuddy(), ClientSetupHandlerCodex(), ClientSetupHandlerGrok(), ] - src/serena/config/context_mode.py (11418 bytes)
""" Context and Mode configuration loader """ # SPDX-License-Identifier: GPL-3.0-or-later import os from dataclasses import dataclass, field from pathlib import Path from typing import TYPE_CHECKING, Self import yaml from sensai.util import logging from sensai.util.string import ToStringMixin from serena.config.serena_config import ApiInclusionDefinition, SerenaPaths, ToolInclusionDefinition from serena.constants import ( DEFAULT_CONTEXT, INTERNAL_MODE_YAMLS_DIR, SERENA_FILE_ENCODING, SERENAS_OWN_CONTEXT_YAMLS_DIR, SERENAS_OWN_MODE_YAMLS_DIR, ) if TYPE_CHECKING: pass log = logging.getLogger(__name__) def looks_like_yaml_path(s: str) -> bool: return os.sep in s or (os.altsep and os.altsep in s) or s.lower().endswith((".yml", ".yaml")) @dataclass(kw_only=True) class SerenaAgentMode(ToolInclusionDefinition, ApiInclusionDefinition, ToStringMixin): """Represents a mode of operation for the agent, typically read off a YAML file. An agent can be in multiple modes simultaneously as long as they are not mutually exclusive. The modes can be adjusted after the agent is running, for example for switching from planning to editing. """ name: str prompt: str """ a Jinja2 template for the generation of the system prompt. It is formatted by the agent (see SerenaAgent._format_prompt()). """ description: str = "" _yaml_path: Path | None = field(default=None, repr=False, compare=False) """ Internal field storing the path to the YAML file this mode was loaded from. Used to support loading modes from arbitrary file paths. """ def _tostring_includes(self) -> list[str]: return ["name"] def print_overview(self) -> None: """Print an overview of the mode.""" print(f"{self.name}:\n {self.description}") if self.excluded_tools: print(" excluded tools:\n " + ", ".join(sorted(self.excluded_tools))) if self.included_optional_tools: print(" included optional tools:\n " + ", ".join(sorted(self.included_optional_tools))) if self.fixed_tools: print(" fixed tools:\n " + ", ".join(sorted(self.fixed_tools))) if self.prompt: print(" defines initial prompt") @classmethod def from_yaml(cls, yaml_path: str | Path) -> Self: """Load a mode from a YAML file.""" yaml_as_path = Path(yaml_path).resolve() with Path(yaml_as_path).open(encoding=SERENA_FILE_ENCODING) as f: data = yaml.safe_load(f) name = data.pop("name", yaml_as_path.stem) return cls(name=name, _yaml_path=yaml_as_path, **data) @classmethod def get_path(cls, name: str, instance: Self | None = None) -> str: """Get the path to the YAML file for a mode. :param name: The name of the mode :param instance: Optional mode instance. If provided and it has a stored path, that path is returned. :return: The path to the mode's YAML file """ # If we have an instance with a stored path, use that if instance is not None and instance._yaml_path is not None: return str(instance._yaml_path) fname = f"{name}.yml" custom_mode_path = os.path.join(SerenaPaths().user_modes_dir, fname) if os.path.exists(custom_mode_path): return custom_mode_path own_yaml_path = os.path.join(SERENAS_OWN_MODE_YAMLS_DIR, fname) if not os.path.exists(own_yaml_path): raise FileNotFoundError( f"Mode {name} not found in {SerenaPaths().user_modes_dir} or in {SERENAS_OWN_MODE_YAMLS_DIR}." f"Available modes:\n{cls.list_registered_mode_names()}" ) return own_yaml_path @classmethod def from_name(cls, name: str) -> Self: """Load a registered Serena mode.""" mode_path = cls.get_path(name) return cls.from_yaml(mode_path) @classmethod def from_name_internal(cls, name: str) -> Self: """Loads an internal Serena mode""" yaml_path = os.path.join(INTERNAL_MODE_YAMLS_DIR, f"{name}.yml") if not os.path.exists(yaml_path): raise FileNotFoundError(f"Internal mode '{name}' not found in {INTERNAL_MODE_YAMLS_DIR}") return cls.from_yaml(yaml_path) @classmethod def list_registered_mode_names(cls, include_user_modes: bool = True) -> list[str]: """Names of all registered modes (from the corresponding YAML files in the serena repo).""" modes = [f.stem for f in Path(SERENAS_OWN_MODE_YAMLS_DIR).glob("*.yml") if f.name != "mode.template.yml"] if include_user_modes: modes += cls.list_custom_mode_names() return sorted(set(modes)) @classmethod def list_custom_mode_names(cls) -> list[str]: """Names of all custom modes defined by the user.""" return [f.stem for f in Path(SerenaPaths().user_modes_dir).glob("*.yml")] @classmethod def load(cls, name_or_path: str | Path) -> Self: # If it is a path or looks like a path, load from file if isinstance(name_or_path, Path) or looks_like_yaml_path(str(name_or_path)): path = Path(name_or_path) if path.exists() and path.is_file(): return cls.from_yaml(name_or_path) else: raise FileNotFoundError(f"Mode file not found: {path.resolve()}") # load from name return cls.from_name(str(name_or_path)) def has_prompt(self) -> bool: """ :return: whether this mode defines a prompt """ return bool(self.prompt and self.prompt.strip()) @dataclass(kw_only=True) class SerenaAgentContext(ToolInclusionDefinition, ApiInclusionDefinition, ToStringMixin): """Represents a context where the agent is operating (an IDE, a chat, etc.), typically read off a YAML file. An agent can only be in a single context at a time. The contexts cannot be changed after the agent is running. """ name: str """the name of the context""" prompt: str """ a Jinja2 template for the generation of the system prompt. It is formatted by the agent (see SerenaAgent._format_prompt()). """ description: str = "" tool_description_overrides: dict[str, str] = field(default_factory=dict) """ maps tool names to custom descriptions, default descriptions are extracted from the tool docstrings. """ _yaml_path: Path | None = field(default=None, repr=False, compare=False) """ Internal field storing the path to the YAML file this context was loaded from. Used to support loading contexts from arbitrary file paths. """ single_project: bool = False """ whether to assume that Serena shall only work on a single project in this context (provided that a project is given when Serena is started). If set to true and a project is provided at startup, the set of tools is limited to those required by the project's concrete configuration, and other tools are excluded completely, allowing the set of tools to be minimal. The `activate_project` tool will, therefore, be disabled in this case, as project switching is not allowed. """ structured_tool_output: bool | None = None """ whether to use structured output for tools (None = auto) """ def _tostring_includes(self) -> list[str]: return ["name"] @classmethod def from_yaml(cls, yaml_path: str | Path) -> Self: """Load a context from a YAML file.""" yaml_as_path = Path(yaml_path).resolve() with yaml_as_path.open(encoding=SERENA_FILE_ENCODING) as f: data = yaml.safe_load(f) name = data.pop("name", yaml_as_path.stem) # Ensure backwards compatibility for tool_description_overrides if "tool_description_overrides" not in data: data["tool_description_overrides"] = {} return cls(name=name, _yaml_path=yaml_as_path, **data) @classmethod def get_path(cls, name: str, instance: Self | None = None) -> str: """Get the path to the YAML file for a context. :param name: The name of the context :param instance: Optional context instance. If provided and it has a stored path, that path is returned. :return: The path to the context's YAML file """ # If we have an instance with a stored path, use that if instance is not None and instance._yaml_path is not None: return str(instance._yaml_path) fname = f"{name}.yml" custom_context_path = os.path.join(SerenaPaths().user_contexts_dir, fname) if os.path.exists(custom_context_path): return custom_context_path own_yaml_path = os.path.join(SERENAS_OWN_CONTEXT_YAMLS_DIR, fname) if not os.path.exists(own_yaml_path): raise FileNotFoundError( f"Context {name} not found in {SerenaPaths().user_contexts_dir} or in {SERENAS_OWN_CONTEXT_YAMLS_DIR}." f"Available contexts:\n{cls.list_registered_context_names()}" ) return own_yaml_path @classmethod def from_name(cls, name: str) -> Self: """Load a registered Serena context.""" legacy_name_mapping = { "ide-assistant": "claude-code", } if name in legacy_name_mapping: log.warning( f"Context name '{name}' is deprecated and has been renamed to '{legacy_name_mapping[name]}'. " f"Please update your configuration; refer to the configuration guide for more details: " "https://oraios.github.io/serena/02-usage/050_configuration.html#contexts" ) name = legacy_name_mapping[name] context_path = cls.get_path(name) return cls.from_yaml(context_path) @classmethod def load(cls, name_or_path: str | Path) -> Self: # If it is a path or looks like a path, load from file if isinstance(name_or_path, Path) or looks_like_yaml_path(str(name_or_path)): path = Path(name_or_path) if path.exists() and path.is_file(): return cls.from_yaml(name_or_path) else: raise FileNotFoundError(f"Context file not found: {path.resolve()}") return cls.from_name(str(name_or_path)) @classmethod def list_registered_context_names(cls, include_user_contexts: bool = True) -> list[str]: """Names of all registered contexts (from the corresponding YAML files in the serena repo).""" contexts = [f.stem for f in Path(SERENAS_OWN_CONTEXT_YAMLS_DIR).glob("*.yml")] if include_user_contexts: contexts += cls.list_custom_context_names() return sorted(set(contexts)) @classmethod def list_custom_context_names(cls) -> list[str]: """Names of all custom contexts defined by the user.""" return [f.stem for f in Path(SerenaPaths().user_contexts_dir).glob("*.yml")] @classmethod def load_default(cls) -> Self: """Load the default context.""" return cls.from_name(DEFAULT_CONTEXT) def print_overview(self) -> None: """Print an overview of the mode.""" print(f"{self.name}:\n {self.description}") if self.excluded_tools: print(" excluded tools:\n " + ", ".join(sorted(self.excluded_tools))) - src/serena/config/serena_config.py (71160 bytes)
""" The Serena Model Context Protocol (MCP) Server """ # SPDX-License-Identifier: GPL-3.0-or-later import dataclasses import os import re import shutil import stat import threading from collections.abc import Iterator, Sequence from copy import deepcopy from dataclasses import dataclass, field from datetime import UTC, datetime from enum import Enum from pathlib import Path from typing import TYPE_CHECKING, Any, Optional, Self, TypeVar from uuid import uuid4 import yaml from filelock import FileLock from ruamel.yaml.comments import CommentedMap from sensai.util import logging from sensai.util.logging import LogTime from sensai.util.string import ToStringMixin from serena.constants import ( DEFAULT_SOURCE_FILE_ENCODING, PROJECT_LOCAL_TEMPLATE_FILE, PROJECT_TEMPLATE_FILE, REPO_ROOT, SERENA_CONFIG_TEMPLATE_FILE, SERENA_FILE_ENCODING, SERENA_MANAGED_DIR_NAME, ) from serena.util.inspection import compute_language_server_support_composition from serena.util.text_utils import GlobMatcher from serena.util.yaml import YamlCommentNormalisation, load_yaml, normalise_yaml_comments, save_yaml, transfer_yaml_comments from solidlsp.ls_config import LanguageServerIdLike, LanguageServerRegistry from ..analytics import RegisteredTokenCountEstimator from ..language_backend import BuiltinLanguageBackend, LanguageBackend, LanguageBackendRegistry from ..util.cli_util import ask_yes_no from ..util.dataclass import get_dataclass_default from .serena_paths import SerenaPaths if TYPE_CHECKING: from ..project import Project log = logging.getLogger(__name__) T = TypeVar("T") DEFAULT_TOOL_TIMEOUT: float = 240 DictType = dict | CommentedMap TDict = TypeVar("TDict", bound=DictType) @dataclass class ToolInclusionDefinition: """ Defines which tools to include/exclude in Serena's operation. This can mean either * defining exclusions/inclusions to apply to an existing set of tools [incremental mode], or * defining a fixed set of tools to use [fixed mode]. """ excluded_tools: Sequence[str] = () """ the names of tools (or markers) to exclude from use [incremental mode] """ included_optional_tools: Sequence[str] = () """ the names of (optional/disabled) tools (or markers) to include [incremental mode] """ fixed_tools: Sequence[str] = () """ the names of tools to use as a fixed set of tools [fixed mode] """ def is_fixed_tool_set(self) -> bool: num_fixed = len(self.fixed_tools) num_incremental = len(self.excluded_tools) + len(self.included_optional_tools) if num_fixed > 0 and num_incremental > 0: raise ValueError("Cannot use both fixed_tools and excluded_tools/included_optional_tools at the same time.") return num_fixed > 0 @dataclass class NamedToolInclusionDefinition(ToolInclusionDefinition): name: str | None = None def __str__(self) -> str: return f"ToolInclusionDefinition[{self.name}]" @dataclass class ApiInclusionDefinition: """ Defines which APIs to include/exclude in Serena's operation. A single API inclusion/exclusion can either be a full facade (facade name, which encompasses all of its methods, e.g. "lsp") or a method of a facade (facade name + method name, e.g. "lsp.find_symbol"). Exclusions can additionally define `marker:editing` to exclude functions capable of modifying the project. """ MARKER_EDITING = "marker:editing" included_apis: Sequence[str] = () excluded_apis: Sequence[str] = () @dataclass class NamedApiInclusionDefinition(ApiInclusionDefinition): name: str | None = None def __str__(self) -> str: return f"ApiInclusionDefinition[{self.name}]" @dataclass class ModeSelectionDefinition: default_modes: Sequence[str] | None = None @dataclass class ModeSelectionDefinitionWithBaseModes(ModeSelectionDefinition): base_modes: Sequence[str] | None = ("interactive", "editing") """ the base modes to use, which are always guaranteed to be included """ @dataclass class ModeSelectionDefinitionWithAddedModes(ModeSelectionDefinition): added_modes: Sequence[str] | None = None class AgentInterface(Enum): """ The interface through which the agent (LLM) accesses Serena's functionality. """ TOOLS = "tools" """ The classic tool interface: each operation is a separate tool, and the set of tools is configurable (via tool inclusions/exclusions in the configuration, context, modes and project). """ REPL = "REPL" """ The REPL interface: operations are accessed programmatically via the serena_repl tool, which executes Python code. The set of tools is fixed (the REPL tool and the tools required for session management) and tool inclusions/exclusions do not apply; the operations available in the REPL are configured via API inclusions/exclusions instead. """ @staticmethod def from_str(interface_str: str) -> "AgentInterface": for interface in AgentInterface: if interface.value.lower() == interface_str.lower(): return interface raise ValueError(f"Unknown agent interface '{interface_str}': valid values are {[i.value for i in AgentInterface]}") def is_tools(self) -> bool: return self == AgentInterface.TOOLS def is_repl(self) -> bool: return self == AgentInterface.REPL class LineEnding(Enum): """Line ending convention for file writes.""" LF = "lf" CRLF = "crlf" NATIVE = "native" @property def newline_str(self) -> str | None: """The newline parameter value for :func:`open` and :meth:`Path.write_text`. Returns ``None`` for native mode (platform default). """ if self is LineEnding.LF: return "\n" elif self is LineEnding.CRLF: return "\r\n" return None @classmethod def from_str(cls, value: str) -> "LineEnding": """Parse a string value into a :class:`LineEnding`.""" try: return cls(value.lower()) except ValueError as e: valid = [le.value for le in cls] raise ValueError(f"Invalid line_ending: {value!r}. Valid values are: {valid}") from e @dataclass class SharedConfig(ToolInclusionDefinition, ApiInclusionDefinition, ToStringMixin): """Shared between SerenaConfig and ProjectConfig, the latter used to override values in the form (same as in ModeSelectionDefinition). The defaults here shall be none and should be set to the global default values in SerenaConfig. """ symbol_info_budget: float | None = None language_backend: LanguageBackend | None = None agent_interface: AgentInterface | None = None line_ending: LineEnding | None = None read_only_memory_patterns: list[str] = field(default_factory=list) ignored_memory_patterns: list[str] = field(default_factory=list) ls_specific_settings: dict = field(default_factory=dict) """Advanced configuration option allowing to configure language server implementation specific options, see SolidLSPSettings for more info.""" class SerenaConfigError(Exception): pass DEFAULT_PROJECT_SERENA_FOLDER_LOCATION = "$projectDir/" + SERENA_MANAGED_DIR_NAME """ The default template for the project Serena folder location. Uses $projectDir and $projectFolderName as placeholders. """ class ProjectConfigAutoGenerationMode(Enum): NONE = "none" """ no auto-generation """ SYNCHRONOUS = "sync" """ synchronous auto-generation, i.e. the configuration is fully generated before returning from the function call """ ASYNCHRONOUS = "async" """ asynchronous auto-generation, where time-consuming configuration parts (currently only the list of programming languages) are determined in a background thread and initialised as empty """ def is_autogen_enabled(self): return self != ProjectConfigAutoGenerationMode.NONE @dataclass(kw_only=True) class ProjectConfig(SharedConfig, ModeSelectionDefinitionWithAddedModes): project_name: str language_servers: list[LanguageServerIdLike] ignored_paths: list[str] = field(default_factory=list) ls_workspace_folders: list[str] = field(default_factory=lambda: ["."]) ls_additional_workspace_folders: list[str] = field(default_factory=list) read_only: bool = False ignore_all_files_in_gitignore: bool = True initial_prompt: str = "" encoding: str = DEFAULT_SOURCE_FILE_ENCODING activation_command: str | None = None activation_command_timeout: float = 180.0 # internal fields which are not mapped to/from the configuration file (must start with "_") _local_override_keys: list[str] = field(default_factory=list) # class-level members SERENA_PROJECT_FILE = "project.yml" SERENA_LOCAL_PROJECT_FILE = "project.local.yml" FIELDS_WITHOUT_DEFAULTS = {"project_name", "language_servers"} RENAMED_FIELDS = {"additional_workspace_folders": "ls_additional_workspace_folders", "languages": "language_servers"} YAML_COMMENT_NORMALISATION = YamlCommentNormalisation.LEADING """ the comment normalisation strategy to use when loading/saving project configuration files. The template file must match this configuration (i.e. it must use leading comments if this is set to LEADING). """ _async_completion_events = {} """ maps the object id of a ProjectConfig instance to an event which is set when the asynchronous auto-generation of the configuration is complete (if applicable). """ _save_lock = threading.Lock() def _tostring_includes(self) -> list[str]: return ["project_name"] @classmethod def _determine_project_language_servers( cls, project_root: str, interactive: bool, serena_config: "SerenaConfig" ) -> list[LanguageServerIdLike]: log.info("Determining suitable language servers for the project") # determine language servers to be considered and their priorities # the registry is the single source of truth — it includes both built-in enum members # and externally-registered adapters (via solidlsp.language_server_registration entry points). # priorities are user-configurable per-key via serena_config.ls_priorities (works for both kinds). ls_priorities: dict[LanguageServerIdLike, int] = {} registry = LanguageServerRegistry.get_instance() for ls_id in registry.iter_registered_ls_ids(): priority = serena_config.get_ls_priority(ls_id) if priority > 0: ls_priorities[ls_id] = priority log.debug("Language server priorities: %s", ls_priorities) ls_composition = compute_language_server_support_composition(project_root, list(ls_priorities.keys())) log.info("Project composition: %s", ls_composition) if len(ls_composition) == 0: log.warning( "No source files for supported language servers were found in %s. " "Creating project with no configured language servers. " "Symbol-related tools (e.g. find_symbol, get_symbols_overview) will not work " "when using the LSP backend. You can add languages later via the Serena dashboard " "or by manually editing the project configuration.", project_root, ) language_servers_to_use = [] else: # sort languages by number of files found languages_and_percentages = sorted(ls_composition.items(), key=lambda item: (item[1], ls_priorities[item[0]]), reverse=True) # find the language with the highest percentage and enable it top_language_pair = languages_and_percentages[0] other_language_pairs = languages_and_percentages[1:] language_servers_to_use = [top_language_pair[0]] # if in interactive mode, ask the user which other languages to enable if len(other_language_pairs) > 0 and interactive: print( "Detected and enabled main language server '%s' (%.2f%% of source files)." % (top_language_pair[0].get_key(), top_language_pair[1]) ) print(f"Additionally detected {len(other_language_pairs)} other applicable language servers.\n") print("Note: Enable only servers for languages you need symbolic retrieval/editing capabilities for.") print(" Additional language servers use resources and some may require additional") print(" system-level installations/configuration (see Serena documentation).") print("\nWhich additional language servers do you want to enable?") for ls_id, perc in other_language_pairs: enable = ask_yes_no("Enable %s (%.2f%% of source files)?" % (ls_id.get_key(), perc), default=False) if enable: language_servers_to_use.append(ls_id) print() log.info("Using language servers: %s", language_servers_to_use) return language_servers_to_use @classmethod def autogenerate( cls, project_root: str | Path, serena_config: "SerenaConfig", project_name: str | None = None, languages: list[LanguageServerIdLike] | None = None, save_to_disk: bool = True, interactive: bool = False, asynchronous: bool = False, ) -> Self: """ Autogenerate a project configuration for a given project root. :param project_root: the path to the project root :param serena_config: the global Serena configuration :param project_name: the name of the project; if None, the name of the project will be the name of the directory containing the project :param languages: the languages of the project; if None, they will be determined automatically :param save_to_disk: whether to save the project configuration to disk :param interactive: whether to run in interactive CLI mode, asking the user for input where appropriate :param asynchronous: whether to run in asynchronous mode, where time-consuming configuration parts (currently only the determination of the list of programming languages) are determined in a background thread and initialised as empty :return: the project configuration """ if interactive and asynchronous: raise ValueError("Cannot use interactive mode with asynchronous auto-generation") project_root = Path(project_root).resolve() if not project_root.exists(): raise FileNotFoundError(f"Project root not found: {project_root}") with LogTime("Project configuration auto-generation", logger=log): log.info("Project root: %s", project_root) project_folder_name - src/serena/config/serena_paths.py (4361 bytes)
""" The Serena Model Context Protocol (MCP) Server """ # SPDX-License-Identifier: GPL-3.0-or-later import os from datetime import datetime from pathlib import Path from sensai.util import logging from sensai.util.logging import datetime_tag from serena.constants import ( REPO_ROOT, RESOURCES_DIR, SERENA_MANAGED_DIR_NAME, ) from ..util.class_decorators import singleton log = logging.getLogger(__name__) @singleton class SerenaPaths: """ Provides paths to various Serena-related directories and files. """ def __init__(self) -> None: home_dir = os.getenv("SERENA_HOME") if home_dir is None or home_dir.strip() == "": home_dir = str(Path.home() / SERENA_MANAGED_DIR_NAME) else: home_dir = home_dir.strip() self.resources_dir: str = RESOURCES_DIR """ the resources directory (within the `serena` package) """ self.serena_user_home_dir: str = home_dir """ the path to the Serena home directory, where the user's configuration/data is stored. This is ~/.serena by default, but it can be overridden via the SERENA_HOME environment variable. """ self.user_prompt_templates_dir: str = os.path.join(self.serena_user_home_dir, "prompt_templates") """ directory containing prompt templates defined by the user. Prompts defined by the user take precedence over Serena's built-in prompt templates. """ self.user_contexts_dir: str = os.path.join(self.serena_user_home_dir, "contexts") """ directory containing contexts defined by the user. If a name of a context matches a name of a context in SERENAS_OWN_CONTEXT_YAMLS_DIR, the user context will override the default context definition. """ self.user_modes_dir: str = os.path.join(self.serena_user_home_dir, "modes") """ directory containing modes defined by the user. If a name of a mode matches a name of a mode in SERENAS_OWN_MODES_YAML_DIR, the user mode will override the default mode definition. """ self.news_legacy_last_read_id_file: str = os.path.join(self.serena_user_home_dir, "last_read_news_snippet_id.txt") """ file containing the ID of the last read news snippet """ self.news_read_items_file: str = os.path.join(self.serena_user_home_dir, "news_read.pkl") """ file containing the ID of the last read news snippet """ self.news_etag_file: str = os.path.join(self.serena_user_home_dir, "news_etag.txt") """ file containing the ETag of the last fetched remote news JSON """ self.news_file: str = os.path.join(self.serena_user_home_dir, "news.json") """ local cache of the remote news JSON file """ self.news_dir: str = os.path.join(REPO_ROOT, "news") """ repository news directory containing the source HTML snippets and generated news.json """ global_memories_path = Path(os.path.join(self.serena_user_home_dir, "memories", "global")) global_memories_path.mkdir(parents=True, exist_ok=True) self.global_memories_path = global_memories_path """ directory where global memories are stored, i.e. memories that are available across all projects """ self.last_returned_log_file_path: str | None = None """ the path to the last log file returned by `get_next_log_file_path`. If this is not None, the logs are currently being written to this file """ def get_next_log_file_path(self, prefix: str) -> str: """ :param prefix: the filename prefix indicating the type of the log file :return: the full path to the log file to use """ log_dir = os.path.join(self.serena_user_home_dir, "logs", datetime.now().strftime("%Y-%m-%d")) os.makedirs(log_dir, exist_ok=True) self.last_returned_log_file_path = os.path.join(log_dir, prefix + "_" + datetime_tag() + f"_{os.getpid()}" + ".txt") return self.last_returned_log_file_path def get_resource_path(self, *path_elems: str) -> Path: return Path(os.path.join(self.resources_dir, *path_elems)) # TODO: Paths from constants.py should be moved here - src/serena/constants.py (1975 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from pathlib import Path _repo_root_path = Path(__file__).parent.parent.parent.resolve() _serena_pkg_path = Path(__file__).parent.resolve() _resources_path = _serena_pkg_path / "resources" SERENA_MANAGED_DIR_NAME = ".serena" # TODO: Path-related constants should be moved to SerenaPaths; don't add further constants here. REPO_ROOT = str(_repo_root_path) RESOURCES_DIR = str(_resources_path) PROMPT_TEMPLATES_DIR_INTERNAL = str(_resources_path / "config" / "prompt_templates") SERENAS_OWN_CONTEXT_YAMLS_DIR = str(_resources_path / "config" / "contexts") """The contexts that are shipped with the Serena package, i.e. the default contexts.""" SERENAS_OWN_MODE_YAMLS_DIR = str(_resources_path / "config" / "modes") """The modes that are shipped with the Serena package, i.e. the default modes.""" INTERNAL_MODE_YAMLS_DIR = str(_resources_path / "config" / "internal_modes") """Internal modes, never overridden by user modes.""" SERENA_DASHBOARD_DIR = str(_resources_path / "dashboard") SERENA_ICON_DIR = str(_resources_path / "icons") DEFAULT_SOURCE_FILE_ENCODING = "utf-8" """The default encoding assumed for project source files.""" DEFAULT_CONTEXT = "desktop-app" SERENA_FILE_ENCODING = "utf-8" """The encoding used for Serena's own files, such as configuration files and memories.""" PROJECT_TEMPLATE_FILE = str(_resources_path / "project.template.yml") PROJECT_LOCAL_TEMPLATE_FILE = str(_resources_path / "project.local.template.yml") SERENA_CONFIG_TEMPLATE_FILE = str(_resources_path / "serena_config.template.yml") SERENA_LOG_FORMAT = "%(levelname)-5s %(asctime)-15s [%(threadName)s] %(name)s:%(funcName)s:%(lineno)d - %(message)s" LOG_MESSAGES_BUFFER_SIZE = 2500 """The maximum number of log messages to keep in the buffer (for the dashboard).""" class SerenaPorts: TRAY_MANAGER_PORT = 0x5EA0 PROJECT_SERVER_PORT = 0x5EA1 JETBRAINS_PLUGIN_SERVER_BASE_PORT = 0x5EA2 DASHBOARD_API_BASE_PORT = 0x5EDA - src/serena/dashboard/dashboard_api.py (36635 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json import os import pickle import socket import threading import urllib.error import urllib.request from html import escape from typing import TYPE_CHECKING, Any, Self from flask import Flask, Response, redirect, request, send_from_directory from pydantic import BaseModel from sensai.util import logging from sensai.util.pickle import dump_pickle from serena.analytics import ToolUsageStats from serena.config.serena_config import SerenaConfig, SerenaPaths from serena.constants import SERENA_DASHBOARD_DIR, SerenaPorts from serena.task_executor import TaskExecutor from serena.tools import ReadMemoryTool from serena.util.logging import MemoryLogHandler from serena.util.pypi import PyPIPackageInfo from serena.util.version import Version from solidlsp.ls_config import LanguageServerRegistry if TYPE_CHECKING: from serena.agent import SerenaAgent log = logging.getLogger(__name__) # disable Werkzeug's logging to avoid cluttering the output logging.getLogger("werkzeug").setLevel(logging.WARNING) class RequestLog(BaseModel): start_idx: int = 0 class ResponseLog(BaseModel): messages: list[str] max_idx: int active_project: str | None = None class ResponseToolNames(BaseModel): tool_names: list[str] class ResponseToolStats(BaseModel): stats: dict[str, dict[str, int]] class ResponseFacadeMethod(BaseModel): name: str is_enabled: bool class ResponseFacade(BaseModel): name: str is_enabled: bool methods: list[ResponseFacadeMethod] class ResponseConfigOverview(BaseModel): web_dashboard_open_on_launch: bool | None active_project: dict[str, str | bool | None] context: dict[str, str] modes: list[dict[str, str]] active_tools: list[str] agent_interface: str language_backend: str facades: list[ResponseFacade] | None tool_stats_summary: dict[str, dict[str, int]] repl_stats_summary: dict[str, dict[str, int]] registered_projects: list[dict[str, str | bool]] available_tools: list[dict[str, str | bool]] available_modes: list[dict[str, str | bool]] available_contexts: list[dict[str, str | bool]] available_memories: list[str] | None jetbrains_mode: bool languages: list[str] encoding: str | None current_client: str | None serena_version: str newer_serena_version: str | None class ResponseAvailableLanguages(BaseModel): languages: list[str] class RequestAddLanguage(BaseModel): language: str class RequestRemoveLanguage(BaseModel): language: str class RequestGetMemory(BaseModel): memory_name: str class ResponseGetMemory(BaseModel): content: str memory_name: str class RequestSaveMemory(BaseModel): memory_name: str content: str class RequestDeleteMemory(BaseModel): memory_name: str class RequestRenameMemory(BaseModel): old_name: str new_name: str class ResponseGetSerenaConfig(BaseModel): content: str class RequestSaveSerenaConfig(BaseModel): content: str class RequestCancelTaskExecution(BaseModel): task_id: int class QueuedExecution(BaseModel): task_id: int is_running: bool name: str finished_successfully: bool logged: bool @classmethod def from_task_info(cls, task_info: TaskExecutor.TaskInfo) -> Self: return cls( task_id=task_info.task_id, is_running=task_info.is_running, name=task_info.name, finished_successfully=task_info.finished_successfully(), logged=task_info.logged, ) class ReadNews: def __init__(self, read_ids: list[str], legacy_last_read_id: str | None = None): self._read_ids = set(read_ids) self._legacy_last_read_id = legacy_last_read_id @staticmethod def load() -> "ReadNews": read_news_path = SerenaPaths().news_read_items_file legacy_last_read_id_path = SerenaPaths().news_legacy_last_read_id_file def load_legacy_last_read_id() -> str | None: if not os.path.exists(legacy_last_read_id_path): return None with open(legacy_last_read_id_path, encoding="utf-8") as f: last_read_news_id = f.read().strip() if last_read_news_id == "20262103": last_read_news_id = "20260321" # fix originally misnamed news id return last_read_news_id class RemappingUnpickler(pickle.Unpickler): def find_class(self, module, name): if (module, name) == ("serena.dashboard", "ReadNews"): return ReadNews return super().find_class(module, name) if os.path.exists(read_news_path): with open(read_news_path, "rb") as f: return RemappingUnpickler(f).load() else: instance = ReadNews(read_ids=[], legacy_last_read_id=load_legacy_last_read_id()) instance._save() try: os.unlink(legacy_last_read_id_path) except: pass return instance def _save(self) -> None: dump_pickle(self, SerenaPaths().news_read_items_file) def is_read(self, identifier: str) -> bool: if identifier in self._read_ids: return True if self._legacy_last_read_id is not None and identifier <= self._legacy_last_read_id: return True return False def mark_read(self, identifier: str) -> None: """ Marks the given news snippet as read, saving the new state to disk """ self._read_ids.add(identifier) self._save() class SerenaDashboardAPI: BASE_PORT = SerenaPorts.DASHBOARD_API_BASE_PORT log = logging.getLogger(__qualname__) def __init__( self, memory_log_handler: MemoryLogHandler, tool_names: list[str], agent: "SerenaAgent", tool_usage_stats: ToolUsageStats | None = None, host: str = "127.0.0.1", trusted_hosts: list[str] | None = None, ) -> None: self._memory_log_handler = memory_log_handler self._tool_names = tool_names self._agent = agent self._host = host self._app = Flask(self.__class__.__name__) if trusted_hosts: self._app.config["TRUSTED_HOSTS"] = trusted_hosts self._tool_usage_stats = tool_usage_stats self._loaded_news: dict[str, str] = {} self._news_ready = threading.Event() self._setup_routes() self._read_news = ReadNews.load() self._newer_serena_version: str | None = None # register callback for config changes self._current_config_overview: dict[str, Any] | None = None self._agent.register_config_changed_callback(self._on_agent_config_changed) # start threads for background computations # * fetch remote news in background on startup (non-blocking) threading.Thread(target=self._fetch_news, daemon=True).start() # * determine if a newer Serena version is available threading.Thread(target=self._determine_newer_serena_version, daemon=True).start() @property def memory_log_handler(self) -> MemoryLogHandler: return self._memory_log_handler def _determine_newer_serena_version(self) -> str | None: """ Checks for availability of a newer Serena version on PyPI and stores it in self._newer_serena_version if found. """ try: # query PyPI for the latest released version latest_serena_version = PyPIPackageInfo("serena-agent").get_latest_version(timeout_secs=5) # compare against the running version latest_version = Version(latest_serena_version) current_version = Version(self._agent.version) log.debug("Latest available Serena version on PyPI: %s, current version: %s", latest_version, current_version) if not current_version.is_at_least(*latest_version.components): self._newer_serena_version = latest_serena_version except Exception as e: log.info("Failed to check for newer Serena version on PyPI: %s", e) def _setup_routes(self) -> None: @self._app.route("/") def redirect_to_dashboard() -> Response: return redirect("/dashboard/") # type: ignore[return-value] # Static files @self._app.route("/dashboard/<path:filename>") def serve_dashboard(filename: str) -> Response: return send_from_directory(SERENA_DASHBOARD_DIR, filename) @self._app.route("/dashboard/") def serve_dashboard_index() -> Response: return send_from_directory(SERENA_DASHBOARD_DIR, "index.html") # API routes @self._app.route("/heartbeat", methods=["GET"]) def get_heartbeat() -> dict[str, Any]: return {"status": "alive"} @self._app.route("/get_log_messages", methods=["POST"]) def get_log_messages() -> dict[str, Any]: request_data = request.get_json() if not request_data: request_log = RequestLog() else: request_log = RequestLog.model_validate(request_data) result = self._get_log_messages(request_log) return result.model_dump() @self._app.route("/get_tool_names", methods=["GET"]) def get_tool_names() -> dict[str, Any]: result = self._get_tool_names() return result.model_dump() @self._app.route("/get_tool_stats", methods=["GET"]) def get_tool_stats_route() -> dict[str, Any]: result = self._get_tool_stats() return result.model_dump() @self._app.route("/clear_tool_stats", methods=["POST"]) def clear_tool_stats_route() -> dict[str, str]: self._clear_tool_stats() return {"status": "cleared"} @self._app.route("/clear_logs", methods=["POST"]) def clear_logs() -> dict[str, str]: self._memory_log_handler.clear_log_messages() return {"status": "cleared"} @self._app.route("/get_token_count_estimator_name", methods=["GET"]) def get_token_count_estimator_name() -> dict[str, str]: estimator_name = self._tool_usage_stats.token_estimator_name if self._tool_usage_stats else "unknown" return {"token_count_estimator_name": estimator_name} @self._app.route("/get_config_overview", methods=["GET"]) def get_config_overview() -> dict[str, Any]: result = self._current_config_overview if result is None: raise ValueError("Config overview not yet available") return result @self._app.route("/save_web_dashboard_open_on_launch", methods=["POST"]) def save_web_dashboard_open_on_launch() -> dict[str, str]: # require an explicit boolean choice request_data = request.get_json() value = request_data.get("web_dashboard_open_on_launch") if isinstance(request_data, dict) else None if not isinstance(value, bool): return {"status": "error", "message": "web_dashboard_open_on_launch must be a boolean"} # persist the preference through the task executor def run() -> None: self._agent.serena_config.save_web_dashboard_open_on_launch(value) try: self._agent.issue_task(run, logged=True, name="SaveWebDashboardOpenOnLaunch") return {"status": "success"} except Exception as e: return {"status": "error", "message": str(e)} @self._app.route("/shutdown", methods=["PUT"]) def shutdown() -> dict[str, str]: self._agent.shutdown() return {"status": "shutting down"} @self._app.route("/get_available_languages", methods=["GET"]) def get_available_languages() -> dict[str, Any]: result = self._get_available_languages() return result.model_dump() @self._app.route("/add_language", methods=["POST"]) def add_language() -> dict[str, str]: request_data = request.get_json() if not request_data: return {"status": "error", "message": "No data provided"} request_add_language = RequestAddLanguage.model_validate(request_data) try: self._add_language(request_add_language) return {"status": "success", "message": f"Language {request_add_language.language} added successfully"} except Exception as e: return {"status": "error", "message": str(e)} @self._app.route("/remove_language", methods=["POST"]) def remove_language() -> dict[str, str]: request_data = request.get_json() if not request_data: return {"status": "error", "message": "No data provided"} request_remove_language = RequestRemoveLanguage.model_validate(request_data) try: self._remove_language(request_remove_language) return {"status": "success", "message": f"Language {request_remove_language.language} removed successfully"} except Exception as e: return {"status": "error", "message": str(e)} @self._app.route("/get_memory", methods=["POST"]) def get_memory() -> dict[str, Any]: request_data = request.get_json() if not request_data: return {"status": "error", "message": "No data provided"} request_get_memory = RequestGetMemory.model_validate(request_data) try: result = self._get_memory(request_get_memory) return result.model_dump() except Exception as e: return {"status": "error", "message": str(e)} @self._app.route("/save_memory", methods=["POST"]) def save_memory() -> dict[str, str]: request_data = request.get_json() if not request_data: return {"status": "error", "message": "No data provided"} request_save_memory = RequestSaveMemory.model_validate(request_data) try: self._save_memory(request_save_memory) return {"status": "success", "message": f"Memory {request_save_memory.memory_name} saved successfully"} except Exception as e: return {"status": "error", "message": str(e)} @self._app.route("/delete_memory", methods=["POST"]) def delete_memory() -> dict[str, str]: request_data = request.get_json() if not request_data: return {"status": "error", "message": "No data provided"} request_delete_memory = RequestDeleteMemory.model_validate(request_data) try: self._delete_memory(request_delete_memory) - src/serena/dashboard/dashboard_tray_manager.py (18327 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json import multiprocessing import os import subprocess import sys import threading import time import urllib.error import urllib.request from collections.abc import Callable from dataclasses import dataclass from pathlib import Path from typing import Any, Optional import psutil from flask import Flask, request from PIL import Image from sensai.util import logging from serena.config.serena_paths import SerenaPaths from serena.constants import SERENA_DASHBOARD_DIR, SerenaPorts from serena.dashboard.dashboard_viewer import SerenaDashboardViewer, open_url_in_browser from serena.util.tray import create_tray_icon log = logging.getLogger(__name__) @dataclass class TrayManagedInstance: """A registered Serena dashboard instance managed by the tray manager.""" port: int """the port on which the dashboard API is listening""" parent_process: psutil.Process """the process of the Serena agent owning this dashboard instance""" dashboard_url: str """the full URL to the dashboard frontend""" project: str | None """the name of the active project, or None if no project is activated""" started_at: str """ISO 8601 timestamp of when the agent instance was started""" class SerenaDashboardTrayManager: """ Singleton process managing a system tray icon for all Serena dashboard instances. Runs a Flask backend on a fixed port and displays a single tray icon that aggregates all running Serena instances. Individual dashboard viewers are spawned on demand when the user clicks a menu item. The manager is started as a detached process by the first Serena agent that needs it and terminates automatically when no dashboard instances remain. """ DEBUG = False PORT = SerenaPorts.TRAY_MANAGER_PORT HOST = "127.0.0.1" """listen address (local only)""" TRUSTED_HOSTS = ["localhost", "127.0.0.1"] ALIVE_CHECK_INTERVAL_SECONDS = 3 """interval in seconds between alive checks of registered instances""" def __init__(self) -> None: """ NOTE: This constructor is called in `ensure_running` (string execution) """ import pystray self._instances: dict[int, TrayManagedInstance] = {} self._lock = threading.Lock() self._tray_icon: Optional["pystray.Icon"] = None self._alive_check_use_pid = True """ whether to use the process ID for alive checks of registered instances. If True, the manager will check whether the process with the registered PID is still running. If False, the manager will perform an HTTP request to the instance's heartbeat endpoint to check if it's alive. """ self._app = Flask(self.__class__.__name__) self._app.config["TRUSTED_HOSTS"] = self.TRUSTED_HOSTS self._use_pywebview = False """ whether to use pywebview-based viewer applications (separate child processes) for opening dashboards; if False, open them directly in the user's default web browser. """ self._setup_routes() def _setup_routes(self) -> None: @self._app.route("/health", methods=["GET"]) def health() -> dict[str, str]: return {"status": "alive"} @self._app.route("/register", methods=["POST"]) def register() -> dict[str, str]: data = request.get_json() instance = TrayManagedInstance( port=data["port"], parent_process=psutil.Process(data["pid"]), dashboard_url=data["dashboard_url"], project=data.get("project"), started_at=data["started_at"], ) log.info("Registering instance on port %d (project=%s)", instance.port, instance.project) with self._lock: self._instances[instance.port] = instance self._update_menu() # open a viewer immediately if requested if data.get("open_viewer", False): self._open_dashboard(instance) return {"status": "registered"} @self._app.route("/update_project", methods=["POST"]) def update_project() -> dict[str, str]: data = request.get_json() port = data["port"] project = data.get("project") with self._lock: if port in self._instances: self._instances[port].project = project self._update_menu() log.info("Updated project for instance on port %d to '%s'", port, project) return {"status": "updated"} @self._app.route("/unregister", methods=["POST"]) def unregister() -> dict[str, str]: data = request.get_json() port = data["port"] with self._lock: self._instances.pop(port, None) self._update_menu() log.info("Unregistered instance on port %d", port) return {"status": "unregistered"} @staticmethod def _run_in_ui_thread(fn: Callable[[], None]) -> None: """ Runs a UI mutation in the thread in which the platform's UI toolkit requires it to run (where necessary). On macOS, AppKit demands that mutations of the status item happen on the main thread, and recent macOS versions terminate the process with SIGTRAP when they do not. The tray manager reaches such mutations from Flask request handlers and from the alive-check thread, so the call has to be marshalled. On other platforms it is made directly. :param fn: the UI mutation to run """ if sys.platform == "darwin": from PyObjCTools import AppHelper # ty: ignore[unresolved-import] AppHelper.callAfter(fn) else: fn() def _update_menu(self) -> None: if self._tray_icon: self._run_in_ui_thread(self._tray_icon.update_menu) def _build_menu_items(self) -> tuple[Any, ...]: """ Callable that returns the current tray menu items. Invoked dynamically by pystray each time the menu is shown. When there is exactly one instance, it is marked as the default action so that a left-click on the tray icon opens the viewer immediately. When there are multiple instances, a hidden default item forces the menu to appear on left-click (Windows only; macOS always shows the menu). """ from pystray import MenuItem as Item with self._lock: instances = list(self._instances.values()) if not instances: return (Item("No instances", None, enabled=False),) # determine whether a single-instance shortcut applies is_single = len(instances) == 1 items: list[Any] = [] # for multi-instance: add a hidden default item that opens the menu on left-click if not is_single: def _force_show_menu(icon: Any, _item: Any) -> None: if hasattr(icon, "_show_menu"): icon._show_menu() items.append(Item("Instances", _force_show_menu, default=True, visible=False)) for inst in sorted(instances, key=lambda i: i.started_at): label = f"{inst.project or 'SerenaAgent'} ({inst.started_at})" # closure to capture the current instance def _make_callback(instance: TrayManagedInstance) -> Callable: def _callback(_icon: Any, _item: Any) -> None: self._open_dashboard(instance) return _callback items.append(Item(label, _make_callback(inst), default=is_single)) return tuple(items) def _open_dashboard(self, instance: TrayManagedInstance) -> None: """Opens the dashboard of the given instance.""" if self._use_pywebview: # spawn pywebview process showing the dashboard process = multiprocessing.Process( target=self._run_viewer, args=(instance.dashboard_url,), daemon=True, ) process.start() else: open_url_in_browser(instance.dashboard_url) @staticmethod def _run_viewer(url: str) -> None: """Process target for running a dashboard viewer window.""" SerenaDashboardViewer(url, tray=False, start_minimized=False).run() def _alive_check_loop(self) -> None: """Periodically check whether registered instances are still reachable. Removes unreachable instances and terminates the manager when none remain. """ time.sleep(max(1, 5 - self.ALIVE_CHECK_INTERVAL_SECONDS)) # initial delay to allow instances to start and register while True: time.sleep(self.ALIVE_CHECK_INTERVAL_SECONDS) try: dead_ports: list[int] = [] if self._alive_check_use_pid: with self._lock: ports_and_processes = [(port, inst.parent_process) for port, inst in self._instances.items()] dead_ports = [] for port, process in ports_and_processes: is_dead = False try: if not process.is_running(): is_dead = True except psutil.NoSuchProcess: # parent process already exited is_dead = True if is_dead: dead_ports.append(port) else: # collect ports to check with self._lock: ports_to_check = list(self._instances.keys()) # probe each instance for port in ports_to_check: try: url = f"http://127.0.0.1:{port}/heartbeat" req = urllib.request.Request(url, method="GET") urllib.request.urlopen(req, timeout=1) except Exception: dead_ports.append(port) # remove dead instances if dead_ports: with self._lock: for port in dead_ports: self._instances.pop(port, None) log.info("Removed unreachable instance on port %d", port) self._update_menu() # terminate if no instances remain with self._lock: remaining = len(self._instances) if remaining == 0: log.info("No dashboard instances remaining; shutting down tray manager") if self._tray_icon is not None: self._tray_icon.stop() return except Exception as e: log.error("Error during alive check loop: %s", e, exc_info=e) def run(self) -> None: """Run the tray manager (blocking). Starts Flask, alive-check thread, and tray icon.""" import pystray if self.DEBUG: logging.configure(level=logging.DEBUG, stream=sys.stderr) logging.add_file_logger(SerenaPaths().get_next_log_file_path("tray-manager")) log.info("Starting tray manager") dashboard_path = Path(SERENA_DASHBOARD_DIR) # select the appropriate icon for the platform icon_filename = "serena-icon-tray-mac.png" if sys.platform == "darwin" else "serena-icon-48.png" icon_img = Image.open(dashboard_path / icon_filename) # start Flask in a background thread flask_thread = threading.Thread( target=lambda: self._app.run(host=self.HOST, port=self.PORT, debug=False, use_reloader=False, threaded=True), daemon=True, ) flask_thread.start() # start alive-check in a background thread alive_thread = threading.Thread(target=self._alive_check_loop, daemon=True) alive_thread.start() # set up tray icon with a dynamic menu (callable returns items on each open) kwargs: dict[str, Any] = {} if sys.platform == "darwin": from AppKit import NSApplication, NSApplicationActivationPolicyAccessory # ty: ignore[unresolved-import] (macOS only) nsapp = NSApplication.sharedApplication() # run as an accessory app so that only the menu bar icon is shown (no Dock icon) nsapp.setActivationPolicy_(NSApplicationActivationPolicyAccessory) kwargs["darwin_nsapplication"] = nsapp self._tray_icon = create_tray_icon( "serena_tray_manager", icon_img, "Serena", menu=pystray.Menu(self._build_menu_items), **kwargs, ) # blocks until stop() is called self._tray_icon.run() # ------------------------------------------------------------------ # Class-level helpers (used by agents to interact with the manager) # ------------------------------------------------------------------ @classmethod def is_current_platform_supported(cls) -> bool: """ :return: whether the current platform supports the tray manager """ # supported_platforms = ["win32", "darwin"] # return sys.platform in supported_platforms # TODO: Enable all platforms for the time being for users to try out (only Windows tested) return True @classmethod def is_running(cls) -> bool: """ :return: True if a tray manager process is already listening on the fixed port """ try: url = f"http://{cls.HOST}:{cls.PORT}/health" req = urllib.request.Request(url, method="GET") urllib.request.urlopen(req, timeout=2) return True except Exception: return False @classmethod def ensure_running(cls) -> None: """Ensure a tray manager process is running, starting one if necessary.""" log.info("Ensuring dashboard tray manager availability") if cls.is_running(): log.info("Dashboard tray manager is already running") return # spawn a detached process log.info("Starting new dashboard tray manager process") cmd = [ sys.executable, "-c", "from serena.dashboard.dashboard_tray_manager import SerenaDashboardTrayManager; SerenaDashboardTrayManager().run()", ] kwargs: dict[str, Any] = { "stdin": subprocess.DEVNULL, "stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL, } if sys.platform == "win32": # CREATE_NO_WINDOW suppresses the console; CREATE_NEW_PROCESS_GROUP - src/serena/dashboard/dashboard_viewer.py (4149 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import subprocess import sys import threading from pathlib import Path from sensai.util import logging from serena.config.serena_paths import SerenaPaths from serena.constants import SERENA_DASHBOARD_DIR from serena.util.pywebview import WebViewWithTray log = logging.getLogger(__name__) def open_url_in_browser(url: str, use_subprocess: bool = False) -> None: """ Opens the given URL in the user's default web browser, optionally using a subprocess to ensure that no output is written to stdout (highly problematic when run within a stdio MCP server context) :param url: the URL to open :param use_subprocess: whether to use a subprocess to opening the URL, making stdio contamination impossible """ if use_subprocess: # Use a subprocess to avoid any output from webbrowser.open being written to stdout try: p = subprocess.Popen( [sys.executable, "-c", f"import webbrowser; webbrowser.open({url!r})"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=False, ) threading.Thread(target=p.wait, daemon=True).start() except Exception as e: # Subprocess creation can fail in rare cases (e.g. on some Linux systems; possibly subprocess/glibc bug) # See #1363 log.error("Failed to open URL (%s) in subprocess; %s", url, e) else: import webbrowser webbrowser.open(url) class SerenaDashboardViewer(WebViewWithTray): """ Minimal pywebview wrapper that opens a dashboard in a native window with optional system tray. """ DEBUG = False def __init__( self, url: str, *, width: int = 1400, height: int = 900, start_minimized: bool = False, parent_process_id: int | None = None, tray: bool = True, ): """ :param url: the URL to open :param width: the width of the window :param height: the height of the window :param start_minimized: whether to start the window minimized (to the tray if tray is enabled) :param parent_process_id: the process ID of the parent Serena agent process, which is monitored for termination, automatically closing the dashboard when the parent process dies :param tray: whether to use a system tray icon (which the app minimizes to when the window is closed) """ dashboard_path = Path(SERENA_DASHBOARD_DIR) # .ico is Windows-only; macOS expects a PNG for the window/dock icon. app_icon_filename = "serena.ico" if sys.platform == "win32" else "serena-icon-1024-mac.png" app_icon_path = str(dashboard_path / app_icon_filename) tray_icon_filename = "serena-icon-tray-mac.png" if sys.platform == "darwin" else "serena-icon-48.png" tray_icon_path = str(dashboard_path / tray_icon_filename) super().__init__( url, title="Serena Dashboard", tray=tray, width=width, height=height, start_minimized=start_minimized, parent_process_id=parent_process_id, app_id="oraios.serena", app_icon_path=app_icon_path, tray_icon_path=tray_icon_path, ) @staticmethod def is_current_platform_supported() -> bool: """ :return: whether the current platform supports the native dashboard viewer (and tray manager). """ # supported on Windows and macOS; Linux support is problematic # (see https://github.com/oraios/serena/pull/1117#issuecomment-4128753943) supported_platforms = [ "win32", "darwin", ] return sys.platform in supported_platforms def run(self) -> None: if self.DEBUG: logging.configure(level=logging.DEBUG, stream=sys.stderr) logging.add_file_logger(SerenaPaths().get_next_log_file_path("dashboard-viewer")) super().run() - src/serena/generated/generated_prompt_factory.py (1954 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later # ruff: noqa # black: skip # mypy: ignore-errors # NOTE: This module is auto-generated from interprompt.autogenerate_prompt_factory_module, do not edit manually! from interprompt.prompt_factory import PromptFactoryBase from typing import Any class PromptFactory(PromptFactoryBase): """ A class for retrieving and rendering prompt templates and prompt lists. """ def get_info_jet_brains_debug_repl_template_string(self) -> str: return self.get_prompt_template_string("info_jet_brains_debug_repl") def create_info_jet_brains_debug_repl(self) -> str: return self._render_prompt("info_jet_brains_debug_repl", locals()) def get_onboarding_prompt_template_string(self) -> str: return self.get_prompt_template_string("onboarding_prompt") def create_onboarding_prompt(self, *, memory_maintenance_name: Any, system: Any) -> str: return self._render_prompt("onboarding_prompt", locals()) def get_connection_prompt_template_string(self) -> str: return self.get_prompt_template_string("connection_prompt") def create_connection_prompt(self) -> str: return self._render_prompt("connection_prompt", locals()) def get_system_prompt_template_string(self) -> str: return self.get_prompt_template_string("system_prompt") def create_system_prompt( self, *, available_markers: Any, available_tools: Any, context_system_prompt: Any, global_memories_list: Any, mode_system_prompts: Any, tool_names: Any, ) -> str: return self._render_prompt("system_prompt", locals()) def get_cc_system_prompt_override_template_string(self) -> str: return self.get_prompt_template_string("cc_system_prompt_override") def create_cc_system_prompt_override(self) -> str: return self._render_prompt("cc_system_prompt_override", locals()) - src/serena/generated/tool_capabilities.py (740 bytes)
"""Generated tool-capability metadata. Do not edit manually.""" EDIT_CAPABLE_TOOL_NAMES: frozenset[str] = frozenset( { "create_text_file", "delete_lines", "delete_memory", "edit_memory", "execute_shell_command", "insert_after_symbol", "insert_at_line", "insert_before_symbol", "jet_brains_inline_symbol", "jet_brains_move", "jet_brains_rename", "jet_brains_safe_delete", "onboarding", "rename_memory", "rename_symbol", "replace_content", "replace_in_files", "replace_lines", "replace_symbol_body", "safe_delete_symbol", "serena_repl", "write_memory", } ) - src/serena/gui_log_viewer.py (15723 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import queue import sys import threading import tkinter as tk import traceback from collections.abc import Callable from enum import Enum, auto from pathlib import Path from typing import Literal from serena import constants from serena.util.logging import MemoryLogHandler log = logging.getLogger(__name__) class LogLevel(Enum): DEBUG = auto() INFO = auto() WARNING = auto() ERROR = auto() DEFAULT = auto() class GuiLogViewer: """ A class that creates a Tkinter GUI for displaying log messages in a separate thread. The log viewer supports coloring based on log levels (DEBUG, INFO, WARNING, ERROR). It can also highlight tool names in boldface when they appear in log messages. """ def __init__( self, mode: Literal["dashboard", "error"], title="Log Viewer", memory_log_handler: MemoryLogHandler | None = None, width=800, height=600, shutdown_handler: Callable[[], None] | None = None, ): """ :param mode: the mode; if "dashboard", run a dashboard with logs and some control options; if "error", run a simple error log viewer (for fatal exceptions) :param title: the window title :param memory_log_handler: an optional log handler from which to obtain log messages; If not provided, must pass the instance to a `GuiLogViewerHandler` to add log messages. :param width: the initial window width :param height: the initial window height """ self.mode = mode self.title = title self.width = width self.height = height self.message_queue = queue.Queue() self.running = False self.log_thread = None self.menubar: tk.Menu | None = None self.tool_names = [] # List to store tool names for highlighting self.shutdown_handler = shutdown_handler # Define colors for different log levels self.log_colors = { LogLevel.DEBUG: "#808080", # Gray LogLevel.INFO: "#000000", # Black LogLevel.WARNING: "#FF8C00", # Dark Orange LogLevel.ERROR: "#FF0000", # Red LogLevel.DEFAULT: "#000000", # Black } if memory_log_handler is not None: for msg in memory_log_handler.get_log_messages().messages: self.message_queue.put(msg) memory_log_handler.add_emit_callback(lambda msg: self.message_queue.put(msg)) def start(self): """Start the log viewer in a separate thread.""" if not self.running: self.log_thread = threading.Thread(target=self.run_gui) self.log_thread.daemon = True self.log_thread.start() return True return False def stop(self): """Stop the log viewer.""" if self.running: # Add a sentinel value to the queue to signal the GUI to exit self.message_queue.put(None) return True return False def set_tool_names(self, tool_names): """ Set or update the list of tool names to be highlighted in log messages. Args: tool_names (list): A list of tool name strings to highlight """ self.tool_names = tool_names def set_dashboard_url(self, url: str) -> None: def copy_url(): self.root.clipboard_clear() self.root.clipboard_append(url) log.info(f"Copied dashboard URL to clipboard: {url}") if self.menubar is not None: dashboard_menu = tk.Menu(self.menubar, tearoff=0) dashboard_menu.add_command(label="Copy URL", command=copy_url) self.menubar.add_cascade(label="Dashboard", menu=dashboard_menu) def add_log(self, message): """ Add a log message to the viewer. Args: message (str): The log message to display """ self.message_queue.put(message) def _determine_log_level(self, message): """ Determine the log level from the message. Args: message (str): The log message Returns: LogLevel: The determined log level """ message_upper = message.upper() if message_upper.startswith("DEBUG"): return LogLevel.DEBUG elif message_upper.startswith("INFO"): return LogLevel.INFO elif message_upper.startswith("WARNING"): return LogLevel.WARNING elif message_upper.startswith("ERROR"): return LogLevel.ERROR else: return LogLevel.DEFAULT def _process_queue(self): """Process messages from the queue and update the text widget.""" try: while not self.message_queue.empty(): message = self.message_queue.get_nowait() # Check for sentinel value to exit if message is None: self.root.quit() return # Check if scrollbar is at the bottom before adding new text # Get current scroll position current_position = self.text_widget.yview() # If near the bottom (allowing for small floating point differences) was_at_bottom = current_position[1] > 0.99 log_level = self._determine_log_level(message) # Insert the message at the end of the text with appropriate log level tag self.text_widget.configure(state=tk.NORMAL) # Find tool names in the message and highlight them if self.tool_names: # Capture start position (before insertion) start_index = self.text_widget.index("end-1c") # Insert the message self.text_widget.insert(tk.END, message + "\n", log_level.name) # Convert start index to line/char format line, char = map(int, start_index.split(".")) # Search for tool names in the message string directly for tool_name in self.tool_names: start_offset = 0 while True: found_at = message.find(tool_name, start_offset) if found_at == -1: break # Calculate line/column from offset offset_line = line offset_char = char for c in message[:found_at]: if c == "\n": offset_line += 1 offset_char = 0 else: offset_char += 1 # Construct index positions start_pos = f"{offset_line}.{offset_char}" end_pos = f"{offset_line}.{offset_char + len(tool_name)}" # Add tag to highlight the tool name self.text_widget.tag_add("TOOL_NAME", start_pos, end_pos) start_offset = found_at + len(tool_name) else: # No tool names to highlight, just insert the message self.text_widget.insert(tk.END, message + "\n", log_level.name) self.text_widget.configure(state=tk.DISABLED) # Auto-scroll to the bottom only if it was already at the bottom if was_at_bottom: self.text_widget.see(tk.END) # Schedule to check the queue again if self.running: self.root.after(100, self._process_queue) except Exception as e: print(f"Error processing message queue: {e}", file=sys.stderr) if self.running: self.root.after(100, self._process_queue) def run_gui(self): """Run the GUI""" self.running = True try: # Set app id (avoid app being lumped together with other Python-based apps in Windows taskbar) if sys.platform == "win32": import ctypes ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("oraios.serena") self.root = tk.Tk() self.root.title(self.title) self.root.geometry(f"{self.width}x{self.height}") # Make the window resizable self.root.columnconfigure(0, weight=1) # We now have two rows - one for logo and one for text self.root.rowconfigure(0, weight=0) # Logo row self.root.rowconfigure(1, weight=1) # Text content row dashboard_path = Path(constants.SERENA_DASHBOARD_DIR) # Load and display the logo image try: # construct path relative to path of this file image_path = dashboard_path / "serena-logs.png" self.logo_image = tk.PhotoImage(file=image_path) # Create a label to display the logo self.logo_label = tk.Label(self.root, image=self.logo_image) self.logo_label.grid(row=0, column=0, sticky="ew") except Exception as e: print(f"Error loading logo image: {e}", file=sys.stderr) # Create frame to hold text widget and scrollbars frame = tk.Frame(self.root) frame.grid(row=1, column=0, sticky="nsew") frame.columnconfigure(0, weight=1) frame.rowconfigure(0, weight=1) # Create horizontal scrollbar h_scrollbar = tk.Scrollbar(frame, orient=tk.HORIZONTAL) h_scrollbar.grid(row=1, column=0, sticky="ew") # Create vertical scrollbar v_scrollbar = tk.Scrollbar(frame, orient=tk.VERTICAL) v_scrollbar.grid(row=0, column=1, sticky="ns") # Create text widget with horizontal scrolling self.text_widget = tk.Text( frame, wrap=tk.NONE, width=self.width, height=self.height, xscrollcommand=h_scrollbar.set, yscrollcommand=v_scrollbar.set ) self.text_widget.grid(row=0, column=0, sticky="nsew") self.text_widget.configure(state=tk.DISABLED) # Make it read-only # Configure scrollbars h_scrollbar.config(command=self.text_widget.xview) v_scrollbar.config(command=self.text_widget.yview) # Configure tags for different log levels with appropriate colors for level, color in self.log_colors.items(): self.text_widget.tag_configure(level.name, foreground=color) # Configure tag for tool names self.text_widget.tag_configure("TOOL_NAME", background="#ffff00") # Set up the queue processing self.root.after(100, self._process_queue) # Handle window close event depending on mode if self.mode == "dashboard": self.root.protocol("WM_DELETE_WINDOW", lambda: self.root.iconify()) else: self.root.protocol("WM_DELETE_WINDOW", self.stop) # Create menu bar if self.mode == "dashboard": self.menubar = tk.Menu(self.root) server_menu = tk.Menu(self.menubar, tearoff=0) server_menu.add_command(label="Shutdown", command=self._shutdown_server) self.menubar.add_cascade(label="Server", menu=server_menu) self.root.config(menu=self.menubar) # Configure icons icon_16 = tk.PhotoImage(file=dashboard_path / "serena-icon-16.png") icon_32 = tk.PhotoImage(file=dashboard_path / "serena-icon-32.png") icon_48 = tk.PhotoImage(file=dashboard_path / "serena-icon-48.png") self.root.iconphoto(False, icon_48, icon_32, icon_16) # Start the Tkinter event loop self.root.mainloop() except Exception as e: print(f"Error in GUI thread: {e}", file=sys.stderr) finally: self.running = False def _shutdown_server(self) -> None: if self.shutdown_handler is not None: self.shutdown_handler() class GuiLogViewerHandler(logging.Handler): """ A logging handler that sends log records to a ThreadedLogViewer instance. This handler can be integrated with Python's standard logging module to direct log entries to a GUI log viewer. """ def __init__( self, log_viewer: GuiLogViewer, level=logging.NOTSET, format_string: str | None = "%(levelname)-5s %(asctime)-15s %(name)s:%(funcName)s:%(lineno)d - %(message)s", ): """ Initialize the handler with a ThreadedLogViewer instance. Args: log_viewer: A ThreadedLogViewer instance that will display the logs level: The logging level (default: NOTSET which captures all logs) format_string: the format string """ super().__init__(level) self.log_viewer = log_viewer self.formatter = logging.Formatter(format_string) # Start the log viewer if it's not already running if not self.log_viewer.running: self.log_viewer.start() @classmethod def is_instance_registered(cls) -> bool: for h in logging.Logger.root.handlers: if isinstance(h, cls): return True return False def emit(self, record): """ Emit a log record to the ThreadedLogViewer. Args: record: The log record to emit """ try: # Format the record according to the formatter msg = self.format(record) # Convert the level name to a standard format for the viewer level_prefix = record.levelname # Add the appropriate prefix if it's not already there if not msg.startswith(level_prefix): msg = f"{level_prefix}: {msg}" self.log_viewer.add_log(msg) except Exception: self.handleError(record) def close(self): """ Close the handler and optionally stop the log viewer. """ # We don't automatically stop the log viewer here as it might # be used by other handlers or directly - src/serena/hooks.py (39130 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json import os import pickle import re import shlex import shutil import sys from abc import ABC, abstractmethod from dataclasses import dataclass from datetime import datetime from enum import Enum from pathlib import Path from typing import Literal, Self import click from serena.generated.tool_capabilities import EDIT_CAPABLE_TOOL_NAMES from serena.util.cli_util import AutoRegisteringGroup # copied from serena_config.py, we don't want to import anything here to keep the hook commands fast serena_home_dir = os.getenv("SERENA_HOME", "").strip() or str(Path.home() / ".serena") class HookClient(Enum): """The client application that triggered the hook.""" CLAUDE_CODE = "claude-code" CODEBUDDY = "codebuddy" VSCODE = "vscode" CODEX = "codex" GROK = "grok" DSH = "dsh" ZCODE = "zcode" class Hook(ABC): def __init__(self, client: HookClient): raw = sys.stdin.read() input_data = json.loads(raw, strict=False) self._input_data = input_data self._client = client # parse the permission mode shared by Codex hook events raw_permission_mode = input_data.get("permission_mode") or input_data.get("permissionMode") or "" self._permission_mode = str(raw_permission_mode).strip() session_id = input_data.get("session_id") or input_data.get("sessionId") if not session_id: raise ValueError("Session ID is required in the hook input data") self._session_id = str(session_id) self.session_persistence_dir = os.path.join(serena_home_dir, "hook_data", self._session_id) # tool input has a timestamp but using now is enough self.triggered_at_timestamp = datetime.now() @abstractmethod def execute(self) -> None: pass def _is_plan_mode(self) -> bool: """Whether the current hook payload reports Codex plan mode.""" return self._permission_mode == "plan" #: substrings that mark a "serena"-containing tool name as one of Serena's own non-symbolic #: utilities (read/config/dashboard/shell) rather than a code-navigation tool; shared across #: PreToolUse and PostToolUse hooks so both classify a call the same way. _NON_SYMBOLIC_SERENA_TOOL_NAME_SUBSTRINGS = frozenset( ( "pattern", "read", "diagnostics", "memory", "onboarding", "config", "list_file", "find_file", "shell", "dashboard", "restart_language_server", ) ) def _is_serena_symbolic_tool_name(tool_name: str) -> bool: return "serena" in tool_name and not any(substring in tool_name for substring in _NON_SYMBOLIC_SERENA_TOOL_NAME_SUBSTRINGS) class PreToolUseHook(Hook, ABC): def __init__(self, client: HookClient): super().__init__(client) _tool_name = self._input_data.get("tool_name") or self._input_data.get("toolName", "") or "" _tool_name = str(_tool_name).lower().strip() if not _tool_name: raise ValueError("Tool name is required in the hook input data") self._tool_name = _tool_name raw_tool_input = self._input_data.get("tool_input") or self._input_data.get("toolInput") # TODO: some agents, like copilot CLI, can send a string as value for raw_tool_input # Example: "tool_input":"*** Begin Patch\n*** Add File: /Users/acbdef/.copilot/session-state/08a961db-02f0-4c7c-b783-1e9818290292/files/hook-tool-test-3.txt\n+third edit tool test\n*** End Patch\n" # We currently don't parse such tool input and hence don't react to it in hooks self._tool_input: dict | None = raw_tool_input if isinstance(raw_tool_input, dict) else None @dataclass class OutputData: permission_decision: Literal["deny", "allow"] permission_decision_reason: str additional_context: str = "" def to_json_string(self, client: HookClient) -> str: if client == HookClient.GROK: grok_output: dict[str, str] = {"decision": self.permission_decision} if self.permission_decision == "deny": grok_output["reason"] = self.permission_decision_reason return json.dumps(grok_output) hook_output = { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": self.permission_decision, "permissionDecisionReason": self.permission_decision_reason, } } if client != HookClient.CODEX: hook_output["hookSpecificOutput"]["additionalContext"] = self.additional_context return json.dumps(hook_output) def is_serena_symbolic_tool(self) -> bool: return _is_serena_symbolic_tool_name(self._tool_name) def _get_codex_serena_tool_name(self) -> str | None: """Serena tool name from a canonical Codex MCP hook name, if present.""" prefix = "mcp__serena__" if not self._tool_name.startswith(prefix): return None tool_name = self._tool_name.removeprefix(prefix) return tool_name or None class PreToolUseRemindAboutSymbolicToolsHook(PreToolUseHook): """Pre-tool-use hook that nudges the agent toward Serena's symbolic tools. Tracks consecutive uses of grep and read-file tools via a persisted :class:`ToolUseCounter`. When the number of recent calls reaches the configured threshold, a deny response is emitted with a reminder to use symbolic alternatives. The counter for a given tool type is reset whenever * a Serena tool is invoked (both counters are reset), * a deny is emitted (the acting counter is reset so the next retry starts fresh), * or the configured reset period elapses *between two consecutive calls of that same tool type* — i.e. the period gates the gap between successive calls, not an absolute sliding window. Three grep calls at t=0, t=9, t=18 therefore count as a burst of three, even though the total span (18s) exceeds the 10s grep period; only an individual pair that is more than 10s apart resets the counter. Non-tracked tools (Edit, Write, Bash, etc.) are deliberately neutral: they neither increment nor reset counters, so they also do not mask bursts by pushing the last timestamp forward. The hook is additionally gated by :attr:`ToolUseCounter._MIN_DENY_INTERVAL_SECONDS` (two minutes by default): once a deny has been emitted, *every* subsequent invocation of this hook is a no-op until the window has elapsed — neither the counters are updated nor any further deny is produced. This prevents the agent from being nudged more than once per window during a sustained non-symbolic-tool burst, and also avoids surprising the user with reminders that were already counted up under stale state. """ @dataclass class ToolUseCounter: _FILE_NAME = "tool_use_counter.pkl" _GREP_USES_THRESHOLD = 3 _READ_FILE_USES_THRESHOLD = 3 # threshold for the combined "non-symbolic" counter that catches mixed sequences of grep+read _NON_SYMBOLIC_USES_THRESHOLD = 4 # The following periods are set to essentially infinity since we neglect the per-tool reset periods for them _READ_FILE_RESET_PERIOD_SECONDS = 1000 _GREP_RESET_PERIOD_SECONDS = 1000 # reset period for the combined counter _NON_SYMBOLIC_RESET_PERIOD_SECONDS = 2000 # minimum seconds between two engagements of the hook after a deny; the entire # hook (counter updates included) is a no-op while this window is active, so a # single sustained burst triggers at most one nudge per window _MIN_DENY_INTERVAL_SECONDS = 120 n_recent_read_file_uses: int = 0 n_recent_grep_uses: int = 0 n_recent_non_symbolic_uses: int = 0 last_grep_use_timestamp: datetime | None = None last_read_file_use_timestamp: datetime | None = None last_non_symbolic_use_timestamp: datetime | None = None # timestamp of the most recently emitted deny; deliberately not cleared by # :meth:`reset` so the rate limit survives counter resets (e.g. Serena tool use) last_deny_timestamp: datetime | None = None def too_many_recent_reads(self) -> bool: return self.n_recent_read_file_uses >= self._READ_FILE_USES_THRESHOLD def too_many_recent_greps(self) -> bool: return self.n_recent_grep_uses >= self._GREP_USES_THRESHOLD def too_many_recent_non_symbolic(self) -> bool: return self.n_recent_non_symbolic_uses >= self._NON_SYMBOLIC_USES_THRESHOLD def is_hook_active(self, now: datetime) -> bool: """:return: whether the hook should engage at all at ``now``. Returns ``False`` while we are still within :attr:`_MIN_DENY_INTERVAL_SECONDS` of the most recent emitted deny — in that case the entire hook is short-circuited (no counter updates, no deny). Returns ``True`` when no deny has been emitted yet in this session, or when the window has elapsed. """ if self.last_deny_timestamp is None: return True return (now - self.last_deny_timestamp).total_seconds() >= self._MIN_DENY_INTERVAL_SECONDS @classmethod def _get_persistence_path(cls, hook: Hook) -> Path: return Path(hook.session_persistence_dir) / cls._FILE_NAME @classmethod def load(cls, hook: Hook) -> Self: path = cls._get_persistence_path(hook) try: with open(path, "rb") as f: return pickle.load(f) except Exception: return cls() def save(self, hook: Hook) -> None: path = self._get_persistence_path(hook) try: path.parent.mkdir(parents=True, exist_ok=True) with open(path, "wb") as f: pickle.dump(self, f) except Exception: pass def update(self, hook: "PreToolUseRemindAboutSymbolicToolsHook") -> None: if hook.is_serena_symbolic_tool(): self.reset() return now = hook.triggered_at_timestamp is_grep = hook.is_grep_call() is_code_file_read = hook.is_read_code_file_call() # update grep counter if is_grep: grep_period = self._GREP_RESET_PERIOD_SECONDS if self.last_grep_use_timestamp is not None and (now - self.last_grep_use_timestamp).total_seconds() <= grep_period: self.n_recent_grep_uses += 1 else: self.n_recent_grep_uses = 1 self.last_grep_use_timestamp = now # update read file counter if is_code_file_read: read_period = self._READ_FILE_RESET_PERIOD_SECONDS if ( self.last_read_file_use_timestamp is not None and (now - self.last_read_file_use_timestamp).total_seconds() <= read_period ): self.n_recent_read_file_uses += 1 else: self.n_recent_read_file_uses = 1 self.last_read_file_use_timestamp = now # update combined non-symbolic counter — catches mixed bursts (e.g. # alternating grep/read) that neither per-tool counter would trip if is_grep or is_code_file_read: combined_period = self._NON_SYMBOLIC_RESET_PERIOD_SECONDS if ( self.last_non_symbolic_use_timestamp is not None and (now - self.last_non_symbolic_use_timestamp).total_seconds() <= combined_period ): self.n_recent_non_symbolic_uses += 1 else: self.n_recent_non_symbolic_uses = 1 self.last_non_symbolic_use_timestamp = now def reset(self) -> None: self.n_recent_read_file_uses = 0 self.n_recent_grep_uses = 0 self.n_recent_non_symbolic_uses = 0 self.last_grep_use_timestamp = None self.last_read_file_use_timestamp = None self.last_non_symbolic_use_timestamp = None class ShellCommandLine: """ Command line of a shell-command tool call, parsed into the program invocations it comprises, e.g. ``cd repo && rg foo src`` comprises invocations of ``cd`` and ``rg``. Parsing is best-effort: an unparsable command line (e.g. one with unbalanced quotes) is split at whitespace. """ _CONTROL_OPERATORS = frozenset(("&&", "||", ";", ";;", "|", "|&", "&", "(", ")")) _REDIRECTION_OPERATORS = frozenset((">", ">>", ">|", ">&", "&>", "&>>", "<", "<<", "<<<", "<&", "<>")) _PREFIX_COMMANDS = frozenset(("command", "env", "exec")) _ENV_ASSIGNMENT_PATTERN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*=") @dataclass(frozen=True) class Invocation: program: str """the name of the invoked program (base name, lowercase)""" arguments: tuple[str, ...] def get_operands(self) -> list[str]: """:return: the arguments which are not options""" return [argument for argument in self.arguments if argument and not argument.startswith("-")] def __init__(self, command_line: str): self.invocations: list[PreToolUseRemindAboutSymbolicToolsHook.ShellCommandLine.Invocation] = [] for segment in self._split_into_simple_commands(self._tokenize(command_line)): invocation = self._create_invocation(segment) if invocation is not None: self.invocations.append(invocation) @staticmethod def _tokenize(command_line: str) -> list[str]: lexer = shlex.shlex(command_line, posix=True, punctuation_chars=True) lexer.whitespace_split = True try: return list(lexer) except ValueError: return command_line.split() @classmethod def _split_into_simple_commands(cls, tokens: list[str]) -> list[list[str]]: segments: list[list[str]] = [[]] skip_next = False for token in tokens: if skip_next: skip_next = False elif token in cls._CONTROL_OPERATORS: segments.append([]) elif token in cls._REDIRECTION_OPERATORS: # the redirection target is not an argument of the invoked program skip_next = True else: segments[-1].append(token) return [segme - src/serena/jetbrains/jetbrains_backend.py (4442 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging from typing import TYPE_CHECKING from overrides import override from serena.code_editor import JetBrainsCodeEditor from serena.jetbrains import launch_coordinator from serena.language_backend import BuiltinLanguageBackend, LanguageBackend from ..util.file_proxy import FileProxy, LocalProjectFileProxy from . import jetbrains_types as jb if TYPE_CHECKING: from serena.agent import SerenaAgent from serena.code_editor import CodeEditor from serena.project import Project from serena.repl.facade import ApiScope, Facade from serena.tools import Tool log = logging.getLogger(__name__) class JetBrainsLanguageBackend(LanguageBackend): def __init__(self, key: str | None = None): super().__init__(key or BuiltinLanguageBackend.JETBRAINS.value) @override def get_lsp_tool_class_replacements(self) -> "dict[type[Tool], type[Tool]]": from ..tools import jetbrains_tools, symbol_tools return { symbol_tools.FindSymbolTool: jetbrains_tools.JetBrainsFindSymbolTool, symbol_tools.GetSymbolsOverviewTool: jetbrains_tools.JetBrainsGetSymbolsOverviewTool, symbol_tools.FindReferencingSymbolsTool: jetbrains_tools.JetBrainsFindReferencingSymbolsTool, symbol_tools.FindImplementationsTool: jetbrains_tools.JetBrainsFindImplementationsTool, symbol_tools.FindDeclarationTool: jetbrains_tools.JetBrainsFindDeclarationTool, symbol_tools.RenameSymbolTool: jetbrains_tools.JetBrainsRenameTool, symbol_tools.SafeDeleteSymbol: jetbrains_tools.JetBrainsSafeDeleteTool, } def _create_ide_facade(self, agent: "SerenaAgent", api_scope: "ApiScope") -> "Facade": from ..repl.api.jb_api import JetBrainsApi from ..repl.facade import Facade return Facade.from_api(JetBrainsApi(agent), api_scope, agent.get_repl_facade_method_usage_stats()) @override def create_facades(self, agent: "SerenaAgent", api_scope: "ApiScope") -> list["Facade"]: return [self._create_ide_facade(agent, api_scope)] def _init_project_ide_launch(self, agent: "SerenaAgent") -> None: project = agent.get_active_project_or_raise() launch_command = agent.serena_config.jetbrains_launch_command if launch_command: launch_coordinator.launch_and_wait_for_plugin_server(project, launch_command) @override def init_active_project(self, agent: "SerenaAgent") -> None: project = agent.get_active_project_or_raise() client = launch_coordinator.find_plugin_server(project) if client is not None: log.info("Found Serena JetBrains Plugin server: %s", client) else: self._init_project_ide_launch(agent) @override def shutdown_active_project(self, project: "Project", timeout: float) -> None: # Do nothing; IDE lifecycle is user-controlled pass @override def create_code_editor(self, project: "Project") -> "CodeEditor": return JetBrainsCodeEditor(project) @override def is_source_file(self, abs_path: str, project: "Project") -> bool: # no distinction is made; every file is potentially a source file return True @override def is_external_path(self, relative_path: str) -> bool: return relative_path.startswith(jb.JB_EXTERNAL_FILE_PREFIX) @override def create_file_proxy(self, relative_path: str, project: "Project") -> FileProxy: if self.is_external_path(relative_path): return JetBrainsFileProxy(relative_path, project) return LocalProjectFileProxy(relative_path, project) class JetBrainsFileProxy(FileProxy): """ Retrieves the contents of a file from the JetBrains plugin via the plugin client, given its relative path, which may be an external path (e.g., "<ext:FileUtil.class|472e0a13>") """ def __init__(self, relative_path: str, project: "Project"): self._relative_path = relative_path self._project = project def get_contents(self) -> str: from serena.jetbrains.jetbrains_plugin_client import JetBrainsPluginClient client = JetBrainsPluginClient.from_project(self._project) return client.read_file(self._relative_path) def get_relative_path(self) -> str: return self._relative_path def is_glob_supported(self): return False - src/serena/jetbrains/jetbrains_plugin_client.py (32075 bytes)
""" Client for the Serena JetBrains Plugin """ # SPDX-License-Identifier: GPL-3.0-or-later import concurrent import json import logging import re import threading from concurrent.futures.thread import ThreadPoolExecutor from dataclasses import dataclass from pathlib import Path from typing import Any, Literal, Optional, Self, TypeVar, cast import requests from requests import Response from sensai.util.string import ToStringMixin import serena.jetbrains.jetbrains_types as jb from serena.config.serena_config import RegisteredProject from serena.constants import SerenaPorts from serena.jetbrains.jetbrains_types import PluginStatusDTO from serena.project import Project from serena.util.class_decorators import singleton from serena.util.text_utils import render_html from serena.util.version import Version T = TypeVar("T") log = logging.getLogger(__name__) class SerenaClientError(Exception): """Base exception for Serena client errors.""" class ConnectionError(SerenaClientError): """Raised when connection to the service fails.""" class APIError(SerenaClientError): """Raised when the API returns an error response that shall be reported on the caller/LLM.""" def __init__(self, response: Response): try: error_data = response.json() message = error_data.get("error", response.text) except: message = response.text super().__init__(message) class PluginServerError(SerenaClientError): """Raised when the plugin's service encounters an internal error (which may need to be reported).""" def __init__(self, message: str): unrecoverable_error_prefix = ( "The request failed due to an error on the Serena JetBrains plugin side. This may be caused " "by a bug or an incompatibility in the plugin. In that case, please report the error below together with " "your setup (IDE + version, Serena plugin version, programming language) at https://github.com/oraios/serena/issues " "(if you are an LLM, tell the user about this). The Oraios team will then provide support on this.\n" ) super().__init__(unrecoverable_error_prefix + message) class ServerNotFoundError(Exception): """Raised when the plugin's service is not found.""" @dataclass class MatchedClient: client: "JetBrainsPluginClient" registered_project: RegisteredProject @singleton class JetBrainsPluginClientManager: """ Manager for JetBrainsPluginClient instances, responsible for scanning ports to find available plugin instances """ NUM_PORTS_TO_SCAN = 20 def __init__(self) -> None: self._clients: dict[int, "JetBrainsPluginClient"] = {} self._matched_clients: list[MatchedClient] = [] self._lock = threading.Lock() def _submit_scan(self) -> list[concurrent.futures.Future["JetBrainsPluginClient"]]: """ Performs a port scan to find available plugin instances in parallel. :return: futures that will resolve to plugin clients for every port """ def scan_port(port: int) -> JetBrainsPluginClient: client = JetBrainsPluginClient(port) with self._lock: self._clients[port] = client return client futures = [] with ThreadPoolExecutor(max_workers=self.NUM_PORTS_TO_SCAN) as executor: for i in range(self.NUM_PORTS_TO_SCAN): future = executor.submit(scan_port, JetBrainsPluginClient.BASE_PORT + i) futures.append(future) return futures def find_client(self, project_root: Path, log_warning: bool = True) -> "JetBrainsPluginClient": """ :param project_root: the project root path to find a plugin instance for :param log_warning: whether to log a warning if no matching plugin instance is found :return: the instance """ plugin_paths_found = [] for future in self._submit_scan(): client = future.result() if client.matches(project_root): return client elif client.project_root is not None: plugin_paths_found.append(client.project_root) if log_warning: log.warning( "Searched for Serena JetBrains plugin service for project at %s but found no matching service. " "Found plugin instances for the following project paths: %s", project_root, plugin_paths_found, ) raise ServerNotFoundError( f"Found no Serena service in a JetBrains IDE instance for the project at {project_root}. " "STOP. Do not attempt any other tools or workarounds. Ask the user to open this folder as a project in a JetBrains IDE " "with the Serena plugin installed and running!" ) def match_clients(self, registered_projects: list[RegisteredProject]) -> list[MatchedClient]: """ Scans for plugin instances and matches them against the given registered projects. :param registered_projects: the list of registered projects to match plugin instances against :return: the list of matched clients with their corresponding registered project """ matched_clients = [] for future in self._submit_scan(): client = future.result() if client.project_root is not None: for rp in registered_projects: if client.matches(Path(rp.project_root)): matched_clients.append(MatchedClient(client, rp)) break self._matched_clients = matched_clients return matched_clients def get_matched_client( self, registered_project: RegisteredProject, registered_projects: list[RegisteredProject] ) -> Optional["JetBrainsPluginClient"]: """ Gets the matched client for a given registered project, if any. :param registered_project: the registered project to get the matched client for :param registered_projects: the list of all registered projects (used to perform matching of all clients if no match is found for the given project) :return: the matched client or None if no match is found """ def find_match() -> Optional["JetBrainsPluginClient"]: for matched_client in self._matched_clients: if matched_client.registered_project.project_root == registered_project.project_root: return matched_client.client return None match = find_match() if match is None: self.match_clients(registered_projects) return find_match() class JetBrainsPluginClient(ToStringMixin): """ Python client for the Serena Backend Service. Provides simple methods to interact with all available endpoints. """ BASE_PORT = SerenaPorts.JETBRAINS_PLUGIN_SERVER_BASE_PORT PLUGIN_REQUEST_TIMEOUT = 300 """ the timeout used for request handling within the plugin (a constant in the plugin) """ _last_port: int | None = None """ the last port that was successfully used to connect to a plugin instance in the current session """ _server_address: str = "127.0.0.1" """ the server address where to connect to the plugin service """ def __init__(self, port: int, timeout: int = PLUGIN_REQUEST_TIMEOUT): self._port = port self._timeout = timeout self._session = requests.Session() self._session.headers.update({"Content-Type": "application/json", "Accept": "application/json"}) # connect and obtain status self.project_root: str | None = None self._plugin_version: Version | None = None try: status_response: PluginStatusDTO = cast(jb.PluginStatusDTO, self._make_request("GET", "/status")) self.project_root = status_response["project_root"] self._plugin_version = Version(status_response["plugin_version"]) except ConnectionError: # expected if no server is running at the port pass except Exception as e: log.warning("Failed to obtain status from JetBrains plugin service at port %d: %s", port, e, exc_info=e) @property def _base_url(self) -> str: return f"http://{self._server_address}:{self._port}" @classmethod def set_server_address(cls, address: str) -> None: cls._server_address = address def _tostring_includes(self) -> list[str]: return ["_port", "project_root", "_plugin_version"] @classmethod def from_project(cls, project: Project, log_warning: bool = True) -> "JetBrainsPluginClient": resolved_path = Path(project.project_root).resolve() if cls._last_port is not None: client = JetBrainsPluginClient(cls._last_port) if client.matches(resolved_path): return client client = JetBrainsPluginClientManager().find_client(resolved_path, log_warning=log_warning) cls._last_port = client._port return client @staticmethod def _paths_match(resolved_serena_path: str, plugin_path: str) -> bool: """ Checks whether the resolved Serena path matches the plugin path, accounting for possible prefixes in the plugin path, different file system perspectives, and case sensitivity. Concrete aspects considered: - The plugin path may contain prefixes: - The plugin path may be a WSL UNC path, e.g. `//wsl.localhost/Ubuntu-24.04/home/user/project` or `//wsl$/Ubuntu/home/user/project` while Serena will just have `/home/user/project` - Other prefixes like `/workspaces/serena/C:/Users/user/projects/my-app` - One path may use a different file system perspective (particularly WSL vs Windows-native) but still point to the same location, e.g. `/mnt/c/` vs `C:/` - Case sensitivity :param resolved_serena_path: The resolved project root path from Serena's perspective :param plugin_path: The project root path reported by the plugin (which may be a WSL UNC path) :return: True if the paths match, False otherwise """ # try to resolve the plugin path, checking for a direct match # (this is robust against symlinks as long as there are no prefixes) try: resolved_plugin_path = str(Path(plugin_path).resolve()) if resolved_plugin_path == resolved_serena_path: return True except: pass def normalise_wsl_mnt(path_str: str) -> str: # normalise WSL /mnt/c/ to c:/ for comparison return re.sub(r"/mnt/([a-z])/", r"\1:/", path_str, flags=re.IGNORECASE) # standardise paths for comparison: normalise WSL /mnt/ to Windows paths and ignore case std_serena_path = normalise_wsl_mnt(str(resolved_serena_path)).lower() std_plugin_path = normalise_wsl_mnt(str(plugin_path)).lower() # At this point, the plugin path may still contain prefixes, so we check if the Serena path is a suffix of the plugin path return std_plugin_path.endswith(std_serena_path) def matches(self, resolved_path: Path) -> bool: """ :param resolved_path: the resolved project root path from Serena's perspective :return: whether this client instance matches the given project path """ if self.project_root is None: return False return self._paths_match(str(resolved_path), self.project_root) def is_version_at_least(self, *version_parts: int) -> bool: if self._plugin_version is None: return False return self._plugin_version.is_at_least(*version_parts) def _require_version_at_least(self, *version_parts: int) -> None: """ Ensures that the plugin version is at least the given version and raises an error otherwise. :param version_parts: the minimum required version parts (major, minor, patch) """ if not self.is_version_at_least(*version_parts): raise SerenaClientError( f"This operation requires Serena JetBrains plugin version " f"{'.'.join(map(str, version_parts))} or higher, but the installed version is " f"{self._plugin_version}. Ask the user to update the plugin!" ) def _make_request(self, method: str, endpoint: str, data: Optional[dict] = None, pythonify: bool = True) -> dict[str, Any]: """ :param method: the HTTP method to use ("GET" or "POST") :param endpoint: the endpoint to call (e.g., "/findSymbol") :param data: the data to send in the request body (for POST requests) :param pythonify: whether to recursively "pythonify" the response object, converting all keys to snake_case. This must not be enabled if *any* key contains variable data rather (and therefore isn't a well-defined DTO structure). :return: the response as a dictionary """ url = f"{self._base_url}{endpoint}" response: Response | None = None try: if method.upper() == "GET": response = self._session.get(url, timeout=self._timeout) elif method.upper() == "POST": data_dict = data if data is not None else {} response = self._session.post(url, data=json.dumps(data_dict), timeout=self._timeout) else: raise ValueError(f"Unsupported HTTP method: {method}") response.raise_for_status() # Try to parse JSON response try: response_json = response.json() if pythonify: return self._pythonify_response(response_json) else: return response_json except json.JSONDecodeError: # If response is not JSON, return raw text return {"response": response.text} except requests.exceptions.ConnectionError as e: raise ConnectionError(f"Failed to connect to Serena service at {url}: {e}") except requests.exceptions.Timeout as e: raise ConnectionError(f"Request to {url} timed out: {e}") except requests.exceptions.HTTPError as e: if response is not None: # check for recoverable error (i.e. errors where the problem can be resolved by the caller or # other errors where the error text shall simply be passed on to the LLM). # The plugin returns 400 for such errors (typically illegal arguments, e.g. non-unique name path) # but only since version 2023.2.6 if self.is_version_at_least(2023, 2, 6): is_recoverable_error = response.status_code == 400 else - src/serena/jetbrains/jetbrains_types.py (2794 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later from typing import Literal, NotRequired, TypedDict JB_EXTERNAL_FILE_PREFIX = "<ext:" """ Prefix used for in relative paths of symbols that are from external libraries (i.e., not defined in the user's codebase). """ class PluginStatusDTO(TypedDict): project_root: str plugin_version: str class PositionDTO(TypedDict): line: int col: int class TextRangeDTO(TypedDict): start_pos: PositionDTO end_pos: PositionDTO class SymbolDTO(TypedDict): name_path: str relative_path: str type: str body: NotRequired[str] quick_info: NotRequired[str] """quick info text (e.g., type signature) for the symbol, as HTML string.""" documentation: NotRequired[str] """documentation text for the symbol (if available), as HTML string.""" text_range: NotRequired[TextRangeDTO] children: NotRequired[list["SymbolDTO"]] num_usages: NotRequired[int] reference_line_no: NotRequired[int] """ for the case where this is a reference, the line number of the reference (0-based, relative to the file where the symbol is defined). """ # --- Python-side extensions, i.e. fields that are not returned by the plugin but set later by the Python code --- context: NotRequired[str] """ context around the symbol/reference, e.g., a few lines of code before and after the symbol definition or reference, to provide additional context for the LLM. """ SymbolDTOKey = Literal[ "name_path", "relative_path", "type", "body", "quick_info", "documentation", "text_range", "children", "num_usages", "reference_line_no", "context", ] class SymbolDTOUtil: @staticmethod def is_external_symbol(symbol_dto: SymbolDTO) -> bool: """ Checks if a symbol is an external symbol (i.e., from a library) based on its relative path. """ return symbol_dto["relative_path"].startswith(JB_EXTERNAL_FILE_PREFIX) class SymbolCollectionResponse(TypedDict): symbols: list[SymbolDTO] class GetSymbolsOverviewResponse(SymbolCollectionResponse): documentation: NotRequired[str] """Docstring of the collection (if applicable - usually present only if the collection is from a single file), as HTML string.""" class TypeHierarchyNodeDTO(TypedDict): symbol: SymbolDTO children: NotRequired[list["TypeHierarchyNodeDTO"]] class TypeHierarchyResponse(TypedDict): hierarchy: NotRequired[list[TypeHierarchyNodeDTO]] num_levels_not_included: NotRequired[int] class InspectionInfoDTO(TypedDict): name: str group_path: str language: NotRequired[str] description: NotRequired[str] class ListInspectionsResponse(TypedDict): inspections: list[InspectionInfoDTO] - src/serena/jetbrains/launch_coordinator.py (5752 bytes)
""" Coordinates the launching of JetBrains IDE instances triggered by Serena's own `jetbrains_launch_command`, so that concurrent Serena sessions activating different projects at (nearly) the same time do not race each other into the same IDE launch. """ # SPDX-License-Identifier: GPL-3.0-or-later import hashlib import logging import subprocess import tempfile import time from pathlib import Path from filelock import FileLock, Timeout from serena.jetbrains import jetbrains_plugin_client from serena.project import Project from solidlsp.util import subprocess_util log = logging.getLogger(__name__) LOCK_ACQUIRE_TIMEOUT = 90.0 """ How long a session waits for another session's IDE launch (for the same launch command) to finish before giving up on launching its own instance. """ PLUGIN_SERVER_WAIT_TIMEOUT = 60.0 """How long to poll for the plugin server to become reachable after the launch command exits.""" PLUGIN_SERVER_POLL_INTERVAL = 1.0 """The interval at which we poll for the plugin server while waiting for it to come up.""" def _lock_path_for_launch_command(launch_command: str | list[str]) -> Path: """ :param launch_command: the configured `jetbrains_launch_command` :return: a stable, cross-process lock file path for the given launch command, so that concurrent Serena sessions configured with the same launch command serialize on the same file regardless of which project each of them is activating """ digest = hashlib.sha256(str(launch_command).encode("utf-8")).hexdigest()[:16] return Path(tempfile.gettempdir()) / f"serena-jetbrains-launch-{digest}.lock" def find_plugin_server(project: Project) -> "jetbrains_plugin_client.JetBrainsPluginClient | None": """ :param project: the project to find a matching, already-running plugin server for :return: the matching plugin server client, or None if none is currently reachable """ try: return jetbrains_plugin_client.JetBrainsPluginClient.from_project(project, log_warning=False) except jetbrains_plugin_client.ServerNotFoundError: return None def launch_and_wait_for_plugin_server( project: Project, launch_command: str | list[str], lock_acquire_timeout: float = LOCK_ACQUIRE_TIMEOUT, plugin_server_wait_timeout: float = PLUGIN_SERVER_WAIT_TIMEOUT, plugin_server_poll_interval: float = PLUGIN_SERVER_POLL_INTERVAL, ) -> None: """ Launches the JetBrains IDE for `project` via `launch_command`, serialized across concurrent Serena sessions that share the same launch command, and waits for the plugin server to become reachable before returning. Without serialization, several sessions activating different projects at once each independently find no running plugin server and race the same launch command against the same IDE config directory; only one IDE process wins the JetBrains-side directory lock, and the others fail with a native modal dialog that never surfaces as a subprocess exit code. Re-checking for the plugin server both before and after acquiring the lock means every session but the first either finds the IDE already launching (and waits for it here, rather than in a failed tool call) or finds it already serving (and returns immediately). :param project: the project being activated :param launch_command: the base command, to which the project directory is to be added, either as a string (e.g. "idea") or as a list of strings (e.g. ["idea", "--wait"]) :param lock_acquire_timeout: how long to wait for another session's launch to finish before giving up on launching our own instance :param plugin_server_wait_timeout: how long to poll for the plugin server to become reachable after the launch command exits :param plugin_server_poll_interval: the interval at which to poll while waiting """ lock = FileLock(str(_lock_path_for_launch_command(launch_command)), timeout=lock_acquire_timeout) try: with lock: if find_plugin_server(project) is not None: # another session launched the IDE while we were waiting for the lock return if isinstance(launch_command, list): cmd_list = launch_command + [project.project_root] else: cmd_list = [launch_command, project.project_root] cmd = subprocess_util.convert_shell_cmd(cmd_list) log.info("Launching IDE with command: %s", cmd) p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = p.communicate() if p.returncode != 0: log.error("Failed to launch JetBrains IDE: %s", stderr.decode("utf-8")) return deadline = time.monotonic() + plugin_server_wait_timeout while True: if find_plugin_server(project) is not None: return if time.monotonic() >= deadline: log.warning( "JetBrains IDE launch command exited but no Serena plugin server became reachable " "for project %s within %.0fs; the IDE may still be starting.", project.project_name, plugin_server_wait_timeout, ) return time.sleep(plugin_server_poll_interval) except Timeout: log.warning( "Timed out after %.0fs waiting for another Serena session's JetBrains IDE launch to finish " "for project %s; not launching a second instance.", lock_acquire_timeout, project.project_name, ) - src/serena/language_backend.py (9936 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import importlib import logging import threading from abc import ABC, abstractmethod from enum import Enum from functools import cache from typing import TYPE_CHECKING from serena.util.file_proxy import FileProxy log = logging.getLogger(__name__) if TYPE_CHECKING: from serena.agent import SerenaAgent from serena.code_editor import CodeEditor from serena.project import Project from serena.repl.facade import ApiScope, Facade from serena.tools import Tool class LanguageBackend(ABC): def __init__(self, key: str): """ :param key: the key by which the backend is identified in the registry and in configuration """ self._key = key def __str__(self): return self._key def get_key(self) -> str: """ :return: the key by which the backend is identified in the registry and in configuration """ return self._key def is_lsp(self): return self.get_key() == BuiltinLanguageBackend.LSP.value def is_jetbrains(self): return self.get_key() == BuiltinLanguageBackend.JETBRAINS.value @property def name(self): return self.get_key() @abstractmethod def get_lsp_tool_class_replacements(self) -> "dict[type[Tool], type[Tool]]": """ :return: mapping from LSP tool classes to replacement tool classes (functional replacements) """ @abstractmethod def create_facades(self, agent: "SerenaAgent", api_scope: "ApiScope") -> list["Facade"]: """ Creates backend-specific facades for the given agent and API scope. :param agent: the agent :param api_scope: the API scope defining active facade methods :return: the list of facades to be used by the agent for this backend """ @abstractmethod def init_active_project(self, agent: "SerenaAgent") -> None: """ Initialises the backend for the given agent's newly activated project. :param agent: the agent, which has just set a new active project """ @abstractmethod def shutdown_active_project(self, project: "Project", timeout: float) -> None: """ Cleans up, freeing resources, after a project has been deactivated. :param project: the project :param timeout: the timeout, in seconds, after which to give up on graceful shutdown """ def get_project_activation_statement(self, project: "Project") -> str: """ :return: a statement to add to the project activation message """ return "" def get_config_overview_statement(self, project: "Project") -> str: """ :return: a statement to add to the project configuration overview """ return "" @abstractmethod def create_code_editor(self, project: "Project") -> "CodeEditor": pass @abstractmethod def is_source_file(self, abs_path: str, project: "Project") -> bool: """ Determines whether the given absolute path corresponds to a source file that can (potentially) be processed/understood by the backend. :param abs_path: the absolute path to an existing file :param project: the project in which the file is located :return: True if the file is a source file for this backend (or the backend does not specifically make distinctions), False otherwise """ @abstractmethod def is_external_path(self, relative_path: str) -> bool: """ Determines whether the given relative path corresponds to a file that is external to the project (e.g. a dependency file). Virtually all of Serena's interfaces use `relative_path` (relative to the project root) to refer to files, but some backends may need to support project-external files. In this case, the external path should be encoded in the `relative_path` parameter (e.g. "<ext:/path/to/whatever>") rather than this being an actual relative path that points outside the project root. Therefore, information about the project in question is deliberately not provided to this method. :param relative_path: the relative path to a file within the project or an encoded external path. The path can be assumed to have been provided by the backend itself. :return: whether the file is considered external to the project by this backend """ @abstractmethod def create_file_proxy(self, relative_path: str, project: "Project") -> FileProxy: """ Creates a file proxy for the given relative path in the given project. :param relative_path: the relative path to a file within the project or an encoded external path. :param project: the project :return: a file proxy for the given file """ class BuiltinLanguageBackend(Enum): LSP = "LSP" """ Use the language server protocol (LSP), spawning freely available language servers via the SolidLSP library that is part of Serena """ JETBRAINS = "JetBrains" """ Use the Serena plugin in your JetBrains IDE. (requires the plugin to be installed and the project being worked on to be open in your IDE) """ OLB_JVM = "olb-jvm" @staticmethod def from_str(backend_str: str) -> "BuiltinLanguageBackend": for backend in BuiltinLanguageBackend: if backend.value.lower() == backend_str.lower(): return backend raise ValueError(f"Unknown language backend '{backend_str}': valid values are {[b.value for b in BuiltinLanguageBackend]}") @cache def get_instance(self) -> LanguageBackend: if self == BuiltinLanguageBackend.LSP: from .lsp.lsp_backend import LSPLanguageBackend return LSPLanguageBackend() elif self == BuiltinLanguageBackend.JETBRAINS: from .jetbrains.jetbrains_backend import JetBrainsLanguageBackend return JetBrainsLanguageBackend() elif self == BuiltinLanguageBackend.OLB_JVM: from .olb.olb_jvm_backend import OraiosJVMLanguageBackend return OraiosJVMLanguageBackend() else: raise NotImplementedError class LanguageBackendRegistry: """ Registry of language backends """ REGISTRATION_ENTRY_POINT_GROUP = "serena.language_backend_registration" """ entry point group for language backend registration functions; each function should call use `LanguageBackendRegistry.get_instance().register(...)` to register a backend """ _instance = None _instance_lock = threading.Lock() @classmethod def get_instance(cls): if cls._instance is None: with cls._instance_lock: if cls._instance is None: cls._instance = cls(True) cls._discover_backends_from_entry_points() return cls._instance def __init__(self, _singleton: bool): if not _singleton: raise RuntimeError("LanguageServerRegistry is a singleton. Use get_instance() to access it.") self._registered_backends: dict[str, LanguageBackend] = {} # auto-register built-in language backends for builtin_backend in BuiltinLanguageBackend: self._registered_backends[builtin_backend.value] = builtin_backend.get_instance() @classmethod def _discover_backends_from_entry_points(cls) -> None: """ Discover and execute language server adapter registration functions from entry points. """ log.debug("Discovering language backend registration entry points ...") try: entry_points = importlib.metadata.entry_points(group=cls.REGISTRATION_ENTRY_POINT_GROUP) except Exception as error: log.exception("Failed to discover language server registration entry points: %s", error) return def get_distribution_name(ep: importlib.metadata.EntryPoint) -> str: distribution = getattr(ep, "dist", None) if distribution is None: return "unknown distribution" return distribution.name or "unknown distribution" log.debug("Found %d language server registration entry points", len(entry_points)) for entry_point in entry_points: try: registration = entry_point.load() if not callable(registration): raise TypeError("Entry point must resolve to a callable registration function") registration() except Exception as error: log.exception( "Failed to load language backend entry point '%s' from %s: %s", entry_point.name, get_distribution_name(entry_point), error, ) def resolve(self, key: str) -> LanguageBackend: if key in self._registered_backends: return self._registered_backends[key] raise ValueError(f"Unknown language backend key: '{key}'; Valid keys: {self.get_keys()}") def register(self, backend: LanguageBackend, allow_override: bool = False) -> None: """ :param backend: the backend to register :param allow_override: whether to allow overriding an existing registration with the same key """ key = backend.get_key() log.info("Registering language backend: %s (class=%s)", key, backend.__class__.__name__) if backend.get_key() in self._registered_backends and not allow_override: raise ValueError(f"Language backend already registered: {key}") self._registered_backends[key] = backend def get_keys(self) -> list[str]: """ :return: the sorted list of all registered string keys """ return sorted(self._registered_backends.keys()) - src/serena/ls_manager.py (19203 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import os.path import threading import time from collections.abc import Iterator from pathlib import Path from typing import TYPE_CHECKING from sensai.util.logging import LogTime from serena.config.serena_config import ProjectConfig, SerenaPaths from solidlsp import SolidLanguageServer from solidlsp.ls_config import LanguageServerConfig, LanguageServerIdLike from solidlsp.lsp_protocol_handler.lsp_types import DidChangeWatchedFilesParams, FileChangeType, FileEvent from solidlsp.settings import SolidLSPSettings if TYPE_CHECKING: from .project import Project log = logging.getLogger(__name__) class LanguageServerManagerInitialisationError(Exception): def __init__(self, message: str): super().__init__(message) class LanguageServerFactory: def __init__( self, project_root: str, project_config: ProjectConfig, project_data_path: str, encoding: str, ignored_patterns: list[str], ls_timeout: float | None = None, ls_specific_settings: dict | None = None, trace_lsp_communication: bool = False, is_project_trusted: bool = True, ): self.project_root = project_root self.project_config = project_config self.project_data_path = project_data_path self.encoding = encoding self.ignored_patterns = ignored_patterns self.ls_timeout = ls_timeout self.ls_specific_settings = ls_specific_settings self.trace_lsp_communication = trace_lsp_communication self.is_project_trusted = is_project_trusted def create_language_server(self, ls_id: LanguageServerIdLike) -> SolidLanguageServer: ls_config = LanguageServerConfig( workspace_folders=self.project_config.ls_workspace_folders, additional_workspace_folders=self.project_config.ls_additional_workspace_folders, ls_id=ls_id, ignored_paths=self.ignored_patterns, trace_lsp_communication=self.trace_lsp_communication, encoding=self.encoding, is_project_trusted=self.is_project_trusted, ) log.info(f"Creating language server instance for {self.project_root}, language={ls_id}.") return SolidLanguageServer.create( ls_config, self.project_root, timeout=self.ls_timeout, solidlsp_settings=SolidLSPSettings( solidlsp_dir=SerenaPaths().serena_user_home_dir, project_data_path=self.project_data_path, ls_specific_settings=self.ls_specific_settings or {}, ), ) class LanguageServerManager: """ Manages one or more language servers for a project. """ _CACHE_SAVE_INTERVAL = 30.0 """ the minimum time, in seconds, between two cache saves triggered by tool calls (see `save_all_caches_if_due`) """ def __init__( self, language_servers: dict[LanguageServerIdLike, SolidLanguageServer], language_server_factory: LanguageServerFactory, project: "Project", ) -> None: """ :param language_servers: a mapping from language to language server; the servers are assumed to be already started. The first server in the iteration order is used as the default server. All servers are assumed to serve the same project root. :param language_server_factory: factory for language server creation; if None, dynamic (re)creation of language servers is not supported """ self._language_servers = language_servers self._language_server_factory = language_server_factory self._last_cache_save_time: float | None = None self._file_change_notifier = LanguageServerFileChangeNotifier(project, self) @property def _default_language_server(self) -> SolidLanguageServer: if len(self._language_servers) == 0: raise ValueError("No language servers available in the manager") return next(iter(self._language_servers.values())) @staticmethod def from_languages( languages: list[LanguageServerIdLike], factory: LanguageServerFactory, project: "Project" ) -> "LanguageServerManager": """ Creates a manager with language servers for the given languages using the given factory. The language servers are started in parallel threads. :param languages: the languages for which to spawn language servers :param factory: the factory for language server creation :param project: the project for which the language servers are created :return: the instance """ class StartLSThread(threading.Thread): def __init__(self, ls_id: LanguageServerIdLike): super().__init__(target=self._start_language_server, name="StartLS:" + ls_id.get_key()) self.ls_id = ls_id self.language_server: SolidLanguageServer | None = None self.exception: Exception | None = None def _start_language_server(self) -> None: try: with LogTime(f"Language server startup (ls_id={self.ls_id.get_key()})"): self.language_server = factory.create_language_server(self.ls_id) self.language_server.start() if not self.language_server.is_running(): raise RuntimeError(f"Failed to start the language server {self.ls_id.get_key()}") except Exception as e: log.error(f"Error starting language server {self.ls_id.get_key()}: {e}", exc_info=e) self.exception = e # start language servers in parallel threads threads = [] for language in languages: thread = StartLSThread(language) thread.start() threads.append(thread) # collect language servers and exceptions language_servers: dict[LanguageServerIdLike, SolidLanguageServer] = {} exceptions: dict[LanguageServerIdLike, Exception] = {} for thread in threads: thread.join() if thread.exception is not None: exceptions[thread.ls_id] = thread.exception elif thread.language_server is not None: language_servers[thread.ls_id] = thread.language_server # If any server failed to start up, raise an exception and stop all started language servers. # A server whose own thread raised has already stopped its own process, since # SolidLanguageServer.start() cleans up after itself on failure; only the servers that # started successfully (and are therefore absent from `exceptions`) still need stopping. # We intentionally fail fast here. The user's intention is to work with all the specified languages, # so if any of them is not available, it is better to make symbolic tool calls fail, bringing the issue to the # user's attention instead of silently continuing with a subset of the language servers and potentially # causing suboptimal agent behaviour. if exceptions: for ls in language_servers.values(): ls.stop() failure_messages = "\n".join([f"{ls_id.get_key()}: {e}" for ls_id, e in exceptions.items()]) raise LanguageServerManagerInitialisationError(f"Failed to start {len(exceptions)} language server(s):\n{failure_messages}") return LanguageServerManager(language_servers, factory, project) def _ensure_functional_ls(self, ls: SolidLanguageServer) -> SolidLanguageServer: if not ls.is_running(): log.warning(f"Language server for language {ls.ls_id} is not running; restarting ...") ls = self.restart_language_server(ls.ls_id) return ls def _get_suitable_language_server(self, relative_path: str) -> SolidLanguageServer | None: """:param relative_path: relative path to a file""" for candidate in self._language_servers.values(): if not candidate.is_ignored_path(relative_path, ignore_unsupported_files=True): return candidate return None def get_language_server(self, relative_path: str) -> SolidLanguageServer: """:param relative_path: relative path to a file""" ls: SolidLanguageServer | None = None if len(self._language_servers) > 1: if os.path.isdir(relative_path): raise ValueError(f"Expected a file path, but got a directory: {relative_path}") ls = self._get_suitable_language_server(relative_path) if ls is None: ls = self._default_language_server return self._ensure_functional_ls(ls) def _create_and_start_language_server(self, ls_id: LanguageServerIdLike) -> SolidLanguageServer: if self._language_server_factory is None: raise ValueError(f"No language server factory available to create language server for {ls_id}") language_server = self._language_server_factory.create_language_server(ls_id) language_server.start() self._language_servers[ls_id] = language_server return language_server def restart_language_server(self, ls_id: LanguageServerIdLike) -> SolidLanguageServer: """ Forces recreation and restart of the language server for the given language. The previous instance is stopped first, releasing any processes it left behind. :param ls_id: the language server identifier :return: the newly created language server """ if ls_id not in self._language_servers: raise ValueError(f"No language server for language {ls_id.get_key()} present; cannot restart") # keep the cache entries of the replaced server, which the new server loads from disk self._language_servers[ls_id].save_cache() self._stop_language_server(self._language_servers[ls_id]) return self._create_and_start_language_server(ls_id) def add_language_server(self, ls_id: LanguageServerIdLike) -> SolidLanguageServer: """ Dynamically adds a new language server for the given language. :param ls_id: the language server to add :return: the newly created language server """ if ls_id in self._language_servers: raise ValueError(f"Language server {ls_id.get_key()} already present") return self._create_and_start_language_server(ls_id) def remove_language_server(self, ls_id: LanguageServerIdLike, save_cache: bool = False) -> None: """ Removes the language server for the given language, stopping it if it is running. :param ls_id: the language """ if ls_id not in self._language_servers: raise ValueError(f"No language server for language {ls_id.get_key()} present; cannot remove") ls = self._language_servers.pop(ls_id) self._stop_language_server(ls, save_cache=save_cache) def get_active_language_server_ids(self) -> list[LanguageServerIdLike]: """ Returns the list of languages for which language servers are currently managed. :return: list of languages """ return list(self._language_servers.keys()) @staticmethod def _stop_language_server(ls: SolidLanguageServer, save_cache: bool = False, timeout: float = 2.0) -> None: if save_cache and ls.is_running(): ls.save_cache() log.info(f"Stopping language server for language {ls.ls_id} ...") ls.stop(shutdown_timeout=timeout) def iter_language_servers(self) -> Iterator[SolidLanguageServer]: for ls in self._language_servers.values(): yield self._ensure_functional_ls(ls) def stop_all(self, save_cache: bool = False, timeout: float = 2.0) -> None: """ Stops all managed language servers. :param save_cache: whether to save the cache before stopping :param timeout: timeout for shutdown of each language server """ for ls in self._language_servers.values(): self._stop_language_server(ls, save_cache=save_cache, timeout=timeout) def save_all_caches(self) -> None: """ Saves the caches of all managed language servers. """ for ls in self.iter_language_servers(): if ls.is_running(): ls.save_cache() self._last_cache_save_time = time.monotonic() def save_all_caches_if_due(self) -> None: """ Saves the caches of all managed language servers unless they were saved less than `_CACHE_SAVE_INTERVAL` seconds ago, such that frequent tool calls do not rewrite large caches every time. Changes not saved yet are saved when the language servers are stopped or restarted. """ if self._last_cache_save_time is not None and time.monotonic() - self._last_cache_save_time < self._CACHE_SAVE_INTERVAL: return self.save_all_caches() def has_suitable_ls_for_file(self, relative_file_path: str) -> bool: return self._get_suitable_language_server(relative_file_path) is not None def sync_file_system_changes(self) -> int: """ Polls the file system for changes to source files and notifies the language servers of any changes (particularly changes that happened outside of Serena's own file tools, which are not covered by the notifications sent by those tools/CodeEditor). :return: the number of individual file change events detected (0 if nothing changed). """ log.info("Polling file system for changes to source files ...") num_changes = self._file_change_notifier.poll_and_notify() log.info(f"File system polling complete; {num_changes} change events sent to language servers.") return num_changes class LanguageServerFileChangeNotifier: """ Detects changes to source files on disk and notifies language servers of those changes. """ def __init__(self, project: "Project", language_server_manager: LanguageServerManager, initial_poll: bool = True) -> None: self._project = project self._language_server_manager = language_server_manager self._freshness_last_seen_mtimes: dict[str, float] | None = None self._freshness_lock = threading.Lock() if initial_poll: # Establish the baseline for the first poll; no notifications are sent on the first call. with LogTime("Initialising file change notifier (polling for baseline)"): self.poll_and_notify() def poll_and_notify(self) -> int: """ Detects source files that were changed, created or deleted on disk since the last call and notifies every language server managed for this project via the LSP ``wo - src/serena/lsp/lsp_backend.py (3097 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging from typing import TYPE_CHECKING from overrides import override from sensai.util.logging import LogTime from serena.language_backend import BuiltinLanguageBackend, LanguageBackend from serena.util.file_proxy import FileProxy, LocalProjectFileProxy if TYPE_CHECKING: from serena.agent import SerenaAgent from serena.code_editor import LanguageServerCodeEditor from serena.project import Project from serena.repl.facade import ApiScope, Facade from serena.tools import Tool log = logging.getLogger(__name__) class LSPLanguageBackend(LanguageBackend): def __init__(self): super().__init__(BuiltinLanguageBackend.LSP.value) @override def get_lsp_tool_class_replacements(self) -> "dict[type[Tool], type[Tool]]": return {} @override def create_facades(self, agent: "SerenaAgent", api_scope: "ApiScope") -> list["Facade"]: from ..repl.api.lsp_api import LspApi from ..repl.facade import Facade return [Facade.from_api(LspApi(agent), api_scope, agent.get_repl_facade_method_usage_stats())] @override def init_active_project(self, agent: "SerenaAgent") -> None: with LogTime("Language server initialization", logger=log): agent.reset_language_server_manager() @override def shutdown_active_project(self, project: "Project", timeout: float) -> None: # nothing to do; the language server manager is already shut down by the project itself pass @override def get_project_activation_statement(self, project: "Project") -> str: language_servers_str = ", ".join([ls.get_key() for ls in project.project_config.language_servers]) return f"Active language servers: {language_servers_str}.\n" @override def get_config_overview_statement(self, project: "Project") -> str: return f"Language server status: {project.get_language_server_manager_status()}\n" @override def create_code_editor(self, project: "Project") -> "LanguageServerCodeEditor": from serena.code_editor import LanguageServerCodeEditor from serena.symbol import LanguageServerSymbolRetriever symbol_retriever = LanguageServerSymbolRetriever(project) return LanguageServerCodeEditor(symbol_retriever) @override def is_source_file(self, abs_path: str, project: "Project") -> bool: is_file_in_supported_languages = False for language in project.project_config.language_servers: fn_matcher = language.get_source_fn_matcher() if fn_matcher.is_relevant_filename(abs_path): is_file_in_supported_languages = True break return is_file_in_supported_languages @override def is_external_path(self, relative_path: str) -> bool: # LSP backend currently uses only true project-relative paths return False @override def create_file_proxy(self, relative_path: str, project: "Project") -> FileProxy: return LocalProjectFileProxy(relative_path, project) - src/serena/lsp/lsp_diagnostics.py (10415 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json from collections.abc import Iterable from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Optional, Self from serena.util.text_utils import TextOutputUtils from solidlsp import ls_types from solidlsp.lsp_protocol_handler.lsp_types import DiagnosticSeverity if TYPE_CHECKING: from serena.agent import SerenaAgent from serena.symbol import LanguageServerSymbolRetriever @dataclass(frozen=True) class EditedFilePath: before_relative_path: str after_relative_path: str @dataclass(frozen=True) class DiagnosticIdentity: message: str start_line: int start_character: int end_line: int end_character: int severity: int | None code_repr: str | None source: str | None @classmethod def from_diagnostic(cls, diagnostic: ls_types.Diagnostic) -> "DiagnosticIdentity": diagnostic_range = diagnostic["range"] start = diagnostic_range["start"] end = diagnostic_range["end"] return DiagnosticIdentity( message=diagnostic["message"], start_line=start["line"], start_character=start["character"], end_line=end["line"], end_character=end["character"], severity=diagnostic.get("severity"), code_repr=cls._diagnostic_code_repr(diagnostic.get("code")), source=diagnostic.get("source"), ) @staticmethod def _diagnostic_code_repr(code: Any) -> str | None: if code is None: return None try: return json.dumps(code, sort_keys=True, ensure_ascii=False) except TypeError: return repr(code) class PublishedDiagnosticsSnapshot: def __init__(self, edited_file_paths: Iterable[EditedFilePath], symbol_retriever: "LanguageServerSymbolRetriever"): generation_by_after_path: dict[str, int] = {} warning_identities_by_before_path: dict[str, set[DiagnosticIdentity]] = {} for edited_file_path in edited_file_paths: try: language_server = symbol_retriever.get_language_server(edited_file_path.after_relative_path) except Exception: continue generation_by_after_path[edited_file_path.after_relative_path] = language_server.get_published_diagnostics_generation( edited_file_path.after_relative_path ) cached_diagnostics = language_server.get_cached_published_text_document_diagnostics( edited_file_path.before_relative_path, min_severity=2, ) if cached_diagnostics is None: try: cached_diagnostics = language_server.request_text_document_diagnostics( edited_file_path.before_relative_path, min_severity=2, ) except Exception: cached_diagnostics = [] warning_identities_by_before_path[edited_file_path.before_relative_path] = { DiagnosticIdentity.from_diagnostic(diagnostic) for diagnostic in cached_diagnostics or [] } self.generation_by_after_path = generation_by_after_path self.warning_identities_by_before_path = warning_identities_by_before_path class GroupedDiagnostics: def __init__(self) -> None: self._grouped_diagnostics: dict[str, dict[str, dict[str, list[dict[str, Any]]]]] = {} def add(self, relative_path: str, name_path: str, diagnostic: ls_types.Diagnostic) -> None: severity_name = self._diagnostic_severity_name(diagnostic.get("severity")) self._grouped_diagnostics.setdefault(relative_path, {}).setdefault(severity_name, {}).setdefault(name_path, []).append( self._diagnostic_output_dict(diagnostic) ) def get_dict(self) -> dict[str, dict[str, dict[str, list[dict[str, Any]]]]]: """ Returns a nested dictionary of the form: { relative_file_path: { severity_name: { name_path: [ diagnostic_dict, ... ], ... }, ... }, ... } where: - relative_file_path is the relative path of the file containing the diagnostic - severity_name is the name of the diagnostic severity (e.g. "Warning", "Error") - name_path is the name path of the symbol that owns the diagnostic (or "<file>" if no owner symbol was found) - diagnostic_dict is a dictionary containing the diagnostic's message, range, and optionally code and source """ return self._grouped_diagnostics @staticmethod def _diagnostic_severity_name(severity: int | None) -> str: if severity is None: return "Unknown" try: return DiagnosticSeverity(severity).name except ValueError: return f"Severity_{severity}" @staticmethod def _diagnostic_output_dict(diagnostic: ls_types.Diagnostic) -> dict[str, Any]: result: dict[str, Any] = { "message": diagnostic["message"], "range": diagnostic["range"], } if "code" in diagnostic: result["code"] = diagnostic["code"] if "source" in diagnostic: result["source"] = diagnostic["source"] return result class DiagnosticsDiff: def __init__( self, before_snapshot: PublishedDiagnosticsSnapshot, edited_files: Iterable[EditedFilePath], symbol_retriever: "LanguageServerSymbolRetriever", ): grouped_diagnostics = GroupedDiagnostics() for edited_file_path in edited_files: try: language_server = symbol_retriever.get_language_server(edited_file_path.after_relative_path) except: continue published_diagnostics = language_server.request_published_text_document_diagnostics( relative_file_path=edited_file_path.after_relative_path, after_generation=before_snapshot.generation_by_after_path.get(edited_file_path.after_relative_path, -1), timeout=2.5, min_severity=2, allow_cached=True, ) if not published_diagnostics: try: published_diagnostics = language_server.request_text_document_diagnostics( edited_file_path.after_relative_path, min_severity=2, ) except: published_diagnostics = None if published_diagnostics is None: continue existing_warning_identities = before_snapshot.warning_identities_by_before_path.get( edited_file_path.before_relative_path, set() ) new_warning_identities: set[DiagnosticIdentity] = set() for diagnostic in published_diagnostics: diagnostic_identity = DiagnosticIdentity.from_diagnostic(diagnostic) if diagnostic_identity in existing_warning_identities or diagnostic_identity in new_warning_identities: continue new_warning_identities.add(diagnostic_identity) diagnostic_start = diagnostic["range"]["start"] owner_symbol = symbol_retriever.find_diagnostic_owner_symbol( relative_file_path=edited_file_path.after_relative_path, line=diagnostic_start["line"], column=diagnostic_start["character"], ) name_path = owner_symbol.get_name_path() if owner_symbol is not None else "<file>" grouped_diagnostics.add(edited_file_path.after_relative_path, name_path, diagnostic) self._grouped_diagnostics = grouped_diagnostics def get_grouped_diagnostics(self) -> GroupedDiagnostics: return self._grouped_diagnostics class DiagnosticsContext: ENABLE_DIAGNOSTICS_DEFAULT: bool = False """ Global flag to enable/disable diagnostics for LSP-based editing tools derived from this class. The feature is currently disabled, because per-edit diagnostics are a questionable feature, since individual edits often intentionally introduce diagnostics (e.g. function signature mismatches or even syntax errors) that are then resolved in subsequent edits. """ DIAGNOSTICS_KEY = "diagnostics[warning-or-higher]" def __init__(self, agent: "SerenaAgent", *edited_relative_paths: str, enable: bool = ENABLE_DIAGNOSTICS_DEFAULT) -> None: self._is_diagnostics_enabled = enable and agent.get_language_backend() self._edited_files = [EditedFilePath(path, path) for path in edited_relative_paths] self._before_edit_diagnostics_snapshot: PublishedDiagnosticsSnapshot | None = None self._symbol_retriever: Optional["LanguageServerSymbolRetriever"] | None = None if self._is_diagnostics_enabled: from serena.symbol import LanguageServerSymbolRetriever # local import to avoid a circular dependency self._symbol_retriever = LanguageServerSymbolRetriever(agent.get_active_project_or_raise()) self._before_edit_diagnostics_snapshot = PublishedDiagnosticsSnapshot(self._edited_files, self._symbol_retriever) def __enter__(self) -> Self: return self def __exit__(self, exc_type, exc_val, exc_tb): pass def format_result( self, base_result: str, ) -> str: if not self._is_diagnostics_enabled: return base_result if self._before_edit_diagnostics_snapshot is None: return base_result assert self._symbol_retriever is not None diagnostics_diff = DiagnosticsDiff(self._before_edit_diagnostics_snapshot, self._edited_files, self._symbol_retriever) grouped_diagnostics = diagnostics_diff.get_grouped_diagnostics().get_dict() if not grouped_diagnostics: return base_result else: result_dict = { "result": base_result, self.DIAGNOSTICS_KEY: grouped_diagnostics, } return TextOutputUtils.to_json(result_dict) - src/serena/mcp.py (21254 bytes)
""" The Serena Model Context Protocol (MCP) Server """ # SPDX-License-Identifier: GPL-3.0-or-later import sys from collections.abc import AsyncIterator, Iterator from contextlib import asynccontextmanager, contextmanager from copy import deepcopy from dataclasses import dataclass from functools import wraps from inspect import signature from typing import Any, Literal, cast import docstring_parser import uvicorn from mcp.server.mcpserver import server from mcp.server.mcpserver.context import LifespanContextT, RequestT from mcp.server.mcpserver.exceptions import ToolError from mcp.server.mcpserver.server import Context from mcp.server.mcpserver.server import MCPServer as FastMCP from mcp.server.mcpserver.tools.base import Tool as FastMCPTool from mcp.types import ToolAnnotations from sensai.util import logging from serena import __version__ as serena_version_str from serena.agent import ( SerenaAgent, ) from serena.config.context_mode import SerenaAgentContext from serena.config.serena_config import AgentInterface, ModeSelectionDefinition, SerenaConfig from serena.constants import DEFAULT_CONTEXT, SERENA_LOG_FORMAT from serena.language_backend import LanguageBackend from serena.tools import Tool, ToolCallError from serena.util.exception import show_fatal_exception_safe from serena.util.logging import MemoryLogHandler log = logging.getLogger(__name__) def configure_logging(*args, **kwargs) -> None: # We only do something here if logging has not yet been configured. # Normally, logging is configured in the MCP server startup script. if not logging.is_enabled(): logging.basicConfig(level=logging.INFO, stream=sys.stderr, format=SERENA_LOG_FORMAT) # patch the logging configuration function in fastmcp, because it's hard-coded and broken server.configure_logging = configure_logging # type: ignore @contextmanager def uvicorn_ignore_logging_config_context() -> Iterator[None]: """ Temporarily suppress Uvicorn logging configuration during HTTP server execution. The MCP SDK uses Uvicorn to serve the MCP server over HTTP but does not allow uvicorn's logging configuration to be set. As a result, uvicorn's default configuration applies, which, unfortunately, overrides any existing logging configuration. This context manager temporarily replaces the uvicorn.Config constructor to ignore any logging configuration options, ensuring that the existing logging configuration remains intact. """ original_config = uvicorn.Config @wraps(original_config) def create_config(*args: Any, **kwargs: Any) -> uvicorn.Config: # override logging options supplied positionally, by keyword, or through defaults arguments = signature(original_config).bind_partial(*args, **kwargs) arguments.arguments["log_config"] = None arguments.arguments["log_level"] = None return original_config(*arguments.args, **arguments.kwargs) # restore the constructor uvicorn.Config = create_config # type: ignore try: yield finally: uvicorn.Config = original_config @dataclass class SerenaMCPRequestContext: agent: SerenaAgent class SerenaFastMCPTool(FastMCPTool): def __init__(self, tool: Tool, openai_tool_compatible: bool, structured_output: bool | None): """ :param tool: the Serena tool :param openai_tool_compatible: whether to process the tool schema to be compatible with OpenAI tools (doesn't accept integer, needs number instead, etc.). This allows using Serena MCP within Codex. :param structured_output: whether to use structured output for the tool (None = auto) """ func_name = tool.get_name() func_doc = tool.get_apply_docstring() or "" func_arg_metadata = tool.get_apply_fn_metadata(structured_output=structured_output) is_async = False parameters = func_arg_metadata.arg_model.model_json_schema() if openai_tool_compatible: parameters = SerenaMCPFactory._sanitize_for_openai_tools(parameters) docstring = docstring_parser.parse(func_doc) # Mount the tool description as a combination of the docstring description and # the return value description, if it exists. overridden_description = tool.agent.get_context().tool_description_overrides.get(func_name, None) if overridden_description is not None: func_doc = overridden_description elif docstring.description: func_doc = docstring.description else: func_doc = "" func_doc = func_doc.strip().strip(".") if func_doc: func_doc += "." if docstring.returns and (docstring_returns_descr := docstring.returns.description): # Only add a space before "Returns" if func_doc is not empty prefix = " " if func_doc else "" func_doc = f"{func_doc}{prefix}Returns {docstring_returns_descr.strip().strip('.')}." # Parse the parameter descriptions from the docstring and add pass its description # to the parameter schema. docstring_params = {param.arg_name: param for param in docstring.params} parameters_properties: dict[str, dict[str, Any]] = parameters["properties"] for parameter, properties in parameters_properties.items(): if (param_doc := docstring_params.get(parameter)) and param_doc.description: param_desc = f"{param_doc.description.strip().strip('.') + '.'}" properties["description"] = param_desc[0].upper() + param_desc[1:] def execute_fn(**kwargs) -> str: try: return tool.apply_ex(log_call=True, catch_exceptions=False, **kwargs) except ToolCallError as e: raise ToolError(e.get_error_message()) from e # Generate human-readable title from snake_case tool name tool_title = " ".join(word.capitalize() for word in func_name.split("_")) # Create annotations with appropriate hints based on tool capabilities can_edit = tool.can_edit() annotations = ToolAnnotations( title=tool_title, read_only_hint=not can_edit, destructive_hint=can_edit, ) super().__init__( fn=execute_fn, name=func_name, description=func_doc, parameters=parameters, fn_metadata=func_arg_metadata, is_async=is_async, # keep the value in sync with the kwarg name in Tool.apply_ex. The mcp sdk uses reflection to infer this # when the tool is constructed via from_function (which is a bit crazy IMO, but well...) context_kwarg="mcp_ctx", annotations=annotations, title=tool_title, ) self._param_aliases = tool.get_param_aliases() async def run( self, arguments: dict[str, Any], context: Context[LifespanContextT, RequestT], convert_result: bool = False, ) -> Any: # apply parameter aliases for param_alias, param_name in self._param_aliases.items(): if param_alias in arguments and param_name not in arguments: arguments[param_name] = arguments.pop(param_alias) return await super().run(arguments, context, convert_result) class SerenaMCPFactory: """ Factory for the creation of the Serena MCP server with an associated SerenaAgent. """ def __init__( self, transport: Literal["stdio", "sse", "streamable-http"], context: str = DEFAULT_CONTEXT, project: str | None = None, memory_log_handler: MemoryLogHandler | None = None, ): """ :param transport: The transport to use for the MCP server. :param context: The context name or path to context file :param project: Either an absolute path to the project directory or a name of an already registered project. If the project passed here hasn't been registered yet, it will be registered automatically and can be activated by its name afterward. :param memory_log_handler: the in-memory log handler to use for the agent's logging """ self.transport = transport self.context = SerenaAgentContext.load(context) self.project = project self.agent: SerenaAgent | None = None self.memory_log_handler = memory_log_handler @staticmethod def _sanitize_for_openai_tools(schema: dict) -> dict: """ This method was written by GPT-5, I have not reviewed it in detail. Only called when `openai_tool_compatible` is True. Make a Pydantic/JSON Schema object compatible with OpenAI tool schema. - 'integer' -> 'number' (+ multipleOf: 1) - remove 'null' from union type arrays - coerce integer-only enums to number - best-effort simplify oneOf/anyOf when they only differ by integer/number """ s = deepcopy(schema) def walk(node): if not isinstance(node, dict): # lists get handled by parent calls return node # ---- handle type ---- t = node.get("type") if isinstance(t, str): if t == "integer": node["type"] = "number" # preserve existing multipleOf but ensure it's integer-like if "multipleOf" not in node: node["multipleOf"] = 1 elif isinstance(t, list): # remove 'null' (OpenAI tools don't support nullables) t2 = [x if x != "integer" else "number" for x in t if x != "null"] if not t2: # fall back to object if it somehow becomes empty t2 = ["object"] node["type"] = t2[0] if len(t2) == 1 else t2 if "integer" in t or "number" in t2: # if integers were present, keep integer-like restriction node.setdefault("multipleOf", 1) # ---- enums of integers -> number ---- if "enum" in node and isinstance(node["enum"], list): vals = node["enum"] if vals and all(isinstance(v, int) for v in vals): node.setdefault("type", "number") # keep them as ints; JSON 'number' covers ints node.setdefault("multipleOf", 1) # ---- simplify anyOf/oneOf if they only differ by integer/number ---- for key in ("oneOf", "anyOf"): if key in node and isinstance(node[key], list): # Special case: anyOf or oneOf with "type X" and "null" if len(node[key]) == 2: types = [sub.get("type") for sub in node[key]] if "null" in types: non_null_type = next(t for t in types if t != "null") if isinstance(non_null_type, str): node["type"] = non_null_type node.pop(key, None) continue simplified = [] changed = False for sub in node[key]: sub = walk(sub) # recurse simplified.append(sub) # If all subs are the same after integer→number, collapse try: import json canon = [json.dumps(x, sort_keys=True) for x in simplified] if len(set(canon)) == 1: # copy the single schema up only = simplified[0] node.pop(key, None) for k, v in only.items(): if k not in node: node[k] = v changed = True except Exception: pass if not changed: node[key] = simplified # ---- recurse into known schema containers ---- for child_key in ("properties", "patternProperties", "definitions", "$defs"): if child_key in node and isinstance(node[child_key], dict): for k, v in list(node[child_key].items()): node[child_key][k] = walk(v) # arrays/items if "items" in node: node["items"] = walk(node["items"]) # allOf/if/then/else - pass through with integer→number conversions applied inside for key in ("allOf",): if key in node and isinstance(node[key], list): node[key] = [walk(x) for x in node[key]] if "if" in node: node["if"] = walk(node["if"]) if "then" in node: node["then"] = walk(node["then"]) if "else" in node: node["else"] = walk(node["else"]) return node return walk(s) @staticmethod def make_mcp_tool(tool: Tool, openai_tool_compatible: bool = True, structured_output: bool | None = None) -> SerenaFastMCPTool: """ Creates an MCP tool from a Serena Tool instance. :param tool: the Serena Tool instance to convert. :param openai_tool_compatible: whether to process the tool schema to be compatible with OpenAI tools (doesn't accept integer, needs number instead, etc.). This allows using Serena MCP within codex. :param structured_output: whether to use structured output for the tool (None = auto) """ return SerenaFastMCPTool(tool, openai_tool_compatible=openai_tool_compatible, structured_output=structured_output) def _iter_tools(self) -> Iterator[Tool]: assert self.agent is not None yield from self.agent.get_exposed_tool_instances() # noinspection PyProtectedMember def _set_mcp_tools(self, mcp: FastMCP, openai_tool_compatible: bool, structured_output: bool | None) -> None: """ Update the tools in the MCP server :param mcp: The MCP server to update :param openai_tool_compatible: whether to process the tool schema to be compatible with OpenAI tools :param structured_output: whether to use structured output for the tools (None = auto) """ if mcp is not None: mcp._tool_manager._tools = {} for tool in self._iter_tools(): mcp_tool = self.make_mcp_tool(tool, openai_tool_compatible=openai_tool_compatible, structured_output=structured_output) mcp._tool_manager._tools[tool.get_name()] = mcp_tool log.info(f"Starting MCP server with {len(mcp._tool_manager._tools)} tools: {list(mcp._too - src/serena/memories/memory_manager.py (21434 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import os import re import shutil from collections.abc import Iterator, Sequence from pathlib import Path from typing import Literal from serena.config.serena_config import ( SerenaPaths, ) from serena.constants import SERENA_FILE_ENCODING from serena.util.file_system import write_file_atomic from serena.util.text_utils import ContentReplacer from .memory_reference_analysis import ( MEMORY_REF_PREFIX, AutofixReport, MemoryReferenceAnalyzer, ReferentialIntegrityReport, ) log = logging.getLogger(__name__) class MemoryManager: GLOBAL_TOPIC = "global" _global_memory_dir = SerenaPaths().global_memories_path _MEMORY_REF_PREFIX = MEMORY_REF_PREFIX def __init__( self, serena_data_folder: str | Path | None, read_only_memory_patterns: Sequence[str] = (), ignored_memory_patterns: Sequence[str] = (), ): """ :param serena_data_folder: the absolute path to the project's .serena data folder :param read_only_memory_patterns: whether to allow writing global memories in tool execution contexts :param ignored_memory_patterns: regex patterns for memories to completely exclude from listing, reading, and writing. Matching memories will not appear in list_memories or activate_project output and cannot be accessed via read_memory or write_memory. Use read_file on the raw path to access ignored memory files. """ self._project_memory_dir: Path | None = None if serena_data_folder is not None: self._project_memory_dir = Path(serena_data_folder) / "memories" self._project_memory_dir.mkdir(parents=True, exist_ok=True) self._encoding = SERENA_FILE_ENCODING self._read_only_memory_patterns = [re.compile(pattern) for pattern in set(read_only_memory_patterns)] self._ignored_memory_patterns = [re.compile(pattern) for pattern in set(ignored_memory_patterns)] def _is_read_only_memory(self, name: str) -> bool: for pattern in self._read_only_memory_patterns: if pattern.fullmatch(name): return True return False def _is_ignored_memory(self, name: str) -> bool: for pattern in self._ignored_memory_patterns: if pattern.fullmatch(name): return True return False def _check_not_ignored(self, name: str) -> None: if self._is_ignored_memory(name): raise ValueError( f"Memory '{name}' matches an ignored_memory_patterns pattern and cannot be accessed. " f"Use the read_file tool on the raw file path instead." ) def _is_global(self, name: str) -> bool: return name == self.GLOBAL_TOPIC or name.startswith(self.GLOBAL_TOPIC + "/") @classmethod def _sanitize_name(cls, name: str) -> str: """Corrects the name for common mistakes made by LLMs (``mem:`` prefix, ``.md`` suffix, OS-specific separators).""" name = name.removeprefix(cls._MEMORY_REF_PREFIX) if name.endswith(".md"): name = name[:-3] return name.replace(os.sep, "/") @classmethod def _add_reference_prefix(cls, name: str) -> str: name = cls._sanitize_name(name) return cls._MEMORY_REF_PREFIX + name MEMORY_MAINTENANCE_NAME: str = "memory_maintenance" _MEMORY_MAINTENANCE_TEMPLATE_PATH: Path = SerenaPaths().get_resource_path("memory_maintenance.md") def ensure_memory_maintenance_memory(self) -> str: """ Ensures a memory describing how memories should be maintained exists for this project, and returns the name to reference it by. Precedence: 1. If a global copy exists at ``global/memory_maintenance``, return that name; no project copy is created (the global version takes precedence). 2. Else if a project copy already exists, return its name unchanged. 3. Else seed a project copy from the package-shipped template and return that name. Existing memory files are never overwritten; users may have customized them. To refresh from the shipped template, delete the existing memory first. :return: the bare name to reference the maintenance memory by (without the ``mem:`` prefix); either ``"global/memory_maintenance"`` or ``"memory_maintenance"``. :raises FileNotFoundError: if the shipped template is missing on disk. :raises AssertionError: if this manager has no associated project directory. """ global_name = f"{self.GLOBAL_TOPIC}/{self.MEMORY_MAINTENANCE_NAME}" if self.get_memory_file_path(global_name).exists(): return global_name if self.get_memory_file_path(self.MEMORY_MAINTENANCE_NAME).exists(): return self.MEMORY_MAINTENANCE_NAME # seed a project copy from the shipped template template_path = self._MEMORY_MAINTENANCE_TEMPLATE_PATH if not template_path.exists(): raise FileNotFoundError(f"Memory maintenance template not found at {template_path}") content = template_path.read_text(encoding=self._encoding) self.save_memory(self.MEMORY_MAINTENANCE_NAME, content, is_tool_context=False) return self.MEMORY_MAINTENANCE_NAME def rename_references_to_memory(self, content: str, old_name: str, new_name: str) -> tuple[str, int]: r""" Replaces all occurrences of a memory reference (e.g. ``mem:foo``) in ``content`` with the reference to ``new_name``. Matches only references whose name is exactly ``old_name``: the match must not be embedded in a longer memory name. A memory name consists of the character class ``[A-Za-z0-9_\\-/]`` (alphanumerics, underscore, hyphen, slash for topic separation), which determines the boundary of the match. The surrounding delimiters (backticks, quotes, parentheses, whitespace, etc.) are intentionally unconstrained. :param content: the text to search through :param old_name: the memory name being renamed away from (without the ``mem:`` prefix) :param new_name: the memory name being renamed to (without the ``mem:`` prefix) :return: a tuple of (updated content, number of replacements made) """ # define the character class that constitutes a memory name; matches inside such a run are not real references name_char = r"[A-Za-z0-9_\-/]" ref_old = self._add_reference_prefix(old_name) ref_new = self._add_reference_prefix(new_name) # build a pattern that anchors the reference on both sides so it cannot be embedded inside a longer name pattern = rf"(?<!{name_char}){re.escape(ref_old)}(?!{name_char})" # use a callable replacement to avoid backreference interpretation of characters in ref_new return re.subn(pattern, lambda _m: ref_new, content) def _resolve_memory_path(self, base_dir: Path, parts: Sequence[str]) -> Path: """ Builds the ``*.md`` path for ``parts`` under ``base_dir``, creating any parent subdirectories, and guarantees the result stays inside ``base_dir``. The containment check is a defense-in-depth backstop for :meth:`get_memory_file_path`'s up-front segment validation: even if a crafted name slipped through, the built path must never escape the memories sandbox (which would let an agent read/write/delete arbitrary files). The check runs *before* any directory is created, so a rejected name cannot leave stray directories behind either. It is deliberately *lexical* (``normpath``, no symlink resolution): directory symlinks placed inside the memories folder are a supported way to share memories (e.g. a monorepo symlinking each submodule's memory dir), and those must keep resolving to their targets at I/O time. """ filename = f"{parts[-1]}.md" subdir = base_dir if len(parts) == 1 else base_dir.joinpath(*parts[:-1]) candidate = subdir / filename base_norm = Path(os.path.normpath(base_dir)) if not Path(os.path.normpath(candidate)).is_relative_to(base_norm): raise ValueError(f"Memory name resolves outside the memories directory. Got: {'/'.join(parts)}") subdir.mkdir(parents=True, exist_ok=True) return candidate def get_memory_file_path(self, name: str) -> Path: name = self._sanitize_name(name) parts = name.split("/") if ".." in parts: raise ValueError(f"Memory name cannot contain '..' segments. Got: {name}") # Reject absolute names and empty path segments: pathlib discards the base directory when # joined with an absolute path (e.g. "/etc/cron.d/backdoor" would reset to "/etc/cron.d"), # letting a memory name escape the sandbox. A leading "/" produces an empty first segment. if os.path.isabs(name) or "" in parts: raise ValueError(f"Memory name cannot be absolute or contain empty path segments. Got: {name}") if self._is_global(name): if name == self.GLOBAL_TOPIC: raise ValueError( f'Bare "{self.GLOBAL_TOPIC}" is not a valid memory name. Use "{self.GLOBAL_TOPIC}/<name>" to address a global memory.' ) # Strip "global/" prefix and resolve against global dir sub_name = name[len(self.GLOBAL_TOPIC) + 1 :] return self._resolve_memory_path(self._global_memory_dir, sub_name.split("/")) # Project-local memory assert self._project_memory_dir is not None, "Project dir was not passed at initialization" return self._resolve_memory_path(self._project_memory_dir, parts) def _check_write_access(self, name: str, is_tool_context: bool) -> None: # in tool context, memories can be read-only if is_tool_context and self._is_read_only_memory(name): raise PermissionError(f"Attempted to write to read_only memory: '{name}')") def load_memory(self, name: str) -> str: name = self._sanitize_name(name) self._check_not_ignored(name) memory_file_path = self.get_memory_file_path(name) if not memory_file_path.exists(): raise FileNotFoundError(f"Memory named '{name}' not found") with open(memory_file_path, encoding=self._encoding) as f: return f.read() def save_memory(self, name: str, content: str, is_tool_context: bool) -> str: name = self._sanitize_name(name) self._check_not_ignored(name) self._check_write_access(name, is_tool_context) memory_file_path = self.get_memory_file_path(name) write_file_atomic(str(memory_file_path), content, encoding=self._encoding) return f"Memory {name} written." class MemoriesList: def __init__(self) -> None: self.memories: list[str] = [] self.read_only_memories: list[str] = [] def __len__(self) -> int: return len(self.memories) + len(self.read_only_memories) def add(self, memory_name: str, is_read_only: bool) -> None: if is_read_only: self.read_only_memories.append(memory_name) else: self.memories.append(memory_name) def extend(self, other: "MemoryManager.MemoriesList") -> None: self.memories.extend(other.memories) self.read_only_memories.extend(other.read_only_memories) def to_dict(self) -> dict[str, list[str]]: result = {} if self.memories: result["memories"] = sorted(self.memories) if self.read_only_memories: result["read_only_memories"] = sorted(self.read_only_memories) return result def get_full_list(self) -> list[str]: return sorted(self.memories + self.read_only_memories) @staticmethod def _iter_memory_files(search_dir: Path) -> Iterator[Path]: """Yields every ``*.md`` file under ``search_dir``, descending into symlinked directories. Directory symlinks must be followed so that memories shared via symlink are discovered (e.g. a monorepo whose ``.serena/memories`` folder symlinks each submodule's memory directory, making them addressable as ``<submodule>/<name>``). ``Path.rglob`` only follows symlinked directories from Python 3.13 onwards, via ``recurse_symlinks``; on 3.11/3.12 it silently skips them, so we fall back to ``os.walk(followlinks=True)`` there. ``rglob`` is preferred when available as it is faster than ``os.walk``. """ for root, _dirs, files in os.walk(search_dir, followlinks=True): for filename in files: if filename.endswith(".md"): yield Path(root) / filename def _list_memories(self, search_dir: Path, base_dir: Path, prefix: str = "") -> MemoriesList: result = self.MemoriesList() if not search_dir.exists(): return result for md_file in self._iter_memory_files(search_dir): rel = str(md_file.relative_to(base_dir).with_suffix("")).replace(os.sep, "/") memory_name = prefix + rel if self._is_ignored_memory(memory_name): continue result.add(memory_name, is_read_only=self._is_read_only_memory(memory_name)) return result def list_global_memories(self, subtopic: str = "") -> MemoriesList: dir_path = self._global_memory_dir if subtopic: dir_path = dir_path / subtopic.replace("/", os.sep) return self._list_memories(dir_path, self._global_memory_dir, self.GLOBAL_TOPIC + "/") def list_project_memories(self, topic: str = "") -> MemoriesList: assert self._project_memory_dir is not None, "Project dir was not passed at initialization" dir_path = self._project_memory_dir if topic: dir_path = dir_path / topic.replace("/", os.sep) return self._list_memories(dir_path, self._project_memory_dir) def list_memories(self, topic: str = "") -> MemoriesList: """ Lists all memories, optionally filtered by topic. If the topic is omitted, both global and project-specific memories are returned. """ memories: MemoryManager.MemoriesList if topic: if self._is_global(topic): topic_parts = topic.split("/") subtopic = "/".join(topic_parts[1:]) memories = self.list_global_memories(subtopic=subtopic) else: memories = self.list_project_memories(topic=topic) else: memories = self.list_project_memories() memories.extend(self.list_global_memories()) return memories def delete_memory(self, name: str, i - src/serena/memories/memory_reference_analysis.py (38862 bytes)
""" Memory reference matching, similarity scoring, and integrity reporting. This module contains the pure helpers and data types used by :class:`serena.project.MemoriesManager` to (a) detect and rank references between memories, and (b) report referential integrity issues. The :class:`MemoryReferenceAnalyzer` class drives the validation and autofix workflows against a live ``MemoriesManager`` instance. Kept separate from the manager so the matching heuristics can be evolved and tested in isolation from filesystem and lifecycle concerns. """ # SPDX-License-Identifier: GPL-3.0-or-later from __future__ import annotations import re from collections.abc import Iterator from dataclasses import dataclass, field from difflib import SequenceMatcher from typing import TYPE_CHECKING from sensai.util.string import TextBuilder if TYPE_CHECKING: from .memory_manager import MemoryManager # --------------------------------------------------------------------------- # Constants # --------------------------------------------------------------------------- MEMORY_REF_PREFIX: str = "mem:" """Reference prefix used inside memory bodies to point at another memory.""" NAME_SIMILARITY_THRESHOLD: float = 0.55 """Minimum :func:`compute_name_similarity` score for a candidate to be reported.""" HIGH_CONFIDENCE_NAME_LENGTH: int = 10 """Length threshold above which a flat memory name is considered "name-shaped" (i.e. unlikely to coincide with ordinary prose).""" SHORT_NAME_FLOOR: int = 3 """Below this basename length, only an exact token match keeps similarity above 0.""" FUZZY_BARE_TOKEN_JACCARD_FLOOR: float = 0.6 """For fuzzy bare-text matching, the bare token and the candidate existing name must share at least this fraction of their tokenized name parts. Containment / SequenceMatcher signals alone over-match — e.g. a generic prose word like ``repository`` is a substring of ``serena_repository_structure`` but their token Jaccard is only 1/3, so we reject it at this floor.""" BASENAME_JACCARD_FLOOR: float = 0.34 """In :func:`compute_name_similarity` case 2 (basenames differ), when the two names also carry *differing* topic prefixes, demand at least one strong basename signal: token Jaccard >= this floor, basename containment, or typo-level seq ratio. Without this gate, names like ``frontend/x-subtleties`` and ``backend/y-subtleties`` get matched purely on the shared trailing token via the SequenceMatcher signal.""" BASENAME_TYPO_SEQ_FLOOR: float = 0.75 """Companion to :data:`BASENAME_JACCARD_FLOOR`: a basename seq ratio above this is treated as typo-level edit distance and bypasses the Jaccard/containment requirement.""" MAX_STALE_REFERENCE_CANDIDATES: int = 3 """Hard cap on candidates proposed per stale reference. Beyond a small number the list stops aiding disambiguation and becomes noise.""" WORDS_TO_IGNORE_AS_MEMORY_NAME_CANDIDATES: frozenset[str] = frozenset({"core"}) """Names that coincide with common English words and are filtered out of the unmarked- reference scan to avoid false positives.""" NAME_CHAR_CLASS: str = r"[A-Za-z0-9_\-/]" """Character class delimiting a memory name. Used to anchor regex matches so we never consume a partial name (kept in sync with the boundary rule in :meth:`MemoriesManager.rename_references_to_memory`).""" _VERSION_SUFFIX_PATTERN: re.Pattern[str] = re.compile(r"_(?:v\d+|old|new|legacy|bak)$", re.IGNORECASE) # --------------------------------------------------------------------------- # Pure helpers: normalization, tokenization, similarity # --------------------------------------------------------------------------- def normalize_for_similarity(name: str) -> str: """ :param name: a memory name :return: a lowercased copy of ``name`` with version/legacy-style trailing suffixes stripped (e.g. ``"auth_v2"`` -> ``"auth"``); used as the canonical form for similarity scoring. """ return _VERSION_SUFFIX_PATTERN.sub("", name.lower()) def tokenize_name(name: str) -> set[str]: """ :param name: a memory name :return: the set of lowercase tokens extracted by splitting ``name`` on ``/``, ``_``, ``-`` and at camelCase boundaries; empty tokens are dropped. """ parts = re.split(r"[/_\-]|(?<=[a-z])(?=[A-Z])", name) return {p.lower() for p in parts if p} def compute_name_similarity(a: str, b: str) -> float: """ Computes a similarity score in ``[0, 1]`` between two memory names. Examples (with default threshold ``0.55``):: auth/login == auth/login -> 1.00 (exact) auth_v1 ~ auth_v2 -> 1.00 (version suffix normalized) login ~ auth/login -> 1.00 (flat <-> topic move) auth/login ~ auth/v2/login -> 0.75 (shared prefix token + basename) auth/login ~ security/login -> 0.50 (basename only; disjoint topics) auth ~ authentication -> 0.64 (substring containment) foo ~ for -> 0.00 (short-name floor) frontend/x-subtleties ~ backend/y-subtleties -> 0.00 (different topics + only a shared generic trailing token) :param a: first memory name :param b: second memory name :return: the similarity score """ # normalize: lowercase + strip version/legacy suffixes norm_a, norm_b = normalize_for_similarity(a), normalize_for_similarity(b) if norm_a == norm_b: return 1.0 # split into prefix / basename basename_a = norm_a.rsplit("/", 1)[-1] basename_b = norm_b.rsplit("/", 1)[-1] prefix_a = norm_a.rsplit("/", 1)[0] if "/" in norm_a else "" prefix_b = norm_b.rsplit("/", 1)[0] if "/" in norm_b else "" # case 1: basenames match -- score is determined entirely by prefix relationship if basename_a == basename_b: if not prefix_a or not prefix_b: # one side is flat -> canonical topic move, strongly confident return 1.0 # both sides carry a topic prefix -> blend basename match (0.5 floor) with prefix token similarity prefix_tokens_a, prefix_tokens_b = tokenize_name(prefix_a), tokenize_name(prefix_b) prefix_jaccard = ( len(prefix_tokens_a & prefix_tokens_b) / len(prefix_tokens_a | prefix_tokens_b) if (prefix_tokens_a | prefix_tokens_b) else 0.0 ) return 0.5 + 0.5 * prefix_jaccard # case 2: basenames differ -- score the *basenames* only, so that a shared topic prefix # plus a generic trailing token (e.g. "frontend/X-subtleties" vs "frontend/Y-subtleties") # does not inflate the SequenceMatcher signal into a false positive. basename_tokens_a, basename_tokens_b = tokenize_name(basename_a), tokenize_name(basename_b) union_basename = basename_tokens_a | basename_tokens_b basename_jaccard = (len(basename_tokens_a & basename_tokens_b) / len(union_basename)) if union_basename else 0.0 basename_contained = bool(basename_a) and bool(basename_b) and (basename_a in basename_b or basename_b in basename_a) seq = SequenceMatcher(None, basename_a, basename_b).ratio() # when both names carry *differing* topic prefixes, demand at least one strong basename # signal — otherwise a single coincidental shared token at the end of long basenames # under different topic roots slips through purely on the seq-ratio if prefix_a and prefix_b and prefix_a != prefix_b: if basename_jaccard < BASENAME_JACCARD_FLOOR and not basename_contained and seq < BASENAME_TYPO_SEQ_FLOOR: return 0.0 # containment is a meaningful rename signal on its own (e.g. auth -> authentication), # so we lift it above the threshold floor when one basename fully contains the other, # with the length-ratio gating how confident we are contained = 0.0 if basename_contained: length_ratio = min(len(basename_a), len(basename_b)) / max(len(basename_a), len(basename_b)) contained = 0.5 + 0.5 * length_ratio # short-name floor: for very short basenames, only accept candidates with a strong token signal if min(len(basename_a), len(basename_b)) <= SHORT_NAME_FLOOR and basename_jaccard < 1.0: return 0.0 return max(basename_jaccard, seq, contained) def find_stale_reference_candidates(missing_name: str, existing_names: list[str], threshold: float | None = None) -> list[str]: """ :param missing_name: the unresolved reference target (without the ``mem:`` prefix). :param existing_names: the names of all currently existing memories. :param threshold: optional override for the minimum similarity required; defaults to :data:`NAME_SIMILARITY_THRESHOLD`. :return: existing memory names whose similarity to ``missing_name`` meets or exceeds ``threshold``, sorted in descending order of similarity (ties broken alphabetically) and capped at :data:`MAX_STALE_REFERENCE_CANDIDATES` entries to keep the output focused on the most plausible matches. """ cutoff = NAME_SIMILARITY_THRESHOLD if threshold is None else threshold scored: list[tuple[float, str]] = [] for existing in existing_names: score = compute_name_similarity(missing_name, existing) if score >= cutoff: scored.append((score, existing)) scored.sort(key=lambda pair: (-pair[0], pair[1])) return [name for _, name in scored[:MAX_STALE_REFERENCE_CANDIDATES]] def iter_referenced_names_in_content(content: str) -> Iterator[str]: """ :param content: arbitrary memory content :return: an iterator over the memory names appearing as ``mem:NAME`` references in ``content``; duplicate occurrences are yielded once each. """ # use the same boundary rule as MemoriesManager.rename_references_to_memory so the two stay consistent pattern = rf"(?<!{NAME_CHAR_CLASS}){re.escape(MEMORY_REF_PREFIX)}({NAME_CHAR_CLASS}+?)(?!{NAME_CHAR_CLASS})" for match in re.finditer(pattern, content): yield match.group(1) def find_bare_occurrences(content: str, name: str) -> int: """ :param content: arbitrary memory content :param name: a memory name to look for :return: the count of bare (i.e. not already ``mem:``-prefixed) word-boundary-anchored occurrences of ``name`` in ``content``. The match must not be preceded by ``mem:`` and must not be embedded within a longer memory-name-like run of characters. """ pattern = ( rf"(?<!{re.escape(MEMORY_REF_PREFIX)})" rf"(?<!{NAME_CHAR_CLASS})" rf"{re.escape(name)}" rf"(?!{NAME_CHAR_CLASS})" ) return len(re.findall(pattern, content)) def add_bare_occurrences_prefix(content: str, name: str) -> tuple[str, int]: """ :param content: arbitrary memory content :param name: the memory name whose bare occurrences should be rewritten :return: ``(new_content, n_replacements)`` after prefixing each bare occurrence of ``name`` with ``mem:`` (using the same boundary rule as :func:`find_bare_occurrences`). """ pattern = ( rf"(?<!{re.escape(MEMORY_REF_PREFIX)})" rf"(?<!{NAME_CHAR_CLASS})" rf"{re.escape(name)}" rf"(?!{NAME_CHAR_CLASS})" ) replacement = MEMORY_REF_PREFIX + name return re.subn(pattern, lambda _m: replacement, content) def iter_long_bare_tokens(content: str) -> Iterator[tuple[str, int]]: """ :param content: arbitrary memory content :return: an iterator over ``(token, count)`` pairs for each distinct name-shaped token in ``content`` whose length meets :data:`HIGH_CONFIDENCE_NAME_LENGTH` and which is not preceded by ``mem:`` (those are already valid references). The boundaries follow :data:`NAME_CHAR_CLASS`, so embedded substrings of longer name-character runs are not matched. """ pattern = ( rf"(?<!{re.escape(MEMORY_REF_PREFIX)})" rf"(?<!{NAME_CHAR_CLASS})" rf"({NAME_CHAR_CLASS}{{{HIGH_CONFIDENCE_NAME_LENGTH},}})" rf"(?!{NAME_CHAR_CLASS})" ) counts: dict[str, int] = {} for match in re.finditer(pattern, content): token = match.group(1) counts[token] = counts.get(token, 0) + 1 return iter(counts.items()) def is_self_reference(source_memory: str, suspected_name: str) -> bool: """ :return: True iff ``suspected_name`` would refer to ``source_memory`` itself (including the case where ``suspected_name`` equals the basename of a topic-path source memory). """ if suspected_name == source_memory: return True source_basename = source_memory.rsplit("/", 1)[-1] return suspected_name == source_basename # --------------------------------------------------------------------------- # Report dataclasses # --------------------------------------------------------------------------- @dataclass(frozen=True) class StaleReference: """ A ``mem:NAME`` reference whose target memory does not exist. :ivar source_memory: the name of the memory whose content contains the broken reference. :ivar referenced_name: the name following ``mem:`` that did not resolve to an existing memory. :ivar candidates: existing memory names proposed as likely intended targets, ranked by decreasing similarity. May be empty if no candidate exceeded the similarity threshold. :ivar source_is_read_only: whether the source memory is read-only. """ source_memory: str referenced_name: str candidates: list[str] source_is_read_only: bool @dataclass(frozen=True) class UnmarkedReferenceWarning: """ A bare occurrence in a memory's content that looks like a forgotten reference to an existing memory. Two flavours of finding share this class: * **exact match** — the bare text equals an existing memory name verbatim (``actual_token`` either equals ``suspected_name`` or is left empty). * **fuzzy near-miss** — the bare text does not equal any existing memory name, but a long, distinctive token in the body similarity-matches a high-confidence existing memory name (``actual_token`` is the bare text actually found, distinct from ``suspected_name``). Such findings are reported but **not** rewritten by :meth:`MemoryReferenceAnalyzer.auto_prefix_bare_references`, since they would require substring substitution rather than a prefix addition. :ivar source_memory: the name of the memory whose content contains the bare occurrence. :ivar suspected_name: the existing memory name proposed as the intended target. :ivar occurrences: the number of occurrences of ``actual_token`` in the source memory's content. :ivar is_high_confidence: True when ``suspected_name`` contains a ``/`` separator or exceeds the configured length threshold; such names are unlikely to coincide with ordinary prose. False otherwise (a low-co - src/serena/olb/olb_jvm_backend.py (2963 bytes)
import logging import math import shutil import subprocess from typing import TYPE_CHECKING from overrides import override from serena.jetbrains import launch_coordinator from serena.jetbrains.jetbrains_backend import JetBrainsLanguageBackend from serena.language_backend import BuiltinLanguageBackend from solidlsp.util import subprocess_util if TYPE_CHECKING: from serena.agent import SerenaAgent from serena.project import Project from serena.repl.facade import ApiScope, Facade log = logging.getLogger(__name__) class OraiosJVMLanguageBackend(JetBrainsLanguageBackend): """ The Oraios Language Backend (OLB) for JVM-based languages (Java, Kotlin, Groovy). This is a drop-in replacement for the JetBrains backend. """ _OLB_LANGUAGE_BACKEND = "jvm" """the id of the language backend in the olb CLI.""" def __init__(self): super().__init__(key=BuiltinLanguageBackend.OLB_JVM.value) def _create_ide_facade(self, agent: "SerenaAgent", api_scope: "ApiScope") -> "Facade": facade = super()._create_ide_facade(agent, api_scope) facade.set_name("ide") facade.set_description(facade.description.replace("JetBrains", "Oraios")) return facade def is_jetbrains(self): # TODO: For the time being, this backend shall be treated the same as the JetBrains backend. # Ultimately, we'll want to remove this method altogether. return True @staticmethod def _check_olb_installed(): """Checks whether the Oraios Language Backend (olb) CLI tool is available, raising an exception if not.""" if shutil.which("olb") is None: raise Exception( "The Oraios Language Backend CLI (olb) was not found on the PATH. " "Install it via `uv tool install olb-cli` and then install the JVM language backend via `olb install jvm`." ) def _init_project_ide_launch(self, agent: "SerenaAgent") -> None: self._check_olb_installed() project = agent.get_active_project_or_raise() launch_command = ["olb", "start", self._OLB_LANGUAGE_BACKEND] launch_coordinator.launch_and_wait_for_plugin_server(project, launch_command) @override def shutdown_active_project(self, project: "Project", timeout: float) -> None: # stop the project's IDE instance command = ["olb", "stop", "--lb", self._OLB_LANGUAGE_BACKEND, project.project_root] try: result = subprocess_util.subprocess_run(command, timeout=math.ceil(timeout)) except (OSError, subprocess.TimeoutExpired) as e: log.warning("Failed to stop the IDE instance for project %s: %s", project.project_name, e) return if result.returncode != 0: # e.g. no instance was running (any more) log.info("The IDE instance for project %s was not stopped: %s", project.project_name, (result.stderr or result.stdout).strip()) - src/serena/project_server.py (12365 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import json import logging import pickle import secrets import threading from typing import TYPE_CHECKING, Any import requests as requests_lib from flask import Flask, Response, abort, request from pydantic import BaseModel from sensai.util.logging import LogTime from serena.config.serena_config import SerenaConfig from serena.constants import SerenaPorts from serena.language_backend import BuiltinLanguageBackend if TYPE_CHECKING: from serena.project import Project log = logging.getLogger(__name__) # disable Werkzeug's logging to avoid cluttering the output logging.getLogger("werkzeug").setLevel(logging.WARNING) class QueryProjectRequest(BaseModel): """ Request model for the /query_project endpoint, matching the interface of :class:`~serena.tools.query_project_tools.QueryProjectTool`. """ project_name: str tool_name: str tool_params_json: str class CallFacadeMethodRequest(BaseModel): """ Request model for the /call_facade_method endpoint: the execution of a REPL facade method in the context of a project. """ project_name: str facade_name: str method_name: str args: list[Any] kwargs: dict[str, Any] class ProjectServer: """ A lightweight Flask server that exposes a SerenaAgent's project querying capabilities via HTTP, using the LSP language server backend for symbolic retrieval. Projects are loaded on demand when a query is made for them, and cached in memory for subsequent queries. The server instantiates a :class:`SerenaAgent` with default options and provides a ``/query_project`` endpoint whose interface matches :class:`~serena.tools.query_project_tools.QueryProjectTool`. """ PORT = SerenaPorts.PROJECT_SERVER_PORT def __init__(self, host: str = "127.0.0.1", port: int | None = None) -> None: """ :param host: the host address to listen on. :param port: the port to listen on; if None, use default """ from serena.agent import SerenaAgent if port is None: port = self.PORT serena_config = SerenaConfig.from_config_file().with_headless_mode_overrides() serena_config.set_builtin_language_backend(BuiltinLanguageBackend.LSP) self._agent = SerenaAgent(serena_config=serena_config) self._loaded_projects_by_root: dict[str, "Project"] = {} self._project_load_locks_by_root: dict[str, threading.Lock] = {} self._active_project_lock = threading.Lock() self._loaded_projects_lock = threading.Lock() self._port = port self._host = host # create the Flask application, limiting trusted hosts for the case where the server is running on localhost self._app = Flask(__name__) local_hosts = ["localhost", "127.0.0.1"] if self._host in local_hosts: self._app.config["TRUSTED_HOSTS"] = local_hosts self._setup_routes() def get_serena_config(self) -> SerenaConfig: return self._agent.serena_config def get_auth_secret(self) -> str: """Returns the authentication secret used by the server.""" return self._agent.serena_config.auth_secret def _setup_routes(self) -> None: @self._app.before_request def authenticate() -> None: # authenticate every request before parsing input or accessing projects secret = self.get_auth_secret() provided = request.headers.get("Authorization", "") if not secret or not secrets.compare_digest(provided.encode("utf-8"), f"Bearer {secret}".encode()): abort(401) @self._app.route("/heartbeat", methods=["GET"]) def heartbeat() -> dict[str, str]: return {"status": "alive"} @self._app.route("/query_project", methods=["POST"]) def query_project() -> str: query_request = QueryProjectRequest.model_validate(request.get_json()) return self._query_project(query_request) @self._app.route("/call_facade_method", methods=["POST"]) def call_facade_method() -> Response: call_request = CallFacadeMethodRequest.model_validate(request.get_json()) try: result = self._call_facade_method(call_request) except Exception as e: # report the error to the client (which raises it in the REPL) instead of a generic server error page log.warning("Facade method call failed: %s", e) return Response(f"{type(e).__name__}: {e}", status=400, mimetype="text/plain") # NOTE: the result is pickled; the client (a Serena instance on the same machine) unpickles it return Response(pickle.dumps(result), mimetype="application/octet-stream") def _get_project(self, project_root_or_name: str) -> "Project": """Gets the project with the given name, loading it if necessary.""" serena_config = self._agent.serena_config registered_project = serena_config.get_registered_project(project_root_or_name) if registered_project is None: raise ValueError(f"Project '{project_root_or_name}' is not registered with Serena.") key = str(registered_project.project_root) # find or publish the per-project load lock while holding the shared dictionaries with self._loaded_projects_lock: project = self._loaded_projects_by_root.get(key) if project is not None: return project project_load_lock = self._project_load_locks_by_root.get(key) if project_load_lock is None: project_load_lock = threading.Lock() self._project_load_locks_by_root[key] = project_load_lock # initialize only this project; another project's cached lookup or cold load can proceed with project_load_lock: with self._loaded_projects_lock: project = self._loaded_projects_by_root.get(key) if project is not None: return project with LogTime(f"Loading project '{project_root_or_name}'"): project = registered_project.get_project_instance(serena_config) project.create_language_server_manager() with self._loaded_projects_lock: self._loaded_projects_by_root[key] = project return project def _query_project(self, req: QueryProjectRequest) -> str: """Handle a /query_project request by invoking the agent on the specified project and tool. The active project is process-wide state, whereas ``apply_ex`` runs the tool on the agent's task executor thread. Without the lock, a second request entering ``active_project_context`` while the first request's tool is still executing would redirect that tool to the wrong project (and restore the wrong project afterwards). """ project = self._get_project(req.project_name) with self._active_project_lock, self._agent.active_project_context(project): tool = self._agent.get_tool_by_name(req.tool_name) if not tool.is_readonly(): raise ValueError(f"Tool '{req.tool_name}' is not read-only and cannot be executed via the query_project route") params = json.loads(req.tool_params_json) return tool.apply_ex(**params) def _call_facade_method(self, req: CallFacadeMethodRequest) -> Any: """ Handles a /call_facade_method request by executing the facade method on the agent's REPL facades in the context of the specified project (see `_query_project` regarding the lock). """ project = self._get_project(req.project_name) with self._active_project_lock, self._agent.active_project_context(project): facade = self._agent.get_repl().entrypoint.get_facade_(req.facade_name) method = facade.get_method(req.method_name) return self._agent.execute_task(lambda: method(*req.args, **req.kwargs)) def run(self) -> None: """ Run the server on the given host and port. """ from flask import cli # suppress the default Flask startup banner # ty cannot model reassigning a third-party module's function attribute (it rejects any # replacement, even one with an identical signature), so the monkeypatch is suppressed here cli.show_server_banner = lambda *args, **kwargs: None # ty: ignore[invalid-assignment] self._app.run(host=self._host, port=self._port, debug=False, use_reloader=False, threaded=True) class ProjectServerClient: """Client for interacting with a running :class:`ProjectServer`. Upon instantiation, the client verifies that the server is reachable by sending a heartbeat request. If the server is not running, a :class:`ConnectionError` is raised. """ def __init__(self, serena_config: SerenaConfig, host: str = "127.0.0.1", port: int | None = None) -> None: """ :param host: the host address of the project server. :param port: the port of the project server; if None, use default. :param auth_secret: the shared authentication secret; defaults to the secret in Serena's configuration. :raises ConnectionError: if the project server is not reachable. """ if port is None: port = ProjectServer.PORT self._base_url = f"http://{host}:{port}" self._timeout = serena_config.tool_timeout - 1 auth_secret = serena_config.auth_secret self._headers = {"Authorization": f"Bearer {auth_secret}"} # verify that the server is running try: response = requests_lib.get(f"{self._base_url}/heartbeat", headers=self._headers, timeout=5) response.raise_for_status() except requests_lib.ConnectionError: raise ConnectionError(f"ProjectServer is not reachable at {self._base_url}. Make sure the server is running.") except requests_lib.RequestException as e: raise ConnectionError(f"ProjectServer health check failed: {e}") def query_project(self, project_name: str, tool_name: str, tool_params_json: str) -> str: """ Query a project by executing a Serena tool in its context. The interface matches :meth:`QueryProjectTool.apply <serena.tools.query_project_tools.QueryProjectTool.apply>`. :param project_name: the name of the project to query. :param tool_name: the name of the tool to execute. The tool must be read-only. :param tool_params_json: the parameters to pass to the tool, encoded as a JSON string. :return: the tool's result as a string. """ payload = QueryProjectRequest( project_name=project_name, tool_name=tool_name, tool_params_json=tool_params_json, ).model_dump() response = requests_lib.post(f"{self._base_url}/query_project", json=payload, headers=self._headers, timeout=self._timeout) response.raise_for_status() return response.text def call_facade_method(self, project_name: str, facade_name: str, method_name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: """ Executes a (read-only) REPL facade method in the context of a project. :param project_name: the name of the project to query :param facade_name: the facade's name :param method_name: the method's name :param args: the positional arguments (JSON-serialisable) :param kwargs: the keyword arguments (JSON-serialisable) :return: the method's result, as returned by the server (unpickled; the server is a trusted local process) """ payload = CallFacadeMethodRequest( project_name=project_name, facade_name=facade_name, method_name=method_name, args=args, kwargs=kwargs ).model_dump() response = requests_lib.post(f"{self._base_url}/call_facade_method", json=payload, headers=self._headers, timeout=self._timeout) if not response.ok: raise ValueError(f"Project server error ({response.status_code}): {response.text[:2000]}") return pickle.loads(response.content) - src/serena/project.py (40442 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import logging import os import threading from collections.abc import Callable from pathlib import Path from typing import TYPE_CHECKING, Any, Optional import pathspec from sensai.util.logging import LogTime from sensai.util.string import TextBuilder, ToStringMixin from serena.config.serena_config import ( ProjectConfig, ProjectConfigAutoGenerationMode, SerenaConfig, ) from serena.language_backend import LanguageBackend from serena.ls_manager import LanguageServerFactory, LanguageServerManager from serena.memories.memory_manager import MemoryManager from serena.util.file_proxy import FileCollection, FileProxy from serena.util.file_system import GitignoreParser, ScanResult, dir_entry_from_path, match_path, walk_dir_entries from serena.util.text_utils import MatchedConsecutiveLines, search_files from solidlsp import SolidLanguageServer from solidlsp.ls_config import LanguageServerIdLike if TYPE_CHECKING: from serena.agent import SerenaAgent log = logging.getLogger(__name__) def merge_ls_specific_settings(global_settings: dict, project_settings: dict) -> dict: """ Merge project-level LS-specific settings on top of the global ones, language block by language block. The merge is per language and not per key: a project-level block for a language replaces the global block for that language entirely, so keys the project block omits silently fall back to the language server's own defaults. That is easy to misread as a small override, so any global key hidden this way is logged. :param global_settings: the ``ls_specific_settings`` from the global configuration :param project_settings: the ``ls_specific_settings`` from the project configuration :return: a new dict containing the merged settings """ merged_settings = dict(global_settings) for ls_key, project_ls_settings in project_settings.items(): global_ls_settings = global_settings.get(ls_key) if isinstance(global_ls_settings, dict) and isinstance(project_ls_settings, dict): hidden_keys = sorted(set(global_ls_settings) - set(project_ls_settings)) if hidden_keys: log.warning( f"Project-level settings for language server '{ls_key}' replace the global settings for the same " f"language and hide: {', '.join(hidden_keys)}. Copy the global values into the project " f"configuration to keep them." ) merged_settings[ls_key] = project_ls_settings return merged_settings class Project(ToStringMixin): def __init__( self, *, project_root: str, project_config: ProjectConfig, serena_config: SerenaConfig, is_newly_created: bool = False, ): """ :param project_root: path to the project's root folder; it is assumed to be fully resolved :param project_config: the project's configuration :param serena_config: the global Serena configuration :param is_newly_created: whether the project was newly created """ assert serena_config is not None self.project_root = project_root self.project_config = project_config self.serena_config = serena_config self._serena_data_folder = serena_config.get_project_serena_folder(self.project_root) log.info("Serena project data folder: %s", self._serena_data_folder) read_only_memory_patterns = serena_config.read_only_memory_patterns + project_config.read_only_memory_patterns ignored_memory_patterns = serena_config.ignored_memory_patterns + project_config.ignored_memory_patterns self.memory_manager = MemoryManager( self._serena_data_folder, read_only_memory_patterns=read_only_memory_patterns, ignored_memory_patterns=ignored_memory_patterns, ) # resolve line ending (project -> global) self.line_ending = project_config.line_ending or serena_config.line_ending self.language_server_manager: LanguageServerManager | None = None self._language_server_manager_init_error: Exception | None = None self.is_newly_created = is_newly_created self._agent: Optional["SerenaAgent"] = None # create .gitignore file in the project's Serena data folder if not yet present serena_data_gitignore_path = os.path.join(self._serena_data_folder, ".gitignore") if not os.path.exists(serena_data_gitignore_path): os.makedirs(os.path.dirname(serena_data_gitignore_path), exist_ok=True) log.info(f"Creating .gitignore file in {serena_data_gitignore_path}") with open(serena_data_gitignore_path, "w", encoding="utf-8") as f: f.write(f"/{SolidLanguageServer.CACHE_FOLDER_NAME}\n") f.write(f"/{ProjectConfig.SERENA_LOCAL_PROJECT_FILE}\n") # prepare ignore spec asynchronously, ensuring immediate project activation. self.__ignored_patterns: list[str] | None = None self.__ignore_spec: pathspec.PathSpec | None = None self._ignore_spec_available = threading.Event() threading.Thread(name=f"gather-ignorespec[{self.project_config.project_name}]", target=self._gather_ignorespec, daemon=True).start() def _gather_ignorespec(self) -> None: with LogTime(f"Gathering ignore spec for project {self.project_config.project_name}", logger=log): # gather ignored paths from the global configuration, project configuration, and gitignore files try: # extend the ignored paths from the global config with ".git" to ensure that .git folders (anywhere in the project) # are always ignored global_ignored_paths = [".git"] + self.serena_config.ignored_paths # Only configured paths need separator normalization; gitignore patterns already use POSIX syntax and escapes. configured_patterns = [ pattern.replace(os.path.sep, "/") for pattern in [*global_ignored_paths, *self.project_config.ignored_paths] ] ignored_patterns = list(configured_patterns) if len(global_ignored_paths) > 0: log.info(f"Using {len(global_ignored_paths)} ignored paths from the global configuration.") log.debug(f"Global ignored paths: {list(global_ignored_paths)}") if len(self.project_config.ignored_paths) > 0: log.info(f"Using {len(self.project_config.ignored_paths)} ignored paths from the project configuration.") log.debug(f"Project ignored paths: {self.project_config.ignored_paths}") log.debug(f"Combined ignored patterns: {ignored_patterns}") if self.project_config.ignore_all_files_in_gitignore: # Directories excluded by the configured patterns are never entered by the .gitignore # discovery walk (the configured patterns have the final say, see below, so nested # .gitignore rules under such a directory could never change a verdict anyway). prune_spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, configured_patterns) gitignore_parser = GitignoreParser(self.project_root, prune_spec=prune_spec) for spec in gitignore_parser.get_ignore_specs(): log.debug(f"Adding {len(spec.patterns)} patterns from {spec.file_path} to the ignored paths.") ignored_patterns.extend(spec.patterns) # Explicit configuration has the final say, in its configured order: re-appending it after # the .gitignore patterns means neither a .gitignore negation can re-include a configured # exclusion nor a .gitignore rule can narrow a configured re-inclusion. This is what keeps # discovery pruning (by configuration) and the final verdict consistent by construction. ignored_patterns.extend(configured_patterns) self.__ignored_patterns = ignored_patterns # Set up the pathspec matcher for the ignored paths log.debug(f"Processing {len(ignored_patterns)} ignored paths") self.__ignore_spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern, ignored_patterns) except Exception as e: log.error(f"Error while gathering ignore spec for project {self.project_config.project_name}: {e}", exc_info=e) self._ignore_spec_available.set() def _tostring_includes(self) -> list[str]: return [] def _tostring_additional_entries(self) -> dict[str, Any]: return {"root": self.project_root, "name": self.project_name} def set_agent(self, agent: "SerenaAgent") -> None: self._agent = agent @property def project_name(self) -> str: return self.project_config.project_name @property def language_backend(self) -> LanguageBackend: # The backend configuration is fundamentally owned by the agent, so it takes # precedence. (Note: The agent does not necessarily honour the project's choice, # as it may be invalid.) if self._agent is not None: return self._agent.get_language_backend() else: return self.serena_config.determine_language_backend(self.project_config) @classmethod def load( cls, project_root: str | Path, serena_config: "SerenaConfig", autogen: ProjectConfigAutoGenerationMode = ProjectConfigAutoGenerationMode.SYNCHRONOUS, ) -> "Project": assert serena_config is not None project_root = Path(project_root).resolve() if not project_root.exists(): raise FileNotFoundError(f"Project root not found: {project_root}") project_config = ProjectConfig.load(project_root, serena_config=serena_config, autogen=autogen) return Project(project_root=str(project_root), project_config=project_config, serena_config=serena_config) def save_config(self) -> None: """ Saves the current project configuration to disk. """ self.project_config.save(self.path_to_project_yml()) def path_to_serena_data_folder(self) -> str: return self._serena_data_folder def path_to_project_yml(self) -> str: return self.serena_config.get_project_yml_location(self.project_root) def is_trusted(self) -> bool: """ Checks whether the project is trusted, based on the global configuration. :return: True if the project is trusted, False otherwise """ return self.serena_config.is_trusted_project_path(self.project_root) def read_file(self, relative_path: str) -> str: """ Reads a project file. :param relative_path: the path to the file relative to the project root or an external path token like "<ext:FileUtil.class|472e0a13>" :return: the content of the file """ return FileProxy.from_project_relative_path(self, relative_path).get_contents() @property def _ignore_spec(self) -> pathspec.PathSpec: """ :return: the pathspec matcher for the paths that were configured to be ignored, either explicitly or implicitly through .gitignore files, with explicit configuration taking precedence. """ if not self._ignore_spec_available.is_set(): log.info("Waiting for ignore spec to become available ...") self._ignore_spec_available.wait() if self.__ignore_spec is not None: log.info("Ignore spec is now available for project; proceeding") if self.__ignore_spec is None: raise ValueError( "The ignore spec could not be computed; please check the log for errors and report here: https://github.com/oraios/serena/issues" ) return self.__ignore_spec @property def _ignored_patterns(self) -> list[str]: """ :return: the list of ignored path patterns """ if not self._ignore_spec_available.is_set(): log.info("Waiting for ignored patterns to become available ...") self._ignore_spec_available.wait() if self.__ignored_patterns is not None: log.info("Ignored patterns are now available for project; proceeding") if self.__ignored_patterns is None: raise ValueError( "The ignored patterns could not be computed; please check the log for errors and report here: https://github.com/oraios/serena/issues" ) return self.__ignored_patterns def _is_ignored_relative_path( self, relative_path: str | Path, ignore_non_source_files: bool = True, is_file: bool | None = None ) -> bool: """ Determine whether a path should be ignored based on file type and ignore patterns. Returns False for non-existent paths since they cannot be matched by ignore patterns. :param relative_path: Relative path to check :param ignore_non_source_files: whether files that are not source files (according to the file masks determined by the project's programming language) shall be ignored :param is_file: whether the path exists and is a file, for callers that already know :return: whether the path should be ignored """ # special case, never ignore the project root itself # If the user ignores hidden files, "." might match against the corresponding PathSpec pattern. # The empty string also points to the project root and should never be ignored. if str(relative_path) in [".", ""]: return False abs_path = os.path.join(self.project_root, relative_path) if is_file is None: if not os.path.exists(abs_path): log.debug(f"Path {abs_path} does not exist, skipping ignore check") return False # check code file restriction (depending on backend) if ignore_non_source_files: if is_file is None: is_file = os.path.isfile(abs_path) if is_file: # non-source files are ignored if not self.language_backend.is_source_file(abs_path, self): return True is_dir = None if is_file is None else not is_file return match_path(str(relative_path), self._ignore_spec, root_path=self.project_root, is_dir=is_dir) def is_ignored_path(self, path: str | Path, ignore_non_source_files: bool = False, is_file: bool | None = None) -> bool: """ Checks whether the given path is ignored :param path: the path to check, can be - src/serena/prompt_factory.py (618 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later import os from serena.config.serena_config import SerenaPaths from serena.constants import PROMPT_TEMPLATES_DIR_INTERNAL from serena.generated.generated_prompt_factory import PromptFactory class SerenaPromptFactory(PromptFactory): """ A class for retrieving and rendering prompt templates and prompt lists. """ def __init__(self) -> None: user_templates_dir = SerenaPaths().user_prompt_templates_dir os.makedirs(user_templates_dir, exist_ok=True) super().__init__(prompts_dir=[user_templates_dir, PROMPT_TEMPLATES_DIR_INTERNAL]) - src/serena/repl/api/cfg_api.py (1581 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of operations concerning Serena's configuration and session state. """ from typing import TYPE_CHECKING from serena.tools import GetCurrentConfigTool, OpenDashboardTool from ..facade import FacadeApi, facade_method if TYPE_CHECKING: from serena.agent import SerenaAgent class ConfigApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__(agent, name="cfg", description="Serena's configuration and session state (incl. the dashboard)") @facade_method(corresponding_tool=GetCurrentConfigTool) def get_current_config(self) -> str: """ Provides the current configuration of the agent, including the active and available projects, tools, contexts, and modes. :return: the configuration overview """ return self._agent.get_current_config_overview() @facade_method(corresponding_tool=OpenDashboardTool) def open_dashboard(self) -> str: """ Opens the Serena web dashboard in the default web browser. The dashboard provides logs, session information, and tool usage statistics. :return: a message indicating whether the dashboard could be opened """ if self._agent.open_dashboard(): return f"Serena web dashboard has been opened in the user's default web browser: {self._agent.get_dashboard_url()}" else: return f"Serena web dashboard could not be opened automatically; tell the user to open it via {self._agent.get_dashboard_url()}" - src/serena/repl/api/edit_api.py (15595 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of editing operations, which are independent of the language backend. """ from typing import TYPE_CHECKING, Literal from serena.code_editor import EditedFileContext from serena.tools import ( DeleteLinesTool, InsertAfterSymbolTool, InsertAtLineTool, InsertBeforeSymbolTool, ReplaceContentTool, ReplaceInFilesTool, ReplaceLinesTool, ReplaceSymbolBodyTool, ) from serena.util.text_utils import ContentReplacer, MultiFileReplacement, ReplacementOccurrence, ReplacementRejectedError from ..facade import SUCCESS_RESULT, FacadeApi, ReferencedType, facade_method from ..representable import Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class ReplacementPreview(RepresentableViaRenderer): """ The prospective changes of a multi-file replacement (nothing has been modified). Each entry of `occurrences` (`ReplacementOccurrence`) has an `occurrence_id` (to be passed to `replace_in_files` in order to apply exactly that occurrence), `relative_path`, `start_line`, `end_line`, `matched_text`, `replacement` and `is_ambiguous`. """ def __init__(self, replacement: MultiFileReplacement, renderer: "ReplacementPreviewRenderer"): """ :param replacement: the replacement :param renderer: the renderer to use for representing the preview """ super().__init__(renderer) self.replacement_ = replacement @property def occurrences(self) -> list[ReplacementOccurrence]: return self.replacement_.occurrences @property def affected_files(self) -> list[str]: return self.replacement_.affected_files class ReplacementPreviewRenderer(Renderer[ReplacementPreview]): """ Renders the listing of prospective changes (minimal line diffs with occurrence ids), subject to the length limit. """ def __init__(self, agent: "SerenaAgent", max_answer_chars: int, dry_run: bool): """ :param agent: the agent :param max_answer_chars: the maximum number of characters; -1 for the configured default :param dry_run: whether the listing is the result of a dry run (adding instructions on how to proceed) """ super().__init__(agent, max_answer_chars) self._dry_run = dry_run def render(self, obj: ReplacementPreview) -> str: return obj.replacement_.render_listing(self._get_max_answer_chars(), dry_run=self._dry_run) class EditApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__( agent, name="edit", description="modifying content within existing files (independent of the language backend)", types=[ ReferencedType( ReplacementOccurrence, members=["occurrence_id", "relative_path", "start_line", "end_line", "matched_text", "replacement", "is_ambiguous"], ), ], ) # file-level operations @facade_method(can_edit=True, corresponding_tool=ReplaceContentTool) def replace_content( self, relative_path: str, needle: str, repl: str, mode: Literal["literal", "regex"], allow_multiple_occurrences: bool = False, ) -> str: r""" Replaces one or more occurrences of a given pattern in a file with new content. VERY IMPORTANT: The "regex" mode allows very large sections of code to be replaced WITHOUT quoting them fully: use a needle of the form "beginning.*?end-of-text-to-be-replaced" with wildcards instead of pasting the exact original text — shorter, cheaper, and you cannot make mistakes, because an ambiguous match returns an error you can refine, so wildcards are safe. Prefer regex mode with suitable wildcards for long multi-line replacements; use the symbol-level editors when replacing a whole method/class. :param relative_path: the relative path to the file :param needle: the string or regex pattern to search for. If `mode` is "literal", this string will be matched exactly. If `mode` is "regex", this string will be treated as a regular expression (syntax of Python's `re` module, with flags DOTALL and MULTILINE enabled). :param repl: the replacement string (verbatim). If mode is "regex", the string can contain backreferences to matched groups in the needle regex, specified using the syntax $!1, $!2, etc. for groups 1, 2, etc. :param mode: either "literal" or "regex", specifying how the `needle` parameter is to be interpreted. :param allow_multiple_occurrences: whether to allow matching and replacing multiple occurrences. If false and multiple occurrences are found, an error will be raised :return: a success message """ self._get_project().validate_relative_path(relative_path) with EditedFileContext(relative_path, self._create_code_editor()) as context: replacer = ContentReplacer(mode=mode, allow_multiple_occurrences=allow_multiple_occurrences) context.set_updated_content(replacer.replace(context.get_original_content(), needle, repl)) return SUCCESS_RESULT @facade_method(can_edit=True, corresponding_tool=ReplaceInFilesTool) def replace_in_files( self, needle: str, repl: str, mode: Literal["literal", "regex"], relative_path: str = "", paths_include_glob: str = "", paths_exclude_glob: str = "", dry_run: bool = False, occurrence_ids: list[str] | None = None, expected_count: int = -1, max_answer_chars: int = -1, ) -> ReplacementPreview | str: r""" Replaces occurrences of a pattern across multiple files in ONE call. This is the preferred operation for repeated small edits (renames, import swaps, annotation changes, path prefixes) spanning several files or many places in one file: one call with a SHORT pattern replaces many single-file replacements with long disambiguating needles. Recommended protocol whenever there is ANY risk of unintended replacements: 1. Call with dry_run=True: every prospective change is returned as a minimal line diff with an occurrence id; nothing is modified. 2. Call again with dry_run=False, passing the ids you want in occurrence_ids (omit it to apply all). You pick the desired replacements from the list - no counting, no needle-crafting. For clearly unambiguous bulk replacements you may skip the dry run; pass expected_count as a guard. If the actual number of matches differs, NOTHING is changed and an error containing the prospective changes is raised, so a failed guard costs one call and gives you the dry-run output to select from. :param needle: the string (mode "literal") or regular expression (mode "regex"; Python `re` syntax with DOTALL and MULTILINE) to search for :param repl: the replacement string. In regex mode, backreferences to matched groups can be specified as $!1, $!2, etc. :param mode: either "literal" or "regex", specifying how `needle` is to be interpreted :param relative_path: only consider this file or directory (default: the whole project) :param paths_include_glob: optional glob (relative to the project root, e.g. "src/**/*.java") restricting which files are considered :param paths_exclude_glob: optional glob of files to exclude; takes precedence over the include glob :param dry_run: if True, do not modify anything; return the prospective changes with occurrence ids :param occurrence_ids: optional list of occurrence ids (obtained from a dry run) to which the replacement is restricted; if any id is unknown or stale, NOTHING is changed. If omitted, all occurrences are replaced. :param expected_count: optional guard for calls without occurrence_ids: the number of occurrences you expect to be replaced. If the actual count differs, nothing is changed and an error containing the prospective changes is raised. -1 disables the guard. :return: in a dry run, the prospective changes (`ReplacementPreview`); otherwise a summary of the applied replacements """ replacement = MultiFileReplacement( self._get_project(), needle, repl, mode, relative_path=relative_path, paths_include_glob=paths_include_glob, paths_exclude_glob=paths_exclude_glob, ) if dry_run: return ReplacementPreview(replacement, ReplacementPreviewRenderer(self._agent, max_answer_chars, dry_run=True)) # select the occurrences to replace try: if occurrence_ids is not None: occurrences = replacement.select(occurrence_ids) else: occurrences = replacement.select_all_guarded(expected_count) except ReplacementRejectedError as e: message = str(e) if e.show_prospective_changes: preview = ReplacementPreview(replacement, ReplacementPreviewRenderer(self._agent, max_answer_chars, dry_run=False)) message += "\n" + preview.represent() raise ValueError(message) from e return replacement.apply(self._create_code_editor(), occurrences).to_display_string() # line-level operations @facade_method(optional=True, can_edit=True, corresponding_tool=DeleteLinesTool) def delete_lines(self, relative_path: str, start_line: int, end_line: int) -> str: """ Deletes the given lines in the file. Requires that the same range of lines was previously read to verify correctness of the operation. :param relative_path: the relative path to the file :param start_line: the 0-based index of the first line to be deleted :param end_line: the 0-based index of the last line to be deleted :return: a success message """ self._get_project().validate_relative_path(relative_path) self._create_code_editor().delete_lines(relative_path, start_line, end_line) return SUCCESS_RESULT @facade_method(optional=True, can_edit=True, corresponding_tool=ReplaceLinesTool) def replace_lines(self, relative_path: str, start_line: int, end_line: int, content: str) -> str: """ Replaces the given range of lines in the given file. Requires that the same range of lines was previously read to verify correctness of the operation. :param relative_path: the relative path to the file :param start_line: the 0-based index of the first line to be replaced :param end_line: the 0-based index of the last line to be replaced :param content: the content to insert :return: a success message """ self._get_project().validate_relative_path(relative_path) code_editor = self._create_code_editor() code_editor.replace_lines(relative_path, start_line, end_line, self._normalize_inserted_content(content)) return SUCCESS_RESULT @facade_method(optional=True, can_edit=True, corresponding_tool=InsertAtLineTool) def insert_at_line(self, relative_path: str, line: int, content: str) -> str: """ Inserts the given content at the given line in the file, pushing existing content of the line down. In general, symbolic insert operations like insert_after_symbol or insert_before_symbol should be preferred if you know which symbol you are looking for. However, this can also be useful for small targeted edits of the body of a longer symbol (without replacing the entire body). :param relative_path: the relative path to the file :param line: the 0-based index of the line to insert content at :param content: the content to be inserted :return: a success message """ self._get_project().validate_relative_path(relative_path) self._create_code_editor().insert_at_line(relative_path, line, self._normalize_inserted_content(content)) return SUCCESS_RESULT @staticmethod def _normalize_inserted_content(content: str) -> str: return content if content.endswith("\n") else content + "\n" # symbol-level operations @facade_method(can_edit=True, corresponding_tool=ReplaceSymbolBodyTool) def replace_symbol_body(self, name_path: str, relative_path: str, body: str) -> str: """ Replaces the body of the given symbol. IMPORTANT: Only replace symbol bodies if you have previously made a retrieval with include_body=True and thus know what constitutes the body! :param name_path: name path of the symbol whose body to replace :param relative_path: the relative path to the file containing the symbol :param body: the new symbol body. The symbol body is the definition of a symbol in the programming language, including e.g. the signature line for functions. Depending on the language, it may or may not include a preceding docstring or other preceding annotations. :return: a success message """ self._get_project().validate_relative_path(relative_path) self._create_code_editor().replace_body(name_path, relative_file_path=relative_path, body=body) return SUCCESS_RESULT @facade_method(can_edit=True, corresponding_tool=InsertAfterSymbolTool) def insert_after_symbol(self, name_path: str, relative_path: str, body: str) -> str: """ Inserts code after a class/method/function definition. Don't use this to insert after assignments (constants, fields). :param name_path: name path of the symbol after which to insert content :param relative_path: the relative path to the file containing the symbol :param body: the body/content to be inserted. The inserted code shall begin with the next line after the symbol. :return: a success message """ self._get_project().validate_relative_path(relative_path) self._create_code_editor().insert_after_symbol(name_path, relative_file_path=relative_path, body=body) return SUCCESS_RESULT @facade_method(can_edit=True, corresponding_tool=InsertBeforeSymbolTool) def insert_before_symbol(self, name_path: str, relative_path: str, body: str) -> str: """ Inserts the given content before the beginning of the definition of the given symbol (via the symbol's location). A typical use case is to insert a new class, function, method, field or variable assignment; or - src/serena/repl/api/ext_api.py (5464 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of access to external projects (projects other than the active one). """ from types import TracebackType from typing import TYPE_CHECKING from serena.jetbrains.jetbrains_plugin_client import JetBrainsPluginClientManager from serena.tools import ListQueryableProjectsTool, QueryProjectTool from ..external_project import ExternalProjectExecution from ..facade import FacadeApi, facade_method from ..representable import JsonObject, JsonObjectRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class ExternalProjectContextManager: """ A context manager (for use in a `with` statement) within which the facades operate on an external project (read-only): the external project is temporarily activated, and operations requiring language servers are executed in the project's server. Contexts cannot be nested. """ def __init__(self, agent: "SerenaAgent", project_name: str, read_only: bool) -> None: """ :param agent: the agent :param project_name: the name (or root path) of the registered external project :param read_only: whether the context is read-only """ self._agent = agent self._project_name = project_name self._active_project_context = None self._read_only = read_only def __enter__(self) -> None: entrypoint = self._agent.get_repl().entrypoint if entrypoint.get_external_project_() is not None: raise ValueError("External project contexts cannot be nested") # temporarily activate the external project registered_project = self._agent.serena_config.get_registered_project(self._project_name) if registered_project is None: raise ValueError(f"Project '{self._project_name}' is not registered and cannot be queried") project = registered_project.get_project_instance(self._agent.serena_config) self._active_project_context = self._agent.active_project_context(project) self._active_project_context.__enter__() # switch the facades to the external project entrypoint.set_external_project_(ExternalProjectExecution(registered_project.project_name, self._read_only, self._agent)) def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None: self._agent.get_repl().entrypoint.set_external_project_(None) assert self._active_project_context is not None self._active_project_context.__exit__(exc_type, exc_value, traceback) class ExternalProjectsApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__(agent, name="ext", description="access to external projects (projects other than the active one)") @facade_method(corresponding_tool=ListQueryableProjectsTool) def list_projects(self, symbol_access: bool = True) -> JsonObject: """ Lists the registered projects which can be queried. :param symbol_access: whether to list only projects for which symbol-level access is available :return: the project names mapped to their root directories """ registered_projects = self._agent.serena_config.projects if symbol_access and self._agent.get_language_backend().is_jetbrains(): # only projects with open IDE instances can be queried matched_clients = JetBrainsPluginClientManager().match_clients(registered_projects) relevant_projects = [mc.registered_project for mc in matched_clients] else: # all projects can be queried (the project server instantiates projects dynamically) relevant_projects = registered_projects result = {p.project_name: str(p.project_root) for p in relevant_projects} return JsonObject(result, JsonObjectRenderer(self._agent, -1)) @facade_method(corresponding_tool=QueryProjectTool) def read_project_context(self, project_name: str) -> ExternalProjectContextManager: """ Provides a context (for use in a `with` statement) within which all facades operate on the given external project instead of the active one, with read-only access. Example: `with s.ext.project_context("other"): result = s.lsp.find_symbol("Foo")` Results obtained within the context can be used after it (they are self-contained). :param project_name: the name (or root path) of the project, as listed by `list_projects` :return: the context manager """ return ExternalProjectContextManager(self._agent, project_name, read_only=True) @facade_method(optional=True) def project_context(self, project_name: str) -> ExternalProjectContextManager: """ Provides a context (for use in a `with` statement) within which all facades operate on the given external project instead of the active one (read and write operations are possible). Example: `with s.ext.project_context("other"): result = s.lsp.find_symbol("Foo")` Results obtained within the context can be used after it (they are self-contained). :param project_name: the name (or root path) of the project, as listed by `list_projects` :return: the context manager """ return ExternalProjectContextManager(self._agent, project_name, read_only=False) - src/serena/repl/api/fs_api.py (13689 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of operations on the project's files. """ from collections import defaultdict from fnmatch import fnmatch from pathlib import Path from typing import TYPE_CHECKING from serena.tools import CreateTextFileTool, FindFileTool, ListDirTool, ReadFileTool, SearchForPatternTool from serena.util.text_utils import MatchedConsecutiveLines from solidlsp.ls_utils import TextUtils from ..facade import FacadeApi, ReferencedType, facade_method from ..representable import Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class FileContent(RepresentableViaRenderer): """ The content of a file (or of a range of its lines): `text` (the joined lines) and `lines`. """ def __init__(self, lines: list[str], renderer: "FileContentRenderer"): """ :param lines: the lines (without line breaks) :param renderer: the renderer to use for representing the content """ super().__init__(renderer) self.lines = lines lines: list[str] @property def text(self) -> str: return "\n".join(self.lines) class FileContentRenderer(Renderer[FileContent]): def render(self, obj: FileContent) -> str: return self._limit_length(obj.text) class DirectoryListing(RepresentableViaRenderer): """ The entries of a directory: `dirs` and `files` (relative paths). """ def __init__(self, dirs: list[str], files: list[str], renderer: "DirectoryListingRenderer"): """ :param dirs: the relative paths of the directories :param files: the relative paths of the files :param renderer: the renderer to use for representing the listing """ super().__init__(renderer) self.dirs = dirs self.files = files dirs: list[str] files: list[str] class DirectoryListingRenderer(Renderer[DirectoryListing]): def render(self, obj: DirectoryListing) -> str: return self._limit_length(self._to_json({"dirs": obj.dirs, "files": obj.files})) class PatternMatches(RepresentableViaRenderer): """ The matches of a pattern search (`MatchedConsecutiveLines`). """ def __init__(self, matches: list[MatchedConsecutiveLines], renderer: "PatternMatchesRenderer"): """ :param matches: the matches :param renderer: the renderer to use for representing the matches """ super().__init__(renderer) self.matches = matches matches: list[MatchedConsecutiveLines] def __len__(self) -> int: return len(self.matches) def matches_by_file_(self) -> dict[str, list[MatchedConsecutiveLines]]: result: defaultdict[str, list[MatchedConsecutiveLines]] = defaultdict(list) for match in self.matches: assert match.source_file_path is not None result[match.source_file_path].append(match) return result class PatternMatchesRenderer(Renderer[PatternMatches]): """ Renders matches as a mapping from file paths to matched line blocks (with context), falling back to progressively shorter representations (first lines, truncated first lines, line numbers, per-file counts, a summary) if the length limit is exceeded. """ _TEXT_TRUNCATE = 60 def render(self, obj: PatternMatches) -> str: matches_by_file = obj.matches_by_file_() file_to_matches = {path: [m.to_display_string() for m in matches] for path, matches in matches_by_file.items()} # capture lightweight match data for shortening before serialization match_lines_by_file = { path: [{"line": m.matched_lines[0].line_number, "text": m.matched_lines[0].line_content.strip()} for m in matches] for path, matches in matches_by_file.items() } # shortened result closures, from least to most aggressive shortening def render_first_lines(truncate: bool) -> str: """Render each match's first line, either in full or truncated to a fixed length.""" def entry_text(text: str) -> str: if truncate and len(text) > self._TEXT_TRUNCATE: return text[: self._TEXT_TRUNCATE] + "..." return text compact = { path: [{"line": m["line"], "text": entry_text(str(m["text"]))} for m in lines] for path, lines in match_lines_by_file.items() } if truncate: header = ( f"Matched lines (text over {self._TEXT_TRUNCATE} chars is truncated, marked with a trailing '...'); " "use read_file with the line numbers for full content:" ) else: header = "Matched lines per file; use read_file with the line numbers for surrounding context:" return f"{header}\n{self._to_json(compact)}" def make_first_lines_full() -> str: return render_first_lines(truncate=False) def make_first_lines_truncated() -> str: return render_first_lines(truncate=True) def make_line_numbers_only() -> str: numbers = {path: [m["line"] for m in lines] for path, lines in match_lines_by_file.items()} return f"Match lines per file:\n{self._to_json(numbers)}" def make_per_file_counts() -> str: counts = {path: len(lines) for path, lines in match_lines_by_file.items()} return f"Match counts per file:\n{self._to_json(counts)}" def make_summary() -> str: return f"Found {len(obj)} matches in {len(match_lines_by_file)} files." return self._limit_length( self._to_json(file_to_matches), shortened_result_factories=[ make_first_lines_full, make_first_lines_truncated, make_line_numbers_only, make_per_file_counts, make_summary, ], ) class FsApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__( agent, name="fs", description="the project's files as units (as opposed to their content, see `edit`)", types=[ ReferencedType( MatchedConsecutiveLines, members=["source_file_path", "matched_lines", "start_line", "end_line", "to_display_string"] ), ], ) @facade_method(corresponding_tool=ReadFileTool) def read_file(self, relative_path: str, start_line: int = 0, end_line: int | None = None, max_answer_chars: int = -1) -> FileContent: """ Reads the given file or a range of its lines. :param relative_path: the relative path to the file to read :param start_line: the 0-based index of the first line to be retrieved, negative values count from the end of the file. :param end_line: the 0-based index of the last line to be retrieved (inclusive). If None, read until the end of the file. :return: the content """ project = self._get_project() project.validate_relative_path(relative_path) # read lines, using the same (LSP-compliant) notion of line breaks as the line-based editing operations lines = TextUtils.split_lines(project.read_file(relative_path)) start_idx, end_idx = TextUtils.line_slice_indices(start_line, end_line, len(lines)) lines = lines[start_idx:end_idx] return FileContent(lines, FileContentRenderer(self._agent, max_answer_chars)) @facade_method(can_edit=True, corresponding_tool=CreateTextFileTool) def create_text_file(self, relative_path: str, content: str) -> str: """ Writes a new file or overwrites an existing file with the given content. :param relative_path: the relative path to the file to create :param content: the (appropriately encoded) content to write to the file :return: a message indicating success """ project = self._get_project() project_root = Path(project.project_root) # the destination is resolved up front, so that the path which is validated is the path which is written abs_path = (project_root / relative_path).resolve() will_overwrite_existing = abs_path.exists() # validate the destination path; the validation resolves symlinks, thus covering abs_path project.validate_relative_path(relative_path) # write the file abs_path.parent.mkdir(parents=True, exist_ok=True) abs_path.write_text(content, encoding=project.project_config.encoding, newline=project.line_ending.newline_str) answer = f"File created: {relative_path}." if will_overwrite_existing: answer += " Overwrote existing file." return answer @facade_method(corresponding_tool=ListDirTool) def list_dir( self, relative_path: str, recursive: bool, skip_ignored_files: bool = False, max_answer_chars: int = -1 ) -> DirectoryListing: """ Lists files and directories in the given directory (optionally with recursion). :param relative_path: the relative path to the directory to list; pass "." to scan the project root :param recursive: whether to scan subdirectories recursively :param skip_ignored_files: whether to skip files and directories that are ignored :return: the listing """ project = self._get_project() if not project.relative_path_exists(relative_path): raise FileNotFoundError(f"Directory not found: {relative_path} (check if the path is correct relative to the project root)") project.validate_relative_path(relative_path) scan_result = project.scan_directory(relative_path, recursive=recursive, skip_ignored_paths=skip_ignored_files) return DirectoryListing(scan_result.directories, scan_result.files, DirectoryListingRenderer(self._agent, max_answer_chars)) @facade_method(corresponding_tool=FindFileTool) def find_file(self, file_mask: str, relative_path: str, skip_ignored_files: bool = False) -> list[str]: """ Finds files matching the given file mask within the given relative path. :param file_mask: the filename or file mask (using the wildcards * or ?) to search for :param relative_path: the relative path to the directory to search in; pass "." to scan the project root :param skip_ignored_files: whether to skip ignored files/directories :return: the relative paths of the matching files """ project = self._get_project() project.validate_relative_path(relative_path) scan_result = project.scan_directory( relative_path, recursive=True, skip_ignored_paths=skip_ignored_files, is_matching_file=lambda e: fnmatch(e.name, file_mask), ) return scan_result.files @facade_method(corresponding_tool=SearchForPatternTool) def search_for_pattern( self, substring_pattern: str, context_lines_before: int = 0, context_lines_after: int = 0, paths_include_glob: str = "", paths_exclude_glob: str = "", relative_path: str = "", restrict_search_to_code_files: bool = False, skip_ignored_files: bool = True, multiline: bool = True, max_answer_chars: int = -1, ) -> PatternMatches: """ Searches for a regex pattern across project files, returning whole matched lines (plus optional context). Prefer symbolic operations if you know which symbols you are looking for! :param substring_pattern: regular expression to search for. :param context_lines_before: number of context lines to include before each match. :param context_lines_after: number of context lines to include after each match. :param paths_include_glob: optional glob (relative to project root, e.g. ``"src/**/*.ts"``) restricting which files are searched. :param paths_exclude_glob: optional glob to exclude files; takes precedence over `paths_include_glob`. :param relative_path: restricts the search to this file or subdirectory of the project root :param restrict_search_to_code_files: whether to search only (non-ignored) files containing analyzable code symbols (useful when looking for class/method definitions); otherwise also search non-code files. :param skip_ignored_files: whether to skip ignored sub-paths (default: True) :param multiline: whether to apply multi-line matching (default: True), enabling the flags re.DOTALL and re.MULTILINE :return: the matches, rendered as a mapping from file paths to matched consecutive lines (0-based line numbers) """ project = self._get_project() relative_path = relative_path.strip() if relative_path: project.validate_relative_path(relative_path) matches = project.search_project_files_for_pattern( pattern=substring_pattern, relative_path=relative_path, context_lines_before=context_lines_before, context_lines_after=context_lines_after, paths_include_glob=paths_include_glob.strip(), paths_exclude_glob=paths_exclude_glob.strip(), multiline=multiline, code_files_only=restrict_search_to_code_files, skip_ignored_files=skip_ignored_files, ) return PatternMatches(matches, PatternMatchesRenderer(self._agent, max_answer_chars)) - src/serena/repl/api/jb_api.py (32862 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of JetBrains IDE-backed operations. """ from collections import Counter, defaultdict from collections.abc import Iterator from contextlib import contextmanager from typing import TYPE_CHECKING, Any, Literal import serena.jetbrains.jetbrains_types as jb from serena.code_editor import JetBrainsCodeEditor from serena.jetbrains.jetbrains_plugin_client import JetBrainsPluginClient from serena.jetbrains.jetbrains_types import SymbolDTO, SymbolDTOUtil from serena.symbol import JetBrainsSymbolDictGrouper from serena.tools import ( JetBrainsDebugTool, JetBrainsFindDeclarationTool, JetBrainsFindImplementationsTool, JetBrainsFindReferencingSymbolsTool, JetBrainsFindSymbolTool, JetBrainsGetSymbolsOverviewTool, JetBrainsInlineSymbol, JetBrainsListInspectionsTool, JetBrainsMoveTool, JetBrainsRenameTool, JetBrainsRunInspectionsTool, JetBrainsSafeDeleteTool, JetBrainsTypeHierarchyTool, ) from serena.util.text_utils import find_text_coordinates from ..facade import FacadeApi, facade_method from ..representable import JsonObject, JsonObjectRenderer, Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class JetBrainsSymbolCollection(RepresentableViaRenderer): """ A collection of symbols retrieved via the JetBrains backend. Each symbol is a dict with keys such as `name_path`, `relative_path` and `type`, and optionally `children`, `body`, `quick_info`, `documentation` and (for references) `context`. """ symbols: list[SymbolDTO] def __init__(self, symbols: list[SymbolDTO], renderer: "JetBrainsSymbolCollectionRenderer"): """ :param symbols: the symbols :param renderer: the renderer to use for representing the collection """ super().__init__(renderer) self.symbols = symbols def __len__(self) -> int: return len(self.symbols) def relative_paths_(self) -> list[str]: return [s.get("relative_path", "unknown") for s in self.symbols] def identifiers_(self) -> list[SymbolDTO]: """ :return: dicts containing only the identifying information (name_path, type, relative_path) of the symbols """ return [{"name_path": s["name_path"], "type": s["type"], "relative_path": s["relative_path"]} for s in self.symbols] class JetBrainsSymbolCollectionRenderer(Renderer[JetBrainsSymbolCollection]): """ Renders a symbol collection as (optionally grouped) JSON, falling back to a listing of symbol identifiers if the length limit is exceeded. """ def __init__(self, agent: "SerenaAgent", max_answer_chars: int, grouper: JetBrainsSymbolDictGrouper | None = None): super().__init__(agent, max_answer_chars) self._grouper = grouper def _group(self, symbols: list[SymbolDTO]) -> Any: return self._grouper.group(symbols) if self._grouper is not None else symbols def render_identifiers(self, obj: JetBrainsSymbolCollection) -> str: """ :return: a shortened representation containing symbol types and identifiers (path + name_path) only, without children """ return f"Names with paths:\n{self._to_json(self._group(obj.identifiers_()))}" def render(self, obj: JetBrainsSymbolCollection) -> str: result = self._to_json(self._group(obj.symbols)) return self._limit_length(result, shortened_result_factories=[lambda: self.render_identifiers(obj)]) class JetBrainsReferencesRenderer(JetBrainsSymbolCollectionRenderer): """ Renders a collection of referencing symbols, falling back to per-file counts and finally the total count if the length limit is exceeded. """ def render(self, obj: JetBrainsSymbolCollection) -> str: ref_paths = obj.relative_paths_() result = self._to_json(self._group(obj.symbols)) return self._limit_length( result, shortened_result_factories=[ lambda: f"Reference counts per file:\n{self._to_json(Counter(ref_paths))}", lambda: f"Found {len(ref_paths)} references.", ], ) class JetBrainsSymbolsOverview(RepresentableViaRenderer): """ The overview of the symbols defined in a file, i.e. the top-level symbols (each a dict with keys such as `name_path` and `type`, optionally with `children`) and, if requested, the file's documentation. """ def __init__(self, symbols: list[SymbolDTO], documentation: str | None, renderer: "JetBrainsSymbolsOverviewRenderer"): """ :param symbols: the top-level symbols :param documentation: the file's documentation, if requested and present :param renderer: the renderer to use for representing the overview """ super().__init__(renderer) self.symbols = symbols self.documentation = documentation symbols: list[SymbolDTO] documentation: str | None class JetBrainsSymbolsOverviewRenderer(Renderer[JetBrainsSymbolsOverview]): """ Renders an overview in the compact grouped format, dropping (in order) the documentation, the children and finally everything but symbol counts by type if the length limit is exceeded. """ def __init__(self, agent: "SerenaAgent", max_answer_chars: int, grouper: JetBrainsSymbolDictGrouper, depth: int): super().__init__(agent, max_answer_chars) self._grouper = grouper self._depth = depth def render(self, obj: JetBrainsSymbolsOverview) -> str: grouped_symbols = self._grouper.group(obj.symbols) shortened_result_factories = [] # create the full result result: dict[str, Any] = {"symbols": grouped_symbols} if obj.documentation: result["docstring"] = obj.documentation shortened_result_factories.append(lambda: self._to_json(grouped_symbols)) # shortened result without docstring json_result = self._to_json(result) # create shortened results if self._depth > 0: def create_short_result_depth_0() -> str: depth_0_symbols = [d.copy() for d in obj.symbols] for d in depth_0_symbols: d.pop("children", None) return "Depth 0 overview:\n" + self._to_json(self._grouper.group(depth_0_symbols)) shortened_result_factories.append(create_short_result_depth_0) def create_short_result_type_counts() -> str: type_names = [d.get("type", "unknown") for d in obj.symbols] return f"Symbol counts by type:\n{self._to_json(Counter(type_names))}" shortened_result_factories.append(create_short_result_type_counts) return self._limit_length(json_result, shortened_result_factories=shortened_result_factories) class JetBrainsApi(FacadeApi): # groupers for the various symbol collections; top-level symbols are grouped by the first key list, # children by the second find_symbol_grouper_ = JetBrainsSymbolDictGrouper( ["relative_path", "type"], ["type"], collapse_singleton=True, map_name_path_to_name=True ) references_grouper_ = JetBrainsSymbolDictGrouper(["relative_path", "type"], ["type"], collapse_singleton=True) overview_grouper_ = JetBrainsSymbolDictGrouper(["type"], ["type"], collapse_singleton=True, map_name_path_to_name=True) def __init__(self, agent: "SerenaAgent") -> None: super().__init__( agent, name="jb", description="operations on the codebase backed by the JetBrains IDE's code intelligence", ) @contextmanager def _client(self) -> Iterator[JetBrainsPluginClient]: with JetBrainsPluginClient.from_project(self._get_project()) as client: yield client def _json_object(self, data: Any, max_answer_chars: int = -1) -> JsonObject: return JsonObject(data, JsonObjectRenderer(self._agent, max_answer_chars)) # read operations @facade_method(corresponding_tool=JetBrainsFindSymbolTool) def find_symbol( self, name_path_pattern: str, depth: int = 0, relative_path: str | None = None, include_body: bool = False, include_info: bool = False, search_deps: bool = False, max_matches: int = -1, max_answer_chars: int = -1, ) -> JetBrainsSymbolCollection: """ Finds symbols and code entities (classes, methods, etc.) based on the given name path pattern. The returned symbol information can be used for edits or further queries. Specify `depth > 0` to retrieve children (e.g., methods of a class). Important: through `search_deps=True` dependencies can be searched, which should be preferred to web search or other less sophisticated approaches to analyzing dependencies. You will always receive at least quick info for returned symbols (even if `include_info=False`). A name path is a path in the symbol tree *within a source file*. For example, the method `my_method` defined in class `MyClass` would have the name path `MyClass/my_method`. If a symbol is overloaded (e.g., in Java), a 0-based index is appended (e.g. "MyClass/my_method[0]") to uniquely identify it. To search for a symbol, you provide a name path pattern that is used to match against name paths. It can be * a simple name (e.g. "method"), which will match any symbol with that name * a relative path like "class/method", which will match any symbol with that name path suffix * an absolute name path "/class/method" (absolute name path), which requires an exact match of the full name path within the source file. Append an index `[i]` to match a specific overload only, e.g. "MyClass/my_method[1]". In any path component, using `*` will match any sequence of characters (excluding /), e.g. "Class/*substring*" matches a member substring. A pattern must not contain only wildcards (e.g. "*" or "/*"); use `get_symbols_overview` to list a file's symbols. :param name_path_pattern: the name path matching pattern (see above) :param depth: depth up to which descendants shall be retrieved (e.g. use 1 to also retrieve immediate children; for the case where the symbol is a class, this will return its methods). Ignored if `include_body=True`. Default 0. :param relative_path: Optional. Restrict search to this file or directory. If not specified, searches entire codebase. Note: for external dependencies, this must be an identifier starting with `<ext` that you have received earlier (don't try to guess!). :param include_body: If True, include the symbol's full source code. :param include_info: whether to include additional info (hover-like, typically including docstring and signature), about the symbol. Default False; info is never included for child symbols or if include_body is True. :param search_deps: If True, also search in project dependencies (e.g., libraries). :param max_matches: Maximum number of permitted matches. If exceeded, an error containing a shortened result is raised, which allows refining the search. -1 (default) means no limit. Set to 1 if you search for a single symbol. :return: the symbols matching the pattern """ if name_path_pattern.replace("*", "").replace("/", "") == "": raise ValueError("name_path_pattern must not be empty or contain only wildcards; consider using get_symbols_overview") if include_body: depth = 0 # ignore user-specified depth if body is requested if relative_path == ".": relative_path = None if relative_path is not None and relative_path.startswith(jb.JB_EXTERNAL_FILE_PREFIX): search_deps = True # determine which additional information to request: if no additional information is requested, # we still include the quick info (type signature) include_documentation = include_info and not include_body include_quick_info = not include_info and not include_body with self._client() as client: response = client.find_symbol( name_path=name_path_pattern, relative_path=relative_path, depth=depth, include_body=include_body, include_documentation=include_documentation, include_quick_info=include_quick_info, search_deps=search_deps, ) renderer = JetBrainsSymbolCollectionRenderer(self._agent, max_answer_chars, grouper=self.find_symbol_grouper_) collection = JetBrainsSymbolCollection(response["symbols"], renderer) n_matches = len(collection) if 0 < max_matches < n_matches: raise ValueError(f"Matched {n_matches}>{max_matches=} symbols.\n" + renderer.render_identifiers(collection)) return collection @facade_method(corresponding_tool=JetBrainsFindReferencingSymbolsTool) def find_referencing_symbols(self, name_path: str, relative_path: str, max_answer_chars: int = -1) -> JetBrainsSymbolCollection: """ Finds all symbols that reference the given symbol (its callers / usages / dependents) i.e. the symbols whose own definition (e.g. a method body) contains a reference to it. For each, returns its name path, file, and the surrounding line of code. :param name_path: name path of the symbol for which to find references :param relative_path: the relative path to the file containing the symbol (must be a file, not a directory) Note: for external dependencies, this must be an identifier starting with `<ext` that you have received earlier (don't try to guess!). :return: the referencing symbols """ with self._client() as client: response = client.find_references(name_path=name_path, relative_path=relative_path, include_quick_info=False) symbol_dicts = response["symbols"] # replace reference line number (if present) by actual line/context project = self._get_project() for symbol_dict in symbol_dicts: if "reference_line_no" in symbol_dict: ref_line = symbol_dict["reference_line_no"] if not SymbolDTOUtil.is_external_symbol(symbol_dict) and ref_line is not None and ref_line >= 0: content_around_ref = project.retrieve_content_around_line( relative_file_path=symbol_dict["relative_path"], line=ref_line, context_lines_before=1, context_lines_after=1 ) symbol_dict["context"] = content_around_ref.to_display_string() del symbol_dict[" - src/serena/repl/api/lsp_api.py (38601 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of language server (LSP)-backed operations. """ import os from collections import Counter, defaultdict from collections.abc import Callable, Sequence from dataclasses import dataclass from typing import TYPE_CHECKING, Any from serena.code_editor import LanguageServerCodeEditor from serena.lsp.lsp_diagnostics import GroupedDiagnostics from serena.symbol import ( LanguageServerSymbol, LanguageServerSymbolDictGrouper, LanguageServerSymbolRetriever, ReferenceInLanguageServerSymbol, SymbolDictGrouper, ) from serena.tools import ( FindDeclarationTool, FindImplementationsTool, FindReferencingSymbolsTool, FindSymbolTool, GetDiagnosticsForFileTool, GetDiagnosticsForSymbolTool, GetSymbolsOverviewTool, RenameSymbolTool, RestartLanguageServerTool, SafeDeleteSymbol, ) from serena.util.text_utils import TextOutputUtils, find_text_coordinates from solidlsp.lsp_protocol_handler.lsp_types import SymbolKind from ..facade import SUCCESS_RESULT, FacadeApi, ReferencedType, facade_method from ..representable import Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class LspSymbolCollection(RepresentableViaRenderer): """ A collection of symbols (`LanguageServerSymbol`) retrieved via the language server. """ symbols: list[LanguageServerSymbol] def __init__( self, symbols: list[LanguageServerSymbol], renderer: "LspSymbolCollectionRenderer", info_by_symbol: dict[LanguageServerSymbol, str] | None = None, ): """ :param symbols: the list of symbols :param renderer: the renderer to use for representing the collection :param info_by_symbol: additional (hover-like) info per symbol, if requested """ super().__init__(renderer) self.symbols = symbols self.info_by_symbol_ = info_by_symbol or {} def __len__(self) -> int: return len(self.symbols) def relative_path_to_name_paths_(self) -> dict[str, list[str]]: result: defaultdict[str, list[str]] = defaultdict(list) for s in self.symbols: result[s.location.relative_path or "unknown"].append(s.get_name_path()) return result class LspSymbol(RepresentableViaRenderer): """ A single symbol retrieved via the language server (see `LspSymbolCollection` for the symbol's interface). """ symbol: LanguageServerSymbol def __init__(self, symbol: LanguageServerSymbol, renderer: "LspSymbolRenderer", info: str | None = None): """ :param symbol: the symbol :param renderer: the renderer to use for representing the symbol :param info: additional (hover-like) info on the symbol, if requested """ super().__init__(renderer) self.symbol = symbol self.info_ = info @dataclass(kw_only=True) class SymbolOutputParams: name_path: bool = True name: bool = False kind: bool = False location: bool = False depth: int = 0 body_location: bool = False children_body: bool = False children_name: bool | None = None children_name_path: bool | None = None relative_path: bool = False include_body: bool = False include_info: bool = False child_inclusion_predicate: Callable[[LanguageServerSymbol], bool] | None = None class LspSymbolCollectionRenderer(Renderer[LspSymbolCollection]): """ Renders a symbol collection as (optionally grouped) JSON according to the output parameters, falling back to a mapping from files to name paths if the length limit is exceeded. """ def __init__( self, agent: "SerenaAgent", max_answer_chars: int, output_params: SymbolOutputParams, grouper: SymbolDictGrouper | None = None, ): super().__init__(agent, max_answer_chars) self._output_params = output_params self._grouper = grouper def symbol_dicts_( self, symbols: list[LanguageServerSymbol], info_by_symbol: dict[LanguageServerSymbol, str] ) -> list[LanguageServerSymbol.OutputDict]: """ :param symbols: the symbols to convert :param info_by_symbol: additional info to include per symbol, if any :return: the dict representations of the symbols according to the output parameters (including the info) """ p = self._output_params symbol_dicts = [ s.to_dict( kind=p.kind, name_path=p.name_path, name=p.name, location=p.location, relative_path=p.relative_path, body_location=p.body_location, depth=p.depth, body=p.include_body, children_body=p.children_body, children_name=p.children_name, children_name_path=p.children_name_path, child_inclusion_predicate=p.child_inclusion_predicate, ) for s in symbols ] for s, s_dict in zip(symbols, symbol_dicts, strict=True): if symbol_info := info_by_symbol.get(s): # In python 3.15 we could specify extra_items=True in the TypedDict definition, # https://peps.python.org/pep-0728/ # If we ever upgrade to 3.15, we can remove the type: ignore[typeddict-unknown-key] s_dict["info"] = symbol_info return symbol_dicts def _group(self, symbol_dicts: list[LanguageServerSymbol.OutputDict]) -> Any: return self._grouper.group(symbol_dicts) if self._grouper is not None else symbol_dicts def render(self, obj: LspSymbolCollection) -> str: def create_short_result_relative_path_to_name_paths() -> str: return f"Shortened result:\n{TextOutputUtils.to_json(obj.relative_path_to_name_paths_())}" result = self._to_json(self._group(self.symbol_dicts_(obj.symbols, obj.info_by_symbol_))) return self._limit_length(result, shortened_result_factories=[create_short_result_relative_path_to_name_paths]) class LspSymbolRenderer(Renderer[LspSymbol]): """ Renders a single symbol as JSON, using a collection renderer for the conversion. """ def __init__(self, agent: "SerenaAgent", max_answer_chars: int, collection_renderer: LspSymbolCollectionRenderer): super().__init__(agent, max_answer_chars) self._collection_renderer = collection_renderer def render(self, obj: LspSymbol) -> str: info_by_symbol = {obj.symbol: obj.info_} if obj.info_ else {} symbol_dict = self._collection_renderer.symbol_dicts_([obj.symbol], info_by_symbol)[0] return self._limit_length(self._to_json(symbol_dict)) class LspSymbolsOverviewRenderer(LspSymbolCollectionRenderer): """ Renders a file's symbol overview, falling back to a depth-0 overview and finally symbol counts by kind if the length limit is exceeded. """ def render(self, obj: LspSymbolCollection) -> str: symbol_dicts = self.symbol_dicts_(obj.symbols, obj.info_by_symbol_) result = self._to_json(self._group(symbol_dicts)) def make_kind_counts() -> str: kind_names = [d.get("kind", "unknown") for d in symbol_dicts] return f"Symbol counts by kind:\n{self._to_json(Counter(kind_names))}" shortened_results: list[Callable[[], str]] = [make_kind_counts] if self._output_params.depth > 0: def make_depth_0_result() -> str: depth_0_dicts = [d.copy() for d in symbol_dicts] for d in depth_0_dicts: d.pop("children", None) return "Depth 0 overview:\n" + self._to_json(self._group(depth_0_dicts)) shortened_results.insert(0, make_depth_0_result) return self._limit_length(result, shortened_result_factories=shortened_results) class LspReferenceCollection(RepresentableViaRenderer): """ The references to a symbol (`ReferenceInLanguageServerSymbol`). """ references: list[ReferenceInLanguageServerSymbol] def __init__( self, references: list[ReferenceInLanguageServerSymbol], contents_around_references: list[str], renderer: "LspReferenceCollectionRenderer", ): """ :param references: the references :param contents_around_references: for each reference, the code around it (for display) :param renderer: the renderer to use for representing the collection """ super().__init__(renderer) self.references = references self.contents_around_references_ = contents_around_references def __len__(self) -> int: return len(self.references) class LspReferenceCollectionRenderer(Renderer[LspReferenceCollection]): """ Renders references as grouped JSON including the code around each reference, falling back to references without code, per-file counts and finally the total count if the length limit is exceeded. """ def __init__(self, agent: "SerenaAgent", max_answer_chars: int, grouper: SymbolDictGrouper): super().__init__(agent, max_answer_chars) self._grouper = grouper def render(self, obj: LspReferenceCollection) -> str: reference_dicts = [] ref_summaries = [] for ref, content_around_ref in zip(obj.references, obj.contents_around_references_, strict=True): ref_dict = dict(ref.symbol.to_dict(kind=True, relative_path=True, depth=0, body=False, body_location=True)) ref_dict["content_around_reference"] = content_around_ref reference_dicts.append(ref_dict) ref_summaries.append( { "name_path": ref_dict.get("name_path"), "kind": ref_dict.get("kind"), "relative_path": ref_dict.get("relative_path"), "reference_line": ref.line, } ) result = self._to_json(self._grouper.group(reference_dicts)) # shortened result closures, from least to most aggressive shortening def make_refs_without_context() -> str: return f"References without surrounding lines:\n{self._to_json(self._grouper.group([dict(s) for s in ref_summaries]))}" def make_per_file_counts() -> str: counts = Counter(str(r["relative_path"]) for r in ref_summaries) return f"Reference counts per file:\n{self._to_json(counts)}" def make_summary() -> str: return f"Found {len(ref_summaries)} references." return self._limit_length(result, shortened_result_factories=[make_refs_without_context, make_per_file_counts, make_summary]) class LspDiagnostics(RepresentableViaRenderer): """ Diagnostics grouped as `relative_path -> severity -> name_path -> diagnostics`; see `grouped.get_dict()`. """ grouped: GroupedDiagnostics def __init__(self, grouped: GroupedDiagnostics, renderer: "LspDiagnosticsRenderer"): """ :param grouped: the grouped diagnostics :param renderer: the renderer to use for representing the diagnostics """ super().__init__(renderer) self.grouped = grouped class LspDiagnosticsRenderer(Renderer[LspDiagnostics]): def render(self, obj: LspDiagnostics) -> str: return self._limit_length(self._to_json(obj.grouped.get_dict())) def _is_not_low_level(symbol: LanguageServerSymbol) -> bool: return not symbol.is_low_level() class LspApi(FacadeApi): FILE_LEVEL_DIAGNOSTIC_BUCKET = "<file>" """the name path under which diagnostics that cannot be mapped to a symbol are grouped""" # groupers for the various symbol collections; top-level symbols are grouped by the first key list, # children by the second. # For find_symbol, we group children by kind, keeping just the name (the parent's name_path makes it unambiguous); # we don't group the top-level result list because many tests rely on it being a flat list of symbol dicts find_symbol_dict_grouper_ = LanguageServerSymbolDictGrouper([], ["kind"], collapse_singleton=True) references_grouper_ = LanguageServerSymbolDictGrouper(["relative_path", "kind"], ["kind"], collapse_singleton=True) overview_grouper_ = LanguageServerSymbolDictGrouper(["kind"], ["kind"], collapse_singleton=True) def __init__(self, agent: "SerenaAgent") -> None: super().__init__( agent, name="lsp", description="symbol-level operations on the codebase backed by language servers", types=[ ReferencedType( LanguageServerSymbol, members=[ "name", "get_name_path", "relative_path", "symbol_kind_name", "line", "column", "body", "get_body_line_numbers", "iter_children", "iter_ancestors", "get_parent", ], ), ], ) def _create_symbol_retriever(self) -> LanguageServerSymbolRetriever: assert self._agent.get_language_backend().is_lsp(), "Language server operations require the language server backend" return LanguageServerSymbolRetriever(self._get_project()) def _create_ls_code_editor(self, symbol_retriever: LanguageServerSymbolRetriever | None = None) -> LanguageServerCodeEditor: return LanguageServerCodeEditor(symbol_retriever or self._create_symbol_retriever()) @staticmethod def _request_info( symbol_retriever: LanguageServerSymbolRetriever, symbols: list[LanguageServerSymbol], output_params: SymbolOutputParams ) -> dict[LanguageServerSymbol, str]: """ :return: additional (hover-like) info per symbol, if the output parameters request it (and not the body, which supersedes it); requested eagerly, such that results are self-contained """ if output_params.include_info and not output_params.include_body: return {s: info for s, info in symbol_retriever.request_info_for_symbol_batch(symbols).items() if info} return {} def _retrieve_content_around_reference(self, reference: ReferenceInLanguageServerSymbol) -> str: relative_path = reference.symbol.location.relative_path assert relative_path is not None, f"Referencing symbol {reference.symbol.name} has no relative path, this is likely a bug." content = self._get_project().retrieve_content_around_line( relative_file_path=relative_path, line=reference.line, context_lines_before=1, context_lines_after=1 ) return content.to_display_string() @staticmethod def _p - src/serena/repl/api/mem_api.py (7654 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of memory operations (and onboarding, which creates the initial memories). """ import logging import platform from typing import TYPE_CHECKING, Literal from serena.memories.memory_manager import MemoryManager from serena.tools import ( DeleteMemoryTool, EditMemoryTool, ListMemoriesTool, OnboardingTool, ReadMemoryTool, RenameMemoryTool, WriteMemoryTool, ) from ..facade import FacadeApi, facade_method from ..representable import Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent log = logging.getLogger(__name__) class MemoryList(RepresentableViaRenderer): """ The available memories: `memories` (writable) and `read_only_memories` (e.g. global memories), each a list of names. """ def __init__(self, memories_list: MemoryManager.MemoriesList, renderer: "MemoryListRenderer"): """ :param memories_list: the list of memories :param renderer: the renderer to use for representing the list """ super().__init__(renderer) self.memories_list_ = memories_list @property def memories(self) -> list[str]: return sorted(self.memories_list_.memories) @property def read_only_memories(self) -> list[str]: return sorted(self.memories_list_.read_only_memories) class MemoryListRenderer(Renderer[MemoryList]): def render(self, obj: MemoryList) -> str: return self._limit_length(self._to_json(obj.memories_list_.to_dict())) class MemoryApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__( agent, name="mem", description="project memories, i.e. persistent notes for future tasks", ) def _get_memory_manager(self) -> MemoryManager: return self._get_project().memory_manager @facade_method(corresponding_tool=ListMemoriesTool) def list_memories(self, topic: str = "") -> MemoryList: """ Lists the available memories, optionally filtered by topic. :param topic: the topic (prefix of the memory name, e.g. "frontend") to restrict the listing to; empty for all memories :return: the memories """ return MemoryList(self._get_memory_manager().list_memories(topic), MemoryListRenderer(self._agent, -1)) @facade_method(corresponding_tool=ReadMemoryTool) def read_memory(self, memory_name: str) -> str: """ Reads a memory. :param memory_name: the name of the memory :return: the memory's content """ return self._get_memory_manager().load_memory(memory_name) @facade_method(can_edit=True, corresponding_tool=WriteMemoryTool) def write_memory(self, memory_name: str, content: str, max_chars: int = -1) -> str: """ Writes information (about the active project) to a memory. The name should be meaningful and can include "/" to organize into topics. If explicitly instructed, use the "global/" prefix for writing a memory that is shared across projects. References to other memories should be inside backticks and prefixed with mem:, e.g., `mem:auth`. :param memory_name: the memory name :param content: the memory content (utf-8-encoded markdown) :param max_chars: the maximum content length; -1 for the configured default :return: a message indicating the result """ if max_chars == -1: max_chars = self._agent.serena_config.default_max_tool_answer_chars if len(content) > max_chars: raise ValueError( f"Content for {memory_name} is too long. Max length is {max_chars} characters. Please make the content shorter." ) return self._get_memory_manager().save_memory(memory_name, content, is_tool_context=True) @facade_method(can_edit=True, corresponding_tool=EditMemoryTool) def edit_memory( self, memory_name: str, needle: str, repl: str, mode: Literal["literal", "regex"], allow_multiple_occurrences: bool = False, ) -> str: """ Replaces content matching a pattern in a memory. :param memory_name: the name of the memory :param needle: the string or regex pattern to search for. In regex mode, be careful to not replace too much! If `mode` is "literal", this string will be matched exactly. If `mode` is "regex", this string will be treated as a regular expression (syntax of Python's `re` module, with the MULTILINE and DOTALL flags enabled). :param repl: the replacement string (verbatim). :param mode: either "literal" or "regex", specifying how the `needle` parameter is to be interpreted. :param allow_multiple_occurrences: whether to allow matching and replacing multiple occurrences. If false and multiple occurrences are found, an error will be raised. :return: a message indicating the result """ return self._get_memory_manager().edit_memory( memory_name, needle, repl, mode, allow_multiple_occurrences, is_tool_context=True, regex_multiline=True ) @facade_method(can_edit=True, corresponding_tool=RenameMemoryTool) def rename_memory(self, old_name: str, new_name: str) -> str: """ Renames or moves a memory; use "/" in the name to organize into topics. The "global" topic should only be used if explicitly instructed. References to other memories that are marked with the `mem:` prefix will be updated accordingly. References in read-only memories are not affected. :param old_name: the current name of the memory :param new_name: the new name of the memory :return: a message indicating the result """ renaming_message, n_references_updated = self._get_memory_manager().rename_memory_and_propagate_references( old_name, new_name, is_tool_context=True ) if n_references_updated > 0: log.info(f"Updated {n_references_updated} references to memory {old_name} to {new_name}") return renaming_message @facade_method(can_edit=True, corresponding_tool=DeleteMemoryTool) def delete_memory(self, memory_name: str) -> str: """ Deletes a memory; only call this if instructed explicitly or permission was granted by the user. :param memory_name: the name of the memory :return: a message indicating the result """ return self._get_memory_manager().delete_memory(memory_name, is_tool_context=True) @facade_method(corresponding_tool=OnboardingTool, can_edit=True) def onboarding(self) -> str: """ Provides the instructions for performing onboarding (identifying the project structure and essential tasks, e.g. for testing or building, and recording the findings in memories). Call this if onboarding was not performed yet, at most once per conversation. :return: the instructions on how to create the onboarding information """ # seed the project-local memory-maintenance memory (or detect a global override) so # the prompt can point the agent at the conventions before it writes anything memory_maintenance_name = self._get_memory_manager().ensure_memory_maintenance_memory() return self._agent.prompt_factory.create_onboarding_prompt( system=platform.system(), memory_maintenance_name=memory_maintenance_name ) - src/serena/repl/api/shell_api.py (3267 bytes)
# SPDX-License-Identifier: GPL-3.0-or-later """ The implementation of shell command execution. """ import os.path from typing import TYPE_CHECKING from serena.tools import ExecuteShellCommandTool from serena.util.shell import ShellCommandResult, execute_shell_command from ..facade import FacadeApi, facade_method from ..representable import Renderer, RepresentableViaRenderer if TYPE_CHECKING: from serena.agent import SerenaAgent class ShellCommandOutput(RepresentableViaRenderer): """ The outcome of a shell command: `stdout`, `stderr` (None if not captured), `return_code` and `cwd`. """ def __init__(self, result: ShellCommandResult, renderer: "ShellCommandOutputRenderer"): """ :param result: the result of the command execution :param renderer: the renderer to use for representing the output """ super().__init__(renderer) self.result_ = result @property def stdout(self) -> str: return self.result_.stdout @property def stderr(self) -> str | None: return self.result_.stderr @property def return_code(self) -> int: return self.result_.return_code @property def cwd(self) -> str: return self.result_.cwd class ShellCommandOutputRenderer(Renderer[ShellCommandOutput]): def render(self, obj: ShellCommandOutput) -> str: return self._limit_length(obj.result_.model_dump_json()) class ShellApi(FacadeApi): def __init__(self, agent: "SerenaAgent") -> None: super().__init__(agent, name="shell", description="execution of shell commands") @facade_method(can_edit=True, corresponding_tool=ExecuteShellCommandTool) def execute_shell_command( self, command: str, cwd: str | None = None, capture_stderr: bool = True, max_answer_chars: int = -1 ) -> ShellCommandOutput: """ Executes a shell command and returns its output. If there is a memory about suggested commands, read that first. Never execute unsafe shell commands! IMPORTANT: Do not use this to start * long-running processes (e.g. servers) that are not intended to terminate quickly, * processes that require user interaction. :param command: the shell command to execute :param cwd: the working directory to execute the command in (absolute, or relative to the project root). If None, the project root will be used. :param capture_stderr: whether to capture and return stderr output :return: the output (object with properties stdout, stderr, return_code and cwd) """ project_root = self._get_project().project_root if cwd is None: _cwd = project_root elif os.path.isabs(cwd): _cwd = cwd else: _cwd = os.path.join(project_root, cwd) if not os.path.isdir(_cwd): raise FileNotFoundError( f"Specified a relative working directory ({cwd}), but the resulting path is not a directory: {_cwd}" ) result = execute_shell_command(command, cwd=_cwd, capture_stderr=capture_stderr) return ShellCommandOutput(result, ShellCommandOutputRenderer(self._agent, max_answer_chars)) - sync.py (224 bytes)
import os from repo_dir_sync import LibRepo, OtherRepo r = LibRepo(name="serena", libDirectory="src") r.add(OtherRepo(name="mux", branch="mux", pathToLib=os.path.join("..", "serena-multiplexer", "src-serena"))) r.runMain()