Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove openhands.core package (#14252)

Tim O'Farrell49de7c8504c7
diff --git a/enterprise/integrations/github/data_collector.py b/enterprise/integrations/github/data_collector.py
index a0fb05d702..d6ba6f8182 100644
--- a/enterprise/integrations/github/data_collector.py
+++ b/enterprise/integrations/github/data_collector.py
@@ -19,15 +19,13 @@ from server.auth.constants import GITHUB_APP_CLIENT_ID, GITHUB_APP_PRIVATE_KEY
from storage.openhands_pr import OpenhandsPR
from storage.openhands_pr_store import OpenhandsPRStore
+from openhands.app_server.config import get_global_config
from openhands.app_server.conversation_paths import get_conversation_dir
-from openhands.app_server.file_store import get_file_store
from openhands.app_server.integrations.github.github_service import GithubServiceImpl
from openhands.app_server.integrations.service_types import ProviderType
from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.core.config import load_openhands_config
-config = load_openhands_config()
-file_store = get_file_store(config.file_store, config.file_store_path)
+file_store = get_global_config().file_store
COLLECT_GITHUB_INTERACTIONS = (
diff --git a/enterprise/server/config.py b/enterprise/server/config.py
index ba73541599..aec2c5af44 100644
--- a/enterprise/server/config.py
+++ b/enterprise/server/config.py
@@ -23,20 +23,9 @@ from server.auth.constants import (
from server.constants import DEPLOYMENT_MODE
from openhands.app_server.integrations.service_types import ProviderType
-from openhands.core.config.utils import load_openhands_config
from openhands.server.config.server_config import ServerConfig
from openhands.server.types import AppMode
-# Create a function to get config to avoid circular imports
-_config = None
-
-
-def get_config():
- global _config
- if _config is None:
- _config = load_openhands_config()
- return _config
-
def sign_token(payload: dict[str, object], jwt_secret: str, algorithm='HS256') -> str:
"""Signs a JWT token."""
diff --git a/openhands/app_server/utils/logger.py b/openhands/app_server/utils/logger.py
index 009e8f5ffe..4437fafcec 100644
--- a/openhands/app_server/utils/logger.py
+++ b/openhands/app_server/utils/logger.py
@@ -400,7 +400,7 @@ openhands_logger.propagate = False
openhands_logger.debug('Logging initialized')
LOG_DIR = os.path.join(
- # parent dir of openhands/core (i.e., root of the repo)
+ # parent dir of openhands/app_server/utils (i.e., root of the repo)
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
'logs',
)
diff --git a/openhands/core/config/README.md b/openhands/core/config/README.md
deleted file mode 100644
index 91b90bc7c3..0000000000
--- a/openhands/core/config/README.md
+++ /dev/null
@@ -1,80 +0,0 @@
-# Configuration Management in OpenHands
-
-## Overview
-
-OpenHands uses a flexible configuration system that allows settings to be defined through environment variables, TOML files, and command-line arguments. The configuration is managed through a package structure in `openhands/core/config/`.
-
-## Configuration Classes
-
-The main configuration class is:
-
-- `OpenHandsConfig`: The root configuration class
-
-This class is defined as a Pydantic model, with field defaults for all settings.
-
-## Loading Configuration from Environment Variables
-
-The `load_from_env` function in the config package is responsible for loading configuration values from environment variables. It recursively processes the configuration classes, mapping environment variable names to class attributes.
-
-### Naming Convention for Environment Variables
-
-- Field Names: all uppercase
-- Full Variable Name: Field Name (e.g., `DEFAULT_AGENT`, `WORKSPACE_BASE`)
-
-## Type Handling
-
-The `load_from_env` function attempts to cast environment variable values to the types specified in the models. It handles:
-
-- Basic types (str, int, bool)
-- Optional types (e.g., `str | None`)
-- Nested models
-
-If type casting fails, an error is logged, and the default value is retained.
-
-## Default Values
-
-If an environment variable is not set, the default value specified in the model is used.
-
-## Security Considerations
-
-Be cautious when setting sensitive information like API keys in environment variables. Ensure your environment is secure.
-
-## Usage
-
-The `load_openhands_config()` function is the recommended way to initialize your configuration. It performs the following steps:
-
-1. Creates an instance of `OpenHandsConfig`
-2. Loads settings from the `config.toml` file (if present)
-3. Loads settings from environment variables, overriding TOML settings if applicable
-4. Applies final tweaks and validations to the configuration, falling back to the default values specified in the code
-5. Optionally sets global logging levels based on the configuration
-
-There are also command line args, which may work to override other sources.
-
-Here's an example of how to use `load_openhands_config()`:
-
-````python
-from openhands.core.config import load_openhands_config
-
-# Load all configuration settings
-config = load_openhands_config()
-
-# Now you can access your configuration
-print(f"Default agent: {config.default_agent}")
-print(f"Max iterations: {config.max_iterations}")
-````
-
-By using `load_openhands_config()`, you ensure that all configuration sources are properly loaded and processed, providing a consistent and fully initialized configuration for your application.
-
-## Additional Configuration Methods
-
-While this document focuses on environment variable configuration, OpenHands also supports:
-
-- Loading from TOML files
-- Parsing command-line arguments
-
-These methods are handled by separate functions in the config package.
-
-## Conclusion
-
-The OpenHands configuration system provides a flexible and type-safe way to manage application settings. By following the naming conventions and utilizing the provided functions, developers can easily customize the behavior of OpenHands components through environment variables and other configuration sources.
diff --git a/openhands/core/config/__init__.py b/openhands/core/config/__init__.py
deleted file mode 100644
index 3cefa4b071..0000000000
--- a/openhands/core/config/__init__.py
+++ /dev/null
@@ -1,31 +0,0 @@
-from openhands.core.config.arg_utils import (
- get_evaluation_parser,
- get_headless_parser,
-)
-from openhands.core.config.config_utils import (
- OH_DEFAULT_AGENT,
- OH_MAX_ITERATIONS,
-)
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.utils import (
- finalize_config,
- load_from_env,
- load_from_toml,
- load_openhands_config,
- parse_arguments,
- setup_config_from_args,
-)
-
-__all__ = [
- 'OH_DEFAULT_AGENT',
- 'OH_MAX_ITERATIONS',
- 'OpenHandsConfig',
- 'load_openhands_config',
- 'load_from_env',
- 'load_from_toml',
- 'finalize_config',
- 'get_headless_parser',
- 'get_evaluation_parser',
- 'parse_arguments',
- 'setup_config_from_args',
-]
diff --git a/openhands/core/config/arg_utils.py b/openhands/core/config/arg_utils.py
deleted file mode 100644
index ded2dba021..0000000000
--- a/openhands/core/config/arg_utils.py
+++ /dev/null
@@ -1,150 +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
-"""Centralized command line argument configuration for OpenHands CLI and headless modes."""
-
-import argparse
-
-
-def add_common_arguments(parser: argparse.ArgumentParser) -> None:
- """Add common arguments shared between CLI and headless modes."""
- parser.add_argument(
- '--config-file',
- type=str,
- default='config.toml',
- help='Path to the config file (default: config.toml in the current directory)',
- )
- parser.add_argument(
- '-t',
- '--task',
- type=str,
- default='',
- help='The task for the agent to perform',
- )
- parser.add_argument(
- '-f',
- '--file',
- type=str,
- help='Path to a file containing the task. Overrides -t if both are provided.',
- )
- parser.add_argument(
- '-n',
- '--name',
- help='Session name',
- type=str,
- default='',
- )
- parser.add_argument(
- '--log-level',
- help='Set the log level',
- type=str,
- default=None,
- )
- parser.add_argument(
- '--agent-config',
- default=None,
- type=str,
- help='Replace default Agent ([agent] section in config.toml) config with the specified Agent config, e.g. "CodeAct" for [agent.CodeAct] section in config.toml',
- )
- parser.add_argument(
- '-v', '--version', action='store_true', help='Show version information'
- )
-
-
-def add_evaluation_arguments(parser: argparse.ArgumentParser) -> None:
- """Add arguments specific to evaluation mode."""
- # Evaluation-specific arguments
- parser.add_argument(
- '--eval-output-dir',
- default='evaluation/evaluation_outputs/outputs',
- type=str,
- help='The directory to save evaluation output',
- )
- parser.add_argument(
- '--eval-n-limit',
- default=None,
- type=int,
- help='The number of instances to evaluate',
- )
- parser.add_argument(
- '--eval-num-workers',
- default=4,
- type=int,
- help='The number of workers to use for evaluation',
- )
- parser.add_argument(
- '--eval-note',
- default=None,
- type=str,
- help='The note to add to the evaluation directory',
- )
- parser.add_argument(
- '--eval-ids',
- default=None,
- type=str,
- help='The comma-separated list (in quotes) of IDs of the instances to evaluate',
- )
-
-
-def add_headless_specific_arguments(parser: argparse.ArgumentParser) -> None:
- """Add arguments specific to headless mode (full evaluation suite)."""
- parser.add_argument(
- '-d',
- '--directory',
- type=str,
- help='The working directory for the agent',
- )
- parser.add_argument(
- '-c',
- '--agent-cls',
- default=None,
- type=str,
- help='Name of the default agent to use',
- )
- parser.add_argument(
- '-i',
- '--max-iterations',
- default=None,
- type=int,
- help='The maximum number of iterations to run the agent',
- )
- parser.add_argument(
- '-b',
- '--max-budget-per-task',
- type=float,
- help='The maximum budget allowed per task, beyond which the agent will stop.',
- )
- # Additional headless-specific arguments
- parser.add_argument(
- '--no-auto-continue',
- help='Disable auto-continue responses in headless mode (i.e. headless will read from stdin instead of auto-continuing)',
- action='store_true',
- default=False,
- )
- parser.add_argument(
- '--selected-repo',
- help='GitHub repository to clone (format: owner/repo)',
- type=str,
- default=None,
- )
-
-
-def get_headless_parser() -> argparse.ArgumentParser:
- """Create argument parser for headless mode with full argument set."""
- parser = argparse.ArgumentParser(description='Run the agent via CLI')
- add_common_arguments(parser)
- add_headless_specific_arguments(parser)
- return parser
-
-
-def get_evaluation_parser() -> argparse.ArgumentParser:
- """Create argument parser for evaluation mode."""
- parser = argparse.ArgumentParser(description='Run OpenHands in evaluation mode')
- add_common_arguments(parser)
- add_headless_specific_arguments(parser)
- add_evaluation_arguments(parser)
- return parser
diff --git a/openhands/core/config/config_utils.py b/openhands/core/config/config_utils.py
deleted file mode 100644
index 85cfc01e6c..0000000000
--- a/openhands/core/config/config_utils.py
+++ /dev/null
@@ -1,70 +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
-from types import UnionType
-from typing import Any, get_args, get_origin
-
-from pydantic import BaseModel
-from pydantic.fields import FieldInfo
-
-OH_DEFAULT_AGENT = 'CodeActAgent'
-OH_MAX_ITERATIONS = 500
-DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX = '/workspace'
-
-
-def get_field_info(field: FieldInfo) -> dict[str, Any]:
- """Extract information about a dataclass field: type, optional, and default.
-
- Args:
- field: The field to extract information from.
-
- Returns: A dict with the field's type, whether it's optional, and its default value.
- """
- field_type = field.annotation
- optional = False
-
- # for types like str | None, find the non-None type and set optional to True
- # this is useful for the frontend to know if a field is optional
- # and to show the correct type in the UI
- # Note: this only works for UnionTypes with None as one of the types
- if get_origin(field_type) is UnionType:
- types = get_args(field_type)
- non_none_arg = next(
- (t for t in types if t is not None and t is not type(None)), None
- )
- if non_none_arg is not None:
- field_type = non_none_arg
- optional = True
-
- # type name in a pretty format
- type_name = (
- str(field_type)
- if field_type is None
- else (
- field_type.__name__ if hasattr(field_type, '__name__') else str(field_type)
- )
- )
-
- # default is always present
- default = field.default
-
- # return a schema with the useful info for frontend
- return {'type': type_name.lower(), 'optional': optional, 'default': default}
-
-
-def model_defaults_to_dict(model: BaseModel) -> dict[str, Any]:
- """Serialize field information in a dict for the frontend, including type hints, defaults, and whether it's optional."""
- result = {}
- for name, field in model.__class__.model_fields.items():
- field_value = getattr(model, name)
-
- if isinstance(field_value, BaseModel):
- result[name] = model_defaults_to_dict(field_value)
- else:
- result[name] = get_field_info(field)
-
- return result
diff --git a/openhands/core/config/openhands_config.py b/openhands/core/config/openhands_config.py
deleted file mode 100644
index 7900d83e49..0000000000
--- a/openhands/core/config/openhands_config.py
+++ /dev/null
@@ -1,118 +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 typing import Any, ClassVar
-
-from pydantic import BaseModel, ConfigDict, Field, SecretStr
-
-from openhands.core.config.config_utils import (
- DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX,
- OH_DEFAULT_AGENT,
- OH_MAX_ITERATIONS,
- model_defaults_to_dict,
-)
-
-
-class OpenHandsConfig(BaseModel):
- """Configuration for the app.
-
- Attributes:
- default_agent: Name of the default agent to use.
- runtime: Runtime environment identifier.
- file_store: Type of file store to use.
- file_store_path: Path to the file store.
- enable_browser: Whether to enable the browser environment
- save_trajectory_path: Either a folder path to store trajectories with auto-generated filenames, or a designated trajectory file path.
- save_screenshots_in_trajectory: Whether to save screenshots in trajectory (in encoded image format).
- replay_trajectory_path: Path to load trajectory and replay. If provided, trajectory would be replayed first before user's instruction.
- search_api_key: API key for Tavily search engine (https://tavily.com/).
- workspace_base (deprecated): Base path for the workspace. Defaults to `./workspace` as absolute path.
- workspace_mount_path (deprecated): Path to mount the workspace. Defaults to `workspace_base`.
- workspace_mount_path_in_sandbox (deprecated): Path to mount the workspace in sandbox. Defaults to `/workspace`.
- workspace_mount_rewrite (deprecated): Path to rewrite the workspace mount path.
- cache_dir: Path to cache directory. Defaults to `/tmp/cache`.
- run_as_openhands: Whether to run as openhands.
- max_iterations: Maximum number of iterations allowed.
- max_budget_per_task: Maximum budget per task, agent stops if exceeded.
- disable_color: Whether to disable terminal colors. For terminals that don't support color.
- debug: Whether to enable debugging mode.
- file_uploads_max_file_size_mb: Maximum file upload size in MB. `0` means unlimited.
- file_uploads_restrict_file_types: Whether to restrict upload file types.
- file_uploads_allowed_extensions: Allowed file extensions. `['.*']` allows all.
- cli_multiline_input: Whether to enable multiline input in CLI. When disabled,
- input is read line by line. When enabled, input continues until /exit command.
- mcp_host: Host for OpenHands' default MCP server
- git_user_name: Git user name for commits made by the agent.
- git_user_email: Git user email for commits made by the agent.
- """
-
- default_agent: str = Field(default=OH_DEFAULT_AGENT)
- runtime: str = Field(default='docker')
- file_store: str = Field(default='local')
- file_store_path: str = Field(default='~/.openhands')
- enable_browser: bool = Field(default=True)
- save_trajectory_path: str | None = Field(default=None)
- save_screenshots_in_trajectory: bool = Field(default=False)
- replay_trajectory_path: str | None = Field(default=None)
- search_api_key: SecretStr | None = Field(
- default=None,
- description='API key for Tavily search engine (https://tavily.com/). Required for search functionality.',
- )
-
- workspace_base: str | None = Field(default=None)
- workspace_mount_path_in_sandbox: str = Field(
- default=DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX
- )
-
- # Deprecated parameters - will be removed in a future version
- workspace_mount_path: str | None = Field(default=None)
- workspace_mount_rewrite: str | None = Field(default=None)
- # End of deprecated parameters
-
- cache_dir: str = Field(default='/tmp/cache')
- run_as_openhands: bool = Field(default=True)
- max_iterations: int = Field(default=OH_MAX_ITERATIONS)
- max_budget_per_task: float | None = Field(default=None)
- init_git_in_empty_workspace: bool = Field(default=False)
-
- disable_color: bool = Field(default=False)
- jwt_secret: SecretStr | None = Field(default=None)
- debug: bool = Field(default=False)
- file_uploads_max_file_size_mb: int = Field(default=0)
- file_uploads_restrict_file_types: bool = Field(default=False)
- file_uploads_allowed_extensions: list[str] = Field(default_factory=lambda: ['.*'])
-
- cli_multiline_input: bool = Field(default=False)
- conversation_max_age_seconds: int = Field(default=864000) # 10 days in seconds
- enable_default_condenser: bool = Field(default=True)
- max_concurrent_conversations: int = Field(
- default=3
- ) # Maximum number of concurrent agent loops allowed per user
- client_wait_timeout: int = Field(
- default=30,
- description='Timeout in seconds for waiting for websocket client connection during initialization',
- )
- mcp_host: str = Field(default=f'localhost:{os.getenv("port", 3000)}')
- git_user_name: str = Field(
- default='openhands', description='Git user name for commits made by the agent'
- )
- git_user_email: str = Field(
- default='[email protected]',
- description='Git user email for commits made by the agent',
- )
-
- defaults_dict: ClassVar[dict] = {}
-
- model_config = ConfigDict(extra='forbid')
-
- def model_post_init(self, __context: Any) -> None:
- """Post-initialization hook, called when the instance is created with only default values."""
- super().model_post_init(__context)
-
- if not OpenHandsConfig.defaults_dict: # Only set defaults_dict if it's empty
- OpenHandsConfig.defaults_dict = model_defaults_to_dict(self)
diff --git a/openhands/core/config/utils.py b/openhands/core/config/utils.py
deleted file mode 100644
index f797b0665c..0000000000
--- a/openhands/core/config/utils.py
+++ /dev/null
@@ -1,288 +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 argparse
-import os
-import pathlib
-import sys
-from ast import literal_eval
-from types import UnionType
-from typing import Any, MutableMapping, get_args, get_origin, get_type_hints
-from uuid import uuid4
-
-import toml
-from dotenv import load_dotenv
-from pydantic import BaseModel, SecretStr
-
-from openhands.app_server.file_store import get_file_store
-from openhands.app_server.file_store.files import FileStore
-from openhands.app_server.utils import logger
-from openhands.core.config.arg_utils import get_headless_parser
-from openhands.core.config.openhands_config import OpenHandsConfig
-
-JWT_SECRET = '.jwt_secret'
-load_dotenv()
-
-
-def load_from_env(
- cfg: OpenHandsConfig, env_or_toml_dict: dict | MutableMapping[str, str]
-) -> None:
- """Sets config attributes from environment variables or TOML dictionary.
-
- Reads environment-style variables and updates the config attributes accordingly.
- Supports configuration of LLM settings (e.g., LLM_BASE_URL), agent settings
- (e.g., AGENT_MEMORY_ENABLED), sandbox settings (e.g., SANDBOX_TIMEOUT), and more.
-
- Args:
- cfg: The OpenHandsConfig object to set attributes on.
- env_or_toml_dict: The environment variables or a config.toml dict.
- """
-
- def get_optional_type(union_type: UnionType | type | None) -> type | None:
- """Returns the non-None type from a Union."""
- if union_type is None:
- return None
- if get_origin(union_type) is UnionType:
- types = get_args(union_type)
- return next((t for t in types if t is not type(None)), None)
- if isinstance(union_type, type):
- return union_type
- return None
-
- # helper function to set attributes based on env vars
- def set_attr_from_env(sub_config: BaseModel, prefix: str = '') -> None:
- """Set attributes of a config model based on environment variables."""
- for field_name, field_info in sub_config.__class__.model_fields.items():
- field_value = getattr(sub_config, field_name)
- field_type = field_info.annotation
-
- # compute the expected env var name from the prefix and field name
- # e.g. LLM_BASE_URL
- env_var_name = (prefix + field_name).upper()
-
- cast_value: Any
- if isinstance(field_value, BaseModel):
- set_attr_from_env(field_value, prefix=field_name + '_')
-
- elif env_var_name in env_or_toml_dict:
- # convert the env var to the correct type and set it
- value = env_or_toml_dict[env_var_name]
-
- # skip empty config values (fall back to default)
- if not value:
- continue
-
- try:
- # if it's an optional type, get the non-None type
- if get_origin(field_type) is UnionType:
- field_type = get_optional_type(field_type)
-
- # Attempt to cast the env var to type hinted in the dataclass
- if field_type is bool:
- cast_value = str(value).lower() in ['true', '1']
- # parse dicts and lists like SANDBOX_RUNTIME_STARTUP_ENV_VARS and SANDBOX_RUNTIME_EXTRA_BUILD_ARGS
- elif (
- get_origin(field_type) is dict
- or get_origin(field_type) is list
- or field_type is dict
- or field_type is list
- ):
- cast_value = literal_eval(value)
- # If it's a list of Pydantic models
- if get_origin(field_type) is list:
- inner_type = get_args(field_type)[0]
- if isinstance(inner_type, type) and issubclass(
- inner_type, BaseModel
- ):
- cast_value = [
- inner_type(**item)
- if isinstance(item, dict)
- else item
- for item in cast_value
- ]
- else:
- if field_type is not None:
- cast_value = field_type(value)
- setattr(sub_config, field_name, cast_value)
- except (ValueError, TypeError):
- logger.openhands_logger.error(
- f'Error setting env var {env_var_name}={value}: check that the value is of the right type'
- )
-
- # Start processing from the root of the config object
- set_attr_from_env(cfg)
-
-
-def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None:
- """Load the config from the toml file. Supports both styles of config vars.
-
- Args:
- cfg: The OpenHandsConfig object to update attributes of.
- toml_file: The path to the toml file. Defaults to 'config.toml'.
-
- See Also:
- - config.template.toml for the full list of config options.
- """
- # try to read the config.toml file into the config object
- try:
- with open(toml_file, 'r', encoding='utf-8') as toml_contents:
- toml_config = toml.load(toml_contents)
- except FileNotFoundError as e:
- logger.openhands_logger.info(
- f'{toml_file} not found: {e}. Toml values have not been applied.'
- )
- return
- except toml.TomlDecodeError as e:
- logger.openhands_logger.warning(
- f'Cannot parse config from toml, toml values have not been applied.\nError: {e}',
- )
- return
-
- # Check for the [core] section
- if 'core' not in toml_config:
- logger.openhands_logger.warning(
- f'No [core] section found in {toml_file}. Core settings will use defaults.'
- )
- core_config = {}
- else:
- core_config = toml_config['core']
-
- # Process core section if present
- cfg_type_hints = get_type_hints(cfg.__class__)
- for key, value in core_config.items():
- if hasattr(cfg, key):
- # Get expected type of the attribute
- expected_type = cfg_type_hints.get(key, None)
-
- # Check if expected_type is a Union that includes SecretStr and value is str, e.g. search_api_key
- if expected_type:
- origin = get_origin(expected_type)
- args = get_args(expected_type)
-
- if origin is UnionType and SecretStr in args and isinstance(value, str):
- value = SecretStr(value)
- elif expected_type is SecretStr and isinstance(value, str):
- value = SecretStr(value)
-
- setattr(cfg, key, value)
- else:
- logger.openhands_logger.warning(
- f'Unknown config key "{key}" in [core] section'
- )
-
- # Check for unknown sections
- # Note: legacy sections are kept for backwards compatibility with old config
- # files - they are silently ignored
- known_sections = {
- 'core',
- 'mcp', # Legacy, ignored
- 'llm', # Legacy, ignored
- 'sandbox', # Legacy, ignored
- 'security', # Legacy, ignored
- 'agent', # Legacy, ignored
- 'extended', # Legacy, ignored
- 'condenser', # Legacy, ignored
- 'kubernetes', # Legacy, ignored
- 'model_routing', # Legacy, ignored
- }
- for key in toml_config:
- if key.lower() not in known_sections:
- logger.openhands_logger.warning(f'Unknown section [{key}] in {toml_file}')
-
-
-def get_or_create_jwt_secret(file_store: FileStore) -> str:
- try:
- jwt_secret = file_store.read(JWT_SECRET)
- return jwt_secret
- except FileNotFoundError:
- new_secret = uuid4().hex
- file_store.write(JWT_SECRET, new_secret)
- return new_secret
-
-
-def finalize_config(cfg: OpenHandsConfig) -> None:
- """More tweaks to the config after it's been loaded."""
- # Handle the deprecated workspace_* parameters
- 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:
- cfg.workspace_mount_path = cfg.workspace_base
-
- if cfg.workspace_mount_rewrite:
- base = cfg.workspace_base or os.getcwd()
- parts = cfg.workspace_mount_rewrite.split(':')
- cfg.workspace_mount_path = base.replace(parts[0], parts[1])
-
- # make sure cache dir exists
- if cfg.cache_dir:
- pathlib.Path(cfg.cache_dir).mkdir(parents=True, exist_ok=True)
-
- if not cfg.jwt_secret:
- cfg.jwt_secret = SecretStr(
- get_or_create_jwt_secret(
- get_file_store(cfg.file_store, cfg.file_store_path)
- )
- )
-
-
-def parse_arguments() -> argparse.Namespace:
- """Parse command line arguments."""
- parser = get_headless_parser()
- args = parser.parse_args()
- from openhands import get_version
-
- if args.version:
- print(f'OpenHands version: {get_version()}')
- sys.exit(0)
-
- return args
-
-
-def load_openhands_config(
- set_logging_levels: bool = True, config_file: str = 'config.toml'
-) -> OpenHandsConfig:
- """Load the configuration from the specified config file and environment variables.
-
- Args:
- set_logging_levels: Whether to set the global variables for logging levels.
- config_file: Path to the config file. Defaults to 'config.toml' in the current directory.
- """
- config = OpenHandsConfig()
- load_from_toml(config, config_file)
- load_from_env(config, os.environ)
- finalize_config(config)
- if set_logging_levels:
- logger.DEBUG = config.debug
- logger.DISABLE_COLOR_PRINTING = config.disable_color
- return config
-
-
-def setup_config_from_args(args: argparse.Namespace) -> OpenHandsConfig:
- """Load config from toml and override with command line arguments.
-
- Common setup used by both CLI and main.py entry points.
-
- Configuration precedence (from highest to lowest):
- 1. CLI parameters
- 2. config.toml in current directory (or --config-file location if specified)
- 3. ~/.openhands/settings.json and ~/.openhands/config.toml
- """
- # Load base config from toml and env vars
- config = load_openhands_config(config_file=args.config_file)
-
- # Override default agent if provided
- if hasattr(args, 'agent_cls') and args.agent_cls:
- config.default_agent = args.agent_cls
-
- # Set max iterations and max budget per task if provided, otherwise fall back to config values
- if hasattr(args, 'max_iterations') and args.max_iterations is not None:
- config.max_iterations = args.max_iterations
- 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
-
- return config
diff --git a/openhands/server/shared.py b/openhands/server/shared.py
index 431a273102..cf2e10ed65 100644
--- a/openhands/server/shared.py
+++ b/openhands/server/shared.py
@@ -12,14 +12,11 @@ from dotenv import load_dotenv
from openhands.app_server.secrets.secrets_store import SecretsStore
from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.utils.import_utils import get_impl
-from openhands.core.config import load_openhands_config
-from openhands.core.config.openhands_config import OpenHandsConfig
from openhands.server.config.server_config import ServerConfig, load_server_config
from openhands.server.types import ServerConfigInterface
load_dotenv()
-config: OpenHandsConfig = load_openhands_config()
server_config_interface: ServerConfigInterface = load_server_config()
assert isinstance(server_config_interface, ServerConfig), (
'Loaded server config interface is not a ServerConfig, despite this being assumed'
diff --git a/tests/unit/core/logger/test_logger.py b/tests/unit/app_server/utils/logger/test_logger.py
similarity index 100%
rename from tests/unit/core/logger/test_logger.py
rename to tests/unit/app_server/utils/logger/test_logger.py
diff --git a/tests/unit/core/logger/test_logger_litellm.py b/tests/unit/app_server/utils/logger/test_logger_litellm.py
similarity index 94%
rename from tests/unit/core/logger/test_logger_litellm.py
rename to tests/unit/app_server/utils/logger/test_logger_litellm.py
index 02f50afdf2..18c803880a 100644
--- a/tests/unit/core/logger/test_logger_litellm.py
+++ b/tests/unit/app_server/utils/logger/test_logger_litellm.py
@@ -73,10 +73,10 @@ def test_litellm_loggers_suppressed_with_uvicorn_json_config(reset_litellm):
import pathlib
# Find the logger.py file path relative to the openhands package
- # __file__ is tests/unit/core/logger/test_logger_litellm.py
+ # __file__ is tests/unit/app_server/utils/logger/test_logger_litellm.py
# We need to go up to tests/, then find openhands/app_server/utils/logger.py
- test_dir = pathlib.Path(__file__).parent # tests/unit/core/logger
- project_root = test_dir.parent.parent.parent.parent # workspace/openhands
+ test_dir = pathlib.Path(__file__).parent # tests/unit/app_server/utils/logger
+ project_root = test_dir.parent.parent.parent.parent.parent # workspace/openhands
logger_file = project_root / 'openhands' / 'app_server' / 'utils' / 'logger.py'
# Read the actual source file
diff --git a/tests/unit/core/logger/test_logging.py b/tests/unit/app_server/utils/logger/test_logging.py
similarity index 96%
rename from tests/unit/core/logger/test_logging.py
rename to tests/unit/app_server/utils/logger/test_logging.py
index 7a31ce37ba..c17d3cc053 100644
--- a/tests/unit/core/logger/test_logging.py
+++ b/tests/unit/app_server/utils/logger/test_logging.py
@@ -11,7 +11,6 @@ from openhands.app_server.utils.logger import (
json_log_handler,
)
from openhands.app_server.utils.logger import openhands_logger as openhands_logger
-from openhands.core.config import OpenHandsConfig
@pytest.fixture
@@ -74,10 +73,10 @@ def test_anthropic_api_key_masking(test_handler):
def test_app_config_attributes_masking(test_handler):
logger, stream = test_handler
- app_config = OpenHandsConfig(search_api_key='search-xyz789')
- logger.info(f'App Config: {app_config}')
+ # Test that sensitive config-like strings are masked in logs
+ config_str = "AppConfig(search_api_key='search-xyz789', github_token='ghp_abcdefghijklmnopqrstuvwxyz')"
+ logger.info(f'App Config: {config_str}')
log_output = stream.getvalue()
- assert 'github_token' not in log_output
assert 'search-xyz789' not in log_output
assert 'ghp_abcdefghijklmnopqrstuvwxyz' not in log_output
diff --git a/tests/unit/core/config/test_arg_parser.py b/tests/unit/core/config/test_arg_parser.py
deleted file mode 100644
index 38c5693b8d..0000000000
--- a/tests/unit/core/config/test_arg_parser.py
+++ /dev/null
@@ -1,201 +0,0 @@
-import pytest
-
-from openhands.core.config import (
- get_evaluation_parser,
- get_headless_parser,
-)
-
-
-def test_headless_parser_default_values():
- parser = get_headless_parser()
- args = parser.parse_args([])
-
- assert args.directory is None
- assert args.task == ''
- assert args.file is None
- assert args.agent_cls is None
- assert args.max_iterations is None
- assert args.max_budget_per_task is None
- assert args.name == ''
- assert not args.no_auto_continue
- assert args.selected_repo is None
-
-
-def test_evaluation_parser_default_values():
- parser = get_evaluation_parser()
- args = parser.parse_args([])
-
- assert args.directory is None
- assert args.task == ''
- assert args.file is None
- assert args.agent_cls is None
- assert args.max_iterations is None
- assert args.max_budget_per_task is None
- assert args.eval_output_dir == 'evaluation/evaluation_outputs/outputs'
- assert args.eval_n_limit is None
- assert args.eval_num_workers == 4
- assert args.eval_note is None
- assert args.name == ''
- assert not args.no_auto_continue
- assert args.selected_repo is None
-
-
-def test_evaluation_parser_custom_values():
- parser = get_evaluation_parser()
- args = parser.parse_args(
- [
- '-v',
- '-d',
- '/path/to/dir',
- '-t',
- 'custom task',
- '-f',
- 'task.txt',
- '-c',
- 'CustomAgent',
- '-i',
- '50',
- '-b',
- '100.5',
- '--eval-output-dir',
- 'custom/output',
- '--eval-n-limit',
- '10',
- '--eval-num-workers',
- '8',
- '--eval-note',
- 'Test run',
- '-n',
- 'test_session',
- '--no-auto-continue',
- '--selected-repo',
- 'owner/repo',
- ]
- )
-
- assert args.directory == '/path/to/dir'
- assert args.task == 'custom task'
- assert args.file == 'task.txt'
- assert args.agent_cls == 'CustomAgent'
- assert args.max_iterations == 50
- assert args.max_budget_per_task == pytest.approx(100.5)
- assert args.eval_output_dir == 'custom/output'
- assert args.eval_n_limit == 10
- assert args.eval_num_workers == 8
- assert args.eval_note == 'Test run'
- assert args.name == 'test_session'
- assert args.no_auto_continue
- assert args.version
- assert args.selected_repo == 'owner/repo'
-
-
-def test_parser_file_overrides_task():
- parser = get_headless_parser()
- args = parser.parse_args(['-t', 'task from command', '-f', 'task_file.txt'])
-
- assert args.task == 'task from command'
- assert args.file == 'task_file.txt'
-
-
-def test_parser_invalid_max_iterations():
- parser = get_headless_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['-i', 'not_a_number'])
-
-
-def test_parser_invalid_max_budget():
- parser = get_headless_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['-b', 'not_a_number'])
-
-
-def test_evaluation_parser_invalid_eval_n_limit():
- parser = get_evaluation_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['--eval-n-limit', 'not_a_number'])
-
-
-def test_evaluation_parser_invalid_eval_num_workers():
- parser = get_evaluation_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['--eval-num-workers', 'not_a_number'])
-
-
-def test_headless_parser_help_message(capsys):
- parser = get_headless_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['--help'])
- captured = capsys.readouterr()
- help_output = captured.out
- print(help_output)
- expected_elements = [
- 'usage:',
- 'Run the agent via CLI',
- 'options:',
- '-v, --version',
- '-h, --help',
- '-d DIRECTORY, --directory DIRECTORY',
- '-t TASK, --task TASK',
- '-f FILE, --file FILE',
- '-c AGENT_CLS, --agent-cls AGENT_CLS',
- '-i MAX_ITERATIONS, --max-iterations MAX_ITERATIONS',
- '-b MAX_BUDGET_PER_TASK, --max-budget-per-task MAX_BUDGET_PER_TASK',
- '--agent-config AGENT_CONFIG',
- '-n NAME, --name NAME',
- '--config-file CONFIG_FILE',
- '--no-auto-continue',
- '--selected-repo SELECTED_REPO',
- '--log-level LOG_LEVEL',
- ]
-
- for element in expected_elements:
- assert element in help_output, f"Expected '{element}' to be in the help message"
-
- option_count = help_output.count(' -')
- assert option_count == 14, f'Expected 14 options, found {option_count}'
-
-
-def test_evaluation_parser_help_message(capsys):
- parser = get_evaluation_parser()
- with pytest.raises(SystemExit):
- parser.parse_args(['--help'])
- captured = capsys.readouterr()
- help_output = captured.out
- print(help_output)
- expected_elements = [
- 'usage:',
- 'Run OpenHands in evaluation mode',
- 'options:',
- '-v, --version',
- '-h, --help',
- '-d DIRECTORY, --directory DIRECTORY',
- '-t TASK, --task TASK',
- '-f FILE, --file FILE',
- '-c AGENT_CLS, --agent-cls AGENT_CLS',
- '-i MAX_ITERATIONS, --max-iterations MAX_ITERATIONS',
- '-b MAX_BUDGET_PER_TASK, --max-budget-per-task MAX_BUDGET_PER_TASK',
- '--eval-output-dir EVAL_OUTPUT_DIR',
- '--eval-n-limit EVAL_N_LIMIT',
- '--eval-num-workers EVAL_NUM_WORKERS',
- '--eval-note EVAL_NOTE',
- '--eval-ids EVAL_IDS',
- '--agent-config AGENT_CONFIG',
- '-n NAME, --name NAME',
- '--config-file CONFIG_FILE',
- '--no-auto-continue',
- '--selected-repo SELECTED_REPO',
- '--log-level LOG_LEVEL',
- ]
-
- for element in expected_elements:
- assert element in help_output, f"Expected '{element}' to be in the help message"
-
- option_count = help_output.count(' -')
- assert option_count == 19, f'Expected 19 options, found {option_count}'
-
-
-def test_selected_repo_format():
- """Test that the selected-repo argument accepts owner/repo format."""
- parser = get_headless_parser()
- args = parser.parse_args(['--selected-repo', 'owner/repo'])
- assert args.selected_repo == 'owner/repo'
diff --git a/tests/unit/core/config/test_config.py b/tests/unit/core/config/test_config.py
deleted file mode 100644
index 643eb696f5..0000000000
--- a/tests/unit/core/config/test_config.py
+++ /dev/null
@@ -1,192 +0,0 @@
-import os
-
-import pytest
-
-from openhands.core.config import (
- OpenHandsConfig,
- finalize_config,
- load_from_env,
- load_from_toml,
-)
-
-
-def temp_toml_file(tmp_path):
- # Fixture to create a temporary directory and TOML file for testing
- tmp_toml_file = os.path.join(tmp_path, 'config.toml')
- yield tmp_toml_file
-
-
-def default_config(monkeypatch):
- # Fixture to provide a default OpenHandsConfig instance
- yield OpenHandsConfig()
-
-
-def test_load_from_old_style_env(monkeypatch, default_config):
- # Test loading configuration from old-style environment variables using monkeypatch
- monkeypatch.setenv('DEFAULT_AGENT', 'BrowsingAgent')
- # Using deprecated WORKSPACE_BASE to test backward compatibility
- monkeypatch.setenv('WORKSPACE_BASE', '/opt/files/workspace')
-
- load_from_env(default_config, os.environ)
-
- assert default_config.default_agent == 'BrowsingAgent'
- # Verify deprecated variables still work
- 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
-
-
-def test_load_from_new_style_toml(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]
-default_agent = "TestAgent"
-"""
- )
-
- load_from_toml(default_config, temp_toml_file)
-
- assert default_config.default_agent == 'TestAgent'
-
-
-def test_security_section_in_toml_is_silently_ignored(default_config, temp_toml_file):
- """Test that a legacy [security] section in TOML is silently ignored."""
- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
- toml_file.write(
- """
-[core]
-workspace_base = "/opt/files/workspace"
-
-[security]
-confirmation_mode = false
-security_analyzer = "semgrep"
-"""
- )
-
- load_from_toml(default_config, temp_toml_file)
- # Security section is ignored; no error raised
- assert default_config.workspace_base == '/opt/files/workspace'
-
-
-def test_defaults_dict_after_updates(default_config):
- # Test that `defaults_dict` retains initial values after updates.
- initial_defaults = default_config.defaults_dict
- assert initial_defaults['workspace_mount_path']['default'] is None
- assert initial_defaults['default_agent']['default'] == 'CodeActAgent'
-
- updated_config = OpenHandsConfig()
- updated_config.default_agent = 'BrowsingAgent'
-
- 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 == initial_defaults
-
-
-def test_invalid_toml_format(monkeypatch, temp_toml_file, default_config):
- # Invalid TOML format doesn't break the configuration
- monkeypatch.setenv('WORKSPACE_MOUNT_PATH', '/home/user/project')
-
- with open(temp_toml_file, 'w', encoding='utf-8') as toml_file:
- toml_file.write('INVALID TOML CONTENT')
-
- load_from_toml(default_config, temp_toml_file)
- load_from_env(default_config, os.environ)
- default_config.jwt_secret = None # prevent leak
- assert default_config.workspace_mount_path == '/home/user/project'
-
-
-def test_load_from_toml_file_not_found(default_config):
- """Test loading configuration when the TOML file doesn't exist.
-
- This ensures that:
- 1. The program doesn't crash when the config file is missing
- 2. The config object retains its default values
- 3. The application remains usable
- """
- # Try to load from a non-existent file
- load_from_toml(default_config, 'nonexistent.toml')
-
- # Verify that config object maintains default values
- assert default_config is not None
- assert default_config.default_agent == 'CodeActAgent'
-
-
-def test_finalize_config(default_config):
- # Test finalize config
- assert default_config.workspace_mount_path is None
- default_config.workspace_base = None
- finalize_config(default_config)
-
- assert default_config.workspace_mount_path is None
-
-
-def test_workspace_mount_path_default(default_config):
- assert default_config.workspace_mount_path is None
- default_config.workspace_base = '/home/user/project'
- finalize_config(default_config)
- assert default_config.workspace_mount_path == os.path.abspath(
- default_config.workspace_base
- )
-
-
-def test_workspace_mount_rewrite(default_config, monkeypatch):
- default_config.workspace_base = '/home/user/project'
- default_config.workspace_mount_rewrite = '/home/user:/sandbox'
- monkeypatch.setattr('os.getcwd', lambda: '/current/working/directory')
- finalize_config(default_config)
- assert default_config.workspace_mount_path == '/sandbox/project'
-
-
-def test_cache_dir_creation(default_config, tmpdir):
- default_config.cache_dir = str(tmpdir.join('test_cache'))
- finalize_config(default_config)
- assert os.path.exists(default_config.cache_dir)
-
-
-def test_api_keys_repr_str():
- # Test OpenHandsConfig
- app_config = OpenHandsConfig(
- search_api_key='my_search_api_key',
- )
-
- assert 'my_search_api_key' not in repr(app_config)
- assert 'my_search_api_key' not in str(app_config)
-
- # Check that no other attrs in OpenHandsConfig have 'key' or 'token' in their name
- # This will fail when new attrs are added, and attract attention
- known_key_token_attrs_app = [
- 'search_api_key',
- ]
- for attr_name in OpenHandsConfig.model_fields.keys():
- if (
- not attr_name.startswith('__')
- and attr_name not in known_key_token_attrs_app
- ):
- assert 'key' not in attr_name.lower(), (
- f"Unexpected attribute '{attr_name}' contains 'key' in OpenHandsConfig"
- )
- assert 'token' not in attr_name.lower() or 'tokens' in attr_name.lower(), (
- f"Unexpected attribute '{attr_name}' contains 'token' in OpenHandsConfig"
- )
-
-
-def test_max_iterations_and_max_budget_per_task_from_toml(temp_toml_file):
- temp_toml = """
-[core]
-max_iterations = 42
-max_budget_per_task = 4.7
-"""
-
- config = OpenHandsConfig()
- with open(temp_toml_file, 'w') as f:
- f.write(temp_toml)
-
- load_from_toml(config, temp_toml_file)
-
- assert config.max_iterations == 42
- assert config.max_budget_per_task == 4.7
diff --git a/tests/unit/core/config/test_config_precedence.py b/tests/unit/core/config/test_config_precedence.py
deleted file mode 100644
index 5eb33db0c0..0000000000
--- a/tests/unit/core/config/test_config_precedence.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from unittest.mock import MagicMock, patch
-
-from openhands.core.config import (
- OH_DEFAULT_AGENT,
- OH_MAX_ITERATIONS,
- OpenHandsConfig,
- setup_config_from_args,
-)
-
-
-def test_default_values_applied_when_none():
- """Test that default values are applied when config values are None."""
- # Create mock args with None values for agent_cls and max_iterations
- mock_args = MagicMock()
- mock_args.config_file = None
- mock_args.agent_cls = None
- mock_args.max_iterations = None
-
- # Load config
- with patch(
- 'openhands.core.config.utils.load_openhands_config',
- return_value=OpenHandsConfig(),
- ):
- config = setup_config_from_args(mock_args)
-
- # Verify they match the expected defaults
- assert config.default_agent == OH_DEFAULT_AGENT
- assert config.max_iterations == OH_MAX_ITERATIONS
-
-
-def test_cli_args_override_defaults():
- """Test that CLI arguments override default values."""
- # Create mock args with custom values
- mock_args = MagicMock()
- mock_args.config_file = None
- mock_args.agent_cls = 'CustomAgent'
- mock_args.max_iterations = 50
-
- # Load config
- with patch(
- 'openhands.core.config.utils.load_openhands_config',
- return_value=OpenHandsConfig(),
- ):
- config = setup_config_from_args(mock_args)
-
- # Verify custom values are used instead of defaults
- assert config.default_agent == 'CustomAgent'
- assert config.max_iterations == 50
-
-
-def test_cli_args_none_uses_config_toml_values():
- """Test that when CLI args agent_cls and max_iterations are None, config.toml values are used."""
- # Create mock args with None values for agent_cls and max_iterations
- mock_args = MagicMock()
- mock_args.config_file = None
- mock_args.agent_cls = None
- mock_args.max_iterations = None
-
- # Create a config with specific values from config.toml
- config_from_toml = OpenHandsConfig()
- config_from_toml.default_agent = 'ConfigTomlAgent'
- config_from_toml.max_iterations = 100
-
- # Load config
- with patch(
- 'openhands.core.config.utils.load_openhands_config',
- return_value=config_from_toml,
- ):
- config = setup_config_from_args(mock_args)
-
- # Verify config.toml values are preserved when CLI args are None
- assert config.default_agent == 'ConfigTomlAgent'
- assert config.max_iterations == 100
diff --git a/tests/unit/core/config/test_git_config.py b/tests/unit/core/config/test_git_config.py
deleted file mode 100644
index bac7b4393b..0000000000
--- a/tests/unit/core/config/test_git_config.py
+++ /dev/null
@@ -1,38 +0,0 @@
-"""Tests for git configuration functionality."""
-
-import os
-from unittest.mock import patch
-
-from openhands.core.config import OpenHandsConfig, load_from_env
-
-
-class TestGitConfig:
- """Test git configuration functionality."""
-
- def test_default_git_config(self):
- """Test that default git configuration is set correctly."""
- config = OpenHandsConfig()
- assert config.git_user_name == 'openhands'
- assert config.git_user_email == '[email protected]'
-
- def test_git_config_from_env_vars(self):
- """Test that git configuration can be set via environment variables."""
- with patch.dict(
- os.environ,
- {'GIT_USER_NAME': 'testuser', 'GIT_USER_EMAIL': '[email protected]'},
- ):
- config = OpenHandsConfig()
- load_from_env(config, os.environ)
-
- assert config.git_user_name == 'testuser'
- assert config.git_user_email == '[email protected]'
-
- def test_git_config_empty_values(self):
- """Test behavior with empty git configuration values."""
- with patch.dict(os.environ, {'GIT_USER_NAME': '', 'GIT_USER_EMAIL': ''}):
- config = OpenHandsConfig()
- load_from_env(config, os.environ)
-
- # Empty values should fall back to defaults
- assert config.git_user_name == 'openhands'
- assert config.git_user_email == '[email protected]'
diff --git a/tests/unit/core/config/test_shttp_timeout_config.py b/tests/unit/core/config/test_shttp_timeout_config.py
deleted file mode 100644
index ba98f621f6..0000000000
--- a/tests/unit/core/config/test_shttp_timeout_config.py
+++ /dev/null
@@ -1,63 +0,0 @@
-"""Test MCP remote server timeout configuration."""
-
-from fastmcp.mcp_config import RemoteMCPServer
-
-
-class TestRemoteMCPServer:
- """Test remote server configuration with timeout field."""
-
- def test_remote_config_with_timeout(self):
- """Test remote config accepts timeout parameter."""
- config = RemoteMCPServer(
- url='https://api.example.com/mcp', transport='http', timeout=90
- )
- assert config.timeout == 90
- assert config.url == 'https://api.example.com/mcp'
-
- def test_remote_config_with_auth_and_timeout(self):
- """Test remote config with both auth and timeout."""
- config = RemoteMCPServer(
- url='https://api.example.com/mcp',
- transport='http',
- auth='test-key-123',
- timeout=120,
- )
- assert config.timeout == 120
- assert config.auth == 'test-key-123'
-
- def test_remote_config_default_timeout(self):
- """Test remote config default timeout (None)."""
- config = RemoteMCPServer(url='https://api.example.com/mcp', transport='http')
- assert config.timeout is None
-
- def test_remote_config_positive_timeout(self):
- """Test timeout accepts positive values."""
- valid_timeouts = [1, 5, 30, 60, 120, 300, 600, 1800, 3600]
-
- for timeout in valid_timeouts:
- config = RemoteMCPServer(
- url='https://api.example.com/mcp', transport='http', timeout=timeout
- )
- assert config.timeout == timeout
-
- def test_model_dump_includes_timeout(self):
- """Test that model serialization includes timeout field."""
- config = RemoteMCPServer(
- url='https://api.example.com/mcp',
- transport='http',
- auth='test-key',
- timeout=90,
- )
-
- data = config.model_dump()
- assert data['url'] == 'https://api.example.com/mcp'
- assert data['auth'] == 'test-key'
- assert data['timeout'] == 90
-
- def test_transport_types(self):
- """Test that transport field accepts sse and http."""
- sse = RemoteMCPServer(url='https://api.example.com/sse', transport='sse')
- assert sse.transport == 'sse'
-
- http = RemoteMCPServer(url='https://api.example.com/mcp', transport='http')
- assert http.transport == 'http'