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
19 changes: 19 additions & 0 deletions openhands-agent-server/openhands/agent_server/_secrets_exposure.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,22 @@ def translate_missing_cipher() -> Iterator[None]:
),
)
raise


@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 ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
"""

import asyncio
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Annotated, Any

from fastapi import APIRouter, HTTPException, Path, Request, status
from pydantic import BaseModel, Field, ValidationError

from openhands.agent_server._secrets_exposure import get_cipher, get_config
from openhands.agent_server._secrets_exposure import (
get_cipher,
get_config,
store_errors,
)
from openhands.agent_server.persistence import (
PersistedSettings,
get_agent_profile_store,
Expand Down Expand Up @@ -105,25 +107,6 @@ class RenameAgentProfileRequest(BaseModel):
)


@contextmanager
def _store_errors() -> Iterator[None]:
"""Map ``AgentProfileStore`` errors to HTTP responses.

Mirrors ``profiles_router._store_errors``: ``TimeoutError`` and
``ValueError`` only. ``FileNotFoundError`` / ``FileExistsError`` are handled
inline per-endpoint so each gets a clean, resource-specific message.
"""
try:
yield
except TimeoutError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Agent profile store is busy. Please retry.",
)
except ValueError as e:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))


def _llm_has_real_config(llm: LLM) -> bool:
"""True when ``llm`` carries real, user-provided configuration.

Expand Down Expand Up @@ -173,7 +156,7 @@ def _seed_default_llm_profile(llm: LLM, cipher: Cipher | None) -> str:
silently clobber it.
"""
llm_store = get_llm_profile_store()
with _store_errors():
with store_errors():
try:
llm_store.load(SEED_PROFILE_NAME, cipher=cipher)
return SEED_PROFILE_NAME
Expand Down Expand Up @@ -227,7 +210,7 @@ def _seed_default_profile(
The lock spans empty-check + save + pointer write so concurrent first
requests seed exactly once and the pointer matches the persisted id.
"""
with _store_errors(), store.lock():
with store_errors(), store.lock():
# Double-checked under the lock: a concurrent first request may have
# already seeded (the outer emptiness check in the list endpoint is
# unlocked).
Expand Down Expand Up @@ -261,7 +244,7 @@ def set_pointer(s: PersistedSettings) -> PersistedSettings:

def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None:
"""Return the stable id of the profile stored under ``name``, if present."""
with _store_errors():
with store_errors():
for summary in store.list_summaries():
if summary.get("name") == name:
sid = summary.get("id")
Expand All @@ -282,14 +265,14 @@ async def list_agent_profiles(request: Request) -> AgentProfileListResponse:
settings = settings_store.load() or PersistedSettings()

store = get_agent_profile_store()
with _store_errors():
with store_errors():
existing = store.list()

if not existing and settings.active_agent_profile_id is None:
_seed_default_profile(store, request, settings, get_cipher(request))
settings = settings_store.load() or settings

with _store_errors():
with store_errors():
summaries = store.list_summaries()

return AgentProfileListResponse(
Expand All @@ -308,7 +291,7 @@ async def get_agent_profile(name: ProfileName) -> AgentProfileDetailResponse:
"""
store = get_agent_profile_store()
try:
with _store_errors():
with store_errors():
profile = store.load(name)
except FileNotFoundError:
raise HTTPException(
Expand Down Expand Up @@ -361,7 +344,7 @@ async 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():
with store_errors():
save_profile_preserving_identity(
store, profile, max_profiles=MAX_AGENT_PROFILES
)
Expand Down Expand Up @@ -392,7 +375,7 @@ async def delete_agent_profile(
store = get_agent_profile_store()
deleted_id = _summary_id_for_name(store, name)

with _store_errors():
with store_errors():
store.delete(name)

if deleted_id is not None:
Expand Down Expand Up @@ -428,7 +411,7 @@ async def rename_agent_profile(
"""
store = get_agent_profile_store()
try:
with _store_errors():
with store_errors():
store.rename(name, body.new_name)
except FileNotFoundError:
raise HTTPException(
Expand Down Expand Up @@ -462,7 +445,7 @@ async 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():
with store_errors():
known_ids = {
str(s["id"]) for s in store.list_summaries() if s.get("id") is not None
}
Expand Down Expand Up @@ -515,7 +498,7 @@ async def materialize_agent_profile(
"""
store = get_agent_profile_store()
try:
with _store_errors():
with store_errors():
profile = store.load(name)
except FileNotFoundError:
raise HTTPException(
Expand Down
32 changes: 7 additions & 25 deletions openhands-agent-server/openhands/agent_server/profiles_router.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
"""HTTP endpoints for managing named LLM configurations (profiles)."""

from collections.abc import Iterator
from contextlib import contextmanager
from typing import Annotated, Any

from fastapi import APIRouter, HTTPException, Path, Request, status
Expand All @@ -13,6 +11,7 @@
get_cipher,
get_config,
parse_expose_secrets_header,
store_errors,
translate_missing_cipher,
)
from openhands.agent_server.persistence import (
Expand Down Expand Up @@ -88,23 +87,6 @@ class RenameProfileRequest(BaseModel):
)


@contextmanager
def _store_errors() -> Iterator[None]:
"""Map ``LLMProfileStore`` errors to HTTP responses."""
try:
yield
except TimeoutError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Profile store is busy. Please retry.",
)
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)


def _has_api_key(llm: LLM) -> bool:
if not isinstance(llm.api_key, SecretStr):
return False
Expand Down Expand Up @@ -141,7 +123,7 @@ async def list_profiles(request: Request) -> ProfileListResponse:
settings = settings_store.load() or PersistedSettings()

store = get_llm_profile_store()
with _store_errors():
with store_errors():
summaries = store.list_summaries()

return ProfileListResponse(
Expand All @@ -164,7 +146,7 @@ async def get_profile(request: Request, name: ProfileName) -> ProfileDetailRespo

store = get_llm_profile_store()
try:
with _store_errors():
with store_errors():
llm = store.load(name, cipher=cipher)
except FileNotFoundError:
raise HTTPException(
Expand Down Expand Up @@ -208,7 +190,7 @@ async 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():
with store_errors():
store.save(
name,
llm,
Expand Down Expand Up @@ -241,7 +223,7 @@ async def delete_profile(
store = get_llm_profile_store()
agent_store = get_agent_profile_store()
try:
with _store_errors():
with store_errors():
delete_llm_profile(agent_store, store, name)
except ProfileReferenced as e:
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
Expand Down Expand Up @@ -269,7 +251,7 @@ async def rename_profile(
store = get_llm_profile_store()
agent_store = get_agent_profile_store()
try:
with _store_errors():
with store_errors():
rename_llm_profile(agent_store, store, name, body.new_name)
except FileNotFoundError:
raise HTTPException(
Expand Down Expand Up @@ -325,7 +307,7 @@ async def activate_profile(
# Load the profile
profile_store = get_llm_profile_store()
try:
with _store_errors():
with store_errors():
llm = profile_store.load(name, cipher=cipher)
except FileNotFoundError:
raise HTTPException(
Expand Down
43 changes: 43 additions & 0 deletions openhands-agent-server/openhands/agent_server/settings_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,16 @@

from openhands.agent_server._secrets_exposure import (
build_expose_context,
get_cipher,
get_config,
parse_expose_secrets_header,
store_errors,
translate_missing_cipher,
)
from openhands.agent_server.persistence import (
SECRET_NAME_PATTERN,
PersistedSettings,
get_llm_profile_store,
get_secrets_store,
get_settings_store,
)
Expand Down Expand Up @@ -179,6 +182,10 @@ async def update_settings(

Accepts ``agent_settings_diff``, ``conversation_settings_diff``,
``misc_settings_diff``, and/or ``active_profile`` for incremental updates.
Setting ``active_profile`` loads and applies that profile's LLM, same as
``POST /api/profiles/{name}/activate``, unless ``agent_settings_diff.llm``
is also given.

The three ``*_settings_diff`` fields are deep-merged; nested objects merge
recursively, and a ``null`` value **inside a nested map deletes that entry**
— the "unset" primitive that lets a client remove a single map key without
Expand Down Expand Up @@ -226,11 +233,47 @@ async def update_settings(
)


def _resolve_active_profile_llm(
request: Request, update_data: SettingsUpdatePayload
) -> SettingsUpdatePayload:
"""Fold the named profile's LLM into ``agent_settings_diff`` unless the
caller already gave one explicitly. Mirrors ``/activate``."""
profile_name = update_data.get("active_profile")
agent_diff = update_data.get("agent_settings_diff")
explicit_llm_diff = isinstance(agent_diff, dict) and "llm" in agent_diff
if not profile_name or explicit_llm_diff:
return update_data

cipher = get_cipher(request)
profile_store = get_llm_profile_store()
try:
with store_errors():
llm = profile_store.load(profile_name, cipher=cipher)
except FileNotFoundError:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Profile '{profile_name}' not found",
)

return cast(
SettingsUpdatePayload,
{
**update_data,
"agent_settings_diff": {
**(agent_diff if isinstance(agent_diff, dict) else {}),
"llm": llm.model_dump(mode="json", context={"expose_secrets": True}),
},
},
)


def _apply_settings_update(
request: Request,
update_data: SettingsUpdatePayload,
before_update: Callable[[PersistedSettings], None] | None = None,
) -> SettingsResponse:
update_data = _resolve_active_profile_llm(request, update_data)

# Apply updates atomically with file locking
def apply_update(settings: PersistedSettings) -> PersistedSettings:
if before_update is not None:
Expand Down
3 changes: 2 additions & 1 deletion tests/agent_server/test_agent_profiles_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,8 +105,9 @@ def test_seed_is_idempotent(client):
assert second["active_agent_profile_id"] == first["active_agent_profile_id"]


def test_seed_references_active_llm_profile(client):
def test_seed_references_active_llm_profile(client, default_llm_profile_store):
"""The seed references the active LLM profile when one is set."""
default_llm_profile_store.save("my-llm", LLM(model="gpt-4o-mini"))
client.patch("/api/settings", json={"active_profile": "my-llm"})

body = client.get("/api/agent-profiles").json()
Expand Down
Loading
Loading