π OpenHands: AI-Driven Development
chore: remove unused items from openhands.server package (#14202)
Tim O'Farrell85b959d88390
diff --git a/openhands/server/README.md b/openhands/server/README.mdindex 8d0cf383f1..78038349dc 100644--- a/openhands/server/README.md+++ b/openhands/server/README.md@@ -1,182 +1,28 @@-# OpenHands Server+# OpenHands Legacy (V0) Server-This is a WebSocket server that executes tasks using an agent.+> **IMPORTANT**: This is the legacy V0 web server, deprecated since version 1.0.0.+> The V1 application server lives under `openhands/app_server/`.-## Recommended Prerequisites+This package provides the V0 ASGI entry point (`listen.py`) that is still used by+the Makefile and the container `CMD`. It assembles the FastAPI app from+`openhands.server.app`, layers on middleware, Socket.IO, and (optionally) serves+the frontend static build.-- [Initialize the frontend code](../../frontend/README.md)-- Install Python 3.12 (`brew install python` for those using homebrew)-- Install pipx: (`brew install pipx` followed by `pipx ensurepath`)-- Install poetry: (`pipx install poetry`)+## Key modules-## Install+| Module | Purpose |+|--------|---------|+| `app.py` | Creates the FastAPI application, mounts MCP and V1 routers |+| `listen.py` | Adds middleware (CORS, caching, rate-limiting), mounts SPA static files, wraps in Socket.IO ASGI |+| `listen_socket.py` | Re-exports the `sio` Socket.IO server for backward compatibility |+| `shared.py` | Module-level singletons (config, server config, Socket.IO, store implementations) |+| `middleware.py` | CORS, cache-control, and rate-limiting middleware |+| `static.py` | `SPAStaticFiles` β serves the frontend with SPA fallback |+| `types.py` | Shared types (`AppMode`, `ServerConfigInterface`, error classes) |+| `config/server_config.py` | OSS `ServerConfig` implementation and loader |-First build a distribution of the frontend code (From the project root directory):+## Starting the server```sh-cd frontend-npm install-npm run build-cd ..+uvicorn openhands.server.listen:app --host 0.0.0.0 --port 3000```--Next run `poetry shell` (So you don't have to repeat `poetry run`)--## Start the Server--```sh-uvicorn openhands.server.listen:app --reload --port 3000-```--## Test the Server--You can use [`websocat`](https://github.com/vi/websocat) to test the server.--```sh-websocat ws://127.0.0.1:3000/ws-{"action": "start", "args": {"task": "write a bash script that prints hello"}}-```--## Supported Environment Variables--```sh-LLM_API_KEY=sk-... # Your Anthropic API Key-LLM_MODEL=claude-3-5-sonnet-20241022 # Default model for the agent to use-SANDBOX_VOLUMES=/path/to/your/workspace:/workspace:rw # Mount paths in format host_path:container_path:mode-```--## API Schema--There are two types of messages that can be sent to, or received from, the server:--* Actions-* Observations--### Actions--An action has three parts:--* `action`: The action to be taken-* `args`: The arguments for the action-* `message`: A friendly message that can be put in the chat log--There are several kinds of actions. Their arguments are listed below.-This list may grow over time.--* `initialize` - initializes the agent. Only sent by client.- * `model` - the name of the model to use- * `directory` - the path to the workspace- * `agent_cls` - the class of the agent to use-* `start` - starts a new development task. Only sent by the client.- * `task` - the task to start-* `read` - reads the content of a file.- * `path` - the path of the file to read-* `write` - writes the content to a file.- * `path` - the path of the file to write- * `content` - the content to write to the file-* `run` - runs a command.- * `command` - the command to run-* `browse` - opens a web page.- * `url` - the URL to open-* `think` - Allows the agent to make a plan, set a goal, or record thoughts- * `thought` - the thought to record-* `finish` - agent signals that the task is completed--### Observations--An observation has four parts:--* `observation`: The observation type-* `content`: A string representing the observed data-* `extras`: additional structured data-* `message`: A friendly message that can be put in the chat log--There are several kinds of observations. Their extras are listed below.-This list may grow over time.--* `read` - the content of a file- * `path` - the path of the file read-* `browse` - the HTML content of a url- * `url` - the URL opened-* `run` - the output of a command- * `command` - the command run- * `exit_code` - the exit code of the command-* `chat` - a message from the user--## Server Components--The following section describes the server-side components of the OpenHands project.--### 1. session/session.py--The `session.py` file defines the `Session` class, which represents a WebSocket session with a client. Key features include:--- Handling WebSocket connections and disconnections-- Initializing and managing the agent session-- Dispatching events between the client and the agent-- Sending messages and errors to the client--### 2. session/agent_session.py--The `agent_session.py` file contains the `AgentSession` class, which manages the lifecycle of an agent within a session. Key features include:--- Creating and managing the runtime environment-- Initializing the agent controller-- Handling security analysis-- Managing the event stream--### 3. session/conversation_manager/conversation_manager.py--The `conversation_manager.py` file defines the `ConversationManager` class, which is responsible for managing multiple client conversations. Key features include:--- Adding and restarting conversations-- Sending messages to specific conversations-- Cleaning up inactive conversations--### 4. listen.py--The `listen.py` file is the main server file that sets up the FastAPI application and defines various API endpoints. Key features include:--- Setting up CORS middleware-- Handling WebSocket connections-- Managing file uploads-- Providing API endpoints for agent interactions, file operations, and security analysis-- Serving static files for the frontend--## Workflow Description--1. **Server Initialization**:- - The FastAPI application is created and configured in `listen.py`.- - CORS middleware and static file serving are set up.- - The `ConversationManager` is initialized.--2. **Client Connection**:- - When a client connects via WebSocket, a new `Session` is created or an existing one is restarted.- - The `Session` initializes an `AgentSession`, which sets up the runtime environment and agent controller.--3. **Agent Initialization**:- - The client sends an initialization request.- - The server creates and configures the agent based on the provided parameters.- - The runtime environment is set up, and the agent controller is initialized.--4. **Event Handling**:- - The `Session` manages the event stream between the client and the agent.- - Events from the client are dispatched to the agent.- - Observations from the agent are sent back to the client.--5. **File Operations**:- - The server handles file uploads, ensuring they meet size and type restrictions.- - File read and write operations are performed through the runtime environment.--6. **Security Analysis**:- - If configured, a security analyzer is initialized for each session.- - Security-related API requests are forwarded to the security analyzer.--7. **Session Management**:- - The `ConversationManager` periodically cleans up inactive sessions.- - It also handles sending messages to specific sessions when needed.--8. **API Endpoints**:- - Various API endpoints are provided for agent interactions, file operations, and retrieving configuration defaults.--This server architecture allows for managing multiple client sessions, each with its own agent instance, runtime environment, and security analyzer. The event-driven design facilitates real-time communication between clients and agents, while the modular structure allows for easy extension and maintenance of different components.diff --git a/openhands/server/file_config.py b/openhands/server/file_config.pydeleted file mode 100644index efe53317e3..0000000000--- a/openhands/server/file_config.py+++ /dev/null@@ -1,147 +0,0 @@-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk-# - V1 application server (in this repo): openhands/app_server/-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.-# Tag: Legacy-V0-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.-import os-import re--from openhands.core.config import OpenHandsConfig-from openhands.core.logger import openhands_logger as logger-from openhands.server.shared import config as shared_config--FILES_TO_IGNORE = [- '.git/',- '.DS_Store',- 'node_modules/',- '__pycache__/',- 'lost+found/',- '.vscode/',-]---def sanitize_filename(filename: str) -> str:- """Sanitize the filename to prevent directory traversal"""- # Remove any directory components- filename = os.path.basename(filename)- # Remove any non-alphanumeric characters except for .-_- filename = re.sub(r'[^\w\-_\.]', '', filename)- # Limit the filename length- max_length = 255- if len(filename) > max_length:- name, ext = os.path.splitext(filename)- filename = name[: max_length - len(ext)] + ext- return filename---def load_file_upload_config(- config: OpenHandsConfig = shared_config,-) -> tuple[int, bool, list[str]]:- """Load file upload configuration from the config object.-- This function retrieves the file upload settings from the global config object.- It handles the following settings:- - Maximum file size for uploads- - Whether to restrict file types- - List of allowed file extensions-- It also performs sanity checks on the values to ensure they are valid and safe.-- Returns:- tuple: A tuple containing:- - max_file_size_mb (int): Maximum file size in MB. 0 means no limit.- - restrict_file_types (bool): Whether file type restrictions are enabled.- - allowed_extensions (set): Set of allowed file extensions.- """- # Retrieve values from config- max_file_size_mb = config.file_uploads_max_file_size_mb- restrict_file_types = config.file_uploads_restrict_file_types- allowed_extensions = config.file_uploads_allowed_extensions-- # Sanity check for max_file_size_mb- if not isinstance(max_file_size_mb, int) or max_file_size_mb < 0:- logger.warning(- f'Invalid max_file_size_mb: {max_file_size_mb}. Setting to 0 (no limit).'- )- max_file_size_mb = 0-- # Sanity check for allowed_extensions- if not isinstance(allowed_extensions, (list, set)) or not allowed_extensions:- logger.warning(- f'Invalid allowed_extensions: {allowed_extensions}. Setting to [".*"].'- )- allowed_extensions = ['.*']- else:- # Ensure all extensions start with a dot and are lowercase- allowed_extensions = [- ext.lower() if ext.startswith('.') else f'.{ext.lower()}'- for ext in allowed_extensions- ]-- # If restrictions are disabled, allow all- if not restrict_file_types:- allowed_extensions = ['.*']-- logger.debug(- f'File upload config: max_size={max_file_size_mb}MB, '- f'restrict_types={restrict_file_types}, '- f'allowed_extensions={allowed_extensions}'- )-- return max_file_size_mb, restrict_file_types, allowed_extensions---# Load configuration-MAX_FILE_SIZE_MB, RESTRICT_FILE_TYPES, ALLOWED_EXTENSIONS = load_file_upload_config()---def is_extension_allowed(filename: str) -> bool:- """Check if the file extension is allowed based on the current configuration.-- This function supports wildcards and files without extensions.- The check is case-insensitive for extensions.-- Args:- filename (str): The name of the file to check.-- Returns:- bool: True if the file extension is allowed, False otherwise.- """- if not RESTRICT_FILE_TYPES:- return True-- file_ext = os.path.splitext(filename)[1].lower() # Convert to lowercase- return (- '.*' in ALLOWED_EXTENSIONS- or file_ext in (ext.lower() for ext in ALLOWED_EXTENSIONS)- or (file_ext == '' and '.' in ALLOWED_EXTENSIONS)- )---def get_unique_filename(filename: str, folder_path: str) -> str:- """Returns unique filename on given folder_path. By checking if the given- filename exists. If it doesn't, filename is simply returned.- Otherwise, it append copy(#number) until the filename is unique.-- Args:- filename (str): The name of the file to check.- folder_path (str): directory path in which file name check is performed.-- Returns:- string: unique filename.- """- name, ext = os.path.splitext(filename)- filename_candidate = filename- copy_index = 0-- while os.path.exists(os.path.join(folder_path, filename_candidate)):- if copy_index == 0:- filename_candidate = f'{name} copy{ext}'- else:- filename_candidate = f'{name} copy({copy_index}){ext}'- copy_index += 1-- return filename_candidatediff --git a/openhands/server/shared.py b/openhands/server/shared.pyindex 6f8fca6e5f..de87d7320b 100644--- a/openhands/server/shared.py+++ b/openhands/server/shared.py@@ -11,8 +11,6 @@ import osimport socketiofrom dotenv import load_dotenv-from openhands.app_server.file_store import get_file_store-from openhands.app_server.file_store.files import FileStorefrom openhands.app_server.secrets.secrets_store import SecretsStorefrom openhands.app_server.settings.settings_store import SettingsStorefrom openhands.core.config import load_openhands_config@@ -29,10 +27,6 @@ assert isinstance(server_config_interface, ServerConfig), ('Loaded server config interface is not a ServerConfig, despite this being assumed')server_config: ServerConfig = server_config_interface-file_store: FileStore = get_file_store(- file_store_type=config.file_store,- file_store_path=config.file_store_path,-)client_manager = Noneredis_host = os.environ.get('REDIS_HOST')diff --git a/openhands/server/types.py b/openhands/server/types.pyindex e04d0bb1f0..1e52bf7984 100644--- a/openhands/server/types.py+++ b/openhands/server/types.py@@ -8,30 +8,15 @@# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.from abc import ABC, abstractmethodfrom enum import Enum-from typing import Any, ClassVar, Protocol+from typing import Anyclass AppMode(Enum):OPENHANDS = 'oss'SAAS = 'saas'- # Backwards-compatible alias (deprecated): prefer AppMode.OPENHANDS- OSS = 'oss'---class SessionMiddlewareInterface(Protocol):- """Protocol for session middleware classes."""-- pass-class ServerConfigInterface(ABC):- CONFIG_PATH: ClassVar[str | None]- APP_MODE: ClassVar[AppMode]- POSTHOG_CLIENT_KEY: ClassVar[str]- GITHUB_CLIENT_ID: ClassVar[str]- ATTACH_SESSION_MIDDLEWARE_PATH: ClassVar[str]-@abstractmethoddef verify_config(self) -> None:"""Verify configuration settings."""diff --git a/tests/unit/server/test_listen.py b/tests/unit/server/test_listen.pydeleted file mode 100644index f740af7622..0000000000--- a/tests/unit/server/test_listen.py+++ /dev/null@@ -1,76 +0,0 @@-from unittest.mock import patch--from openhands.core.config import OpenHandsConfig---# Mock StaticFiles-class MockStaticFiles:- def __init__(self, *args, **kwargs):- pass---# Patch necessary components before importing from listen-with (- patch('fastapi.staticfiles.StaticFiles', MockStaticFiles),-):- from openhands.server.file_config import (- is_extension_allowed,- load_file_upload_config,- )---def test_load_file_upload_config():- config = OpenHandsConfig(- file_uploads_max_file_size_mb=10,- file_uploads_restrict_file_types=True,- file_uploads_allowed_extensions=['.txt', '.pdf'],- )- max_size, restrict_types, allowed_extensions = load_file_upload_config(config)-- assert max_size == 10- assert restrict_types is True- assert set(allowed_extensions) == {'.txt', '.pdf'}---def test_load_file_upload_config_invalid_max_size():- config = OpenHandsConfig(- file_uploads_max_file_size_mb=-5,- file_uploads_restrict_file_types=False,- file_uploads_allowed_extensions=[],- )- with patch('openhands.server.shared.config', config):- max_size, restrict_types, allowed_extensions = load_file_upload_config()-- assert max_size == 0 # Should default to 0 when invalid- assert restrict_types is False- assert allowed_extensions == ['.*'] # Should default to '.*' when empty---def test_is_extension_allowed():- with (- patch('openhands.server.file_config.RESTRICT_FILE_TYPES', True),- patch('openhands.server.file_config.ALLOWED_EXTENSIONS', ['.txt', '.pdf']),- ):- assert is_extension_allowed('file.txt')- assert is_extension_allowed('file.pdf')- assert not is_extension_allowed('file.doc')- assert not is_extension_allowed('file')---def test_is_extension_allowed_no_restrictions():- with patch('openhands.server.file_config.RESTRICT_FILE_TYPES', False):- assert is_extension_allowed('file.txt')- assert is_extension_allowed('file.pdf')- assert is_extension_allowed('file.doc')- assert is_extension_allowed('file')---def test_is_extension_allowed_wildcard():- with (- patch('openhands.server.file_config.RESTRICT_FILE_TYPES', True),- patch('openhands.server.file_config.ALLOWED_EXTENSIONS', ['.*']),- ):- assert is_extension_allowed('file.txt')- assert is_extension_allowed('file.pdf')- assert is_extension_allowed('file.doc')- assert is_extension_allowed('file')