Serena REPL and API Facades
Overview
This area is Serena's Python REPL facade layer: src/…/repl.py executes notebook-like Python snippets for an LLM, binds the entrypoint object as s, and exposes project-facing operations through facades built in src/…/facade.py. SerenaRepl.execute() runs code in the SerenaSession.repl_namespace when a session is supplied, so variables, imports, functions, and classes persist across calls unless they fail the persisted-name pattern or are cleared with s.clear(). A trailing expression is evaluated and rendered as the result; syntax and runtime errors are formatted with line numbers from the submitted cell, including a special hint when return is used outside a function.
Facade startup is two-stage. API implementations subclass FacadeApi in src/…/*.py and mark exposed methods with @facade_method; Facade.from_api() scans only those decorated methods, attaches FacadeMethodInfo, applies ApiScope, and discovers referenced result/parameter types from annotations. SerenaReplEntrypoint receives the resulting facades, registers only facades with at least one enabled method as attributes on s, and exposes s.overview() / s.info(...) for progressive discovery. ApiScope applies configured include/exclude definitions in order, supports the special editing exclusion marker, treats optional facades/methods as opt-in, and disables can_edit methods when editing is excluded.
Facade methods are read-only attributes on Facade; calling s.fs.read_file(...) or s.lsp.find_symbol(...) invokes a FacadeMethod wrapper, not the implementation directly. The wrapper also enforces the external-project model. src/…/ext_api.py provides s.ext.list_projects() and context managers from read_project_context() / optional project_context(). Entering a context temporarily activates the registered external project and installs ExternalProjectExecution on every facade. src/…/external_project.py then forbids editing in read-only contexts and routes methods marked uses_project_server — plus edit methods under the LSP backend — through ProjectServerClient.call_facade_method() with JSON-serializable arguments. Contexts cannot be nested, and leaving the context restores the previous project and clears the external execution state.
Returned values use the representation protocol in src/…/representable.py. SerenaRepl._represent() delegates to Representable.represent(), renders lists and tuples one item per line, and otherwise falls back to str(). Most structured API results extend RepresentableViaRenderer; renderers pull the default answer limit from agent.serena_config.default_max_tool_answer_chars and call TextOutputUtils.limit_length(), often with progressively shorter fallbacks. JsonObject is the generic JSON-rendered result for plain dict/list payloads. ReferencedType in src/…/facade.py controls what type documentation s.info() shows for returned objects, including curated members, enum/TypedDict formatting, method signatures, and transitive referenced types; per-session described_type_names prevents repeating type docs unless explicitly requested.
The API modules map classic Serena tools to REPL facades:
- src/…/fs_api.py exposes
s.fsfile-unit operations: read files or line ranges, create/overwrite text files, list directories, find files by mask, and regex-search project files. Results areFileContent,DirectoryListing, andPatternMatches; pattern rendering degrades from contextual match blocks to first lines, line numbers, per-file counts, and a summary. - src/…/edit_api.py exposes backend-independent content edits under
s.edit: literal/regex single-file replacement, guarded multi-file replacement with dry-run occurrence IDs, optional line-level edits, and symbol insertion/body replacement viaCodeEditor. Multi-file dry runs returnReplacementPreviewso callers can choose exact occurrence IDs before applying changes. - src/…/lsp_api.py exposes LSP-backed symbol, reference, diagnostic, and refactoring operations under
s.lsp. It validates relative paths, synchronizes language-server state before operations that depend on current filesystem contents, usesLanguageServerSymbolRetriever, groups symbol/reference/diagnostic results, and marks LSP/project-server-dependent methods withuses_project_server. Edit methods includerename_symbol()andsafe_delete_symbol();restart_language_server()and symbol-level diagnostics are optional. - src/…/jb_api.py exposes JetBrains-backed operations under
s.jbviaJetBrainsPluginClientandJetBrainsCodeEditor: symbol search, references, overviews, type hierarchy, declaration/implementation lookup, rename/move/safe-delete/inline, inspections, and a persistent debug REPL. JetBrains renderers shorten symbol collections to identifiers, reference counts, total counts, depth-0 overviews, or type counts as needed. - src/…/mem_api.py exposes
s.memproject memory operations plus onboarding. Writes enforce the configured/default maximum content length, rename updates memory references through theMemoryManager, and delete is marked editing because it mutates persistent project memory. - src/…/shell_api.py exposes
s.shell.execute_shell_command(), resolvingcwdrelative to the active project root unless an absolute path is supplied, returning stdout/stderr/return code/cwd asShellCommandOutput. - src/…/cfg_api.py exposes
s.cfg.get_current_config()ands.cfg.open_dashboard()for session/config visibility and dashboard launch.
The covered demo scripts exercise the same surface mostly through classic tools, which are linked back to facade methods by FacadeMethodInfo.corresponding_tool. scripts/demo_cli_call.py imports serena.cli.top_level and invokes --help. scripts/demo_diagnostics.py creates an LSP-backed agent for the Serena repo, writes a temporary file, uses create/replace/diagnostic tools, and verifies edit-tool diagnostics report only newly introduced warnings. scripts/demo_find_defining_symbol.py demonstrates FindDeclarationTool against a Python fixture using both whole-file and containing-symbol regex searches. scripts/demo_find_implementing_symbol.py demonstrates FindImplementationsTool on a Go fixture. scripts/demo_progressive_tool_shortening.py deliberately shrinks max_answer_chars for LSP, JetBrains, and search tools to show renderer fallback stages. scripts/demo_run_tools.py is a local scratch/demo harness that builds an agent for the Serena repo, obtains several tool classes, and currently runs file diagnostics for a Clojure fixture.
Coupling
- If a new REPL-facing method is added in any src/…/*.py file, decorate it with
@facade_methodand setcan_edit,optional,beta,niche,uses_project_server, andcorresponding_toolaccurately.Facade.from_api()in src/…/facade.py ignores undecorated methods entirely, andExternalProjectExecutionin src/…/external_project.py relies onuses_project_server/can_editto route or reject external-project calls. - If result classes or renderer output shapes change in src/…/lsp_api.py, src/…/jb_api.py, src/…/fs_api.py, or src/…/edit_api.py, also verify
ReferencedTypedeclarations in those files and the progressive-shortening demo in scripts/demo_progressive_tool_shortening.py;s.info()derives processable type docs from annotations and curated members, while the demo asserts the intended shortening stages by exercising the corresponding classic tools. - If
ApiScopebehavior changes in src/…/facade.py, check callers that expect read-only operation to exclude allcan_editmethods. Editing permissions are enforced both at method enablement time and again for external project contexts in src/…/external_project.py, so an incorrect flag can silently expose mutating operations. - If classic tool classes are renamed or split, update
corresponding_toolmetadata in the matching API module.SerenaReplEntrypoint.is_tool_function_available()in src/…/repl.py and the demo scripts under scripts/demo_*.py depend on the mapping between tool classes and REPL facade methods.
Risks
- src/…/external_project.py only remote-routes methods whose metadata says
uses_project_serveror LSP edit methods. If an LSP-dependent read operation in src/…/lsp_api.py is added withoutuses_project_server=True, external project queries may execute against the locally active process instead of the target project's server. - src/…/repl.py stores the active session and namespace on the shared entrypoint during execution and documents that executions are expected to be serialized. If concurrent executions share one
SerenaRepl,s.vars(),s.clear(), and facade external-project state can observe or mutate the wrong namespace. - src/…/fs_api.py writes files in
create_text_file()after resolving the destination and validating the relative path. If project path validation semantics change, this method is a path-safety boundary because it creates parent directories and overwrites existing files.