Introducing a new way to review your PRs.

Read the announcement

oraios / serena

A powerful MCP toolkit for coding, providing semantic retrieval and editing capabilities - the IDE for your agent

View on GitHub

13 documents · Updated Nov 16, 2026

docs / serena-agent-core


slug: docs/serena-agent-core.md status: NEW scope: Serena's central agent/runtime model: projects, sessions, task execution, code editing, symbols, prompts, analytics/hooks, and language-backend abstraction points used by higher-level flows. covers:

  • src/serena/agent.py
  • src/serena/agno.py
  • src/serena/analytics.py
  • src/serena/code_editor.py
  • src/serena/constants.py
  • src/serena/hooks.py
  • src/serena/language_backend.py
  • src/serena/project.py
  • src/serena/session.py
  • src/serena/symbol.py
  • src/serena/task_executor.py
  • src/serena/prompt_factory.py
  • src/serena/generated/generated_prompt_factory.py

Serena Agent Core

Overview

The core runtime is centered on SerenaAgent in src/…/agent.py. Agent construction loads SerenaConfig, propagates settings, resolves an optional startup project, chooses the session's language backend and agent interface, creates every registered Tool, starts a single-lane TaskExecutor, initializes prompt rendering via SerenaPromptFactory, computes active modes/toolsets, optionally starts dashboard/logging UI, and finally reports usage telemetry unless disabled by environment. The exposed tool set is intentionally fixed for MCP/tool clients after startup (get_exposed_tool_instances), while the active tool set can be narrowed by active project config, modes, read-only project settings, or REPL API scope.

Project activation is the main lifecycle transition. SerenaAgent.activate_project_from_path_or_name finds or auto-registers a Project through global config, then _activate_project switches the active project, handles backend incompatibility, shuts down the previous project, applies project modes/tool filters, resets project prompt status, schedules project activation work, and updates dashboard state. Activation work runs through TaskExecutor and includes trusted activation_command execution followed by LanguageBackend.init_active_project. In tools mode, a project-specific backend override must match the backend selected at startup because exposed tools are fixed; in REPL mode _activate_project can switch self._language_backend and recompute backend-dependent REPL facades and prompt parameters.

Project in src/…/project.py owns per-project state: root path, loaded ProjectConfig, Serena data folder, memory manager, line ending, ignore spec, trust checks, file scanning/search helpers, and the LSP LanguageServerManager when the active backend uses language servers. It builds its ignore spec asynchronously from global/project ignored paths and optionally nested .gitignore files, then blocks callers on first use if the spec is not ready. It protects untrusted projects by not following symlinks that can escape the project root and by ignoring project-provided LS-specific settings and activation commands unless the project is trusted. Its language_backend property delegates to the agent once attached, so backend-sensitive file filtering and file proxies reflect the effective session backend.

LanguageBackend in src/…/language_backend.py is the abstraction boundary between the agent and concrete language-analysis implementations. A backend supplies LSP-tool replacements, REPL facades, active-project init/shutdown hooks, project activation/config overview text, a CodeEditor, source-file classification, external-path detection, and file-proxy creation. Built-ins are registered through BuiltinLanguageBackend (LSP, JetBrains, olb-jvm), while LanguageBackendRegistry adds plugin backends from the serena.language_backend_registration entry point group and resolves backends by string key.

Code editing is funneled through CodeEditor in src/…/code_editor.py. The base class exposes common operations such as replace_body, insert_after_symbol, insert_before_symbol, insert_at_line, line deletion/replacement, and delete_symbol; edits are applied inside edited_file_context, which rejects backend-marked external paths and saves atomically using project encoding and configured line endings. LanguageServerCodeEditor edits through a SolidLanguageServer file buffer and applies LSP workspace edits for rename, including text edits and file renames. JetBrainsCodeEditor edits in memory using file proxies, writes atomically, and asks the JetBrains plugin to refresh the changed file when possible; its rename delegates to the plugin and can also rename files/directories when name_path is None.

Symbol navigation is modeled in src/…/symbol.py. LanguageServerSymbol wraps SolidLSP's unified symbol tree, computes name paths with / separators and overload indexes, exposes body/location dictionaries for tool output, and supports recursive matching via NamePathMatcher. LanguageServerSymbolRetriever uses a project's LanguageServerManager to retrieve symbol trees, hover info, references, implementations, declarations, diagnostics, and file overviews; expensive hover lookups are grouped per file and bounded by global/project symbol_info_budget. JetBrainsSymbol wraps JetBrains plugin DTOs and lazily computes body text from project files when the DTO did not include a body. LanguageServerSymbolDictGrouper and JetBrainsSymbolDictGrouper post-process tool outputs into grouped trees without mutating original symbol dictionaries.

Sessions are lightweight per-client state in src/…/session.py. SerenaAgent.create_system_prompt creates a new SerenaSession, embeds its random hex id into the prompt, and callers pass that id back to tools that need session-scoped state. Each SerenaSession tracks REPL result-type docs already shown and a persistent REPL namespace. SessionRegistry creates unknown ids on demand, keeps sessions in LRU order, and evicts idle sessions after 48 hours or when more than 100 are retained.

Prompts are generated through src/…/prompt_factory.py and src/…/generated_prompt_factory.py. SerenaPromptFactory combines user prompt templates from SerenaPaths().user_prompt_templates_dir with bundled templates under PROMPT_TEMPLATES_DIR_INTERNAL. The generated PromptFactory exposes typed methods for known templates such as create_connection_prompt, create_system_prompt, create_onboarding_prompt, and JetBrains/Claude-Code overrides. SerenaAgent._render_prompt renders context, mode, and project prompt snippets with Jinja variables for available tools, tool markers, backend/interface-specific tool name mappings, and embedded memories.

Task execution is serialized by TaskExecutor in src/…/task_executor.py. issue_task queues work and returns a Task future; execute_task queues and waits. The executor thread starts one worker thread per task but waits for completion or timeout before moving to the next queued task, preserving task order while allowing callers to observe/cancel futures. Serena uses its task-completion callback to notify config/dashboard listeners after any queued work because tasks can alter agent state.

Analytics and hooks are adjacent runtime concerns. src/…/analytics.py provides token estimators (tiktoken, Anthropic token-count API, or character count) and thread-safe ToolUsageStats, which SerenaAgent.record_tool_usage updates and the dashboard consumes. src/…/hooks.py contains fast CLI hook commands: activation reminders at session start, cleanup at session end, grep/read drift reminders persisted under $SERENA_HOME/hook_data/<session_id>, post-tool reset of those counters, Serena auto-approval in permissive client modes, and Codex plan-mode context/guard logic that blocks generated edit-capable Serena tool names. Constants in src/…/constants.py define repository/resource locations, default encodings, bundled config directories, log buffering, and fixed Serena service port bases.

src/…/agno.py adapts the same core agent for the Agno UI. SerenaAgnoAgentProvider.get_agent is a process singleton because Agno reloads the app module; it changes to REPO_ROOT, parses --project/--project-file, loads .env, constructs SerenaAgent(..., context=SerenaAgentContext.load("agent")), deletes a temporary SQLite database, and exposes every fixed Serena tool through SerenaAgnoToolkit. Each Agno Function calls the underlying tool via tool.apply_ex(log_call=True, catch_exceptions=True, **kwargs) and the Agno agent uses serena_agent.create_system_prompt() as its system message.

Coupling

  • If tool names, tool classes, or edit capability metadata change, update the routing in src/…/agent.py, Agno wrapping in src/…/agno.py, and hook guards in src/…/hooks.py. ToolSet.LEGACY_TOOL_NAME_MAPPING, SerenaAgent.PromptParams, SerenaAgnoToolkit, and CodexPlanGuardHook all assume stable tool names and generated metadata.
  • If a language backend adds or replaces LSP-based tool behavior, implement the full LanguageBackend contract in src/…/language_backend.py and verify SerenaAgent._get_prompt_params, _create_base_toolset, get_repl, and Project.language_backend still select the intended tool/facade names. Prompt text uses backend-specific replacement names, not just registered tool classes.
  • If project trust, ignore, or source-file filtering changes in src/…/project.py, verify code search, symbol discovery, file editing, and language-server initialization together. Project.gather_project_files, Project.scan_directory, LanguageServerFactory construction, and CodeEditor.edited_file_context all depend on the same path-boundary and backend source-file decisions.
  • If prompt template variables or generated prompt methods change, regenerate/update src/…/generated_prompt_factory.py and adjust SerenaAgent.create_system_prompt, get_project_activation_message, and _render_prompt in src/…/agent.py. These methods pass concrete keyword sets (available_tools, available_markers, tool_names, mode/context prompts, memories) expected by the generated template functions.
  • If session id semantics or REPL persistence changes in src/…/session.py, check all prompt and REPL entry points in src/…/agent.py. The system prompt announces the id, project activation prompt status is tracked per session id, and REPL execution keeps globals in SerenaSession.repl_namespace.
  • If task cancellation/timeout behavior changes in src/…/task_executor.py, verify project activation and language server changes in src/…/agent.py and src/…/project.py. A timeout cancels only the future; the worker thread can continue and the executor proceeds to the next task, so callers must not assume timed-out backend initialization has stopped.

Risks

  • src/…/agent.py fixes self._exposed_tools after startup for tool-interface clients. If dynamic project activation later enables a tool that was not included in the base exposed set, _update_active_tools only logs a warning and the client cannot call it; project/mode tool changes may appear active in config but remain unavailable to MCP clients.
  • src/…/task_executor.py marks a timed-out running task's future as cancelled but cannot stop the underlying task thread. If project activation or language-server mutation times out, later tasks may run while the old operation still mutates project/backend state.
  • src/…/project.py computes ignore specs asynchronously and blocks on first access. If _gather_ignorespec fails, path scanning and source-file discovery raise a hard error later rather than during project construction; activation can appear successful until the first ignore-dependent operation.
  • src/…/code_editor.py applies LSP workspace-edit operations sequentially and file renames with os.rename after computing operations from the language server. If a later text edit or rename fails, earlier edits are already persisted through edited_file_context, so rename-symbol operations are not atomic across files.
  • src/…/hooks.py persists PreToolUseRemindAboutSymbolicToolsHook.ToolUseCounter via pickle under a per-session hook-data directory. Corrupt or incompatible pickle data is silently replaced with a fresh counter, so reminder rate-limiting and drift history can reset without a visible error.