openhands-agent-server 1.49.5__tar.gz → 1.49.6__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/PKG-INFO +2 -1
  2. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/api.py +2 -0
  3. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/mcp_oauth_store.py +73 -7
  4. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/mcp_router.py +10 -1
  5. openhands_agent_server-1.49.6/openhands/agent_server/meta_profiles_router.py +260 -0
  6. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/persistence/models.py +58 -0
  7. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/settings_router.py +6 -1
  8. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/PKG-INFO +2 -1
  9. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/SOURCES.txt +2 -0
  10. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/requires.txt +1 -0
  11. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/pyproject.toml +2 -1
  12. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/__init__.py +0 -0
  13. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/__main__.py +0 -0
  14. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/_secret_redaction.py +0 -0
  15. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/_secrets_exposure.py +0 -0
  16. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/agent_profiles_router.py +0 -0
  17. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/auth_router.py +0 -0
  18. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/bash_router.py +0 -0
  19. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/bash_service.py +0 -0
  20. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/canvas_extensions/__init__.py +0 -0
  21. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/canvas_extensions/installed.py +0 -0
  22. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/canvas_extensions/manifest.py +0 -0
  23. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/canvas_extensions_router.py +0 -0
  24. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/config.py +0 -0
  25. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/conversation_lease.py +0 -0
  26. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/conversation_registry.py +0 -0
  27. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/conversation_router.py +0 -0
  28. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/conversation_service.py +0 -0
  29. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/credential_binding.py +0 -0
  30. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/dependencies.py +0 -0
  31. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker/Dockerfile +0 -0
  32. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker/build.py +0 -0
  33. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/__init__.py +0 -0
  34. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/mediation.py +0 -0
  35. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/provisioning.py +0 -0
  36. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/proxy.py +0 -0
  37. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/registry.py +0 -0
  38. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/docker_runtime/routers.py +0 -0
  39. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/env_parser.py +0 -0
  40. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/event_router.py +0 -0
  41. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/event_service.py +0 -0
  42. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/file_router.py +0 -0
  43. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/git_router.py +0 -0
  44. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/hooks_router.py +0 -0
  45. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/hooks_service.py +0 -0
  46. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/init_router.py +0 -0
  47. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/llm_router.py +0 -0
  48. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/local_secret_resolver.py +0 -0
  49. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/logging_config.py +0 -0
  50. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/middleware.py +0 -0
  51. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/models.py +0 -0
  52. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/openai/__init__.py +0 -0
  53. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/openai/models.py +0 -0
  54. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/openai/router.py +0 -0
  55. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/openai/service.py +0 -0
  56. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/openapi.py +0 -0
  57. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/persistence/__init__.py +0 -0
  58. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/persistence/store.py +0 -0
  59. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/plugins_router.py +0 -0
  60. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/plugins_service.py +0 -0
  61. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/profiles_router.py +0 -0
  62. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/provider_connections_router.py +0 -0
  63. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/pub_sub.py +0 -0
  64. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/py.typed +0 -0
  65. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/runtime_router.py +0 -0
  66. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/server_details_router.py +0 -0
  67. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/session_protocol.py +0 -0
  68. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/session_socket.py +0 -0
  69. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/skills_router.py +0 -0
  70. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/skills_service.py +0 -0
  71. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/sockets.py +0 -0
  72. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/sub_agents_router.py +0 -0
  73. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/__init__.py +0 -0
  74. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/factory.py +0 -0
  75. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/http_exporter.py +0 -0
  76. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/models.py +0 -0
  77. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/policy.py +0 -0
  78. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/posthog_exporter.py +0 -0
  79. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/sanitizer.py +0 -0
  80. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/service.py +0 -0
  81. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/sink.py +0 -0
  82. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry/subscriber.py +0 -0
  83. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/telemetry_types.py +0 -0
  84. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/tool_preload_service.py +0 -0
  85. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/tool_router.py +0 -0
  86. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/utils.py +0 -0
  87. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/vscode_extensions/openhands-settings/extension.js +0 -0
  88. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/vscode_extensions/openhands-settings/package.json +0 -0
  89. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/vscode_router.py +0 -0
  90. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/vscode_service.py +0 -0
  91. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/workspace_router.py +0 -0
  92. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands/agent_server/workspaces_router.py +0 -0
  93. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/dependency_links.txt +0 -0
  94. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/entry_points.txt +0 -0
  95. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/openhands_agent_server.egg-info/top_level.txt +0 -0
  96. {openhands_agent_server-1.49.5 → openhands_agent_server-1.49.6}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openhands-agent-server
3
- Version: 1.49.5
3
+ Version: 1.49.6
4
4
  Summary: OpenHands Agent Server - REST/WebSocket interface for OpenHands AI Agent
5
5
  Project-URL: Source, https://github.com/OpenHands/software-agent-sdk
6
6
  Project-URL: Homepage, https://github.com/OpenHands/software-agent-sdk
@@ -12,6 +12,7 @@ Requires-Dist: alembic>=1.13
12
12
  Requires-Dist: docker<8,>=7.1
13
13
  Requires-Dist: fastapi>=0.104
14
14
  Requires-Dist: openhands-sdk
15
+ Requires-Dist: openhands-tools
15
16
  Requires-Dist: openai<3,>=2.33.0
16
17
  Requires-Dist: pydantic>=2
17
18
  Requires-Dist: sqlalchemy>=2
@@ -55,6 +55,7 @@ from openhands.agent_server.init_router import (
55
55
  from openhands.agent_server.llm_router import llm_router
56
56
  from openhands.agent_server.local_secret_resolver import local_secret_resolution
57
57
  from openhands.agent_server.mcp_router import mcp_router
58
+ from openhands.agent_server.meta_profiles_router import meta_profiles_router
58
59
  from openhands.agent_server.middleware import CORSDispatcher
59
60
  from openhands.agent_server.openai.router import (
60
61
  check_openai_api_key,
@@ -456,6 +457,7 @@ def _add_api_routes(app: FastAPI) -> None:
456
457
  api_router.include_router(workspaces_router)
457
458
  api_router.include_router(profiles_router)
458
459
  api_router.include_router(agent_profiles_router)
460
+ api_router.include_router(meta_profiles_router)
459
461
  # /api/auth/* mints workspace cookies and requires the header to bootstrap,
460
462
  # so it lives under the header-only auth group.
461
463
  api_router.include_router(auth_router)
@@ -15,7 +15,9 @@ from collections.abc import Mapping, Sequence
15
15
  from dataclasses import dataclass
16
16
  from typing import Any, NamedTuple, SupportsFloat
17
17
 
18
- from openhands.agent_server.config import Config
18
+ import httpx
19
+
20
+ from openhands.agent_server.config import Config, WebhookSpec
19
21
  from openhands.agent_server.persistence import PersistedSettings, get_settings_store
20
22
  from openhands.sdk.logger import get_logger
21
23
  from openhands.sdk.mcp.client import MCPClient
@@ -35,6 +37,8 @@ from openhands.sdk.utils.cipher import Cipher
35
37
 
36
38
  logger = get_logger(__name__)
37
39
 
40
+ _WRITE_BACK_TIMEOUT_SECONDS = 10.0
41
+
38
42
 
39
43
  class _OAuthKeySpec(NamedTuple):
40
44
  suffix: str
@@ -93,6 +97,10 @@ class MCPSettingsOAuthTokenStore:
93
97
  they carry is served to FastMCP, and tokens refreshed during the
94
98
  conversation are kept in memory for the lifetime of the store instead of
95
99
  being dropped. Servers found in settings always take precedence.
100
+
101
+ ``write_back_webhooks`` are the app server callbacks this agent server
102
+ posts conversation events to; a refreshed inline state is posted there
103
+ too so the app server can persist it (see ``_write_back_seeded_state``).
96
104
  """
97
105
 
98
106
  def __init__(
@@ -100,9 +108,13 @@ class MCPSettingsOAuthTokenStore:
100
108
  *,
101
109
  seed_mcp_config: Mapping[str, MCPServer] | None = None,
102
110
  cipher: Cipher | None = None,
111
+ write_back_webhooks: Sequence[WebhookSpec] = (),
112
+ session_api_key: str | None = None,
103
113
  ):
104
114
  self._seeded: dict[str, MCPOAuthState] = {}
105
115
  self._seeded_lock = threading.Lock()
116
+ self._write_back_webhooks = tuple(write_back_webhooks)
117
+ self._session_api_key = session_api_key
106
118
  for server in (seed_mcp_config or {}).values():
107
119
  if server.url is None or server.oauth_auth is None:
108
120
  continue
@@ -156,6 +168,7 @@ class MCPSettingsOAuthTokenStore:
156
168
  if field is None:
157
169
  return
158
170
  stored_value = copy.deepcopy(dict(value))
171
+ seeded_updates: list[tuple[str, MCPOAuthState]] = []
159
172
 
160
173
  def apply_update(settings: PersistedSettings) -> PersistedSettings:
161
174
  mcp_config = settings.agent_settings.mcp_config
@@ -165,9 +178,9 @@ class MCPSettingsOAuthTokenStore:
165
178
  with self._seeded_lock:
166
179
  seeded = self._seeded.get(server_url)
167
180
  if seeded is not None:
168
- self._seeded[server_url] = seeded.with_token_storage_value(
169
- field, stored_value
170
- )
181
+ updated = seeded.with_token_storage_value(field, stored_value)
182
+ self._seeded[server_url] = updated
183
+ seeded_updates.append((server_url, updated))
171
184
  return settings
172
185
  logger.warning(
173
186
  "Could not persist MCP OAuth state: no configured MCP "
@@ -195,6 +208,47 @@ class MCPSettingsOAuthTokenStore:
195
208
  return settings
196
209
 
197
210
  get_settings_store().update(apply_update)
211
+ for server_url, state in seeded_updates:
212
+ self._write_back_seeded_state(server_url, state)
213
+
214
+ def _write_back_seeded_state(self, server_url: str, state: MCPOAuthState) -> None:
215
+ """Post the refreshed state of an inline server to the app server.
216
+
217
+ The settings of a server passed inline on the agent live on the app
218
+ server that started the conversation. Without this the refreshed
219
+ tokens die with the sandbox, and the next conversation starts from
220
+ the previous refresh token, which providers that rotate refresh
221
+ tokens have already revoked. Best effort: a failure only logs, and
222
+ the in-memory overlay keeps serving the new tokens.
223
+ """
224
+ if not self._write_back_webhooks:
225
+ return
226
+ payload = {
227
+ "server_url": server_url,
228
+ "oauth_state": state.to_response().model_dump(
229
+ mode="json", exclude_none=True
230
+ ),
231
+ }
232
+ for spec in self._write_back_webhooks:
233
+ headers = dict(spec.headers)
234
+ if self._session_api_key:
235
+ headers["X-Session-API-Key"] = self._session_api_key
236
+ url = f"{spec.base_url.rstrip('/')}/mcp-oauth-state"
237
+ try:
238
+ response = httpx.post(
239
+ url,
240
+ json=payload,
241
+ headers=headers,
242
+ timeout=_WRITE_BACK_TIMEOUT_SECONDS,
243
+ )
244
+ response.raise_for_status()
245
+ except httpx.HTTPError:
246
+ logger.warning(
247
+ "Could not write back MCP OAuth state for %s to %s",
248
+ server_url,
249
+ url,
250
+ exc_info=True,
251
+ )
198
252
 
199
253
  async def put(
200
254
  self,
@@ -375,10 +429,13 @@ class SettingsBackedMCPToolProvider:
375
429
  """Create MCP tools with FastMCP OAuth state persisted in settings.
376
430
 
377
431
  OAuth servers absent from settings (passed inline on the agent) fall back
378
- to the OAuth state they carry; see ``MCPSettingsOAuthTokenStore``.
432
+ to the OAuth state they carry, and their refreshed state is posted back
433
+ through ``webhooks``; see ``MCPSettingsOAuthTokenStore``.
379
434
  """
380
435
 
381
436
  cipher: Cipher | None = None
437
+ webhooks: tuple[WebhookSpec, ...] = ()
438
+ session_api_key: str | None = None
382
439
 
383
440
  def create_tools(
384
441
  self,
@@ -392,7 +449,10 @@ class SettingsBackedMCPToolProvider:
392
449
  mcp_config,
393
450
  timeout,
394
451
  mcp_oauth_token_storage=MCPSettingsOAuthTokenStore(
395
- seed_mcp_config=mcp_config, cipher=self.cipher
452
+ seed_mcp_config=mcp_config,
453
+ cipher=self.cipher,
454
+ write_back_webhooks=self.webhooks,
455
+ session_api_key=self.session_api_key,
396
456
  ),
397
457
  on_tools_changed=on_tools_changed,
398
458
  on_tools_reconciled=on_tools_reconciled,
@@ -410,4 +470,10 @@ def create_settings_backed_mcp_tool_provider(
410
470
  "(no OH_SECRET_KEY configured). Configure OH_SECRET_KEY for "
411
471
  "production deployments."
412
472
  )
413
- return SettingsBackedMCPToolProvider(cipher=config.cipher)
473
+ return SettingsBackedMCPToolProvider(
474
+ cipher=config.cipher,
475
+ webhooks=tuple(config.webhooks),
476
+ session_api_key=(
477
+ config.session_api_keys[0] if config.session_api_keys else None
478
+ ),
479
+ )
@@ -47,6 +47,7 @@ from openhands.sdk.mcp.config import (
47
47
  MCPServer,
48
48
  )
49
49
  from openhands.sdk.mcp.exceptions import MCPError, MCPTimeoutError
50
+ from openhands.sdk.mcp.oauth import MCPOAuth
50
51
  from openhands.sdk.utils.cipher import Cipher
51
52
 
52
53
 
@@ -346,6 +347,9 @@ class _MCPOAuthProbeJob:
346
347
  "succeeded" if isinstance(result, MCPTestSuccess) else "failed"
347
348
  )
348
349
  self.done.set()
350
+ # Also wakes the start route when the probe finished without needing
351
+ # consent (stored tokens still valid, or refreshed) or failed early.
352
+ self.authorization_ready.set()
349
353
 
350
354
  def to_status_response(self) -> MCPOAuthStatusResponse:
351
355
  with self.lock:
@@ -440,7 +444,7 @@ def _oauth_auth_from_authentication(
440
444
  )
441
445
 
442
446
 
443
- class _BrowserCoordinatedOAuth(OAuth):
447
+ class _BrowserCoordinatedOAuth(MCPOAuth):
444
448
  """FastMCP OAuth client that lets the frontend own browser navigation."""
445
449
 
446
450
  def __init__(self, *, job: _MCPOAuthProbeJob, **kwargs: Any):
@@ -708,6 +712,11 @@ async def start_mcp_oauth(
708
712
  authorization_url=job.authorization_url,
709
713
  )
710
714
 
715
+ if job.done.is_set() and isinstance(job.result, MCPTestSuccess):
716
+ # No consent was needed: the stored tokens were valid or refreshed.
717
+ # The caller reads the outcome from the status route.
718
+ return MCPOAuthStartResponse(ok=True, job_id=job.id)
719
+
711
720
  if job.done.is_set() and isinstance(job.result, MCPTestFailure):
712
721
  return MCPOAuthStartResponse(
713
722
  ok=False,
@@ -0,0 +1,260 @@
1
+ """HTTP CRUD + activate endpoints for meta-profiles (mirrors profiles_router).
2
+
3
+ Unlike LLM profiles, meta-profiles hold no secrets — they are plain JSON
4
+ documents persisted via :class:`MetaProfileStore`.
5
+ """
6
+
7
+ from collections.abc import Iterator
8
+ from contextlib import contextmanager
9
+ from typing import Annotated
10
+
11
+ from fastapi import APIRouter, HTTPException, Path, Request, status
12
+ from pydantic import BaseModel
13
+
14
+ from openhands.agent_server._secrets_exposure import get_config
15
+ from openhands.agent_server.persistence import (
16
+ PersistedSettings,
17
+ get_settings_store,
18
+ )
19
+ from openhands.sdk.llm.llm_profile_store import PROFILE_NAME_PATTERN
20
+ from openhands.sdk.llm.meta_profile_store import (
21
+ MetaProfile,
22
+ MetaProfileLimitExceeded,
23
+ MetaProfileStore,
24
+ default_meta_profile_dir,
25
+ )
26
+ from openhands.sdk.logger import get_logger
27
+
28
+
29
+ logger = get_logger(__name__)
30
+
31
+ meta_profiles_router = APIRouter(prefix="/meta-profiles", tags=["Meta-profiles"])
32
+
33
+ MAX_META_PROFILES = 50
34
+
35
+ MetaProfileName = Annotated[
36
+ str,
37
+ Path(min_length=1, max_length=64, pattern=PROFILE_NAME_PATTERN),
38
+ ]
39
+
40
+
41
+ def _get_meta_profile_store() -> MetaProfileStore:
42
+ """Resolve the meta-profile store under ``OH_PERSISTENCE_DIR``.
43
+
44
+ Uses the same helper as the runtime routing tool, so the HTTP API and
45
+ conversation execution read/write the same isolated store.
46
+ """
47
+ return MetaProfileStore(base_dir=default_meta_profile_dir())
48
+
49
+
50
+ class MetaProfileInfo(BaseModel):
51
+ name: str
52
+ classifier_model: str | None = None
53
+ num_classes: int = 0
54
+
55
+
56
+ class MetaProfileListResponse(BaseModel):
57
+ meta_profiles: list[MetaProfileInfo]
58
+ active_meta_profile: str | None = None
59
+
60
+
61
+ class MetaProfileDetailResponse(BaseModel):
62
+ name: str
63
+ config: MetaProfile
64
+
65
+
66
+ class MetaProfileMutationResponse(BaseModel):
67
+ name: str
68
+ message: str
69
+
70
+
71
+ class ActivateMetaProfileResponse(BaseModel):
72
+ name: str
73
+ message: str
74
+
75
+
76
+ @contextmanager
77
+ def _store_errors() -> Iterator[None]:
78
+ """Map ``MetaProfileStore`` errors to HTTP responses."""
79
+ try:
80
+ yield
81
+ except TimeoutError:
82
+ # save()/delete() can raise TimeoutError from the file lock under
83
+ # contention; surface a retryable 503 instead of a generic 500
84
+ # (mirrors profiles_router._store_errors()).
85
+ raise HTTPException(
86
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
87
+ detail="Meta-profile store is busy. Please retry.",
88
+ )
89
+ except ValueError as e:
90
+ raise HTTPException(
91
+ status_code=status.HTTP_400_BAD_REQUEST,
92
+ detail=str(e),
93
+ )
94
+
95
+
96
+ def _set_active_meta_profile_if_matches(
97
+ request: Request, old_name: str, new_name: str | None
98
+ ) -> bool:
99
+ config = get_config(request)
100
+ settings_store = get_settings_store(config)
101
+ settings = settings_store.load() or PersistedSettings()
102
+ if settings.active_meta_profile != old_name:
103
+ return False
104
+
105
+ def update_active(settings: PersistedSettings) -> PersistedSettings:
106
+ # Route through PersistedSettings.update() so the change also
107
+ # propagates into agent_settings (active_meta_profile +
108
+ # enable_classify_and_switch_llm_tool); a direct field assignment
109
+ # would leave that nested state stale.
110
+ agent_diff = {"meta_profile": None} if new_name is None else {}
111
+ settings.update(
112
+ {
113
+ "active_meta_profile": new_name,
114
+ "agent_settings_diff": agent_diff,
115
+ }
116
+ )
117
+ return settings
118
+
119
+ settings_store.update(update_active)
120
+ return True
121
+
122
+
123
+ @meta_profiles_router.get("", response_model=MetaProfileListResponse)
124
+ async def list_meta_profiles(request: Request) -> MetaProfileListResponse:
125
+ """List all saved meta-profiles and the currently active one."""
126
+ config = get_config(request)
127
+ settings_store = get_settings_store(config)
128
+ settings = settings_store.load() or PersistedSettings()
129
+
130
+ store = _get_meta_profile_store()
131
+ with _store_errors():
132
+ summaries = store.list_summaries()
133
+
134
+ return MetaProfileListResponse(
135
+ meta_profiles=[MetaProfileInfo(**s) for s in summaries],
136
+ active_meta_profile=settings.active_meta_profile,
137
+ )
138
+
139
+
140
+ @meta_profiles_router.get("/{name}", response_model=MetaProfileDetailResponse)
141
+ async def get_meta_profile(name: MetaProfileName) -> MetaProfileDetailResponse:
142
+ """Get a meta-profile's full configuration."""
143
+ store = _get_meta_profile_store()
144
+ try:
145
+ with _store_errors():
146
+ meta_profile = store.load(name)
147
+ except FileNotFoundError:
148
+ raise HTTPException(
149
+ status_code=status.HTTP_404_NOT_FOUND,
150
+ detail=f"Meta-profile '{name}' not found",
151
+ )
152
+
153
+ return MetaProfileDetailResponse(name=name, config=meta_profile)
154
+
155
+
156
+ @meta_profiles_router.post(
157
+ "/{name}",
158
+ response_model=MetaProfileMutationResponse,
159
+ status_code=status.HTTP_201_CREATED,
160
+ )
161
+ async def save_meta_profile(
162
+ name: MetaProfileName,
163
+ body: MetaProfile,
164
+ ) -> MetaProfileMutationResponse:
165
+ """Save (create or overwrite) a meta-profile.
166
+
167
+ Returns 409 if creating a new meta-profile would exceed
168
+ ``MAX_META_PROFILES``.
169
+ """
170
+ store = _get_meta_profile_store()
171
+ try:
172
+ with _store_errors():
173
+ store.save(name, body, max_profiles=MAX_META_PROFILES)
174
+ except MetaProfileLimitExceeded:
175
+ raise HTTPException(
176
+ status_code=status.HTTP_409_CONFLICT,
177
+ detail=(
178
+ f"Meta-profile limit reached ({MAX_META_PROFILES}). "
179
+ "Delete a meta-profile before saving a new one."
180
+ ),
181
+ )
182
+
183
+ logger.info(f"Saved meta-profile '{name}'")
184
+ return MetaProfileMutationResponse(
185
+ name=name, message=f"Meta-profile '{name}' saved"
186
+ )
187
+
188
+
189
+ @meta_profiles_router.delete("/{name}", response_model=MetaProfileMutationResponse)
190
+ async def delete_meta_profile(
191
+ request: Request, name: MetaProfileName
192
+ ) -> MetaProfileMutationResponse:
193
+ """Delete a meta-profile (idempotent).
194
+
195
+ If the deleted meta-profile is the active one, ``active_meta_profile`` is
196
+ cleared.
197
+ """
198
+ store = _get_meta_profile_store()
199
+ with _store_errors():
200
+ store.delete(name)
201
+ if _set_active_meta_profile_if_matches(request, name, None):
202
+ logger.info(f"Cleared active_meta_profile for deleted meta-profile '{name}'")
203
+ logger.info(f"Deleted meta-profile '{name}'")
204
+ return MetaProfileMutationResponse(
205
+ name=name, message=f"Meta-profile '{name}' deleted"
206
+ )
207
+
208
+
209
+ @meta_profiles_router.post(
210
+ "/{name}/activate", response_model=ActivateMetaProfileResponse
211
+ )
212
+ async def activate_meta_profile(
213
+ request: Request, name: MetaProfileName
214
+ ) -> ActivateMetaProfileResponse:
215
+ """Activate a meta-profile by recording it as ``active_meta_profile``.
216
+
217
+ Unlike LLM profiles, activating a meta-profile does not mutate the agent's
218
+ LLM config — it only records which meta-profile the
219
+ ``route_task_to_model`` tool should route with. Returns 404 if the
220
+ meta-profile does not exist.
221
+ """
222
+ # Verify the meta-profile exists (and is valid) before activating.
223
+ store = _get_meta_profile_store()
224
+ try:
225
+ with _store_errors():
226
+ meta_profile = store.load(name)
227
+ except FileNotFoundError:
228
+ raise HTTPException(
229
+ status_code=status.HTTP_404_NOT_FOUND,
230
+ detail=f"Meta-profile '{name}' not found",
231
+ )
232
+
233
+ config = get_config(request)
234
+ settings_store = get_settings_store(config)
235
+
236
+ def apply_active(settings: PersistedSettings) -> PersistedSettings:
237
+ # Route through PersistedSettings.update() so activation also wires
238
+ # agent_settings (active_meta_profile + enable_classify_and_switch_llm_tool),
239
+ # which is what actually attaches the routing tool. A direct field
240
+ # assignment would record the active name but never enable the tool.
241
+ settings.update(
242
+ {
243
+ "active_meta_profile": name,
244
+ "agent_settings_diff": {
245
+ "meta_profile": meta_profile.model_dump(mode="json")
246
+ },
247
+ }
248
+ )
249
+ return settings
250
+
251
+ try:
252
+ settings_store.update(apply_active)
253
+ except (OSError, PermissionError):
254
+ logger.error("Failed to activate meta-profile - file I/O error")
255
+ raise HTTPException(status_code=500, detail="Failed to activate meta-profile")
256
+
257
+ logger.info(f"Activated meta-profile '{name}'")
258
+ return ActivateMetaProfileResponse(
259
+ name=name, message=f"Meta-profile '{name}' activated"
260
+ )
@@ -89,6 +89,7 @@ class SettingsUpdatePayload(TypedDict, total=False):
89
89
  misc_settings_diff: dict[str, Any]
90
90
  active_profile: str | None
91
91
  active_agent_profile_id: str | None
92
+ active_meta_profile: str | None
92
93
 
93
94
 
94
95
  def _deep_merge(
@@ -190,6 +191,11 @@ class PersistedSettings(BaseModel):
190
191
  "default, so older settings files load with this as None."
191
192
  ),
192
193
  )
194
+ active_meta_profile: str | None = Field(
195
+ default=None,
196
+ description="Name of the currently active meta-profile used for "
197
+ "intelligent model routing.",
198
+ )
193
199
  misc_settings: dict[str, Any] = Field(
194
200
  default_factory=dict,
195
201
  description=(
@@ -316,11 +322,63 @@ class PersistedSettings(BaseModel):
316
322
  self.active_profile = payload["active_profile"]
317
323
  if "active_agent_profile_id" in payload:
318
324
  self.active_agent_profile_id = payload["active_agent_profile_id"]
325
+
326
+ # Update active_meta_profile if explicitly provided (incl. None)
327
+ if "active_meta_profile" in payload:
328
+ self._apply_active_meta_profile(payload["active_meta_profile"])
329
+
330
+ # Enforce the invariant even when only ``agent_settings`` changed:
331
+ # switching to an agent variant that cannot attach the routing tool
332
+ # (e.g. ACP) must not leave a stale top-level ``active_meta_profile``
333
+ # claiming routing is active. (No-op when active already matches.)
334
+ self._clear_active_meta_profile_if_unsupported()
319
335
  finally:
320
336
  # Clear conv_merged to minimize plaintext exposure window
321
337
  if conv_merged is not None:
322
338
  conv_merged.clear()
323
339
 
340
+ def _agent_supports_routing(self) -> bool:
341
+ """Whether the current agent variant can attach the routing tool.
342
+
343
+ OpenHands agent settings expose ``active_meta_profile`` /
344
+ ``enable_classify_and_switch_llm_tool``; ACP (and any other) variants do
345
+ not and never attach :class:`ClassifyAndSwitchLLMTool`.
346
+ """
347
+ return "active_meta_profile" in type(self.agent_settings).model_fields
348
+
349
+ def _apply_active_meta_profile(self, name: str | None) -> None:
350
+ """Set ``active_meta_profile`` and propagate it into agent_settings.
351
+
352
+ Propagating into the nested ``agent_settings`` is what enables/uses the
353
+ routing tool on the agent built from these settings (mirrors how
354
+ activating a profile bakes the LLM into ``agent_settings``).
355
+
356
+ The top-level field is a strict facade for the nested state, not a
357
+ best-effort hint: if the current agent variant cannot attach the routing
358
+ tool (e.g. ACP), the request is dropped and the facade cleared so
359
+ persisted state never claims an active router no conversation can use.
360
+ """
361
+ if not self._agent_supports_routing():
362
+ self.active_meta_profile = None
363
+ return
364
+ self.active_meta_profile = name
365
+ self.agent_settings = self.agent_settings.model_copy(
366
+ update={
367
+ "active_meta_profile": name,
368
+ "enable_classify_and_switch_llm_tool": name is not None,
369
+ }
370
+ )
371
+
372
+ def _clear_active_meta_profile_if_unsupported(self) -> None:
373
+ """Clear the facade when the agent variant cannot support routing.
374
+
375
+ Guards the agent-kind-switch path: changing ``agent_settings`` to a
376
+ non-routing variant (e.g. ACP) while a meta-profile is active would
377
+ otherwise leave the top-level ``active_meta_profile`` stale.
378
+ """
379
+ if not self._agent_supports_routing() and self.active_meta_profile is not None:
380
+ self.active_meta_profile = None
381
+
324
382
  @classmethod
325
383
  def from_persisted(
326
384
  cls, data: Any, *, context: dict[str, Any] | None = None
@@ -171,6 +171,7 @@ async def get_settings(request: Request) -> SettingsResponse:
171
171
  llm_api_key_is_set=settings.llm_api_key_is_set,
172
172
  active_profile=settings.active_profile,
173
173
  active_agent_profile_id=settings.active_agent_profile_id,
174
+ active_meta_profile=settings.active_meta_profile,
174
175
  misc_settings=settings.misc_settings,
175
176
  )
176
177
 
@@ -217,6 +218,8 @@ async def update_settings(
217
218
  update_data["active_profile"] = payload.active_profile
218
219
  if "active_agent_profile_id" in payload.model_fields_set:
219
220
  update_data["active_agent_profile_id"] = payload.active_agent_profile_id
221
+ if "active_meta_profile" in payload.model_fields_set:
222
+ update_data["active_meta_profile"] = payload.active_meta_profile
220
223
  if not update_data:
221
224
  # No updates provided - this is a client error
222
225
  raise HTTPException(
@@ -224,7 +227,8 @@ async def update_settings(
224
227
  detail=(
225
228
  "At least one of agent_settings_diff, "
226
229
  "conversation_settings_diff, misc_settings_diff, "
227
- "active_profile, or active_agent_profile_id must be provided"
230
+ "active_profile, active_agent_profile_id, or active_meta_profile "
231
+ "must be provided"
228
232
  ),
229
233
  )
230
234
 
@@ -342,6 +346,7 @@ def _apply_settings_update(
342
346
  llm_api_key_is_set=settings.llm_api_key_is_set,
343
347
  active_profile=settings.active_profile,
344
348
  active_agent_profile_id=settings.active_agent_profile_id,
349
+ active_meta_profile=settings.active_meta_profile,
345
350
  misc_settings=settings.misc_settings,
346
351
  )
347
352
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openhands-agent-server
3
- Version: 1.49.5
3
+ Version: 1.49.6
4
4
  Summary: OpenHands Agent Server - REST/WebSocket interface for OpenHands AI Agent
5
5
  Project-URL: Source, https://github.com/OpenHands/software-agent-sdk
6
6
  Project-URL: Homepage, https://github.com/OpenHands/software-agent-sdk
@@ -12,6 +12,7 @@ Requires-Dist: alembic>=1.13
12
12
  Requires-Dist: docker<8,>=7.1
13
13
  Requires-Dist: fastapi>=0.104
14
14
  Requires-Dist: openhands-sdk
15
+ Requires-Dist: openhands-tools
15
16
  Requires-Dist: openai<3,>=2.33.0
16
17
  Requires-Dist: pydantic>=2
17
18
  Requires-Dist: sqlalchemy>=2
@@ -29,6 +29,7 @@ pyproject.toml
29
29
  ./openhands/agent_server/logging_config.py
30
30
  ./openhands/agent_server/mcp_oauth_store.py
31
31
  ./openhands/agent_server/mcp_router.py
32
+ ./openhands/agent_server/meta_profiles_router.py
32
33
  ./openhands/agent_server/middleware.py
33
34
  ./openhands/agent_server/models.py
34
35
  ./openhands/agent_server/openapi.py
@@ -115,6 +116,7 @@ openhands/agent_server/local_secret_resolver.py
115
116
  openhands/agent_server/logging_config.py
116
117
  openhands/agent_server/mcp_oauth_store.py
117
118
  openhands/agent_server/mcp_router.py
119
+ openhands/agent_server/meta_profiles_router.py
118
120
  openhands/agent_server/middleware.py
119
121
  openhands/agent_server/models.py
120
122
  openhands/agent_server/openapi.py
@@ -3,6 +3,7 @@ alembic>=1.13
3
3
  docker<8,>=7.1
4
4
  fastapi>=0.104
5
5
  openhands-sdk
6
+ openhands-tools
6
7
  openai<3,>=2.33.0
7
8
  pydantic>=2
8
9
  sqlalchemy>=2
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "openhands-agent-server"
3
- version = "1.49.5"
3
+ version = "1.49.6"
4
4
  description = "OpenHands Agent Server - REST/WebSocket interface for OpenHands AI Agent"
5
5
 
6
6
  requires-python = ">=3.12"
@@ -10,6 +10,7 @@ dependencies = [
10
10
  "docker>=7.1,<8",
11
11
  "fastapi>=0.104",
12
12
  "openhands-sdk",
13
+ "openhands-tools",
13
14
  "openai>=2.33.0,<3",
14
15
  "pydantic>=2",
15
16
  "sqlalchemy>=2",