Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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).
Expand Down
7 changes: 4 additions & 3 deletions .agents/skills/verify-agent-server/references/mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
70 changes: 15 additions & 55 deletions openhands-agent-server/openhands/agent_server/_secrets_exposure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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


Expand All @@ -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()

Expand All @@ -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'."
)


Expand Down Expand Up @@ -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),
)
10 changes: 5 additions & 5 deletions openhands-agent-server/openhands/agent_server/acp_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading