Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove AgentConfig and ExtendedConfig (V0 dead code cleanup) (#14210)

Tim O'Farrellfc67d615d268
diff --git a/openhands/core/config/__init__.py b/openhands/core/config/__init__.py
index 7ffc658269..368b7a1989 100644
--- a/openhands/core/config/__init__.py
+++ b/openhands/core/config/__init__.py
@@ -1,4 +1,3 @@
-from openhands.core.config.agent_config import AgentConfig
from openhands.core.config.arg_utils import (
get_evaluation_parser,
get_headless_parser,
@@ -7,7 +6,6 @@ from openhands.core.config.config_utils import (
OH_DEFAULT_AGENT,
OH_MAX_ITERATIONS,
)
-from openhands.core.config.extended_config import ExtendedConfig
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.mcp_config import MCPConfig
from openhands.core.config.openhands_config import OpenHandsConfig
@@ -15,7 +13,6 @@ from openhands.core.config.sandbox_config import SandboxConfig
from openhands.core.config.security_config import SecurityConfig
from openhands.core.config.utils import (
finalize_config,
- get_agent_config_arg,
get_llm_config_arg,
load_from_env,
load_from_toml,
@@ -27,18 +24,15 @@ from openhands.core.config.utils import (
__all__ = [
'OH_DEFAULT_AGENT',
'OH_MAX_ITERATIONS',
- 'AgentConfig',
'OpenHandsConfig',
'MCPConfig',
'LLMConfig',
'SandboxConfig',
'SecurityConfig',
- 'ExtendedConfig',
'load_openhands_config',
'load_from_env',
'load_from_toml',
'finalize_config',
- 'get_agent_config_arg',
'get_llm_config_arg',
'get_headless_parser',
'get_evaluation_parser',
diff --git a/openhands/core/config/agent_config.py b/openhands/core/config/agent_config.py
deleted file mode 100644
index 03124dcac7..0000000000
--- a/openhands/core/config/agent_config.py
+++ /dev/null
@@ -1,120 +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 __future__ import annotations
-
-from pydantic import BaseModel, ConfigDict, Field, ValidationError
-
-from openhands.core.config.extended_config import ExtendedConfig
-from openhands.core.logger import openhands_logger as logger
-
-
-class AgentConfig(BaseModel):
- cli_mode: bool = Field(default=False)
- """Whether the agent is running in CLI mode. This can be used to disable certain tools that are not supported in CLI mode."""
- llm_config: str | None = Field(default=None)
- """The name of the llm config to use. If specified, this will override global llm config."""
- classpath: str | None = Field(default=None)
- """The classpath of the agent to use. To be used for custom agents."""
- system_prompt_filename: str = Field(default='system_prompt.j2')
- """Filename of the system prompt template file within the agent's prompt directory. Defaults to 'system_prompt.j2'."""
- enable_browsing: bool = Field(default=True)
- """Whether to enable browsing tool.
- Note: If using CLIRuntime, browsing is not implemented and should be disabled."""
- enable_llm_editor: bool = Field(default=False)
- """Whether to enable LLM editor tool"""
- enable_editor: bool = Field(default=True)
- """Whether to enable the standard editor tool (str_replace_editor), only has an effect if enable_llm_editor is False."""
- enable_jupyter: bool = Field(default=True)
- """Whether to enable Jupyter tool.
- Note: If using CLIRuntime, Jupyter use is not implemented and should be disabled."""
- enable_cmd: bool = Field(default=True)
- """Whether to enable bash tool"""
- enable_think: bool = Field(default=True)
- """Whether to enable think tool"""
- enable_finish: bool = Field(default=True)
- """Whether to enable finish tool"""
- enable_condensation_request: bool = Field(default=False)
- """Whether to enable condensation request tool"""
- enable_prompt_extensions: bool = Field(default=True)
- """Whether to enable prompt extensions"""
- enable_mcp: bool = Field(default=True)
- """Whether to enable MCP tools"""
- disabled_microagents: list[str] = Field(default_factory=list)
- """A list of microagents to disable (by name, without .py extension, e.g. ["github", "lint"]). Default is None."""
- enable_history_truncation: bool = Field(default=True)
- """Whether history should be truncated to continue the session when hitting LLM context length limit."""
- enable_som_visual_browsing: bool = Field(default=True)
- """Whether to enable SoM (Set of Marks) visual browsing."""
- enable_plan_mode: bool = Field(default=True)
- """Whether to enable plan mode, which uses the long horizon system message and add the new tool - task_tracker - for planning, tracking and executing complex tasks."""
- enable_stuck_detection: bool = Field(default=True)
- """Whether to enable stuck/loop detection. When disabled, the agent will not automatically detect and recover from loops."""
- extended: ExtendedConfig = Field(default_factory=lambda: ExtendedConfig({}))
- """Extended configuration for the agent."""
- runtime: str | None = Field(default=None)
- """Runtime type (e.g., 'docker', 'local', 'cli') used for runtime-specific tool behavior."""
-
- # Allow extra fields for backwards compatibility with old config.toml files
- # that may have condenser or model_routing sections
- model_config = ConfigDict(extra='ignore')
-
- @property
- def resolved_system_prompt_filename(self) -> str:
- """
- Returns the appropriate system prompt filename based on the agent configuration.
- When enable_plan_mode is True, automatically uses the long horizon system prompt
- unless a custom system_prompt_filename was explicitly set (not the default).
- """
- if self.enable_plan_mode and self.system_prompt_filename == 'system_prompt.j2':
- return 'system_prompt_long_horizon.j2'
- return self.system_prompt_filename
-
- @classmethod
- def from_toml_section(cls, data: dict) -> dict[str, AgentConfig]:
- """Create a mapping of AgentConfig instances from a toml dictionary representing the [agent] section.
-
- The default configuration is built from all non-dict keys in data.
- Then, each key with a dict value is treated as a custom agent configuration, and its values override
- the default configuration.
-
- Example:
- Apply generic agent config with custom agent overrides, e.g.
- [agent]
- enable_prompt_extensions = false
- [agent.BrowsingAgent]
- enable_prompt_extensions = true
- results in prompt_extensions being true for BrowsingAgent but false for others.
-
- Returns:
- dict[str, AgentConfig]: A mapping where the key "agent" corresponds to the default configuration
- and additional keys represent custom configurations.
- """
- # Initialize the result mapping
- agent_mapping: dict[str, AgentConfig] = {}
-
- # Extract base config data (non-dict values)
- base_data = {}
- custom_sections: dict[str, dict] = {}
- for key, value in data.items():
- if isinstance(value, dict):
- custom_sections[key] = value
- else:
- base_data[key] = value
-
- # Try to create the base config
- try:
- base_config = cls.model_validate(base_data)
- agent_mapping['agent'] = base_config
- except ValidationError as e:
- logger.warning(f'Invalid base agent configuration: {e}. Using defaults.')
- # If base config fails, create a default one
- base_config = cls()
- # Still add it to the mapping
- agent_mapping['agent'] = base_config
-
- return agent_mapping
diff --git a/openhands/core/config/extended_config.py b/openhands/core/config/extended_config.py
deleted file mode 100644
index 75a443b3b4..0000000000
--- a/openhands/core/config/extended_config.py
+++ /dev/null
@@ -1,48 +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 typing import Any
-
-from pydantic import RootModel
-
-
-class ExtendedConfig(RootModel[dict[str, Any]]):
- """Configuration for extended functionalities.
-
- This is implemented as a root model so that the entire input is stored
- as the root value. This allows arbitrary keys to be stored and later
- accessed via attribute or dictionary-style access.
- """
-
- def __str__(self) -> str:
- # Use the root dict to build a string representation.
- root_dict: dict[str, Any] = self.model_dump()
- attr_str = [f'{k}={repr(v)}' for k, v in root_dict.items()]
- return f'ExtendedConfig({", ".join(attr_str)})'
-
- def __repr__(self) -> str:
- return self.__str__()
-
- @classmethod
- def from_dict(cls, data: dict[str, Any]) -> 'ExtendedConfig':
- # Create an instance directly by wrapping the input dict.
- return cls(data)
-
- def __getitem__(self, key: str) -> Any:
- # Provide dictionary-like access via the root dict.
- root_dict: dict[str, Any] = self.model_dump()
- return root_dict[key]
-
- def __getattr__(self, key: str) -> Any:
- # Fallback for attribute access using the root dict.
- try:
- root_dict: dict[str, Any] = self.model_dump()
- return root_dict[key]
- except KeyError as e:
- raise AttributeError(
- f"'ExtendedConfig' object has no attribute '{key}'"
- ) from e
diff --git a/openhands/core/config/openhands_config.py b/openhands/core/config/openhands_config.py
index 1b0d19b190..2d8ec090f8 100644
--- a/openhands/core/config/openhands_config.py
+++ b/openhands/core/config/openhands_config.py
@@ -11,14 +11,12 @@ from typing import Any, ClassVar
from pydantic import BaseModel, ConfigDict, Field, SecretStr
from openhands.core import logger
-from openhands.core.config.agent_config import AgentConfig
from openhands.core.config.config_utils import (
DEFAULT_WORKSPACE_MOUNT_PATH_IN_SANDBOX,
OH_DEFAULT_AGENT,
OH_MAX_ITERATIONS,
model_defaults_to_dict,
)
-from openhands.core.config.extended_config import ExtendedConfig
from openhands.core.config.llm_config import LLMConfig
from openhands.core.config.mcp_config import MCPConfig
from openhands.core.config.sandbox_config import SandboxConfig
@@ -31,8 +29,6 @@ class OpenHandsConfig(BaseModel):
Attributes:
llms: Dictionary mapping LLM names to their configurations.
The default configuration is stored under the 'llm' key.
- agents: Dictionary mapping agent names to their configurations.
- The default configuration is stored under the 'agent' key.
default_agent: Name of the default agent to use.
sandbox: Sandbox configuration settings.
security: Security configuration settings.
@@ -66,11 +62,9 @@ class OpenHandsConfig(BaseModel):
"""
llms: dict[str, LLMConfig] = Field(default_factory=dict)
- agents: dict[str, AgentConfig] = Field(default_factory=dict)
default_agent: str = Field(default=OH_DEFAULT_AGENT)
sandbox: SandboxConfig = Field(default_factory=SandboxConfig)
security: SecurityConfig = Field(default_factory=SecurityConfig)
- extended: ExtendedConfig = Field(default_factory=lambda: ExtendedConfig({}))
runtime: str = Field(default='docker')
file_store: str = Field(default='local')
file_store_path: str = Field(default='~/.openhands')
@@ -145,34 +139,6 @@ class OpenHandsConfig(BaseModel):
def set_llm_config(self, value: LLMConfig, name: str = 'llm') -> None:
self.llms[name] = value
- def get_agent_config(self, name: str = 'agent') -> AgentConfig:
- """'agent' is the name for default config (for backward compatibility prior to 0.8)."""
- if name in self.agents:
- return self.agents[name]
- if 'agent' not in self.agents:
- self.agents['agent'] = AgentConfig()
- return self.agents['agent']
-
- def set_agent_config(self, value: AgentConfig, name: str = 'agent') -> None:
- self.agents[name] = value
-
- def get_agent_to_llm_config_map(self) -> dict[str, LLMConfig]:
- """Get a map of agent names to llm configs."""
- return {name: self.get_llm_config_from_agent(name) for name in self.agents}
-
- def get_llm_config_from_agent_config(self, agent_config: AgentConfig):
- llm_config_name = (
- agent_config.llm_config if agent_config.llm_config is not None else 'llm'
- )
- return self.get_llm_config(llm_config_name)
-
- def get_llm_config_from_agent(self, name: str = 'agent') -> LLMConfig:
- agent_config: AgentConfig = self.get_agent_config(name)
- return self.get_llm_config_from_agent_config(agent_config)
-
- def get_agent_configs(self) -> dict[str, AgentConfig]:
- return self.agents
-
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)
diff --git a/openhands/core/config/utils.py b/openhands/core/config/utils.py
index 1656be5508..81be5b3a29 100644
--- a/openhands/core/config/utils.py
+++ b/openhands/core/config/utils.py
@@ -22,9 +22,7 @@ from pydantic import BaseModel, SecretStr, ValidationError
from openhands.app_server.file_store import get_file_store
from openhands.app_server.file_store.files import FileStore
from openhands.core import logger
-from openhands.core.config.agent_config import AgentConfig
from openhands.core.config.arg_utils import get_headless_parser
-from openhands.core.config.extended_config import ExtendedConfig
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
@@ -126,9 +124,6 @@ def load_from_env(
# load default LLM config from env
default_llm_config = cfg.get_llm_config()
set_attr_from_env(default_llm_config, 'LLM_')
- # load default agent config from env
- default_agent_config = cfg.get_agent_config()
- set_attr_from_env(default_agent_config, 'AGENT_')
def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None:
@@ -188,17 +183,6 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None
f'Unknown config key "{key}" in [core] section'
)
- # Process agent section if present
- if 'agent' in toml_config:
- try:
- agent_mapping = AgentConfig.from_toml_section(toml_config['agent'])
- for agent_key, agent_conf in agent_mapping.items():
- cfg.set_agent_config(agent_conf, agent_key)
- except (TypeError, KeyError, ValidationError) as e:
- logger.openhands_logger.warning(
- f'Cannot parse [agent] config from toml, values have not been applied.\nError: {e}'
- )
-
# Process llm section if present
if 'llm' in toml_config:
try:
@@ -253,27 +237,19 @@ def load_from_toml(cfg: OpenHandsConfig, toml_file: str = 'config.toml') -> None
except ValueError:
raise ValueError('Error in MCP sections in config.toml')
- # Process extended section if present
- if 'extended' in toml_config:
- try:
- cfg.extended = ExtendedConfig(toml_config['extended'])
- except (TypeError, KeyError, ValidationError) as e:
- logger.openhands_logger.warning(
- f'Cannot parse [extended] config from toml, values have not been applied.\nError: {e}'
- )
-
# Check for unknown sections
- # Note: 'condenser', 'model_routing', and 'kubernetes' are kept for backwards
- # compatibility with old config files - they are silently ignored
+ # Note: 'agent', 'extended', 'condenser', 'model_routing', and 'kubernetes'
+ # are kept for backwards compatibility with old config files - they are
+ # silently ignored
known_sections = {
'core',
- 'extended',
- 'agent',
'llm',
'security',
'sandbox',
- 'condenser', # Legacy, ignored
'mcp',
+ 'agent', # Legacy, ignored
+ 'extended', # Legacy, ignored
+ 'condenser', # Legacy, ignored
'kubernetes', # Legacy, ignored
'model_routing', # Legacy, ignored
}
@@ -369,72 +345,6 @@ def finalize_config(cfg: OpenHandsConfig) -> None:
)
)
- # If CLIRuntime is selected, disable Jupyter for all agents
- # Assuming 'cli' is the identifier for CLIRuntime
- if cfg.runtime and cfg.runtime.lower() == 'cli':
- for age_nt_name, agent_config in cfg.agents.items():
- if agent_config.enable_jupyter:
- agent_config.enable_jupyter = False
- if agent_config.enable_browsing:
- agent_config.enable_browsing = False
- logger.openhands_logger.debug(
- 'Automatically disabled Jupyter plugin and browsing for all agents '
- 'because CLIRuntime is selected and does not support IPython execution.'
- )
-
-
-def get_agent_config_arg(
- agent_config_arg: str, toml_file: str = 'config.toml'
-) -> AgentConfig | None:
- """Get a group of agent settings from the config file.
-
- A group in config.toml can look like this:
-
- ```
- [agent.default]
- enable_prompt_extensions = false
- ```
-
- The user-defined group name, like "default", is the argument to this function. The function will load the AgentConfig object
- with the settings of this group, from the config file, and set it as the AgentConfig object for the app.
-
- Note that the group must be under "agent" group, or in other words, the group name must start with "agent.".
-
- Args:
- agent_config_arg: The group of agent settings to get from the config.toml file.
- toml_file: Path to the configuration file to read from. Defaults to 'config.toml'.
-
- Returns:
- AgentConfig: The AgentConfig object with the settings from the config file.
- """
- # keep only the name, just in case
- agent_config_arg = agent_config_arg.strip('[]')
-
- # truncate the prefix, just in case
- if agent_config_arg.startswith('agent.'):
- agent_config_arg = agent_config_arg[6:]
-
- logger.openhands_logger.debug(f'Loading agent config from {agent_config_arg}')
-
- # load the toml file
- 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'Config file not found: {e}')
- return None
- except toml.TomlDecodeError as e:
- logger.openhands_logger.error(
- f'Cannot parse agent group from {agent_config_arg}. Exception: {e}'
- )
- return None
-
- # update the agent config with the specified section
- if 'agent' in toml_config and agent_config_arg in toml_config['agent']:
- return AgentConfig(**toml_config['agent'][agent_config_arg])
- logger.openhands_logger.debug(f'Loading from toml failed for {agent_config_arg}')
- return None
-
def get_llm_config_arg(
llm_config_arg: str, toml_file: str = 'config.toml'
diff --git a/tests/unit/core/config/test_config.py b/tests/unit/core/config/test_config.py
index 22f38f9add..6036a24440 100644
--- a/tests/unit/core/config/test_config.py
+++ b/tests/unit/core/config/test_config.py
@@ -5,7 +5,6 @@ from io import StringIO
import pytest
from openhands.core.config import (
- AgentConfig,
LLMConfig,
OpenHandsConfig,
finalize_config,
@@ -65,7 +64,6 @@ def test_compat_env_to_config(monkeypatch, setup_env):
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 isinstance(config.get_agent_config(), AgentConfig)
assert config.default_agent == 'CodeActAgent'
assert config.sandbox.timeout == 10
@@ -102,13 +100,6 @@ api_key = "toml-api-key"
model = "some-cheap-model"
api_key = "cheap-model-api-key"
-[agent]
-enable_prompt_extensions = true
-
-[agent.BrowsingAgent]
-llm_config = "cheap"
-enable_prompt_extensions = false
-
[sandbox]
timeout = 1
volumes = "/opt/files2/workspace:/workspace:rw"
@@ -120,17 +111,10 @@ default_agent = "TestAgent"
load_from_toml(default_config, temp_toml_file)
- # default llm & agent configs
+ # default llm config
assert default_config.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.get_agent_config().enable_prompt_extensions is True
-
- # undefined agent config inherits default ones
- assert (
- default_config.get_llm_config_from_agent('CodeActAgent')
- == default_config.get_llm_config()
- )
assert default_config.sandbox.volumes == '/opt/files2/workspace:/workspace:rw'
assert default_config.sandbox.timeout == 1
@@ -222,7 +206,6 @@ user_id = 1001
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_from_agent().model == 'test-model'
assert default_config.get_llm_config().api_key.get_secret_value() == 'env-api-key'
# Environment variable should override TOML value
@@ -396,10 +379,6 @@ def test_defaults_dict_after_updates(default_config):
updated_config = OpenHandsConfig()
updated_config.get_llm_config().api_key = 'updated-api-key'
updated_config.get_llm_config('llm').api_key = 'updated-api-key'
- updated_config.get_llm_config_from_agent('agent').api_key = 'updated-api-key'
- updated_config.get_llm_config_from_agent(
- 'BrowsingAgent'
- ).api_key = 'updated-api-key'
updated_config.default_agent = 'BrowsingAgent'
defaults_after_updates = updated_config.defaults_dict
@@ -493,7 +472,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.get_agent_config() is not None
assert default_config.sandbox is not None
@@ -507,9 +485,6 @@ def test_core_not_in_toml(default_config, temp_toml_file):
[llm]
model = "test-model"
-[agent]
-enable_prompt_extensions = true
-
[sandbox]
timeout = 1
base_container_image = "custom_image"
@@ -521,7 +496,6 @@ security_analyzer = "semgrep"
load_from_toml(default_config, temp_toml_file)
assert default_config.get_llm_config().model == 'test-model'
- assert default_config.get_agent_config().enable_prompt_extensions is True
assert default_config.sandbox.base_container_image == 'custom_image'
assert default_config.sandbox.user_id == 1001
assert default_config.security.security_analyzer == 'semgrep'
@@ -721,22 +695,9 @@ def test_api_keys_repr_str():
f"Unexpected attribute '{attr_name}' contains 'token' in LLMConfig"
)
- # Test AgentConfig
- # No attrs in AgentConfig have 'key' or 'token' in their name
- agent_config = AgentConfig(enable_prompt_extensions=True, enable_browsing=False)
- for attr_name in AgentConfig.model_fields.keys():
- if not attr_name.startswith('__'):
- assert 'key' not in attr_name.lower(), (
- f"Unexpected attribute '{attr_name}' contains 'key' in AgentConfig"
- )
- assert 'token' not in attr_name.lower() or 'tokens' in attr_name.lower(), (
- f"Unexpected attribute '{attr_name}' contains 'token' in AgentConfig"
- )
-
# Test OpenHandsConfig
app_config = OpenHandsConfig(
llms={'llm': llm_config},
- agents={'agent': agent_config},
search_api_key='my_search_api_key',
)
diff --git a/tests/unit/core/config/test_config_extended.py b/tests/unit/core/config/test_config_extended.py
deleted file mode 100644
index 0ee5fcfe87..0000000000
--- a/tests/unit/core/config/test_config_extended.py
+++ /dev/null
@@ -1,171 +0,0 @@
-import os
-
-import pytest
-
-from openhands.core.config.extended_config import ExtendedConfig
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.utils import load_from_toml
-
-
-def test_extended_config_from_dict():
- """Test that ExtendedConfig.from_dict successfully creates an instance.
-
- This test verifies that the from_dict method correctly creates an instance
- from a dictionary containing arbitrary extra keys.
- """
- data = {'foo': 'bar', 'baz': 123, 'flag': True}
- ext_cfg = ExtendedConfig.from_dict(data)
-
- # Check that the keys are accessible both as attributes and via __getitem__
- assert ext_cfg.foo == 'bar'
- assert ext_cfg['baz'] == 123
- assert ext_cfg.flag is True
- # Verify the root dictionary contains all keys
- assert ext_cfg.root == data
-
-
-def test_extended_config_empty():
- """Test that an empty ExtendedConfig can be created and accessed."""
- ext_cfg = ExtendedConfig.from_dict({})
- assert ext_cfg.root == {}
-
- # Creating directly should also work
- ext_cfg2 = ExtendedConfig({})
- assert ext_cfg2.root == {}
-
-
-def test_extended_config_str_and_repr():
- """Test that __str__ and __repr__ return the correct string representations.
-
- This test verifies that the string representations of the ExtendedConfig instance
- include the expected key/value pairs.
- """
- data = {'alpha': 'test', 'beta': 42}
- ext_cfg = ExtendedConfig.from_dict(data)
- string_repr = str(ext_cfg)
- repr_str = repr(ext_cfg)
-
- # Ensure the representations include our key/value pairs
- assert "alpha='test'" in string_repr
- assert 'beta=42' in string_repr
-
- # __repr__ should match __str__
- assert string_repr == repr_str
-
-
-def test_extended_config_getitem_and_getattr():
- """Test that __getitem__ and __getattr__ can be used to access values.
-
- This test verifies that values in the ExtendedConfig instance can be accessed
- both via attribute access and dictionary-style access.
- """
- data = {'key1': 'value1', 'key2': 2}
- ext_cfg = ExtendedConfig.from_dict(data)
-
- # Attribute access
- assert ext_cfg.key1 == 'value1'
- # Dictionary-style access
- assert ext_cfg['key2'] == 2
-
-
-def test_extended_config_invalid_key():
- """Test that accessing a non-existent key via attribute access raises AttributeError."""
- data = {'existing': 'yes'}
- ext_cfg = ExtendedConfig.from_dict(data)
-
- with pytest.raises(AttributeError):
- _ = ext_cfg.nonexistent
-
- with pytest.raises(KeyError):
- _ = ext_cfg['nonexistent']
-
-
-def test_app_config_extended_from_toml(tmp_path: os.PathLike) -> None:
- """Test that the [extended] section in a TOML file is correctly loaded.
-
- This test verifies that the [extended] section is loaded into OpenHandsConfig.extended
- and that it accepts arbitrary keys.
- """
- # Create a temporary TOML file with multiple sections including [extended]
- config_content = """
-[core]
-workspace_base = "/tmp/workspace"
-
-[llm]
-model = "test-model"
-api_key = "toml-api-key"
-
-[extended]
-custom1 = "custom_value"
-custom2 = 42
-llm = "overridden" # even a key like 'llm' is accepted in extended
-
-[agent]
-enable_prompt_extensions = true
-"""
- config_file = tmp_path / 'config.toml'
- config_file.write_text(config_content)
-
- # Load the TOML into the OpenHandsConfig instance
- config = OpenHandsConfig()
- load_from_toml(config, str(config_file))
-
- # Verify that extended section is applied
- assert config.extended.custom1 == 'custom_value'
- assert config.extended.custom2 == 42
- # Even though 'llm' is defined in extended, it should not affect the main llm config.
- assert config.get_llm_config().model == 'test-model'
-
-
-def test_app_config_extended_default(tmp_path: os.PathLike) -> None:
- """Test default behavior when no [extended] section exists.
-
- This test verifies that if there is no [extended] section in the TOML file,
- OpenHandsConfig.extended remains its default (empty) ExtendedConfig.
- """
- config_content = """
-[core]
-workspace_base = "/tmp/workspace"
-
-[llm]
-model = "test-model"
-api_key = "toml-api-key"
-
-[agent]
-enable_prompt_extensions = true
-"""
- config_file = tmp_path / 'config.toml'
- config_file.write_text(config_content)
-
- config = OpenHandsConfig()
- load_from_toml(config, str(config_file))
-
- # Extended config should be empty
- assert config.extended.root == {}
-
-
-def test_app_config_extended_random_keys(tmp_path: os.PathLike) -> None:
- """Test that the extended section accepts arbitrary keys.
-
- This test verifies that the extended section accepts arbitrary keys,
- including ones not defined in any schema.
- """
- config_content = """
-[core]
-workspace_base = "/tmp/workspace"
-
-[extended]
-random_key = "random_value"
-another_key = 3.14
-"""
- config_file = tmp_path / 'config.toml'
- config_file.write_text(config_content)
-
- config = OpenHandsConfig()
- load_from_toml(config, str(config_file))
-
- # Verify that extended config holds the arbitrary keys with correct values.
- assert config.extended.random_key == 'random_value'
- assert config.extended.another_key == 3.14
- # Verify the root dictionary contains all keys
- assert config.extended.root == {'random_key': 'random_value', 'another_key': 3.14}
diff --git a/tests/unit/core/config/test_config_utils.py b/tests/unit/core/config/test_config_utils.py
deleted file mode 100644
index c317b16304..0000000000
--- a/tests/unit/core/config/test_config_utils.py
+++ /dev/null
@@ -1,161 +0,0 @@
-import pytest
-
-from openhands.core.config.agent_config import AgentConfig
-from openhands.core.config.openhands_config import OpenHandsConfig
-from openhands.core.config.utils import finalize_config
-
-# Define a dummy agent name often used in tests or as a default
-DEFAULT_AGENT_NAME = 'CodeActAgent'
-
-
-def test_finalize_config_cli_disables_jupyter_and_browsing_when_true():
- """Test that finalize_config sets enable_jupyter and enable_browsing to False
- when runtime is 'cli' and they were initially True.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'cli'
-
- agent_config = AgentConfig(enable_jupyter=True, enable_browsing=True)
- app_config.agents[DEFAULT_AGENT_NAME] = agent_config
-
- finalize_config(app_config)
-
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_jupyter, (
- "enable_jupyter should be False when runtime is 'cli'"
- )
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_browsing, (
- "enable_browsing should be False when runtime is 'cli'"
- )
-
-
-def test_finalize_config_cli_keeps_jupyter_and_browsing_false_when_false():
- """Test that finalize_config keeps enable_jupyter and enable_browsing as False
- when runtime is 'cli' and they were initially False.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'cli'
-
- agent_config = AgentConfig(enable_jupyter=False, enable_browsing=False)
- app_config.agents[DEFAULT_AGENT_NAME] = agent_config
-
- finalize_config(app_config)
-
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_jupyter, (
- "enable_jupyter should remain False when runtime is 'cli' and initially False"
- )
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_browsing, (
- "enable_browsing should remain False when runtime is 'cli' and initially False"
- )
-
-
-def test_finalize_config_other_runtime_keeps_jupyter_and_browsing_true_by_default():
- """Test that finalize_config keeps enable_jupyter and enable_browsing as True (default)
- when runtime is not 'cli'.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'docker' # A non-cli runtime
-
- # AgentConfig defaults enable_jupyter and enable_browsing to True
- agent_config = AgentConfig()
- app_config.agents[DEFAULT_AGENT_NAME] = agent_config
-
- finalize_config(app_config)
-
- assert app_config.agents[DEFAULT_AGENT_NAME].enable_jupyter, (
- 'enable_jupyter should remain True by default for non-cli runtimes'
- )
- assert app_config.agents[DEFAULT_AGENT_NAME].enable_browsing, (
- 'enable_browsing should remain True by default for non-cli runtimes'
- )
-
-
-def test_finalize_config_other_runtime_keeps_jupyter_and_browsing_false_if_set():
- """Test that finalize_config keeps enable_jupyter and enable_browsing as False
- when runtime is not 'cli' but they were explicitly set to False.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'docker' # A non-cli runtime
-
- agent_config = AgentConfig(enable_jupyter=False, enable_browsing=False)
- app_config.agents[DEFAULT_AGENT_NAME] = agent_config
-
- finalize_config(app_config)
-
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_jupyter, (
- 'enable_jupyter should remain False for non-cli runtimes if explicitly set to False'
- )
- assert not app_config.agents[DEFAULT_AGENT_NAME].enable_browsing, (
- 'enable_browsing should remain False for non-cli runtimes if explicitly set to False'
- )
-
-
-def test_finalize_config_no_agents_defined():
- """Test that finalize_config runs without error if no agents are defined in the config,
- even when runtime is 'cli'.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'cli'
- # No agents are added to app_config.agents
-
- try:
- finalize_config(app_config)
- except Exception as e:
- pytest.fail(f'finalize_config raised an exception with no agents defined: {e}')
-
-
-def test_finalize_config_multiple_agents_cli_runtime():
- """Test that finalize_config correctly disables jupyter and browsing for multiple agents
- when runtime is 'cli'.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'cli'
-
- agent_config1 = AgentConfig(enable_jupyter=True, enable_browsing=True)
- agent_config2 = AgentConfig(enable_jupyter=True, enable_browsing=True)
- app_config.agents['Agent1'] = agent_config1
- app_config.agents['Agent2'] = agent_config2
-
- finalize_config(app_config)
-
- assert not app_config.agents['Agent1'].enable_jupyter, (
- 'Jupyter should be disabled for Agent1'
- )
- assert not app_config.agents['Agent1'].enable_browsing, (
- 'Browsing should be disabled for Agent1'
- )
- assert not app_config.agents['Agent2'].enable_jupyter, (
- 'Jupyter should be disabled for Agent2'
- )
- assert not app_config.agents['Agent2'].enable_browsing, (
- 'Browsing should be disabled for Agent2'
- )
-
-
-def test_finalize_config_multiple_agents_other_runtime():
- """Test that finalize_config correctly keeps jupyter and browsing enabled (or as set)
- for multiple agents when runtime is not 'cli'.
- """
- app_config = OpenHandsConfig()
- app_config.runtime = 'docker'
-
- agent_config1 = AgentConfig(enable_jupyter=True, enable_browsing=True) # Defaults
- agent_config2 = AgentConfig(
- enable_jupyter=False, enable_browsing=False
- ) # Explicitly false
- app_config.agents['Agent1'] = agent_config1
- app_config.agents['Agent2'] = agent_config2
-
- finalize_config(app_config)
-
- assert app_config.agents['Agent1'].enable_jupyter, (
- 'Jupyter should be True for Agent1'
- )
- assert app_config.agents['Agent1'].enable_browsing, (
- 'Browsing should be True for Agent1'
- )
- assert not app_config.agents['Agent2'].enable_jupyter, (
- 'Jupyter should be False for Agent2'
- )
- assert not app_config.agents['Agent2'].enable_browsing, (
- 'Browsing should be False for Agent2'
- )