openhands-agent-server 1.54.0__tar.gz → 1.55.1__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 (110) hide show
  1. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/PKG-INFO +1 -1
  2. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/__main__.py +33 -10
  3. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/agent_profiles_router.py +100 -60
  4. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/api.py +125 -31
  5. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/auth_router.py +4 -2
  6. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions/backend.py +149 -29
  7. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions/bridge.py +18 -6
  8. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions_bridge_router.py +18 -2
  9. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/config.py +51 -3
  10. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/conversation_service.py +1 -3
  11. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker/Dockerfile +38 -0
  12. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/proxy.py +13 -4
  13. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/file_router.py +18 -2
  14. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/init_router.py +38 -13
  15. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/launch.py +16 -2
  16. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/llm_router.py +4 -1
  17. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/openai/service.py +39 -59
  18. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/plugins_router.py +75 -1
  19. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/plugins_service.py +23 -0
  20. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/server_details_router.py +21 -1
  21. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/settings_router.py +10 -2
  22. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/skills_router.py +5 -4
  23. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/skills_service.py +27 -4
  24. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/sockets.py +3 -2
  25. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/sub_agents_router.py +23 -5
  26. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/vscode_service.py +4 -2
  27. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/PKG-INFO +1 -1
  28. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/pyproject.toml +1 -1
  29. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/__init__.py +0 -0
  30. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/_secret_redaction.py +0 -0
  31. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/_secrets_exposure.py +0 -0
  32. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/acp_router.py +0 -0
  33. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/bash_router.py +0 -0
  34. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/bash_service.py +0 -0
  35. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions/__init__.py +0 -0
  36. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions/installed.py +0 -0
  37. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions/manifest.py +0 -0
  38. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/canvas_extensions_router.py +0 -0
  39. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/conversation_lease.py +0 -0
  40. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/conversation_registry.py +0 -0
  41. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/conversation_router.py +0 -0
  42. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/credential_binding.py +0 -0
  43. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/dependencies.py +0 -0
  44. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker/build.py +0 -0
  45. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/__init__.py +0 -0
  46. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/mediation.py +0 -0
  47. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/provisioning.py +0 -0
  48. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/registry.py +0 -0
  49. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/routers.py +0 -0
  50. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/docker_runtime/storage.py +0 -0
  51. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/env_parser.py +0 -0
  52. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/event_router.py +0 -0
  53. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/event_service.py +0 -0
  54. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/git_provider_service.py +0 -0
  55. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/git_router.py +0 -0
  56. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/hooks_router.py +0 -0
  57. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/hooks_service.py +0 -0
  58. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/local_secret_resolver.py +0 -0
  59. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/local_storage.py +0 -0
  60. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/logging_config.py +0 -0
  61. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/managed_llm_key.py +0 -0
  62. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/mcp_oauth_store.py +0 -0
  63. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/mcp_router.py +0 -0
  64. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/meta_profiles_router.py +0 -0
  65. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/middleware.py +0 -0
  66. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/models.py +0 -0
  67. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/openai/__init__.py +0 -0
  68. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/openai/models.py +0 -0
  69. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/openai/router.py +0 -0
  70. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/openapi.py +0 -0
  71. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/persistence/__init__.py +0 -0
  72. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/persistence/models.py +0 -0
  73. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/persistence/store.py +0 -0
  74. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/profiles_router.py +0 -0
  75. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/provider_connections_router.py +0 -0
  76. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/pub_sub.py +0 -0
  77. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/py.typed +0 -0
  78. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/runtime_router.py +0 -0
  79. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/session_protocol.py +0 -0
  80. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/session_socket.py +0 -0
  81. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/storage/__init__.py +0 -0
  82. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/storage/model.py +0 -0
  83. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/storage/reclaimer.py +0 -0
  84. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/storage/selectors.py +0 -0
  85. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/storage/trash.py +0 -0
  86. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/__init__.py +0 -0
  87. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/factory.py +0 -0
  88. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/http_exporter.py +0 -0
  89. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/models.py +0 -0
  90. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/policy.py +0 -0
  91. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/posthog_exporter.py +0 -0
  92. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/sanitizer.py +0 -0
  93. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/service.py +0 -0
  94. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/sink.py +0 -0
  95. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry/subscriber.py +0 -0
  96. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/telemetry_types.py +0 -0
  97. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/tool_preload_service.py +0 -0
  98. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/tool_router.py +0 -0
  99. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/utils.py +0 -0
  100. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/vscode_extensions/openhands-settings/extension.js +0 -0
  101. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/vscode_extensions/openhands-settings/package.json +0 -0
  102. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/vscode_router.py +0 -0
  103. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/workspace_router.py +0 -0
  104. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands/agent_server/workspaces_router.py +0 -0
  105. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/SOURCES.txt +0 -0
  106. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/dependency_links.txt +0 -0
  107. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/entry_points.txt +0 -0
  108. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/requires.txt +0 -0
  109. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/openhands_agent_server.egg-info/top_level.txt +0 -0
  110. {openhands_agent_server-1.54.0 → openhands_agent_server-1.55.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openhands-agent-server
3
- Version: 1.54.0
3
+ Version: 1.55.1
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
@@ -27,25 +27,47 @@ _WILDCARD_HOSTS = frozenset({"0.0.0.0", "::", "[::]"})
27
27
  _LOOPBACK_HOST = "127.0.0.1"
28
28
 
29
29
 
30
- def _auth_enabled() -> bool:
31
- """Return True when at least one session API key is configured.
30
+ def _load_server_config():
31
+ """Resolve the effective agent-server config, or ``None`` if it fails.
32
32
 
33
- Keys may come from the ``SESSION_API_KEY`` / ``OH_SESSION_API_KEYS_0``
34
- environment variables or from the agent-server config file, so we resolve
35
- the effective config rather than checking a single source.
33
+ Settings may come from environment variables or from the agent-server
34
+ config file, so we resolve the effective config rather than checking a
35
+ single source.
36
36
  """
37
37
  from openhands.agent_server.config import load_config
38
38
 
39
39
  try:
40
- config = load_config()
40
+ return load_config()
41
41
  except Exception:
42
42
  logger.warning(
43
- "Failed to load agent-server config while resolving default bind "
44
- "host; assuming no session API key is configured.",
43
+ "Failed to load agent-server config while resolving server "
44
+ "startup options; using safe defaults.",
45
45
  exc_info=True,
46
46
  )
47
- return False
48
- return bool(config.session_api_keys)
47
+ return None
48
+
49
+
50
+ def _auth_enabled() -> bool:
51
+ """Return True when at least one session API key is configured.
52
+
53
+ Keys may come from the ``SESSION_API_KEY`` / ``OH_SESSION_API_KEYS_0``
54
+ environment variables or from the agent-server config file.
55
+ """
56
+ config = _load_server_config()
57
+ return bool(config and config.session_api_keys)
58
+
59
+
60
+ def _trust_forwarded_headers() -> bool:
61
+ """Return True when the operator opted into trusting forwarded headers.
62
+
63
+ uvicorn's ``proxy_headers`` rewrites the request scheme and client address
64
+ from ``X-Forwarded-Proto``/``X-Forwarded-For`` sent by any peer in
65
+ ``FORWARDED_ALLOW_IPS`` (loopback by default). Tying it to
66
+ ``trust_forwarded_headers`` keeps a client from changing the origin the
67
+ server derives while that setting is off.
68
+ """
69
+ config = _load_server_config()
70
+ return bool(config and config.trust_forwarded_headers)
49
71
 
50
72
 
51
73
  def _get_internal_server_url(host: str, port: int) -> str:
@@ -323,6 +345,7 @@ def main() -> None:
323
345
  log_level=log_level,
324
346
  log_config=LOGGING_CONFIG,
325
347
  ws="wsproto", # Use wsproto instead of deprecated websockets implementation
348
+ proxy_headers=_trust_forwarded_headers(),
326
349
  )
327
350
 
328
351
  # Use custom LoggingServer to capture signal handling events
@@ -23,6 +23,7 @@ from openhands.agent_server._secrets_exposure import (
23
23
  get_config,
24
24
  store_errors,
25
25
  )
26
+ from openhands.agent_server.config import Config
26
27
  from openhands.agent_server.launch import (
27
28
  can_probe_tools,
28
29
  server_launch_stores,
@@ -46,6 +47,8 @@ from openhands.sdk.profiles import (
46
47
  ACPAgentProfile,
47
48
  AgentProfile,
48
49
  AgentProfileDiagnostics,
50
+ AgentProfileInfo,
51
+ AgentProfileListResponse,
49
52
  AgentProfileStore,
50
53
  OpenHandsAgentProfile,
51
54
  ProfileLimitExceeded,
@@ -72,22 +75,6 @@ ProfileName = Annotated[
72
75
  ProfileId = Annotated[str, Path(min_length=1, max_length=128)]
73
76
 
74
77
 
75
- class AgentProfileInfo(BaseModel):
76
- """Summary projection of a stored profile (no secret instantiation)."""
77
-
78
- id: str | None = None
79
- name: str
80
- agent_kind: str = "openhands"
81
- revision: int | None = None
82
- llm_profile_ref: str | None = None
83
- mcp_server_refs: list[str] | None = None
84
-
85
-
86
- class AgentProfileListResponse(BaseModel):
87
- profiles: list[AgentProfileInfo]
88
- active_agent_profile_id: str | None = None
89
-
90
-
91
78
  class AgentProfileDetailResponse(BaseModel):
92
79
  name: str
93
80
  profile: dict[str, Any]
@@ -232,47 +219,103 @@ def _seed_default_llm_profile(llm: LLM, cipher: Cipher | None) -> str:
232
219
  return SEED_PROFILE_NAME
233
220
 
234
221
 
235
- def _seed_default_profile(
236
- store: AgentProfileStore,
237
- request: Request,
238
- settings: PersistedSettings,
239
- cipher: Cipher | None,
222
+ def _ensure_active_profile(
223
+ store: AgentProfileStore, config: Config, cipher: Cipher | None
240
224
  ) -> None:
241
- """Persist one default profile and point ``active_agent_profile_id`` at it.
225
+ """Keep ``active_agent_profile_id`` on a stored profile.
242
226
 
243
- The lock spans empty-check + save + pointer write so concurrent first
244
- requests seed exactly once and the pointer matches the persisted id.
227
+ A missing or dangling pointer moves to ``default``, which is seeded from the
228
+ current ``agent_settings`` when absent, so every launch has a profile. When
229
+ ``default`` is unreadable or the store is too full to seed it, the first
230
+ other profile is activated instead. The lock spans the check, the seed and
231
+ the pointer write, so concurrent callers seed once and agree on the pointer.
245
232
  """
233
+ settings_store = get_settings_store(config)
246
234
  with store_errors(), store.lock():
247
- # Double-checked under the lock: a concurrent first request may have
248
- # already seeded (the outer emptiness check in the list endpoint is
249
- # unlocked).
250
- if store.list():
235
+ settings = settings_store.load() or PersistedSettings()
236
+ active_id = settings.active_agent_profile_id
237
+ if active_id is not None and store.name_for_id(active_id) is not None:
251
238
  return
252
- active_llm_profile = settings.active_profile
253
- # Falsy check (not `is None`): mirrors build_seed_profile's own
254
- # `active_llm_profile or SEED_PROFILE_NAME` fallback. A stray empty
255
- # string (e.g. a hand-edited/legacy settings.json, or a direct
256
- # PersistedSettings(active_profile="") construction — the HTTP PATCH
257
- # payload's pattern validator blocks "" but the stored field has no
258
- # such constraint) is falsy there too, so the backfill must trigger
259
- # on the same condition or the exact #3933 dangling ref reappears.
260
- if not active_llm_profile and settings.agent_settings.agent_kind != "acp":
261
- active_llm_profile = _seed_default_llm_profile(
262
- settings.agent_settings.llm, cipher
263
- )
264
- profile = build_seed_profile(settings.agent_settings, active_llm_profile)
265
- store.save(profile, max_profiles=MAX_AGENT_PROFILES)
266
-
267
- profile_id = str(profile.id)
268
- settings_store = get_settings_store(get_config(request))
239
+ target = _profile_to_activate(store, settings, cipher)
240
+ if target is None:
241
+ return
242
+ name, profile_id = target
269
243
 
270
244
  def set_pointer(s: PersistedSettings) -> PersistedSettings:
271
245
  s.active_agent_profile_id = profile_id
272
246
  return s
273
247
 
274
248
  settings_store.update(set_pointer)
275
- logger.info(f"Seeded default agent profile '{profile.name}' (id={profile_id})")
249
+ logger.info(f"Activated agent profile '{name}' (id={profile_id})")
250
+
251
+
252
+ def _profile_to_activate(
253
+ store: AgentProfileStore, settings: PersistedSettings, cipher: Cipher | None
254
+ ) -> tuple[str, str] | None:
255
+ """Return the name and id of ``default``, seeding it if the store has room."""
256
+ try:
257
+ profile = store.load(SEED_PROFILE_NAME)
258
+ return profile.name, str(profile.id)
259
+ except FileNotFoundError:
260
+ try:
261
+ profile = _seed_default_profile(store, settings, cipher)
262
+ return profile.name, str(profile.id)
263
+ except ProfileLimitExceeded:
264
+ pass
265
+ except ValueError:
266
+ logger.warning(
267
+ f"Agent profile '{SEED_PROFILE_NAME}' exists but failed to load; "
268
+ "leaving it as-is"
269
+ )
270
+ first = next(
271
+ (
272
+ s
273
+ for s in store.list_summaries()
274
+ if s["id"] and s["name"] != SEED_PROFILE_NAME
275
+ ),
276
+ None,
277
+ )
278
+ return (first["name"], str(first["id"])) if first else None
279
+
280
+
281
+ def _seed_default_profile(
282
+ store: AgentProfileStore, settings: PersistedSettings, cipher: Cipher | None
283
+ ) -> OpenHandsAgentProfile | ACPAgentProfile:
284
+ active_llm_profile = settings.active_profile
285
+ # Falsy check (not `is None`): mirrors build_seed_profile's own
286
+ # `active_llm_profile or SEED_PROFILE_NAME` fallback. A stray empty
287
+ # string (e.g. a hand-edited/legacy settings.json, or a direct
288
+ # PersistedSettings(active_profile="") construction — the HTTP PATCH
289
+ # payload's pattern validator blocks "" but the stored field has no
290
+ # such constraint) is falsy there too, so the backfill must trigger
291
+ # on the same condition or the exact #3933 dangling ref reappears.
292
+ if not active_llm_profile and settings.agent_settings.agent_kind != "acp":
293
+ active_llm_profile = _seed_default_llm_profile(
294
+ settings.agent_settings.llm, cipher
295
+ )
296
+ profile = build_seed_profile(settings.agent_settings, active_llm_profile)
297
+ store.save(profile, max_profiles=MAX_AGENT_PROFILES)
298
+ logger.info(f"Seeded default agent profile '{profile.name}' (id={profile.id})")
299
+ return profile
300
+
301
+
302
+ def active_agent_profile(
303
+ config: Config, cipher: Cipher | None
304
+ ) -> OpenHandsAgentProfile | ACPAgentProfile | None:
305
+ """Return the active Agent Profile, activating ``default`` when none is."""
306
+ store = get_agent_profile_store()
307
+ _ensure_active_profile(store, config, cipher)
308
+ settings = get_settings_store(config).load() or PersistedSettings()
309
+ if settings.active_agent_profile_id is None:
310
+ return None
311
+ with store_errors():
312
+ name = store.name_for_id(settings.active_agent_profile_id)
313
+ if name is None:
314
+ return None
315
+ try:
316
+ return store.load(name)
317
+ except FileNotFoundError:
318
+ return None
276
319
 
277
320
 
278
321
  def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None:
@@ -289,21 +332,16 @@ def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None:
289
332
  async def list_agent_profiles(request: Request) -> AgentProfileListResponse:
290
333
  """List all stored agent profiles and the active pointer.
291
334
 
292
- On the first call against an empty store with no active pointer, lazily
293
- seeds one default profile from the current ``agent_settings`` and activates
294
- it (the one-time migration that replaces a dedicated seed step).
335
+ Some profile is always active: with no valid pointer, ``default`` is
336
+ activated, and seeded from the current ``agent_settings`` when absent.
295
337
  """
296
338
  config = get_config(request)
297
339
  settings_store = get_settings_store(config)
298
340
  settings = settings_store.load() or PersistedSettings()
299
341
 
300
342
  store = get_agent_profile_store()
301
- with store_errors():
302
- existing = store.list()
303
-
304
- if not existing and settings.active_agent_profile_id is None:
305
- _seed_default_profile(store, request, settings, get_cipher(request))
306
- settings = settings_store.load() or settings
343
+ _ensure_active_profile(store, config, get_cipher(request))
344
+ settings = settings_store.load() or settings
307
345
 
308
346
  with store_errors():
309
347
  summaries = store.list_summaries()
@@ -408,11 +446,12 @@ async def delete_agent_profile(
408
446
  ) -> AgentProfileMutationResponse:
409
447
  """Delete a stored profile (idempotent).
410
448
 
411
- If the deleted profile was the active one, ``active_agent_profile_id`` is
412
- cleared. If ``agent_settings`` is itself left on a non-OpenHands variant,
413
- it is reset to default OpenHands agent settings so stale ACP configuration
414
- does not outlive the profile it came from; the server-wide ``mcp_config``
415
- is carried over.
449
+ If the deleted profile was the active one, ``default`` becomes active,
450
+ reseeded from the settings when it was the one deleted. If
451
+ ``agent_settings`` is itself left on a non-OpenHands variant, it is first
452
+ reset to default OpenHands agent settings so stale ACP configuration does
453
+ not outlive the profile it came from; the server-wide ``mcp_config`` is
454
+ carried over.
416
455
  """
417
456
  store = get_agent_profile_store()
418
457
  deleted_id = _summary_id_for_name(store, name)
@@ -448,6 +487,7 @@ async def delete_agent_profile(
448
487
 
449
488
  settings_store.update(clear_pointer_and_reset_settings)
450
489
  logger.info(f"Cleared active pointer for deleted profile '{name}'")
490
+ _ensure_active_profile(store, config, get_cipher(request))
451
491
 
452
492
  logger.info(f"Deleted agent profile '{name}'")
453
493
  return AgentProfileMutationResponse(
@@ -1,5 +1,6 @@
1
1
  import asyncio
2
2
  import os
3
+ import shutil
3
4
  import sys
4
5
  import tempfile
5
6
  import traceback
@@ -35,6 +36,7 @@ from openhands.agent_server.config import (
35
36
  Config,
36
37
  get_default_config,
37
38
  )
39
+ from openhands.agent_server.conversation_lease import _is_pid_alive
38
40
  from openhands.agent_server.conversation_registry import (
39
41
  create_conversation_registry,
40
42
  )
@@ -109,7 +111,11 @@ from openhands.agent_server.workspaces_router import workspaces_router
109
111
  from openhands.sdk.logger import DEBUG, get_logger
110
112
  from openhands.sdk.tool.registry import seal_tool_catalog, unseal_tool_catalog
111
113
  from openhands.sdk.utils.redact import sanitize_dict
112
- from openhands.tools.terminal.constants import TMUX_SOCKET_NAME
114
+ from openhands.tools.terminal.constants import (
115
+ TMUX_SOCKET_NAME,
116
+ TMUX_SOCKET_OWNER_OPTION,
117
+ )
118
+ from openhands.tools.terminal.terminal.tmux_terminal import _socket_creation_lock
113
119
 
114
120
 
115
121
  logger = get_logger(__name__)
@@ -140,12 +146,15 @@ def _default_server_tmux_tmpdir() -> Path:
140
146
  return _SHORT_TMUX_TMPDIR_ROOT / name
141
147
 
142
148
 
143
- def _ensure_server_tmux_tmpdir() -> tuple[Path, bool]:
149
+ def _ensure_server_tmux_tmpdir() -> tuple[Path, bool, bool]:
150
+ """Return the tmux directory, whether it was defaulted, and whether this
151
+ call created it (only then is it removed at shutdown)."""
144
152
  existing = os.getenv("TMUX_TMPDIR")
145
153
  if existing and _fits_tmux_socket(Path(existing)):
146
- return Path(existing), False
154
+ return Path(existing), False, False
147
155
 
148
156
  tmux_tmpdir = _default_server_tmux_tmpdir()
157
+ created = not tmux_tmpdir.exists()
149
158
  tmux_tmpdir.mkdir(parents=True, exist_ok=True)
150
159
  os.environ["TMUX_TMPDIR"] = str(tmux_tmpdir)
151
160
  if existing:
@@ -160,40 +169,105 @@ def _ensure_server_tmux_tmpdir() -> tuple[Path, bool]:
160
169
  "TMUX_TMPDIR not set; defaulting to per-server tmux directory %s",
161
170
  tmux_tmpdir,
162
171
  )
163
- return tmux_tmpdir, True
172
+ return tmux_tmpdir, True, created
164
173
 
165
174
 
166
- def _cleanup_stale_tmux_sessions() -> None:
167
- """Clean up legacy and isolated terminal sockets on server startup."""
168
- if os.name != "posix":
169
- return
170
- socket_dir = Path(os.environ.get("TMUX_TMPDIR", "/tmp")) / f"tmux-{os.getuid()}"
171
- socket_names = [TMUX_SOCKET_NAME]
172
- socket_names.extend(
175
+ def _isolated_socket_names(socket_dir: Path) -> list[str]:
176
+ """Return per-instance socket names present in *socket_dir*."""
177
+ return [
173
178
  path.name
174
179
  for path in socket_dir.glob(f"{TMUX_SOCKET_NAME}-" + "[0-9a-f]" * 32)
175
180
  if path.is_socket()
176
- )
177
- for socket_name in socket_names:
181
+ ]
182
+
183
+
184
+ def _kill_sessions(server: libtmux.Server) -> None:
185
+ for session in server.sessions:
186
+ try:
187
+ session.kill()
188
+ except Exception as e:
189
+ logger.warning("Failed to kill tmux session %s: %s", session, e)
190
+
191
+
192
+ def _socket_owner_pid(server: libtmux.Server) -> int | None:
193
+ """Return the recorded owner PID for a socket, or None when unknown."""
194
+ try:
195
+ raw = server.show_option(
196
+ TMUX_SOCKET_OWNER_OPTION, global_=True, scope=None, ignore_errors=True
197
+ )
198
+ except Exception:
199
+ return None
200
+ if raw is None:
201
+ return None
202
+ try:
203
+ return int(str(raw).strip())
204
+ except ValueError:
205
+ return None
206
+
207
+
208
+ def _reclaim_stale_tmux_sockets(socket_dir: Path) -> None:
209
+ """Reclaim the legacy socket and any isolated socket whose owner is gone."""
210
+ try:
211
+ _kill_sessions(libtmux.Server(socket_name=TMUX_SOCKET_NAME))
212
+ except Exception as e:
213
+ logger.warning("Failed to cleanup tmux socket %s: %s", TMUX_SOCKET_NAME, e)
214
+
215
+ for socket_name in _isolated_socket_names(socket_dir):
178
216
  try:
179
217
  server = libtmux.Server(socket_name=socket_name)
180
- for session in server.sessions:
181
- try:
182
- session.kill()
183
- except Exception as e:
184
- logger.warning("Failed to kill tmux session %s: %s", session, e)
218
+ owner_pid = _socket_owner_pid(server)
219
+ if owner_pid is not None and _is_pid_alive(owner_pid):
220
+ logger.debug(
221
+ "Leaving tmux socket %s alone; owner pid %s is alive",
222
+ socket_name,
223
+ owner_pid,
224
+ )
225
+ continue
226
+ _kill_sessions(server)
185
227
  except Exception as e:
186
228
  logger.warning("Failed to cleanup tmux socket %s: %s", socket_name, e)
187
229
 
188
230
 
231
+ def _cleanup_stale_tmux_sessions() -> None:
232
+ """Clean up legacy and isolated terminal sockets on server startup.
233
+
234
+ The legacy socket (``openhands``) is always reclaimed. Per-instance
235
+ sockets (``openhands-<32 hex>``) are only reclaimed when their owning
236
+ process is gone: several agent-servers may share one externally supplied
237
+ ``TMUX_TMPDIR``, and killing a live sibling's sessions silently destroys
238
+ that conversation's terminal.
239
+
240
+ The scan holds the same cross-process creation lock that terminal setup
241
+ takes between creating a socket and recording its owner, so a socket that
242
+ is still being set up by a live process is never reclaimed as stale.
243
+ """
244
+ if os.name != "posix":
245
+ return
246
+ socket_dir = Path(os.environ.get("TMUX_TMPDIR", "/tmp")) / f"tmux-{os.getuid()}"
247
+
248
+ try:
249
+ with _socket_creation_lock():
250
+ _reclaim_stale_tmux_sockets(socket_dir)
251
+ except Exception as e:
252
+ # The lock only closes a rare startup race; it must never stop cleanup
253
+ # from running (or the server from starting).
254
+ logger.warning("tmux socket creation lock unavailable: %s", e)
255
+ _reclaim_stale_tmux_sockets(socket_dir)
256
+
257
+
189
258
  @asynccontextmanager
190
259
  async def api_lifespan(api: FastAPI) -> AsyncIterator[None]:
191
260
  original_tmux_tmpdir = os.environ.get("TMUX_TMPDIR")
192
- tmux_tmpdir, tmux_tmpdir_was_defaulted = _ensure_server_tmux_tmpdir()
261
+ tmux_tmpdir, tmux_tmpdir_was_defaulted, tmux_tmpdir_was_created = (
262
+ _ensure_server_tmux_tmpdir()
263
+ )
193
264
  secret_resolution: local_secret_resolution | None = None
194
265
  try:
195
266
  # Clean up stale tmux sessions from previous server runs
196
267
  _cleanup_stale_tmux_sessions()
268
+ backend_manager = getattr(api.state, "canvas_extension_backend_manager", None)
269
+ if backend_manager is not None:
270
+ await backend_manager.reap_orphans()
197
271
 
198
272
  config: Config = api.state.config
199
273
  deferred = config.deferred_init
@@ -348,13 +422,23 @@ async def api_lifespan(api: FastAPI) -> AsyncIterator[None]:
348
422
  emit_server_stopped()
349
423
  await shutdown_telemetry_sink()
350
424
 
351
- if tmux_tmpdir_was_defaulted and os.environ.get("TMUX_TMPDIR") == str(
352
- tmux_tmpdir
353
- ):
354
- if original_tmux_tmpdir is None:
355
- os.environ.pop("TMUX_TMPDIR", None)
356
- else:
357
- os.environ["TMUX_TMPDIR"] = original_tmux_tmpdir
425
+ if tmux_tmpdir_was_defaulted:
426
+ if os.environ.get("TMUX_TMPDIR") == str(tmux_tmpdir):
427
+ if original_tmux_tmpdir is None:
428
+ os.environ.pop("TMUX_TMPDIR", None)
429
+ else:
430
+ os.environ["TMUX_TMPDIR"] = original_tmux_tmpdir
431
+ if tmux_tmpdir_was_created:
432
+ # Only the per-server directory this process created; a
433
+ # user-provided TMUX_TMPDIR is never removed.
434
+ try:
435
+ shutil.rmtree(tmux_tmpdir)
436
+ except OSError as e:
437
+ logger.warning(
438
+ "Failed to remove per-server tmux directory %s: %s",
439
+ tmux_tmpdir,
440
+ e,
441
+ )
358
442
 
359
443
 
360
444
  def _emit_request_failed(request: Request, exc: Exception, error_id: str) -> None:
@@ -472,10 +556,10 @@ def _add_api_routes(app: FastAPI) -> None:
472
556
  # check_session_api_key reads config from request.app.state at request time,
473
557
  # so keys delivered via POST /api/init are honoured without re-registering routes.
474
558
  dependencies = [
475
- Depends(check_session_api_key),
476
559
  # Dormant gate: 503s every /api/* route until POST /api/init completes.
477
560
  # No-op for non-deferred deployments.
478
561
  Depends(require_initialized),
562
+ Depends(check_session_api_key),
479
563
  ]
480
564
 
481
565
  api_router = APIRouter(prefix="/api", dependencies=dependencies)
@@ -508,7 +592,10 @@ def _add_api_routes(app: FastAPI) -> None:
508
592
  # /api/auth/* mints workspace cookies and requires the header to bootstrap,
509
593
  # so it lives under the header-only auth group.
510
594
  api_router.include_router(auth_router)
511
- app.include_router(openai_router, dependencies=[Depends(check_openai_api_key)])
595
+ app.include_router(
596
+ openai_router,
597
+ dependencies=[Depends(require_initialized), Depends(check_openai_api_key)],
598
+ )
512
599
 
513
600
  # Workspace static-file routes get their own auth group that accepts
514
601
  # EITHER the X-Session-API-Key header OR the workspace session cookie.
@@ -516,14 +603,21 @@ def _add_api_routes(app: FastAPI) -> None:
516
603
  # workspace artifacts work — browsers cannot attach custom headers to
517
604
  # those requests.
518
605
  workspace_api_router = APIRouter(
519
- prefix="/api", dependencies=[Depends(check_workspace_session)]
606
+ prefix="/api",
607
+ dependencies=[Depends(require_initialized), Depends(check_workspace_session)],
520
608
  )
521
609
  workspace_api_router.include_router(conversation_registry.workspace_router)
522
610
  app.include_router(workspace_api_router)
523
611
  app.include_router(api_router)
524
612
 
525
- app.include_router(app_backend_bridge_router)
526
- app.include_router(conversation_registry.sockets_router)
613
+ app.include_router(
614
+ app_backend_bridge_router,
615
+ dependencies=[Depends(require_initialized)],
616
+ )
617
+ app.include_router(
618
+ conversation_registry.sockets_router,
619
+ dependencies=[Depends(require_initialized)],
620
+ )
527
621
 
528
622
 
529
623
  def _setup_static_files(app: FastAPI, config: Config) -> None:
@@ -56,10 +56,12 @@ def _request_is_secure_context(request: Request) -> bool:
56
56
 
57
57
  forwarded_host = request.headers.get("x-forwarded-host", "")
58
58
  host = forwarded_host.split(",")[0].strip() or request.url.hostname or ""
59
- # Strip an optional ``:port`` suffix; IPv6 hosts are bracketed.
59
+ # Strip an optional ``:port`` suffix. IPv6 hosts are bracketed in
60
+ # ``X-Forwarded-Host``; ``request.url.hostname`` returns them bare
61
+ # (``::1``), so only split on a single colon.
60
62
  if host.startswith("["):
61
63
  host = host.partition("]")[0].lstrip("[")
62
- else:
64
+ elif host.count(":") == 1:
63
65
  host = host.split(":")[0]
64
66
  return host.lower() in _LOOPBACK_HOSTS
65
67