Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Remove unused items from openhands.core package (#14201)

Tim O'Farrell1ee548b90935
diff --git a/openhands/core/config/__init__.py b/openhands/core/config/__init__.py
index af27a65ae2..dd8fb92c86 100644
--- a/openhands/core/config/__init__.py
+++ b/openhands/core/config/__init__.py
@@ -6,7 +6,6 @@ from openhands.core.config.arg_utils import (
from openhands.core.config.config_utils import (
OH_DEFAULT_AGENT,
OH_MAX_ITERATIONS,
- get_field_info,
)
from openhands.core.config.extended_config import ExtendedConfig
from openhands.core.config.llm_config import LLMConfig
@@ -45,7 +44,6 @@ __all__ = [
'finalize_config',
'get_agent_config_arg',
'get_llm_config_arg',
- 'get_field_info',
'get_headless_parser',
'get_evaluation_parser',
'parse_arguments',
diff --git a/openhands/core/const/guide_url.py b/openhands/core/const/guide_url.py
deleted file mode 100644
index 37ba5e8418..0000000000
--- a/openhands/core/const/guide_url.py
+++ /dev/null
@@ -1,8 +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
-TROUBLESHOOTING_URL = 'https://docs.all-hands.dev/usage/troubleshooting'
diff --git a/openhands/core/exceptions.py b/openhands/core/exceptions.py
deleted file mode 100644
index a58f2669f6..0000000000
--- a/openhands/core/exceptions.py
+++ /dev/null
@@ -1,218 +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
-# ============================================
-# Agent Exceptions
-# ============================================
-
-
-class AgentError(Exception):
- """Base class for all agent exceptions."""
-
- pass
-
-
-class AgentAlreadyRegisteredError(AgentError):
- def __init__(self, name: str | None = None) -> None:
- if name is not None:
- message = f"Agent class already registered under '{name}'"
- else:
- message = 'Agent class already registered'
- super().__init__(message)
-
-
-class AgentNotRegisteredError(AgentError):
- def __init__(self, name: str | None = None) -> None:
- if name is not None:
- message = f"No agent class registered under '{name}'"
- else:
- message = 'No agent class registered'
- super().__init__(message)
-
-
-class AgentStuckInLoopError(AgentError):
- def __init__(self, message: str = 'Agent got stuck in a loop') -> None:
- super().__init__(message)
-
-
-# ============================================
-# LLM Exceptions
-# ============================================
-
-
-# This exception gets sent back to the LLM
-# It might be malformed JSON
-class LLMMalformedActionError(Exception):
- def __init__(self, message: str = 'Malformed response') -> None:
- self.message = message
- super().__init__(message)
-
- def __str__(self) -> str:
- return self.message
-
-
-# This exception gets sent back to the LLM
-# For some reason, the agent did not return an action
-class LLMNoActionError(Exception):
- def __init__(self, message: str = 'Agent must return an action') -> None:
- super().__init__(message)
-
-
-# This exception gets sent back to the LLM
-# The LLM output did not include an action, or the action was not the expected type
-class LLMResponseError(Exception):
- def __init__(
- self, message: str = 'Failed to retrieve action from LLM response'
- ) -> None:
- super().__init__(message)
-
-
-# This exception should be retried
-# Typically, after retry with a non-zero temperature, the LLM will return a response
-class LLMNoResponseError(Exception):
- def __init__(
- self,
- message: str = 'LLM did not return a response. This is only seen in Gemini models so far.',
- ) -> None:
- super().__init__(message)
-
-
-class UserCancelledError(Exception):
- def __init__(self, message: str = 'User cancelled the request') -> None:
- super().__init__(message)
-
-
-class OperationCancelled(Exception):
- """Exception raised when an operation is cancelled (e.g. by a keyboard interrupt)."""
-
- def __init__(self, message: str = 'Operation was cancelled') -> None:
- super().__init__(message)
-
-
-class LLMContextWindowExceedError(RuntimeError):
- def __init__(
- self,
- message: str = 'Conversation history longer than LLM context window limit. Consider turning on enable_history_truncation config to avoid this error',
- ) -> None:
- super().__init__(message)
-
-
-# ============================================
-# LLM function calling Exceptions
-# ============================================
-
-
-class FunctionCallConversionError(Exception):
- """Exception raised when FunctionCallingConverter failed to convert a non-function call message to a function call message.
-
- This typically happens when there's a malformed message (e.g., missing <function=...> tags). But not due to LLM output.
- """
-
- def __init__(self, message: str) -> None:
- super().__init__(message)
-
-
-class FunctionCallValidationError(Exception):
- """Exception raised when FunctionCallingConverter failed to validate a function call message.
-
- This typically happens when the LLM outputs unrecognized function call / parameter names / values.
- """
-
- def __init__(self, message: str) -> None:
- super().__init__(message)
-
-
-class FunctionCallNotExistsError(Exception):
- """Exception raised when an LLM call a tool that is not registered."""
-
- def __init__(self, message: str) -> None:
- super().__init__(message)
-
-
-# ============================================
-# Agent Runtime Exceptions
-# ============================================
-
-
-class AgentRuntimeError(Exception):
- """Base class for all agent runtime exceptions."""
-
- pass
-
-
-class AgentRuntimeBuildError(AgentRuntimeError):
- """Exception raised when an agent runtime build operation fails."""
-
- pass
-
-
-class AgentRuntimeTimeoutError(AgentRuntimeError):
- """Exception raised when an agent runtime operation times out."""
-
- pass
-
-
-class AgentRuntimeUnavailableError(AgentRuntimeError):
- """Exception raised when an agent runtime is unavailable."""
-
- pass
-
-
-class AgentRuntimeNotReadyError(AgentRuntimeUnavailableError):
- """Exception raised when an agent runtime is not ready."""
-
- pass
-
-
-class AgentRuntimeDisconnectedError(AgentRuntimeUnavailableError):
- """Exception raised when an agent runtime is disconnected."""
-
- pass
-
-
-class AgentRuntimeNotFoundError(AgentRuntimeUnavailableError):
- """Exception raised when an agent runtime is not found."""
-
- pass
-
-
-# ============================================
-# Browser Exceptions
-# ============================================
-
-
-class BrowserInitException(Exception):
- def __init__(
- self, message: str = 'Failed to initialize browser environment'
- ) -> None:
- super().__init__(message)
-
-
-class BrowserUnavailableException(Exception):
- def __init__(
- self,
- message: str = 'Browser environment is not available, please check if has been initialized',
- ) -> None:
- super().__init__(message)
-
-
-# ============================================
-# Microagent Exceptions
-# ============================================
-
-
-class MicroagentError(Exception):
- """Base exception for all microagent errors."""
-
- pass
-
-
-class MicroagentValidationError(MicroagentError):
- """Raised when there's a validation error in microagent metadata."""
-
- def __init__(self, message: str = 'Microagent validation failed') -> None:
- super().__init__(message)
diff --git a/openhands/core/message.py b/openhands/core/message.py
deleted file mode 100644
index 596ede01e7..0000000000
--- a/openhands/core/message.py
+++ /dev/null
@@ -1,165 +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 enum import Enum
-from typing import Any, Literal
-
-from litellm import ChatCompletionMessageToolCall
-from pydantic import BaseModel, Field, model_serializer
-
-
-class ContentType(Enum):
- TEXT = 'text'
- IMAGE_URL = 'image_url'
-
-
-class Content(BaseModel):
- type: str
- cache_prompt: bool = False
-
- @model_serializer(mode='plain')
- def serialize_model(
- self,
- ) -> dict[str, str | dict[str, str]] | list[dict[str, str | dict[str, str]]]:
- raise NotImplementedError('Subclasses should implement this method.')
-
-
-class TextContent(Content):
- type: str = ContentType.TEXT.value
- text: str
-
- @model_serializer(mode='plain')
- def serialize_model(self) -> dict[str, str | dict[str, str]]:
- data: dict[str, str | dict[str, str]] = {
- 'type': self.type,
- 'text': self.text,
- }
- if self.cache_prompt:
- data['cache_control'] = {'type': 'ephemeral'}
- return data
-
-
-class ImageContent(Content):
- type: str = ContentType.IMAGE_URL.value
- image_urls: list[str]
-
- @model_serializer(mode='plain')
- def serialize_model(self) -> list[dict[str, str | dict[str, str]]]:
- images: list[dict[str, str | dict[str, str]]] = []
- for url in self.image_urls:
- images.append({'type': self.type, 'image_url': {'url': url}})
- if self.cache_prompt and images:
- images[-1]['cache_control'] = {'type': 'ephemeral'}
- return images
-
-
-class Message(BaseModel):
- # NOTE: this is not the same as EventSource
- # These are the roles in the LLM's APIs
- role: Literal['user', 'system', 'assistant', 'tool']
- content: list[TextContent | ImageContent] = Field(default_factory=list)
- cache_enabled: bool = False
- vision_enabled: bool = False
- # function calling
- function_calling_enabled: bool = False
- # - tool calls (from LLM)
- tool_calls: list[ChatCompletionMessageToolCall] | None = None
- # - tool execution result (to LLM)
- tool_call_id: str | None = None
- name: str | None = None # name of the tool
- # force string serializer
- force_string_serializer: bool = False
-
- @property
- def contains_image(self) -> bool:
- return any(isinstance(content, ImageContent) for content in self.content)
-
- @model_serializer(mode='plain')
- def serialize_model(self) -> dict[str, Any]:
- # We need two kinds of serializations:
- # - into a single string: for providers that don't support list of content items (e.g. no vision, no tool calls)
- # - into a list of content items: the new APIs of providers with vision/prompt caching/tool calls
- # NOTE: remove this when litellm or providers support the new API
- if not self.force_string_serializer and (
- self.cache_enabled or self.vision_enabled or self.function_calling_enabled
- ):
- return self._list_serializer()
- # some providers, like HF and Groq/llama, don't support a list here, but a single string
- return self._string_serializer()
-
- def _string_serializer(self) -> dict[str, Any]:
- # convert content to a single string
- content = '\n'.join(
- item.text for item in self.content if isinstance(item, TextContent)
- )
- message_dict: dict[str, Any] = {'content': content, 'role': self.role}
-
- # add tool call keys if we have a tool call or response
- return self._add_tool_call_keys(message_dict)
-
- def _list_serializer(self) -> dict[str, Any]:
- content: list[dict[str, Any]] = []
- role_tool_with_prompt_caching = False
- for item in self.content:
- d = item.model_dump()
- # We have to remove cache_prompt for tool content and move it up to the message level
- # See discussion here for details: https://github.com/BerriAI/litellm/issues/6422#issuecomment-2438765472
- if self.role == 'tool' and item.cache_prompt:
- role_tool_with_prompt_caching = True
- if isinstance(item, TextContent):
- d.pop('cache_control', None)
- elif isinstance(item, ImageContent):
- # ImageContent.model_dump() always returns a list
- # We know d is a list of dicts for ImageContent
- if hasattr(d, '__iter__'):
- for d_item in d:
- if hasattr(d_item, 'pop'):
- d_item.pop('cache_control', None)
-
- if isinstance(item, TextContent):
- content.append(d)
- elif isinstance(item, ImageContent) and self.vision_enabled:
- # ImageContent.model_dump() always returns a list
- # We know d is a list for ImageContent
- content.extend([d] if isinstance(d, dict) else d)
-
- message_dict: dict[str, Any] = {'content': content, 'role': self.role}
-
- if role_tool_with_prompt_caching:
- message_dict['cache_control'] = {'type': 'ephemeral'}
-
- # add tool call keys if we have a tool call or response
- return self._add_tool_call_keys(message_dict)
-
- def _add_tool_call_keys(self, message_dict: dict[str, Any]) -> dict[str, Any]:
- """Add tool call keys if we have a tool call or response.
-
- NOTE: this is necessary for both native and non-native tool calling
- """
- # an assistant message calling a tool
- if self.tool_calls is not None:
- message_dict['tool_calls'] = [
- {
- 'id': tool_call.id,
- 'type': 'function',
- 'function': {
- 'name': tool_call.function.name,
- 'arguments': tool_call.function.arguments,
- },
- }
- for tool_call in self.tool_calls
- ]
-
- # an observation message with tool response
- if self.tool_call_id is not None:
- assert self.name is not None, (
- 'name is required when tool_call_id is not None'
- )
- message_dict['tool_call_id'] = self.tool_call_id
- message_dict['name'] = self.name
-
- return message_dict
diff --git a/openhands/core/message_format.md b/openhands/core/message_format.md
deleted file mode 100644
index a0eaea5971..0000000000
--- a/openhands/core/message_format.md
+++ /dev/null
@@ -1,96 +0,0 @@
-# OpenHands Message Format and litellm Integration
-
-## Overview
-
-OpenHands uses its own `Message` class (`openhands/core/message.py`) which provides rich content support while maintaining compatibility with litellm's message handling system.
-
-## Class Structure
-
-Our `Message` class (`openhands/core/message.py`):
-
-```python
-class Message(BaseModel):
- role: Literal['user', 'system', 'assistant', 'tool']
- content: list[TextContent | ImageContent] = Field(default_factory=list)
- cache_enabled: bool = False
- vision_enabled: bool = False
- condensable: bool = True
- function_calling_enabled: bool = False
- tool_calls: list[ChatCompletionMessageToolCall] | None = None
- tool_call_id: str | None = None
- name: str | None = None
- event_id: int = -1
-```
-
-litellm's `Message` class (`litellm/types/utils.py`):
-
-```python
-class Message(OpenAIObject):
- content: str | None
- role: Literal["assistant", "user", "system", "tool", "function"]
- tool_calls: List[ChatCompletionMessageToolCall] | None
- function_call: FunctionCall | None
- audio: ChatCompletionAudioResponse | None = None
-```
-
-## How It Works
-
-1. **Message Creation**: Our `Message` class is a Pydantic model that supports rich content (text and images) through its `content` field.
-
-2. **Serialization**: The class uses Pydantic's `@model_serializer` to convert messages into dictionaries that litellm can understand. We have two serialization methods:
-
- ```python
- def _string_serializer(self) -> dict:
- # convert content to a single string
- content = '\n'.join(item.text for item in self.content if isinstance(item, TextContent))
- message_dict: dict = {'content': content, 'role': self.role}
- return self._add_tool_call_keys(message_dict)
-
- def _list_serializer(self) -> dict:
- content: list[dict] = []
- for item in self.content:
- d = item.model_dump()
- if isinstance(item, TextContent):
- content.append(d)
- elif isinstance(item, ImageContent) and self.vision_enabled:
- content.extend(d)
- return {'content': content, 'role': self.role}
- ```
-
- The appropriate serializer is chosen based on the message's capabilities:
-
- ```python
- @model_serializer
- def serialize_model(self) -> dict:
- if self.cache_enabled or self.vision_enabled or self.function_calling_enabled:
- return self._list_serializer()
- return self._string_serializer()
- ```
-
-3. **Tool Call Handling**: Tool calls require special attention in serialization because:
-
- - They need to work with litellm's API calls (which accept both dicts and objects)
- - They need to be properly serialized for token counting
- - They need to maintain compatibility with different LLM providers' formats
-
-4. **litellm Integration**: When we pass our messages to `litellm.completion()`, litellm doesn't care about the message class type - it works with the dictionary representation. This works because:
-
- - litellm's transformation code (e.g., `litellm/llms/anthropic/chat/transformation.py`) processes messages based on their structure, not their type
- - our serialization produces dictionaries that match litellm's expected format
- - litellm handles rich content by looking at the message structure, supporting both simple string content and lists of content items
-
-5. **Provider-Specific Handling**: litellm then transforms these messages into provider-specific formats (e.g., Anthropic, OpenAI) through its transformation layers, which know how to handle both simple and rich content structures.
-
-### Token Counting
-
-To use litellm's token counter, we need to make sure that all message components (including tool calls) are properly serialized to dictionaries. This is because:
-
-- litellm's token counter expects dictionary structures
-- Tool calls need to be included in the token count
-- Different providers may count tokens differently for structured content
-
-## Note
-
-- We don't need to inherit from litellm's `Message` class because litellm works with dictionary representations, not class types
-- Our rich content model is more sophisticated than litellm's basic string content, but litellm handles it correctly through its transformation layers
-- The compatibility is maintained through proper serialization rather than inheritance
diff --git a/openhands/core/schema/__init__.py b/openhands/core/schema/__init__.py
index 8ced1a6f38..6c90382968 100644
--- a/openhands/core/schema/__init__.py
+++ b/openhands/core/schema/__init__.py
@@ -1,9 +1,5 @@
-from openhands.core.schema.action import ActionType
from openhands.core.schema.agent import AgentState
-from openhands.core.schema.observation import ObservationType
__all__ = [
- 'ActionType',
- 'ObservationType',
'AgentState',
]
diff --git a/openhands/core/schema/action.py b/openhands/core/schema/action.py
deleted file mode 100644
index ed7abd17e0..0000000000
--- a/openhands/core/schema/action.py
+++ /dev/null
@@ -1,109 +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 enum import Enum
-
-
-class ActionType(str, Enum):
- MESSAGE = 'message'
- """Represents a message.
- """
-
- SYSTEM = 'system'
- """Represents a system message.
- """
-
- START = 'start'
- """Starts a new development task OR send chat from the user. Only sent by the client.
- """
-
- READ = 'read'
- """Reads the content of a file.
- """
-
- WRITE = 'write'
- """Writes the content to a file.
- """
-
- EDIT = 'edit'
- """Edits a file by providing a draft.
- """
-
- RUN = 'run'
- """Runs a command.
- """
-
- RUN_IPYTHON = 'run_ipython'
- """Runs a IPython cell.
- """
-
- BROWSE = 'browse'
- """Opens a web page.
- """
-
- BROWSE_INTERACTIVE = 'browse_interactive'
- """Interact with the browser instance.
- """
-
- MCP = 'call_tool_mcp'
- """Interact with the MCP server.
- """
-
- DELEGATE = 'delegate'
- """Delegates a task to another agent.
- """
-
- THINK = 'think'
- """Logs a thought.
- """
-
- FINISH = 'finish'
- """If you're absolutely certain that you've completed your task and have tested your work,
- use the finish action to stop working.
- """
-
- REJECT = 'reject'
- """If you're absolutely certain that you cannot complete the task with given requirements,
- use the reject action to stop working.
- """
-
- NULL = 'null'
-
- PAUSE = 'pause'
- """Pauses the task.
- """
-
- RESUME = 'resume'
- """Resumes the task.
- """
-
- STOP = 'stop'
- """Stops the task. Must send a start action to restart a new task.
- """
-
- CHANGE_AGENT_STATE = 'change_agent_state'
-
- PUSH = 'push'
- """Push a branch to github."""
-
- SEND_PR = 'send_pr'
- """Send a PR to github."""
-
- RECALL = 'recall'
- """Retrieves content from a user workspace, microagent, or other source."""
-
- CONDENSATION = 'condensation'
- """Condenses a list of events into a summary."""
-
- CONDENSATION_REQUEST = 'condensation_request'
- """Request for condensation of a list of events."""
-
- TASK_TRACKING = 'task_tracking'
- """Views or updates the task list for task management."""
-
- LOOP_RECOVERY = 'loop_recovery'
- """Recover dead loop."""
diff --git a/openhands/core/schema/exit_reason.py b/openhands/core/schema/exit_reason.py
deleted file mode 100644
index ce007236d6..0000000000
--- a/openhands/core/schema/exit_reason.py
+++ /dev/null
@@ -1,14 +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 enum import Enum
-
-
-class ExitReason(Enum):
- INTENTIONAL = 'intentional'
- INTERRUPTED = 'interrupted'
- ERROR = 'error'
diff --git a/openhands/core/schema/observation.py b/openhands/core/schema/observation.py
deleted file mode 100644
index 6a38c66a13..0000000000
--- a/openhands/core/schema/observation.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 enum import Enum
-
-
-class ObservationType(str, Enum):
- READ = 'read'
- """The content of a file
- """
-
- WRITE = 'write'
-
- EDIT = 'edit'
-
- BROWSE = 'browse'
- """The HTML content of a URL
- """
-
- RUN = 'run'
- """The output of a command
- """
-
- RUN_IPYTHON = 'run_ipython'
- """Runs a IPython cell.
- """
-
- CHAT = 'chat'
- """A message from the user
- """
-
- DELEGATE = 'delegate'
- """The result of a task delegated to another agent
- """
-
- MESSAGE = 'message'
-
- ERROR = 'error'
-
- SUCCESS = 'success'
-
- NULL = 'null'
-
- THINK = 'think'
-
- AGENT_STATE_CHANGED = 'agent_state_changed'
-
- USER_REJECTED = 'user_rejected'
-
- CONDENSE = 'condense'
- """Result of a condensation operation."""
-
- RECALL = 'recall'
- """Result of a recall operation. This can be the workspace context, a microagent, or other types of information."""
-
- MCP = 'mcp'
- """Result of a MCP Server operation"""
-
- DOWNLOAD = 'download'
- """Result of downloading/opening a file via the browser"""
-
- TASK_TRACKING = 'task_tracking'
- """Result of a task tracking operation"""
-
- LOOP_DETECTION = 'loop_detection'
- """Results of a dead-loop detection"""
diff --git a/openhands/core/setup.py b/openhands/core/setup.py
deleted file mode 100644
index feee0db240..0000000000
--- a/openhands/core/setup.py
+++ /dev/null
@@ -1,99 +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 hashlib
-import os
-import uuid
-
-from pydantic import SecretStr
-
-from openhands.app_server.integrations.provider import (
- ProviderToken,
- ProviderType,
-)
-from openhands.app_server.secrets.secrets_models import Secrets
-from openhands.core.config import (
- OpenHandsConfig,
-)
-
-
-def get_provider_tokens():
- """Retrieve provider tokens from environment variables and return them as a dictionary.
-
- Returns:
- A dictionary mapping ProviderType to ProviderToken if tokens are found, otherwise None.
- """
- # Collect provider tokens from environment variables if available
- provider_tokens = {}
- if 'GITHUB_TOKEN' in os.environ:
- github_token = SecretStr(os.environ['GITHUB_TOKEN'])
- provider_tokens[ProviderType.GITHUB] = ProviderToken(token=github_token)
-
- if 'GITLAB_TOKEN' in os.environ:
- gitlab_token = SecretStr(os.environ['GITLAB_TOKEN'])
- provider_tokens[ProviderType.GITLAB] = ProviderToken(token=gitlab_token)
-
- if 'BITBUCKET_TOKEN' in os.environ:
- bitbucket_token = SecretStr(os.environ['BITBUCKET_TOKEN'])
- provider_tokens[ProviderType.BITBUCKET] = ProviderToken(token=bitbucket_token)
-
- # Forgejo support (e.g., Codeberg or self-hosted Forgejo)
- if 'FORGEJO_TOKEN' in os.environ:
- forgejo_token = SecretStr(os.environ['FORGEJO_TOKEN'])
- # If a base URL is provided, extract the domain to use as host override
- forgejo_base_url = os.environ.get('FORGEJO_BASE_URL', '').strip()
- host: str | None = None
- if forgejo_base_url:
- # Normalize by stripping protocol and any path (e.g., /api/v1)
- url = forgejo_base_url
- if url.startswith(('http://', 'https://')):
- try:
- from urllib.parse import urlparse
-
- parsed = urlparse(url)
- host = parsed.netloc or None
- except Exception:
- pass
- if host is None:
- host = url.replace('https://', '').replace('http://', '')
- host = host.split('/')[0].strip('/') if host else None
- provider_tokens[ProviderType.FORGEJO] = ProviderToken(
- token=forgejo_token, host=host
- )
-
- # Wrap provider tokens in Secrets if any tokens were found
- secret_store = (
- Secrets(provider_tokens=provider_tokens) if provider_tokens else None # type: ignore[arg-type]
- )
- return secret_store.provider_tokens if secret_store else None
-
-
-def generate_sid(config: OpenHandsConfig, session_name: str | None = None) -> str:
- """Generate a session id based on the session name and the jwt secret.
-
- The session ID is kept short to ensure Kubernetes resource names don't exceed
- the 63-character limit when prefixed with 'openhands-runtime-' (18 chars).
- Total length is limited to 32 characters to allow for suffixes like '-svc', '-pvc'.
- """
- session_name = session_name or str(uuid.uuid4())
- jwt_secret = config.jwt_secret
-
- hash_str = hashlib.sha256(f'{session_name}{jwt_secret}'.encode('utf-8')).hexdigest()
-
- # Limit total session ID length to 32 characters for Kubernetes compatibility:
- # - 'openhands-runtime-' (18 chars) + session_id (32 chars) = 50 chars
- # - Leaves 13 chars for suffixes like '-svc' (4), '-pvc' (4), '-ingress-code' (13)
- if len(session_name) > 16:
- # If session_name is too long, use first 16 chars + 15-char hash for better readability
- # e.g., "vscode-extension" -> "vscode-extensio-{15-char-hash}"
- session_id = f'{session_name[:16]}-{hash_str[:15]}'
- else:
- # If session_name is short enough, use it + remaining space for hash
- remaining_chars = 32 - len(session_name) - 1 # -1 for the dash
- session_id = f'{session_name}-{hash_str[:remaining_chars]}'
-
- return session_id[:32] # Ensure we never exceed 32 characters
diff --git a/tests/unit/core/message/test_image_content_validation.py b/tests/unit/core/message/test_image_content_validation.py
deleted file mode 100644
index 56a2800b7c..0000000000
--- a/tests/unit/core/message/test_image_content_validation.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""Test for ImageContent serialization behavior.
-
-Note: Image URL filtering now happens at the conversation memory level,
-not at the ImageContent serialization level. These tests verify that
-ImageContent correctly serializes whatever URLs it's given.
-"""
-
-from openhands.core.message import ImageContent
-
-
-def test_image_content_serializes_all_urls():
- """Test that ImageContent serializes all URLs it's given, including empty ones."""
- # Create ImageContent with mixed valid and invalid URLs
- image_content = ImageContent(
- image_urls=[
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
- '', # Empty string
- ' ', # Whitespace only
- 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/wA==',
- ]
- )
-
- # Serialize the content
- serialized = image_content.model_dump()
-
- # Should serialize all URLs, including empty ones (filtering happens upstream)
- assert len(serialized) == 4, (
- f'Expected 4 URLs (including empty), got {len(serialized)}'
- )
-
- expected_urls = [
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
- '',
- ' ',
- 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/wA==',
- ]
-
- for i, item in enumerate(serialized):
- assert item['type'] == 'image_url'
- assert 'image_url' in item
- assert 'url' in item['image_url']
- assert item['image_url']['url'] == expected_urls[i]
-
-
-def test_image_content_serializes_empty_urls():
- """Test that ImageContent serializes empty URLs (filtering happens upstream)."""
- # Create ImageContent with only empty URLs
- image_content = ImageContent(image_urls=['', ' '])
-
- # Serialize the content
- serialized = image_content.model_dump()
-
- # Should serialize all URLs, even empty ones
- assert len(serialized) == 2, f'Expected 2 URLs, got {serialized}'
- assert serialized[0]['image_url']['url'] == ''
- assert serialized[1]['image_url']['url'] == ' '
-
-
-def test_image_content_all_valid_urls():
- """Test that ImageContent preserves all valid URLs."""
- valid_urls = [
- 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==',
- 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAv/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFQEBAQAAAAAAAAAAAAAAAAAAAAX/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/wA==',
- ]
-
- # Create ImageContent with valid URLs
- image_content = ImageContent(image_urls=valid_urls)
-
- # Serialize the content
- serialized = image_content.model_dump()
-
- # Should preserve all valid URLs
- assert len(serialized) == len(valid_urls), (
- f'Expected {len(valid_urls)} URLs, got {len(serialized)}'
- )
-
- for i, item in enumerate(serialized):
- assert item['type'] == 'image_url'
- assert item['image_url']['url'] == valid_urls[i]
diff --git a/tests/unit/core/message/test_message_serialization.py b/tests/unit/core/message/test_message_serialization.py
deleted file mode 100644
index ed40c473cd..0000000000
--- a/tests/unit/core/message/test_message_serialization.py
+++ /dev/null
@@ -1,170 +0,0 @@
-from litellm import ChatCompletionMessageToolCall
-
-from openhands.core.message import ImageContent, Message, TextContent
-
-
-def test_message_with_vision_enabled():
- text_content1 = TextContent(text='This is a text message')
- image_content1 = ImageContent(
- image_urls=['http://example.com/image1.png', 'http://example.com/image2.png']
- )
- text_content2 = TextContent(text='This is another text message')
- image_content2 = ImageContent(
- image_urls=['http://example.com/image3.png', 'http://example.com/image4.png']
- )
-
- message: Message = Message(
- role='user',
- content=[text_content1, image_content1, text_content2, image_content2],
- vision_enabled=True,
- )
- serialized_message: dict = message.serialize_model()
-
- expected_serialized_message = {
- 'role': 'user',
- 'content': [
- {'type': 'text', 'text': 'This is a text message'},
- {
- 'type': 'image_url',
- 'image_url': {'url': 'http://example.com/image1.png'},
- },
- {
- 'type': 'image_url',
- 'image_url': {'url': 'http://example.com/image2.png'},
- },
- {'type': 'text', 'text': 'This is another text message'},
- {
- 'type': 'image_url',
- 'image_url': {'url': 'http://example.com/image3.png'},
- },
- {
- 'type': 'image_url',
- 'image_url': {'url': 'http://example.com/image4.png'},
- },
- ],
- }
-
- assert serialized_message == expected_serialized_message
- assert message.contains_image is True
-
-
-def test_message_with_only_text_content_and_vision_enabled():
- text_content1 = TextContent(text='This is a text message')
- text_content2 = TextContent(text='This is another text message')
-
- message: Message = Message(
- role='user', content=[text_content1, text_content2], vision_enabled=True
- )
- serialized_message: dict = message.serialize_model()
-
- expected_serialized_message = {
- 'role': 'user',
- 'content': [
- {'type': 'text', 'text': 'This is a text message'},
- {'type': 'text', 'text': 'This is another text message'},
- ],
- }
-
- assert serialized_message == expected_serialized_message
- assert message.contains_image is False
-
-
-def test_message_with_only_text_content_and_vision_disabled():
- text_content1 = TextContent(text='This is a text message')
- text_content2 = TextContent(text='This is another text message')
-
- message: Message = Message(
- role='user', content=[text_content1, text_content2], vision_enabled=False
- )
- serialized_message: dict = message.serialize_model()
-
- expected_serialized_message = {
- 'role': 'user',
- 'content': 'This is a text message\nThis is another text message',
- }
-
- assert serialized_message == expected_serialized_message
- assert message.contains_image is False
-
-
-def test_message_with_mixed_content_and_vision_disabled():
- # Create a message with both text and image content
- text_content1 = TextContent(text='This is a text message')
- image_content1 = ImageContent(
- image_urls=['http://example.com/image1.png', 'http://example.com/image2.png']
- )
- text_content2 = TextContent(text='This is another text message')
- image_content2 = ImageContent(
- image_urls=['http://example.com/image3.png', 'http://example.com/image4.png']
- )
-
- # Initialize Message with vision disabled
- message: Message = Message(
- role='user',
- content=[text_content1, image_content1, text_content2, image_content2],
- vision_enabled=False,
- )
- serialized_message: dict = message.serialize_model()
-
- # Expected serialization ignores images and concatenates text
- expected_serialized_message = {
- 'role': 'user',
- 'content': 'This is a text message\nThis is another text message',
- }
-
- # Assert serialized message matches expectation
- assert serialized_message == expected_serialized_message
- # Assert that images exist in the original message
- assert message.contains_image
-
-
-def test_message_tool_call_serialization():
- """Test that tool calls are properly serialized into dicts for token counting."""
- # Create a tool call
- tool_call = ChatCompletionMessageToolCall(
- id='call_123',
- type='function',
- function={'name': 'test_function', 'arguments': '{"arg1": "value1"}'},
- )
-
- # Create a message with the tool call
- message = Message(
- role='assistant',
- content=[TextContent(text='Test message')],
- tool_calls=[tool_call],
- )
-
- # Serialize the message
- serialized = message.model_dump()
-
- # Check that tool calls are properly serialized
- assert 'tool_calls' in serialized
- assert isinstance(serialized['tool_calls'], list)
- assert len(serialized['tool_calls']) == 1
-
- tool_call_dict = serialized['tool_calls'][0]
- assert isinstance(tool_call_dict, dict)
- assert tool_call_dict['id'] == 'call_123'
- assert tool_call_dict['type'] == 'function'
- assert tool_call_dict['function']['name'] == 'test_function'
- assert tool_call_dict['function']['arguments'] == '{"arg1": "value1"}'
-
-
-def test_message_tool_response_serialization():
- """Test that tool responses are properly serialized."""
- # Create a message with tool response
- message = Message(
- role='tool',
- content=[TextContent(text='Function result')],
- tool_call_id='call_123',
- name='test_function',
- )
-
- # Serialize the message
- serialized = message.model_dump()
-
- # Check that tool response fields are properly serialized
- assert 'tool_call_id' in serialized
- assert serialized['tool_call_id'] == 'call_123'
- assert 'name' in serialized
- assert serialized['name'] == 'test_function'
diff --git a/tests/unit/core/schema/test_exit_reason.py b/tests/unit/core/schema/test_exit_reason.py
deleted file mode 100644
index fb4ab3708d..0000000000
--- a/tests/unit/core/schema/test_exit_reason.py
+++ /dev/null
@@ -1,18 +0,0 @@
-from openhands.core.schema.exit_reason import ExitReason
-
-
-def test_exit_reason_enum_values():
- assert ExitReason.INTENTIONAL.value == 'intentional'
- assert ExitReason.INTERRUPTED.value == 'interrupted'
- assert ExitReason.ERROR.value == 'error'
-
-
-def test_exit_reason_enum_names():
- assert ExitReason['INTENTIONAL'] == ExitReason.INTENTIONAL
- assert ExitReason['INTERRUPTED'] == ExitReason.INTERRUPTED
- assert ExitReason['ERROR'] == ExitReason.ERROR
-
-
-def test_exit_reason_str_representation():
- assert str(ExitReason.INTENTIONAL) == 'ExitReason.INTENTIONAL'
- assert repr(ExitReason.ERROR) == "<ExitReason.ERROR: 'error'>"