diff --git a/.agents/skills/verify-agent-server/references/feature-map/F01-server-status.md b/.agents/skills/verify-agent-server/references/feature-map/F01-server-status.md index 2a43b752bbd..e267ac64e64 100644 --- a/.agents/skills/verify-agent-server/references/feature-map/F01-server-status.md +++ b/.agents/skills/verify-agent-server/references/feature-map/F01-server-status.md @@ -202,7 +202,7 @@ Preconditions: control-agent-server logs --grep 'DEBUG mode: ENABLED' --expect-min $((N + 1)) control-agent-server api GET /api/workspaces --expect 500 --check detail eq 'Internal Server Error' \ --check exception contains 'Failed to read workspaces' \ - --check traceback contains 'HTTPException: 500: Failed to read workspaces' --save F01.debug-tracebacks/on + --check traceback contains 'OperationFailed: Failed to read workspaces' --save F01.debug-tracebacks/on control-agent-server api GET /api/conversations/count --auth none --expect 401 --check traceback missing control-agent-server restart --reset-config control-agent-server api GET /api/workspaces --expect 500 --check traceback missing @@ -211,8 +211,8 @@ Preconditions: ``` Without `DEBUG` the 500 body is `detail`, `exception` and nothing else; with `DEBUG=true` the server prints `DEBUG mode: ENABLED` and the same 500 adds a - `traceback` string whose last line is the `HTTPException`, while the 401 - stays `{"detail": ...}`. After `--reset-config` the trace is gone again and + `traceback` string whose last line is the `OperationFailed` domain error, + while the 401 stays `{"detail": ...}`. After `--reset-config` the trace is gone again and the registry reads normally once the directory is removed. - **Tool preload (`F01.preload-tools`).** Restart with `preload_tools` on, first with whatever Chromium the server finds on its own, then with the diff --git a/.agents/skills/verify-agent-server/references/feature-map/F17-workspaces-registry.md b/.agents/skills/verify-agent-server/references/feature-map/F17-workspaces-registry.md index 3b6af1313a0..9c8ad043ed2 100644 --- a/.agents/skills/verify-agent-server/references/feature-map/F17-workspaces-registry.md +++ b/.agents/skills/verify-agent-server/references/feature-map/F17-workspaces-registry.md @@ -626,7 +626,7 @@ Preconditions: temporary file is left next to it, and the restored file lists everything again. The log has one `Cannot access workspaces file: [Errno 21] Is a directory` ERROR line per call and no traceback: the 500 is a deliberate - `HTTPException`, which the server logs without a stack. + `OperationFailed` domain error, which the server logs without a stack. - **No-op writes on read-only storage (`F17.noop-write-readonly`).** Make the persistence directory immutable (`chattr +i`, standing in for a read-only mount: the server owns the directory and re-applies mode `0700` diff --git a/.agents/skills/verify-agent-server/references/feature-map/F32-webhooks-and-telemetry.md b/.agents/skills/verify-agent-server/references/feature-map/F32-webhooks-and-telemetry.md index ec367252f32..fd34c62f804 100644 --- a/.agents/skills/verify-agent-server/references/feature-map/F32-webhooks-and-telemetry.md +++ b/.agents/skills/verify-agent-server/references/feature-map/F32-webhooks-and-telemetry.md @@ -504,7 +504,7 @@ Preconditions: the header's identity, the route template, method, status and `NoCondensationAvailableException`; neither the conversation id nor the exception text (which the server log shows) reached the endpoint. If the condense route stops answering 500, find another - unhandled exception: an `HTTPException` 5xx is not reported. + unhandled exception: a deliberate 5xx domain error is not reported. - **Token and cost buckets from real usage (`F32.telemetry-usage-buckets`).** The run above used tokens; its outcome event should say so. @@ -812,7 +812,7 @@ Preconditions: deferred" is the reading this bullet assumes. Low severity (analytics quality). - `request_failed` is emitted only for unhandled exceptions; a route that - raises `HTTPException(500)` (for example the workspaces registry on an + raises `OperationFailed` (500) (for example the workspaces registry on an unreadable file) is not reported. `F32.telemetry-request-failed` borrows the condense route's unhandled `NoCondensationAvailableException` (the summarizer failing against an unreachable model). diff --git a/.agents/skills/verify-agent-server/references/mapping.md b/.agents/skills/verify-agent-server/references/mapping.md index 0ba1df09959..4fffd2420ce 100644 --- a/.agents/skills/verify-agent-server/references/mapping.md +++ b/.agents/skills/verify-agent-server/references/mapping.md @@ -50,9 +50,10 @@ each candidate. Sources, roughly in order of yield: `openhands-sdk/openhands/sdk/workspace/remote/`), the TypeScript client (`clients/typescript/src`), and `examples/02_remote_agent_server/`. A consumer method is an entry point: list it in the family. -6. **Errors and edge states**: `HTTPException` details, status codes in the - handlers, `deprecated=True` routes and their removal versions. These are the - states a happy path never shows. +6. **Errors and edge states**: the domain errors routes raise + (`openhands.sdk.errors`, statuses from `agent_server/errors.py`), + `deprecated=True` routes and their removal versions. These are the states a + happy path never shows. 7. **Existing tests** (`tests/agent_server/`, `tests/cross/`) are references for request shapes and expected behavior, not proof. diff --git a/openhands-agent-server/openhands/agent_server/_secrets_exposure.py b/openhands-agent-server/openhands/agent_server/_secrets_exposure.py index 3f080e782bd..8cb86433748 100644 --- a/openhands-agent-server/openhands/agent_server/_secrets_exposure.py +++ b/openhands-agent-server/openhands/agent_server/_secrets_exposure.py @@ -4,13 +4,13 @@ from contextlib import contextmanager from typing import Any, Literal, cast -from fastapi import HTTPException, Request, status +from fastapi import Request from pydantic import SecretStr from pydantic_core import PydanticSerializationError +from openhands.sdk.errors import Conflict, Invalid, Unavailable from openhands.sdk.llm import LLM from openhands.sdk.llm.llm import LLM_SECRET_FIELDS -from openhands.sdk.llm.provider_connection_store import ProviderConnectionNotFound from openhands.sdk.logger import get_logger from openhands.sdk.utils.cipher import FERNET_TOKEN_PREFIX, Cipher from openhands.sdk.utils.pydantic_secrets import ( @@ -29,10 +29,7 @@ def get_config(request: Request): """Get config from app state, raising 503 if uninitialized.""" config = getattr(request.app.state, "config", None) if config is None: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Server not fully initialized", - ) + raise Unavailable("Server not fully initialized") return config @@ -45,7 +42,7 @@ def parse_expose_secrets_header(request: Request) -> ExposeSecretsMode | None: """Parse the ``X-Expose-Secrets`` header. Returns ``"encrypted"``, ``"plaintext"``, or ``None`` (header absent). - Raises ``HTTPException(400)`` for any other value. + Raises ``Invalid`` (400) for any other value. """ header_value = request.headers.get("X-Expose-Secrets", "").lower().strip() @@ -60,12 +57,9 @@ def parse_expose_secrets_header(request: Request) -> ExposeSecretsMode | None: if header_value in ("encrypted", "plaintext"): return cast(ExposeSecretsMode, header_value) - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=( - f"Invalid X-Expose-Secrets header value: '{header_value}'. " - "Valid values are: 'encrypted', 'plaintext'." - ), + raise Invalid( + f"Invalid X-Expose-Secrets header value: '{header_value}'. " + "Valid values are: 'encrypted', 'plaintext'." ) @@ -115,56 +109,22 @@ def decrypt_incoming_llm_secrets(llm: LLM, cipher: Cipher) -> LLM: @contextmanager def translate_missing_cipher() -> Iterator[None]: - """Translate a missing-cipher serializer error into HTTP 503.""" + """Translate a missing-cipher serializer error into ``Unavailable`` (503).""" try: yield except (PydanticSerializationError, MissingCipherError) as e: if _has_missing_cipher_cause(e): - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail=( - "Encryption not available: OH_SECRET_KEY is not configured. " - "Cannot return encrypted secrets." - ), + raise Unavailable( + "Encryption not available: OH_SECRET_KEY is not configured. " + "Cannot return encrypted secrets." ) raise -def profile_key_mismatch(name: str, error: SecretDecryptionError) -> HTTPException: +def profile_key_mismatch(name: str, error: SecretDecryptionError) -> Conflict: """409 for a profile whose stored key the current cipher cannot decrypt.""" _logger.error(f"Refusing to use profile '{name}': {error}") - return HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - f"Profile '{name}' is encrypted with a different key: restore that " - "key as OH_SECRET_KEY or add it to OH_PREVIOUS_SECRET_KEYS" - ), + return Conflict( + f"Profile '{name}' is encrypted with a different key: restore that " + "key as OH_SECRET_KEY or add it to OH_PREVIOUS_SECRET_KEYS" ) - - -@contextmanager -def store_errors() -> Iterator[None]: - """Map profile-store errors (``LLMProfileStore``/``AgentProfileStore``) to - HTTP responses. Shared by the settings, profiles, and agent-profiles - routers.""" - try: - yield - except TimeoutError: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Profile store is busy. Please retry.", - ) - except ProviderConnectionNotFound as e: - # Subclass of ValueError, so it must be handled before the generic - # ValueError arm below. A dangling provider reference is a resolvable - # config problem (recreate the connection or edit the profile), hence - # 422 rather than a generic 400. - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail=str(e), - ) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) diff --git a/openhands-agent-server/openhands/agent_server/acp_router.py b/openhands-agent-server/openhands/agent_server/acp_router.py index 46110521cc3..83318866b3c 100644 --- a/openhands-agent-server/openhands/agent_server/acp_router.py +++ b/openhands-agent-server/openhands/agent_server/acp_router.py @@ -9,7 +9,7 @@ from collections.abc import Awaitable, Callable, Mapping from dataclasses import dataclass, field -from fastapi import APIRouter, HTTPException, Request, status +from fastapi import APIRouter, Request from pydantic import BaseModel, Field from openhands.agent_server._secrets_exposure import get_config @@ -20,6 +20,7 @@ from openhands.sdk.agent.acp_model_discovery import discover_acp_models from openhands.sdk.agent.acp_models import ACPModelDiscovery from openhands.sdk.credential import VersionedCredentialBinding +from openhands.sdk.errors import NotSupported, Unprocessable from openhands.sdk.logger import get_logger from openhands.sdk.secret import SecretSource from openhands.sdk.settings.model import ACPAgentSettings @@ -158,15 +159,14 @@ async def discover_models( """ config: Config = get_config(request) if config.conversation_runtime == "docker": - raise HTTPException( - status.HTTP_501_NOT_IMPLEMENTED, - "ACP model discovery runs only where conversations run in-process", + raise NotSupported( + "ACP model discovery runs only where conversations run in-process" ) settings = body.agent_settings try: command = settings.resolve_acp_command() except ValueError as exc: - raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc + raise Unprocessable(str(exc)) from exc secrets = await asyncio.to_thread(_resolve_secrets, body.secrets) bindings = await asyncio.to_thread(_codex_bindings, settings, config, secrets) diff --git a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py index 03ca50f4af9..2fa6e3f622d 100644 --- a/openhands-agent-server/openhands/agent_server/agent_profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/agent_profiles_router.py @@ -15,13 +15,12 @@ import asyncio from typing import Annotated, Any -from fastapi import APIRouter, HTTPException, Path, Request, status +from fastapi import APIRouter, Path, Request, status from pydantic import BaseModel, ConfigDict, Field, PlainValidator, ValidationError from openhands.agent_server._secrets_exposure import ( get_cipher, get_config, - store_errors, ) from openhands.agent_server.config import Config from openhands.agent_server.launch import ( @@ -36,6 +35,7 @@ get_settings_store, ) from openhands.agent_server.profiles_router import MAX_PROFILES, _has_api_key +from openhands.sdk.errors import Conflict, NotFound, OperationFailed, Unprocessable from openhands.sdk.launch import preview_launch from openhands.sdk.llm import LLM from openhands.sdk.llm.llm_profile_store import ( @@ -180,46 +180,45 @@ def _seed_default_llm_profile(llm: LLM, cipher: Cipher | None) -> str: silently clobber it. """ llm_store = get_llm_profile_store() - with store_errors(): - try: - llm_store.load(SEED_PROFILE_NAME, cipher=cipher) - return SEED_PROFILE_NAME - except FileNotFoundError: - pass - except ValueError: - # Something already occupies the name (e.g. corrupted/unparsable - # file) — never overwrite it; a broken ref surfaces at - # materialize/launch time instead. - logger.warning( - f"Default LLM profile '{SEED_PROFILE_NAME}' exists but " - "failed to load; leaving it as-is" - ) - return SEED_PROFILE_NAME - if not _llm_has_real_config(llm): - # Never-configured account: don't persist a keyless ghost profile. - # Leave the ref soft/dangling; the banner + launch-time error handle - # it, and it resolves for real once the user saves a profile. - logger.info( - f"Skipping default LLM profile '{SEED_PROFILE_NAME}' seed: " - "no real LLM config yet (leaving llm_profile_ref as a soft ref)" - ) - return SEED_PROFILE_NAME - try: - llm_store.save( - SEED_PROFILE_NAME, - llm, - include_secrets=True, - cipher=cipher, - max_profiles=MAX_PROFILES, - ) - logger.info(f"Seeded default LLM profile '{SEED_PROFILE_NAME}'") - except LLMProfileLimitExceeded: - # Can't mirror the live LLM as a profile; the agent profile's - # llm_profile_ref will still dangle, but no worse than before. - logger.warning( - "Could not seed default LLM profile " - f"'{SEED_PROFILE_NAME}': profile limit reached" - ) + try: + llm_store.load(SEED_PROFILE_NAME, cipher=cipher) + return SEED_PROFILE_NAME + except FileNotFoundError: + pass + except ValueError: + # Something already occupies the name (e.g. corrupted/unparsable + # file) — never overwrite it; a broken ref surfaces at + # materialize/launch time instead. + logger.warning( + f"Default LLM profile '{SEED_PROFILE_NAME}' exists but " + "failed to load; leaving it as-is" + ) + return SEED_PROFILE_NAME + if not _llm_has_real_config(llm): + # Never-configured account: don't persist a keyless ghost profile. + # Leave the ref soft/dangling; the banner + launch-time error handle + # it, and it resolves for real once the user saves a profile. + logger.info( + f"Skipping default LLM profile '{SEED_PROFILE_NAME}' seed: " + "no real LLM config yet (leaving llm_profile_ref as a soft ref)" + ) + return SEED_PROFILE_NAME + try: + llm_store.save( + SEED_PROFILE_NAME, + llm, + include_secrets=True, + cipher=cipher, + max_profiles=MAX_PROFILES, + ) + logger.info(f"Seeded default LLM profile '{SEED_PROFILE_NAME}'") + except LLMProfileLimitExceeded: + # Can't mirror the live LLM as a profile; the agent profile's + # llm_profile_ref will still dangle, but no worse than before. + logger.warning( + "Could not seed default LLM profile " + f"'{SEED_PROFILE_NAME}': profile limit reached" + ) return SEED_PROFILE_NAME @@ -235,7 +234,7 @@ def _ensure_active_profile( the pointer write, so concurrent callers seed once and agree on the pointer. """ settings_store = get_settings_store(config) - with store_errors(), store.lock(): + with store.lock(): settings = settings_store.load() or PersistedSettings() active_id = settings.active_agent_profile_id if active_id is not None and store.name_for_id(active_id) is not None: @@ -312,24 +311,22 @@ def active_agent_profile( settings = get_settings_store(config).load() or PersistedSettings() if settings.active_agent_profile_id is None: return None - with store_errors(): - name = store.name_for_id(settings.active_agent_profile_id) - if name is None: - return None - try: - return store.load(name) - except FileNotFoundError: - return None + name = store.name_for_id(settings.active_agent_profile_id) + if name is None: + return None + try: + return store.load(name) + except FileNotFoundError: + return None def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None: """Return the stable id of the profile stored under ``name``, if present.""" name = canonical_profile_name(name) - with store_errors(): - for summary in store.list_summaries(): - if summary.get("name") == name: - sid = summary.get("id") - return str(sid) if sid is not None else None + for summary in store.list_summaries(): + if summary.get("name") == name: + sid = summary.get("id") + return str(sid) if sid is not None else None return None @@ -348,8 +345,7 @@ def list_agent_profiles(request: Request) -> AgentProfileListResponse: _ensure_active_profile(store, config, get_cipher(request)) settings = settings_store.load() or settings - with store_errors(): - summaries = store.list_summaries() + summaries = store.list_summaries() return AgentProfileListResponse( profiles=[AgentProfileInfo(**s) for s in summaries], @@ -367,13 +363,9 @@ def get_agent_profile(name: ProfileName) -> AgentProfileDetailResponse: """ store = get_agent_profile_store() try: - with store_errors(): - profile = store.load(name) + profile = store.load(name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Agent profile '{name}' not found", - ) + raise NotFound(f"Agent profile '{name}' not found") payload = profile.model_dump(mode="json") return AgentProfileDetailResponse(name=name, profile=payload) @@ -388,18 +380,12 @@ def _validate_profile_payload( # Match FastAPI's request-validation shape (``detail`` is a list of # error objects): ``loc``/``type``/``msg`` (``input`` dropped — see # safe_validation_error_detail's docstring for why msg is now safe). - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail=safe_validation_error_detail(e), - ) + raise Unprocessable(safe_validation_error_detail(e)) except Exception: # Any other validation failure (e.g. a schema/migration error) is a # client error, never a 500. Stay generic — these messages can embed # the input. - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Invalid agent profile", - ) + raise Unprocessable("Invalid agent profile") @agent_profiles_router.post( @@ -426,17 +412,13 @@ def save_agent_profile( # holds the store lock across read + mint + save so two concurrent creates # of the same new name can't both mint an id and clobber each other. try: - with store_errors(): - save_profile_preserving_identity( - store, profile, max_profiles=MAX_AGENT_PROFILES - ) + save_profile_preserving_identity( + store, profile, max_profiles=MAX_AGENT_PROFILES + ) except ProfileLimitExceeded: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - f"Agent profile limit reached ({MAX_AGENT_PROFILES}). " - "Delete a profile before saving a new one." - ), + raise Conflict( + f"Agent profile limit reached ({MAX_AGENT_PROFILES}). " + "Delete a profile before saving a new one." ) logger.info(f"Saved agent profile '{name}'") @@ -460,8 +442,7 @@ def delete_agent_profile( store = get_agent_profile_store() deleted_id = _summary_id_for_name(store, name) - with store_errors(): - store.delete(name) + store.delete(name) if deleted_id is not None: config = get_config(request) @@ -508,18 +489,11 @@ def rename_agent_profile( """ store = get_agent_profile_store() try: - with store_errors(): - store.rename(name, body.new_name) + store.rename(name, body.new_name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Agent profile '{name}' not found", - ) + raise NotFound(f"Agent profile '{name}' not found") except FileExistsError: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Agent profile '{body.new_name}' already exists", - ) + raise Conflict(f"Agent profile '{body.new_name}' already exists") if name == body.new_name: message = f"Agent profile '{name}' unchanged (same name)" @@ -542,15 +516,11 @@ def activate_agent_profile( creation-time-only contract). Returns 404 if no stored profile has that id. """ store = get_agent_profile_store() - with store_errors(): - known_ids = { - str(s["id"]) for s in store.list_summaries() if s.get("id") is not None - } + known_ids = { + str(s["id"]) for s in store.list_summaries() if s.get("id") is not None + } if profile_id not in known_ids: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Agent profile with id '{profile_id}' not found", - ) + raise NotFound(f"Agent profile with id '{profile_id}' not found") config = get_config(request) settings_store = get_settings_store(config) @@ -563,15 +533,12 @@ def set_pointer(settings: PersistedSettings) -> PersistedSettings: settings_store.update(set_pointer) except (OSError, PermissionError): logger.error("Failed to activate agent profile - file I/O error") - raise HTTPException(status_code=500, detail="Failed to activate agent profile") + raise OperationFailed("Failed to activate agent profile") except RuntimeError as e: # A corrupted / mis-keyed settings file is a server-side integrity # failure, not a client conflict. logger.error(f"Failed to activate agent profile: {e}") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Failed to activate agent profile", - ) + raise OperationFailed("Failed to activate agent profile") logger.info(f"Activated agent profile id '{profile_id}'") return ActivateAgentProfileResponse( @@ -603,14 +570,10 @@ async def materialize_agent_profile( else: store = get_agent_profile_store() try: - with store_errors(): - # Off the event loop: the store lock wait blocks (up to 30 s). - profile = await asyncio.to_thread(store.load, name) + # Off the event loop: the store lock wait blocks (up to 30 s). + profile = await asyncio.to_thread(store.load, name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Agent profile '{name}' not found", - ) + raise NotFound(f"Agent profile '{name}' not found") config = get_config(request) settings = get_settings_store(config).load() or PersistedSettings() diff --git a/openhands-agent-server/openhands/agent_server/api.py b/openhands-agent-server/openhands/agent_server/api.py index a10e5497baa..b115a755011 100644 --- a/openhands-agent-server/openhands/agent_server/api.py +++ b/openhands-agent-server/openhands/agent_server/api.py @@ -6,7 +6,7 @@ import threading import traceback import uuid -from collections.abc import AsyncIterator, Sequence +from collections.abc import AsyncIterator, Mapping, Sequence from concurrent.futures import Future from contextlib import asynccontextmanager, suppress from importlib.metadata import version @@ -43,10 +43,7 @@ export_session_api_key, get_default_config, ) -from openhands.agent_server.conversation_lease import ( - ConversationOwnershipLostError, - _is_pid_alive, -) +from openhands.agent_server.conversation_lease import _is_pid_alive from openhands.agent_server.conversation_registry import ( create_conversation_registry, ) @@ -54,10 +51,7 @@ conversation_catalog_router, conversation_router, ) -from openhands.agent_server.conversation_service import ( - ConversationService, - CredentialBindingActivationRequired, -) +from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.credential_binding import ( router as credential_binding_router, ) @@ -65,7 +59,7 @@ check_session_api_key, check_workspace_session, ) -from openhands.agent_server.event_service import ConversationRunLimitExceeded +from openhands.agent_server.errors import status_for from openhands.agent_server.experimental_features_router import ( experimental_features_router, ) @@ -122,6 +116,7 @@ from openhands.agent_server.vscode_router import vscode_router from openhands.agent_server.vscode_service import get_vscode_service from openhands.agent_server.workspaces_router import workspaces_router +from openhands.sdk.errors import DomainError from openhands.sdk.logger import DEBUG, get_logger from openhands.sdk.tool.registry import seal_tool_catalog, unseal_tool_catalog from openhands.sdk.utils.redact import sanitize_dict @@ -598,17 +593,19 @@ def _create_fastapi_instance(config: Config) -> FastAPI: ) -def _find_http_exception(exc: BaseExceptionGroup) -> HTTPException | None: - """Helper function to find HTTPException in ExceptionGroup. +def _find_http_exception( + exc: BaseExceptionGroup, +) -> HTTPException | DomainError | None: + """Find the first HTTPException or domain error in an ExceptionGroup. Args: - exc: BaseExceptionGroup to search for HTTPException. + exc: BaseExceptionGroup to search. Returns: - HTTPException if found, None otherwise. + The first HTTPException or DomainError found, None otherwise. """ for inner_exc in exc.exceptions: - if isinstance(inner_exc, HTTPException): + if isinstance(inner_exc, (HTTPException, DomainError)): return inner_exc # Recursively search nested ExceptionGroups if isinstance(inner_exc, BaseExceptionGroup): @@ -768,43 +765,28 @@ def _sanitize_validation_errors(errors: Sequence[Any]) -> list[dict]: return sanitized -def _add_exception_handlers(api: FastAPI) -> None: - """Add exception handlers to the FastAPI application.""" +async def _domain_error_handler(request: Request, exc: DomainError) -> JSONResponse: + """Map a domain error to its status from ``ERROR_STATUS``, the only map.""" + headers = {"Retry-After": exc.retry_after} if exc.retry_after else None + return _error_response( + request, + HTTPException(status_for(exc), exc.detail, headers), + exc.extra, + ) - @api.exception_handler(ConversationRunLimitExceeded) - async def _run_limit_handler( - _request: Request, exc: ConversationRunLimitExceeded - ) -> JSONResponse: - return JSONResponse(status_code=429, content={"detail": str(exc)}) - @api.exception_handler(ConversationOwnershipLostError) - async def _ownership_lost_handler( - _request: Request, _exc: ConversationOwnershipLostError - ) -> JSONResponse: - # Another server instance took over this conversation's lease, so the - # guarded write was refused: a conflict, not a server fault. - return JSONResponse( - status_code=409, - content={ - "detail": ( - "Conversation is owned by another agent server instance; " - "the write was refused" - ) - }, - ) +def add_domain_error_handler(app: FastAPI) -> None: + """Answer ``openhands.sdk.errors`` categories with their mapped status. - @api.exception_handler(CredentialBindingActivationRequired) - async def _credential_binding_activation_required_handler( - _request: Request, - exc: CredentialBindingActivationRequired, - ) -> JSONResponse: - return JSONResponse( - status_code=409, - content={ - "detail": str(exc), - "retryable": True, - }, - ) + ``create_app`` installs it with the other handlers; an app that mounts + agent-server routers on its own needs it too, or those errors become 500s. + """ + app.exception_handler(DomainError)(_domain_error_handler) + + +def _add_exception_handlers(api: FastAPI) -> None: + """Add exception handlers to the FastAPI application.""" + add_domain_error_handler(api) @api.exception_handler(RequestValidationError) async def _validation_exception_handler( @@ -861,12 +843,16 @@ async def _unhandled_exception_handler( # Check if this is an HTTPException that should be handled directly if isinstance(exc, HTTPException): return await _http_exception_handler(request, exc) + if isinstance(exc, DomainError): + return await _domain_error_handler(request, exc) # Check if this is a BaseExceptionGroup with HTTPExceptions if isinstance(exc, BaseExceptionGroup): http_exc = _find_http_exception(exc) - if http_exc: + if isinstance(http_exc, HTTPException): return await _http_exception_handler(request, http_exc) + if isinstance(http_exc, DomainError): + return await _domain_error_handler(request, http_exc) # If no HTTPException found, treat as unhandled exception logger.error( "Unhandled ExceptionGroup on %s %s [error_id=%s]", @@ -894,54 +880,61 @@ async def _unhandled_exception_handler( async def _http_exception_handler( request: Request, exc: HTTPException ) -> JSONResponse: - """Handle HTTPExceptions with appropriate logging.""" - # Log 4xx errors at info level (expected client errors like auth failures) - if 400 <= exc.status_code < 500: - logger.info( - "HTTPException %d on %s %s: %s", - exc.status_code, - request.method, - request.url.path, - exc.detail, - ) - # Log 5xx errors at error level. HTTPException is intentionally - # raised flow control — the route picked this status and detail - # on purpose — so a stack trace adds no information beyond - # `exc.detail` and makes routine upstream blips look - # indistinguishable from a process crash. Unhandled exceptions - # still get a full traceback via _unhandled_exception_handler - # above. Include the traceback only when DEBUG is on, as an - # opt-in debugging aid. - elif exc.status_code >= 500: - logger.error( - "HTTPException %d on %s %s: %s", - exc.status_code, - request.method, - request.url.path, - exc.detail, - exc_info=(type(exc), exc, exc.__traceback__) if DEBUG else None, - ) - content = { - "detail": "Internal Server Error", - "exception": str(exc), - } - if DEBUG: - content["traceback"] = traceback.format_exc() - # Don't leak internal details to clients for 5xx errors in production - return JSONResponse( - status_code=exc.status_code, - content=content, - headers=exc.headers, - ) + """Handle HTTPExceptions raised by FastAPI itself (routing, security).""" + return _error_response(request, exc, {}) + - # Return clean JSON response for all non-5xx HTTP exceptions. Keep the - # exception's headers (e.g. Retry-After, WWW-Authenticate). +def _error_response( + request: Request, exc: HTTPException, extra: Mapping[str, object] +) -> JSONResponse: + """Render an error with logging; 5xx details are not shown to clients.""" + # Log 4xx errors at info level (expected client errors like auth failures) + if 400 <= exc.status_code < 500: + logger.info( + "HTTPException %d on %s %s: %s", + exc.status_code, + request.method, + request.url.path, + exc.detail, + ) + # Log 5xx errors at error level. HTTPException is intentionally + # raised flow control — the route picked this status and detail + # on purpose — so a stack trace adds no information beyond + # `exc.detail` and makes routine upstream blips look + # indistinguishable from a process crash. Unhandled exceptions + # still get a full traceback via _unhandled_exception_handler + # above. Include the traceback only when DEBUG is on, as an + # opt-in debugging aid. + elif exc.status_code >= 500: + logger.error( + "HTTPException %d on %s %s: %s", + exc.status_code, + request.method, + request.url.path, + exc.detail, + exc_info=(type(exc), exc, exc.__traceback__) if DEBUG else None, + ) + content = { + "detail": "Internal Server Error", + "exception": str(exc), + } + if DEBUG: + content["traceback"] = traceback.format_exc() + # Don't leak internal details to clients for 5xx errors in production return JSONResponse( status_code=exc.status_code, - content={"detail": exc.detail}, + content=content, headers=exc.headers, ) + # Return clean JSON response for all non-5xx HTTP exceptions. Keep the + # exception's headers (e.g. Retry-After, WWW-Authenticate). + return JSONResponse( + status_code=exc.status_code, + content={"detail": exc.detail, **extra}, + headers=exc.headers, + ) + def create_app(config: Config | None = None) -> FastAPI: """Create and configure the FastAPI application. diff --git a/openhands-agent-server/openhands/agent_server/auth_router.py b/openhands-agent-server/openhands/agent_server/auth_router.py index 6ffaa4cb680..74a583d6311 100644 --- a/openhands-agent-server/openhands/agent_server/auth_router.py +++ b/openhands-agent-server/openhands/agent_server/auth_router.py @@ -19,6 +19,8 @@ from fastapi import APIRouter, Request, Response, status from openhands.agent_server.dependencies import WORKSPACE_SESSION_COOKIE_NAME +from openhands.agent_server.errors import error_responses +from openhands.sdk.errors import Unauthenticated auth_router = APIRouter(prefix="/auth", tags=["Auth"]) @@ -138,7 +140,9 @@ def _append_partitioned_to_last_set_cookie( status_code=status.HTTP_204_NO_CONTENT, responses={ 204: {"description": "Cookie set"}, - 401: {"description": "Missing or invalid X-Session-API-Key header"}, + **error_responses( + {Unauthenticated: "Missing or invalid X-Session-API-Key header"} + ), }, ) async def create_workspace_session(request: Request, response: Response) -> Response: diff --git a/openhands-agent-server/openhands/agent_server/bash_router.py b/openhands-agent-server/openhands/agent_server/bash_router.py index 90b5bcde9d8..d599bbe7129 100644 --- a/openhands-agent-server/openhands/agent_server/bash_router.py +++ b/openhands-agent-server/openhands/agent_server/bash_router.py @@ -9,13 +9,12 @@ from fastapi import ( APIRouter, Depends, - HTTPException, Query, - status, ) from openhands.agent_server.bash_service import BashEventService from openhands.agent_server.dependencies import get_bash_event_service +from openhands.agent_server.errors import error_responses from openhands.agent_server.models import ( BashCommand, BashEventBase, @@ -26,6 +25,7 @@ Success, ) from openhands.agent_server.server_details_router import update_last_execution_time +from openhands.sdk.errors import NotFound, Unprocessable bash_router = APIRouter(prefix="/bash", tags=["Bash"]) @@ -73,7 +73,7 @@ async def search_bash_events( @bash_router.get( - "/bash_events/{event_id}", responses={404: {"description": "Item not found"}} + "/bash_events/{event_id}", responses=error_responses({NotFound: "Item not found"}) ) async def get_bash_event( event_id: str, @@ -82,7 +82,7 @@ async def get_bash_event( """Get a bash event event given an id""" event = await bash_event_service.get_bash_event(event_id) if event is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return event @@ -168,7 +168,7 @@ async def clear_all_bash_events( @bash_router.post( "/bash_commands/{command_id}/stop", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def stop_bash_command( command_id: UUID, @@ -185,7 +185,7 @@ async def stop_bash_command( return Success() if await bash_event_service.get_bash_event(command_id.hex) is not None: return Success() - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() def _validate_cwd(request: ExecuteBashRequest, service: BashEventService) -> None: @@ -195,4 +195,4 @@ def _validate_cwd(request: ExecuteBashRequest, service: BashEventService) -> Non .resolve() .is_relative_to(Path(service.default_cwd).resolve()) ): - raise HTTPException(422, "cwd must be inside the conversation workspace") + raise Unprocessable("cwd must be inside the conversation workspace") diff --git a/openhands-agent-server/openhands/agent_server/canvas_extensions/bridge.py b/openhands-agent-server/openhands/agent_server/canvas_extensions/bridge.py index 2b8d658493b..c0bac11d3b1 100644 --- a/openhands-agent-server/openhands/agent_server/canvas_extensions/bridge.py +++ b/openhands-agent-server/openhands/agent_server/canvas_extensions/bridge.py @@ -16,7 +16,7 @@ from urllib.parse import unquote, urlparse import httpx -from fastapi import HTTPException, Request, Response, WebSocket, status +from fastapi import Request, Response, WebSocket from pydantic import BaseModel from openhands.agent_server.auth_router import ( @@ -28,6 +28,17 @@ proxy_http, strip_auth_query, ) +from openhands.sdk.errors import ( + Conflict, + DomainError, + Forbidden, + Invalid, + Misdirected, + Unauthenticated, + Unavailable, + UpstreamFailed, + UpstreamTimeout, +) APP_BACKEND_SESSION_COOKIE_NAME: Final = "oh_app_backend_session" @@ -232,16 +243,10 @@ def get_app_backend_session_store( def _public_url(config: Config) -> str: value = config.app_backend_public_url if not value: - raise HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - "Canvas App backend ingress is not configured", - ) + raise Unavailable("Canvas App backend ingress is not configured") parsed = urlparse(value) if parsed.scheme not in {"http", "https"} or not parsed.netloc: - raise HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - "Canvas App backend ingress is misconfigured", - ) + raise Unavailable("Canvas App backend ingress is misconfigured") return value.rstrip("/") @@ -296,10 +301,7 @@ def _request_origin(request: Request | WebSocket) -> str | None: def _require_ingress_host(request: Request | WebSocket, public_url: str) -> None: if _request_origin(request) != _origin(public_url): - raise HTTPException( - status.HTTP_421_MISDIRECTED_REQUEST, - "Canvas App request must use the configured ingress origin", - ) + raise Misdirected("Canvas App request must use the configured ingress origin") def _require_bootstrap_origin(request: Request, public_url: str) -> None: @@ -307,17 +309,14 @@ def _require_bootstrap_origin(request: Request, public_url: str) -> None: origin = request.headers.get("origin", "") config: Config = request.app.state.config if not _allowed_control_origin(config, origin): - raise HTTPException(status.HTTP_403_FORBIDDEN, "Origin is not allowed") + raise Forbidden("Origin is not allowed") if _origin(origin) == _origin(public_url): - raise HTTPException( - status.HTTP_409_CONFLICT, - "Canvas App ingress must use a separate browser origin", - ) + raise Conflict("Canvas App ingress must use a separate browser origin") def _require_app_origin(origin: str | None, public_url: str) -> None: if not origin or _origin(origin) != _origin(public_url): - raise HTTPException(status.HTTP_403_FORBIDDEN, "Origin is not allowed") + raise Forbidden("Origin is not allowed") def _validate_proxy_path(path: str) -> None: @@ -338,9 +337,9 @@ def _validate_proxy_path(path: str) -> None: break candidate = decoded else: - raise HTTPException(status.HTTP_400_BAD_REQUEST, "Invalid backend path") + raise Invalid("Invalid backend path") if "\\" in candidate or any(part in {".", ".."} for part in candidate.split("/")): - raise HTTPException(status.HTTP_400_BAD_REQUEST, "Invalid backend path") + raise Invalid("Invalid backend path") def _ready_endpoint( @@ -351,16 +350,10 @@ def _ready_endpoint( ) endpoint = manager.ready_endpoint(extension_name) if manager is not None else None if endpoint is None: - raise HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - "Canvas App backend is not ready", - ) + raise Unavailable("Canvas App backend is not ready") host, port = endpoint if host not in {"127.0.0.1", "::1", "localhost"}: - raise HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - "Canvas App backend target is not loopback", - ) + raise Unavailable("Canvas App backend target is not loopback") return host, port @@ -398,9 +391,8 @@ def _set_session_cookie( max_age: int, ) -> None: if not _session_cookie_is_secure(request): - raise HTTPException( - status.HTTP_503_SERVICE_UNAVAILABLE, - "Canvas App sessions require HTTPS or a loopback secure context", + raise Unavailable( + "Canvas App sessions require HTTPS or a loopback secure context" ) response.set_cookie( key=APP_BACKEND_SESSION_COOKIE_NAME, @@ -460,7 +452,7 @@ async def proxy_app_backend_http( token, extension_name, endpoint ) if session is None: - raise HTTPException(status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() query = strip_auth_query("?" + request.url.query).lstrip("?") upstream_path = f"/{path}" if path else "/" if query: @@ -472,15 +464,13 @@ async def proxy_app_backend_http( upstream_path=upstream_path, reject_redirects=True, ) - except HTTPException as exc: + except UpstreamFailed as exc: # proxy_http words connection failures for the Docker runtime # ("Conversation container unreachable"); name the Canvas backend. - if exc.status_code == status.HTTP_502_BAD_GATEWAY and isinstance( + if not isinstance(exc, UpstreamTimeout) and isinstance( exc.__cause__, httpx.HTTPError ): - raise HTTPException( - status.HTTP_502_BAD_GATEWAY, "Canvas App backend unreachable" - ) from exc.__cause__ + raise UpstreamFailed("Canvas App backend unreachable") from exc.__cause__ raise @@ -497,8 +487,8 @@ async def proxy_app_backend_websocket( store = get_app_backend_session_store(websocket) session = await store.authorize(token, extension_name, endpoint) if session is None: - raise HTTPException(status.HTTP_401_UNAUTHORIZED) - except HTTPException: + raise Unauthenticated() + except DomainError: await websocket.close(code=1008) return diff --git a/openhands-agent-server/openhands/agent_server/canvas_extensions_bridge_router.py b/openhands-agent-server/openhands/agent_server/canvas_extensions_bridge_router.py index 2b16348eb9c..1c4e9a00e00 100644 --- a/openhands-agent-server/openhands/agent_server/canvas_extensions_bridge_router.py +++ b/openhands-agent-server/openhands/agent_server/canvas_extensions_bridge_router.py @@ -15,6 +15,8 @@ CANVAS_EXTENSION_NAME_PATTERN, ) from openhands.agent_server.dependencies import check_session_api_key +from openhands.agent_server.errors import error_responses +from openhands.sdk.errors import Conflict, Forbidden, Unauthenticated, Unavailable app_backend_bridge_router = APIRouter(tags=["Canvas App Backends"]) @@ -33,12 +35,14 @@ "/app-backends/{extension_name}/session", response_model=AppBackendSessionResponse, dependencies=[Depends(check_session_api_key)], - responses={ - 401: {"description": "Missing or invalid X-Session-API-Key header"}, - 403: {"description": "Origin is not allowed"}, - 409: {"description": "Ingress does not use a separate browser origin"}, - 503: {"description": "Backend is unavailable or ingress is not configured"}, - }, + responses=error_responses( + { + Unauthenticated: "Missing or invalid X-Session-API-Key header", + Forbidden: "Origin is not allowed", + Conflict: "Ingress does not use a separate browser origin", + Unavailable: "Backend is unavailable or ingress is not configured", + } + ), ) async def create_app_backend_session_endpoint( extension_name: AppBackendNamePath, @@ -62,8 +66,12 @@ async def create_app_backend_session_endpoint( dependencies=[Depends(check_session_api_key)], responses={ 204: {"description": "Browser session revoked and cookie cleared"}, - 401: {"description": "Missing or invalid X-Session-API-Key header"}, - 403: {"description": "Origin is not allowed"}, + **error_responses( + { + Unauthenticated: "Missing or invalid X-Session-API-Key header", + Forbidden: "Origin is not allowed", + } + ), }, ) async def delete_app_backend_session_endpoint( diff --git a/openhands-agent-server/openhands/agent_server/canvas_extensions_router.py b/openhands-agent-server/openhands/agent_server/canvas_extensions_router.py index ed4068ee5c8..7a8498dac2c 100644 --- a/openhands-agent-server/openhands/agent_server/canvas_extensions_router.py +++ b/openhands-agent-server/openhands/agent_server/canvas_extensions_router.py @@ -10,7 +10,7 @@ import asyncio from typing import Annotated, Final -from fastapi import APIRouter, HTTPException, Path, Query, Request +from fastapi import APIRouter, Path, Query, Request from fastapi.responses import FileResponse from pydantic import BaseModel, Field, ValidationError @@ -38,6 +38,8 @@ MANIFEST_FILENAME, CanvasExtensionManifest, ) +from openhands.agent_server.errors import error_responses +from openhands.sdk.errors import Conflict, Invalid, NotFound, Unprocessable from openhands.sdk.extensions.fetch import ExtensionFetchError from openhands.sdk.utils.redact import redact_url_credentials @@ -192,11 +194,13 @@ class UninstallCanvasExtensionResponse(BaseModel): @canvas_extensions_router.post( "/install", response_model=InstalledCanvasExtensionResponse, - responses={ - 400: {"description": "Could not read canvas extension source"}, - 409: {"description": "Canvas extension already installed (use force=true)"}, - 422: {"description": "Invalid canvas extension (bad manifest, etc.)"}, - }, + responses=error_responses( + { + Invalid: "Could not read canvas extension source", + Conflict: "Canvas extension already installed (use force=true)", + Unprocessable: "Invalid canvas extension (bad manifest, etc.)", + } + ), ) async def install_canvas_extension_endpoint( request: InstallCanvasExtensionRequest, @@ -210,10 +214,7 @@ async def install_canvas_extension_endpoint( """ manager = _backend_manager(http_request) if request.force and manager.has_running_backends(): - raise HTTPException( - status_code=409, - detail="Stop running Canvas App backends before a forced install", - ) + raise Conflict("Stop running Canvas App backends before a forced install") try: info = await asyncio.to_thread( install_canvas_extension, @@ -227,9 +228,8 @@ async def install_canvas_extension_endpoint( info, get_installed_canvas_extension_manifest(info.name) ) except FileExistsError: - raise HTTPException( - status_code=409, - detail="Canvas extension already installed. Use force=true to overwrite.", + raise Conflict( + "Canvas extension already installed. Use force=true to overwrite." ) except ExtensionFetchError as e: # Pass the specific reason through -- which of source/ref/repo_path is @@ -238,26 +238,18 @@ async def install_canvas_extension_endpoint( # Deliberately not worded "failed to fetch": the canvas client treats # that phrase as a network outage and hides the reason behind a # "Disconnected, check your network" toast. - raise HTTPException( - status_code=400, - detail=( - "Could not read canvas extension source: " - f"{redact_url_credentials(str(e))}" - ), + raise Invalid( + f"Could not read canvas extension source: {redact_url_credentials(str(e))}" ) except FileNotFoundError: - raise HTTPException( - status_code=422, - detail=( - f"No {MANIFEST_FILENAME} found at the resolved location. " - "Source plus Path must point at the extension's own " - "directory, not the repository root." - ), + raise Unprocessable( + f"No {MANIFEST_FILENAME} found at the resolved location. " + "Source plus Path must point at the extension's own " + "directory, not the repository root." ) except (ValidationError, ValueError, OSError): - raise HTTPException( - status_code=422, - detail="Invalid canvas extension. Ensure the manifest is well-formed.", + raise Unprocessable( + "Invalid canvas extension. Ensure the manifest is well-formed." ) @@ -282,7 +274,7 @@ def list_installed_canvas_extensions_endpoint() -> ( @canvas_extensions_router.get( "/installed/{extension_name}", response_model=InstalledCanvasExtensionResponse, - responses={404: {"description": "Canvas extension not installed"}}, + responses=error_responses({NotFound: "Canvas extension not installed"}), ) def get_installed_canvas_extension_endpoint( extension_name: CanvasExtensionNamePath, @@ -290,10 +282,7 @@ def get_installed_canvas_extension_endpoint( """Get information about a specific installed canvas extension.""" info = get_installed_canvas_extension(name=extension_name) if info is None: - raise HTTPException( - status_code=404, - detail=f"Canvas extension '{extension_name}' is not installed", - ) + raise NotFound(f"Canvas extension '{extension_name}' is not installed") return InstalledCanvasExtensionResponse.from_info( info, get_installed_canvas_extension_manifest(extension_name) ) @@ -302,7 +291,7 @@ def get_installed_canvas_extension_endpoint( @canvas_extensions_router.patch( "/installed/{extension_name}", response_model=UpdateCanvasExtensionStateResponse, - responses={404: {"description": "Canvas extension not installed"}}, + responses=error_responses({NotFound: "Canvas extension not installed"}), ) async def set_canvas_extension_enabled_endpoint( extension_name: CanvasExtensionNamePath, @@ -316,7 +305,7 @@ async def set_canvas_extension_enabled_endpoint( if not request.enabled: await _revoke_and_stop_backend(http_request, extension_name) if not disable_canvas_extension(name=extension_name): - raise HTTPException(404, "Canvas App is not installed") + raise NotFound("Canvas App is not installed") return UpdateCanvasExtensionStateResponse( name=extension_name, enabled=False ) @@ -364,20 +353,20 @@ async def set_canvas_extension_enabled_endpoint( except (ValueError, RuntimeError, OSError) as exc: await _revoke_and_stop_backend(http_request, extension_name) disable_canvas_extension(name=extension_name) - raise HTTPException(409, str(exc)) from exc + raise Conflict(str(exc)) from exc except BaseException: await _revoke_and_stop_backend(http_request, extension_name) disable_canvas_extension(name=extension_name) raise if not enable_canvas_extension(name=extension_name): - raise HTTPException(404, "Canvas App is not installed") + raise NotFound("Canvas App is not installed") return UpdateCanvasExtensionStateResponse(name=extension_name, enabled=True) @canvas_extensions_router.delete( "/installed/{extension_name}", response_model=UninstallCanvasExtensionResponse, - responses={404: {"description": "Canvas extension not installed"}}, + responses=error_responses({NotFound: "Canvas extension not installed"}), ) async def uninstall_canvas_extension_endpoint( extension_name: CanvasExtensionNamePath, @@ -386,10 +375,7 @@ async def uninstall_canvas_extension_endpoint( """Uninstall a canvas extension by name while retaining backend data.""" await _revoke_and_stop_backend(request, extension_name) if not uninstall_canvas_extension(name=extension_name): - raise HTTPException( - status_code=404, - detail=f"Canvas extension '{extension_name}' is not installed", - ) + raise NotFound(f"Canvas extension '{extension_name}' is not installed") return UninstallCanvasExtensionResponse( message=f"Canvas extension '{extension_name}' uninstalled" ) @@ -410,7 +396,7 @@ async def get_canvas_extension_backend_status_endpoint( @canvas_extensions_router.post( "/installed/{extension_name}/backend/prepare", response_model=BackendStatus, - responses={409: {"description": "Revision or checksum approval conflict"}}, + responses=error_responses({Conflict: "Revision or checksum approval conflict"}), ) async def prepare_canvas_extension_backend_endpoint( extension_name: CanvasExtensionNamePath, @@ -421,13 +407,13 @@ async def prepare_canvas_extension_backend_endpoint( try: return await _backend_manager(request).prepare(extension_name, body.revision) except ValueError as exc: - raise HTTPException(status_code=409, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc @canvas_extensions_router.post( "/installed/{extension_name}/backend/start", response_model=BackendStatus, - responses={409: {"description": "Revision is not prepared or cannot start"}}, + responses=error_responses({Conflict: "Revision is not prepared or cannot start"}), ) async def start_canvas_extension_backend_endpoint( extension_name: CanvasExtensionNamePath, @@ -438,7 +424,7 @@ async def start_canvas_extension_backend_endpoint( try: return await _backend_manager(request).start(extension_name, body.revision) except (RuntimeError, ValueError) as exc: - raise HTTPException(status_code=409, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc @canvas_extensions_router.post( @@ -471,7 +457,7 @@ async def get_canvas_extension_backend_logs_endpoint( @canvas_extensions_router.delete( "/installed/{extension_name}/backend/data", response_model=BackendStatus, - responses={409: {"description": "Backend must be stopped first"}}, + responses=error_responses({Conflict: "Backend must be stopped first"}), ) async def delete_canvas_extension_backend_data_endpoint( extension_name: CanvasExtensionNamePath, @@ -481,12 +467,12 @@ async def delete_canvas_extension_backend_data_endpoint( try: return await _backend_manager(request).delete_data(extension_name) except RuntimeError as exc: - raise HTTPException(status_code=409, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc @canvas_extensions_router.get( "/installed/{extension_name}/bundle", - responses={404: {"description": "Canvas extension or bundle not found"}}, + responses=error_responses({NotFound: "Canvas extension or bundle not found"}), ) def get_canvas_extension_bundle_endpoint( extension_name: CanvasExtensionNamePath, @@ -503,10 +489,7 @@ def get_canvas_extension_bundle_endpoint( """ bundle_path = get_canvas_extension_bundle_path(name=extension_name) if bundle_path is None: - raise HTTPException( - status_code=404, - detail=f"Canvas extension '{extension_name}' bundle not found", - ) + raise NotFound(f"Canvas extension '{extension_name}' bundle not found") return FileResponse(bundle_path, headers={"Cache-Control": "no-cache"}) @@ -519,7 +502,7 @@ def get_canvas_extension_bundle_endpoint( "image/svg+xml": {"schema": {"type": "string", "format": "binary"}} } }, - 404: {"description": "Canvas extension or icon not found"}, + **error_responses({NotFound: "Canvas extension or icon not found"}), }, ) def get_canvas_extension_icon_endpoint( @@ -532,10 +515,7 @@ def get_canvas_extension_icon_endpoint( """ icon_path = get_canvas_extension_icon_path(name=extension_name) if icon_path is None: - raise HTTPException( - status_code=404, - detail=f"Canvas extension '{extension_name}' icon not found", - ) + raise NotFound(f"Canvas extension '{extension_name}' icon not found") return FileResponse( icon_path, media_type="image/svg+xml", @@ -552,7 +532,7 @@ def get_canvas_extension_icon_endpoint( @canvas_extensions_router.post( "/installed/{extension_name}/backend/secret-grant", response_model=BackendStatus, - responses={409: {"description": "Grant does not match installed declaration"}}, + responses=error_responses({Conflict: "Grant does not match installed declaration"}), ) async def grant_canvas_extension_backend_secrets_endpoint( extension_name: CanvasExtensionNamePath, @@ -563,7 +543,7 @@ async def grant_canvas_extension_backend_secrets_endpoint( try: return await _backend_manager(request).grant_secrets(extension_name, body) except ValueError as exc: - raise HTTPException(status_code=409, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc @canvas_extensions_router.delete( diff --git a/openhands-agent-server/openhands/agent_server/conversation_lease.py b/openhands-agent-server/openhands/agent_server/conversation_lease.py index 195904d81f3..fb70b365926 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_lease.py +++ b/openhands-agent-server/openhands/agent_server/conversation_lease.py @@ -11,6 +11,7 @@ from filelock import FileLock from openhands.sdk import get_logger +from openhands.sdk.errors import Conflict logger = get_logger(__name__) @@ -84,7 +85,10 @@ def __init__( ) -class ConversationOwnershipLostError(RuntimeError): +class ConversationOwnershipLostError(Conflict, RuntimeError): + """Another server instance took over this conversation's lease, so the + guarded write was refused: a conflict, not a server fault.""" + def __init__( self, *, @@ -95,7 +99,11 @@ def __init__( self.conversation_dir = conversation_dir self.owner_instance_id = owner_instance_id self.generation = generation - super().__init__("conversation ownership was lost before the write completed") + super().__init__( + "Conversation is owned by another agent server instance; " + "the write was refused", + message="conversation ownership was lost before the write completed", + ) class ConversationLease: diff --git a/openhands-agent-server/openhands/agent_server/conversation_router.py b/openhands-agent-server/openhands/agent_server/conversation_router.py index 42bfc98a07e..614a13db5c4 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_router.py +++ b/openhands-agent-server/openhands/agent_server/conversation_router.py @@ -9,7 +9,6 @@ Body, Depends, Header, - HTTPException, Query, Request, Response, @@ -20,7 +19,6 @@ from openhands.agent_server._secrets_exposure import ( decrypt_incoming_llm_secrets, get_cipher, - store_errors, ) from openhands.agent_server.conversation_registry import ConversationRegistry from openhands.agent_server.conversation_service import ( @@ -29,8 +27,9 @@ UnavailableAgentTool, ) from openhands.agent_server.dependencies import get_conversation_service +from openhands.agent_server.errors import error_responses from openhands.agent_server.event_service import CondensationUnavailable -from openhands.agent_server.launch import launch_http_exception +from openhands.agent_server.launch import launch_error from openhands.agent_server.models import ( INCLUDE_SKILLS_PARAM_TITLE, AgentResponseResult, @@ -62,6 +61,14 @@ ConversationObservabilitySpanName, ConversationObservabilityTags, ) +from openhands.sdk.errors import ( + Conflict, + Invalid, + NotFound, + RateLimited, + Unprocessable, + UpstreamTimeout, +) from openhands.sdk.launch import AgentLaunchError, LaunchStoreError from openhands.sdk.marketplace.registry import ( MarketplaceNotFoundError, @@ -109,15 +116,11 @@ def _request_with_observability_headers( **request.observability_metadata, } except json.JSONDecodeError as exc: - raise HTTPException( - status_code=422, - detail="X-OpenHands-Observability-Metadata must be a JSON object", + raise Unprocessable( + "X-OpenHands-Observability-Metadata must be a JSON object" ) from exc except ValidationError as exc: - raise HTTPException( - status_code=422, - detail=exc.errors(include_context=False), - ) from exc + raise Unprocessable(exc.errors(include_context=False)) from exc if parent_span_context and not request.observability_parent_span_context: updates["observability_parent_span_context"] = parent_span_context return request.model_copy(update=updates) if updates else request @@ -217,7 +220,7 @@ async def count_conversations( @conversation_router.get( - "/{conversation_id}", responses={404: {"description": "Item not found"}} + "/{conversation_id}", responses=error_responses({NotFound: "Item not found"}) ) async def get_conversation( conversation_id: UUID, @@ -228,7 +231,7 @@ async def get_conversation( """Given an id, get a conversation""" conversation = await conversation_service.get_conversation(conversation_id) if conversation is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() if not include_skills: conversation = trim_conversation_response_skills(conversation) return _with_runtime_info(request, conversation) @@ -242,7 +245,7 @@ async def get_local_conversation_runtime( ) -> ConversationRuntimeInfo: """Inspect the always-available in-process runtime.""" if await conversation_service.get_conversation(conversation_id) is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() registry = getattr(request.app.state, "conversation_registry", None) if isinstance(registry, ConversationRegistry): return registry.runtime_info(conversation_id) @@ -265,7 +268,7 @@ async def reprovision_local_conversation_runtime( @conversation_router.get( "/{conversation_id}/agent_final_response", - responses={404: {"description": "Conversation not found"}}, + responses=error_responses({NotFound: "Conversation not found"}), ) async def get_conversation_agent_final_response( conversation_id: UUID, @@ -279,7 +282,7 @@ async def get_conversation_agent_final_response( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() response = await event_service.get_agent_final_response() return AgentResponseResult(response=response) @@ -310,7 +313,10 @@ async def batch_get_conversations( @conversation_router.post( - "", responses={429: {"description": "Server conversation run capacity is full"}} + "", + responses=error_responses( + {RateLimited: "Server conversation run capacity is full"} + ), ) async def start_conversation( request: Annotated[ @@ -334,10 +340,7 @@ async def start_conversation( ) -> ConversationInfo: """Start a conversation in the local environment.""" if request.conversation_runtime not in (None, "local"): - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="This server only runs local conversations", - ) + raise Unprocessable("This server only runs local conversations") request = _request_with_observability_headers( request, span_name=x_openhands_observability_span_name, @@ -348,15 +351,11 @@ async def start_conversation( try: info, is_new = await conversation_service.start_conversation(request) except (ProfileNotFound, AgentLaunchError, LaunchStoreError) as e: - raise launch_http_exception(e) from e + raise launch_error(e) from e except ClientToolRegistrationError as e: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) - ) from e + raise Unprocessable(str(e)) from e except (InvalidParentConversation, UnavailableAgentTool) as e: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(e) - ) from e + raise Unprocessable(str(e)) from e response.status_code = status.HTTP_201_CREATED if is_new else status.HTTP_200_OK if not include_skills: info = trim_conversation_response_skills(info) @@ -364,7 +363,7 @@ async def start_conversation( @conversation_router.post( - "/{conversation_id}/pause", responses={404: {"description": "Item not found"}} + "/{conversation_id}/pause", responses=error_responses({NotFound: "Item not found"}) ) async def pause_conversation( conversation_id: UUID, @@ -373,13 +372,13 @@ async def pause_conversation( """Pause a conversation, allowing it to be resumed later.""" paused = await conversation_service.pause_conversation(conversation_id) if not paused: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return Success() @conversation_router.post( "/{conversation_id}/interrupt", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def interrupt_conversation( conversation_id: UUID, @@ -393,12 +392,12 @@ async def interrupt_conversation( """ interrupted = await conversation_service.interrupt_conversation(conversation_id) if not interrupted: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return Success() @conversation_router.delete( - "/{conversation_id}", responses={404: {"description": "Item not found"}} + "/{conversation_id}", responses=error_responses({NotFound: "Item not found"}) ) async def delete_conversation( conversation_id: UUID, @@ -407,17 +406,19 @@ async def delete_conversation( """Permanently delete a conversation.""" deleted = await conversation_service.delete_conversation(conversation_id) if not deleted: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return Success() @conversation_router.post( "/{conversation_id}/run", - responses={ - 404: {"description": "Item not found"}, - 409: {"description": "Conversation is already running"}, - 429: {"description": "Server conversation run capacity is full"}, - }, + responses=error_responses( + { + NotFound: "Item not found", + Conflict: "Conversation is already running", + RateLimited: "Server conversation run capacity is full", + } + ), ) async def run_conversation( conversation_id: UUID, @@ -426,30 +427,29 @@ async def run_conversation( """Start running the conversation in the background.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.run() except ValueError as e: if str(e) == "conversation_already_running": - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - "Conversation already running. Wait for completion or pause first." - ), + raise Conflict( + "Conversation already running. Wait for completion or pause first." ) - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + raise Invalid(str(e)) return Success() @conversation_router.post( "/{conversation_id}/goal", - responses={ - 404: {"description": "Item not found"}, - 409: {"description": "Conversation run or goal loop is already running"}, - 429: {"description": "Server conversation run capacity is full"}, - }, + responses=error_responses( + { + NotFound: "Item not found", + Conflict: "Conversation run or goal loop is already running", + RateLimited: "Server conversation run capacity is full", + } + ), ) async def start_goal_in_conversation( conversation_id: UUID, @@ -464,7 +464,7 @@ async def start_goal_in_conversation( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.start_goal_loop( @@ -473,18 +473,15 @@ async def start_goal_in_conversation( except ValueError as e: message = str(e) if message in ("conversation_already_running", "goal_already_running"): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Conversation run or goal loop already running.", - ) - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message) + raise Conflict("Conversation run or goal loop already running.") + raise Invalid(message) return Success() @conversation_router.post( "/{conversation_id}/goal/stop", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def stop_goal_in_conversation( conversation_id: UUID, @@ -497,18 +494,20 @@ async def stop_goal_in_conversation( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() await event_service.stop_goal_loop() return Success() @conversation_router.post( "/{conversation_id}/goal/resume", - responses={ - 404: {"description": "Item not found"}, - 409: {"description": "Conversation run or goal loop is already running"}, - 429: {"description": "Server conversation run capacity is full"}, - }, + responses=error_responses( + { + NotFound: "Item not found", + Conflict: "Conversation run or goal loop is already running", + RateLimited: "Server conversation run capacity is full", + } + ), ) async def resume_goal_in_conversation( conversation_id: UUID, @@ -517,24 +516,22 @@ async def resume_goal_in_conversation( """Resume the last interrupted ``/goal`` loop inside this conversation.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.resume_goal_loop() except ValueError as e: message = str(e) if message in ("conversation_already_running", "goal_already_running"): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Conversation run or goal loop already running.", - ) - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=message) + raise Conflict("Conversation run or goal loop already running.") + raise Invalid(message) return Success() @conversation_router.post( - "/{conversation_id}/secrets", responses={404: {"description": "Item not found"}} + "/{conversation_id}/secrets", + responses=error_responses({NotFound: "Item not found"}), ) async def update_conversation_secrets( conversation_id: UUID, @@ -544,7 +541,7 @@ async def update_conversation_secrets( """Update secrets for a conversation.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() # Strings are valid SecretValue (SecretValue = str | SecretProvider) from typing import cast @@ -557,7 +554,7 @@ async def update_conversation_secrets( @conversation_router.post( "/{conversation_id}/confirmation_policy", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def set_conversation_confirmation_policy( conversation_id: UUID, @@ -567,14 +564,14 @@ async def set_conversation_confirmation_policy( """Set the confirmation policy for a conversation.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() await event_service.set_confirmation_policy(request.policy) return Success() @conversation_router.post( "/{conversation_id}/security_analyzer", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def set_conversation_security_analyzer( conversation_id: UUID, @@ -584,17 +581,19 @@ async def set_conversation_security_analyzer( """Set the security analyzer for a conversation.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() await event_service.set_security_analyzer(request.security_analyzer) return Success() @conversation_router.post( "/{conversation_id}/switch_profile", - responses={ - 400: {"description": "Invalid or corrupted profile, or an ACP agent"}, - 404: {"description": "Conversation or profile not found"}, - }, + responses=error_responses( + { + Invalid: "Invalid or corrupted profile, or an ACP agent", + NotFound: "Conversation or profile not found", + } + ), ) async def switch_conversation_profile( conversation_id: UUID, @@ -604,29 +603,25 @@ async def switch_conversation_profile( """Switch the conversation's LLM profile to a named profile.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() conversation = event_service.get_conversation() try: conversation.switch_profile(profile_name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{profile_name}' not found", - ) + raise NotFound(f"Profile '{profile_name}' not found") except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) + raise Invalid(str(e)) return Success() @conversation_router.post( "/{conversation_id}/switch_llm", - responses={ - 400: {"description": "Agent is ACP (use switch_acp_model)"}, - 404: {"description": "Conversation not found"}, - }, + responses=error_responses( + { + Invalid: "Agent is ACP (use switch_acp_model)", + NotFound: "Conversation not found", + } + ), ) async def switch_conversation_llm( request: Request, @@ -644,7 +639,7 @@ async def switch_conversation_llm( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() conversation = event_service.get_conversation() cipher = get_cipher(request) if cipher is not None: @@ -655,24 +650,22 @@ async def switch_conversation_llm( # reference or missing credential surfaces as 422 before the working LLM # is replaced. Inline-key configs without a provider_connection_id are # byte-identical to the old path. - with store_errors(): - llm = get_llm_profile_store().resolve_provider_connection(llm, cipher=cipher) + llm = get_llm_profile_store().resolve_provider_connection(llm, cipher=cipher) try: conversation.switch_llm(llm) except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) + raise Invalid(str(e)) return Success() @conversation_router.post( "/{conversation_id}/load_plugin", - responses={ - 400: {"description": "Invalid plugin reference or inactive conversation"}, - 404: {"description": "Conversation or plugin not found"}, - }, + responses=error_responses( + { + Invalid: "Invalid plugin reference or inactive conversation", + NotFound: "Conversation or plugin not found", + } + ), ) async def load_conversation_plugin( conversation_id: UUID, @@ -682,34 +675,30 @@ async def load_conversation_plugin( """Load a plugin from the conversation's registered marketplaces.""" event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.load_plugin(plugin_ref) except (PluginNotFoundError, MarketplaceNotFoundError) as e: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=str(e), - ) + raise NotFound(str(e)) except ( PluginResolutionError, PluginFetchError, FileNotFoundError, ValueError, ) as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) + raise Invalid(str(e)) return Success() @conversation_router.post( "/{conversation_id}/switch_acp_model", - responses={ - 400: {"description": "Agent is not ACP, or provider can't switch models"}, - 404: {"description": "Conversation not found"}, - 504: {"description": "ACP server did not answer the model switch in time"}, - }, + responses=error_responses( + { + Invalid: "Agent is not ACP, or provider can't switch models", + NotFound: "Conversation not found", + UpstreamTimeout: "ACP server did not answer the model switch in time", + } + ), ) async def switch_conversation_acp_model( conversation_id: UUID, @@ -727,32 +716,28 @@ async def switch_conversation_acp_model( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.switch_acp_model(model) except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) + raise Invalid(str(e)) except TimeoutError as e: # The bounded session/set_model round-trip expired. The ACP server is # wedged/slow rather than rejecting the request, so surface a 504 # instead of an opaque 500. - raise HTTPException( - status_code=status.HTTP_504_GATEWAY_TIMEOUT, - detail=str(e), - ) + raise UpstreamTimeout(str(e)) return Success() @conversation_router.post( "/{conversation_id}/switch_acp_effort", - responses={ - 400: {"description": "Agent is not ACP, or the model doesn't offer it"}, - 404: {"description": "Conversation not found"}, - 504: {"description": "ACP server did not answer the switch in time"}, - }, + responses=error_responses( + { + Invalid: "Agent is not ACP, or the model doesn't offer it", + NotFound: "Conversation not found", + UpstreamTimeout: "ACP server did not answer the switch in time", + } + ), ) async def switch_conversation_acp_effort( conversation_id: UUID, @@ -769,18 +754,18 @@ async def switch_conversation_acp_effort( """ event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() try: await event_service.switch_acp_effort(effort) except ValueError as e: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) + raise Invalid(str(e)) except TimeoutError as e: - raise HTTPException(status_code=status.HTTP_504_GATEWAY_TIMEOUT, detail=str(e)) + raise UpstreamTimeout(str(e)) return Success() @conversation_router.patch( - "/{conversation_id}", responses={404: {"description": "Item not found"}} + "/{conversation_id}", responses=error_responses({NotFound: "Item not found"}) ) async def update_conversation( conversation_id: UUID, @@ -793,13 +778,13 @@ async def update_conversation( """ updated = await conversation_service.update_conversation(conversation_id, request) if not updated: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return Success() @conversation_router.post( "/{conversation_id}/ask_agent", - responses={404: {"description": "Item not found"}}, + responses=error_responses({NotFound: "Item not found"}), ) async def ask_agent( conversation_id: UUID, @@ -809,16 +794,18 @@ async def ask_agent( """Ask the agent a simple question without affecting conversation state.""" response = await conversation_service.ask_agent(conversation_id, request.question) if response is None: - raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Conversation not found") + raise NotFound("Conversation not found") return AskAgentResponse(response=response) @conversation_router.post( "/{conversation_id}/condense", - responses={ - 404: {"description": "Item not found"}, - 409: {"description": "The agent has no condenser that handles requests"}, - }, + responses=error_responses( + { + NotFound: "Item not found", + Conflict: "The agent has no condenser that handles requests", + } + ), ) async def condense_conversation( conversation_id: UUID, @@ -828,9 +815,9 @@ async def condense_conversation( try: success = await conversation_service.condense(conversation_id) except CondensationUnavailable as exc: - raise HTTPException(status.HTTP_409_CONFLICT, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc if not success: - raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Conversation not found") + raise NotFound("Conversation not found") return Success() @@ -838,8 +825,12 @@ async def condense_conversation( "/{conversation_id}/fork", responses={ 201: {"description": "Forked conversation created"}, - 404: {"description": "Source conversation not found"}, - 409: {"description": "Fork ID already in use"}, + **error_responses( + { + NotFound: "Source conversation not found", + Conflict: "Fork ID already in use", + } + ), }, status_code=status.HTTP_201_CREATED, ) @@ -866,17 +857,14 @@ async def fork_conversation( ) except ValueError as exc: if "already exists" in str(exc): - raise HTTPException(status.HTTP_409_CONFLICT, detail=str(exc)) from exc + raise Conflict(str(exc)) from exc # An unknown ``from_event_id`` is a bad request against an existing # source conversation, not a missing conversation. if "from_event_id" in str(exc): - raise HTTPException(status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc + raise NotFound(str(exc)) from exc raise if info is None: - raise HTTPException( - status.HTTP_404_NOT_FOUND, - detail="Source conversation not found", - ) + raise NotFound("Source conversation not found") if not include_skills: info = trim_conversation_response_skills(info) return info @@ -886,8 +874,12 @@ async def fork_conversation( "/{conversation_id}/children", responses={ 201: {"description": "Child conversation created"}, - 404: {"description": "Parent conversation not found"}, - 429: {"description": "Server conversation run capacity is full"}, + **error_responses( + { + NotFound: "Parent conversation not found", + RateLimited: "Server conversation run capacity is full", + } + ), }, status_code=status.HTTP_201_CREATED, ) @@ -908,21 +900,15 @@ async def start_child_conversation( conversation_id, request ) except ValueError as exc: - raise HTTPException( - status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc) - ) from exc + raise Unprocessable(str(exc)) from exc if result is None: - raise HTTPException( - status.HTTP_404_NOT_FOUND, detail="Parent conversation not found" - ) + raise NotFound("Parent conversation not found") return result @conversation_router.post( "/{conversation_id}/navigate", - responses={ - 404: {"description": "Conversation or event not found"}, - }, + responses=error_responses({NotFound: "Conversation or event not found"}), ) async def navigate_conversation( conversation_id: UUID, @@ -944,13 +930,10 @@ async def navigate_conversation( # An unknown ``event_id`` against an existing conversation is a 404; # other ValueErrors (e.g. inactive_service) are genuine server errors. if "event_id" in str(exc): - raise HTTPException(status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc + raise NotFound(str(exc)) from exc raise if info is None: - raise HTTPException( - status.HTTP_404_NOT_FOUND, - detail="Conversation not found", - ) + raise NotFound("Conversation not found") if not include_skills: info = trim_conversation_response_skills(info) return info diff --git a/openhands-agent-server/openhands/agent_server/conversation_service.py b/openhands-agent-server/openhands/agent_server/conversation_service.py index 39003f51c78..dcec0d636cd 100644 --- a/openhands-agent-server/openhands/agent_server/conversation_service.py +++ b/openhands-agent-server/openhands/agent_server/conversation_service.py @@ -83,6 +83,7 @@ CredentialBindingError, VersionedCredentialBinding, ) +from openhands.sdk.errors import Conflict from openhands.sdk.event import MessageEvent from openhands.sdk.event.conversation_state import ConversationStateUpdateEvent from openhands.sdk.git.exceptions import GitCommandError, GitRepositoryError @@ -104,8 +105,11 @@ _AUTOMATION_TAG_KEYS = ("automationtrigger", "automationid", "automationrunid") -class CredentialBindingActivationRequired(RuntimeError): - pass +class CredentialBindingActivationRequired(Conflict, RuntimeError): + """A runtime credential binding must be activated first; retry after it.""" + + def __init__(self, detail: str) -> None: + super().__init__(detail, extra={"retryable": True}) def _build_worktree_guidance( diff --git a/openhands-agent-server/openhands/agent_server/credential_binding.py b/openhands-agent-server/openhands/agent_server/credential_binding.py index 3674e52b3eb..cbc6caaa188 100644 --- a/openhands-agent-server/openhands/agent_server/credential_binding.py +++ b/openhands-agent-server/openhands/agent_server/credential_binding.py @@ -5,7 +5,7 @@ from typing import Final from uuid import UUID -from fastapi import APIRouter, HTTPException, Request, Response, status +from fastapi import APIRouter, Request, Response, status from pydantic import BaseModel, ConfigDict, Field, field_validator from openhands.agent_server.event_service import CredentialBindingActivationTooLate @@ -22,6 +22,14 @@ HttpVersionedCredentialBinding, ResolvedCredential, ) +from openhands.sdk.errors import ( + Conflict, + Forbidden, + NotFound, + NotSupported, + Unprocessable, + UpstreamFailed, +) class CredentialBindingActivation(BaseModel): @@ -121,7 +129,7 @@ async def activate_credential_binding( request: Request, ) -> Response: if not supports_file_credential_binding(secret_name): - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() binding = HttpVersionedCredentialBinding( activation.url, activation.headers, @@ -134,36 +142,20 @@ async def activate_credential_binding( binding, ) except CredentialBindingActivationTooLate as exc: - raise HTTPException( - status.HTTP_409_CONFLICT, - "Credential binding activation arrived after ACP initialization", + raise Conflict( + "Credential binding activation arrived after ACP initialization" ) from exc except CredentialConflict as exc: - raise HTTPException( - status.HTTP_409_CONFLICT, - "Credential binding source changed", - ) from exc + raise Conflict("Credential binding source changed") from exc except CredentialAuthorizationRejected as exc: - raise HTTPException( - status.HTTP_403_FORBIDDEN, - "Credential binding authorization was rejected", - ) from exc + raise Forbidden("Credential binding authorization was rejected") from exc except CredentialBindingUnsupported as exc: - raise HTTPException( - status.HTTP_501_NOT_IMPLEMENTED, - "Credential binding source is unsupported", - ) from exc + raise NotSupported("Credential binding source is unsupported") from exc except ( CredentialInvalidResponse, CredentialNeedsReauthentication, ) as exc: - raise HTTPException( - status.HTTP_422_UNPROCESSABLE_ENTITY, - "Credential binding source is invalid", - ) from exc + raise Unprocessable("Credential binding source is invalid") from exc except CredentialBindingError as exc: - raise HTTPException( - status.HTTP_502_BAD_GATEWAY, - "Credential binding source is unavailable", - ) from exc + raise UpstreamFailed("Credential binding source is unavailable") from exc return Response(status_code=status.HTTP_204_NO_CONTENT) diff --git a/openhands-agent-server/openhands/agent_server/dependencies.py b/openhands-agent-server/openhands/agent_server/dependencies.py index d2a69c2474d..f374b8edaa6 100644 --- a/openhands-agent-server/openhands/agent_server/dependencies.py +++ b/openhands-agent-server/openhands/agent_server/dependencies.py @@ -1,6 +1,6 @@ from uuid import UUID -from fastapi import Depends, HTTPException, Request, status +from fastapi import Depends, Request from fastapi.exceptions import RequestValidationError from fastapi.security import APIKeyCookie, APIKeyHeader from pydantic import TypeAdapter, ValidationError @@ -10,6 +10,7 @@ from openhands.agent_server.conversation_registry import ConversationRegistry from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.event_service import EventService +from openhands.sdk.errors import NotFound, OperationFailed, Unauthenticated, Unavailable # Cookie name used to authenticate the workspace static-file routes. @@ -36,7 +37,7 @@ def check_session_api_key( """ config: Config = request.app.state.config if config.session_api_keys and session_api_key not in config.session_api_keys: - raise HTTPException(status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() def check_workspace_session( @@ -60,16 +61,13 @@ def check_workspace_session( for candidate in (header_key, cookie_key): if candidate and candidate in config.session_api_keys: return - raise HTTPException(status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() def get_conversation_service(request: Request) -> ConversationService: service = getattr(request.app.state, "conversation_service", None) if service is None: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Conversation service is not available", - ) + raise Unavailable("Conversation service is not available") return service @@ -92,10 +90,7 @@ async def get_bash_event_service(request: Request) -> BashEventService: for error in exc.errors(include_url=False) ] ) from exc - raise HTTPException( - status.HTTP_500_INTERNAL_SERVER_ERROR, - "Conversation runtime is not bound", - ) + raise OperationFailed("Conversation runtime is not bound") if event_service.bash_event_service is None: event_service.bash_event_service = BashEventService( bash_events_dir=event_service.conversation_dir / "bash_events", @@ -105,10 +100,7 @@ async def get_bash_event_service(request: Request) -> BashEventService: return event_service.bash_event_service service = getattr(request.app.state, "bash_event_service", None) if service is None: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Bash event service is not available", - ) + raise Unavailable("Bash event service is not available") return service @@ -127,8 +119,5 @@ async def get_event_service( else: event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Conversation not found: {conversation_id}", - ) + raise NotFound(f"Conversation not found: {conversation_id}") return event_service diff --git a/openhands-agent-server/openhands/agent_server/docker_runtime/proxy.py b/openhands-agent-server/openhands/agent_server/docker_runtime/proxy.py index 2c23ee5ec4c..c735f266633 100644 --- a/openhands-agent-server/openhands/agent_server/docker_runtime/proxy.py +++ b/openhands-agent-server/openhands/agent_server/docker_runtime/proxy.py @@ -11,12 +11,12 @@ import httpx import websockets -from fastapi import HTTPException, status from starlette.requests import Request from starlette.responses import StreamingResponse from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState from websockets.typing import Subprotocol +from openhands.sdk.errors import Unprocessable, UpstreamFailed from openhands.sdk.logger import get_logger @@ -126,7 +126,7 @@ async def proxy_http( story trivial. """ if request.headers.get("x-expose-secrets"): - raise HTTPException(422, "Runtime secret exposure is unsupported") + raise Unprocessable("Runtime secret exposure is unsupported") url = workspace.host + strip_auth_query(upstream_path) headers = _filter_headers(request.headers) # If the client authenticated via the workspace-session cookie (used by @@ -169,18 +169,12 @@ async def _request_body() -> AsyncIterator[bytes]: if not isinstance(exc, httpx.HTTPError): raise logger.warning("Conversation upstream connection failed") - raise HTTPException( - status_code=status.HTTP_502_BAD_GATEWAY, - detail="Conversation container unreachable", - ) from exc + raise UpstreamFailed("Conversation container unreachable") from exc if reject_redirects and upstream.is_redirect: await stack.aclose() await _invoke_close(on_close) - raise HTTPException( - status_code=status.HTTP_502_BAD_GATEWAY, - detail="Upstream redirect is not allowed", - ) + raise UpstreamFailed("Upstream redirect is not allowed") async def _response_body() -> AsyncIterator[bytes]: try: diff --git a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py index 2fe72a865f1..dff5df6f87e 100644 --- a/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py +++ b/openhands-agent-server/openhands/agent_server/docker_runtime/routers.py @@ -11,7 +11,7 @@ from uuid import UUID, uuid4 import httpx -from fastapi import APIRouter, HTTPException, Query, Request, WebSocket +from fastapi import APIRouter, Query, Request, WebSocket from starlette.responses import JSONResponse, Response, StreamingResponse from openhands.agent_server.dependencies import get_conversation_service @@ -29,7 +29,7 @@ from openhands.agent_server.event_router import require_reactions_enabled from openhands.agent_server.launch import ( forward_to_runtime, - launch_http_exception, + launch_error, launch_source, request_secrets, server_launch_stores, @@ -43,6 +43,17 @@ from openhands.agent_server.persistence import PersistedSettings, get_settings_store from openhands.agent_server.utils import safe_rmtree from openhands.sdk.conversation.request import ConversationContainerOptions +from openhands.sdk.errors import ( + Conflict, + DomainError, + Gone, + Invalid, + NotFound, + NotSupported, + Unavailable, + Unprocessable, + UpstreamFailed, +) from openhands.sdk.git.exceptions import GitCommandError, GitRepositoryError from openhands.sdk.git.utils import run_git_command, validate_git_repository from openhands.sdk.launch import AgentLaunchError, LaunchStoreError, ResolvedLaunch @@ -59,7 +70,7 @@ def get_registry(request: Request) -> DockerConversationRegistry: registry = request.app.state.conversation_registry if not isinstance(registry, DockerConversationRegistry): - raise HTTPException(503, "Docker conversation runtime is unavailable") + raise Unavailable("Docker conversation runtime is unavailable") return registry @@ -67,16 +78,16 @@ async def _container( registry: DockerConversationRegistry, conversation_id: UUID ) -> ConversationContainer: if not registry.provisioning.manifest_path(conversation_id).is_file(): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") try: return await registry.get_or_create(conversation_id) except RuntimeArchivedError as exc: - raise HTTPException( - 410, "Conversation runtime was archived; its history is read-only" + raise Gone( + "Conversation runtime was archived; its history is read-only" ) from exc except Exception as exc: logger.exception("Could not start conversation container %s", conversation_id) - raise HTTPException(502, "Could not start conversation container") from exc + raise UpstreamFailed("Could not start conversation container") from exc def _upstream_path(request: Request, path: str) -> str: @@ -137,9 +148,9 @@ async def start_conversation( try: body = json.loads(await request.body()) except (json.JSONDecodeError, UnicodeDecodeError) as exc: - raise HTTPException(400, "Invalid JSON body") from exc + raise Invalid("Invalid JSON body") from exc if not isinstance(body, dict): - raise HTTPException(422, "Expected a JSON object") + raise Unprocessable("Expected a JSON object") status_code, content, conversation_id = await start_docker_conversation( body, get_registry(request), @@ -161,14 +172,14 @@ async def start_docker_conversation( """Start a Docker conversation through the same path as the REST route.""" body = body.copy() if body.pop("conversation_runtime", None) not in (None, "docker"): - raise HTTPException(422, "This server only runs docker conversations") + raise Unprocessable("This server only runs docker conversations") workspace = body.get("workspace") if workspace is not None and ( not isinstance(workspace, dict) or workspace.get("kind", "LocalWorkspace") != "LocalWorkspace" ): - raise HTTPException(422, "Docker conversations require a local workspace") + raise Unprocessable("Docker conversations require a local workspace") working_dir = (workspace or {}).get("working_dir", "/workspace") host_workspace = None if working_dir == "/workspace" else Path(working_dir) @@ -177,7 +188,7 @@ async def start_docker_conversation( UUID(body["conversation_id"]) if body.get("conversation_id") else uuid4() ) except (TypeError, ValueError) as exc: - raise HTTPException(400, "Invalid conversation_id") from exc + raise Invalid("Invalid conversation_id") from exc body["conversation_id"] = str(conversation_id) body["workspace"] = {"kind": "LocalWorkspace", "working_dir": "/workspace"} @@ -188,7 +199,7 @@ async def start_docker_conversation( registry.conversation_dir(conversation_id).joinpath("meta.json").is_file() ) except ValueError as exc: - raise HTTPException(422, str(exc)) from exc + raise Unprocessable(str(exc)) from exc release = None try: payload, launched, options, worktree = await _prepare_forward( @@ -245,20 +256,20 @@ async def start_docker_conversation( json=forwarded, ) except (ProfileNotFound, AgentLaunchError, LaunchStoreError) as exc: - raise launch_http_exception(exc) from exc + raise launch_error(exc) from exc except ValueError as exc: - raise HTTPException(422, str(exc)) from exc + raise Unprocessable(str(exc)) from exc except httpx.HTTPError as exc: if not existing: await registry.stop(conversation_id) - raise HTTPException( - 502, "Conversation container did not accept the request" + raise UpstreamFailed( + "Conversation container did not accept the request" ) from exc except Exception as exc: if not existing: await registry.stop(conversation_id) logger.exception("Could not create conversation container") - raise HTTPException(502, "Could not create conversation container") from exc + raise UpstreamFailed("Could not create conversation container") from exc finally: if release is not None: release() @@ -325,7 +336,7 @@ async def runtime_info( ) -> ConversationRuntimeInfo: registry = get_registry(request) if not registry.conversation_dir(conversation_id).joinpath("meta.json").is_file(): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") return registry.runtime_info(conversation_id) @@ -334,7 +345,7 @@ async def runtime_credentials(conversation_id: UUID, request: Request) -> JSONRe """Return the key for an authenticated client attached to this runtime.""" registry = get_registry(request) if not registry.conversation_dir(conversation_id).joinpath("meta.json").is_file(): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") identity = registry.provisioning.load(conversation_id) return JSONResponse({"session_api_key": identity.api_key.get_secret_value()}) @@ -344,7 +355,7 @@ async def release_runtime(conversation_id: UUID, request: Request) -> Response: """Stop the container while retaining conversation and workspace state.""" registry = get_registry(request) if not registry.conversation_dir(conversation_id).joinpath("meta.json").is_file(): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") try: await registry.stop(conversation_id) await get_conversation_service(request).refresh_persisted_conversation( @@ -352,7 +363,7 @@ async def release_runtime(conversation_id: UUID, request: Request) -> Response: ) except Exception as exc: logger.exception("Could not release conversation runtime %s", conversation_id) - raise HTTPException(502, "Could not release conversation runtime") from exc + raise UpstreamFailed("Could not release conversation runtime") from exc return Response(status_code=204) @@ -373,10 +384,10 @@ async def reprovision_runtime( async def delete_conversation(conversation_id: UUID, request: Request) -> Response: registry = get_registry(request) if not registry.provisioning.manifest_path(conversation_id).is_file(): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") if not await registry.begin_delete(conversation_id): - raise HTTPException(409, "Conversation deletion is already in progress") + raise Conflict("Conversation deletion is already in progress") # Stopping the container closes its conversation service. The outer server # owns the bind-mounted state and removes it after Docker has unmounted it; @@ -427,7 +438,7 @@ async def proxy_conversation( "switch_llm", "switch_profile", }: - raise HTTPException(501, "This operation is unavailable in Docker runtime mode") + raise NotSupported("This operation is unavailable in Docker runtime mode") registry = get_registry(request) if tail == "reactions" and request.method == "POST": # The runtime's server has no settings of its own to check: the @@ -442,7 +453,7 @@ async def proxy_conversation( try: update = UpdateSecretsRequest.model_validate_json(await request.body()) except ValueError as exc: - raise HTTPException(422, "Invalid secrets payload") from exc + raise Unprocessable("Invalid secrets payload") from exc profile = registry.provisioning.load(conversation_id).launched_agent_profile secrets = update.secrets if profile is not None: @@ -518,8 +529,8 @@ async def _proxy_socket( return try: container = await _container(registry, conversation_id) - except HTTPException as exc: - await websocket.close(code=1008 if exc.status_code == 404 else 1011) + except DomainError as exc: + await websocket.close(code=1008 if isinstance(exc, NotFound) else 1011) return release = registry.acquire_lease(conversation_id) query = strip_auth_query("?" + websocket.url.query).lstrip("?") diff --git a/openhands-agent-server/openhands/agent_server/errors.py b/openhands-agent-server/openhands/agent_server/errors.py new file mode 100644 index 00000000000..a4c22864927 --- /dev/null +++ b/openhands-agent-server/openhands/agent_server/errors.py @@ -0,0 +1,114 @@ +"""HTTP mapping for the SDK domain errors. + +``ERROR_STATUS`` is the only place a domain error category gets an HTTP +status. The exception handler in ``api.py`` resolves raised errors through it, +and routes document their error responses with :func:`error_responses`, which +reads the same table. Routers and services raise ``openhands.sdk.errors`` +categories; they never build ``HTTPException`` (a guard test enforces it). +""" + +from collections.abc import Mapping +from typing import Any + +from fastapi import status + +from openhands.sdk.errors import ( + Busy, + Conflict, + DomainError, + ErrorDetail, + Forbidden, + Gone, + Invalid, + Misdirected, + NotFound, + NotSupported, + OperationFailed, + RateLimited, + Unauthenticated, + Unavailable, + Unprocessable, + UpstreamFailed, + UpstreamTimeout, +) + + +ERROR_STATUS: Mapping[type[DomainError], int] = { + Invalid: status.HTTP_400_BAD_REQUEST, + Unauthenticated: status.HTTP_401_UNAUTHORIZED, + Forbidden: status.HTTP_403_FORBIDDEN, + NotFound: status.HTTP_404_NOT_FOUND, + Conflict: status.HTTP_409_CONFLICT, + Gone: status.HTTP_410_GONE, + Misdirected: status.HTTP_421_MISDIRECTED_REQUEST, + Unprocessable: status.HTTP_422_UNPROCESSABLE_CONTENT, + RateLimited: status.HTTP_429_TOO_MANY_REQUESTS, + OperationFailed: status.HTTP_500_INTERNAL_SERVER_ERROR, + NotSupported: status.HTTP_501_NOT_IMPLEMENTED, + UpstreamFailed: status.HTTP_502_BAD_GATEWAY, + Busy: status.HTTP_503_SERVICE_UNAVAILABLE, + Unavailable: status.HTTP_503_SERVICE_UNAVAILABLE, + UpstreamTimeout: status.HTTP_504_GATEWAY_TIMEOUT, +} + +# Inverse lookup for errors that arrive carrying a status (a provider error +# with ``status_code``). Where two categories share a status, the first one +# listed in ``ERROR_STATUS`` wins (503 -> Busy). +_CATEGORY_FOR_STATUS: Mapping[int, type[DomainError]] = { + code: category for category, code in reversed(ERROR_STATUS.items()) +} + + +class ForwardedStatus(DomainError): + """Relay the status another HTTP server chose (a proxied runtime's reply). + + Only for forwarding: the status is not ours to pick, so it cannot go + through a category. Everything raised by this server uses a category. + """ + + def __init__( + self, + status_code: int, + detail: ErrorDetail, + *, + retry_after: str | None = None, + ) -> None: + super().__init__(detail, retry_after=retry_after) + self.status_code = status_code + + +def _category_status(error_type: type[DomainError]) -> int: + for cls in error_type.__mro__: + if cls in ERROR_STATUS: + return ERROR_STATUS[cls] + return status.HTTP_500_INTERNAL_SERVER_ERROR + + +def status_for(exc: DomainError) -> int: + """The HTTP status for ``exc``: its nearest category in ``ERROR_STATUS``.""" + if isinstance(exc, ForwardedStatus): + return exc.status_code + return _category_status(type(exc)) + + +def error_for_status( + status_code: int, detail: ErrorDetail, *, retry_after: str | None = None +) -> DomainError: + """Build the category error for a status carried by a lower-level error. + + A status no category maps to is relayed unchanged (``ForwardedStatus``). + """ + category = _CATEGORY_FOR_STATUS.get(status_code) + if category is None: + return ForwardedStatus(status_code, detail, retry_after=retry_after) + return category(detail, retry_after=retry_after) + + +def error_responses( + descriptions: Mapping[type[DomainError], str], +) -> dict[int | str, dict[str, Any]]: + """``responses=`` for a route, keyed by the statuses in ``ERROR_STATUS``.""" + return { + _category_status(error_type): {"description": description} + for error_type, description in descriptions.items() + } diff --git a/openhands-agent-server/openhands/agent_server/event_router.py b/openhands-agent-server/openhands/agent_server/event_router.py index dab297962e7..ff8a2ff3fa7 100644 --- a/openhands-agent-server/openhands/agent_server/event_router.py +++ b/openhands-agent-server/openhands/agent_server/event_router.py @@ -12,9 +12,7 @@ from fastapi import ( APIRouter, Depends, - HTTPException, Query, - status, ) from starlette.requests import Request from starlette.responses import JSONResponse @@ -26,6 +24,7 @@ get_conversation_service, get_event_service, ) +from openhands.agent_server.errors import error_responses from openhands.agent_server.event_service import EventService from openhands.agent_server.experimental_features import ( host_experimental_features, @@ -42,6 +41,13 @@ from openhands.agent_server.persistence import PersistedSettings, get_settings_store from openhands.sdk import Message from openhands.sdk.conversation.state import ConversationExecutionStatus +from openhands.sdk.errors import ( + Conflict, + Invalid, + NotFound, + RateLimited, + UpstreamTimeout, +) from openhands.sdk.event import Event, ReactionEvent @@ -85,7 +91,7 @@ def normalize_datetime_to_server_timezone(dt: datetime) -> datetime: @event_read_router.get( - "/search", responses={404: {"description": "Conversation not found"}} + "/search", responses=error_responses({NotFound: "Conversation not found"}) ) async def search_conversation_events( page_id: Annotated[ @@ -159,7 +165,7 @@ async def search_conversation_events( @event_read_router.get( - "/count", responses={404: {"description": "Conversation not found"}} + "/count", responses=error_responses({NotFound: "Conversation not found"}) ) async def count_conversation_events( kind: Annotated[ @@ -205,7 +211,7 @@ async def count_conversation_events( @event_read_router.get( - "/{event_id}", responses={404: {"description": "Item not found"}} + "/{event_id}", responses=error_responses({NotFound: "Item not found"}) ) async def get_conversation_event( event_id: str, @@ -214,7 +220,7 @@ async def get_conversation_event( """Get a local event given an id""" event = await event_service.get_event(event_id) if event is None: - raise HTTPException(status.HTTP_404_NOT_FOUND) + raise NotFound() return event @@ -231,7 +237,9 @@ async def batch_get_conversation_events( @event_write_router.post( "", - responses={429: {"description": "Message saved but server run capacity is full"}}, + responses=error_responses( + {RateLimited: "Message saved but server run capacity is full"} + ), ) async def send_message( request: SendMessageRequest, @@ -283,7 +291,7 @@ async def run_gateway_message( timeout=deadline - time.monotonic(), ) except TimeoutError as exc: - raise HTTPException(504, "Agent run timed out") from exc + raise UpstreamTimeout("Agent run timed out") from exc try: return await _run_gateway_message(request, event_service, deadline) finally: @@ -300,14 +308,14 @@ async def _run_gateway_message( timeout=max(0, deadline - time.monotonic()) ) except TimeoutError as exc: - raise HTTPException(504, "Agent run timed out") from exc + raise UpstreamTimeout("Agent run timed out") from exc state_before = await event_service.get_state() min_event_count = len(state_before.events) + 1 usage_before = state_before.stats.get_combined_metrics().accumulated_token_usage run_slot = await event_service.reserve_run_slot() try: if time.monotonic() >= deadline: - raise HTTPException(504, "Agent run timed out") + raise UpstreamTimeout("Agent run timed out") await event_service.send_message( request.create_message(), run=True, run_slot=run_slot ) @@ -317,11 +325,11 @@ async def _run_gateway_message( while True: remaining = deadline - time.monotonic() if remaining <= 0: - raise HTTPException(504, "Agent run timed out") + raise UpstreamTimeout("Agent run timed out") try: run_status = await event_service.wait_for_run_completion(timeout=remaining) except TimeoutError as exc: - raise HTTPException(504, "Agent run timed out") from exc + raise UpstreamTimeout("Agent run timed out") from exc state = await event_service.get_state() if len(state.events) > min_event_count and ( run_status.is_terminal() @@ -345,10 +353,12 @@ async def _run_gateway_message( @event_write_router.post( "/respond_to_confirmation", - responses={ - 404: {"description": "Item not found"}, - 429: {"description": "Server conversation run capacity is full"}, - }, + responses=error_responses( + { + NotFound: "Item not found", + RateLimited: "Server conversation run capacity is full", + } + ), ) async def respond_to_confirmation( request: ConfirmationResponseRequest, @@ -371,24 +381,20 @@ async def require_reactions_enabled(config: Config) -> None: lambda: get_settings_store(config).load() or PersistedSettings() ) except (PermissionError, OSError): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Cannot read the settings file to check the feature flag", - ) + raise Conflict("Cannot read the settings file to check the feature flag") if not is_enabled(settings.experimental_features, "conversation_reactions"): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Conversation reactions are turned off", - ) + raise Conflict("Conversation reactions are turned off") @reaction_router.post( "", - responses={ - 400: {"description": "There is no such message to react to"}, - 404: {"description": "Item not found"}, - 409: {"description": "Conversation reactions are turned off"}, - }, + responses=error_responses( + { + Invalid: "There is no such message to react to", + NotFound: "Item not found", + Conflict: "Conversation reactions are turned off", + } + ), ) async def react_to_message( request: ReactionRequest, @@ -416,7 +422,7 @@ async def react_to_message( except ValueError as exc: if str(exc) == "inactive_service": raise - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) + raise Invalid(str(exc)) event_router = APIRouter() diff --git a/openhands-agent-server/openhands/agent_server/event_service.py b/openhands-agent-server/openhands/agent_server/event_service.py index 39b5487e1bb..b4f545e991b 100644 --- a/openhands-agent-server/openhands/agent_server/event_service.py +++ b/openhands-agent-server/openhands/agent_server/event_service.py @@ -72,6 +72,7 @@ HttpVersionedCredentialBinding, VersionedCredentialBinding, ) +from openhands.sdk.errors import RateLimited from openhands.sdk.event import ( AgentErrorEvent, ObservationBaseEvent, @@ -104,7 +105,7 @@ logger = get_logger(__name__) -class ConversationRunLimitExceeded(RuntimeError): +class ConversationRunLimitExceeded(RateLimited, RuntimeError): """The server has no capacity to start another conversation run.""" diff --git a/openhands-agent-server/openhands/agent_server/experimental_features_router.py b/openhands-agent-server/openhands/agent_server/experimental_features_router.py index b88b0cd167a..d6eb44cae1b 100644 --- a/openhands-agent-server/openhands/agent_server/experimental_features_router.py +++ b/openhands-agent-server/openhands/agent_server/experimental_features_router.py @@ -2,9 +2,10 @@ import asyncio -from fastapi import APIRouter, HTTPException, Request, status +from fastapi import APIRouter, Request from openhands.agent_server._secrets_exposure import get_config +from openhands.agent_server.errors import error_responses from openhands.agent_server.experimental_features import ( ExperimentalFeature, ExperimentalFeatureUpdate, @@ -13,6 +14,7 @@ is_enabled, ) from openhands.agent_server.persistence import PersistedSettings, get_settings_store +from openhands.sdk.errors import Conflict, NotFound experimental_features_router = APIRouter( @@ -31,10 +33,12 @@ async def list_experimental_features(request: Request) -> list[ExperimentalFeatu @experimental_features_router.patch( "/{key}", response_model=ExperimentalFeature, - responses={ - 404: {"description": "There is no feature with this key"}, - 409: {"description": "The settings file cannot be read"}, - }, + responses=error_responses( + { + NotFound: "There is no feature with this key", + Conflict: "The settings file cannot be read", + } + ), ) def update_experimental_feature( request: Request, key: str, payload: ExperimentalFeatureUpdate @@ -42,10 +46,7 @@ def update_experimental_feature( """Turn a feature on or off.""" feature = find_experimental_feature(key) if feature is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Unknown experimental feature: {key}", - ) + raise NotFound(f"Unknown experimental feature: {key}") def apply(settings: PersistedSettings) -> PersistedSettings: settings.experimental_features = { @@ -58,10 +59,7 @@ def apply(settings: PersistedSettings) -> PersistedSettings: try: settings = store.update(apply) except RuntimeError: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Settings file is corrupted or encrypted with a different key", - ) + raise Conflict("Settings file is corrupted or encrypted with a different key") return ExperimentalFeature( key=feature.key, label=feature.label, diff --git a/openhands-agent-server/openhands/agent_server/file_router.py b/openhands-agent-server/openhands/agent_server/file_router.py index 65431e8afb8..00d076b29cb 100644 --- a/openhands-agent-server/openhands/agent_server/file_router.py +++ b/openhands-agent-server/openhands/agent_server/file_router.py @@ -20,11 +20,9 @@ from fastapi import ( APIRouter, File, - HTTPException, Query, Request, UploadFile, - status, ) from fastapi.responses import FileResponse from pydantic import BaseModel @@ -38,6 +36,13 @@ from openhands.agent_server.config import Config from openhands.agent_server.models import FileUploadResult, Success from openhands.agent_server.server_details_router import update_last_execution_time +from openhands.sdk.errors import ( + DomainError, + Forbidden, + Invalid, + NotFound, + OperationFailed, +) from openhands.sdk.git.exceptions import GitCommandError, GitRepositoryError from openhands.sdk.git.utils import ( GIT_EMPTY_TREE_HASH, @@ -94,10 +99,7 @@ async def _upload_file(path: str, file: UploadFile) -> FileUploadResult: try: target_path = Path(path) if not target_path.is_absolute(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path must be absolute", - ) + raise Invalid("Path must be absolute") # Ensure target directory exists target_path.parent.mkdir(parents=True, exist_ok=True) @@ -115,28 +117,19 @@ async def _upload_file(path: str, file: UploadFile) -> FileUploadResult: logger.info(f"Uploaded file to {target_path}") return FileUploadResult(file_size=file_size) - except HTTPException: + except DomainError: raise except IsADirectoryError: # The target itself is an existing directory: the caller's path is # wrong, not a server fault (create_directory answers 400 likewise). - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path is a directory", - ) + raise Invalid("Path is a directory") except (FileExistsError, NotADirectoryError): # mkdir(parents=True) raises FileExistsError when the direct parent is # a file and NotADirectoryError when a component further up is one. - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="A parent of the path is not a directory", - ) + raise Invalid("A parent of the path is not a directory") except Exception as e: logger.error(f"Failed to upload file: {e}") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to upload file: {str(e)}", - ) + raise OperationFailed(f"Failed to upload file: {str(e)}") async def _download_file(path: str) -> FileResponse: @@ -146,20 +139,13 @@ async def _download_file(path: str) -> FileResponse: try: target_path = Path(path) if not target_path.is_absolute(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path must be absolute", - ) + raise Invalid("Path must be absolute") if not target_path.exists(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, detail="File not found" - ) + raise NotFound("File not found") if not target_path.is_file(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, detail="Path is not a file" - ) + raise Invalid("Path is not a file") return FileResponse( path=target_path, @@ -167,14 +153,11 @@ async def _download_file(path: str) -> FileResponse: media_type="application/octet-stream", ) - except HTTPException: + except DomainError: raise except Exception as e: logger.error(f"Failed to download file: {e}") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to download file: {str(e)}", - ) + raise OperationFailed(f"Failed to download file: {str(e)}") _TRAJECTORY_EXCLUDED_TOP_DIRS = frozenset({"acp"}) @@ -773,10 +756,7 @@ async def create_directory( target_path = Path(path) if not target_path.is_absolute(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path must be absolute", - ) + raise Invalid("Path must be absolute") try: await asyncio.to_thread(lambda: target_path.mkdir(parents=True, exist_ok=True)) @@ -784,21 +764,12 @@ async def create_directory( # mkdir(exist_ok=True) still raises when the final component exists as a # non-directory; NotADirectoryError covers a parent component being a # file. Both are the caller's path being wrong, not a server fault. - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path exists and is not a directory", - ) + raise Invalid("Path exists and is not a directory") except PermissionError as e: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Permission denied: {e}", - ) + raise Forbidden(f"Permission denied: {e}") except Exception as e: logger.error(f"Failed to create directory {path}: {e}") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to create directory: {str(e)}", - ) + raise OperationFailed(f"Failed to create directory: {str(e)}") logger.info(f"Created directory {target_path}") return Success() @@ -908,20 +879,11 @@ async def search_subdirs( target = Path(path) if not target.is_absolute(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path must be absolute", - ) + raise Invalid("Path must be absolute") if not target.exists(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Directory not found", - ) + raise NotFound("Directory not found") if not target.is_dir(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path is not a directory", - ) + raise Invalid("Path is not a directory") entries: list[SubdirectoryEntry] = [] try: @@ -938,10 +900,7 @@ async def search_subdirs( SubdirectoryEntry(name=entry.name, path=str(target / entry.name)) ) except PermissionError as e: - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail=f"Permission denied: {e}", - ) + raise Forbidden(f"Permission denied: {e}") # Break case-insensitive ties by the exact name so that names differing # only by case ("Foo", "foo") have a stable order and distinct cursors. @@ -981,10 +940,7 @@ async def download_trajectory( conversation_dir = config.conversations_path / conversation_id.hex if not conversation_dir.is_dir(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Conversation not found", - ) + raise NotFound("Conversation not found") await asyncio.to_thread( _remove_stale_trajectory_temp_zips, config.conversations_path @@ -1097,25 +1053,13 @@ async def archive_directory( target = Path(path) if not target.is_absolute(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path must be absolute", - ) + raise Invalid("Path must be absolute") if not target.exists(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Directory not found", - ) + raise NotFound("Directory not found") if not target.is_dir(): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path is not a directory", - ) + raise Invalid("Path is not a directory") if base_ref is not None and base_ref.startswith("-"): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="base_ref must not start with '-'", - ) + raise Invalid("base_ref must not start with '-'") target = target.resolve() effective_excludes = ( @@ -1157,29 +1101,17 @@ async def archive_directory( ) except GitRepositoryError as e: output_path.unlink(missing_ok=True) - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Not a git repository: {e}", - ) + raise Invalid(f"Not a git repository: {e}") except ValueError as e: output_path.unlink(missing_ok=True) - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) + raise Invalid(str(e)) except GitCommandError as e: output_path.unlink(missing_ok=True) - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to generate git delta: {e}", - ) + raise OperationFailed(f"Failed to generate git delta: {e}") except Exception as e: output_path.unlink(missing_ok=True) logger.error(f"Failed to archive {target}: {e}") - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Failed to archive directory: {str(e)}", - ) + raise OperationFailed(f"Failed to archive directory: {str(e)}") # Repo identity (remote / branch / HEAD) applies to both formats so a # tar.gz snapshot is self-describing too; base_commit/base_ref are diff --git a/openhands-agent-server/openhands/agent_server/git_router.py b/openhands-agent-server/openhands/agent_server/git_router.py index 497a5fb2711..13e86a00d9b 100644 --- a/openhands-agent-server/openhands/agent_server/git_router.py +++ b/openhands-agent-server/openhands/agent_server/git_router.py @@ -6,9 +6,10 @@ from pathlib import Path from typing import Annotated -from fastapi import APIRouter, HTTPException, Path as PathParam, Query, Request +from fastapi import APIRouter, Path as PathParam, Query, Request from openhands.agent_server._secrets_exposure import get_config +from openhands.agent_server.errors import error_for_status, error_responses from openhands.agent_server.git_provider_service import ( GitProviderAPIError, MissingGitProviderTokenError, @@ -17,6 +18,7 @@ search_provider_repositories, ) from openhands.agent_server.server_details_router import update_last_execution_time +from openhands.sdk.errors import Conflict, Invalid, RateLimited, Unprocessable from openhands.sdk.git.exceptions import GitError, GitRepositoryError from openhands.sdk.git.git_changes import get_git_changes from openhands.sdk.git.git_commits import ( @@ -60,7 +62,7 @@ def _repo_path(path: str) -> Path: """Reject an empty path, which Path() would turn into the server's own cwd.""" if not path: - raise HTTPException(status_code=400, detail="'path' must not be empty") + raise Invalid("'path' must not be empty") return Path(path) @@ -160,9 +162,9 @@ async def git_repositories_search( page_id=page_id, ) except UnsupportedGitProviderError as e: - raise HTTPException(status_code=400, detail=str(e)) from e + raise Invalid(str(e)) from e except GitProviderAPIError as e: - raise HTTPException(status_code=e.status_code, detail=str(e)) from e + raise error_for_status(e.status_code, str(e)) from e # One path segment of a GitHub owner or repository name. "." and ".." also @@ -176,16 +178,14 @@ async def git_repositories_search( @git_router.get( "/repositories/{owner}/{repo}/pull-requests/{number}", response_model=GitPullRequestStatus, - responses={ - 409: { - "description": ( - "No token is configured for the provider. The detail is " - f'{{"code": "{MISSING_PROVIDER_TOKEN_CODE}", "message": ...}}, ' - "so a client can hide the status instead of showing an error." - ) - }, - 429: {"description": "The provider's rate limit was reached."}, - }, + responses=error_responses( + { + Conflict: "No token is configured for the provider. The detail is " + f'{{"code": "{MISSING_PROVIDER_TOKEN_CODE}", "message": ...}}, ' + "so a client can hide the status instead of showing an error.", + RateLimited: "The provider's rate limit was reached.", + } + ), ) async def git_pull_request_status( request: Request, @@ -198,25 +198,17 @@ async def git_pull_request_status( ) -> GitPullRequestStatus: """Read a pull request's state and the combined CI result of its head commit.""" if owner in _DOT_SEGMENTS or repo in _DOT_SEGMENTS: - raise HTTPException( - status_code=422, detail="'owner' and 'repo' must not be '.' or '..'" - ) + raise Unprocessable("'owner' and 'repo' must not be '.' or '..'") try: return await get_provider_pull_request( get_config(request), provider, owner, repo, number ) except UnsupportedGitProviderError as e: - raise HTTPException(status_code=400, detail=str(e)) from e + raise Invalid(str(e)) from e except MissingGitProviderTokenError as e: - raise HTTPException( - status_code=409, - detail={"code": MISSING_PROVIDER_TOKEN_CODE, "message": str(e)}, - ) from e + raise Conflict({"code": MISSING_PROVIDER_TOKEN_CODE, "message": str(e)}) from e except GitProviderAPIError as e: - headers = {"Retry-After": e.retry_after} if e.retry_after else None - raise HTTPException( - status_code=e.status_code, detail=str(e), headers=headers - ) from e + raise error_for_status(e.status_code, str(e), retry_after=e.retry_after) from e @git_router.get("/changes") @@ -233,7 +225,7 @@ async def git_changes_query( # Any remaining GitError subclass (e.g. GitCommandError) surfaces as # 400 so the client can show an actionable error instead of an # opaque 500. - raise HTTPException(status_code=400, detail=str(e)) + raise Invalid(str(e)) @git_router.get("/diff") @@ -247,9 +239,7 @@ async def git_diff_query( ) -> GitDiff: """Get git diff using query parameter (preferred method).""" if ref is not None and commit is not None: - raise HTTPException( - status_code=400, detail="'ref' and 'commit' are mutually exclusive" - ) + raise Invalid("'ref' and 'commit' are mutually exclusive") try: if commit is not None: return await _get_commit_file_diff(path, commit) @@ -259,7 +249,7 @@ async def git_diff_query( # empty diff). Any remaining GitError subclass (e.g. GitCommandError, # GitPathError) surfaces as 400 so the client can show an actionable # error instead of an opaque 500. - raise HTTPException(status_code=400, detail=str(e)) + raise Invalid(str(e)) @git_router.get("/commits") @@ -274,7 +264,7 @@ async def git_commits_query( except GitError as e: # GitRepositoryError is already handled in the helper (returns an # empty page). Any remaining GitError subclass surfaces as 400. - raise HTTPException(status_code=400, detail=str(e)) + raise Invalid(str(e)) @git_router.get("/commits/{sha}/changes") @@ -289,4 +279,4 @@ async def git_commit_changes_query( except GitError as e: # GitRepositoryError is already handled in the helper (returns []). # An unknown/unresolvable sha raises GitCommandError -> 400. - raise HTTPException(status_code=400, detail=str(e)) + raise Invalid(str(e)) diff --git a/openhands-agent-server/openhands/agent_server/init_router.py b/openhands-agent-server/openhands/agent_server/init_router.py index e8636233e1b..3666b464461 100644 --- a/openhands-agent-server/openhands/agent_server/init_router.py +++ b/openhands-agent-server/openhands/agent_server/init_router.py @@ -21,7 +21,6 @@ APIRouter, Depends, FastAPI, - HTTPException, Request, WebSocketException, status, @@ -51,6 +50,14 @@ shutdown_telemetry_sink, ) from openhands.agent_server.vscode_service import get_vscode_service +from openhands.sdk.errors import ( + Invalid, + NotFound, + OperationFailed, + Unauthenticated, + Unavailable, + Unprocessable, +) from openhands.sdk.logger import get_logger from openhands.sdk.observability import maybe_init_laminar @@ -252,17 +259,11 @@ def snapshot(self) -> InitStatus: async def initialize(self, req: InitRequest) -> InitStatus: async with self._lock: if self._state != "dormant": - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"server already in state: {self._state}", - ) + raise Invalid(f"server already in state: {self._state}") if req.session_api_keys is not None and any( not key for key in req.session_api_keys ): - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="session_api_keys cannot contain empty keys", - ) + raise Unprocessable("session_api_keys cannot contain empty keys") self._state = "initializing" self._error = None try: @@ -347,10 +348,7 @@ async def initialize(self, req: InitRequest) -> InitStatus: self._restore_session_api_key_env() self._error = f"{type(exc).__name__}: {exc}" self._state = "dormant" - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=self._error, - ) from exc + raise OperationFailed(self._error) from exc async def teardown(self) -> None: """Tear down the conversation service if /api/init succeeded. @@ -384,12 +382,9 @@ def _restore_session_api_key_env(self) -> None: def get_init_service(request: Request) -> InitService: init_service = getattr(request.app.state, "init_service", None) if init_service is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=( - "server is not running with deferred_init=True; the /api/init " - "endpoint is not available" - ), + raise NotFound( + "server is not running with deferred_init=True; the /api/init " + "endpoint is not available" ) return init_service @@ -407,12 +402,12 @@ def check_init_api_key( if config is not None and config.secret_key_was_blank: # A blank key was configured but no usable key remains → fail # closed, since no client can present a blank key. - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() # No key configured → endpoint is open. Acceptable for dev. return expected = config.secret_key.get_secret_value() if init_api_key != expected: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() def require_initialized(connection: HTTPConnection) -> None: @@ -434,7 +429,7 @@ def require_initialized(connection: HTTPConnection) -> None: ) if connection.scope["type"] == "websocket": raise WebSocketException(code=status.WS_1013_TRY_AGAIN_LATER, reason=reason) - raise HTTPException(status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail=reason) + raise Unavailable(reason) init_router = APIRouter(prefix="/init", tags=["Init"]) diff --git a/openhands-agent-server/openhands/agent_server/launch.py b/openhands-agent-server/openhands/agent_server/launch.py index 1e54c8794e1..cb0adbc7866 100644 --- a/openhands-agent-server/openhands/agent_server/launch.py +++ b/openhands-agent-server/openhands/agent_server/launch.py @@ -11,7 +11,6 @@ from collections.abc import Callable, Mapping from typing import Any -from fastapi import HTTPException, status from pydantic import TypeAdapter from openhands.agent_server.config import ( @@ -33,6 +32,13 @@ from openhands.sdk.agent.base import AgentBase from openhands.sdk.context.agent_context import AgentContext from openhands.sdk.conversation.request import StartConversationRequest +from openhands.sdk.errors import ( + Busy, + DomainError, + NotFound, + OperationFailed, + Unprocessable, +) from openhands.sdk.launch import ( AgentLaunchError, LaunchRuntime, @@ -195,17 +201,15 @@ def _decryption_context( LaunchFailure = ProfileNotFound | AgentLaunchError | LaunchStoreError -def launch_http_exception(exc: LaunchFailure) -> HTTPException: +def launch_error(exc: LaunchFailure) -> DomainError: + """The domain error a route raises for a failed launch.""" if isinstance(exc, ProfileNotFound): - return HTTPException(status.HTTP_404_NOT_FOUND, str(exc)) + return NotFound(str(exc)) if isinstance(exc, AgentLaunchError): - return HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, exc.to_detail()) - code = ( - status.HTTP_503_SERVICE_UNAVAILABLE - if exc.retryable - else status.HTTP_500_INTERNAL_SERVER_ERROR - ) - return HTTPException(code, str(exc)) + return Unprocessable(exc.to_detail()) + if exc.retryable: + return Busy(str(exc)) + return OperationFailed(str(exc)) def scoped_secrets( diff --git a/openhands-agent-server/openhands/agent_server/llm_router.py b/openhands-agent-server/openhands/agent_server/llm_router.py index 5ca4ca1ea3e..4702919f68b 100644 --- a/openhands-agent-server/openhands/agent_server/llm_router.py +++ b/openhands-agent-server/openhands/agent_server/llm_router.py @@ -10,9 +10,10 @@ from dataclasses import dataclass import httpx -from fastapi import APIRouter, HTTPException, Query, status +from fastapi import APIRouter, Query from pydantic import BaseModel, Field +from openhands.sdk.errors import NotFound, UpstreamFailed, UpstreamTimeout from openhands.sdk.llm.auth.openai import ( DEVICE_CODE_TIMEOUT_SECONDS, OPENAI_CODEX_MODELS, @@ -113,21 +114,12 @@ def _openai_upstream_errors() -> Iterator[None]: try: yield except httpx.TimeoutException as exc: - raise HTTPException( - status_code=status.HTTP_504_GATEWAY_TIMEOUT, - detail="OpenAI did not answer in time", - ) from exc + raise UpstreamTimeout("OpenAI did not answer in time") from exc except httpx.HTTPError as exc: - raise HTTPException( - status_code=status.HTTP_502_BAD_GATEWAY, - detail="OpenAI is unreachable", - ) from exc + raise UpstreamFailed("OpenAI is unreachable") from exc except RuntimeError as exc: # The SDK raises RuntimeError for a non-2xx or malformed OpenAI answer. - raise HTTPException( - status_code=status.HTTP_502_BAD_GATEWAY, - detail=f"OpenAI device login failed: {exc}", - ) from exc + raise UpstreamFailed(f"OpenAI device login failed: {exc}") from exc def _drop_expired_device_logins() -> None: @@ -256,10 +248,7 @@ async def poll_openai_subscription_device_login( if pending is None: if request.device_code in _IN_FLIGHT_OPENAI_DEVICE_LOGINS: return SubscriptionStatusResponse(connected=False) - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Subscription device login not found or expired", - ) + raise NotFound("Subscription device login not found or expired") _IN_FLIGHT_OPENAI_DEVICE_LOGINS.add(request.device_code) auth = _get_openai_subscription_auth() diff --git a/openhands-agent-server/openhands/agent_server/mcp_router.py b/openhands-agent-server/openhands/agent_server/mcp_router.py index ac5195361de..8cfeaa4f386 100644 --- a/openhands-agent-server/openhands/agent_server/mcp_router.py +++ b/openhands-agent-server/openhands/agent_server/mcp_router.py @@ -35,7 +35,7 @@ import httpx import mcp.types -from fastapi import APIRouter, HTTPException, Request +from fastapi import APIRouter, Request from fastmcp.client.auth.oauth import ClientNotFoundError, OAuth from pydantic import BaseModel, Field, ValidationError, model_validator @@ -44,6 +44,7 @@ InMemoryMCPOAuthTokenStore, ) from openhands.agent_server.persistence import get_secrets_store +from openhands.sdk.errors import Conflict, Invalid, NotFound from openhands.sdk.logger import get_logger from openhands.sdk.mcp import create_mcp_tools from openhands.sdk.mcp.client import MCPClient @@ -870,7 +871,7 @@ def _get_oauth_job(job_id: str) -> _MCPOAuthProbeJob: _sweep_oauth_probe_jobs_locked() job = _oauth_probe_jobs.get(job_id) if job is None: - raise HTTPException(status_code=404, detail="MCP OAuth job not found") + raise NotFound("MCP OAuth job not found") return job @@ -885,10 +886,7 @@ async def start_mcp_oauth( ) -> MCPOAuthStartResponse: """Start OAuth for a candidate MCP server and return the authorization URL.""" if request.resolved_server.oauth_auth is None: - raise HTTPException( - status_code=400, - detail="MCP OAuth start requires auth.strategy='oauth2'", - ) + raise Invalid("MCP OAuth start requires auth.strategy='oauth2'") job = _MCPOAuthProbeJob(request=request, cipher=get_cipher(http_request)) _register_oauth_job(job) @@ -949,30 +947,26 @@ def _validate_callback_url(callback_url: str, job: _MCPOAuthProbeJob) -> None: try: parsed = urlparse(callback_url) except ValueError: # e.g. an unclosed IPv6 bracket - raise HTTPException( - status_code=400, detail="Invalid OAuth callback URL" - ) from None + raise Invalid("Invalid OAuth callback URL") from None if parsed.scheme != "http" or parsed.hostname not in { "localhost", "127.0.0.1", "::1", }: - raise HTTPException(status_code=400, detail="Invalid OAuth callback URL") + raise Invalid("Invalid OAuth callback URL") with job.lock: expected = job.callback_url if expected is None: - raise HTTPException(status_code=409, detail="OAuth callback is not ready") + raise Conflict("OAuth callback is not ready") expected_parsed = urlparse(expected) try: port = parsed.port except ValueError: # out of range or not a number - raise HTTPException( - status_code=400, detail="Unexpected OAuth callback URL" - ) from None + raise Invalid("Unexpected OAuth callback URL") from None if port != expected_parsed.port or parsed.path != expected_parsed.path: - raise HTTPException(status_code=400, detail="Unexpected OAuth callback URL") + raise Invalid("Unexpected OAuth callback URL") @mcp_router.post( @@ -997,9 +991,7 @@ async def submit_mcp_oauth_callback( # The probe may have finished while we were forwarding. if job.done.is_set(): return job.to_status_response() - raise HTTPException( - status_code=409, detail="OAuth callback server is not listening" - ) from exc + raise Conflict("OAuth callback server is not listening") from exc if response.status_code >= 400: return MCPOAuthStatusResponse( ok=False, diff --git a/openhands-agent-server/openhands/agent_server/meta_profiles_router.py b/openhands-agent-server/openhands/agent_server/meta_profiles_router.py index 25d35910a55..bcfd5cb0d3b 100644 --- a/openhands-agent-server/openhands/agent_server/meta_profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/meta_profiles_router.py @@ -4,11 +4,9 @@ documents persisted via :class:`MetaProfileStore`. """ -from collections.abc import Iterator -from contextlib import contextmanager from typing import Annotated -from fastapi import APIRouter, HTTPException, Path, Request, status +from fastapi import APIRouter, Path, Request, status from pydantic import AfterValidator, BaseModel from openhands.agent_server._secrets_exposure import get_config @@ -16,6 +14,11 @@ PersistedSettings, get_settings_store, ) +from openhands.sdk.errors import ( + Conflict, + NotFound, + OperationFailed, +) from openhands.sdk.llm.llm_profile_store import PROFILE_NAME_PATTERN from openhands.sdk.llm.meta_profile_store import ( MetaProfile, @@ -94,26 +97,6 @@ class ActivateMetaProfileResponse(BaseModel): activation).""" -@contextmanager -def _store_errors() -> Iterator[None]: - """Map ``MetaProfileStore`` errors to HTTP responses.""" - try: - yield - except TimeoutError: - # save()/delete() can raise TimeoutError from the file lock under - # contention; surface a retryable 503 instead of a generic 500 - # (mirrors profiles_router._store_errors()). - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Meta-profile store is busy. Please retry.", - ) - except ValueError as e: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=str(e), - ) - - def _set_active_meta_profile_if_matches( request: Request, old_name: str, new_name: str | None ) -> bool: @@ -149,8 +132,7 @@ def list_meta_profiles(request: Request) -> MetaProfileListResponse: settings = settings_store.load() or PersistedSettings() store = _get_meta_profile_store() - with _store_errors(): - summaries = store.list_summaries() + summaries = store.list_summaries() return MetaProfileListResponse( meta_profiles=[MetaProfileInfo(**s) for s in summaries], @@ -163,13 +145,9 @@ def get_meta_profile(name: MetaProfileName) -> MetaProfileDetailResponse: """Get a meta-profile's full configuration.""" store = _get_meta_profile_store() try: - with _store_errors(): - meta_profile = store.load(name) + meta_profile = store.load(name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Meta-profile '{name}' not found", - ) + raise NotFound(f"Meta-profile '{name}' not found") return MetaProfileDetailResponse(name=name, config=meta_profile) @@ -190,15 +168,11 @@ def save_meta_profile( """ store = _get_meta_profile_store() try: - with _store_errors(): - store.save(name, body, max_profiles=MAX_META_PROFILES) + store.save(name, body, max_profiles=MAX_META_PROFILES) except MetaProfileLimitExceeded: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - f"Meta-profile limit reached ({MAX_META_PROFILES}). " - "Delete a meta-profile before saving a new one." - ), + raise Conflict( + f"Meta-profile limit reached ({MAX_META_PROFILES}). " + "Delete a meta-profile before saving a new one." ) logger.info(f"Saved meta-profile '{name}'") @@ -217,8 +191,7 @@ def delete_meta_profile( cleared. """ store = _get_meta_profile_store() - with _store_errors(): - store.delete(name) + store.delete(name) if _set_active_meta_profile_if_matches(request, name, None): logger.info(f"Cleared active_meta_profile for deleted meta-profile '{name}'") logger.info(f"Deleted meta-profile '{name}'") @@ -245,13 +218,9 @@ def activate_meta_profile( # Verify the meta-profile exists (and is valid) before activating. store = _get_meta_profile_store() try: - with _store_errors(): - meta_profile = store.load(name) + meta_profile = store.load(name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Meta-profile '{name}' not found", - ) + raise NotFound(f"Meta-profile '{name}' not found") config = get_config(request) settings_store = get_settings_store(config) @@ -279,13 +248,10 @@ def apply_active(settings: PersistedSettings) -> PersistedSettings: settings_store.update(apply_active) except (OSError, PermissionError): logger.error("Failed to activate meta-profile - file I/O error") - raise HTTPException(status_code=500, detail="Failed to activate meta-profile") + raise OperationFailed("Failed to activate meta-profile") except RuntimeError as e: logger.error(f"Failed to activate meta-profile: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Settings file is corrupted or encrypted with a different key", - ) + raise Conflict("Settings file is corrupted or encrypted with a different key") if not applied: logger.info(f"Meta-profile '{name}' not activated: agent cannot route") diff --git a/openhands-agent-server/openhands/agent_server/openai/router.py b/openhands-agent-server/openhands/agent_server/openai/router.py index e8f5c046024..9a9171dc9c4 100644 --- a/openhands-agent-server/openhands/agent_server/openai/router.py +++ b/openhands-agent-server/openhands/agent_server/openai/router.py @@ -4,7 +4,7 @@ from typing import Annotated from uuid import UUID -from fastapi import APIRouter, Depends, Header, HTTPException, Request, Response, status +from fastapi import APIRouter, Depends, Header, Request, Response from fastapi.responses import StreamingResponse from fastapi.security import APIKeyHeader, HTTPAuthorizationCredentials, HTTPBearer from pydantic import TypeAdapter, ValidationError @@ -31,6 +31,7 @@ ConversationObservabilitySpanName, ConversationObservabilityTags, ) +from openhands.sdk.errors import Unauthenticated, Unavailable, Unprocessable openai_router = APIRouter(tags=["OpenAI Compatibility"]) @@ -67,16 +68,13 @@ def check_openai_api_key( return if bearer_token in config.session_api_keys: return - raise HTTPException(status.HTTP_401_UNAUTHORIZED) + raise Unauthenticated() def _get_config(request: Request) -> Config: config = getattr(request.app.state, "config", None) if not isinstance(config, Config): - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Agent server config is not available", - ) + raise Unavailable("Agent server config is not available") return config @@ -109,15 +107,11 @@ def _parse_observability_overrides( _OBSERVABILITY_METADATA_ADAPTER.validate_python(metadata_payload) ) except json.JSONDecodeError as exc: - raise HTTPException( - status_code=422, - detail="X-OpenHands-Observability-Metadata must be a JSON object", + raise Unprocessable( + "X-OpenHands-Observability-Metadata must be a JSON object" ) from exc except ValidationError as exc: - raise HTTPException( - status_code=422, - detail=exc.errors(include_context=False), - ) from exc + raise Unprocessable(exc.errors(include_context=False)) from exc if parent_span_context: overrides["observability_parent_span_context"] = parent_span_context return overrides diff --git a/openhands-agent-server/openhands/agent_server/openai/service.py b/openhands-agent-server/openhands/agent_server/openai/service.py index 23aea5eb71d..d0dd69da292 100644 --- a/openhands-agent-server/openhands/agent_server/openai/service.py +++ b/openhands-agent-server/openhands/agent_server/openai/service.py @@ -8,7 +8,6 @@ from uuid import UUID, uuid4 import httpx -from fastapi import HTTPException, status from pydantic import ValidationError from openhands.agent_server.agent_profiles_router import active_agent_profile @@ -20,8 +19,9 @@ _container, start_docker_conversation, ) +from openhands.agent_server.errors import ForwardedStatus from openhands.agent_server.event_service import EventService -from openhands.agent_server.launch import launch_http_exception +from openhands.agent_server.launch import launch_error from openhands.agent_server.openai.models import ( OpenAIChatCompletionChoice, OpenAIChatCompletionChunk, @@ -57,6 +57,15 @@ from openhands.sdk.conversation.state import ( ConversationExecutionStatus, ) +from openhands.sdk.errors import ( + Conflict, + Invalid, + NotFound, + OperationFailed, + Unavailable, + UpstreamFailed, + UpstreamTimeout, +) from openhands.sdk.launch import AgentLaunchError, LaunchStoreError from openhands.sdk.llm import Metrics from openhands.sdk.llm.message import ImageContent, TextContent @@ -96,27 +105,18 @@ class OpenAIAgentRunResult: def _profile_name_from_model(model: str) -> str: if model.startswith(_MODEL_PREFIX) and len(model) > len(_MODEL_PREFIX): return model[len(_MODEL_PREFIX) :] - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Unknown OpenHands model '{model}'. Use GET /v1/models.", - ) + raise NotFound(f"Unknown OpenHands model '{model}'. Use GET /v1/models.") def _require_llm_profile(profile_name: str, config: Config) -> None: try: get_llm_profile_store().load(profile_name, cipher=config.cipher) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{profile_name}' not found", - ) + raise NotFound(f"Profile '{profile_name}' not found") except TimeoutError: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Profile store is busy. Please retry.", - ) + raise Unavailable("Profile store is busy. Please retry.") except ValueError as exc: - raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) + raise Invalid(str(exc)) def _content_to_sdk_parts( @@ -140,16 +140,10 @@ def _content_to_sdk_parts( elif part.image_url is not None: image_url = part.image_url.url else: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="image_url content part is missing a url", - ) + raise Invalid("image_url content part is missing a url") parts.append(ImageContent(image_urls=[image_url])) continue - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Unsupported content part type: {part.type}", - ) + raise Invalid(f"Unsupported content part type: {part.type}") return parts @@ -165,10 +159,7 @@ def _latest_user_message(messages: list[OpenAIChatMessage]) -> OpenAIChatMessage for message in reversed(messages): if message.role == "user": return message - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="At least one user message is required", - ) + raise Invalid("At least one user message is required") def _system_text(messages: list[OpenAIChatMessage]) -> str: @@ -196,16 +187,10 @@ def _response_content_to_sdk_parts( continue if part.type == "input_image": if not part.image_url: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="input_image content part is missing an image_url", - ) + raise Invalid("input_image content part is missing an image_url") parts.append(ImageContent(image_urls=[part.image_url])) continue - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail=f"Unsupported Responses content part type: {part.type}", - ) + raise Invalid(f"Unsupported Responses content part type: {part.type}") return parts @@ -236,10 +221,7 @@ def _response_user_content( ) -> list[TextContent | ImageContent]: if isinstance(request.input, str): if not request.input: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Responses input must not be empty", - ) + raise Invalid("Responses input must not be empty") return [TextContent(text=request.input)] messages = [ @@ -248,10 +230,7 @@ def _response_user_content( if message.role not in {"system", "developer"} ] if not any(message.role == "user" for message in messages): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Responses input must include a user message", - ) + raise Invalid("Responses input must include a user message") if len(messages) == 1 and messages[0].role == "user": return _response_content_to_sdk_parts(messages[0]) @@ -275,10 +254,7 @@ def _create_conversation_request( _require_llm_profile(llm_profile, config) profile = active_agent_profile(config, config.cipher) if profile is None: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="No active Agent Profile; activate one to use the gateway", - ) + raise Conflict("No active Agent Profile; activate one to use the gateway") settings = get_settings_store(config).load() or PersistedSettings() try: additions = AgentLaunchAdditions( @@ -289,10 +265,7 @@ def _create_conversation_request( system_message_suffix_append=system_text or None, ) except ValidationError: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="System instructions are too long", - ) from None + raise Invalid("System instructions are too long") from None return settings.conversation_settings.create_request( StartConversationRequest, agent_profile_id=profile.id, @@ -379,10 +352,7 @@ async def _wait_for_reused_conversation_completion( return last_status if time.monotonic() >= deadline: - raise HTTPException( - status_code=status.HTTP_504_GATEWAY_TIMEOUT, - detail="Agent run timed out", - ) + raise UpstreamTimeout("Agent run timed out") await asyncio.sleep(_POLL_INTERVAL_SECONDS) @@ -391,22 +361,15 @@ def _raise_for_terminal_error(status_value: ConversationExecutionStatus) -> None ConversationExecutionStatus.ERROR, ConversationExecutionStatus.STUCK, ): - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Agent run ended with status: {status_value.value}", - ) + raise OperationFailed(f"Agent run ended with status: {status_value.value}") if status_value in ( ConversationExecutionStatus.PAUSED, ConversationExecutionStatus.WAITING_FOR_CONFIRMATION, ): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Agent run ended with status: {status_value.value}", - ) + raise Conflict(f"Agent run ended with status: {status_value.value}") if status_value != ConversationExecutionStatus.FINISHED: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail=f"Agent run ended with unexpected status: {status_value.value}", + raise OperationFailed( + f"Agent run ended with unexpected status: {status_value.value}" ) @@ -532,10 +495,7 @@ async def list_openai_models() -> OpenAIModelListResponse: try: profiles = await asyncio.to_thread(get_llm_profile_store().list_summaries) except TimeoutError: - raise HTTPException( - status_code=status.HTTP_503_SERVICE_UNAVAILABLE, - detail="Profile store is busy. Please retry.", - ) + raise Unavailable("Profile store is busy. Please retry.") data = [ OpenAIModel( id=f"{_MODEL_PREFIX}{profile['name']}", @@ -585,7 +545,7 @@ async def _run_agent( registry=registry, ) if config.conversation_runtime == "docker" and registry is None: - raise HTTPException(503, "Docker conversation runtime is unavailable") + raise Unavailable("Docker conversation runtime is unavailable") event_service = None conversation_id = reusable_conversation_id min_event_count: int | None = None @@ -619,16 +579,13 @@ async def _run_agent( start_request ) except (ProfileNotFound, AgentLaunchError, LaunchStoreError) as exc: - raise launch_http_exception(exc) from exc + raise launch_error(exc) from exc conversation_id = conversation_info.id event_service = await conversation_service.get_event_service( conversation_info.id ) if event_service is None: - raise HTTPException( - status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, - detail="Conversation did not start", - ) + raise OperationFailed("Conversation did not start") if started_new_conversation: try: @@ -636,10 +593,7 @@ async def _run_agent( timeout=_GATEWAY_TIMEOUT_SECONDS ) except TimeoutError: - raise HTTPException( - status_code=status.HTTP_504_GATEWAY_TIMEOUT, - detail="Agent run timed out", - ) from None + raise UpstreamTimeout("Agent run timed out") from None else: assert min_event_count is not None status_value = await _wait_for_reused_conversation_completion( @@ -678,7 +632,7 @@ async def _run_docker_agent( .joinpath("meta.json") .is_file() ): - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") docker_request = start_request.model_copy( update={ "workspace": LocalWorkspace(working_dir="/workspace"), @@ -690,7 +644,7 @@ async def _run_docker_agent( registry, ) if status_code >= 400: - raise HTTPException( + raise ForwardedStatus( status_code, "Conversation runtime rejected the request" ) await conversation_service.refresh_persisted_conversation(conversation_id) @@ -716,11 +670,11 @@ async def _run_docker_agent( except (ValueError, AttributeError): detail = None if detail == f"Conversation not found: {conversation_id}": - raise HTTPException(404, detail) - raise HTTPException( - 502, "Conversation container does not provide the gateway route" + raise NotFound(detail) + raise UpstreamFailed( + "Conversation container does not provide the gateway route" ) - raise HTTPException( + raise ForwardedStatus( response.status_code, "Conversation runtime rejected the gateway run" ) result = response.json() @@ -736,9 +690,9 @@ async def _run_docker_agent( ), ) except httpx.TimeoutException as exc: - raise HTTPException(504, "Conversation runtime timed out") from exc + raise UpstreamTimeout("Conversation runtime timed out") from exc except httpx.HTTPError as exc: - raise HTTPException(502, "Conversation container unreachable") from exc + raise UpstreamFailed("Conversation container unreachable") from exc finally: registry.detach_session(conversation_id) @@ -754,10 +708,7 @@ async def run_chat_completion( ) -> OpenAIChatCompletionResult: if request.stream: # SSE streaming needs incremental agent-event forwarding; add it separately. - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Streaming chat completions are not supported yet", - ) + raise Invalid("Streaming chat completions are not supported yet") start_request = _conversation_request( request=request, @@ -809,22 +760,15 @@ async def run_response( registry: DockerConversationRegistry | None = None, ) -> OpenAIResponseResult: if request.stream: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Streaming responses are not supported yet", - ) + raise Invalid("Streaming responses are not supported yet") if request.store: # `store=True` promises server-side persistence retrievable through # GET /v1/responses/{id}, which this gateway does not provide. Rejecting # it is safer than silently returning a response no client can fetch. - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Persistent response storage (store=True) is not supported yet", - ) + raise Invalid("Persistent response storage (store=True) is not supported yet") if request.previous_response_id: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="previous_response_id is not supported; replay input items instead", + raise Invalid( + "previous_response_id is not supported; replay input items instead" ) user_content = _response_user_content(request) diff --git a/openhands-agent-server/openhands/agent_server/plugins_router.py b/openhands-agent-server/openhands/agent_server/plugins_router.py index 0d86c9ac7c3..5dbd096b445 100644 --- a/openhands-agent-server/openhands/agent_server/plugins_router.py +++ b/openhands-agent-server/openhands/agent_server/plugins_router.py @@ -11,9 +11,10 @@ from typing import Annotated -from fastapi import APIRouter, HTTPException, Path +from fastapi import APIRouter, Path from pydantic import BaseModel, Field +from openhands.agent_server.errors import error_for_status, error_responses from openhands.agent_server.plugins_service import ( MarketplacePluginInfo, PluginSkillSummary, @@ -30,6 +31,14 @@ service_uninstall_plugin, service_update_plugin, ) +from openhands.sdk.errors import ( + Conflict, + Invalid, + NotFound, + Unprocessable, + UpstreamFailed, + UpstreamTimeout, +) from openhands.sdk.extensions.fetch import ExtensionFetchError from openhands.sdk.plugin import InstalledPluginInfo, Plugin, PluginFetchError from openhands.sdk.plugin.strict_fetch import PluginSourceError @@ -278,11 +287,13 @@ def get_plugins(request: PluginsRequest) -> PluginsResponse: @plugins_router.post( "/fetch", response_model=FetchPluginResponse, - responses={ - 422: {"description": "Invalid plugin source, ref, path, or plugin"}, - 502: {"description": "Plugin source unavailable"}, - 504: {"description": "Plugin fetch timed out"}, - }, + responses=error_responses( + { + Unprocessable: "Invalid plugin source, ref, path, or plugin", + UpstreamFailed: "Plugin source unavailable", + UpstreamTimeout: "Plugin fetch timed out", + } + ), ) def fetch_plugin_endpoint(request: FetchPluginRequest) -> FetchPluginResponse: """Fetch and pin a plugin source without installing or enabling it.""" @@ -295,9 +306,8 @@ def fetch_plugin_endpoint(request: FetchPluginRequest) -> FetchPluginResponse: timeout=request.timeout, ) except PluginSourceError as exc: - raise HTTPException( - status_code=exc.status_code, - detail={"code": exc.code, "message": exc.message}, + raise error_for_status( + exc.status_code, {"code": exc.code, "message": exc.message} ) from exc return FetchPluginResponse( @@ -314,11 +324,13 @@ def fetch_plugin_endpoint(request: FetchPluginRequest) -> FetchPluginResponse: @plugins_router.post( "/install", response_model=InstalledPluginResponse, - responses={ - 400: {"description": "Failed to fetch plugin source"}, - 409: {"description": "Plugin already installed (use force=true)"}, - 422: {"description": "Invalid plugin (bad name, etc.)"}, - }, + responses=error_responses( + { + Invalid: "Failed to fetch plugin source", + Conflict: "Plugin already installed (use force=true)", + Unprocessable: "Invalid plugin (bad name, etc.)", + } + ), ) def install_plugin_endpoint(request: InstallPluginRequest) -> InstalledPluginResponse: """Install a plugin from a git URL, GitHub shorthand, or local path.""" @@ -331,20 +343,11 @@ def install_plugin_endpoint(request: InstallPluginRequest) -> InstalledPluginRes ) return _installed_response(info) except FileExistsError: - raise HTTPException( - status_code=409, - detail="Plugin already installed. Use force=true to overwrite.", - ) + raise Conflict("Plugin already installed. Use force=true to overwrite.") except (PluginFetchError, ExtensionFetchError): - raise HTTPException( - status_code=400, - detail="Failed to fetch plugin source. Check that the source is valid.", - ) + raise Invalid("Failed to fetch plugin source. Check that the source is valid.") except ValueError: - raise HTTPException( - status_code=422, - detail="Invalid plugin. Ensure it has a valid kebab-case name.", - ) + raise Unprocessable("Invalid plugin. Ensure it has a valid kebab-case name.") @plugins_router.get("/installed", response_model=InstalledPluginsListResponse) @@ -359,7 +362,7 @@ def list_installed_plugins_endpoint() -> InstalledPluginsListResponse: @plugins_router.get( "/installed/{plugin_name}", response_model=InstalledPluginResponse, - responses={404: {"description": "Plugin not installed"}}, + responses=error_responses({NotFound: "Plugin not installed"}), ) def get_installed_plugin_endpoint( plugin_name: PluginNamePath, @@ -367,17 +370,14 @@ def get_installed_plugin_endpoint( """Get information about a specific installed plugin.""" info = service_get_installed_plugin(name=plugin_name) if info is None: - raise HTTPException( - status_code=404, - detail=f"Plugin '{plugin_name}' is not installed", - ) + raise NotFound(f"Plugin '{plugin_name}' is not installed") return _installed_response(info) @plugins_router.patch( "/installed/{plugin_name}", response_model=UpdatePluginStateResponse, - responses={404: {"description": "Plugin not installed"}}, + responses=error_responses({NotFound: "Plugin not installed"}), ) def set_plugin_enabled_endpoint( plugin_name: PluginNamePath, request: UpdatePluginStateRequest @@ -385,35 +385,31 @@ def set_plugin_enabled_endpoint( """Enable or disable an installed plugin.""" fn = service_enable_plugin if request.enabled else service_disable_plugin if not fn(name=plugin_name): - raise HTTPException( - status_code=404, - detail=f"Plugin '{plugin_name}' is not installed", - ) + raise NotFound(f"Plugin '{plugin_name}' is not installed") return UpdatePluginStateResponse(name=plugin_name, enabled=request.enabled) @plugins_router.delete( "/installed/{plugin_name}", response_model=UninstallPluginResponse, - responses={404: {"description": "Plugin not installed"}}, + responses=error_responses({NotFound: "Plugin not installed"}), ) def uninstall_plugin_endpoint(plugin_name: PluginNamePath) -> UninstallPluginResponse: """Uninstall a plugin by name.""" if not service_uninstall_plugin(name=plugin_name): - raise HTTPException( - status_code=404, - detail=f"Plugin '{plugin_name}' is not installed", - ) + raise NotFound(f"Plugin '{plugin_name}' is not installed") return UninstallPluginResponse(message=f"Plugin '{plugin_name}' uninstalled") @plugins_router.post( "/installed/{plugin_name}/refresh", response_model=UpdatePluginResponse, - responses={ - 400: {"description": "Failed to fetch the plugin's recorded source"}, - 404: {"description": "Plugin not installed"}, - }, + responses=error_responses( + { + Invalid: "Failed to fetch the plugin's recorded source", + NotFound: "Plugin not installed", + } + ), ) def refresh_plugin_endpoint(plugin_name: PluginNamePath) -> UpdatePluginResponse: """Refresh an installed plugin to the latest version from its source. @@ -423,26 +419,17 @@ def refresh_plugin_endpoint(plugin_name: PluginNamePath) -> UpdatePluginResponse try: info = service_update_plugin(name=plugin_name) except (PluginFetchError, ExtensionFetchError): - raise HTTPException( - status_code=400, - detail=( - f"Failed to fetch the source of plugin '{plugin_name}'. " - "The installed copy was kept." - ), + raise Invalid( + f"Failed to fetch the source of plugin '{plugin_name}'. " + "The installed copy was kept." ) except ValueError: - raise HTTPException( - status_code=422, - detail=( - f"The source of plugin '{plugin_name}' no longer holds a valid " - "plugin. The installed copy was kept." - ), + raise Unprocessable( + f"The source of plugin '{plugin_name}' no longer holds a valid " + "plugin. The installed copy was kept." ) if info is None: - raise HTTPException( - status_code=404, - detail=f"Plugin '{plugin_name}' is not installed", - ) + raise NotFound(f"Plugin '{plugin_name}' is not installed") return UpdatePluginResponse( message=f"Plugin '{plugin_name}' updated", plugin=_installed_response(info), diff --git a/openhands-agent-server/openhands/agent_server/profiles_router.py b/openhands-agent-server/openhands/agent_server/profiles_router.py index 290da67fe44..9751e53ccc1 100644 --- a/openhands-agent-server/openhands/agent_server/profiles_router.py +++ b/openhands-agent-server/openhands/agent_server/profiles_router.py @@ -3,7 +3,7 @@ import asyncio from typing import Annotated, Any -from fastapi import APIRouter, HTTPException, Path, Request, status +from fastapi import APIRouter, Path, Request, status from pydantic import BaseModel, Field, SecretStr from openhands.agent_server._secrets_exposure import ( @@ -13,7 +13,6 @@ get_config, parse_expose_secrets_header, profile_key_mismatch, - store_errors, translate_missing_cipher, ) from openhands.agent_server.persistence import ( @@ -23,6 +22,7 @@ get_provider_connections_store, get_settings_store, ) +from openhands.sdk.errors import Conflict, NotFound, OperationFailed from openhands.sdk.llm import LLM, Message, TextContent from openhands.sdk.llm.exceptions import ( LLMError, @@ -124,10 +124,9 @@ def _profile_api_key_set(request: Request, llm: LLM) -> bool: cipher = get_cipher(request) # The provider store read can raise on a corrupted file; map it instead of # letting it surface as an unhandled 500 on GET /profiles/{name}. - with store_errors(): - connection = get_provider_connections_store(config).get( - connection_id, cipher=cipher - ) + connection = get_provider_connections_store(config).get( + connection_id, cipher=cipher + ) return connection is not None and connection.api_key_value() is not None @@ -167,8 +166,7 @@ def list_profiles(request: Request) -> ProfileListResponse: settings = settings_store.load() or PersistedSettings() store = get_llm_profile_store() - with store_errors(): - summaries = store.list_summaries() + summaries = store.list_summaries() return ProfileListResponse( profiles=[ProfileInfo(**s) for s in summaries], @@ -191,17 +189,13 @@ def get_profile(request: Request, name: ProfileName) -> ProfileDetailResponse: store = get_llm_profile_store() try: - with store_errors(): - # Runtime reads need current provider credentials. Editor reads - # retain the stored reference, including dangling references. - llm = store.load( - name, cipher=cipher, resolve_provider=expose_mode == "plaintext" - ) - except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{name}' not found", + # Runtime reads need current provider credentials. Editor reads + # retain the stored reference, including dangling references. + llm = store.load( + name, cipher=cipher, resolve_provider=expose_mode == "plaintext" ) + except FileNotFoundError: + raise NotFound(f"Profile '{name}' not found") if expose_mode: context = build_expose_context(expose_mode, cipher) @@ -241,23 +235,19 @@ def save_profile( llm = decrypt_incoming_llm_secrets(body.llm, cipher) if cipher else body.llm store = get_llm_profile_store() try: - with store_errors(): - store.save( - name, - llm, - include_secrets=body.include_secrets, - cipher=cipher, - max_profiles=MAX_PROFILES, - ) + store.save( + name, + llm, + include_secrets=body.include_secrets, + cipher=cipher, + max_profiles=MAX_PROFILES, + ) except SecretDecryptionError as e: raise profile_key_mismatch(name, e) except ProfileLimitExceeded: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - f"Profile limit reached ({MAX_PROFILES}). " - "Delete a profile before saving a new one." - ), + raise Conflict( + f"Profile limit reached ({MAX_PROFILES}). " + "Delete a profile before saving a new one." ) logger.info(f"Saved profile '{name}' (include_secrets={body.include_secrets})") @@ -351,8 +341,7 @@ async def validate_profile( # Check a draft linked to a provider connection with the connection's # credentials, as activation and ``switch_llm`` run it. No-op without # ``provider_connection_id``; a dangling link is a 422 naming it. - with store_errors(): - llm = get_llm_profile_store().resolve_provider_connection(llm, cipher=cipher) + llm = get_llm_profile_store().resolve_provider_connection(llm, cipher=cipher) messages = [ Message( @@ -433,10 +422,9 @@ def delete_profile(request: Request, name: ProfileName) -> ProfileMutationRespon store = get_llm_profile_store() agent_store = get_agent_profile_store() try: - with store_errors(): - delete_llm_profile(agent_store, store, name) + delete_llm_profile(agent_store, store, name) except ProfileReferenced as e: - raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e)) + raise Conflict(str(e)) if _set_active_profile_if_matches(request, name, None): logger.info(f"Cleared active_profile for deleted profile '{name}'") logger.info(f"Deleted profile '{name}'") @@ -461,18 +449,11 @@ def rename_profile( store = get_llm_profile_store() agent_store = get_agent_profile_store() try: - with store_errors(): - rename_llm_profile(agent_store, store, name, body.new_name) + rename_llm_profile(agent_store, store, name, body.new_name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{name}' not found", - ) + raise NotFound(f"Profile '{name}' not found") except FileExistsError: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"Profile '{body.new_name}' already exists", - ) + raise Conflict(f"Profile '{body.new_name}' already exists") if name != body.new_name and _set_active_profile_if_matches( request, name, body.new_name @@ -520,18 +501,13 @@ def activate_profile(request: Request, name: ProfileName) -> ActivateProfileResp # api_key / base_url; ``provider_connection_id`` is retained so a later # rotation re-resolves on the next activation or launch. profile_store = get_llm_profile_store() - # A dangling provider_connection_id raises ProviderConnectionNotFound, which - # store_errors() maps to 422. + # A dangling provider_connection_id raises ProviderConnectionNotFound (422). try: - with store_errors(): - llm = profile_store.load(name, cipher=cipher, strict=True) + llm = profile_store.load(name, cipher=cipher, strict=True) except SecretDecryptionError as e: raise profile_key_mismatch(name, e) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{name}' not found", - ) + raise NotFound(f"Profile '{name}' not found") settings_store = get_settings_store(config) llm_applied = False @@ -550,16 +526,13 @@ def apply_profile(settings: PersistedSettings) -> PersistedSettings: settings_store.update(apply_profile) except (OSError, PermissionError): logger.error("Failed to activate profile - file I/O error") - raise HTTPException(status_code=500, detail="Failed to activate profile") + raise OperationFailed("Failed to activate profile") except RuntimeError as e: logger.error(f"Failed to activate profile: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - "Settings file is corrupted or encrypted with a different key: " - "restore that key as OH_SECRET_KEY or add it to " - "OH_PREVIOUS_SECRET_KEYS" - ), + raise Conflict( + "Settings file is corrupted or encrypted with a different key: " + "restore that key as OH_SECRET_KEY or add it to " + "OH_PREVIOUS_SECRET_KEYS" ) logger.info(f"Activated profile '{name}'") diff --git a/openhands-agent-server/openhands/agent_server/provider_connections_router.py b/openhands-agent-server/openhands/agent_server/provider_connections_router.py index f376480d2b1..58571045cbb 100644 --- a/openhands-agent-server/openhands/agent_server/provider_connections_router.py +++ b/openhands-agent-server/openhands/agent_server/provider_connections_router.py @@ -15,7 +15,7 @@ import uuid from typing import Any -from fastapi import APIRouter, HTTPException, Request, status +from fastapi import APIRouter, Request, status from pydantic import ( BaseModel, ConfigDict, @@ -28,7 +28,6 @@ from openhands.agent_server._secrets_exposure import ( get_cipher, get_config, - store_errors, ) from openhands.agent_server.persistence import ( ProviderConnection, @@ -36,6 +35,7 @@ get_provider_connections_store, get_settings_store, ) +from openhands.sdk.errors import Conflict, NotFound, Unprocessable from openhands.sdk.llm.provider_connection_store import ( ProviderConnectionLimitExceeded, ProviderConnectionNotFound, @@ -153,13 +153,10 @@ def _raise_if_connection_is_referenced(config, connection_id: str) -> None: reasons.append(f"referenced by LLM profile(s): {', '.join(profile_names)}") if active_reference: reasons.append("referenced by the active agent settings") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - "Provider connection cannot be deleted while it is " - + " and ".join(reasons) - + ". Update those references before deleting it." - ), + raise Conflict( + "Provider connection cannot be deleted while it is " + + " and ".join(reasons) + + ". Update those references before deleting it." ) @@ -169,8 +166,7 @@ def list_provider_connections( ) -> list[ProviderConnectionResponse]: cipher = get_cipher(request) store = get_provider_connections_store(get_config(request)) - with store_errors(): - connections = store.list(cipher=cipher) + connections = store.list(cipher=cipher) return [_to_response(c) for c in connections] @@ -193,13 +189,9 @@ def create_provider_connection( updated_at=now, ) try: - with store_errors(): - store.create(connection, cipher=cipher) + store.create(connection, cipher=cipher) except ProviderConnectionLimitExceeded as e: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"{e} Delete one before adding another.", - ) + raise Conflict(f"{e} Delete one before adding another.") logger.info( "Created LLM provider connection", extra={"connection_id": connection.id} ) @@ -214,28 +206,18 @@ def update_provider_connection( ) -> ProviderConnectionResponse: fields = body.model_fields_set if not fields: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Provide at least one provider connection field to update", - ) + raise Unprocessable("Provide at least one provider connection field to update") cipher = get_cipher(request) store = get_provider_connections_store(get_config(request)) - with store_errors(): - connection = store.get(connection_id, cipher=cipher) + connection = store.get(connection_id, cipher=cipher) if connection is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Provider connection '{connection_id}' not found", - ) + raise NotFound(f"Provider connection '{connection_id}' not found") # A connection must always have a key, so clearing it is not a valid # update. Reject api_key: null explicitly instead of silently dropping it. if "api_key" in fields and body.api_key is None: - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="api_key cannot be cleared; provide a new key to rotate it", - ) + raise Unprocessable("api_key cannot be cleared; provide a new key to rotate it") updates: dict[str, Any] = {"updated_at": _now()} for field in ("display_name", "provider", "base_url"): @@ -245,18 +227,14 @@ def update_provider_connection( updates["api_key"] = body.api_key updated = connection.model_copy(update=updates) - # store_errors() maps infra failures (lock timeout -> 503, corrupted/ - # wrong-cipher file -> 4xx); the inner except keeps the deleted-between- - # get-and-update race as a 404 rather than the 422 store_errors would give - # ProviderConnectionNotFound. - with store_errors(): - try: - store.update(updated, cipher=cipher) - except ProviderConnectionNotFound: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Provider connection '{connection_id}' not found", - ) + # The store raises domain errors for infra failures (lock timeout -> 503, + # corrupted/wrong-cipher file -> 4xx); the except keeps the deleted-between- + # get-and-update race as a 404 rather than the 422 ProviderConnectionNotFound + # maps to. + try: + store.update(updated, cipher=cipher) + except ProviderConnectionNotFound: + raise NotFound(f"Provider connection '{connection_id}' not found") logger.info( "Updated LLM provider connection", extra={"connection_id": connection_id} ) @@ -272,24 +250,16 @@ def delete_provider_connection( config = get_config(request) cipher = get_cipher(request) store = get_provider_connections_store(config) - with store_errors(): - connection = store.get(connection_id, cipher=cipher) + connection = store.get(connection_id, cipher=cipher) if connection is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Provider connection '{connection_id}' not found", - ) + raise NotFound(f"Provider connection '{connection_id}' not found") _raise_if_connection_is_referenced(config, connection_id) # See update handler: keep the delete-race as 404, map infra errors. - with store_errors(): - try: - store.delete(connection_id, cipher=cipher) - except ProviderConnectionNotFound: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Provider connection '{connection_id}' not found", - ) + try: + store.delete(connection_id, cipher=cipher) + except ProviderConnectionNotFound: + raise NotFound(f"Provider connection '{connection_id}' not found") logger.info( "Deleted LLM provider connection", extra={"connection_id": connection_id} ) diff --git a/openhands-agent-server/openhands/agent_server/runtime_router.py b/openhands-agent-server/openhands/agent_server/runtime_router.py index fddc306f933..6b6dc4f9733 100644 --- a/openhands-agent-server/openhands/agent_server/runtime_router.py +++ b/openhands-agent-server/openhands/agent_server/runtime_router.py @@ -10,7 +10,7 @@ from typing import Any from uuid import UUID -from fastapi import APIRouter, Depends, HTTPException, Request +from fastapi import APIRouter, Depends, Request from fastapi.responses import FileResponse from fastapi.routing import APIRoute @@ -26,6 +26,7 @@ get_vscode_url, vscode_router, ) +from openhands.sdk.errors import NotFound, Unprocessable async def bind_local_conversation_runtime( @@ -36,7 +37,7 @@ async def bind_local_conversation_runtime( runtime_conversation_id, request, conversation_service ) if event_service is None: - raise HTTPException(404, "Conversation not found") + raise NotFound("Conversation not found") request.state.runtime_event_service = event_service workspace_root = Path( event_service.get_conversation().workspace.working_dir @@ -47,19 +48,15 @@ async def bind_local_conversation_runtime( not Path(requested_path).is_absolute() or not Path(requested_path).resolve().is_relative_to(workspace_root) ): - raise HTTPException( - 422, f"{name} must be inside the conversation workspace" - ) + raise Unprocessable(f"{name} must be inside the conversation workspace") trajectory_id = request.path_params.get("conversation_id") if trajectory_id is not None: try: matches = UUID(trajectory_id) == runtime_conversation_id except ValueError as exc: - raise HTTPException(422, "Invalid trajectory conversation id") from exc + raise Unprocessable("Invalid trajectory conversation id") from exc if not matches: - raise HTTPException( - 422, "Trajectory must belong to the selected conversation" - ) + raise Unprocessable("Trajectory must belong to the selected conversation") class RuntimeRouter(APIRouter): diff --git a/openhands-agent-server/openhands/agent_server/settings_router.py b/openhands-agent-server/openhands/agent_server/settings_router.py index aa7a0b6245c..e863c9810a7 100644 --- a/openhands-agent-server/openhands/agent_server/settings_router.py +++ b/openhands-agent-server/openhands/agent_server/settings_router.py @@ -2,7 +2,7 @@ from functools import lru_cache from typing import cast -from fastapi import APIRouter, HTTPException, Request, Response, status +from fastapi import APIRouter, Request, Response, status from pydantic import ValidationError from openhands.agent_server._secrets_exposure import ( @@ -11,7 +11,6 @@ get_config, parse_expose_secrets_header, profile_key_mismatch, - store_errors, translate_missing_cipher, ) from openhands.agent_server.persistence import ( @@ -24,6 +23,13 @@ ) from openhands.agent_server.persistence.models import SettingsUpdatePayload from openhands.agent_server.telemetry import notify_misc_settings_changed +from openhands.sdk.errors import ( + Conflict, + Invalid, + NotFound, + OperationFailed, + Unprocessable, +) from openhands.sdk.llm import LLM from openhands.sdk.llm.meta_profile_store import ( MetaProfileStore, @@ -109,13 +115,10 @@ def _validate_secret_name(name: str) -> None: HTTPException: 422 if name format is invalid. """ if not SECRET_NAME_PATTERN.match(name): - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail=( - "Invalid secret name format. Must start with a letter, " - "contain only letters, numbers, and underscores, " - "and be 1-64 characters long." - ), + raise Unprocessable( + "Invalid secret name format. Must start with a letter, " + "contain only letters, numbers, and underscores, " + "and be 1-64 characters long." ) @@ -238,14 +241,11 @@ def update_settings( update_data["active_meta_profile"] = payload.active_meta_profile if not update_data: # No updates provided - this is a client error - raise HTTPException( - status_code=400, - detail=( - "At least one of agent_settings_diff, " - "conversation_settings_diff, misc_settings_diff, " - "active_profile, active_agent_profile_id, or active_meta_profile " - "must be provided" - ), + raise Invalid( + "At least one of agent_settings_diff, " + "conversation_settings_diff, misc_settings_diff, " + "active_profile, active_agent_profile_id, or active_meta_profile " + "must be provided" ) _require_pointer_targets(update_data) @@ -263,24 +263,16 @@ def _require_pointer_targets(update_data: dict) -> None: """ profile_id = update_data.get("active_agent_profile_id") if profile_id is not None: - with store_errors(): - known = get_agent_profile_store().name_for_id(profile_id) is not None + known = get_agent_profile_store().name_for_id(profile_id) is not None if not known: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Agent profile with id '{profile_id}' not found", - ) + raise NotFound(f"Agent profile with id '{profile_id}' not found") meta_name = update_data.get("active_meta_profile") if meta_name is not None: try: - with store_errors(): - MetaProfileStore(base_dir=default_meta_profile_dir()).load(meta_name) + MetaProfileStore(base_dir=default_meta_profile_dir()).load(meta_name) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Meta-profile '{meta_name}' not found", - ) + raise NotFound(f"Meta-profile '{meta_name}' not found") def _load_active_profile_llm( @@ -296,19 +288,15 @@ def _load_active_profile_llm( cipher = get_cipher(request) profile_store = get_llm_profile_store() # ``load`` resolves any referenced provider connection (read-at-use); a - # dangling reference raises ProviderConnectionNotFound, which - # store_errors() maps to 422. A key the cipher cannot decrypt is refused + # dangling reference raises ProviderConnectionNotFound (422). A key the + # cipher cannot decrypt is refused # (409) rather than applied to settings as ``null``. try: - with store_errors(): - llm = profile_store.load(profile_name, cipher=cipher, strict=True) + llm = profile_store.load(profile_name, cipher=cipher, strict=True) except SecretDecryptionError as e: raise profile_key_mismatch(profile_name, e) except FileNotFoundError: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Profile '{profile_name}' not found", - ) + raise NotFound(f"Profile '{profile_name}' not found") return llm @@ -386,25 +374,19 @@ def apply_update(settings: PersistedSettings) -> PersistedSettings: ) # 422 Unprocessable Entity - semantic validation failure # Don't expose error details - could contain secrets in tracebacks - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Settings validation failed", - ) + raise Unprocessable("Settings validation failed") except RuntimeError as e: # Data corruption protection triggered (file exists but unreadable) logger.error(f"Settings update blocked: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=( - "Settings file is corrupted or encrypted with a different key: " - "restore that key as OH_SECRET_KEY or add it to " - "OH_PREVIOUS_SECRET_KEYS" - ), + raise Conflict( + "Settings file is corrupted or encrypted with a different key: " + "restore that key as OH_SECRET_KEY or add it to " + "OH_PREVIOUS_SECRET_KEYS" ) except (OSError, PermissionError): # Note: exc_info omitted to prevent secrets in scope from leaking in tracebacks logger.error("Settings update failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to update settings") + raise OperationFailed("Failed to update settings") # Don't expose secrets in mutation responses (consistent with GET behavior) return SettingsResponse( @@ -420,18 +402,12 @@ def apply_update(settings: PersistedSettings) -> PersistedSettings: def _require_mcp_server_absent(settings: PersistedSettings, settings_key: str) -> None: if settings_key in settings.agent_settings.mcp_config: - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail=f"MCP server '{settings_key}' already exists", - ) + raise Conflict(f"MCP server '{settings_key}' already exists") def _require_mcp_server_present(settings: PersistedSettings, settings_key: str) -> None: if settings_key not in settings.agent_settings.mcp_config: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"MCP server '{settings_key}' was not found", - ) + raise NotFound(f"MCP server '{settings_key}' was not found") @settings_router.post( @@ -514,13 +490,12 @@ def list_secrets( allowed_names: set[str] | None = None if agent_profile_id is not None: profile_store = get_agent_profile_store() - # store_errors() answers an unloadable profile (400) and a busy store - # (503) the way the agent-profile routes do. - with store_errors(): - profile_name = profile_store.name_for_id(agent_profile_id) - if profile_name is None: - raise HTTPException(status_code=404, detail="Agent profile not found") - profile = profile_store.load(profile_name) + # The store raises Invalid for an unloadable profile (400) and + # LockTimeout for a busy store (503), as on the agent-profile routes. + profile_name = profile_store.name_for_id(agent_profile_id) + if profile_name is None: + raise NotFound("Agent profile not found") + profile = profile_store.load(profile_name) if profile.secret_refs is not None: allowed_names = set(profile.secret_refs) @@ -567,7 +542,7 @@ async def get_secret_value(request: Request, name: str) -> Response: extra={"secret_name": name, "client_host": client_host}, ) # Use generic message to prevent secret name enumeration attacks - raise HTTPException(status_code=404, detail="Secret not found") + raise NotFound("Secret not found") logger.info( "Secret accessed", @@ -589,10 +564,7 @@ async def create_secret( value = secret.value.get_secret_value() if not value.strip() or is_redacted_secret(value): - raise HTTPException( - status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, - detail="Secret value must not be empty or redacted", - ) + raise Unprocessable("Secret value must not be empty or redacted") config = get_config(request) store = get_secrets_store(config) @@ -606,18 +578,15 @@ async def create_secret( except RuntimeError as e: # Data corruption protection triggered (file exists but unreadable) logger.error(f"Secret create blocked: {e}") - raise HTTPException( - status_code=500, - detail=( - "Secrets file is corrupted or encrypted with a different key: " - "restore that key as OH_SECRET_KEY or add it to " - "OH_PREVIOUS_SECRET_KEYS" - ), + raise OperationFailed( + "Secrets file is corrupted or encrypted with a different key: " + "restore that key as OH_SECRET_KEY or add it to " + "OH_PREVIOUS_SECRET_KEYS" ) except (OSError, PermissionError): # Note: exc_info omitted to prevent secret values from leaking in tracebacks logger.error("Failed to save secret - file I/O error") - raise HTTPException(status_code=500, detail="Failed to save secret") + raise OperationFailed("Failed to save secret") logger.info( "Secret created/updated", @@ -648,13 +617,10 @@ async def delete_secret(request: Request, name: str) -> dict[str, bool]: except RuntimeError as e: # Data corruption protection triggered (file exists but unreadable) logger.error(f"Secret delete blocked: {e}") - raise HTTPException( - status_code=500, - detail=( - "Secrets file is corrupted or encrypted with a different key: " - "restore that key as OH_SECRET_KEY or add it to " - "OH_PREVIOUS_SECRET_KEYS" - ), + raise OperationFailed( + "Secrets file is corrupted or encrypted with a different key: " + "restore that key as OH_SECRET_KEY or add it to " + "OH_PREVIOUS_SECRET_KEYS" ) if not deleted: @@ -664,7 +630,7 @@ async def delete_secret(request: Request, name: str) -> dict[str, bool]: extra={"secret_name": name, "client_host": client_host}, ) # Use generic message to prevent secret name enumeration attacks - raise HTTPException(status_code=404, detail="Secret not found") + raise NotFound("Secret not found") logger.info( "Secret deleted", diff --git a/openhands-agent-server/openhands/agent_server/skills_router.py b/openhands-agent-server/openhands/agent_server/skills_router.py index b54abd9e3c8..b7864027871 100644 --- a/openhands-agent-server/openhands/agent_server/skills_router.py +++ b/openhands-agent-server/openhands/agent_server/skills_router.py @@ -6,9 +6,10 @@ from typing import Annotated, Literal -from fastapi import APIRouter, HTTPException, Path, Request +from fastapi import APIRouter, Path, Request from pydantic import BaseModel, Field +from openhands.agent_server.errors import error_responses from openhands.agent_server.skills_service import ( ExposedUrlData, MarketplaceSkillInfo, @@ -25,6 +26,7 @@ service_update_skill, sync_public_skills, ) +from openhands.sdk.errors import Conflict, Invalid, NotFound, Unprocessable from openhands.sdk.extensions.fetch import ExtensionFetchError from openhands.sdk.marketplace.registration import MarketplaceRegistration from openhands.sdk.skills import ( @@ -374,11 +376,13 @@ def sync_skills() -> SyncResponse: @skills_router.post( "/install", response_model=InstalledSkillResponse, - responses={ - 400: {"description": "Failed to fetch skill source"}, - 409: {"description": "Skill already installed (use force=true)"}, - 422: {"description": "Invalid skill (missing SKILL.md, etc.)"}, - }, + responses=error_responses( + { + Invalid: "Failed to fetch skill source", + Conflict: "Skill already installed (use force=true)", + Unprocessable: "Invalid skill (missing SKILL.md, etc.)", + } + ), ) def install_skill_endpoint(request: InstallSkillRequest) -> InstalledSkillResponse: """Install a skill from a source. @@ -406,19 +410,12 @@ def install_skill_endpoint(request: InstallSkillRequest) -> InstalledSkillRespon ) return InstalledSkillResponse.from_skill_info(info) except FileExistsError: - raise HTTPException( - status_code=409, - detail="Skill already installed. Use force=true to overwrite.", - ) + raise Conflict("Skill already installed. Use force=true to overwrite.") except (SkillFetchError, ExtensionFetchError): - raise HTTPException( - status_code=400, - detail="Failed to fetch skill source. Check that the source is valid.", - ) + raise Invalid("Failed to fetch skill source. Check that the source is valid.") except SkillValidationError: - raise HTTPException( - status_code=422, - detail="Invalid skill. Ensure the source contains a valid SKILL.md.", + raise Unprocessable( + "Invalid skill. Ensure the source contains a valid SKILL.md." ) @@ -441,7 +438,7 @@ def list_installed_skills_endpoint() -> InstalledSkillsListResponse: @skills_router.get( "/installed/{skill_name}", response_model=InstalledSkillResponse, - responses={404: {"description": "Skill not installed"}}, + responses=error_responses({NotFound: "Skill not installed"}), ) def get_installed_skill_endpoint(skill_name: SkillNamePath) -> InstalledSkillResponse: """Get information about a specific installed skill. @@ -457,17 +454,14 @@ def get_installed_skill_endpoint(skill_name: SkillNamePath) -> InstalledSkillRes """ info = service_get_installed_skill(name=skill_name) if info is None: - raise HTTPException( - status_code=404, - detail=f"Skill '{skill_name}' is not installed", - ) + raise NotFound(f"Skill '{skill_name}' is not installed") return InstalledSkillResponse.from_skill_info(info) @skills_router.patch( "/installed/{skill_name}", response_model=UpdateSkillStateResponse, - responses={404: {"description": "Skill not installed"}}, + responses=error_responses({NotFound: "Skill not installed"}), ) def set_skill_enabled_endpoint( skill_name: SkillNamePath, request: UpdateSkillStateRequest @@ -486,10 +480,7 @@ def set_skill_enabled_endpoint( """ fn = service_enable_skill if request.enabled else service_disable_skill if not fn(name=skill_name): - raise HTTPException( - status_code=404, - detail=f"Skill '{skill_name}' is not installed", - ) + raise NotFound(f"Skill '{skill_name}' is not installed") return UpdateSkillStateResponse( name=skill_name, @@ -500,7 +491,7 @@ def set_skill_enabled_endpoint( @skills_router.delete( "/installed/{skill_name}", response_model=UninstallSkillResponse, - responses={404: {"description": "Skill not installed"}}, + responses=error_responses({NotFound: "Skill not installed"}), ) def uninstall_skill_endpoint(skill_name: SkillNamePath) -> UninstallSkillResponse: """Uninstall a skill by name. @@ -518,10 +509,7 @@ def uninstall_skill_endpoint(skill_name: SkillNamePath) -> UninstallSkillRespons """ success = service_uninstall_skill(name=skill_name) if not success: - raise HTTPException( - status_code=404, - detail=f"Skill '{skill_name}' is not installed", - ) + raise NotFound(f"Skill '{skill_name}' is not installed") return UninstallSkillResponse( message=f"Skill '{skill_name}' uninstalled", ) @@ -530,10 +518,12 @@ def uninstall_skill_endpoint(skill_name: SkillNamePath) -> UninstallSkillRespons @skills_router.post( "/installed/{skill_name}/refresh", response_model=UpdateSkillResponse, - responses={ - 400: {"description": "Failed to fetch the skill's recorded source"}, - 404: {"description": "Skill not installed"}, - }, + responses=error_responses( + { + Invalid: "Failed to fetch the skill's recorded source", + NotFound: "Skill not installed", + } + ), ) def refresh_skill_endpoint(skill_name: SkillNamePath) -> UpdateSkillResponse: """Refresh an installed skill to the latest version. @@ -555,26 +545,17 @@ def refresh_skill_endpoint(skill_name: SkillNamePath) -> UpdateSkillResponse: try: info = service_update_skill(name=skill_name) except (SkillFetchError, ExtensionFetchError): - raise HTTPException( - status_code=400, - detail=( - f"Failed to fetch the source of skill '{skill_name}'. " - "The installed copy was kept." - ), + raise Invalid( + f"Failed to fetch the source of skill '{skill_name}'. " + "The installed copy was kept." ) except SkillValidationError: - raise HTTPException( - status_code=422, - detail=( - f"The source of skill '{skill_name}' no longer holds a valid " - "skill. The installed copy was kept." - ), + raise Unprocessable( + f"The source of skill '{skill_name}' no longer holds a valid " + "skill. The installed copy was kept." ) if info is None: - raise HTTPException( - status_code=404, - detail=f"Skill '{skill_name}' is not installed", - ) + raise NotFound(f"Skill '{skill_name}' is not installed") return UpdateSkillResponse( message=f"Skill '{skill_name}' updated", skill=InstalledSkillResponse.from_skill_info(info), diff --git a/openhands-agent-server/openhands/agent_server/vscode_router.py b/openhands-agent-server/openhands/agent_server/vscode_router.py index 8bfc7b26fe0..ca6f74ff14e 100644 --- a/openhands-agent-server/openhands/agent_server/vscode_router.py +++ b/openhands-agent-server/openhands/agent_server/vscode_router.py @@ -1,9 +1,10 @@ """VSCode router for agent server API endpoints.""" -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter from pydantic import BaseModel from openhands.agent_server.vscode_service import get_vscode_service +from openhands.sdk.errors import OperationFailed, Unavailable from openhands.sdk.logger import get_logger @@ -37,11 +38,8 @@ async def get_vscode_url( """ vscode_service = get_vscode_service() if vscode_service is None: - raise HTTPException( - status_code=503, - detail=( - "VSCode is disabled in configuration. Set enable_vscode=true to enable." - ), + raise Unavailable( + "VSCode is disabled in configuration. Set enable_vscode=true to enable." ) try: @@ -49,7 +47,7 @@ async def get_vscode_url( return VSCodeUrlResponse(url=url) except Exception as e: logger.error(f"Error getting VSCode URL: {e}") - raise HTTPException(status_code=500, detail="Failed to get VSCode URL") + raise OperationFailed("Failed to get VSCode URL") @vscode_router.get("/status") @@ -71,4 +69,4 @@ async def get_vscode_status() -> dict[str, bool | str]: return {"running": vscode_service.is_running(), "enabled": True} except Exception as e: logger.error(f"Error getting VSCode status: {e}") - raise HTTPException(status_code=500, detail="Failed to get VSCode status") + raise OperationFailed("Failed to get VSCode status") diff --git a/openhands-agent-server/openhands/agent_server/workspace_router.py b/openhands-agent-server/openhands/agent_server/workspace_router.py index 506627d30b3..4d37e48f0fa 100644 --- a/openhands-agent-server/openhands/agent_server/workspace_router.py +++ b/openhands-agent-server/openhands/agent_server/workspace_router.py @@ -15,11 +15,13 @@ from pathlib import Path from uuid import UUID -from fastapi import APIRouter, Depends, HTTPException, status +from fastapi import APIRouter, Depends from fastapi.responses import FileResponse from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service +from openhands.agent_server.errors import error_responses +from openhands.sdk.errors import Invalid, NotFound from openhands.sdk.logger import get_logger from openhands.sdk.workspace import LocalWorkspace @@ -44,22 +46,13 @@ async def _resolve_workspace_dir( ) -> Path: event_service = await conversation_service.get_event_service(conversation_id) if event_service is None: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail=f"Conversation not found: {conversation_id}", - ) + raise NotFound(f"Conversation not found: {conversation_id}") workspace = event_service.stored.workspace if not isinstance(workspace, LocalWorkspace): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Conversation workspace is not local; cannot be served", - ) + raise NotFound("Conversation workspace is not local; cannot be served") workspace_dir = Path(workspace.working_dir).resolve() if not workspace_dir.is_dir(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="Workspace directory does not exist", - ) + raise NotFound("Workspace directory does not exist") return workspace_dir @@ -70,10 +63,7 @@ def _resolve_target(workspace_dir: Path, file_path: str) -> Path: """ candidate = (workspace_dir / file_path).resolve() if candidate != workspace_dir and not candidate.is_relative_to(workspace_dir): - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Path is outside the workspace", - ) + raise Invalid("Path is outside the workspace") return candidate @@ -86,23 +76,17 @@ def _serve_path(workspace_dir: Path, file_path: str) -> FileResponse: workspace_dir, str(target.relative_to(workspace_dir) / "index.html") ) if not index_file.is_file(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="No index.html in directory", - ) + raise NotFound("No index.html in directory") return FileResponse(path=index_file) if not target.is_file(): - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="File not found", - ) + raise NotFound("File not found") return FileResponse(path=target) @workspace_router.get( "/{conversation_id}/workspace", - responses={404: {"description": "File or conversation not found"}}, + responses=error_responses({NotFound: "File or conversation not found"}), ) async def serve_workspace_root( conversation_id: UUID, @@ -115,7 +99,7 @@ async def serve_workspace_root( @workspace_router.get( "/{conversation_id}/workspace/{file_path:path}", - responses={404: {"description": "File or conversation not found"}}, + responses=error_responses({NotFound: "File or conversation not found"}), ) async def serve_workspace_file( conversation_id: UUID, diff --git a/openhands-agent-server/openhands/agent_server/workspaces_router.py b/openhands-agent-server/openhands/agent_server/workspaces_router.py index 5ee50edc587..0a9a5493d11 100644 --- a/openhands-agent-server/openhands/agent_server/workspaces_router.py +++ b/openhands-agent-server/openhands/agent_server/workspaces_router.py @@ -8,7 +8,7 @@ from typing import Annotated -from fastapi import APIRouter, HTTPException, Query, Request, status +from fastapi import APIRouter, Query, Request from pydantic import BaseModel, ConfigDict, Field from openhands.agent_server._secrets_exposure import get_config @@ -18,6 +18,7 @@ WorkspaceParentItem, get_workspaces_store, ) +from openhands.sdk.errors import Conflict, NotFound, OperationFailed from openhands.sdk.logger import get_logger @@ -68,17 +69,14 @@ async def list_workspaces(request: Request) -> WorkspacesListResponse: persisted = store.load() except (OSError, PermissionError): logger.error("Workspaces list failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to read workspaces") + raise OperationFailed("Failed to read workspaces") if persisted is None: # ``load()`` collapses "file missing" and "file present but # unreadable/corrupted/future-schema" into the same ``None``. Returning # an empty list for the second case would hide the user's data and let # a subsequent POST overwrite the still-on-disk file with defaults. if store._path.exists(): - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Workspaces file is corrupted", - ) + raise Conflict("Workspaces file is corrupted") persisted = PersistedWorkspaces() return _to_response(persisted) @@ -116,13 +114,10 @@ def apply(current: PersistedWorkspaces) -> PersistedWorkspaces: updated = store.update(apply) except RuntimeError as e: logger.error(f"Workspaces add blocked: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Workspaces file is corrupted", - ) + raise Conflict("Workspaces file is corrupted") except (OSError, PermissionError): logger.error("Workspaces add failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to save workspaces") + raise OperationFailed("Failed to save workspaces") return _to_response(updated) @@ -150,16 +145,13 @@ def apply(current: PersistedWorkspaces) -> PersistedWorkspaces: store.update(apply) except RuntimeError as e: logger.error(f"Workspaces delete blocked: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Workspaces file is corrupted", - ) + raise Conflict("Workspaces file is corrupted") except (OSError, PermissionError): logger.error("Workspaces delete failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to update workspaces") + raise OperationFailed("Failed to update workspaces") if not removed: - raise HTTPException(status_code=404, detail="Workspace not found") + raise NotFound("Workspace not found") return DeleteResponse() @@ -197,13 +189,10 @@ def apply(current: PersistedWorkspaces) -> PersistedWorkspaces: updated = store.update(apply) except RuntimeError as e: logger.error(f"Workspace parents add blocked: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Workspaces file is corrupted", - ) + raise Conflict("Workspaces file is corrupted") except (OSError, PermissionError): logger.error("Workspace parents add failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to save workspaces") + raise OperationFailed("Failed to save workspaces") return _to_response(updated) @@ -231,14 +220,11 @@ def apply(current: PersistedWorkspaces) -> PersistedWorkspaces: store.update(apply) except RuntimeError as e: logger.error(f"Workspace parents delete blocked: {e}") - raise HTTPException( - status_code=status.HTTP_409_CONFLICT, - detail="Workspaces file is corrupted", - ) + raise Conflict("Workspaces file is corrupted") except (OSError, PermissionError): logger.error("Workspace parents delete failed - file I/O error") - raise HTTPException(status_code=500, detail="Failed to update workspaces") + raise OperationFailed("Failed to update workspaces") if not removed: - raise HTTPException(status_code=404, detail="Workspace parent not found") + raise NotFound("Workspace parent not found") return DeleteResponse() diff --git a/openhands-sdk/openhands/sdk/AGENTS.md b/openhands-sdk/openhands/sdk/AGENTS.md index c81e58bd5e2..0af78078266 100644 --- a/openhands-sdk/openhands/sdk/AGENTS.md +++ b/openhands-sdk/openhands/sdk/AGENTS.md @@ -78,6 +78,7 @@ When modifying event types (e.g., `TextContent`, `Message`, or any Pydantic mode ```python from openhands.sdk.utils.deprecation import handle_deprecated_model_fields + class MyModel(BaseModel): model_config = ConfigDict(extra="forbid") diff --git a/openhands-sdk/openhands/sdk/errors.py b/openhands-sdk/openhands/sdk/errors.py new file mode 100644 index 00000000000..29b4073c3e8 --- /dev/null +++ b/openhands-sdk/openhands/sdk/errors.py @@ -0,0 +1,134 @@ +"""Domain errors: expected failures a caller can act on. + +Stores and services raise these instead of transport-specific errors. A +transport maps each category to its own response once; the agent server does +it in ``openhands.agent_server.errors``. Nothing in this module knows about +HTTP, and it imports nothing from the SDK so any layer can raise from it. + +The categories are deliberately few. Pick the one that says what the caller +should do: fix the reference (``NotFound``), resolve the clash (``Conflict``), +fix the input (``Invalid``), retry later (``Busy``, ``RateLimited``, +``Unavailable``), or report the failure (``OperationFailed``). +""" + +from collections.abc import Mapping, Sequence + + +__all__ = [ + "Busy", + "Conflict", + "DomainError", + "ErrorDetail", + "Forbidden", + "Gone", + "Invalid", + "LockTimeout", + "Misdirected", + "NotFound", + "NotSupported", + "OperationFailed", + "RateLimited", + "Unauthenticated", + "Unavailable", + "Unprocessable", + "UpstreamFailed", + "UpstreamTimeout", +] + + +# What a client is shown: a sentence, or a small structured payload such as +# ``{"code": ..., "message": ...}`` that a client can branch on. +type ErrorDetail = str | Mapping[str, object] | Sequence[object] + + +class DomainError(Exception): + """Base of the domain error hierarchy. + + Args: + detail: What the client is shown. ``None`` lets the transport use its + default wording for the category. + message: What logs and ``str(exc)`` show, when it should differ from + ``detail`` (for example a lock timeout whose client-facing detail + is just "busy, retry"). Defaults to ``detail`` when it is a string. + extra: Additional top-level fields for the client, next to the detail. + retry_after: Seconds (or an HTTP date) after which a retry may succeed. + """ + + def __init__( + self, + detail: ErrorDetail | None = None, + *, + message: str | None = None, + extra: Mapping[str, object] | None = None, + retry_after: str | None = None, + ) -> None: + if message is None: + message = detail if isinstance(detail, str) else "" + super().__init__(message) + self.detail = detail + self.extra: Mapping[str, object] = extra or {} + self.retry_after = retry_after + + +class NotFound(DomainError): + """The referenced item does not exist.""" + + +class Gone(DomainError): + """The item existed but is no longer available (archived, removed).""" + + +class Conflict(DomainError): + """The request clashes with the current state (exists, running, in use).""" + + +class Invalid(DomainError, ValueError): + """The request is malformed. Also a ``ValueError`` for existing callers.""" + + +class Unprocessable(Invalid): + """The request is well formed but cannot be acted on as given.""" + + +class Unauthenticated(DomainError): + """The caller did not prove who it is.""" + + +class Forbidden(DomainError): + """The caller is known but not allowed to do this.""" + + +class Busy(DomainError): + """A shared resource is held by someone else; retry shortly.""" + + +class LockTimeout(Busy, TimeoutError): + """A store lock wait timed out. Also a ``TimeoutError`` for existing callers.""" + + +class RateLimited(DomainError): + """The caller has used its allowance or capacity; back off and retry.""" + + +class Unavailable(DomainError): + """A dependency is not configured or not ready.""" + + +class NotSupported(DomainError): + """This deployment does not implement the operation.""" + + +class Misdirected(DomainError): + """The request reached a server that cannot answer for this target.""" + + +class UpstreamFailed(DomainError): + """A service this one depends on failed or answered unusably.""" + + +class UpstreamTimeout(UpstreamFailed): + """A service this one depends on did not answer in time.""" + + +class OperationFailed(DomainError): + """The operation failed for a reason the caller cannot fix.""" diff --git a/openhands-sdk/openhands/sdk/extensions/installation/README.md b/openhands-sdk/openhands/sdk/extensions/installation/README.md index 3c605fca421..ea664c4ced9 100644 --- a/openhands-sdk/openhands/sdk/extensions/installation/README.md +++ b/openhands-sdk/openhands/sdk/extensions/installation/README.md @@ -23,17 +23,17 @@ from openhands.sdk.extensions.installation import ( InstallationManager, ) + class Widget(BaseModel): name: str version: str description: str + class WidgetLoader(InstallationInterface[Widget]): @staticmethod def load_from_dir(extension_dir: Path) -> Widget: - return Widget.model_validate_json( - (extension_dir / "widget.json").read_text() - ) + return Widget.model_validate_json((extension_dir / "widget.json").read_text()) ``` ### 2. Create a manager @@ -56,15 +56,15 @@ info = manager.install("/path/to/local/widget") info = manager.install("github:owner/my-widget", force=True) # List / load -all_info = manager.list_installed() # List[InstallationInfo] -widgets = manager.load_installed() # List[Widget] (enabled only) +all_info = manager.list_installed() # List[InstallationInfo] +widgets = manager.load_installed() # List[Widget] (enabled only) # Enable / disable -manager.disable("my-widget") # excluded from load_installed() -manager.enable("my-widget") # included again +manager.disable("my-widget") # excluded from load_installed() +manager.enable("my-widget") # included again # Look up a single extension -info = manager.get("my-widget") # InstallationInfo | None +info = manager.get("my-widget") # InstallationInfo | None # Update to latest from the original source info = manager.update("my-widget") diff --git a/openhands-sdk/openhands/sdk/llm/llm_profile_store.py b/openhands-sdk/openhands/sdk/llm/llm_profile_store.py index 62c58c5c4d0..fa3b6f9db05 100644 --- a/openhands-sdk/openhands/sdk/llm/llm_profile_store.py +++ b/openhands-sdk/openhands/sdk/llm/llm_profile_store.py @@ -12,6 +12,7 @@ from filelock import FileLock, Timeout +from openhands.sdk.errors import Invalid, LockTimeout from openhands.sdk.llm.utils.openhands_provider import ( canonicalize_openhands_llm_payload, ) @@ -179,8 +180,9 @@ def _acquire_lock(self, timeout: float = _LOCK_TIMEOUT_SECONDS) -> Iterator[None yield except Timeout: logger.error(f"[Profile Store] Failed to acquire lock within {timeout}s") - raise TimeoutError( - f"Profile store lock acquisition timed out after {timeout}s" + raise LockTimeout( + "Profile store is busy. Please retry.", + message=f"Profile store lock acquisition timed out after {timeout}s", ) def list(self) -> list[str]: @@ -203,7 +205,7 @@ def _get_profile_path(self, name: str) -> Path: """ clean_name = canonical_profile_name(name) if not PROFILE_NAME_REGEX.match(clean_name): - raise ValueError( + raise Invalid( f"Invalid profile name: {name!r}. " "Profile names must be 1-64 characters, start with a letter " "or digit, and contain only letters, digits, '.', '_', or '-'." @@ -353,7 +355,7 @@ def load( raise except Exception as e: # Re-raise as ValueError for clearer error handling - raise ValueError(f"Failed to load profile `{name}`: {e}") from e + raise Invalid(f"Failed to load profile `{name}`: {e}") from e logger.info(f"[Profile Store] Loaded profile `{name}` from {profile_path}") diff --git a/openhands-sdk/openhands/sdk/llm/meta_profile_store.py b/openhands-sdk/openhands/sdk/llm/meta_profile_store.py index 3b64c900010..d6762fe5a9c 100644 --- a/openhands-sdk/openhands/sdk/llm/meta_profile_store.py +++ b/openhands-sdk/openhands/sdk/llm/meta_profile_store.py @@ -20,6 +20,7 @@ from filelock import FileLock, Timeout from pydantic import BaseModel, Field, model_validator +from openhands.sdk.errors import Invalid, LockTimeout from openhands.sdk.llm.llm_profile_store import PROFILE_NAME_REGEX from openhands.sdk.logger import get_logger from openhands.sdk.utils.path import get_user_persistence_dir @@ -140,8 +141,11 @@ def _acquire_lock(self, timeout: float = _LOCK_TIMEOUT_SECONDS) -> Iterator[None logger.error( f"[Meta-profile Store] Failed to acquire lock within {timeout}s" ) - raise TimeoutError( - f"Meta-profile store lock acquisition timed out after {timeout}s" + raise LockTimeout( + "Meta-profile store is busy. Please retry.", + message=( + f"Meta-profile store lock acquisition timed out after {timeout}s" + ), ) def list(self) -> list[str]: @@ -160,7 +164,7 @@ def list(self) -> list[str]: def _get_path(self, name: str) -> Path: clean_name = name.removesuffix(".json") if not PROFILE_NAME_REGEX.match(clean_name): - raise ValueError( + raise Invalid( f"Invalid meta-profile name: {name!r}. " "Names must be 1-64 characters, start with a letter or digit, " "and contain only letters, digits, '.', '_', or '-'." @@ -185,7 +189,7 @@ def load(self, name: str) -> MetaProfile: data = json.loads(path.read_text(encoding="utf-8")) return MetaProfile.model_validate(data) except Exception as e: - raise ValueError(f"Failed to load meta-profile `{name}`: {e}") from e + raise Invalid(f"Failed to load meta-profile `{name}`: {e}") from e def save( self, diff --git a/openhands-sdk/openhands/sdk/llm/provider_connection_store.py b/openhands-sdk/openhands/sdk/llm/provider_connection_store.py index 32536844dc6..bd57beeac83 100644 --- a/openhands-sdk/openhands/sdk/llm/provider_connection_store.py +++ b/openhands-sdk/openhands/sdk/llm/provider_connection_store.py @@ -34,10 +34,12 @@ ConfigDict, Field, SecretStr, + ValidationError, field_serializer, field_validator, ) +from openhands.sdk.errors import Invalid, LockTimeout, Unprocessable from openhands.sdk.logger import get_logger from openhands.sdk.utils.pydantic_secrets import is_redacted_secret, serialize_secret @@ -65,16 +67,17 @@ class ProviderConnectionLimitExceeded(Exception): """Raised when creating a connection would exceed the configured limit.""" -class ProviderConnectionNotFound(ValueError): +class ProviderConnectionNotFound(Unprocessable): """A referenced provider connection id does not exist. Raised by :meth:`LLMProfileStore.load` when a profile points at a connection that has been deleted and the profile has no usable inline key to fall back on. - Subclasses :class:`ValueError` so every ``load()`` caller degrades sensibly - even without a dedicated ``except``. The profile-activation and settings - endpoints (via ``store_errors``) map it to 422, and the OpenAI-compatible + An :class:`~openhands.sdk.errors.Unprocessable` (so also a + :class:`ValueError`) so every ``load()`` caller degrades sensibly even + without a dedicated ``except``. The agent server answers it with 422 from + the domain error table, and the OpenAI-compatible gateway's ``except ValueError`` turns it into a 400 instead of an opaque 500. The agent-profile launch path already funnels load failures through its resolver's ``ValueError`` handling; that path can't actually hit a @@ -171,8 +174,12 @@ def _acquire_lock(self, timeout: float = _LOCK_TIMEOUT_SECONDS) -> Iterator[None logger.error( f"[Provider Connections] Failed to acquire lock within {timeout}s" ) - raise TimeoutError( - f"Provider connection store lock acquisition timed out after {timeout}s" + raise LockTimeout( + "Profile store is busy. Please retry.", + message=( + "Provider connection store lock acquisition timed out after " + f"{timeout}s" + ), ) def _read(self, *, cipher: Cipher | None) -> PersistedProviderConnections: @@ -187,20 +194,23 @@ def _read(self, *, cipher: Cipher | None) -> PersistedProviderConnections: try: raw = json.loads(self._path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError) as e: - raise ValueError(f"Provider connections file is unreadable: {e}") from e + raise Invalid(f"Provider connections file is unreadable: {e}") from e if not isinstance(raw, dict): - raise ValueError("Provider connections file must contain a JSON object") + raise Invalid("Provider connections file must contain a JSON object") version = raw.get("schema_version", PROVIDER_CONNECTIONS_SCHEMA_VERSION) if not isinstance(version, int): - raise ValueError("schema_version must be an integer") + raise Invalid("schema_version must be an integer") if version > PROVIDER_CONNECTIONS_SCHEMA_VERSION: - raise ValueError( + raise Invalid( f"schema_version {version} is newer than supported " f"{PROVIDER_CONNECTIONS_SCHEMA_VERSION}" ) raw["schema_version"] = PROVIDER_CONNECTIONS_SCHEMA_VERSION context = {"cipher": cipher} if cipher else None - return PersistedProviderConnections.model_validate(raw, context=context) + try: + return PersistedProviderConnections.model_validate(raw, context=context) + except ValidationError as e: + raise Invalid(str(e)) from e def _write( self, persisted: PersistedProviderConnections, *, cipher: Cipher | None @@ -241,13 +251,11 @@ def create( self, connection: ProviderConnection, *, cipher: Cipher | None = None ) -> ProviderConnection: if not CONNECTION_ID_REGEX.match(connection.id): - raise ValueError(f"Invalid provider connection id: {connection.id!r}") + raise Invalid(f"Invalid provider connection id: {connection.id!r}") with self._acquire_lock(): persisted = self._read(cipher=cipher) if any(c.id == connection.id for c in persisted.connections): - raise ValueError( - f"Provider connection {connection.id!r} already exists" - ) + raise Invalid(f"Provider connection {connection.id!r} already exists") if len(persisted.connections) >= MAX_PROVIDER_CONNECTIONS: raise ProviderConnectionLimitExceeded( f"Provider connection limit reached ({MAX_PROVIDER_CONNECTIONS})." diff --git a/openhands-sdk/openhands/sdk/profiles/agent_profile_store.py b/openhands-sdk/openhands/sdk/profiles/agent_profile_store.py index ed8a50c03a6..b7cc413a921 100644 --- a/openhands-sdk/openhands/sdk/profiles/agent_profile_store.py +++ b/openhands-sdk/openhands/sdk/profiles/agent_profile_store.py @@ -13,6 +13,7 @@ from filelock import FileLock, Timeout +from openhands.sdk.errors import Invalid, LockTimeout from openhands.sdk.logger import get_logger from openhands.sdk.profiles.agent_profile import validate_agent_profile from openhands.sdk.utils.path import get_user_persistence_dir @@ -88,8 +89,11 @@ def _acquire_lock(self, timeout: float = _LOCK_TIMEOUT_SECONDS) -> Iterator[None yield except Timeout: logger.error(f"[AgentProfile Store] Failed to acquire lock in {timeout}s") - raise TimeoutError( - f"Agent profile store lock acquisition timed out after {timeout}s" + raise LockTimeout( + "Profile store is busy. Please retry.", + message=( + f"Agent profile store lock acquisition timed out after {timeout}s" + ), ) def lock( @@ -118,7 +122,7 @@ def _get_profile_path(self, name: str) -> Path: """ clean_name = canonical_profile_name(name) if not PROFILE_NAME_REGEX.match(clean_name): - raise ValueError( + raise Invalid( f"Invalid profile name: {name!r}. " "Profile names must be 1-64 characters, start with a letter " "or digit, and contain only letters, digits, '.', '_', or '-'." @@ -216,7 +220,7 @@ def load( data = json.loads(profile_path.read_text()) profile = validate_agent_profile(data) except Exception as e: - raise ValueError(f"Failed to load profile `{name}`: {e}") from e + raise Invalid(f"Failed to load profile `{name}`: {e}") from e logger.info( f"[AgentProfile Store] Loaded profile `{name}` from {profile_path}" @@ -266,7 +270,10 @@ def rename(self, old_name: str, new_name: str) -> None: if new_path.exists() and not case_only: raise FileExistsError(f"Profile `{new_name}` already exists") - data = json.loads(old_path.read_text()) + try: + data = json.loads(old_path.read_text()) + except json.JSONDecodeError as e: + raise Invalid(str(e)) from e if isinstance(data, dict): data["name"] = new_stem self._atomic_write(new_path, json.dumps(data, indent=2)) diff --git a/openhands-sdk/openhands/sdk/profiles/profile_refs.py b/openhands-sdk/openhands/sdk/profiles/profile_refs.py index a8259eaa064..5d15754c940 100644 --- a/openhands-sdk/openhands/sdk/profiles/profile_refs.py +++ b/openhands-sdk/openhands/sdk/profiles/profile_refs.py @@ -18,6 +18,7 @@ from typing import TYPE_CHECKING +from openhands.sdk.errors import Invalid from openhands.sdk.llm.llm_profile_store import canonical_profile_name from openhands.sdk.logger import get_logger from openhands.sdk.profiles.agent_profile_store import PROFILE_NAME_REGEX @@ -49,7 +50,7 @@ def __init__(self, referrers: list[str]) -> None: def _validate_name(name: str) -> None: """Reject names that are not legal profile keys (path traversal etc.).""" if not PROFILE_NAME_REGEX.match(name): - raise ValueError(f"Invalid profile name: {name!r}.") + raise Invalid(f"Invalid profile name: {name!r}.") def _scan_referrers( diff --git a/tests/agent_server/canvas_extensions/test_canvas_extension_backend.py b/tests/agent_server/canvas_extensions/test_canvas_extension_backend.py index 523a83d9354..305e52ec71f 100644 --- a/tests/agent_server/canvas_extensions/test_canvas_extension_backend.py +++ b/tests/agent_server/canvas_extensions/test_canvas_extension_backend.py @@ -18,6 +18,7 @@ from fastapi.testclient import TestClient from httpx import ASGITransport, AsyncClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.canvas_extensions.backend import ( BackendSecretGrantRequest, CanvasExtensionBackendManager, @@ -395,6 +396,7 @@ async def test_prepare_rejects_artifact_that_is_not_a_gzip_tarball( def test_prepare_endpoint_refuses_non_gzip_artifact_with_409(tmp_path: Path): manager, revision = _install_with_artifact_bytes(tmp_path, b"not a tarball\n") app = FastAPI() + add_domain_error_handler(app) app.state.canvas_extension_backend_manager = manager app.include_router(canvas_extensions_router) @@ -885,6 +887,7 @@ def test_backend_http_lifecycle_and_data_deletion( ) manager = CanvasExtensionBackendManager(installed_dir, tmp_path / "state") app = FastAPI() + add_domain_error_handler(app) app.state.canvas_extension_backend_manager = manager app.include_router(canvas_extensions_router) @@ -1041,6 +1044,7 @@ def test_secret_grant_api_requires_exact_names_and_revokes(tmp_path: Path): install_canvas_extension(str(source), installed_dir=installed) manager = CanvasExtensionBackendManager(installed, tmp_path / "state") app = FastAPI() + add_domain_error_handler(app) app.state.canvas_extension_backend_manager = manager app.include_router(canvas_extensions_router, prefix="/api") base = "/api/canvas-extensions/installed/my-extension/backend" @@ -1082,6 +1086,7 @@ async def test_secret_revoke_api_invalidates_bridge_session(tmp_path: Path): manager = CanvasExtensionBackendManager(tmp_path / "installed", tmp_path / "state") sessions = AppBackendSessionStore() app = FastAPI() + add_domain_error_handler(app) app.state.canvas_extension_backend_manager = manager app.state.app_backend_session_store = sessions app.include_router(canvas_extensions_router, prefix="/api") @@ -1141,6 +1146,7 @@ async def test_enable_orchestrates_backend_and_retains_revision_consent( installed, tmp_path / "state", secrets_store=store ) app = FastAPI() + add_domain_error_handler(app) app.state.canvas_extension_backend_manager = manager app.state.app_backend_session_store = AppBackendSessionStore() app.include_router(canvas_extensions_router, prefix="/api") diff --git a/tests/agent_server/canvas_extensions/test_canvas_extension_bridge.py b/tests/agent_server/canvas_extensions/test_canvas_extension_bridge.py index ebf1ca10700..bd95dc8d6d3 100644 --- a/tests/agent_server/canvas_extensions/test_canvas_extension_bridge.py +++ b/tests/agent_server/canvas_extensions/test_canvas_extension_bridge.py @@ -26,6 +26,7 @@ from fastapi.responses import JSONResponse, RedirectResponse, StreamingResponse from websockets.typing import Subprotocol +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.canvas_extensions.bridge import ( APP_BACKEND_SESSION_COOKIE_NAME, APP_BACKEND_SESSION_TTL_SECONDS, @@ -143,6 +144,7 @@ async def _live_bridge( stream_closed = threading.Event() backend_observation: dict[str, str | None] = {} backend = FastAPI() + add_domain_error_handler(backend) @backend.get("/prefix/static/app.js") async def static_asset(request: Request) -> JSONResponse: @@ -203,6 +205,7 @@ async def protocol_endpoint(websocket: WebSocket) -> None: bridge_port = _free_port() public_url = f"https://127.0.0.1:{bridge_port}" app = FastAPI() + add_domain_error_handler(app) app.state.config = Config( session_api_keys=[CONTROL_KEY], allow_cors_origins=[CANVAS_ORIGIN], @@ -570,6 +573,7 @@ async def test_untrusted_forwarded_proto_does_not_change_origin_on_launch_config monkeypatch.setenv("OPENHANDS_AGENT_SERVER_CONFIG_PATH", str(config_file)) backend = FastAPI() + add_domain_error_handler(backend) @backend.get("/echo") async def echo() -> JSONResponse: @@ -579,6 +583,7 @@ async def echo() -> JSONResponse: bridge_port = _free_port() public_url = f"{public_scheme}://127.0.0.1:{bridge_port}" app = FastAPI() + add_domain_error_handler(app) app.state.config = Config( session_api_keys=[CONTROL_KEY], allow_cors_origins=[CANVAS_ORIGIN], @@ -641,4 +646,9 @@ async def test_unreachable_backend_error_names_the_canvas_backend( unreachable = await client.get(f"{root}/prefix/static/app.js") assert unreachable.status_code == 502 - assert unreachable.json() == {"detail": "Canvas App backend unreachable"} + # 5xx details are not shown to clients; the server log and ``exception`` + # field carry them, as for every 5xx the agent server answers. + assert unreachable.json() == { + "detail": "Internal Server Error", + "exception": "502: Canvas App backend unreachable", + } diff --git a/tests/agent_server/canvas_extensions/test_canvas_extension_bridge_routes.py b/tests/agent_server/canvas_extensions/test_canvas_extension_bridge_routes.py index fb82713bbbe..d45048916b9 100644 --- a/tests/agent_server/canvas_extensions/test_canvas_extension_bridge_routes.py +++ b/tests/agent_server/canvas_extensions/test_canvas_extension_bridge_routes.py @@ -8,6 +8,7 @@ from starlette.websockets import WebSocketDisconnect from openhands.agent_server import canvas_extensions_bridge_router as bridge_router +from openhands.agent_server.api import add_domain_error_handler APP_NAME = "demo-app" @@ -30,6 +31,7 @@ async def fake_websocket( monkeypatch.setattr(bridge_router, "proxy_app_backend_http", fake_http) monkeypatch.setattr(bridge_router, "proxy_app_backend_websocket", fake_websocket) app = FastAPI() + add_domain_error_handler(app) app.include_router(bridge_router.app_backend_bridge_router) return TestClient(app), paths diff --git a/tests/agent_server/docker_runtime/test_proxy.py b/tests/agent_server/docker_runtime/test_proxy.py index 8692e5801a4..89e23009755 100644 --- a/tests/agent_server/docker_runtime/test_proxy.py +++ b/tests/agent_server/docker_runtime/test_proxy.py @@ -89,9 +89,9 @@ async def test_http_setup_failure_closes_client_and_preserves_cancellation( monkeypatch, failure ): import httpx - from fastapi import HTTPException from openhands.agent_server.docker_runtime import proxy + from openhands.sdk.errors import UpstreamFailed errors = { "ReadTimeout": httpx.ReadTimeout, @@ -105,11 +105,9 @@ def respond(request): client = httpx.AsyncClient(transport=httpx.MockTransport(respond)) monkeypatch.setattr(proxy.httpx, "AsyncClient", lambda **kwargs: client) - expected = asyncio.CancelledError if failure == "cancel" else HTTPException - with pytest.raises(expected) as raised: + expected = asyncio.CancelledError if failure == "cancel" else UpstreamFailed + with pytest.raises(expected): await proxy.proxy_http(*request_and_target(), upstream_path="/api/test") - if isinstance(raised.value, HTTPException): - assert raised.value.status_code == 502 assert client.is_closed diff --git a/tests/agent_server/docker_runtime/test_retention.py b/tests/agent_server/docker_runtime/test_retention.py index 901345412cc..718b9302c0a 100644 --- a/tests/agent_server/docker_runtime/test_retention.py +++ b/tests/agent_server/docker_runtime/test_retention.py @@ -4,7 +4,6 @@ from uuid import UUID, uuid4 import pytest -from fastapi import HTTPException from pydantic import SecretStr from openhands.agent_server.config import Config @@ -14,7 +13,9 @@ DockerConversationRegistry, RuntimeArchivedError, ) +from openhands.agent_server.errors import status_for from openhands.agent_server.models import ConversationRuntimeStatus +from openhands.sdk.errors import DomainError DAY = 86400 @@ -128,9 +129,9 @@ def no_docker(_conversation_id): monkeypatch.setattr(runtime, "_build_container", no_docker) with pytest.raises(RuntimeArchivedError): await runtime.get_or_create(conversation_id) - with pytest.raises(HTTPException) as raised: + with pytest.raises(DomainError) as raised: await routers._container(runtime, conversation_id) - assert raised.value.status_code == 410 + assert status_for(raised.value) == 410 @pytest.mark.asyncio diff --git a/tests/agent_server/docker_runtime/test_routes.py b/tests/agent_server/docker_runtime/test_routes.py index 1dc89106f88..59ccb3c2253 100644 --- a/tests/agent_server/docker_runtime/test_routes.py +++ b/tests/agent_server/docker_runtime/test_routes.py @@ -13,7 +13,7 @@ from starlette.responses import Response from starlette.routing import Match -from openhands.agent_server.api import create_app +from openhands.agent_server.api import add_domain_error_handler, create_app from openhands.agent_server.config import Config from openhands.agent_server.docker_runtime import routers from openhands.agent_server.docker_runtime.provisioning import RuntimeProvisioningStore @@ -114,6 +114,7 @@ def test_root_conversation_proxy_preserves_canonical_path(tmp_path, monkeypatch) secret_key=SecretStr("outer-key"), ) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = DockerConversationRegistry(config) app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -157,6 +158,7 @@ def test_worktree_start_forwards_only_mounted_host_paths( secret_key=SecretStr("outer-key"), ) app = FastAPI() + add_domain_error_handler(app) registry = DockerConversationRegistry(config) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() @@ -213,6 +215,7 @@ async def stop(conversation_id): stopped.append(conversation_id) app = FastAPI() + add_domain_error_handler(app) registry = DockerConversationRegistry(config) registry.stop = stop app.state.conversation_registry = registry @@ -265,6 +268,7 @@ def test_runtime_release_prunes_cache_but_keeps_conversation_state( ) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -300,6 +304,7 @@ def test_runtime_info_marks_legacy_local_conversation_non_resumable( (docker_dir / "meta.json").write_text("{}") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.include_router(docker_conversation_router, prefix="/api") with TestClient(app) as client: @@ -335,6 +340,7 @@ def test_docker_event_history_reads_persistence_without_starting_a_container( search_events=AsyncMock(return_value={"items": [], "next_page_id": None}) ) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = SimpleNamespace( get_persisted_event_service=AsyncMock(return_value=event_service), @@ -373,6 +379,7 @@ def test_delete_stops_runtime_before_removing_outer_owned_state(tmp_path, monkey registry.stop = AsyncMock() app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -443,6 +450,7 @@ def test_delete_unregisters_host_worktree_before_removing_runtime( registry.stop = AsyncMock() app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -541,6 +549,7 @@ def fail_conversation_delete(path): monkeypatch.setattr(routers, "safe_rmtree", fail_conversation_delete) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -699,6 +708,7 @@ def _docker_start_app( ) registry = DockerConversationRegistry(config) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = registry app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") @@ -868,6 +878,7 @@ def apply(settings: PersistedSettings) -> PersistedSettings: get_settings_store(config).update(apply) app = FastAPI() + add_domain_error_handler(app) app.state.conversation_registry = DockerConversationRegistry(config) app.state.conversation_service = AsyncMock() app.include_router(docker_conversation_router, prefix="/api") diff --git a/tests/agent_server/stress/conftest.py b/tests/agent_server/stress/conftest.py index 0052ea2d311..a409ce9acde 100644 --- a/tests/agent_server/stress/conftest.py +++ b/tests/agent_server/stress/conftest.py @@ -21,6 +21,7 @@ from fastapi import FastAPI from openhands.agent_server import bash_router as bash_router_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.bash_service import BashEventService from openhands.agent_server.config import Config from openhands.agent_server.conversation_router import conversation_router @@ -85,6 +86,7 @@ def app( returns 200 in the responsiveness canary. """ fastapi_app = FastAPI() + add_domain_error_handler(fastapi_app) fastapi_app.state.config = Config() fastapi_app.state.bash_event_service = bash_service fastapi_app.include_router(server_details_router) diff --git a/tests/agent_server/stress/test_slow_webhook.py b/tests/agent_server/stress/test_slow_webhook.py index 4de818d960e..dc74cc999a5 100644 --- a/tests/agent_server/stress/test_slow_webhook.py +++ b/tests/agent_server/stress/test_slow_webhook.py @@ -32,6 +32,7 @@ from fastapi import FastAPI from openhands.agent_server import bash_router as bash_router_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.bash_service import BashEventService from openhands.agent_server.config import Config, WebhookSpec from openhands.agent_server.conversation_router import conversation_router @@ -126,6 +127,7 @@ def app( conversation_service: ConversationService, bash_service: BashEventService ) -> FastAPI: fastapi_app = FastAPI() + add_domain_error_handler(fastapi_app) fastapi_app.state.config = Config() fastapi_app.include_router(conversation_router, prefix="/api") fastapi_app.include_router(event_router, prefix="/api") @@ -196,6 +198,7 @@ async def test_slow_webhook_does_not_unbound_growth( # but with a webhook-free ConversationService. We need a separate ASGI # client for it. baseline_app = FastAPI() + add_domain_error_handler(baseline_app) baseline_app.state.config = Config() baseline_app.include_router(conversation_router, prefix="/api") baseline_app.include_router(event_router, prefix="/api") diff --git a/tests/agent_server/telemetry/test_telemetry_init_lifecycle.py b/tests/agent_server/telemetry/test_telemetry_init_lifecycle.py index b39811a174b..50dcd312a17 100644 --- a/tests/agent_server/telemetry/test_telemetry_init_lifecycle.py +++ b/tests/agent_server/telemetry/test_telemetry_init_lifecycle.py @@ -20,6 +20,7 @@ DiagnosticEventFactory, build_runtime_properties, ) +from openhands.sdk.errors import DomainError class _RecordingSink: @@ -113,10 +114,8 @@ def _maybe_boom(config): monkeypatch.setattr(init_mod.ConversationService, "get_instance", _maybe_boom) - from fastapi import HTTPException - try: - with pytest.raises(HTTPException): + with pytest.raises(DomainError): await svc.initialize(InitRequest()) assert svc.state == "dormant", "failed init should roll back to dormant" assert recording.events == [], "a failed init must not emit server_started" diff --git a/tests/agent_server/test_acp_router.py b/tests/agent_server/test_acp_router.py index b1f366c0f31..9589cf00d65 100644 --- a/tests/agent_server/test_acp_router.py +++ b/tests/agent_server/test_acp_router.py @@ -13,6 +13,7 @@ from openhands.agent_server import acp_router as acp_router_module from openhands.agent_server.acp_router import acp_router +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.credential_binding import LocalVersionedCredentialBinding from openhands.agent_server.local_secret_resolver import local_secret_resolution @@ -41,6 +42,7 @@ def config(tmp_path: Path) -> Config: @pytest.fixture def client(config: Config) -> Iterator[TestClient]: app = FastAPI() + add_domain_error_handler(app) app.state.config = config app.include_router(acp_router, prefix="/api") with local_secret_resolution(config): diff --git a/tests/agent_server/test_agent_profile_conv_start.py b/tests/agent_server/test_agent_profile_conv_start.py index 430f8eb3ace..c119abd01e6 100644 --- a/tests/agent_server/test_agent_profile_conv_start.py +++ b/tests/agent_server/test_agent_profile_conv_start.py @@ -19,6 +19,7 @@ from fastapi.testclient import TestClient from pydantic import SecretStr, ValidationError +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService @@ -67,6 +68,7 @@ def client(): """TestClient with no auth — conversations router only.""" app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") app.state.config = Config( static_files_path=None, session_api_keys=[], secret_key=None diff --git a/tests/agent_server/test_agent_profiles_router.py b/tests/agent_server/test_agent_profiles_router.py index 9421d36b578..bbeacc230e6 100644 --- a/tests/agent_server/test_agent_profiles_router.py +++ b/tests/agent_server/test_agent_profiles_router.py @@ -20,6 +20,7 @@ from openhands.agent_server.config import Config from openhands.agent_server.persistence import reset_stores from openhands.agent_server.profiles_router import MAX_PROFILES +from openhands.sdk.errors import LockTimeout from openhands.sdk.llm import LLM from openhands.sdk.llm.llm_profile_store import LLMProfileStore from openhands.sdk.profiles import ( @@ -1131,7 +1132,7 @@ def test_seed_preserves_acp_fields(client): def test_list_timeout_returns_503(client, monkeypatch): def boom(self, timeout=0): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(AgentProfileStore, "lock", boom) response = client.get("/api/agent-profiles") @@ -1140,7 +1141,7 @@ def boom(self, timeout=0): def test_save_timeout_returns_503(client, monkeypatch): def boom(self, profile, *, max_profiles=None): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(AgentProfileStore, "save", boom) response = client.post("/api/agent-profiles/x", json={"llm_profile_ref": "y"}) diff --git a/tests/agent_server/test_api_authentication.py b/tests/agent_server/test_api_authentication.py index 7c56cc64da1..5395c9dbe12 100644 --- a/tests/agent_server/test_api_authentication.py +++ b/tests/agent_server/test_api_authentication.py @@ -12,7 +12,9 @@ from openhands.agent_server.api import _find_http_exception, create_app from openhands.agent_server.config import Config from openhands.agent_server.dependencies import get_conversation_service +from openhands.agent_server.errors import status_for from openhands.agent_server.openai.router import _parse_observability_overrides +from openhands.sdk.errors import DomainError @pytest.fixture @@ -163,14 +165,14 @@ def test_openai_observability_headers_parse_to_conversation_overrides(): def test_openai_observability_headers_reject_invalid_span_name(): - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: _parse_observability_overrides( span_name="bad span name", tags=None, metadata=None, ) - assert exc_info.value.status_code == 422 + assert status_for(exc_info.value) == 422 json.dumps(exc_info.value.detail) diff --git a/tests/agent_server/test_bash_router.py b/tests/agent_server/test_bash_router.py index 6c2224a7e88..eb24386418c 100644 --- a/tests/agent_server/test_bash_router.py +++ b/tests/agent_server/test_bash_router.py @@ -5,6 +5,7 @@ from fastapi import FastAPI import openhands.agent_server.bash_service as bash_service_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.bash_router import bash_router from openhands.agent_server.bash_service import BashEventService @@ -12,6 +13,7 @@ @pytest.fixture async def bash_client(tmp_path): app = FastAPI() + add_domain_error_handler(app) app.include_router(bash_router, prefix="/api") app.state.bash_event_service = BashEventService(tmp_path / "bash_events") async with httpx.AsyncClient( diff --git a/tests/agent_server/test_bash_service.py b/tests/agent_server/test_bash_service.py index fce91eab092..ef24d726c69 100644 --- a/tests/agent_server/test_bash_service.py +++ b/tests/agent_server/test_bash_service.py @@ -17,6 +17,7 @@ from fastapi import FastAPI from openhands.agent_server import bash_router as bash_router_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.bash_service import BashEventService from openhands.agent_server.config import Config from openhands.agent_server.models import BashCommand, BashEventSortOrder, BashOutput @@ -37,6 +38,7 @@ async def bash_service(tmp_path: Path) -> AsyncIterator[BashEventService]: @pytest_asyncio.fixture async def client(bash_service: BashEventService) -> AsyncIterator[httpx.AsyncClient]: app = FastAPI() + add_domain_error_handler(app) app.state.config = Config() app.state.bash_event_service = bash_service app.include_router(server_details_router) diff --git a/tests/agent_server/test_canvas_extensions_router.py b/tests/agent_server/test_canvas_extensions_router.py index e266e125126..4713d78404e 100644 --- a/tests/agent_server/test_canvas_extensions_router.py +++ b/tests/agent_server/test_canvas_extensions_router.py @@ -14,6 +14,7 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.canvas_extensions.bridge import AppBackendSessionStore from openhands.agent_server.canvas_extensions.manifest import MANIFEST_FILENAME from openhands.agent_server.canvas_extensions_router import canvas_extensions_router @@ -31,6 +32,7 @@ def client(tmp_path: Path, monkeypatch) -> TestClient: lambda: store, ) app = FastAPI() + add_domain_error_handler(app) app.include_router(canvas_extensions_router) return TestClient(app) @@ -165,6 +167,7 @@ def client_with_sessions(tmp_path: Path, monkeypatch) -> tuple[TestClient, objec lambda: store, ) app = FastAPI() + add_domain_error_handler(app) app.include_router(canvas_extensions_router) sessions = AppBackendSessionStore() app.state.app_backend_session_store = sessions diff --git a/tests/agent_server/test_conversation_response.py b/tests/agent_server/test_conversation_response.py index 874fb8e736d..7b543e45b14 100644 --- a/tests/agent_server/test_conversation_response.py +++ b/tests/agent_server/test_conversation_response.py @@ -10,6 +10,7 @@ from fastapi.testclient import TestClient from pydantic import SecretStr +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service @@ -23,6 +24,7 @@ @pytest.fixture def client(): app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") return TestClient(app) diff --git a/tests/agent_server/test_conversation_router.py b/tests/agent_server/test_conversation_router.py index 429eb83aae5..2c772b418b6 100644 --- a/tests/agent_server/test_conversation_router.py +++ b/tests/agent_server/test_conversation_router.py @@ -9,6 +9,7 @@ from fastapi.testclient import TestClient from pydantic import SecretStr +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.conversation_registry import ConversationRegistry from openhands.agent_server.conversation_router import conversation_router @@ -47,6 +48,7 @@ def client(): """Create a test client for the FastAPI app without authentication.""" app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") # switch_llm reads request.app.state.config to get the optional cipher; # populate it with a no-cipher config so unrelated tests don't 503. diff --git a/tests/agent_server/test_conversation_router_skill_trim.py b/tests/agent_server/test_conversation_router_skill_trim.py index b910fb1a4d9..0ad326bd9bb 100644 --- a/tests/agent_server/test_conversation_router_skill_trim.py +++ b/tests/agent_server/test_conversation_router_skill_trim.py @@ -23,6 +23,7 @@ from fastapi.testclient import TestClient from pydantic import SecretStr +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService @@ -155,6 +156,7 @@ def client(self, heavy_conversation): ) app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") app.state.config = Config( static_files_path=None, session_api_keys=[], secret_key=None @@ -239,6 +241,7 @@ def test_batch_get_handles_null_items(self): service = AsyncMock(spec=ConversationService) service.batch_get_conversations.return_value = [None] app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") app.state.config = Config( static_files_path=None, session_api_keys=[], secret_key=None diff --git a/tests/agent_server/test_conversation_tags.py b/tests/agent_server/test_conversation_tags.py index 41b370b2253..fb5f099b518 100644 --- a/tests/agent_server/test_conversation_tags.py +++ b/tests/agent_server/test_conversation_tags.py @@ -9,6 +9,7 @@ from fastapi.testclient import TestClient from pydantic import SecretStr +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service @@ -28,6 +29,7 @@ @pytest.fixture def client(): app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") return TestClient(app) diff --git a/tests/agent_server/test_credential_binding.py b/tests/agent_server/test_credential_binding.py index d49cfe45545..1287f8953ba 100644 --- a/tests/agent_server/test_credential_binding.py +++ b/tests/agent_server/test_credential_binding.py @@ -13,6 +13,7 @@ from pydantic import SecretStr import openhands.agent_server.event_service as event_service_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.conversation_service import ( ConversationService, CredentialBindingActivationRequired, @@ -199,6 +200,7 @@ def test_activation_route_installs_http_binding( ) -> None: service = ConversationService(conversations_dir=tmp_path / "conversations") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_service = service app.include_router(router, prefix="/api") conversation_id = uuid4() @@ -229,6 +231,7 @@ def test_activation_route_rejects_unavailable_binding( ) -> None: service = ConversationService(conversations_dir=tmp_path / "conversations") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_service = service app.include_router(router, prefix="/api") conversation_id = uuid4() @@ -257,6 +260,7 @@ def test_activation_route_retries_transient_binding_failure( ) -> None: service = ConversationService(conversations_dir=tmp_path / "conversations") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_service = service app.include_router(router, prefix="/api") conversation_id = uuid4() @@ -303,6 +307,7 @@ def test_activation_route_rejects_terminal_binding_failure( ) -> None: service = ConversationService(conversations_dir=tmp_path / "conversations") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_service = service app.include_router(router, prefix="/api") conversation_id = uuid4() @@ -336,6 +341,7 @@ def test_activation_route_rejects_invalid_binding_url( ) -> None: service = ConversationService(conversations_dir=tmp_path / "conversations") app = FastAPI() + add_domain_error_handler(app) app.state.conversation_service = service app.include_router(router, prefix="/api") conversation_id = uuid4() diff --git a/tests/agent_server/test_dependencies.py b/tests/agent_server/test_dependencies.py index b3c6571befc..9b6b37e936c 100644 --- a/tests/agent_server/test_dependencies.py +++ b/tests/agent_server/test_dependencies.py @@ -6,12 +6,14 @@ from fastapi import Depends, FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.dependencies import check_session_api_key def _make_app(session_api_keys: list[str]) -> FastAPI: app = FastAPI() + add_domain_error_handler(app) app.state.config = Config(session_api_keys=session_api_keys) @app.get("/test", dependencies=[Depends(check_session_api_key)]) diff --git a/tests/agent_server/test_domain_errors.py b/tests/agent_server/test_domain_errors.py new file mode 100644 index 00000000000..56ebcec92aa --- /dev/null +++ b/tests/agent_server/test_domain_errors.py @@ -0,0 +1,187 @@ +"""The domain error table answers exactly as the HTTPExceptions it replaced.""" + +from pathlib import Path + +import pytest +from fastapi import FastAPI, HTTPException +from fastapi.testclient import TestClient +from filelock import FileLock + +from openhands.agent_server.api import _add_exception_handlers +from openhands.agent_server.conversation_lease import ConversationOwnershipLostError +from openhands.agent_server.conversation_service import ( + CredentialBindingActivationRequired, +) +from openhands.agent_server.errors import ( + ERROR_STATUS, + ForwardedStatus, + error_for_status, + error_responses, + status_for, +) +from openhands.agent_server.event_service import ConversationRunLimitExceeded +from openhands.sdk.errors import ( + Busy, + Conflict, + DomainError, + Invalid, + LockTimeout, + NotFound, + RateLimited, + Unauthenticated, + Unprocessable, +) +from openhands.sdk.llm.llm_profile_store import LLMProfileStore +from openhands.sdk.llm.meta_profile_store import MetaProfileStore +from openhands.sdk.llm.provider_connection_store import ProviderConnectionNotFound +from openhands.sdk.profiles.agent_profile_store import AgentProfileStore + + +def _client(raise_error: BaseException) -> TestClient: + app = FastAPI() + _add_exception_handlers(app) + + @app.get("/boom") + def boom() -> None: + raise raise_error + + return TestClient(app, raise_server_exceptions=False) + + +def _response(error: BaseException) -> tuple[int, object, str | None]: + response = _client(error).get("/boom") + return response.status_code, response.json(), response.headers.get("retry-after") + + +@pytest.mark.parametrize("category", list(ERROR_STATUS), ids=lambda c: c.__name__) +@pytest.mark.parametrize( + "detail", + ["Profile 'x' not found", {"code": "missing_token", "message": "no token"}], + ids=["text", "structured"], +) +def test_each_category_answers_like_the_http_exception_it_replaced( + category: type[DomainError], detail: str | dict[str, str] +) -> None: + status = ERROR_STATUS[category] + assert _response(category(detail)) == _response(HTTPException(status, detail)) + + +def test_a_missing_detail_uses_the_status_phrase_like_http_exception() -> None: + assert _response(Unauthenticated()) == _response(HTTPException(401)) + + +def test_retry_after_is_sent_like_the_header_it_replaced() -> None: + assert _response(RateLimited("slow down", retry_after="30")) == _response( + HTTPException(429, "slow down", headers={"Retry-After": "30"}) + ) + + +def test_a_domain_error_inside_an_exception_group_is_mapped() -> None: + group = ExceptionGroup("task group", [NotFound("Conversation not found")]) + assert _response(group) == _response(HTTPException(404, "Conversation not found")) + + +def test_forwarded_status_relays_the_upstream_status() -> None: + error = ForwardedStatus(418, "Conversation runtime rejected the request") + assert _response(error) == _response( + HTTPException(418, "Conversation runtime rejected the request") + ) + + +@pytest.mark.parametrize( + ("error", "status", "body"), + [ + # These three had their own handlers in api.py; the bodies are theirs. + ( + ConversationRunLimitExceeded( + "Conversation run limit reached. Retry the request later." + ), + 429, + {"detail": "Conversation run limit reached. Retry the request later."}, + ), + ( + ConversationOwnershipLostError( + conversation_dir=Path("/tmp/c"), owner_instance_id="a", generation=1 + ), + 409, + { + "detail": "Conversation is owned by another agent server instance; " + "the write was refused" + }, + ), + ( + CredentialBindingActivationRequired( + "credential_binding_activation_required" + ), + 409, + {"detail": "credential_binding_activation_required", "retryable": True}, + ), + (ProviderConnectionNotFound("conn-1"), 422, {"detail": "conn-1"}), + ], + ids=["run-limit", "ownership-lost", "binding-activation", "provider-missing"], +) +def test_former_special_cases_keep_their_bodies( + error: DomainError, status: int, body: dict[str, object] +) -> None: + response = _client(error).get("/boom") + assert (response.status_code, response.json()) == (status, body) + + +def test_former_special_cases_keep_their_base_classes() -> None: + assert isinstance(ConversationRunLimitExceeded("x"), RuntimeError) + assert isinstance(CredentialBindingActivationRequired("x"), RuntimeError) + assert isinstance(ProviderConnectionNotFound("x"), ValueError) + assert isinstance(Unprocessable("x"), ValueError) + assert isinstance(LockTimeout("x"), TimeoutError) + + +def test_status_resolves_through_the_nearest_category() -> None: + assert status_for(Unprocessable("x")) == 422 + assert status_for(Invalid("x")) == 400 + assert status_for(LockTimeout("x")) == 503 + assert status_for(ProviderConnectionNotFound("x")) == 422 + + +def test_error_for_status_builds_the_category_or_relays() -> None: + assert type(error_for_status(404, "x")) is NotFound + assert type(error_for_status(503, "x")) is Busy + relayed = error_for_status(418, "x") + assert isinstance(relayed, ForwardedStatus) and status_for(relayed) == 418 + + +def test_error_responses_reads_the_table() -> None: + assert error_responses( + { + NotFound: "Item not found", + ProviderConnectionNotFound: "Dangling", + Conflict: "Busy", + } + ) == { + 404: {"description": "Item not found"}, + 422: {"description": "Dangling"}, + 409: {"description": "Busy"}, + } + + +@pytest.mark.parametrize( + ("make_store", "detail"), + [ + (LLMProfileStore, "Profile store is busy. Please retry."), + (AgentProfileStore, "Profile store is busy. Please retry."), + (MetaProfileStore, "Meta-profile store is busy. Please retry."), + ], + ids=["llm-profiles", "agent-profiles", "meta-profiles"], +) +def test_store_lock_timeouts_are_busy_with_the_old_detail( + tmp_path: Path, + make_store: type[LLMProfileStore | AgentProfileStore | MetaProfileStore], + detail: str, +) -> None: + store = make_store(base_dir=tmp_path) + held = FileLock(str(store._file_lock.lock_file)) + with held: + with pytest.raises(LockTimeout) as caught: + with store._acquire_lock(timeout=0.05): + pass + assert caught.value.detail == detail + assert status_for(caught.value) == 503 diff --git a/tests/agent_server/test_event_router.py b/tests/agent_server/test_event_router.py index 05a1b89adac..463347ef123 100644 --- a/tests/agent_server/test_event_router.py +++ b/tests/agent_server/test_event_router.py @@ -13,6 +13,7 @@ from fastapi.testclient import TestClient from openhands.agent_server import event_router as event_router_module +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.dependencies import get_event_service from openhands.agent_server.event_router import ( event_router, @@ -70,6 +71,7 @@ def test_normalize_datetime_fixed_offset_timezone(): def client(): """Create a test client for the FastAPI app without authentication.""" app = FastAPI() + add_domain_error_handler(app) app.include_router(event_router, prefix="/api") return TestClient(app) diff --git a/tests/agent_server/test_event_service.py b/tests/agent_server/test_event_service.py index 44feacddb3e..3168302264f 100644 --- a/tests/agent_server/test_event_service.py +++ b/tests/agent_server/test_event_service.py @@ -16,12 +16,12 @@ import pytest import pytest_asyncio -from fastapi import HTTPException from pydantic import SecretStr from openhands.agent_server import event_router from openhands.agent_server.conversation_lease import LEASE_FILE_NAME from openhands.agent_server.conversation_service import ConversationService +from openhands.agent_server.errors import status_for from openhands.agent_server.event_router import run_gateway_message from openhands.agent_server.event_service import ( CondensationUnavailable, @@ -54,6 +54,7 @@ ConversationState, ) from openhands.sdk.credential import CredentialSyncError +from openhands.sdk.errors import DomainError from openhands.sdk.event import AgentErrorEvent, Event from openhands.sdk.event.conversation_error import ConversationErrorEvent from openhands.sdk.event.conversation_state import ConversationStateUpdateEvent @@ -126,14 +127,14 @@ async def test_gateway_does_not_save_while_a_previous_run_remains_active( event_service._run_task = previous_run event_service.send_message = AsyncMock() try: - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await run_gateway_message(SendMessageRequest(), event_service) finally: previous_run.cancel() with suppress(asyncio.CancelledError): await previous_run - assert error.value.status_code == 504 + assert status_for(error.value) == 504 event_service.send_message.assert_not_awaited() diff --git a/tests/agent_server/test_experimental_features_router.py b/tests/agent_server/test_experimental_features_router.py index 564c444dd32..bd926249354 100644 --- a/tests/agent_server/test_experimental_features_router.py +++ b/tests/agent_server/test_experimental_features_router.py @@ -8,6 +8,7 @@ from fastapi import FastAPI from openhands.agent_server import experimental_features +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.experimental_features import ( @@ -41,6 +42,7 @@ def qa_feature(monkeypatch) -> ExperimentalFeatureDefinition: @pytest.fixture async def client() -> AsyncIterator[httpx.AsyncClient]: app = FastAPI() + add_domain_error_handler(app) app.state.config = Config( static_files_path=None, session_api_keys=[], secret_key=None ) diff --git a/tests/agent_server/test_init_router.py b/tests/agent_server/test_init_router.py index c3a353d31ed..2afeb2ce459 100644 --- a/tests/agent_server/test_init_router.py +++ b/tests/agent_server/test_init_router.py @@ -23,6 +23,7 @@ from openhands.agent_server.api import api_lifespan, create_app from openhands.agent_server.config import CONFIG_PATH_ENV, Config, load_config +from openhands.agent_server.errors import status_for from openhands.agent_server.init_router import ( InitRequest, InitService, @@ -31,6 +32,7 @@ require_initialized, ) from openhands.agent_server.vscode_service import VSCodeService +from openhands.sdk.errors import DomainError @pytest.fixture(autouse=True) @@ -241,7 +243,6 @@ async def test_init_transitions_dormant_to_ready(self, tmp_path): @pytest.mark.asyncio async def test_second_init_rejected_with_400(self, tmp_path): _reset_conversation_singleton() - from fastapi import HTTPException base = Config( deferred_init=True, @@ -258,9 +259,9 @@ async def test_second_init_rejected_with_400(self, tmp_path): ) ) try: - with pytest.raises(HTTPException) as excinfo: + with pytest.raises(DomainError) as excinfo: await svc.initialize(InitRequest()) - assert excinfo.value.status_code == 400 + assert status_for(excinfo.value) == 400 assert "already in state" in str(excinfo.value.detail) finally: await svc.teardown() diff --git a/tests/agent_server/test_llm_router.py b/tests/agent_server/test_llm_router.py index dd0f0140ed1..075963717a7 100644 --- a/tests/agent_server/test_llm_router.py +++ b/tests/agent_server/test_llm_router.py @@ -3,16 +3,17 @@ import httpx import litellm import pytest -from fastapi import HTTPException from fastapi.testclient import TestClient from openhands.agent_server.api import create_app from openhands.agent_server.config import Config +from openhands.agent_server.errors import status_for from openhands.agent_server.llm_router import ( list_models, list_providers, list_verified_models, ) +from openhands.sdk.errors import DomainError from openhands.sdk.llm.auth.openai import OPENAI_CODEX_MODELS from openhands.sdk.llm.utils.verified_models import VERIFIED_MODELS @@ -450,11 +451,11 @@ def save_credentials(self, credentials): monkeypatch.setattr(llm_router, "_get_openai_subscription_auth", FakeAuth) - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: await llm_router.poll_openai_subscription_device_login( llm_router.SubscriptionDevicePollRequest(device_code="opaque-token") ) - assert exc_info.value.status_code == 502 + assert status_for(exc_info.value) == 502 assert "opaque-token" in llm_router._PENDING_OPENAI_DEVICE_LOGINS success = await llm_router.poll_openai_subscription_device_login( diff --git a/tests/agent_server/test_meta_profiles_router.py b/tests/agent_server/test_meta_profiles_router.py index ea187bfa51f..e4052388034 100644 --- a/tests/agent_server/test_meta_profiles_router.py +++ b/tests/agent_server/test_meta_profiles_router.py @@ -10,6 +10,7 @@ from openhands.agent_server.api import create_app from openhands.agent_server.config import Config from openhands.agent_server.persistence import get_settings_store, reset_stores +from openhands.sdk.errors import LockTimeout from openhands.sdk.llm.meta_profile_store import MetaProfile, MetaProfileStore from openhands.sdk.settings.model import OpenHandsAgentSettings @@ -186,10 +187,10 @@ def test_save_invalid_name_returns_422(client): def test_save_timeout_returns_503(client, monkeypatch): - """Save surfaces store lock TimeoutError as a retryable 503, not a 500.""" + """Save surfaces the store's LockTimeout as a retryable 503, not a 500.""" def boom(self, name, meta_profile, *, max_profiles=None): - raise TimeoutError("locked") + raise LockTimeout("Meta-profile store is busy. Please retry.", message="locked") monkeypatch.setattr(MetaProfileStore, "save", boom) @@ -213,10 +214,10 @@ def test_delete_is_idempotent(client): def test_delete_timeout_returns_503(client, monkeypatch): - """Delete surfaces store lock TimeoutError as a retryable 503, not a 500.""" + """Delete surfaces the store's LockTimeout as a retryable 503, not a 500.""" def boom(self, name): - raise TimeoutError("locked") + raise LockTimeout("Meta-profile store is busy. Please retry.", message="locked") monkeypatch.setattr(MetaProfileStore, "delete", boom) diff --git a/tests/agent_server/test_openai_gateway_docker.py b/tests/agent_server/test_openai_gateway_docker.py index 0d1208df9b9..0d54469f015 100644 --- a/tests/agent_server/test_openai_gateway_docker.py +++ b/tests/agent_server/test_openai_gateway_docker.py @@ -10,13 +10,13 @@ import httpx import pytest -from fastapi import HTTPException from pydantic import SecretStr from openhands.agent_server import event_router from openhands.agent_server.config import Config from openhands.agent_server.docker_runtime.hybrid import HybridConversationRegistry from openhands.agent_server.docker_runtime.registry import DockerConversationRegistry +from openhands.agent_server.errors import status_for from openhands.agent_server.event_router import run_gateway_message from openhands.agent_server.event_service import ConversationRunLimitExceeded from openhands.agent_server.openai import service as gateway @@ -24,6 +24,7 @@ from openhands.sdk.conversation.message_request import SendMessageRequest from openhands.sdk.conversation.request import StartConversationRequest from openhands.sdk.conversation.state import ConversationExecutionStatus +from openhands.sdk.errors import DomainError from openhands.sdk.llm.message import TextContent from openhands.sdk.llm.utils.metrics import Metrics, TokenUsage from openhands.sdk.workspace import LocalWorkspace @@ -290,7 +291,7 @@ def check_attached(request): on_request=check_attached, ) - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway( config, registry, @@ -300,7 +301,7 @@ def check_attached(request): conversation_id=conversation_id, ) - assert error.value.status_code == 503 + assert status_for(error.value) == 503 assert len(requests) == 1 assert not registry.has_attached_sessions(conversation_id) outer_service.get_event_service.assert_not_awaited() @@ -330,7 +331,7 @@ async def test_docker_gateway_reports_inner_timeout_as_gateway_timeout( ), ) - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway( config, registry, @@ -340,7 +341,7 @@ async def test_docker_gateway_reports_inner_timeout_as_gateway_timeout( conversation_id=conversation_id, ) - assert error.value.status_code == 504 + assert status_for(error.value) == 504 assert not registry.has_attached_sessions(conversation_id) @@ -366,7 +367,7 @@ async def test_docker_gateway_maps_inner_404( error_detail=missing_detail if missing_conversation else "Inner run failed", ) - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway( config, registry, @@ -378,11 +379,11 @@ async def test_docker_gateway_maps_inner_404( assert len(requests) == 1 if missing_conversation: - assert error.value.status_code == 404 + assert status_for(error.value) == 404 assert error.value.detail == missing_detail else: - assert error.value.status_code == 502 - assert "gateway route" in error.value.detail + assert status_for(error.value) == 502 + assert "gateway route" in str(error.value) @pytest.mark.asyncio @@ -394,10 +395,10 @@ async def test_docker_gateway_stops_after_docker_start_error(tmp_path, monkeypat monkeypatch.setattr(gateway, "start_docker_conversation", start) monkeypatch.setattr(gateway, "_container", inner) - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway(config, registry, outer_service, start_request, "Do not run") - assert error.value.status_code == 503 + assert status_for(error.value) == 503 start.assert_awaited_once() inner.assert_not_awaited() outer_service.start_conversation.assert_not_awaited() @@ -407,12 +408,12 @@ async def test_docker_gateway_stops_after_docker_start_error(tmp_path, monkeypat async def test_docker_gateway_refuses_outer_launch_without_registry(tmp_path): config, _, outer_service, start_request = _setup(tmp_path) - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway( config, None, outer_service, start_request, "Do not run on host" ) - assert error.value.status_code == 503 + assert status_for(error.value) == 503 outer_service.start_conversation.assert_not_awaited() @@ -424,7 +425,7 @@ async def test_docker_gateway_rejects_id_owned_by_local_conversation(tmp_path): conversation_dir.mkdir(parents=True) conversation_dir.joinpath("meta.json").write_text("{}") - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await _run_gateway( config, registry, @@ -434,7 +435,7 @@ async def test_docker_gateway_rejects_id_owned_by_local_conversation(tmp_path): conversation_id=conversation_id, ) - assert error.value.status_code == 404 + assert status_for(error.value) == 404 outer_service.get_event_service.assert_not_awaited() outer_service.start_conversation.assert_not_awaited() @@ -659,8 +660,8 @@ async def test_gateway_lock_wait_expires_before_saving_message(monkeypatch): event_service = _gateway_event_service() async with event_service._gateway_run_lock: - with pytest.raises(HTTPException) as error: + with pytest.raises(DomainError) as error: await run_gateway_message(SendMessageRequest(), event_service) - assert error.value.status_code == 504 + assert status_for(error.value) == 504 event_service.send_message.assert_not_awaited() diff --git a/tests/agent_server/test_openai_gateway_launch.py b/tests/agent_server/test_openai_gateway_launch.py index a71e4b9c538..80456be1dde 100644 --- a/tests/agent_server/test_openai_gateway_launch.py +++ b/tests/agent_server/test_openai_gateway_launch.py @@ -1,7 +1,7 @@ import pytest -from fastapi import HTTPException from openhands.agent_server.config import Config +from openhands.agent_server.errors import status_for from openhands.agent_server.launch import launch_source, server_launch_stores from openhands.agent_server.openai.service import _create_conversation_request from openhands.agent_server.persistence import ( @@ -13,6 +13,7 @@ from openhands.sdk import LLM from openhands.sdk.context.agent_context import AgentContext from openhands.sdk.conversation.request import StartConversationRequest +from openhands.sdk.errors import DomainError from openhands.sdk.launch import ResolvedLaunch from openhands.sdk.profiles import ACPAgentProfile, OpenHandsAgentProfile from openhands.sdk.settings.model import ACPAgentSettings, OpenHandsAgentSettings @@ -119,7 +120,7 @@ def test_without_an_active_profile_the_gateway_activates_default(config): def test_an_unknown_model_is_not_found_whatever_the_profile(config, profile): _activate(config, profile) - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: _gateway_request(config, "openhands_missing") - assert exc_info.value.status_code == 404 + assert status_for(exc_info.value) == 404 diff --git a/tests/agent_server/test_openai_gateway_reused_wait.py b/tests/agent_server/test_openai_gateway_reused_wait.py index b3df4b06fb0..14b07b00f22 100644 --- a/tests/agent_server/test_openai_gateway_reused_wait.py +++ b/tests/agent_server/test_openai_gateway_reused_wait.py @@ -4,14 +4,15 @@ from types import SimpleNamespace import pytest -from fastapi import HTTPException +from openhands.agent_server.errors import status_for from openhands.agent_server.openai import service from openhands.agent_server.openai.service import ( _raise_for_terminal_error, _wait_for_reused_conversation_completion, ) from openhands.sdk.conversation.state import ConversationExecutionStatus +from openhands.sdk.errors import DomainError class _StatusSequence: @@ -50,9 +51,9 @@ def test_a_continued_run_that_stops_for_the_user_answers_409_at_once(stopped): ) assert status_value == stopped - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: _raise_for_terminal_error(status_value) - assert exc_info.value.status_code == 409 + assert status_for(exc_info.value) == 409 assert exc_info.value.detail == f"Agent run ended with status: {stopped.value}" @@ -61,7 +62,7 @@ def test_a_conversation_left_waiting_before_the_new_turn_is_not_the_answer(): # events, so the earlier turn's waiting status must not end the wait. events = _StatusSequence(ConversationExecutionStatus.WAITING_FOR_CONFIRMATION) - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: asyncio.run( _wait_for_reused_conversation_completion( events, # type: ignore[arg-type] @@ -69,4 +70,4 @@ def test_a_conversation_left_waiting_before_the_new_turn_is_not_the_answer(): timeout_seconds=0, ) ) - assert exc_info.value.status_code == 504 + assert status_for(exc_info.value) == 504 diff --git a/tests/agent_server/test_parent_child_conversations.py b/tests/agent_server/test_parent_child_conversations.py index 22b0ecc4501..a856e31a2da 100644 --- a/tests/agent_server/test_parent_child_conversations.py +++ b/tests/agent_server/test_parent_child_conversations.py @@ -11,6 +11,7 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.conversation_service import ( ConversationService, @@ -234,6 +235,7 @@ async def test_top_level_conversation_has_no_relationships(tmp_path, workspace_d def test_router_maps_invalid_parent_to_422(tmp_path): app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") service = AsyncMock(spec=ConversationService) service.start_conversation.side_effect = InvalidParentConversation( @@ -529,6 +531,7 @@ async def test_start_child_conversation_unknown_parent_returns_none(tmp_path): def _child_client(service: ConversationService) -> TestClient: app = FastAPI() + add_domain_error_handler(app) app.include_router(conversation_router, prefix="/api") app.dependency_overrides[get_conversation_service] = lambda: service return TestClient(app) diff --git a/tests/agent_server/test_plugins_router.py b/tests/agent_server/test_plugins_router.py index 59b3cbb5db0..3b035935839 100644 --- a/tests/agent_server/test_plugins_router.py +++ b/tests/agent_server/test_plugins_router.py @@ -14,6 +14,7 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.plugins_router import plugins_router from openhands.sdk.plugin import Plugin, PluginFetchError @@ -37,6 +38,7 @@ def client(tmp_path: Path, monkeypatch) -> TestClient: "openhands.sdk.plugin.installed.DEFAULT_INSTALLED_PLUGINS_DIR", store ) app = FastAPI() + add_domain_error_handler(app) app.include_router(plugins_router) return TestClient(app) diff --git a/tests/agent_server/test_plugins_service.py b/tests/agent_server/test_plugins_service.py index e66423a163f..20fa5d2dbc9 100644 --- a/tests/agent_server/test_plugins_service.py +++ b/tests/agent_server/test_plugins_service.py @@ -12,6 +12,7 @@ from fastapi.testclient import TestClient from openhands.agent_server import plugins_service +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.plugins_router import plugins_router from openhands.agent_server.plugins_service import ( MarketplacePluginInfo, @@ -278,6 +279,7 @@ def test_marketplace_route_returns_plugins_payload(self, monkeypatch): lambda: sample, ) app = FastAPI() + add_domain_error_handler(app) app.include_router(plugins_router) client = TestClient(app) diff --git a/tests/agent_server/test_profiles_router.py b/tests/agent_server/test_profiles_router.py index 5ee47646230..817813d6715 100644 --- a/tests/agent_server/test_profiles_router.py +++ b/tests/agent_server/test_profiles_router.py @@ -15,6 +15,7 @@ from openhands.agent_server.api import create_app from openhands.agent_server.config import Config from openhands.agent_server.persistence import reset_stores +from openhands.sdk.errors import Invalid, LockTimeout from openhands.sdk.llm import LLM, Message from openhands.sdk.llm.auth.credentials import OAuthCredentials from openhands.sdk.llm.llm_profile_store import LLMProfileStore @@ -934,10 +935,10 @@ def test_save_profile_at_limit_overwrite_allowed(client, store, monkeypatch): def test_list_profiles_timeout_returns_503(client, monkeypatch): - """List endpoint surfaces TimeoutError as 503.""" + """List endpoint surfaces the store's LockTimeout as 503.""" def boom(self): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(LLMProfileStore, "list_summaries", boom) @@ -946,11 +947,11 @@ def boom(self): def test_get_profile_timeout_returns_503(client, store, monkeypatch): - """Get endpoint surfaces TimeoutError as 503.""" + """Get endpoint surfaces the store's LockTimeout as 503.""" store.save("present", LLM(model="gpt-4o")) def boom(self, name, *, cipher=None, resolve_provider=True): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(LLMProfileStore, "load", boom) @@ -959,10 +960,10 @@ def boom(self, name, *, cipher=None, resolve_provider=True): def test_delete_profile_invalid_internal_name_returns_400(client, store, monkeypatch): - """If the store raises ValueError, delete responds 400 instead of 500.""" + """If the store raises Invalid, delete responds 400 instead of 500.""" def boom(self, name): - raise ValueError("Invalid profile name: 'x'.") + raise Invalid("Invalid profile name: 'x'.") monkeypatch.setattr(LLMProfileStore, "delete", boom) @@ -1035,10 +1036,10 @@ def test_get_profile_corrupted_returns_400(client, temp_profiles_dir): def test_save_profile_timeout_returns_503(client, monkeypatch): - """Save endpoint surfaces TimeoutError as 503.""" + """Save endpoint surfaces the store's LockTimeout as 503.""" def boom(self, name, llm, include_secrets=False, *, cipher=None, max_profiles=None): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(LLMProfileStore, "save", boom) @@ -1050,11 +1051,11 @@ def boom(self, name, llm, include_secrets=False, *, cipher=None, max_profiles=No def test_rename_profile_timeout_returns_503(client, store, monkeypatch): - """Rename endpoint surfaces TimeoutError as 503.""" + """Rename endpoint surfaces the store's LockTimeout as 503.""" store.save("src", LLM(model="gpt-4o")) def boom(self, old, new): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(LLMProfileStore, "rename", boom) @@ -1063,11 +1064,11 @@ def boom(self, old, new): def test_delete_profile_timeout_returns_503(client, store, monkeypatch): - """Delete endpoint surfaces TimeoutError as 503.""" + """Delete endpoint surfaces the store's LockTimeout as 503.""" store.save("present", LLM(model="gpt-4o")) def boom(self, name): - raise TimeoutError("locked") + raise LockTimeout("Profile store is busy. Please retry.", message="locked") monkeypatch.setattr(LLMProfileStore, "delete", boom) diff --git a/tests/agent_server/test_reactions_router.py b/tests/agent_server/test_reactions_router.py index ba51bdc6d7c..cf2508fb18d 100644 --- a/tests/agent_server/test_reactions_router.py +++ b/tests/agent_server/test_reactions_router.py @@ -7,6 +7,7 @@ import pytest from fastapi import FastAPI +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.config import Config from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service @@ -45,6 +46,7 @@ def reactions_on(): @pytest.fixture async def client(service) -> AsyncIterator[httpx.AsyncClient]: app = FastAPI() + add_domain_error_handler(app) app.state.config = Config( static_files_path=None, session_api_keys=[], secret_key=None ) diff --git a/tests/agent_server/test_search_limit_validation.py b/tests/agent_server/test_search_limit_validation.py index a857341c6d5..49a54c0b1d9 100644 --- a/tests/agent_server/test_search_limit_validation.py +++ b/tests/agent_server/test_search_limit_validation.py @@ -14,6 +14,7 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.bash_router import bash_router from openhands.agent_server.conversation_router import conversation_router from openhands.agent_server.dependencies import get_event_service @@ -32,6 +33,7 @@ def _limit_schema(router, path: str) -> dict: app = FastAPI() + add_domain_error_handler(app) app.include_router(router, prefix="/api") parameters = app.openapi()["paths"][path]["get"]["parameters"] limit = next(p for p in parameters if p["name"] == "limit") @@ -55,6 +57,7 @@ def test_search_limit_bounds_are_published_in_the_schema(router, path): def test_search_events_rejects_out_of_range_limit(limit): """An out-of-range ``limit`` is a client error, not a server fault.""" app = FastAPI() + add_domain_error_handler(app) app.include_router(event_router, prefix="/api") service = AsyncMock(spec=EventService) service.search_events = AsyncMock(return_value={"items": [], "next_page_id": None}) @@ -71,6 +74,7 @@ def test_search_events_rejects_out_of_range_limit(limit): def test_search_events_accepts_the_maximum_limit(): app = FastAPI() + add_domain_error_handler(app) app.include_router(event_router, prefix="/api") service = AsyncMock(spec=EventService) service.search_events = AsyncMock(return_value={"items": [], "next_page_id": None}) diff --git a/tests/agent_server/test_settings_router.py b/tests/agent_server/test_settings_router.py index 7bdbfce8417..a3aa6aab937 100644 --- a/tests/agent_server/test_settings_router.py +++ b/tests/agent_server/test_settings_router.py @@ -21,6 +21,7 @@ reset_stores, ) from openhands.agent_server.persistence.models import _deep_merge +from openhands.sdk.errors import LockTimeout from openhands.sdk.llm import LLM from openhands.sdk.llm.meta_profile_store import MetaProfile, MetaProfileStore from openhands.sdk.profiles import OpenHandsAgentProfile @@ -2068,7 +2069,10 @@ def test_list_secrets_busy_agent_profile_store_is_503( store = get_agent_profile_store() def _timeout(*_args, **_kwargs): - raise TimeoutError("Agent profile store lock acquisition timed out") + raise LockTimeout( + "Profile store is busy. Please retry.", + message="Agent profile store lock acquisition timed out", + ) monkeypatch.setattr(store, "name_for_id", _timeout) diff --git a/tests/agent_server/test_tool_router.py b/tests/agent_server/test_tool_router.py index bff19a80d7f..5b944ed9031 100644 --- a/tests/agent_server/test_tool_router.py +++ b/tests/agent_server/test_tool_router.py @@ -2,6 +2,7 @@ import importlib +from openhands.agent_server.api import add_domain_error_handler from openhands.sdk.subagent.registry import ( _reset_registry_for_tests, get_agent_factory, @@ -36,6 +37,7 @@ def test_catalog_offers_the_stock_tools_a_profile_may_pick(): from openhands.agent_server.tool_router import tool_router app = FastAPI() + add_domain_error_handler(app) app.state.config = Config() app.include_router(tool_router, prefix="/api") response = TestClient(app).get("/api/tools/catalog") @@ -92,6 +94,7 @@ def test_docker_runtime_catalog_does_not_report_host_usability(monkeypatch): "openhands.sdk.tool.registry._check_tool_usable", lambda name, checker: False ) app = FastAPI() + add_domain_error_handler(app) app.state.config = SimpleNamespace( conversation_runtime="docker", conversation_image_has_browser=True, @@ -113,6 +116,7 @@ def test_docker_catalog_follows_the_image_browser_setting(monkeypatch): from openhands.agent_server.tool_router import tool_router app = FastAPI() + add_domain_error_handler(app) app.state.config = SimpleNamespace( conversation_runtime="docker", conversation_image_has_browser=False, @@ -136,6 +140,7 @@ def test_catalog_reports_a_disabled_browser_as_unusable(): from openhands.agent_server.tool_router import tool_router app = FastAPI() + add_domain_error_handler(app) app.state.config = SimpleNamespace( conversation_runtime="local", conversation_image_has_browser=True, diff --git a/tests/agent_server/test_vscode_router.py b/tests/agent_server/test_vscode_router.py index 0288ed37299..578907f5937 100644 --- a/tests/agent_server/test_vscode_router.py +++ b/tests/agent_server/test_vscode_router.py @@ -3,15 +3,16 @@ from unittest.mock import patch import pytest -from fastapi import HTTPException from fastapi.testclient import TestClient from openhands.agent_server.api import create_app from openhands.agent_server.config import Config +from openhands.agent_server.errors import status_for from openhands.agent_server.vscode_router import ( get_vscode_status, get_vscode_url, ) +from openhands.sdk.errors import DomainError @pytest.fixture @@ -68,10 +69,10 @@ async def test_get_vscode_url_error(mock_vscode_service): """Test getting VSCode URL with service error.""" mock_vscode_service.get_connection_token.side_effect = Exception("Service error") - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: await get_vscode_url() - assert exc_info.value.status_code == 500 + assert status_for(exc_info.value) == 500 assert "Failed to get VSCode URL" in str(exc_info.value.detail) @@ -101,10 +102,10 @@ async def test_get_vscode_status_error(mock_vscode_service): """Test getting VSCode status with service error.""" mock_vscode_service.is_running.side_effect = Exception("Service error") - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: await get_vscode_status() - assert exc_info.value.status_code == 500 + assert status_for(exc_info.value) == 500 assert "Failed to get VSCode status" in str(exc_info.value.detail) @@ -181,10 +182,10 @@ async def test_get_vscode_url_disabled(): ) as mock_service: mock_service.return_value = None - with pytest.raises(HTTPException) as exc_info: + with pytest.raises(DomainError) as exc_info: await get_vscode_url() - assert exc_info.value.status_code == 503 + assert status_for(exc_info.value) == 503 assert "VSCode is disabled in configuration" in str(exc_info.value.detail) diff --git a/tests/agent_server/test_workspace_router.py b/tests/agent_server/test_workspace_router.py index 04eb7075368..68c81cfc03a 100644 --- a/tests/agent_server/test_workspace_router.py +++ b/tests/agent_server/test_workspace_router.py @@ -8,6 +8,7 @@ from fastapi import FastAPI from fastapi.testclient import TestClient +from openhands.agent_server.api import add_domain_error_handler from openhands.agent_server.conversation_service import ConversationService from openhands.agent_server.dependencies import get_conversation_service from openhands.agent_server.event_service import EventService @@ -28,6 +29,7 @@ def _build( workspace_dir=None, ) -> TestClient: app = FastAPI() + add_domain_error_handler(app) app.include_router(workspace_router, prefix="/api") ws = workspace_dir if workspace_dir is not None else tmp_path @@ -206,6 +208,7 @@ def test_non_local_workspace_returns_404(tmp_path): cid = uuid4() app = FastAPI() + add_domain_error_handler(app) app.include_router(workspace_router, prefix="/api") event_service = AsyncMock(spec=EventService) diff --git a/tests/cross/test_no_http_exception_outside_api.py b/tests/cross/test_no_http_exception_outside_api.py new file mode 100644 index 00000000000..4eceec41898 --- /dev/null +++ b/tests/cross/test_no_http_exception_outside_api.py @@ -0,0 +1,56 @@ +"""Guard: the agent server maps errors to HTTP in one place. + +Routers, services and stores raise ``openhands.sdk.errors`` categories, and +``openhands.agent_server.errors.ERROR_STATUS`` maps them to statuses. A hand- +built ``HTTPException`` anywhere else would be a second mapping, which is how +routes drifted before (a route copied without its error mapping answered 500). +""" + +import ast +from pathlib import Path + + +REPO_ROOT = Path(__file__).resolve().parents[2] +AGENT_SERVER = REPO_ROOT / "openhands-agent-server" / "openhands" / "agent_server" + +# api.py renders errors: it handles FastAPI's own HTTPException (routing, +# security dependencies) and builds one to render a domain error. +ALLOWED = {AGENT_SERVER / "api.py"} + + +def _http_exception_uses(path: Path) -> list[int]: + tree = ast.parse(path.read_text(), filename=str(path)) + lines: list[int] = [] + for node in ast.walk(tree): + if isinstance(node, ast.Name) and node.id == "HTTPException": + lines.append(node.lineno) + elif isinstance(node, ast.Attribute) and node.attr == "HTTPException": + lines.append(node.lineno) + elif isinstance(node, ast.ImportFrom): + if any(alias.name == "HTTPException" for alias in node.names): + lines.append(node.lineno) + return lines + + +def test_agent_server_never_builds_http_exception_outside_api() -> None: + offenders = [ + f"{path.relative_to(REPO_ROOT)}:{line}" + for path in sorted(AGENT_SERVER.rglob("*.py")) + if path not in ALLOWED + for line in _http_exception_uses(path) + ] + assert not offenders, ( + "Raise an openhands.sdk.errors category instead of HTTPException; " + "openhands.agent_server.errors.ERROR_STATUS maps it to a status:\n" + + "\n".join(offenders) + ) + + +def test_guard_detects_http_exception(tmp_path: Path) -> None: + sample = tmp_path / "router.py" + sample.write_text( + "from fastapi import HTTPException\n" + "def f():\n" + " raise HTTPException(404, 'x')\n" + ) + assert _http_exception_uses(sample) == [1, 3]