Skip to content

πŸ™Œ OpenHands: AI-Driven Development

refactor: Move openhands.server content to openhands.app_server (#14254)

Tim O'Farrell5232d96dab0c
diff --git a/enterprise/integrations/bitbucket/bitbucket_manager.py b/enterprise/integrations/bitbucket/bitbucket_manager.py
index c1ffe11b4f..479c7ed98b 100644
--- a/enterprise/integrations/bitbucket/bitbucket_manager.py
+++ b/enterprise/integrations/bitbucket/bitbucket_manager.py
@@ -25,12 +25,12 @@ from storage.bitbucket_webhook_store import BitbucketWebhookStore
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.secrets.secrets_models import Secrets
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.utils.logger import openhands_logger as logger
class BitbucketManager(Manager[BitbucketViewType]):
diff --git a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
index a3d6497f63..964ec97fca 100644
--- a/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
+++ b/enterprise/integrations/bitbucket_data_center/bitbucket_dc_manager.py
@@ -26,12 +26,12 @@ from storage.bitbucket_dc_webhook_store import BitbucketDCWebhookStore
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.secrets.secrets_models import Secrets
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.utils.logger import openhands_logger as logger
class BitbucketDCManager(Manager[BitbucketDCViewType]):
diff --git a/enterprise/integrations/github/github_manager.py b/enterprise/integrations/github/github_manager.py
index 3c0f9f13cb..9990766aab 100644
--- a/enterprise/integrations/github/github_manager.py
+++ b/enterprise/integrations/github/github_manager.py
@@ -34,12 +34,12 @@ from server.auth.token_manager import TokenManager
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import AuthenticationError
from openhands.app_server.secrets.secrets_models import Secrets
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.utils.logger import openhands_logger as logger
class GithubManager(Manager[GithubViewType]):
diff --git a/enterprise/integrations/github/github_service.py b/enterprise/integrations/github/github_service.py
index 7c58ef6732..336251876e 100644
--- a/enterprise/integrations/github/github_service.py
+++ b/enterprise/integrations/github/github_service.py
@@ -4,9 +4,9 @@ from integrations.store_repo_utils import store_repositories_in_db
from pydantic import SecretStr
from server.auth.token_manager import TokenManager
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.github.github_service import GitHubService
from openhands.app_server.integrations.service_types import ProviderType, Repository
+from openhands.app_server.types import AppMode
from openhands.app_server.utils.logger import openhands_logger as logger
diff --git a/enterprise/integrations/gitlab/gitlab_manager.py b/enterprise/integrations/gitlab/gitlab_manager.py
index f857ffb31c..0e515c8d34 100644
--- a/enterprise/integrations/gitlab/gitlab_manager.py
+++ b/enterprise/integrations/gitlab/gitlab_manager.py
@@ -28,12 +28,12 @@ from server.auth.token_manager import TokenManager
from openhands.app_server.integrations.gitlab.gitlab_service import GitLabServiceImpl
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.secrets.secrets_models import Secrets
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.utils.logger import openhands_logger as logger
class GitlabManager(Manager[GitlabViewType]):
diff --git a/enterprise/integrations/gitlab/gitlab_service.py b/enterprise/integrations/gitlab/gitlab_service.py
index 2f9e6c9187..d291627d32 100644
--- a/enterprise/integrations/gitlab/gitlab_service.py
+++ b/enterprise/integrations/gitlab/gitlab_service.py
@@ -7,7 +7,6 @@ from server.auth.token_manager import TokenManager
from storage.gitlab_webhook import GitlabWebhook, WebhookStatus
from storage.gitlab_webhook_store import GitlabWebhookStore
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.gitlab.gitlab_service import GitLabService
from openhands.app_server.integrations.service_types import (
ProviderType,
@@ -15,6 +14,7 @@ from openhands.app_server.integrations.service_types import (
Repository,
RequestMethod,
)
+from openhands.app_server.types import AppMode
from openhands.app_server.utils.logger import openhands_logger as logger
diff --git a/enterprise/integrations/jira/jira_manager.py b/enterprise/integrations/jira/jira_manager.py
index 7c67fbcf7e..8aa5483dda 100644
--- a/enterprise/integrations/jira/jira_manager.py
+++ b/enterprise/integrations/jira/jira_manager.py
@@ -42,14 +42,14 @@ from storage.jira_integration_store import JiraIntegrationStore
from storage.jira_user import JiraUser
from storage.jira_workspace import JiraWorkspace
-from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.app_server.utils.http_session import httpx_verify_option
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.user_auth.user_auth import UserAuth
+from openhands.app_server.utils.http_session import httpx_verify_option
+from openhands.app_server.utils.logger import openhands_logger as logger
JIRA_CLOUD_API_URL = 'https://api.atlassian.com/ex/jira'
diff --git a/enterprise/integrations/jira_dc/jira_dc_manager.py b/enterprise/integrations/jira_dc/jira_dc_manager.py
index 1b2e135ac3..c9b31cdb35 100644
--- a/enterprise/integrations/jira_dc/jira_dc_manager.py
+++ b/enterprise/integrations/jira_dc/jira_dc_manager.py
@@ -31,15 +31,15 @@ from storage.jira_dc_workspace import JiraDcWorkspace
from openhands.app_server.integrations.provider import ProviderHandler
from openhands.app_server.integrations.service_types import Repository
-from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.app_server.utils.http_session import httpx_verify_option
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.shared import server_config
-from openhands.server.types import (
+from openhands.app_server.shared import server_config
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.user_auth.user_auth import UserAuth
+from openhands.app_server.utils.http_session import httpx_verify_option
+from openhands.app_server.utils.logger import openhands_logger as logger
class JiraDcManager(Manager[JiraDcViewInterface]):
diff --git a/enterprise/integrations/slack/slack_manager.py b/enterprise/integrations/slack/slack_manager.py
index bea2ab3cc4..b461e72b45 100644
--- a/enterprise/integrations/slack/slack_manager.py
+++ b/enterprise/integrations/slack/slack_manager.py
@@ -36,14 +36,14 @@ from openhands.app_server.integrations.service_types import (
ProviderTimeoutError,
Repository,
)
-from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.shared import server_config
-from openhands.server.types import (
+from openhands.app_server.shared import server_config
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
)
+from openhands.app_server.user_auth.user_auth import UserAuth
+from openhands.app_server.utils.logger import openhands_logger as logger
authorize_url_generator = AuthorizeUrlGenerator(
client_id=SLACK_CLIENT_ID,
diff --git a/enterprise/saas_server.py b/enterprise/saas_server.py
index 77080bf422..ea041d2412 100644
--- a/enterprise/saas_server.py
+++ b/enterprise/saas_server.py
@@ -57,11 +57,11 @@ from server.verified_models.verified_model_router import ( # noqa: E402
api_router as verified_models_router,
)
-from openhands.server.app import app as base_app # noqa: E402
-from openhands.server.middleware import ( # noqa: E402
+from openhands.app_server.app import app as base_app # noqa: E402
+from openhands.app_server.middleware import ( # noqa: E402
CacheControlMiddleware,
)
-from openhands.server.static import SPAStaticFiles # noqa: E402
+from openhands.app_server.static import SPAStaticFiles # noqa: E402
directory = os.getenv('FRONTEND_DIRECTORY', './frontend/build')
diff --git a/enterprise/server/auth/gitlab_sync.py b/enterprise/server/auth/gitlab_sync.py
index f03d6e2899..80c2ecc7da 100644
--- a/enterprise/server/auth/gitlab_sync.py
+++ b/enterprise/server/auth/gitlab_sync.py
@@ -3,8 +3,8 @@ import asyncio
from pydantic import SecretStr
from sqlalchemy import select
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.service_types import ProviderType
+from openhands.app_server.types import AppMode
from openhands.app_server.utils.logger import openhands_logger as logger
diff --git a/enterprise/server/auth/token_manager.py b/enterprise/server/auth/token_manager.py
index 72473fc49f..8365eb6988 100644
--- a/enterprise/server/auth/token_manager.py
+++ b/enterprise/server/auth/token_manager.py
@@ -48,8 +48,8 @@ from storage.offline_token_store import OfflineTokenStore
from tenacity import RetryCallState, retry, retry_if_exception_type, stop_after_attempt
from openhands.app_server.integrations.service_types import ProviderType
+from openhands.app_server.types import SessionExpiredError
from openhands.app_server.utils.http_session import httpx_verify_option
-from openhands.server.types import SessionExpiredError
class KeycloakUserInfo(BaseModel):
diff --git a/enterprise/server/config.py b/enterprise/server/config.py
index c6da43523a..0057d95759 100644
--- a/enterprise/server/config.py
+++ b/enterprise/server/config.py
@@ -22,9 +22,9 @@ from server.auth.constants import (
)
from server.constants import DEPLOYMENT_MODE
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.service_types import ProviderType
-from openhands.server.config.server_config import ServerConfig
+from openhands.app_server.server_config.server_config import ServerConfig
+from openhands.app_server.types import AppMode
def sign_token(payload: dict[str, object], jwt_secret: str, algorithm='HS256') -> str:
diff --git a/enterprise/tests/unit/integrations/jira/test_jira_manager.py b/enterprise/tests/unit/integrations/jira/test_jira_manager.py
index ab25afa7ec..e0c07f8af9 100644
--- a/enterprise/tests/unit/integrations/jira/test_jira_manager.py
+++ b/enterprise/tests/unit/integrations/jira/test_jira_manager.py
@@ -8,7 +8,7 @@ import pytest
from integrations.jira.jira_manager import JiraManager
from integrations.jira.jira_payload import JiraEventType, JiraWebhookPayload
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
diff --git a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
index a6fb1f71a5..6ed8f9e6dc 100644
--- a/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
+++ b/enterprise/tests/unit/integrations/jira_dc/test_jira_dc_manager.py
@@ -19,7 +19,7 @@ from integrations.jira_dc.jira_dc_view import (
from integrations.models import Message, SourceType
from openhands.app_server.integrations.service_types import ProviderType, Repository
-from openhands.server.types import (
+from openhands.app_server.types import (
LLMAuthenticationError,
MissingSettingsError,
SessionExpiredError,
diff --git a/openhands/README.md b/openhands/README.md
deleted file mode 100644
index 85eefc48c0..0000000000
--- a/openhands/README.md
+++ /dev/null
@@ -1,60 +0,0 @@
-
-This directory contains the core components of OpenHands.
-
-## Documentation
-
-**[Architecture Documentation](./architecture/README.md)** with diagrams covering:
- - System Architecture Overview
- - Conversation Startup & WebSocket Flow
- - Agent Execution & LLM Flow
-
-- **[External Architecture Docs](https://docs.openhands.dev/usage/architecture/backend)** - Official documentation (v0 backend architecture)
-
-## Classes
-
-The key classes in OpenHands are:
-
-* LLM: brokers all interactions with large language models. Works with any underlying completion model, thanks to LiteLLM.
-* Agent: responsible for looking at the current State, and producing an Action that moves one step closer toward the end-goal.
-* AgentController: initializes the Agent, manages State, and drive the main loop that pushes the Agent forward, step by step
-* State: represents the current state of the Agent's task. Includes things like the current step, a history of recent events, the Agent's long-term plan, etc
-* EventStream: a central hub for Events, where any component can publish Events, or listen for Events published by other components
- * Event: an Action or Observeration
- * Action: represents a request to e.g. edit a file, run a command, or send a message
- * Observation: represents information collected from the environment, e.g. file contents or command output
-* Runtime: responsible for performing Actions, and sending back Observations
- * Sandbox: the part of the runtime responsible for running commands, e.g. inside of Docker
-* Server: brokers OpenHands sessions over HTTP, e.g. to drive the frontend
- * Session: holds a single EventStream, a single AgentController, and a single Runtime. Generally represents a single task (but potentially including several user prompts)
- * ConversationManager: keeps a list of active sessions, and ensures requests are routed to the correct Session
-
-## Control Flow
-
-Here's the basic loop (in pseudocode) that drives agents.
-
-```python
-while True:
- prompt = agent.generate_prompt(state)
- response = llm.completion(prompt)
- action = agent.parse_response(response)
- observation = runtime.run(action)
- state = state.update(action, observation)
-```
-
-In reality, most of this is achieved through message passing, via the EventStream.
-The EventStream serves as the backbone for all communication in OpenHands.
-
-```mermaid
-flowchart LR
- Agent--Actions-->AgentController
- AgentController--State-->Agent
- AgentController--Actions-->EventStream
- EventStream--Observations-->AgentController
- Runtime--Observations-->EventStream
- EventStream--Actions-->Runtime
- Frontend--Actions-->EventStream
-```
-
-## Runtime
-
-Please refer to the [documentation](https://docs.openhands.dev/usage/architecture/runtime) to learn more about `Runtime`.
diff --git a/openhands/__init__.py b/openhands/__init__.py
index 5e86885fb0..840dae8091 100644
--- a/openhands/__init__.py
+++ b/openhands/__init__.py
@@ -4,6 +4,6 @@
__path__ = __import__('pkgutil').extend_path(__path__, __name__)
# Import version information for backward compatibility
-from openhands.version import __version__, get_version
+from openhands.app_server.version import __version__, get_version
__all__ = ['__version__', 'get_version']
diff --git a/openhands/app_server/app.py b/openhands/app_server/app.py
new file mode 100644
index 0000000000..0af980658c
--- /dev/null
+++ b/openhands/app_server/app.py
@@ -0,0 +1,83 @@
+import contextlib
+import os
+import warnings
+
+from fastapi.routing import Mount
+
+with warnings.catch_warnings():
+ warnings.simplefilter('ignore')
+
+from fastapi import (
+ FastAPI,
+ Request,
+)
+from fastapi.responses import JSONResponse
+
+from openhands.app_server import v1_router
+from openhands.app_server.config import get_app_lifespan_service
+from openhands.app_server.integrations.service_types import AuthenticationError
+from openhands.app_server.mcp.mcp_router import mcp_server
+from openhands.app_server.middleware import (
+ CacheControlMiddleware,
+ InMemoryRateLimiter,
+ LocalhostCORSMiddleware,
+ RateLimitMiddleware,
+)
+from openhands.app_server.static import SPAStaticFiles
+from openhands.app_server.status.status_router import router as health_router
+from openhands.app_server.version import get_version
+
+mcp_app = mcp_server.http_app(path='/mcp', stateless_http=True)
+
+
+def combine_lifespans(*lifespans):
+ # Create a combined lifespan to manage multiple session managers
+ @contextlib.asynccontextmanager
+ async def combined_lifespan(app):
+ async with contextlib.AsyncExitStack() as stack:
+ for lifespan in lifespans:
+ await stack.enter_async_context(lifespan(app))
+ yield
+
+ return combined_lifespan
+
+
+lifespans = [mcp_app.lifespan]
+app_lifespan_ = get_app_lifespan_service()
+if app_lifespan_:
+ lifespans.append(app_lifespan_.lifespan)
+
+
+app = FastAPI(
+ title='OpenHands',
+ description='OpenHands: Code Less, Make More',
+ version=get_version(),
+ lifespan=combine_lifespans(*lifespans),
+ routes=[Mount(path='/mcp', app=mcp_app)],
+)
+
+
[email protected]_handler(AuthenticationError)
+async def authentication_error_handler(request: Request, exc: AuthenticationError):
+ return JSONResponse(
+ status_code=401,
+ content=str(exc),
+ )
+
+
+app.include_router(v1_router.router)
+app.include_router(health_router)
+
+# Middleware and static file setup (merged from listen.py)
+if os.getenv('SERVE_FRONTEND', 'true').lower() == 'true':
+ if os.path.isdir('./frontend/build'):
+ app.mount(
+ '/', SPAStaticFiles(directory='./frontend/build', html=True), name='dist'
+ )
+
+app.add_middleware(LocalhostCORSMiddleware)
+app.add_middleware(CacheControlMiddleware)
+app.add_middleware(
+ RateLimitMiddleware,
+ rate_limiter=InMemoryRateLimiter(requests=10, seconds=1),
+)
diff --git a/openhands/app_server/app_conversation/live_status_app_conversation_service.py b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
index bd43f5fe05..d8c9e419be 100644
--- a/openhands/app_server/app_conversation/live_status_app_conversation_service.py
+++ b/openhands/app_server/app_conversation/live_status_app_conversation_service.py
@@ -2146,7 +2146,7 @@ class LiveStatusAppConversationServiceInjector(AppConversationServiceInjector):
# Get app_mode for SaaS mode
app_mode = None
try:
- from openhands.server.shared import server_config
+ from openhands.app_server.shared import server_config
app_mode = (
server_config.app_mode.value if server_config.app_mode else None
diff --git a/openhands/app_server/integrations/azure_devops/service/repos.py b/openhands/app_server/integrations/azure_devops/service/repos.py
index 11cd19e7d1..eb7793d169 100644
--- a/openhands/app_server/integrations/azure_devops/service/repos.py
+++ b/openhands/app_server/integrations/azure_devops/service/repos.py
@@ -1,10 +1,10 @@
"""Repository operations for Azure DevOps integration."""
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.azure_devops.service.base import (
AzureDevOpsMixinBase,
)
from openhands.app_server.integrations.service_types import ProviderType, Repository
+from openhands.app_server.types import AppMode
class AzureDevOpsReposMixin(AzureDevOpsMixinBase):
diff --git a/openhands/app_server/integrations/bitbucket/bitbucket_service.py b/openhands/app_server/integrations/bitbucket/bitbucket_service.py
index 90e25c02e8..b1a569e762 100644
--- a/openhands/app_server/integrations/bitbucket/bitbucket_service.py
+++ b/openhands/app_server/integrations/bitbucket/bitbucket_service.py
@@ -32,7 +32,7 @@ class BitBucketService(
2. Implementing all required methods
3. Setting server_config.bitbucket_service_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
"""
def __init__(
diff --git a/openhands/app_server/integrations/bitbucket/service/repos.py b/openhands/app_server/integrations/bitbucket/service/repos.py
index 023bfdcadc..46a64d5919 100644
--- a/openhands/app_server/integrations/bitbucket/service/repos.py
+++ b/openhands/app_server/integrations/bitbucket/service/repos.py
@@ -2,9 +2,9 @@ import re
from typing import Any
from urllib.parse import urlparse
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket.service.base import BitBucketMixinBase
from openhands.app_server.integrations.service_types import Repository, SuggestedTask
+from openhands.app_server.types import AppMode
class BitBucketReposMixin(BitBucketMixinBase):
diff --git a/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py b/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py
index 3559cd53f4..caa4c6c19e 100644
--- a/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py
+++ b/openhands/app_server/integrations/bitbucket_data_center/bitbucket_dc_service.py
@@ -32,7 +32,7 @@ class BitbucketDCService(
2. Implementing all required methods
3. Setting server_config.bitbucket_service_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
"""
def __init__(
diff --git a/openhands/app_server/integrations/bitbucket_data_center/service/repos.py b/openhands/app_server/integrations/bitbucket_data_center/service/repos.py
index 7403d33afe..09574ffffd 100644
--- a/openhands/app_server/integrations/bitbucket_data_center/service/repos.py
+++ b/openhands/app_server/integrations/bitbucket_data_center/service/repos.py
@@ -1,11 +1,11 @@
from typing import Any
from urllib.parse import urlparse
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket_data_center.service.base import (
BitbucketDCMixinBase,
)
from openhands.app_server.integrations.service_types import Repository, SuggestedTask
+from openhands.app_server.types import AppMode
class BitbucketDCReposMixin(BitbucketDCMixinBase):
diff --git a/openhands/app_server/integrations/forgejo/service/repos.py b/openhands/app_server/integrations/forgejo/service/repos.py
index 463c838704..364fae45be 100644
--- a/openhands/app_server/integrations/forgejo/service/repos.py
+++ b/openhands/app_server/integrations/forgejo/service/repos.py
@@ -1,8 +1,8 @@
from __future__ import annotations
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.forgejo.service.base import ForgejoMixinBase
from openhands.app_server.integrations.service_types import Repository
+from openhands.app_server.types import AppMode
class ForgejoReposMixin(ForgejoMixinBase):
diff --git a/openhands/app_server/integrations/github/github_service.py b/openhands/app_server/integrations/github/github_service.py
index aead5fe126..7f85ac6437 100644
--- a/openhands/app_server/integrations/github/github_service.py
+++ b/openhands/app_server/integrations/github/github_service.py
@@ -38,7 +38,7 @@ class GitHubService(
2. Implementing all required methods
3. Setting server_config.github_service_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
"""
BASE_URL = 'https://api.github.com'
diff --git a/openhands/app_server/integrations/gitlab/gitlab_service.py b/openhands/app_server/integrations/gitlab/gitlab_service.py
index a49f306604..cb358bce38 100644
--- a/openhands/app_server/integrations/gitlab/gitlab_service.py
+++ b/openhands/app_server/integrations/gitlab/gitlab_service.py
@@ -37,7 +37,7 @@ class GitLabService(
2. Implementing all required methods
3. Setting server_config.gitlab_service_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
"""
BASE_URL = f'https://{GITLAB_HOST}/api/v4'
diff --git a/openhands/app_server/integrations/service_types.py b/openhands/app_server/integrations/service_types.py
index 2a63944ddb..ba5efc56cc 100644
--- a/openhands/app_server/integrations/service_types.py
+++ b/openhands/app_server/integrations/service_types.py
@@ -6,7 +6,7 @@ from typing import Any, Protocol
from jinja2 import Environment, FileSystemLoader
from pydantic import BaseModel, SecretStr
-from openhands.app_server.config_api.config_models import AppMode
+from openhands.app_server.types import AppMode
class TokenResponse(BaseModel):
diff --git a/openhands/app_server/middleware.py b/openhands/app_server/middleware.py
new file mode 100644
index 0000000000..c750e000d5
--- /dev/null
+++ b/openhands/app_server/middleware.py
@@ -0,0 +1,136 @@
+import asyncio
+import logging
+from collections import defaultdict
+from datetime import datetime, timedelta
+from urllib.parse import urlparse
+
+from fastapi import Request
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import JSONResponse
+from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
+from starlette.requests import Request as StarletteRequest
+from starlette.responses import Response
+from starlette.types import ASGIApp
+
+from openhands.app_server.config import get_global_config
+
+
+class LocalhostCORSMiddleware(CORSMiddleware):
+ """Custom CORS middleware that allows any request from localhost/127.0.0.1 domains,
+ while using standard CORS rules for other origins.
+ """
+
+ def __init__(self, app: ASGIApp) -> None:
+ config = get_global_config()
+ allow_origins = tuple(config.permitted_cors_origins)
+ super().__init__(
+ app,
+ allow_origins=allow_origins,
+ allow_credentials=True,
+ allow_methods=['*'],
+ allow_headers=['*'],
+ )
+
+ def is_allowed_origin(self, origin: str) -> bool:
+ if origin and not self.allow_origins and not self.allow_origin_regex:
+ parsed = urlparse(origin)
+ hostname = parsed.hostname or ''
+
+ # Allow any localhost/127.0.0.1 origin regardless of port
+ if hostname in ['localhost', '127.0.0.1']:
+ return True
+
+ # Allow any origin when no specific origins are configured (development mode)
+ # WARNING: This disables CORS protection. Use explicit CORS origins in production.
+ logging.getLogger(__name__).warning(
+ f'No CORS origins configured, allowing origin: {origin}. '
+ 'Set OH_PERMITTED_CORS_ORIGINS for production environments.'
+ )
+ return True
+
+ # For missing origin or other origins, use the parent class's logic
+ result: bool = super().is_allowed_origin(origin)
+ return result
+
+
+class CacheControlMiddleware(BaseHTTPMiddleware):
+ """Middleware to disable caching for all routes by adding appropriate headers"""
+
+ async def dispatch(
+ self, request: Request, call_next: RequestResponseEndpoint
+ ) -> Response:
+ response = await call_next(request)
+ if request.url.path.startswith('/assets'):
+ # The content of the assets directory has fingerprinted file names so we cache aggressively
+ response.headers['Cache-Control'] = 'public, max-age=2592000, immutable'
+ else:
+ response.headers['Cache-Control'] = (
+ 'no-cache, no-store, must-revalidate, max-age=0'
+ )
+ response.headers['Pragma'] = 'no-cache'
+ response.headers['Expires'] = '0'
+ return response
+
+
+class InMemoryRateLimiter:
+ history: dict[str, list[datetime]]
+ requests: int
+ seconds: int
+ sleep_seconds: int
+
+ def __init__(self, requests: int = 2, seconds: int = 1, sleep_seconds: int = 1):
+ self.requests = requests
+ self.seconds = seconds
+ self.sleep_seconds = sleep_seconds
+ self.history = defaultdict(list)
+ self.sleep_seconds = sleep_seconds
+
+ def _clean_old_requests(self, key: str) -> None:
+ now = datetime.now()
+ cutoff = now - timedelta(seconds=self.seconds)
+ self.history[key] = [ts for ts in self.history[key] if ts > cutoff]
+
+ async def __call__(self, request: Request) -> bool:
+ key = request.client.host
+ now = datetime.now()
+
+ self._clean_old_requests(key)
+
+ self.history[key].append(now)
+
+ if len(self.history[key]) > self.requests * 2:
+ return False
+ elif len(self.history[key]) > self.requests:
+ if self.sleep_seconds > 0:
+ await asyncio.sleep(self.sleep_seconds)
+ return True
+ else:
+ return False
+
+ return True
+
+
+class RateLimitMiddleware(BaseHTTPMiddleware):
+ def __init__(self, app: ASGIApp, rate_limiter: InMemoryRateLimiter):
+ super().__init__(app)
+ self.rate_limiter = rate_limiter
+
+ async def dispatch(
+ self, request: Request, call_next: RequestResponseEndpoint
+ ) -> Response:
+ if not self.is_rate_limited_request(request):
+ return await call_next(request)
+ ok = await self.rate_limiter(request)
+ if not ok:
+ return JSONResponse(
+ status_code=429,
+ content={'message': 'Too many requests'},
+ headers={'Retry-After': '1'},
+ )
+ return await call_next(request)
+
+ def is_rate_limited_request(self, request: StarletteRequest) -> bool:
+ if request.url.path.startswith('/assets'):
+ return False
+ # Put Other non rate limited checks here
+ return True
diff --git a/openhands/app_server/secrets/secrets_store.py b/openhands/app_server/secrets/secrets_store.py
index 5ea73354da..5f57437f09 100644
--- a/openhands/app_server/secrets/secrets_store.py
+++ b/openhands/app_server/secrets/secrets_store.py
@@ -14,7 +14,7 @@ class SecretsStore(ABC):
2. Implementing all required methods
3. Setting server_config.secret_store_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
The implementation may or may not support multiple users depending on the environment.
"""
diff --git a/openhands/app_server/server_config/__init__.py b/openhands/app_server/server_config/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/openhands/app_server/server_config/server_config.py b/openhands/app_server/server_config/server_config.py
new file mode 100644
index 0000000000..71108daa10
--- /dev/null
+++ b/openhands/app_server/server_config/server_config.py
@@ -0,0 +1,54 @@
+# TODO: Merge this module with openhands.app_server.config
+import os
+
+from openhands.app_server.types import AppMode, ServerConfigInterface
+from openhands.app_server.utils.import_utils import get_impl
+from openhands.app_server.utils.logger import openhands_logger as logger
+
+
+class ServerConfig(ServerConfigInterface):
+ config_cls = os.environ.get('OPENHANDS_CONFIG_CLS', None)
+ app_mode = AppMode.OPENHANDS
+ posthog_client_key = 'phc_3ESMmY9SgqEAGBB6sMGK5ayYHkeUuknH2vP6FmWH9RA'
+ github_client_id = os.environ.get('GITHUB_APP_CLIENT_ID', '')
+ enable_billing = os.environ.get('ENABLE_BILLING', 'false') == 'true'
+ hide_llm_settings = os.environ.get('HIDE_LLM_SETTINGS', 'false') == 'true'
+ # This config is used to hide the microagent management page from the users for now. We will remove this once we release the new microagent management page.
+ settings_store_class: str = (
+ 'openhands.app_server.settings.file_settings_store.FileSettingsStore'
+ )
+ secret_store_class: str = (
+ 'openhands.app_server.secrets.file_secrets_store.FileSecretsStore'
+ )
+ user_auth_class: str = (
+ 'openhands.app_server.user_auth.default_user_auth.DefaultUserAuth'
+ )
+ enable_v1: bool = os.getenv('ENABLE_V1') != '0'
+
+ def verify_config(self):
+ if self.config_cls:
+ raise ValueError('Unexpected config path provided')
+
+ def get_config(self):
+ config = {
+ 'APP_MODE': self.app_mode,
+ 'GITHUB_CLIENT_ID': self.github_client_id,
+ 'POSTHOG_CLIENT_KEY': self.posthog_client_key,
+ 'FEATURE_FLAGS': {
+ 'ENABLE_BILLING': self.enable_billing,
+ 'HIDE_LLM_SETTINGS': self.hide_llm_settings,
+ },
+ }
+
+ return config
+
+
+def load_server_config() -> ServerConfig:
+ config_cls = os.environ.get('OPENHANDS_CONFIG_CLS', None)
+ logger.info(f'Using config class {config_cls}')
+
+ server_config_cls = get_impl(ServerConfig, config_cls)
+ server_config: ServerConfig = server_config_cls()
+ server_config.verify_config()
+
+ return server_config
diff --git a/openhands/app_server/settings/settings_store.py b/openhands/app_server/settings/settings_store.py
index 56d34def93..e910d03978 100644
--- a/openhands/app_server/settings/settings_store.py
+++ b/openhands/app_server/settings/settings_store.py
@@ -14,7 +14,7 @@ class SettingsStore(ABC):
2. Implementing all required methods
3. Setting server_config.settings_store_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
The implementation may or may not support multiple users depending on the environment.
"""
diff --git a/openhands/app_server/shared.py b/openhands/app_server/shared.py
new file mode 100644
index 0000000000..4c6c9f9344
--- /dev/null
+++ b/openhands/app_server/shared.py
@@ -0,0 +1,25 @@
+from dotenv import load_dotenv
+
+from openhands.app_server.secrets.secrets_store import SecretsStore
+from openhands.app_server.server_config.server_config import (
+ ServerConfig,
+ load_server_config,
+)
+from openhands.app_server.settings.settings_store import SettingsStore
+from openhands.app_server.types import ServerConfigInterface
+from openhands.app_server.utils.import_utils import get_impl
+
+load_dotenv()
+
+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'
+)
+server_config: ServerConfig = server_config_interface
+
+# Note: socketio is no longer used. Redis access should use the standard redis package directly.
+# For enterprise code, use: from enterprise.storage.redis import get_redis_client, get_redis_client_async
+
+SettingsStoreImpl = get_impl(SettingsStore, server_config.settings_store_class)
+
+SecretsStoreImpl = get_impl(SecretsStore, server_config.secret_store_class)
diff --git a/openhands/app_server/static.py b/openhands/app_server/static.py
new file mode 100644
index 0000000000..15557f9d76
--- /dev/null
+++ b/openhands/app_server/static.py
@@ -0,0 +1,12 @@
+from fastapi.staticfiles import StaticFiles
+from starlette.responses import Response
+from starlette.types import Scope
+
+
+class SPAStaticFiles(StaticFiles):
+ async def get_response(self, path: str, scope: Scope) -> Response:
+ try:
+ return await super().get_response(path, scope)
+ except Exception:
+ # FIXME: just making this HTTPException doesn't work for some reason
+ return await super().get_response('index.html', scope)
diff --git a/openhands/app_server/types.py b/openhands/app_server/types.py
new file mode 100644
index 0000000000..787879db93
--- /dev/null
+++ b/openhands/app_server/types.py
@@ -0,0 +1,43 @@
+from abc import ABC, abstractmethod
+from typing import Any
+
+from openhands.app_server.config_api.config_models import AppMode
+
+
+class ServerConfigInterface(ABC):
+ @abstractmethod
+ def verify_config(self) -> None:
+ """Verify configuration settings."""
+ raise NotImplementedError
+
+ @abstractmethod
+ def get_config(self) -> dict[str, Any]:
+ """Configure attributes for frontend"""
+ raise NotImplementedError
+
+
+class MissingSettingsError(ValueError):
+ """Raised when settings are missing or not found."""
+
+ pass
+
+
+class LLMAuthenticationError(ValueError):
+ """Raised when there is an issue with LLM authentication."""
+
+ pass
+
+
+class SessionExpiredError(ValueError):
+ """Raised when the user's authentication session has expired."""
+
+ pass
+
+
+__all__ = [
+ 'AppMode',
+ 'ServerConfigInterface',
+ 'MissingSettingsError',
+ 'LLMAuthenticationError',
+ 'SessionExpiredError',
+]
diff --git a/openhands/app_server/user_auth/default_user_auth.py b/openhands/app_server/user_auth/default_user_auth.py
index 0709314d45..891697e0ea 100644
--- a/openhands/app_server/user_auth/default_user_auth.py
+++ b/openhands/app_server/user_auth/default_user_auth.py
@@ -11,13 +11,13 @@ from dataclasses import dataclass
from fastapi import Request
from pydantic import SecretStr
+from openhands.app_server import shared
from openhands.app_server.integrations.provider import PROVIDER_TOKEN_TYPE
from openhands.app_server.secrets.secrets_models import Secrets
from openhands.app_server.secrets.secrets_store import SecretsStore
from openhands.app_server.settings.settings_models import Settings
from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.server import shared
@dataclass
diff --git a/openhands/app_server/user_auth/user_auth.py b/openhands/app_server/user_auth/user_auth.py
index 45ab56d324..554f4e8aa8 100644
--- a/openhands/app_server/user_auth/user_auth.py
+++ b/openhands/app_server/user_auth/user_auth.py
@@ -23,8 +23,8 @@ from openhands.app_server.secrets.secrets_models import Secrets
from openhands.app_server.secrets.secrets_store import SecretsStore
from openhands.app_server.settings.settings_models import Settings
from openhands.app_server.settings.settings_store import SettingsStore
+from openhands.app_server.shared import server_config
from openhands.app_server.utils.import_utils import get_impl
-from openhands.server.shared import server_config
class AuthType(Enum):
@@ -41,7 +41,7 @@ class UserAuth(ABC):
2. Implementing all required methods
3. Setting server_config.user_auth_class to the fully qualified name of the class
- The class is instantiated via get_impl() in openhands.server.shared.py.
+ The class is instantiated via get_impl() in openhands.app_server.shared.py.
"""
_settings: Settings | None
diff --git a/openhands/app_server/utils/dependencies.py b/openhands/app_server/utils/dependencies.py
index 0d1499283d..6afb0445e4 100644
--- a/openhands/app_server/utils/dependencies.py
+++ b/openhands/app_server/utils/dependencies.py
@@ -4,7 +4,7 @@ from fastapi import Depends, HTTPException, status
from fastapi.security import APIKeyHeader
from openhands.app_server.config import get_global_config
-from openhands.app_server.config_api.config_models import AppMode
+from openhands.app_server.types import AppMode
_SESSION_API_KEY = os.getenv('SESSION_API_KEY')
_SESSION_API_KEY_HEADER = APIKeyHeader(name='X-Session-API-Key', auto_error=False)
diff --git a/openhands/app_server/version.py b/openhands/app_server/version.py
new file mode 100644
index 0000000000..6f88bb7e3c
--- /dev/null
+++ b/openhands/app_server/version.py
@@ -0,0 +1,44 @@
+import os
+from pathlib import Path
+
+__package_name__ = 'openhands_ai'
+
+
+def get_version():
+ # Try getting the version from pyproject.toml
+ try:
+ root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+ candidate_paths = [
+ Path(root_dir) / 'pyproject.toml',
+ Path(root_dir) / 'openhands' / 'pyproject.toml',
+ ]
+ for file_path in candidate_paths:
+ if file_path.is_file():
+ with open(file_path, 'r') as f:
+ for line in f:
+ if line.strip().startswith('version ='):
+ return line.split('=', 1)[1].strip().strip('"').strip("'")
+ except FileNotFoundError:
+ pass
+
+ try:
+ from importlib.metadata import PackageNotFoundError, version
+
+ return version(__package_name__)
+ except (ImportError, PackageNotFoundError):
+ pass
+
+ try:
+ from pkg_resources import DistributionNotFound, get_distribution # type: ignore
+
+ return get_distribution(__package_name__).version
+ except (ImportError, DistributionNotFound):
+ pass
+
+ return 'unknown'
+
+
+try:
+ __version__ = get_version()
+except Exception:
+ __version__ = 'unknown'
diff --git a/openhands/server/README.md b/openhands/server/README.md
deleted file mode 100644
index 78038349dc..0000000000
--- a/openhands/server/README.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# OpenHands Legacy (V0) Server
-
-> **IMPORTANT**: This is the legacy V0 web server, deprecated since version 1.0.0.
-> The V1 application server lives under `openhands/app_server/`.
-
-This package provides the V0 ASGI entry point (`listen.py`) that is still used by
-the Makefile and the container `CMD`. It assembles the FastAPI app from
-`openhands.server.app`, layers on middleware, Socket.IO, and (optionally) serves
-the frontend static build.
-
-## Key modules
-
-| Module | Purpose |
-|--------|---------|
-| `app.py` | Creates the FastAPI application, mounts MCP and V1 routers |
-| `listen.py` | Adds middleware (CORS, caching, rate-limiting), mounts SPA static files, wraps in Socket.IO ASGI |
-| `listen_socket.py` | Re-exports the `sio` Socket.IO server for backward compatibility |
-| `shared.py` | Module-level singletons (config, server config, Socket.IO, store implementations) |
-| `middleware.py` | CORS, cache-control, and rate-limiting middleware |
-| `static.py` | `SPAStaticFiles` β€” serves the frontend with SPA fallback |
-| `types.py` | Shared types (`AppMode`, `ServerConfigInterface`, error classes) |
-| `config/server_config.py` | OSS `ServerConfig` implementation and loader |
-
-## Starting the server
-
-```sh
-uvicorn openhands.server.listen:app --host 0.0.0.0 --port 3000
-```
diff --git a/openhands/server/__main__.py b/openhands/server/__main__.py
index 31dedd2fd5..c73dfc2440 100644
--- a/openhands/server/__main__.py
+++ b/openhands/server/__main__.py
@@ -1,11 +1,8 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
+# DEPRECATED: This module is deprecated. Use uvicorn directly:
+# uvicorn openhands.app_server.app:app --host 0.0.0.0 --port 3000
+#
+# This module is kept for backward compatibility.
+
import os
import uvicorn
diff --git a/openhands/server/app.py b/openhands/server/app.py
index af791b66c5..25f1dfacb1 100644
--- a/openhands/server/app.py
+++ b/openhands/server/app.py
@@ -1,69 +1,15 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import contextlib
-import warnings
-
-from fastapi.routing import Mount
-
-with warnings.catch_warnings():
- warnings.simplefilter('ignore')
-
-from fastapi import (
- FastAPI,
- Request,
-)
-from fastapi.responses import JSONResponse
-
-from openhands.app_server import v1_router
-from openhands.app_server.config import get_app_lifespan_service
-from openhands.app_server.integrations.service_types import AuthenticationError
-from openhands.app_server.mcp.mcp_router import mcp_server
-from openhands.app_server.status.status_router import router as health_router
-from openhands.version import get_version
-
-mcp_app = mcp_server.http_app(path='/mcp', stateless_http=True)
-
-
-def combine_lifespans(*lifespans):
- # Create a combined lifespan to manage multiple session managers
- @contextlib.asynccontextmanager
- async def combined_lifespan(app):
- async with contextlib.AsyncExitStack() as stack:
- for lifespan in lifespans:
- await stack.enter_async_context(lifespan(app))
- yield
-
- return combined_lifespan
-
-
-lifespans = [mcp_app.lifespan]
-app_lifespan_ = get_app_lifespan_service()
-if app_lifespan_:
- lifespans.append(app_lifespan_.lifespan)
-
-
-app = FastAPI(
- title='OpenHands',
- description='OpenHands: Code Less, Make More',
- version=get_version(),
- lifespan=combine_lifespans(*lifespans),
- routes=[Mount(path='/mcp', app=mcp_app)],
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.app instead.
+#
+# For backward compatibility, this module re-exports the app from openhands.app_server.app.
+# Note: This module does NOT include middleware setup. Use openhands.server.listen or
+# openhands.app_server.app directly for the fully configured application.
+
+from openhands.app_server.app import (
+ app,
+ authentication_error_handler,
+ combine_lifespans,
+ mcp_app,
)
-
[email protected]_handler(AuthenticationError)
-async def authentication_error_handler(request: Request, exc: AuthenticationError):
- return JSONResponse(
- status_code=401,
- content=str(exc),
- )
-
-
-app.include_router(v1_router.router)
-app.include_router(health_router)
+__all__ = ['app', 'mcp_app', 'combine_lifespans', 'authentication_error_handler']
diff --git a/openhands/server/config/server_config.py b/openhands/server/config/server_config.py
index babb44ed1e..f58eb561b9 100644
--- a/openhands/server/config/server_config.py
+++ b/openhands/server/config/server_config.py
@@ -1,62 +1,11 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import os
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.server_config.server_config instead.
+#
+# For backward compatibility, this module re-exports from openhands.app_server.server_config.server_config.
-from openhands.app_server.config_api.config_models import AppMode
-from openhands.app_server.utils.import_utils import get_impl
-from openhands.app_server.utils.logger import openhands_logger as logger
-from openhands.server.types import ServerConfigInterface
+from openhands.app_server.server_config.server_config import (
+ ServerConfig,
+ load_server_config,
+)
-
-class ServerConfig(ServerConfigInterface):
- config_cls = os.environ.get('OPENHANDS_CONFIG_CLS', None)
- app_mode = AppMode.OPENHANDS
- posthog_client_key = 'phc_3ESMmY9SgqEAGBB6sMGK5ayYHkeUuknH2vP6FmWH9RA'
- github_client_id = os.environ.get('GITHUB_APP_CLIENT_ID', '')
- enable_billing = os.environ.get('ENABLE_BILLING', 'false') == 'true'
- hide_llm_settings = os.environ.get('HIDE_LLM_SETTINGS', 'false') == 'true'
- # This config is used to hide the microagent management page from the users for now. We will remove this once we release the new microagent management page.
- settings_store_class: str = (
- 'openhands.app_server.settings.file_settings_store.FileSettingsStore'
- )
- secret_store_class: str = (
- 'openhands.app_server.secrets.file_secrets_store.FileSecretsStore'
- )
- user_auth_class: str = (
- 'openhands.app_server.user_auth.default_user_auth.DefaultUserAuth'
- )
- enable_v1: bool = os.getenv('ENABLE_V1') != '0'
-
- def verify_config(self):
- if self.config_cls:
- raise ValueError('Unexpected config path provided')
-
- def get_config(self):
- config = {
- 'APP_MODE': self.app_mode,
- 'GITHUB_CLIENT_ID': self.github_client_id,
- 'POSTHOG_CLIENT_KEY': self.posthog_client_key,
- 'FEATURE_FLAGS': {
- 'ENABLE_BILLING': self.enable_billing,
- 'HIDE_LLM_SETTINGS': self.hide_llm_settings,
- },
- }
-
- return config
-
-
-def load_server_config() -> ServerConfig:
- config_cls = os.environ.get('OPENHANDS_CONFIG_CLS', None)
- logger.info(f'Using config class {config_cls}')
-
- server_config_cls = get_impl(ServerConfig, config_cls)
- server_config: ServerConfig = server_config_cls()
- server_config.verify_config()
-
- return server_config
+__all__ = ['ServerConfig', 'load_server_config']
diff --git a/openhands/server/listen.py b/openhands/server/listen.py
index f7360c5088..70bb14392c 100644
--- a/openhands/server/listen.py
+++ b/openhands/server/listen.py
@@ -1,34 +1,8 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.app instead.
+#
+# For backward compatibility, this module re-exports the app from openhands.app_server.app.
-import os
+from openhands.app_server.app import app
-from openhands.server.app import app as base_app
-from openhands.server.middleware import (
- CacheControlMiddleware,
- InMemoryRateLimiter,
- LocalhostCORSMiddleware,
- RateLimitMiddleware,
-)
-from openhands.server.static import SPAStaticFiles
-
-if os.getenv('SERVE_FRONTEND', 'true').lower() == 'true':
- base_app.mount(
- '/', SPAStaticFiles(directory='./frontend/build', html=True), name='dist'
- )
-
-base_app.add_middleware(LocalhostCORSMiddleware)
-base_app.add_middleware(CacheControlMiddleware)
-base_app.add_middleware(
- RateLimitMiddleware,
- rate_limiter=InMemoryRateLimiter(requests=10, seconds=1),
-)
-
-# Note: socketio is no longer used for communication. The base FastAPI app is used directly.
-app = base_app
+__all__ = ['app']
diff --git a/openhands/server/middleware.py b/openhands/server/middleware.py
index b1e9c5649e..b87f9f87cc 100644
--- a/openhands/server/middleware.py
+++ b/openhands/server/middleware.py
@@ -1,144 +1,18 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-import asyncio
-import logging
-from collections import defaultdict
-from datetime import datetime, timedelta
-from urllib.parse import urlparse
-
-from fastapi import Request
-from fastapi.middleware.cors import CORSMiddleware
-from fastapi.responses import JSONResponse
-from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
-from starlette.requests import Request as StarletteRequest
-from starlette.responses import Response
-from starlette.types import ASGIApp
-
-from openhands.app_server.config import get_global_config
-
-
-class LocalhostCORSMiddleware(CORSMiddleware):
- """Custom CORS middleware that allows any request from localhost/127.0.0.1 domains,
- while using standard CORS rules for other origins.
- """
-
- def __init__(self, app: ASGIApp) -> None:
- config = get_global_config()
- allow_origins = tuple(config.permitted_cors_origins)
- super().__init__(
- app,
- allow_origins=allow_origins,
- allow_credentials=True,
- allow_methods=['*'],
- allow_headers=['*'],
- )
-
- def is_allowed_origin(self, origin: str) -> bool:
- if origin and not self.allow_origins and not self.allow_origin_regex:
- parsed = urlparse(origin)
- hostname = parsed.hostname or ''
-
- # Allow any localhost/127.0.0.1 origin regardless of port
- if hostname in ['localhost', '127.0.0.1']:
- return True
-
- # Allow any origin when no specific origins are configured (development mode)
- # WARNING: This disables CORS protection. Use explicit CORS origins in production.
- logging.getLogger(__name__).warning(
- f'No CORS origins configured, allowing origin: {origin}. '
- 'Set OH_PERMITTED_CORS_ORIGINS for production environments.'
- )
- return True
-
- # For missing origin or other origins, use the parent class's logic
- result: bool = super().is_allowed_origin(origin)
- return result
-
-
-class CacheControlMiddleware(BaseHTTPMiddleware):
- """Middleware to disable caching for all routes by adding appropriate headers"""
-
- async def dispatch(
- self, request: Request, call_next: RequestResponseEndpoint
- ) -> Response:
- response = await call_next(request)
- if request.url.path.startswith('/assets'):
- # The content of the assets directory has fingerprinted file names so we cache aggressively
- response.headers['Cache-Control'] = 'public, max-age=2592000, immutable'
- else:
- response.headers['Cache-Control'] = (
- 'no-cache, no-store, must-revalidate, max-age=0'
- )
- response.headers['Pragma'] = 'no-cache'
- response.headers['Expires'] = '0'
- return response
-
-
-class InMemoryRateLimiter:
- history: dict[str, list[datetime]]
- requests: int
- seconds: int
- sleep_seconds: int
-
- def __init__(self, requests: int = 2, seconds: int = 1, sleep_seconds: int = 1):
- self.requests = requests
- self.seconds = seconds
- self.sleep_seconds = sleep_seconds
- self.history = defaultdict(list)
- self.sleep_seconds = sleep_seconds
-
- def _clean_old_requests(self, key: str) -> None:
- now = datetime.now()
- cutoff = now - timedelta(seconds=self.seconds)
- self.history[key] = [ts for ts in self.history[key] if ts > cutoff]
-
- async def __call__(self, request: Request) -> bool:
- key = request.client.host
- now = datetime.now()
-
- self._clean_old_requests(key)
-
- self.history[key].append(now)
-
- if len(self.history[key]) > self.requests * 2:
- return False
- elif len(self.history[key]) > self.requests:
- if self.sleep_seconds > 0:
- await asyncio.sleep(self.sleep_seconds)
- return True
- else:
- return False
-
- return True
-
-
-class RateLimitMiddleware(BaseHTTPMiddleware):
- def __init__(self, app: ASGIApp, rate_limiter: InMemoryRateLimiter):
- super().__init__(app)
- self.rate_limiter = rate_limiter
-
- async def dispatch(
- self, request: Request, call_next: RequestResponseEndpoint
- ) -> Response:
- if not self.is_rate_limited_request(request):
- return await call_next(request)
- ok = await self.rate_limiter(request)
- if not ok:
- return JSONResponse(
- status_code=429,
- content={'message': 'Too many requests'},
- headers={'Retry-After': '1'},
- )
- return await call_next(request)
-
- def is_rate_limited_request(self, request: StarletteRequest) -> bool:
- if request.url.path.startswith('/assets'):
- return False
- # Put Other non rate limited checks here
- return True
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.middleware instead.
+#
+# For backward compatibility, this module re-exports from openhands.app_server.middleware.
+
+from openhands.app_server.middleware import (
+ CacheControlMiddleware,
+ InMemoryRateLimiter,
+ LocalhostCORSMiddleware,
+ RateLimitMiddleware,
+)
+
+__all__ = [
+ 'LocalhostCORSMiddleware',
+ 'CacheControlMiddleware',
+ 'InMemoryRateLimiter',
+ 'RateLimitMiddleware',
+]
diff --git a/openhands/server/shared.py b/openhands/server/shared.py
index cf2e10ed65..fa224f1962 100644
--- a/openhands/server/shared.py
+++ b/openhands/server/shared.py
@@ -1,31 +1,18 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.shared instead.
+#
+# For backward compatibility, this module re-exports from openhands.app_server.shared.
-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.server.config.server_config import ServerConfig, load_server_config
-from openhands.server.types import ServerConfigInterface
-
-load_dotenv()
-
-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'
+from openhands.app_server.shared import (
+ SecretsStoreImpl,
+ SettingsStoreImpl,
+ server_config,
+ server_config_interface,
)
-server_config: ServerConfig = server_config_interface
-
-# Note: socketio is no longer used. Redis access should use the standard redis package directly.
-# For enterprise code, use: from enterprise.storage.redis import get_redis_client, get_redis_client_async
-
-SettingsStoreImpl = get_impl(SettingsStore, server_config.settings_store_class)
-SecretsStoreImpl = get_impl(SecretsStore, server_config.secret_store_class)
+__all__ = [
+ 'server_config_interface',
+ 'server_config',
+ 'SettingsStoreImpl',
+ 'SecretsStoreImpl',
+]
diff --git a/openhands/server/static.py b/openhands/server/static.py
index d8f70f1bd3..1b0710d786 100644
--- a/openhands/server/static.py
+++ b/openhands/server/static.py
@@ -1,20 +1,8 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from fastapi.staticfiles import StaticFiles
-from starlette.responses import Response
-from starlette.types import Scope
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.static instead.
+#
+# For backward compatibility, this module re-exports from openhands.app_server.static.
+from openhands.app_server.static import SPAStaticFiles
-class SPAStaticFiles(StaticFiles):
- async def get_response(self, path: str, scope: Scope) -> Response:
- try:
- return await super().get_response(path, scope)
- except Exception:
- # FIXME: just making this HTTPException doesn't work for some reason
- return await super().get_response('index.html', scope)
+__all__ = ['SPAStaticFiles']
diff --git a/openhands/server/types.py b/openhands/server/types.py
index 4e4b9c7501..ab812522ea 100644
--- a/openhands/server/types.py
+++ b/openhands/server/types.py
@@ -1,40 +1,20 @@
-# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
-# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
-# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application server. Please refer to:
-# - V1 agentic core (SDK): https://github.com/OpenHands/software-agent-sdk
-# - V1 application server (in this repo): openhands/app_server/
-# Unless you are working on deprecation, please avoid extending this legacy file and consult the V1 codepaths above.
-# Tag: Legacy-V0
-# This module belongs to the old V0 web server. The V1 application server lives under openhands/app_server/.
-from abc import ABC, abstractmethod
-from typing import Any
-
-
-class ServerConfigInterface(ABC):
- @abstractmethod
- def verify_config(self) -> None:
- """Verify configuration settings."""
- raise NotImplementedError
-
- @abstractmethod
- def get_config(self) -> dict[str, Any]:
- """Configure attributes for frontend"""
- raise NotImplementedError
-
-
-class MissingSettingsError(ValueError):
- """Raised when settings are missing or not found."""
-
- pass
-
-
-class LLMAuthenticationError(ValueError):
- """Raised when there is an issue with LLM authentication."""
-
- pass
-
-
-class SessionExpiredError(ValueError):
- """Raised when the user's authentication session has expired."""
-
- pass
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.types instead.
+#
+# For backward compatibility, this module re-exports all types from openhands.app_server.types.
+
+from openhands.app_server.types import (
+ AppMode,
+ LLMAuthenticationError,
+ MissingSettingsError,
+ ServerConfigInterface,
+ SessionExpiredError,
+)
+
+__all__ = [
+ 'AppMode',
+ 'ServerConfigInterface',
+ 'MissingSettingsError',
+ 'LLMAuthenticationError',
+ 'SessionExpiredError',
+]
diff --git a/openhands/version.py b/openhands/version.py
index 6f88bb7e3c..efe3f1a1a6 100644
--- a/openhands/version.py
+++ b/openhands/version.py
@@ -1,44 +1,8 @@
-import os
-from pathlib import Path
+# DEPRECATED: This module is deprecated and will be removed in a future release.
+# Please use openhands.app_server.version instead.
+#
+# For backward compatibility, this module re-exports from openhands.app_server.version.
-__package_name__ = 'openhands_ai'
+from openhands.app_server.version import __package_name__, __version__, get_version
-
-def get_version():
- # Try getting the version from pyproject.toml
- try:
- root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- candidate_paths = [
- Path(root_dir) / 'pyproject.toml',
- Path(root_dir) / 'openhands' / 'pyproject.toml',
- ]
- for file_path in candidate_paths:
- if file_path.is_file():
- with open(file_path, 'r') as f:
- for line in f:
- if line.strip().startswith('version ='):
- return line.split('=', 1)[1].strip().strip('"').strip("'")
- except FileNotFoundError:
- pass
-
- try:
- from importlib.metadata import PackageNotFoundError, version
-
- return version(__package_name__)
- except (ImportError, PackageNotFoundError):
- pass
-
- try:
- from pkg_resources import DistributionNotFound, get_distribution # type: ignore
-
- return get_distribution(__package_name__).version
- except (ImportError, DistributionNotFound):
- pass
-
- return 'unknown'
-
-
-try:
- __version__ = get_version()
-except Exception:
- __version__ = 'unknown'
+__all__ = ['__package_name__', '__version__', 'get_version']
diff --git a/scripts/update_openapi.py b/scripts/update_openapi.py
index 5f58b35ece..641e84fc01 100755
--- a/scripts/update_openapi.py
+++ b/scripts/update_openapi.py
@@ -9,7 +9,7 @@ Usage:
python scripts/update_openapi.py
Behavior:
-- Uses openhands.server.app.app.openapi() to build the spec.
+- Uses openhands.app_server.app.app.openapi() to build the spec.
- Preserves existing "servers" from docs/openapi.json if present; otherwise
writes sensible defaults.
- Sets info.version to openhands.__version__.
@@ -42,7 +42,7 @@ sys.path.insert(0, str(project_root))
try:
from openhands import __version__
- from openhands.server.app import app
+ from openhands.app_server.app import app
except ImportError as e:
print(f'Error importing OpenHands modules: {e}')
print(
diff --git a/tests/unit/app_server/test_profiles_api.py b/tests/unit/app_server/test_profiles_api.py
index df534486f4..6d18e20cf8 100644
--- a/tests/unit/app_server/test_profiles_api.py
+++ b/tests/unit/app_server/test_profiles_api.py
@@ -15,6 +15,7 @@ from fastapi import Request
from fastapi.testclient import TestClient
from pydantic import SecretStr
+from openhands.app_server.app import app
from openhands.app_server.file_store import get_file_store
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import UserGitInfo
@@ -28,7 +29,6 @@ from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.user_auth.user_auth import UserAuth
from openhands.sdk.llm import LLM
from openhands.sdk.settings import AgentSettings
-from openhands.server.app import app
@pytest.fixture(autouse=True)
@@ -661,8 +661,8 @@ def test_save_profile_rejects_invalid_name(test_client, bad_name):
f'/api/v1/settings/profiles/{bad_name}',
json={'llm': {'model': 'openai/gpt-4o'}},
)
- # Invalid chars/length β†’ 422 from Path validation; slash β†’ 404 routing miss.
- assert response.status_code in (404, 422)
+ # Invalid chars/length β†’ 422 from Path validation; slash β†’ 404/405 routing miss.
+ assert response.status_code in (404, 405, 422)
# ── Profile count cap ────────────────────────────────────────────
diff --git a/tests/unit/app_server/test_sandbox_secrets_router.py b/tests/unit/app_server/test_sandbox_secrets_router.py
index 6b89f2d729..d2f3c642f1 100644
--- a/tests/unit/app_server/test_sandbox_secrets_router.py
+++ b/tests/unit/app_server/test_sandbox_secrets_router.py
@@ -135,7 +135,7 @@ class TestValidateSessionKey:
mock_get.return_value.__aenter__ = AsyncMock(return_value=mock_svc)
mock_get.return_value.__aexit__ = AsyncMock(return_value=False)
- from openhands.app_server.config_api.config_models import AppMode
+ from openhands.app_server.types import AppMode
mock_cfg.return_value.app_mode = AppMode.SAAS
diff --git a/tests/unit/app_server/test_settings_api.py b/tests/unit/app_server/test_settings_api.py
index 9e22d8efd7..4c43804c1f 100644
--- a/tests/unit/app_server/test_settings_api.py
+++ b/tests/unit/app_server/test_settings_api.py
@@ -6,6 +6,7 @@ from fastapi import Request
from fastapi.testclient import TestClient
from pydantic import SecretStr
+from openhands.app_server.app import app
from openhands.app_server.file_store.memory import InMemoryFileStore
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import UserGitInfo
@@ -21,7 +22,6 @@ from openhands.sdk.settings import (
ConversationSettings,
VerificationSettings,
)
-from openhands.server.app import app
_EXPOSE = {'expose_secrets': True}
diff --git a/tests/unit/integrations/bitbucket/test_bitbucket.py b/tests/unit/integrations/bitbucket/test_bitbucket.py
index 112351fe07..b78447bd66 100644
--- a/tests/unit/integrations/bitbucket/test_bitbucket.py
+++ b/tests/unit/integrations/bitbucket/test_bitbucket.py
@@ -5,7 +5,6 @@ from unittest.mock import AsyncMock, patch
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket.bitbucket_service import (
BitBucketService,
)
@@ -17,6 +16,7 @@ from openhands.app_server.integrations.service_types import (
from openhands.app_server.integrations.utils import validate_provider_token
from openhands.app_server.secrets.secrets_router import check_provider_tokens
from openhands.app_server.settings.settings_models import POSTProviderModel
+from openhands.app_server.types import AppMode
# Provider Token Validation Tests
diff --git a/tests/unit/integrations/bitbucket/test_bitbucket_repos.py b/tests/unit/integrations/bitbucket/test_bitbucket_repos.py
index 72fb656f19..21c3076f70 100644
--- a/tests/unit/integrations/bitbucket/test_bitbucket_repos.py
+++ b/tests/unit/integrations/bitbucket/test_bitbucket_repos.py
@@ -5,7 +5,6 @@ from unittest.mock import patch
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket.bitbucket_service import (
BitBucketService,
)
@@ -13,6 +12,7 @@ from openhands.app_server.integrations.service_types import OwnerType, Repositor
from openhands.app_server.integrations.service_types import (
ProviderType as ServiceProviderType,
)
+from openhands.app_server.types import AppMode
@pytest.fixture
diff --git a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc.py b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc.py
index 9ddfa204e2..5db28d92c4 100644
--- a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc.py
+++ b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc.py
@@ -6,11 +6,11 @@ from unittest.mock import patch
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket_data_center.bitbucket_dc_service import (
BitbucketDCService,
)
from openhands.app_server.integrations.service_types import AuthenticationError, User
+from openhands.app_server.types import AppMode
# ── init / BASE_URL ───────────────────────────────────────────────────────────
diff --git a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_repos.py b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_repos.py
index a552deb892..a42be98050 100644
--- a/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_repos.py
+++ b/tests/unit/integrations/bitbucket_data_center/test_bitbucket_dc_repos.py
@@ -5,10 +5,10 @@ from unittest.mock import AsyncMock, patch
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.bitbucket_data_center.bitbucket_dc_service import (
BitbucketDCService,
)
+from openhands.app_server.types import AppMode
def make_service():
diff --git a/tests/unit/integrations/github/test_github_service.py b/tests/unit/integrations/github/test_github_service.py
index c2d86bea14..9b5091fd14 100644
--- a/tests/unit/integrations/github/test_github_service.py
+++ b/tests/unit/integrations/github/test_github_service.py
@@ -4,7 +4,6 @@ import httpx
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.github.github_service import GitHubService
from openhands.app_server.integrations.service_types import (
AuthenticationError,
@@ -13,6 +12,7 @@ from openhands.app_server.integrations.service_types import (
Repository,
User,
)
+from openhands.app_server.types import AppMode
@pytest.mark.asyncio
diff --git a/tests/unit/integrations/gitlab/test_gitlab.py b/tests/unit/integrations/gitlab/test_gitlab.py
index e1cc5ca779..808cb94025 100644
--- a/tests/unit/integrations/gitlab/test_gitlab.py
+++ b/tests/unit/integrations/gitlab/test_gitlab.py
@@ -6,7 +6,6 @@ from unittest.mock import patch
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations import provider as provider_module
from openhands.app_server.integrations.gitlab import (
constants as gitlab_constants_module,
@@ -18,6 +17,7 @@ from openhands.app_server.integrations.service_types import (
ProviderType,
Repository,
)
+from openhands.app_server.types import AppMode
@pytest.mark.asyncio
diff --git a/tests/unit/server/routes/test_mcp_routes.py b/tests/unit/server/routes/test_mcp_routes.py
index 6e84ff957d..3ae8ddb726 100644
--- a/tests/unit/server/routes/test_mcp_routes.py
+++ b/tests/unit/server/routes/test_mcp_routes.py
@@ -3,9 +3,9 @@ from unittest.mock import AsyncMock, patch
import pytest
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.service_types import GitService
from openhands.app_server.mcp.mcp_router import get_conversation_link
+from openhands.app_server.types import AppMode
def test_mcp_server_no_stateless_http_deprecation_warning():
diff --git a/tests/unit/server/routes/test_skills_api.py b/tests/unit/server/routes/test_skills_api.py
index a0fab994b1..ee09e6cf21 100644
--- a/tests/unit/server/routes/test_skills_api.py
+++ b/tests/unit/server/routes/test_skills_api.py
@@ -7,6 +7,7 @@ from fastapi import Request
from fastapi.testclient import TestClient
from pydantic import SecretStr
+from openhands.app_server.app import app
from openhands.app_server.file_store.memory import InMemoryFileStore
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import UserGitInfo
@@ -15,7 +16,6 @@ from openhands.app_server.secrets.secrets_store import SecretsStore
from openhands.app_server.settings.file_settings_store import FileSettingsStore
from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.server.app import app
class MockUserAuth(UserAuth):
diff --git a/tests/unit/server/test_middleware.py b/tests/unit/server/test_middleware.py
index cdc922b5e9..aab59d677b 100644
--- a/tests/unit/server/test_middleware.py
+++ b/tests/unit/server/test_middleware.py
@@ -5,7 +5,7 @@ from fastapi import FastAPI
from fastapi.testclient import TestClient
from starlette.middleware.cors import CORSMiddleware
-from openhands.server.middleware import LocalhostCORSMiddleware
+from openhands.app_server.middleware import LocalhostCORSMiddleware
@pytest.fixture
@@ -28,7 +28,7 @@ def test_localhost_cors_middleware_init_with_config():
'https://test.com',
]
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
app = FastAPI()
middleware = LocalhostCORSMiddleware(app)
@@ -44,7 +44,7 @@ def test_localhost_cors_middleware_init_without_config():
mock_config = MagicMock()
mock_config.permitted_cors_origins = []
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
app = FastAPI()
middleware = LocalhostCORSMiddleware(app)
@@ -58,7 +58,7 @@ def test_localhost_cors_middleware_is_allowed_origin_localhost(app):
mock_config = MagicMock()
mock_config.permitted_cors_origins = []
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
app.add_middleware(LocalhostCORSMiddleware)
client = TestClient(app)
@@ -90,7 +90,7 @@ def test_localhost_cors_middleware_is_allowed_origin_non_localhost(app):
mock_config = MagicMock()
mock_config.permitted_cors_origins = ['https://example.com']
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
app.add_middleware(LocalhostCORSMiddleware)
client = TestClient(app)
@@ -112,7 +112,7 @@ def test_localhost_cors_middleware_missing_origin(app):
mock_config = MagicMock()
mock_config.permitted_cors_origins = []
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
app.add_middleware(LocalhostCORSMiddleware)
client = TestClient(app)
@@ -134,7 +134,7 @@ def test_localhost_cors_middleware_cors_parameters():
mock_config = MagicMock()
mock_config.permitted_cors_origins = []
with patch(
- 'openhands.server.middleware.get_global_config', return_value=mock_config
+ 'openhands.app_server.middleware.get_global_config', return_value=mock_config
):
# We need to inspect the initialization parameters rather than attributes
# since CORSMiddleware doesn't expose these as attributes
diff --git a/tests/unit/server/test_openapi_schema_generation.py b/tests/unit/server/test_openapi_schema_generation.py
index dcef9b39cd..3fd9ab6bea 100644
--- a/tests/unit/server/test_openapi_schema_generation.py
+++ b/tests/unit/server/test_openapi_schema_generation.py
@@ -6,6 +6,7 @@ from fastapi import Request
from fastapi.testclient import TestClient
from pydantic import SecretStr
+from openhands.app_server.app import app
from openhands.app_server.file_store.memory import InMemoryFileStore
from openhands.app_server.integrations.provider import ProviderToken, ProviderType
from openhands.app_server.integrations.service_types import UserGitInfo
@@ -14,7 +15,6 @@ from openhands.app_server.secrets.secrets_store import SecretsStore
from openhands.app_server.settings.file_settings_store import FileSettingsStore
from openhands.app_server.settings.settings_store import SettingsStore
from openhands.app_server.user_auth.user_auth import UserAuth
-from openhands.server.app import app
class MockUserAuth(UserAuth):
diff --git a/tests/unit/test_forgejo_service.py b/tests/unit/test_forgejo_service.py
index 59a567ac19..76c7b4832a 100644
--- a/tests/unit/test_forgejo_service.py
+++ b/tests/unit/test_forgejo_service.py
@@ -4,7 +4,6 @@ import httpx
import pytest
from pydantic import SecretStr
-from openhands.app_server.config_api.config_models import AppMode
from openhands.app_server.integrations.forgejo.forgejo_service import ForgejoService
from openhands.app_server.integrations.service_types import (
ProviderType,
@@ -12,6 +11,7 @@ from openhands.app_server.integrations.service_types import (
RequestMethod,
User,
)
+from openhands.app_server.types import AppMode
@pytest.fixture