Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove dead MCP config factory + legacy SandboxConfig (V0 dead code cleanup) (#14215)

Tim O'Farrelld80a482db660
diff --git a/enterprise/server/mcp/mcp_config.py b/enterprise/server/mcp/mcp_config.py
deleted file mode 100644
index 7bfb1adde9..0000000000
--- a/enterprise/server/mcp/mcp_config.py
+++ /dev/null
@@ -1,52 +0,0 @@
-from typing import TYPE_CHECKING
-
-if TYPE_CHECKING:
- from openhands.core.config.openhands_config import OpenHandsConfig
-
-from openhands.core.config.mcp_config import (
- OpenHandsMCPConfig,
- RemoteMCPServer,
- StdioMCPServer,
-)
-from openhands.core.logger import openhands_logger as logger
-
-
-# We opt for Streamable HTTP over SSE connection to the main app server's MCP
-# Reasoning:
-# 1. Better performance over SSE
-# 2. Allows stateless MCP client connections, essential for distributed server environments
-#
-# The second point is very important - any long lived stateful connections (like SSE) will
-# require bespoke implementation to make sure all subsequent requests hit the same replica. It is
-# also not resistant to replica pod restarts (it will kill the connection and there's no recovering from it)
-# NOTE: these details are specific to the MCP protocol
-class SaaSOpenHandsMCPConfig(OpenHandsMCPConfig):
- @staticmethod
- async def create_default_mcp_server_config(
- host: str, config: 'OpenHandsConfig', user_id: str | None = None
- ) -> dict[str, RemoteMCPServer | StdioMCPServer]:
- """Return a dict of default MCP server entries for SaaS mode."""
- from storage.api_key_store import ApiKeyStore
-
- api_key_store = ApiKeyStore.get_instance()
- if user_id:
- api_key = await api_key_store.retrieve_mcp_api_key(user_id)
-
- if not api_key:
- api_key = await api_key_store.create_api_key(
- user_id, 'MCP_API_KEY', None
- )
-
- if not api_key:
- logger.error(f'Could not provision MCP API Key for user: {user_id}')
- return {}
-
- return {
- 'openhands': RemoteMCPServer(
- url=f'https://{host}/mcp/mcp',
- transport='http',
- auth=api_key,
- timeout=60,
- )
- }
- return {}
diff --git a/openhands/app_server/settings/settings_models.py b/openhands/app_server/settings/settings_models.py
index 85db53e4a3..859b380a68 100644
--- a/openhands/app_server/settings/settings_models.py
+++ b/openhands/app_server/settings/settings_models.py
@@ -392,7 +392,6 @@ class Settings(BaseModel):
return Settings(
language='en',
- remote_runtime_resource_factor=app_config.sandbox.remote_runtime_resource_factor,
search_api_key=app_config.search_api_key,
max_budget_per_task=app_config.max_budget_per_task,
# Always LLM for config-file-sourced settings
diff --git a/openhands/app_server/settings/settings_router.py b/openhands/app_server/settings/settings_router.py
index f361d06b74..9b09f4b3d4 100644
--- a/openhands/app_server/settings/settings_router.py
+++ b/openhands/app_server/settings/settings_router.py
@@ -237,12 +237,6 @@ async def store_settings(
if settings.disabled_skills is None:
settings.disabled_skills = existing_settings.disabled_skills
- # Update sandbox config with new settings
- if settings.remote_runtime_resource_factor is not None:
- config.sandbox.remote_runtime_resource_factor = (
- settings.remote_runtime_resource_factor
- )
-
# Update git configuration with new settings
git_config_updated = False
if settings.git_user_name is not None:
diff --git a/openhands/core/config/__init__.py b/openhands/core/config/__init__.py
index fb80331ec9..a0cd0c1f95 100644
--- a/openhands/core/config/__init__.py
+++ b/openhands/core/config/__init__.py
@@ -9,7 +9,6 @@ from openhands.core.config.config_utils import (
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.mcp_config import MCPConfig
from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.sandbox_config import SandboxConfig
from openhands.core.config.utils import (
finalize_config,
get_llm_config_arg,
@@ -26,7 +25,6 @@ __all__ = [
'OpenHandsConfig',
'MCPConfig',
'LLMConfig',
- 'SandboxConfig',
'load_openhands_config',
'load_from_env',
'load_from_toml',
diff --git a/openhands/core/config/mcp_config.py b/openhands/core/config/mcp_config.py
index 9c381dd35d..0904a10b54 100644
--- a/openhands/core/config/mcp_config.py
+++ b/openhands/core/config/mcp_config.py
@@ -1,31 +1,20 @@
"""MCP configuration β€” thin wrappers around the SDK MCPConfig from *fastmcp*.
All server configuration uses the unified ``MCPConfig.mcpServers`` dict.
-Legacy helpers (``from_toml_section``, ``merge``) are provided for
-config.toml parsing and server merging.
+Legacy helpers (``from_toml_section``) are provided for config.toml parsing.
"""
from __future__ import annotations
-import os
import shlex
-from typing import TYPE_CHECKING, Any
+from typing import Any
from fastmcp.mcp_config import MCPConfig, RemoteMCPServer, StdioMCPServer
-if TYPE_CHECKING:
- from openhands.core.config.openhands_config import OpenHandsConfig
-
-from openhands.core.logger import openhands_logger as logger
-from openhands.utils.import_utils import get_impl
-
__all__ = [
'MCPConfig',
'RemoteMCPServer',
'StdioMCPServer',
- 'OpenHandsMCPConfig',
- 'OpenHandsMCPConfigImpl',
- 'merge_mcp_configs',
'mcp_config_from_toml',
]
@@ -35,13 +24,6 @@ __all__ = [
# ---------------------------------------------------------------------------
-def merge_mcp_configs(base: MCPConfig, other: MCPConfig) -> MCPConfig:
- """Return a new MCPConfig with servers from both configs merged."""
- merged = dict(base.mcpServers)
- merged.update(other.mcpServers)
- return MCPConfig(mcpServers=merged)
-
-
def _parse_stdio_args(v: Any) -> list[str]:
"""Parse stdio args from a string using shlex or return list as-is."""
if isinstance(v, str):
@@ -109,65 +91,3 @@ def mcp_config_from_toml(data: dict[str, Any]) -> dict[str, MCPConfig]:
)
return {'mcp': MCPConfig(mcpServers=servers)}
-
-
-# ---------------------------------------------------------------------------
-# OpenHands default MCP server factory
-# ---------------------------------------------------------------------------
-
-
-class OpenHandsMCPConfig:
- """Factory for the default OpenHands MCP server entries."""
-
- @staticmethod
- def add_search_engine(
- app_config: 'OpenHandsConfig',
- ) -> dict[str, StdioMCPServer] | None:
- """Return a tavily stdio server entry if a Tavily API key is configured."""
- if (
- app_config.search_api_key
- and app_config.search_api_key.get_secret_value().startswith('tvly-')
- ):
- logger.info('Adding search engine to MCP config')
- return {
- 'tavily': StdioMCPServer(
- command='npx',
- args=['-y', '[email protected]'],
- env={
- 'TAVILY_API_KEY': app_config.search_api_key.get_secret_value()
- },
- )
- }
- logger.warning('No search engine API key found, skipping search engine')
- return None
-
- @staticmethod
- async def create_default_mcp_server_config(
- host: str, config: 'OpenHandsConfig', user_id: str | None = None
- ) -> dict[str, RemoteMCPServer | StdioMCPServer]:
- """Return a dict of default MCP server entries to merge into config.mcp.
-
- Returns:
- dict mapping server names to their configs.
- """
- servers: dict[str, RemoteMCPServer | StdioMCPServer] = {}
-
- search = OpenHandsMCPConfig.add_search_engine(config)
- if search:
- servers.update(search)
-
- servers['openhands'] = RemoteMCPServer(
- url=f'http://{host}/mcp/mcp',
- transport='http',
- timeout=60,
- )
-
- return servers
-
-
-openhands_mcp_config_cls = os.environ.get(
- 'OPENHANDS_MCP_CONFIG_CLS',
- 'openhands.core.config.mcp_config.OpenHandsMCPConfig',
-)
-
-OpenHandsMCPConfigImpl = get_impl(OpenHandsMCPConfig, openhands_mcp_config_cls)
diff --git a/openhands/core/config/openhands_config.py b/openhands/core/config/openhands_config.py
index 8d75104878..76a4cf2581 100644
--- a/openhands/core/config/openhands_config.py
+++ b/openhands/core/config/openhands_config.py
@@ -19,7 +19,6 @@ from openhands.core.config.config_utils import (
)
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.mcp_config import MCPConfig
-from openhands.core.config.sandbox_config import SandboxConfig
class OpenHandsConfig(BaseModel):
@@ -29,7 +28,6 @@ class OpenHandsConfig(BaseModel):
llms: Dictionary mapping LLM names to their configurations.
The default configuration is stored under the 'llm' key.
default_agent: Name of the default agent to use.
- sandbox: Sandbox configuration settings.
runtime: Runtime environment identifier.
file_store: Type of file store to use.
file_store_path: Path to the file store.
@@ -61,7 +59,6 @@ class OpenHandsConfig(BaseModel):
llms: dict[str, LLMConfig] = Field(default_factory=dict)
default_agent: str = Field(default=OH_DEFAULT_AGENT)
- sandbox: SandboxConfig = Field(default_factory=SandboxConfig)
runtime: str = Field(default='docker')
file_store: str = Field(default='local')
file_store_path: str = Field(default='~/.openhands')
diff --git a/openhands/core/config/sandbox_config.py b/openhands/core/config/sandbox_config.py
deleted file mode 100644
index ea6be162a5..0000000000
--- a/openhands/core/config/sandbox_config.py
+++ /dev/null
@@ -1,132 +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
-import os
-
-from pydantic import BaseModel, ConfigDict, Field, ValidationError, model_validator
-
-from openhands.core.logger import openhands_logger as logger
-
-
-class SandboxConfig(BaseModel):
- """Configuration for the sandbox.
-
- Attributes:
- remote_runtime_api_url: The hostname for the Remote Runtime API.
- local_runtime_url: The default hostname for the local runtime. You may want to change to http://host.docker.internal for DIND environments
- base_container_image: The base container image from which to build the runtime image.
- runtime_container_image: The runtime container image to use.
- user_id: The user ID for the sandbox.
- timeout: The timeout for the default sandbox action execution.
- remote_runtime_init_timeout: The timeout for the remote runtime to start.
- remote_runtime_api_timeout: The timeout for the remote runtime API requests.
- remote_runtime_enable_retries: Whether to enable retries (on recoverable errors like requests.ConnectionError) for the remote runtime API requests.
- enable_auto_lint: Whether to enable auto-lint.
- use_host_network: Whether to use the host network.
- additional_networks: A list of additional Docker networks to connect to
- runtime_binding_address: The binding address for the runtime ports. It specifies which network interface on the host machine Docker should bind the runtime ports to.
- initialize_plugins: Whether to initialize plugins.
- force_rebuild_runtime: Whether to force rebuild the runtime image.
- runtime_extra_deps: The extra dependencies to install in the runtime image (typically used for evaluation).
- This will be rendered into the end of the Dockerfile that builds the runtime image.
- It can contain any valid shell commands (e.g., pip install numpy).
- The path to the interpreter is available as $OH_INTERPRETER_PATH,
- which can be used to install dependencies for the OH-specific Python interpreter.
- runtime_startup_env_vars: The environment variables to set at the launch of the runtime.
- This is a dictionary of key-value pairs.
- This is useful for setting environment variables that are needed by the runtime.
- For example, for specifying the base url of website for browsergym evaluation.
- browsergym_eval_env: The BrowserGym environment to use for evaluation.
- Default is None for general purpose browsing. Check evaluation/miniwob and evaluation/webarena for examples.
- platform: The platform on which the image should be built. Default is None.
- remote_runtime_resource_factor: Factor to scale the resource allocation for remote runtime.
- Must be one of [1, 2, 4, 8]. Will only be used if the runtime is remote.
- enable_gpu: Whether to enable GPU.
- docker_runtime_kwargs: Additional keyword arguments to pass to the Docker runtime when running containers.
- This should be a Python dictionary literal string that will be parsed into a dictionary.
- trusted_dirs: List of directories that can be trusted to run the OpenHands CLI.
- vscode_port: The port to use for VSCode. If None, a random port will be chosen.
- This is useful when deploying OpenHands in a remote machine where you need to expose a specific port.
- """
-
- remote_runtime_api_url: str | None = Field(default='http://localhost:8000')
- local_runtime_url: str = Field(default='http://localhost')
- keep_runtime_alive: bool = Field(default=False)
- pause_closed_runtimes: bool = Field(default=True)
- rm_all_containers: bool = Field(default=False)
- api_key: str | None = Field(default=None)
- base_container_image: str | None = Field(
- default='nikolaik/python-nodejs:python3.12-nodejs22-slim'
- )
- runtime_container_image: str | None = Field(default=None)
- user_id: int = Field(default=os.getuid() if hasattr(os, 'getuid') else 1000)
- logger.debug(f'SandboxConfig user_id default: {user_id}')
- timeout: int = Field(default=120)
- remote_runtime_init_timeout: int = Field(default=180)
- remote_runtime_api_timeout: int = Field(default=180)
- remote_runtime_enable_retries: bool = Field(default=True)
- remote_runtime_class: str | None = Field(
- default=None
- ) # can be "None" (default to gvisor) or "sysbox" (support docker inside runtime + more stable)
- enable_auto_lint: bool = Field(
- default=False
- ) # once enabled, OpenHands would lint files after editing
- use_host_network: bool = Field(default=False)
- additional_networks: list[str] = Field(default=[])
- runtime_binding_address: str = Field(default='0.0.0.0')
- runtime_extra_build_args: list[str] | None = Field(default=None)
- initialize_plugins: bool = Field(default=True)
- force_rebuild_runtime: bool = Field(default=False)
- runtime_extra_deps: str | None = Field(default=None)
- runtime_startup_env_vars: dict[str, str] = Field(default_factory=dict)
- browsergym_eval_env: str | None = Field(default=None)
- platform: str | None = Field(default=None)
- close_delay: int = Field(
- default=3600,
- description='The delay in seconds before closing the sandbox after the agent is done.',
- )
- remote_runtime_resource_factor: int = Field(default=1)
- enable_gpu: bool = Field(default=False)
- docker_runtime_kwargs: dict | None = Field(default=None)
- selected_repo: str | None = Field(default=None)
- trusted_dirs: list[str] = Field(default_factory=list)
- vscode_port: int | None = Field(default=None)
- volumes: str | None = Field(
- default=None,
- description="Volume mounts in the format 'host_path:container_path[:mode]', e.g. '/my/host/dir:/workspace:rw'. Multiple mounts can be specified using commas, e.g. '/path1:/workspace/path1,/path2:/workspace/path2:ro'",
- )
-
- cuda_visible_devices: str | None = Field(default=None)
- model_config = ConfigDict(extra='forbid')
-
- @classmethod
- def from_toml_section(cls, data: dict) -> dict[str, 'SandboxConfig']:
- """Create a mapping of SandboxConfig instances from a toml dictionary representing the [sandbox] section.
-
- The configuration is built from all keys in data.
-
- Returns:
- dict[str, SandboxConfig]: A mapping where the key "sandbox" corresponds to the [sandbox] configuration
- """
- # Initialize the result mapping
- sandbox_mapping: dict[str, SandboxConfig] = {}
-
- # Try to create the configuration instance
- try:
- sandbox_mapping['sandbox'] = cls.model_validate(data)
- except ValidationError as e:
- raise ValueError(f'Invalid sandbox configuration: {e}')
-
- return sandbox_mapping
-
- @model_validator(mode='after')
- def set_default_base_image(self) -> 'SandboxConfig':
- if self.base_container_image is None:
- self.base_container_image = (
- 'nikolaik/python-nodejs:python3.12-nodejs22-slim'
- )
- return self
diff --git a/openhands/core/config/utils.py b/openhands/core/config/utils.py
index 66f3a51d8d..224d3acbd6 100644
--- a/openhands/core/config/utils.py
+++ b/openhands/core/config/utils.py
@@ -8,7 +8,6 @@
import argparse
import os
import pathlib
-import platform
import sys
from ast import literal_eval
from types import UnionType
@@ -26,7 +25,6 @@ from openhands.core.config.arg_utils import get_headless_parser
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.mcp_config import mcp_config_from_toml
from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.sandbox_config import SandboxConfig
JWT_SECRET = '.jwt_secret'
load_dotenv()
@@ -193,21 +191,6 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None
f'Cannot parse [llm] config from toml, values have not been applied.\nError: {e}'
)
- # Process sandbox section if present
- if 'sandbox' in toml_config:
- try:
- sandbox_mapping = SandboxConfig.from_toml_section(toml_config['sandbox'])
- # We only use the base sandbox config for now
- if 'sandbox' in sandbox_mapping:
- cfg.sandbox = sandbox_mapping['sandbox']
- except (TypeError, KeyError, ValidationError) as e:
- logger.openhands_logger.warning(
- f'Cannot parse [sandbox] config from toml, values have not been applied.\nError: {e}'
- )
- except ValueError as e:
- # Re-raise ValueError from SandboxConfig.from_toml_section
- raise ValueError('Error in [sandbox] section in config.toml') from e
-
# Process MCP sections if present
if 'mcp' in toml_config:
try:
@@ -222,20 +205,19 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None
raise ValueError('Error in MCP sections in config.toml')
# Check for unknown sections
- # Note: 'agent', 'extended', 'condenser', 'model_routing', 'kubernetes',
- # and 'security' are kept for backwards compatibility with old config
+ # Note: legacy sections are kept for backwards compatibility with old config
# files - they are silently ignored
known_sections = {
'core',
'llm',
- 'sandbox',
'mcp',
+ 'sandbox', # Legacy, ignored
+ 'security', # Legacy, ignored
'agent', # Legacy, ignored
'extended', # Legacy, ignored
'condenser', # Legacy, ignored
'kubernetes', # Legacy, ignored
'model_routing', # Legacy, ignored
- 'security', # Legacy, ignored
}
for key in toml_config:
if key.lower() not in known_sections:
@@ -254,50 +236,8 @@ def get_or_create_jwt_secret(file_store: FileStore) -> str:
def finalize_config(cfg: OpenHandsConfig) -> None:
"""More tweaks to the config after it's been loaded."""
- # Handle the sandbox.volumes parameter
- if cfg.sandbox.volumes is not None:
- # Split by commas to handle multiple mounts
- mounts = cfg.sandbox.volumes.split(',')
-
- # Check if any mount explicitly targets /workspace
- workspace_mount_found = False
- for mount in mounts:
- parts = mount.split(':')
- if len(parts) >= 2 and parts[1] == '/workspace':
- workspace_mount_found = True
- host_path = os.path.abspath(parts[0])
-
- # Set the workspace_mount_path and workspace_mount_path_in_sandbox
- cfg.workspace_mount_path = host_path
- cfg.workspace_mount_path_in_sandbox = '/workspace'
-
- # Also set workspace_base
- cfg.workspace_base = host_path
- break
-
- # If no explicit /workspace mount was found, don't set any workspace mount
- # This allows users to mount volumes without affecting the workspace
- if not workspace_mount_found:
- logger.openhands_logger.debug(
- 'No explicit /workspace mount found in SANDBOX_VOLUMES. '
- 'Using default workspace path in sandbox.'
- )
- # Ensure workspace_mount_path and workspace_base are None to avoid
- # unintended mounting behavior
- cfg.workspace_mount_path = None
- cfg.workspace_base = None
-
- # Validate all mounts
- for mount in mounts:
- parts = mount.split(':')
- if len(parts) < 2 or len(parts) > 3:
- raise ValueError(
- f'Invalid mount format in sandbox.volumes: {mount}. '
- f"Expected format: 'host_path:container_path[:mode]', e.g. '/my/host/dir:/workspace:rw'"
- )
-
# Handle the deprecated workspace_* parameters
- elif cfg.workspace_base is not None or cfg.workspace_mount_path is not None:
+ if cfg.workspace_base is not None or cfg.workspace_mount_path is not None:
if cfg.workspace_base is not None:
cfg.workspace_base = os.path.abspath(cfg.workspace_base)
if cfg.workspace_mount_path is None:
@@ -312,12 +252,6 @@ def finalize_config(cfg: OpenHandsConfig) -> None:
for llm in cfg.llms.values():
llm.log_completions_folder = os.path.abspath(llm.log_completions_folder)
- if cfg.sandbox.use_host_network and platform.system() == 'Darwin':
- logger.openhands_logger.warning(
- 'Please upgrade to Docker Desktop 4.29.0 or later to use host network mode on macOS. '
- 'See https://github.com/docker/roadmap/issues/238#issuecomment-2044688144 for more information.'
- )
-
# make sure cache dir exists
if cfg.cache_dir:
pathlib.Path(cfg.cache_dir).mkdir(parents=True, exist_ok=True)
@@ -490,8 +424,4 @@ def setup_config_from_args(args: argparse.Namespace) -> OpenHandsConfig:
if hasattr(args, 'max_budget_per_task') and args.max_budget_per_task is not None:
config.max_budget_per_task = args.max_budget_per_task
- # Read selected repository in config for use by CLI and main.py
- if hasattr(args, 'selected_repo') and args.selected_repo is not None:
- config.sandbox.selected_repo = args.selected_repo
-
return config
diff --git a/tests/unit/core/config/test_config.py b/tests/unit/core/config/test_config.py
index bbf6a66e7b..0828998788 100644
--- a/tests/unit/core/config/test_config.py
+++ b/tests/unit/core/config/test_config.py
@@ -46,26 +46,18 @@ def default_config(monkeypatch):
def test_compat_env_to_config(monkeypatch, setup_env):
# Use `monkeypatch` to set environment variables for this specific test
- monkeypatch.setenv('SANDBOX_VOLUMES', '/repos/openhands/workspace:/workspace:rw')
monkeypatch.setenv('LLM_API_KEY', 'sk-proj-rgMV0...')
monkeypatch.setenv('LLM_MODEL', 'gpt-4o')
monkeypatch.setenv('DEFAULT_AGENT', 'CodeActAgent')
- monkeypatch.setenv('SANDBOX_TIMEOUT', '10')
config = OpenHandsConfig()
load_from_env(config, os.environ)
finalize_config(config)
- assert config.sandbox.volumes == '/repos/openhands/workspace:/workspace:rw'
- # Check that the old parameters are set for backward compatibility
- assert config.workspace_base == os.path.abspath('/repos/openhands/workspace')
- assert config.workspace_mount_path == os.path.abspath('/repos/openhands/workspace')
- assert config.workspace_mount_path_in_sandbox == '/workspace'
assert isinstance(config.get_llm_config(), LLMConfig)
assert config.get_llm_config().api_key.get_secret_value() == 'sk-proj-rgMV0...'
assert config.get_llm_config().model == 'gpt-4o'
assert config.default_agent == 'CodeActAgent'
- assert config.sandbox.timeout == 10
def test_load_from_old_style_env(monkeypatch, default_config):
@@ -74,7 +66,6 @@ def test_load_from_old_style_env(monkeypatch, default_config):
monkeypatch.setenv('DEFAULT_AGENT', 'BrowsingAgent')
# Using deprecated WORKSPACE_BASE to test backward compatibility
monkeypatch.setenv('WORKSPACE_BASE', '/opt/files/workspace')
- monkeypatch.setenv('SANDBOX_BASE_CONTAINER_IMAGE', 'custom_image')
load_from_env(default_config, os.environ)
@@ -84,7 +75,6 @@ def test_load_from_old_style_env(monkeypatch, default_config):
assert default_config.workspace_base == '/opt/files/workspace'
assert default_config.workspace_mount_path is None # before finalize_config
assert default_config.workspace_mount_path_in_sandbox is not None
- assert default_config.sandbox.base_container_image == 'custom_image'
def test_load_from_new_style_toml(default_config, temp_toml_file):
@@ -100,10 +90,6 @@ api_key = "toml-api-key"
model = "some-cheap-model"
api_key = "cheap-model-api-key"
-[sandbox]
-timeout = 1
-volumes = "/opt/files2/workspace:/workspace:rw"
-
[core]
default_agent = "TestAgent"
"""
@@ -116,21 +102,6 @@ default_agent = "TestAgent"
assert default_config.get_llm_config().model == 'test-model'
assert default_config.get_llm_config().api_key.get_secret_value() == 'toml-api-key'
- assert default_config.sandbox.volumes == '/opt/files2/workspace:/workspace:rw'
- assert default_config.sandbox.timeout == 1
-
- assert default_config.workspace_mount_path is None
- assert default_config.workspace_mount_path_in_sandbox is not None
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
-
- finalize_config(default_config)
-
- # after finalize_config, workspace_mount_path is set based on sandbox.volumes
- assert default_config.workspace_mount_path == os.path.abspath(
- '/opt/files2/workspace'
- )
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
-
def test_llm_config_native_tool_calling(default_config, temp_toml_file, monkeypatch):
# default is None
@@ -175,7 +146,6 @@ native_tool_calling = true
def test_env_overrides_compat_toml(monkeypatch, default_config, temp_toml_file):
# test that environment variables override TOML values using monkeypatch
- # uses a toml file with sandbox_vars instead of a sandbox section
with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
toml_file.write("""
[llm]
@@ -184,151 +154,19 @@ api_key = "toml-api-key"
[core]
disable_color = true
-
-[sandbox]
-volumes = "/opt/files3/workspace:/workspace:rw"
-timeout = 500
-user_id = 1001
""")
monkeypatch.setenv('LLM_API_KEY', 'env-api-key')
- monkeypatch.setenv('SANDBOX_VOLUMES', '/tmp/test:/workspace:ro')
- monkeypatch.setenv('SANDBOX_TIMEOUT', '1000')
- monkeypatch.setenv('SANDBOX_USER_ID', '1002')
monkeypatch.delenv('LLM_MODEL', raising=False)
load_from_toml(default_config, temp_toml_file)
-
- assert default_config.workspace_mount_path is None
-
load_from_env(default_config, os.environ)
assert os.environ.get('LLM_MODEL') is None
assert default_config.get_llm_config().model == 'test-model'
assert default_config.get_llm_config('llm').model == 'test-model'
assert default_config.get_llm_config().api_key.get_secret_value() == 'env-api-key'
-
- # Environment variable should override TOML value
- assert default_config.sandbox.volumes == '/tmp/test:/workspace:ro'
- assert default_config.workspace_mount_path is None
-
assert default_config.disable_color is True
- assert default_config.sandbox.timeout == 1000
- assert default_config.sandbox.user_id == 1002
-
- finalize_config(default_config)
- # after finalize_config, workspace_mount_path is set based on the sandbox.volumes
- assert default_config.workspace_mount_path == os.path.abspath('/tmp/test')
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
-
-
-def test_env_overrides_sandbox_toml(monkeypatch, default_config, temp_toml_file):
- # test that environment variables override TOML values using monkeypatch
- # uses a toml file with a sandbox section
- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
- toml_file.write("""
-[llm]
-model = "test-model"
-api_key = "toml-api-key"
-
-[core]
-
-[sandbox]
-volumes = "/opt/files3/workspace:/workspace:rw"
-timeout = 500
-user_id = 1001
-""")
-
- monkeypatch.setenv('LLM_API_KEY', 'env-api-key')
- monkeypatch.setenv('SANDBOX_VOLUMES', '/tmp/test:/workspace:ro')
- monkeypatch.setenv('SANDBOX_TIMEOUT', '1000')
- monkeypatch.setenv('SANDBOX_USER_ID', '1002')
- monkeypatch.delenv('LLM_MODEL', raising=False)
-
- load_from_toml(default_config, temp_toml_file)
-
- assert default_config.workspace_mount_path is None
-
- # before load_from_env, values are set to the values from the toml file
- assert default_config.get_llm_config().api_key.get_secret_value() == 'toml-api-key'
- assert default_config.sandbox.volumes == '/opt/files3/workspace:/workspace:rw'
- assert default_config.sandbox.timeout == 500
- assert default_config.sandbox.user_id == 1001
-
- load_from_env(default_config, os.environ)
-
- # values from env override values from toml
- assert os.environ.get('LLM_MODEL') is None
- assert default_config.get_llm_config().model == 'test-model'
- assert default_config.get_llm_config().api_key.get_secret_value() == 'env-api-key'
- assert default_config.sandbox.volumes == '/tmp/test:/workspace:ro'
- assert default_config.sandbox.timeout == 1000
- assert default_config.sandbox.user_id == 1002
-
- finalize_config(default_config)
- # after finalize_config, workspace_mount_path is set based on sandbox.volumes
- assert default_config.workspace_mount_path == os.path.abspath('/tmp/test')
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
-
-
-def test_sandbox_config_from_toml(monkeypatch, default_config, temp_toml_file):
- # Test loading configuration from a new-style TOML file
- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
- toml_file.write(
- """
-[core]
-
-[llm]
-model = "test-model"
-
-[sandbox]
-volumes = "/opt/files/workspace:/workspace:rw"
-timeout = 1
-base_container_image = "custom_image"
-user_id = 1001
-"""
- )
- monkeypatch.setattr(os, 'environ', {})
- load_from_toml(default_config, temp_toml_file)
- load_from_env(default_config, os.environ)
- finalize_config(default_config)
-
- assert default_config.get_llm_config().model == 'test-model'
- assert default_config.sandbox.volumes == '/opt/files/workspace:/workspace:rw'
- assert default_config.workspace_mount_path == os.path.abspath(
- '/opt/files/workspace'
- )
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
- assert default_config.sandbox.timeout == 1
- assert default_config.sandbox.base_container_image == 'custom_image'
- assert default_config.sandbox.user_id == 1001
-
-
-def test_load_from_env_with_list(monkeypatch, default_config):
- """Test loading list values from environment variables, particularly SANDBOX_RUNTIME_EXTRA_BUILD_ARGS."""
- # Set the environment variable with a list-formatted string
- monkeypatch.setenv(
- 'SANDBOX_RUNTIME_EXTRA_BUILD_ARGS',
- '['
- + ' "--add-host=host.docker.internal:host-gateway",'
- + ' "--build-arg=https_proxy=https://my-proxy:912",'
- + ']',
- )
-
- # Load configuration from environment
- load_from_env(default_config, os.environ)
-
- # Verify that the list was correctly parsed
- assert isinstance(default_config.sandbox.runtime_extra_build_args, list)
- assert len(default_config.sandbox.runtime_extra_build_args) == 2
- assert (
- '--add-host=host.docker.internal:host-gateway'
- in default_config.sandbox.runtime_extra_build_args
- )
- assert (
- '--build-arg=https_proxy=https://my-proxy:912'
- in default_config.sandbox.runtime_extra_build_args
- )
def test_security_section_in_toml_is_silently_ignored(default_config, temp_toml_file):
@@ -367,62 +205,9 @@ def test_defaults_dict_after_updates(default_config):
defaults_after_updates = updated_config.defaults_dict
assert defaults_after_updates['default_agent']['default'] == 'CodeActAgent'
assert defaults_after_updates['workspace_mount_path']['default'] is None
- assert defaults_after_updates['sandbox']['timeout']['default'] == 120
- assert (
- defaults_after_updates['sandbox']['base_container_image']['default']
- == 'nikolaik/python-nodejs:python3.12-nodejs22-slim'
- )
assert defaults_after_updates == initial_defaults
-def test_sandbox_volumes(monkeypatch, default_config):
- # Test SANDBOX_VOLUMES with multiple mounts (no explicit /workspace mount)
- monkeypatch.setenv(
- 'SANDBOX_VOLUMES',
- '/host/path1:/container/path1,/host/path2:/container/path2:ro',
- )
- # Clear any existing workspace mount path to test default behavior
- monkeypatch.delenv('WORKSPACE_MOUNT_PATH_IN_SANDBOX', raising=False)
-
- load_from_env(default_config, os.environ)
- finalize_config(default_config)
-
- # Check that sandbox.volumes is set correctly
- assert (
- default_config.sandbox.volumes
- == '/host/path1:/container/path1,/host/path2:/container/path2:ro'
- )
-
- # With the new behavior, workspace_base and workspace_mount_path should be None
- # when no explicit /workspace mount is found
- assert default_config.workspace_base is None
- assert default_config.workspace_mount_path is None
- assert (
- default_config.workspace_mount_path_in_sandbox == '/workspace'
- ) # Default value
-
-
-def test_sandbox_volumes_with_mode(monkeypatch, default_config):
- # Test SANDBOX_VOLUMES with read-only mode (no explicit /workspace mount)
- monkeypatch.setenv('SANDBOX_VOLUMES', '/host/path1:/container/path1:ro')
- # Clear any existing workspace mount path to test default behavior
- monkeypatch.delenv('WORKSPACE_MOUNT_PATH_IN_SANDBOX', raising=False)
-
- load_from_env(default_config, os.environ)
- finalize_config(default_config)
-
- # Check that sandbox.volumes is set correctly
- assert default_config.sandbox.volumes == '/host/path1:/container/path1:ro'
-
- # With the new behavior, workspace_base and workspace_mount_path should be None
- # when no explicit /workspace mount is found
- assert default_config.workspace_base is None
- assert default_config.workspace_mount_path is None
- assert (
- default_config.workspace_mount_path_in_sandbox == '/workspace'
- ) # Default value
-
-
def test_invalid_toml_format(monkeypatch, temp_toml_file, default_config):
# Invalid TOML format doesn't break the configuration
monkeypatch.setenv('LLM_MODEL', 'gpt-5-turbo-1106')
@@ -455,7 +240,6 @@ def test_load_from_toml_file_not_found(default_config):
# Verify that config object maintains default values
assert default_config.get_llm_config() is not None
- assert default_config.sandbox is not None
def test_core_not_in_toml(default_config, temp_toml_file):
@@ -467,17 +251,10 @@ def test_core_not_in_toml(default_config, temp_toml_file):
toml_file.write("""
[llm]
model = "test-model"
-
-[sandbox]
-timeout = 1
-base_container_image = "custom_image"
-user_id = 1001
""")
load_from_toml(default_config, temp_toml_file)
assert default_config.get_llm_config().model == 'test-model'
- assert default_config.sandbox.base_container_image == 'custom_image'
- assert default_config.sandbox.user_id == 1001
def test_load_from_toml_partial_invalid(default_config, temp_toml_file, caplog):
@@ -485,7 +262,7 @@ def test_load_from_toml_partial_invalid(default_config, temp_toml_file, caplog):
This ensures that:
1. Valid configuration sections are properly loaded
- 2. Invalid fields in sandbox sections raise ValueError
+ 2. Invalid fields in LLM section log a warning but don't crash
3. The config object maintains correct values for valid fields
"""
with open(temp_toml_file, 'w', encoding='utf-8') as f:
@@ -500,9 +277,6 @@ model = "gpt-4"
[agent]
enable_prompt_extensions = true
-
-[sandbox]
-invalid_field_in_sandbox = "test"
""")
# Create a string buffer to capture log output
@@ -514,20 +288,14 @@ invalid_field_in_sandbox = "test"
openhands_logger.addHandler(handler)
try:
- # Since sandbox_config.from_toml_section now raises ValueError for invalid fields,
- # we need to catch that exception
- with pytest.raises(ValueError) as excinfo:
- load_from_toml(default_config, temp_toml_file)
-
- # Verify the error message mentions the invalid sandbox field
- assert 'Error in [sandbox] section in config.toml' in str(excinfo.value)
+ load_from_toml(default_config, temp_toml_file)
log_content = log_output.getvalue()
- # The LLM config should still log a warning but not raise an exception
+ # The LLM config should log a warning but not raise an exception
assert 'Cannot parse [llm] config from toml' in log_content
- # Verify valid configurations are loaded before the error was raised
+ # Verify valid configurations are loaded
assert default_config.debug is True
finally:
openhands_logger.removeHandler(handler)
@@ -565,60 +333,6 @@ def test_cache_dir_creation(default_config, tmpdir):
assert os.path.exists(default_config.cache_dir)
-def test_sandbox_volumes_with_workspace(default_config):
- """Test that sandbox.volumes with explicit /workspace mount works correctly."""
- default_config.sandbox.volumes = '/home/user/mydir:/workspace:rw,/data:/data:ro'
- finalize_config(default_config)
- assert default_config.workspace_mount_path == '/home/user/mydir'
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
- assert default_config.workspace_base == '/home/user/mydir'
-
-
-def test_sandbox_volumes_without_workspace(default_config):
- """Test that sandbox.volumes without explicit /workspace mount doesn't set workspace paths."""
- default_config.sandbox.volumes = '/data:/data:ro,/models:/models:ro'
- finalize_config(default_config)
- assert default_config.workspace_mount_path is None
- assert default_config.workspace_base is None
- assert (
- default_config.workspace_mount_path_in_sandbox == '/workspace'
- ) # Default value remains unchanged
-
-
-def test_sandbox_volumes_with_workspace_not_first(default_config):
- """Test that sandbox.volumes with /workspace mount not as first entry works correctly."""
- default_config.sandbox.volumes = (
- '/data:/data:ro,/home/user/mydir:/workspace:rw,/models:/models:ro'
- )
- finalize_config(default_config)
- assert default_config.workspace_mount_path == '/home/user/mydir'
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
- assert default_config.workspace_base == '/home/user/mydir'
-
-
-def test_sandbox_volumes_toml(default_config, temp_toml_file):
- """Test that volumes configuration under [sandbox] works correctly."""
- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
- toml_file.write("""
-[sandbox]
-volumes = "/home/user/mydir:/workspace:rw,/data:/data:ro"
-timeout = 1
-""")
-
- load_from_toml(default_config, temp_toml_file)
- finalize_config(default_config)
-
- # Check that sandbox.volumes is set correctly
- assert (
- default_config.sandbox.volumes
- == '/home/user/mydir:/workspace:rw,/data:/data:ro'
- )
- assert default_config.workspace_mount_path == '/home/user/mydir'
- assert default_config.workspace_mount_path_in_sandbox == '/workspace'
- assert default_config.workspace_base == '/home/user/mydir'
- assert default_config.sandbox.timeout == 1
-
-
def test_api_keys_repr_str():
# Test LLMConfig
llm_config = LLMConfig(
diff --git a/tests/unit/core/config/test_config_dict_casting.py b/tests/unit/core/config/test_config_dict_casting.py
deleted file mode 100644
index bcc6c0c457..0000000000
--- a/tests/unit/core/config/test_config_dict_casting.py
+++ /dev/null
@@ -1,39 +0,0 @@
-import os
-
-import pytest
-
-from openhands.core.config import OpenHandsConfig, load_from_env
-
-
-def test_load_from_env_with_dict(monkeypatch, default_config):
- """Test loading dict values from environment variables, particularly DOCKER_RUNTIME_KWARGS."""
- # Set the environment variable with a dict-formatted string using Python literal syntax
- monkeypatch.setenv(
- 'SANDBOX_DOCKER_RUNTIME_KWARGS',
- '{'
- + ' "mem_limit": "2g",'
- + ' "cpu_count": 2,'
- + ' "environment": {"TEST_VAR": "test_value"}'
- + '}',
- )
-
- # Load configuration from environment
- load_from_env(default_config, os.environ)
-
- # Verify that the dict was correctly parsed
- assert isinstance(default_config.sandbox.docker_runtime_kwargs, dict)
- assert default_config.sandbox.docker_runtime_kwargs.get('mem_limit') == '2g'
- assert default_config.sandbox.docker_runtime_kwargs.get('cpu_count') == 2
- assert isinstance(
- default_config.sandbox.docker_runtime_kwargs.get('environment'), dict
- )
- assert (
- default_config.sandbox.docker_runtime_kwargs.get('environment').get('TEST_VAR')
- == 'test_value'
- )
-
-
-def default_config():
- # Fixture to provide a default OpenHandsConfig instance
- yield OpenHandsConfig()
diff --git a/tests/unit/storage/data_models/test_settings.py b/tests/unit/storage/data_models/test_settings.py
index fd6d2808a4..eaab7a4e47 100644
--- a/tests/unit/storage/data_models/test_settings.py
+++ b/tests/unit/storage/data_models/test_settings.py
@@ -12,7 +12,6 @@ from openhands.app_server.settings.settings_models import Settings
from openhands.app_server.settings.settings_router import LITE_LLM_API_URL
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.sandbox_config import SandboxConfig
from openhands.sdk.llm import LLM
from openhands.sdk.settings import (
AGENT_SETTINGS_SCHEMA_VERSION,
@@ -33,7 +32,6 @@ def test_settings_from_config():
base_url='https://test.example.com',
)
},
- sandbox=SandboxConfig(remote_runtime_resource_factor=2),
)
with patch(
@@ -51,7 +49,6 @@ def test_settings_from_config():
assert settings.agent_settings.llm.model == 'test-model'
assert settings.agent_settings.llm.api_key.get_secret_value() == 'test-key'
assert settings.agent_settings.llm.base_url == 'https://test.example.com'
- assert settings.remote_runtime_resource_factor == 2
assert not settings.secrets_store.provider_tokens
@@ -64,7 +61,6 @@ def test_settings_from_config_no_api_key():
model='test-model', api_key=None, base_url='https://test.example.com'
)
},
- sandbox=SandboxConfig(remote_runtime_resource_factor=2),
)
with patch(