openhands-agent-server 1.53.0__tar.gz → 1.55.0__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.53.0 → openhands_agent_server-1.55.0}/PKG-INFO +1 -1
  2. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/__main__.py +33 -10
  3. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/_secret_redaction.py +24 -12
  4. openhands_agent_server-1.55.0/openhands/agent_server/acp_router.py +186 -0
  5. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/agent_profiles_router.py +98 -44
  6. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/api.py +164 -34
  7. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/auth_router.py +4 -2
  8. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions/backend.py +312 -51
  9. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions/bridge.py +18 -6
  10. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions/manifest.py +42 -4
  11. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions_bridge_router.py +18 -2
  12. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions_router.py +8 -0
  13. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/config.py +80 -3
  14. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/conversation_service.py +17 -3
  15. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker/Dockerfile +45 -12
  16. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/proxy.py +13 -4
  17. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/registry.py +58 -7
  18. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/routers.py +6 -0
  19. openhands_agent_server-1.55.0/openhands/agent_server/docker_runtime/storage.py +96 -0
  20. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/event_service.py +3 -2
  21. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/file_router.py +53 -8
  22. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/init_router.py +38 -13
  23. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/launch.py +16 -2
  24. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/llm_router.py +4 -1
  25. openhands_agent_server-1.55.0/openhands/agent_server/local_storage.py +75 -0
  26. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/openai/service.py +39 -59
  27. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/plugins_router.py +3 -1
  28. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/profiles_router.py +8 -6
  29. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/server_details_router.py +21 -1
  30. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/settings_router.py +10 -2
  31. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/skills_router.py +5 -4
  32. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/skills_service.py +27 -4
  33. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/sockets.py +3 -2
  34. openhands_agent_server-1.55.0/openhands/agent_server/storage/__init__.py +8 -0
  35. openhands_agent_server-1.55.0/openhands/agent_server/storage/model.py +27 -0
  36. openhands_agent_server-1.55.0/openhands/agent_server/storage/reclaimer.py +195 -0
  37. openhands_agent_server-1.55.0/openhands/agent_server/storage/selectors.py +84 -0
  38. openhands_agent_server-1.55.0/openhands/agent_server/storage/trash.py +84 -0
  39. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/sub_agents_router.py +23 -5
  40. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/vscode_service.py +4 -2
  41. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/PKG-INFO +1 -1
  42. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/SOURCES.txt +16 -0
  43. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/pyproject.toml +1 -1
  44. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/__init__.py +0 -0
  45. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/_secrets_exposure.py +0 -0
  46. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/bash_router.py +0 -0
  47. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/bash_service.py +0 -0
  48. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions/__init__.py +0 -0
  49. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/canvas_extensions/installed.py +0 -0
  50. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/conversation_lease.py +0 -0
  51. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/conversation_registry.py +0 -0
  52. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/conversation_router.py +0 -0
  53. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/credential_binding.py +0 -0
  54. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/dependencies.py +0 -0
  55. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker/build.py +0 -0
  56. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/__init__.py +0 -0
  57. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/mediation.py +0 -0
  58. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/docker_runtime/provisioning.py +0 -0
  59. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/env_parser.py +0 -0
  60. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/event_router.py +0 -0
  61. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/git_provider_service.py +0 -0
  62. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/git_router.py +0 -0
  63. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/hooks_router.py +0 -0
  64. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/hooks_service.py +0 -0
  65. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/local_secret_resolver.py +0 -0
  66. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/logging_config.py +0 -0
  67. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/managed_llm_key.py +0 -0
  68. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/mcp_oauth_store.py +0 -0
  69. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/mcp_router.py +0 -0
  70. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/meta_profiles_router.py +0 -0
  71. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/middleware.py +0 -0
  72. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/models.py +0 -0
  73. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/openai/__init__.py +0 -0
  74. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/openai/models.py +0 -0
  75. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/openai/router.py +0 -0
  76. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/openapi.py +0 -0
  77. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/persistence/__init__.py +0 -0
  78. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/persistence/models.py +0 -0
  79. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/persistence/store.py +0 -0
  80. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/plugins_service.py +0 -0
  81. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/provider_connections_router.py +0 -0
  82. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/pub_sub.py +0 -0
  83. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/py.typed +0 -0
  84. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/runtime_router.py +0 -0
  85. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/session_protocol.py +0 -0
  86. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/session_socket.py +0 -0
  87. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/__init__.py +0 -0
  88. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/factory.py +0 -0
  89. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/http_exporter.py +0 -0
  90. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/models.py +0 -0
  91. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/policy.py +0 -0
  92. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/posthog_exporter.py +0 -0
  93. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/sanitizer.py +0 -0
  94. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/service.py +0 -0
  95. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/sink.py +0 -0
  96. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry/subscriber.py +0 -0
  97. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/telemetry_types.py +0 -0
  98. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/tool_preload_service.py +0 -0
  99. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/tool_router.py +0 -0
  100. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/utils.py +0 -0
  101. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/vscode_extensions/openhands-settings/extension.js +0 -0
  102. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/vscode_extensions/openhands-settings/package.json +0 -0
  103. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/vscode_router.py +0 -0
  104. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/workspace_router.py +0 -0
  105. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands/agent_server/workspaces_router.py +0 -0
  106. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/dependency_links.txt +0 -0
  107. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/entry_points.txt +0 -0
  108. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/requires.txt +0 -0
  109. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/openhands_agent_server.egg-info/top_level.txt +0 -0
  110. {openhands_agent_server-1.53.0 → openhands_agent_server-1.55.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openhands-agent-server
3
- Version: 1.53.0
3
+ Version: 1.55.0
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
@@ -7,6 +7,7 @@ material — neither plaintext nor recoverable Fernet ciphertext.
7
7
 
8
8
  import json
9
9
  from pathlib import Path
10
+ from typing import Final
10
11
 
11
12
  from openhands.sdk.llm.llm import LLM_SECRET_FIELDS
12
13
  from openhands.sdk.utils.cipher import FERNET_TOKEN_PREFIX
@@ -21,6 +22,9 @@ TRAJECTORY_SECRET_FIELDS: frozenset[str] = frozenset(
21
22
  (*LLM_SECRET_FIELDS, "llm_api_key")
22
23
  )
23
24
 
25
+ # Suffix of newline-delimited JSON files: one JSON document per line.
26
+ _JSON_LINES_SUFFIX: Final[str] = ".jsonl"
27
+
24
28
 
25
29
  def _is_secret_value(key: object, value: object) -> bool:
26
30
  if not isinstance(value, str) or value in ("", REDACTED_SECRET_VALUE):
@@ -60,23 +64,31 @@ def redact_secrets_in_obj(obj: object) -> bool:
60
64
  return changed
61
65
 
62
66
 
63
- def redacted_file_bytes(path: Path) -> bytes | None:
64
- """Return redacted bytes for a JSON/JSONL file, or ``None`` if unchanged.
67
+ def should_redact(path: Path) -> bool:
68
+ """Return True if exports pass ``path``'s content through redaction.
65
69
 
66
- Persisted conversation files are JSON (``*.json``) or newline-delimited
67
- JSON (``*.jsonl``/the per-event log files). Anything that does not parse as
68
- JSON is left untouched (returns ``None``) so the archive is byte-identical
69
- for non-secret content.
70
+ Persisted conversation payloads are JSON (``*.json``) or newline-delimited
71
+ JSON (``*.jsonl``/the per-event log files); those are the files whose
72
+ bytes go through ``redacted_json_bytes``. Every other file is exported as
73
+ it is.
74
+ """
75
+ return path.suffix.lower() in (".json", _JSON_LINES_SUFFIX)
76
+
77
+
78
+ def redacted_json_bytes(data: bytes, path: Path) -> bytes | None:
79
+ """Return redacted ``data``, or ``None`` if nothing needed redacting.
80
+
81
+ ``data`` is the content of ``path``, a file ``should_redact`` selected;
82
+ a ``.jsonl`` path is parsed one JSON document per line. Content that is not
83
+ UTF-8 or does not parse as JSON is left untouched (returns ``None``) so the
84
+ archive is byte-identical for non-secret content.
70
85
  """
71
- suffix = path.suffix.lower()
72
- if suffix not in (".json", ".jsonl"):
73
- return None
74
86
  try:
75
- raw = path.read_text(encoding="utf-8")
76
- except (OSError, UnicodeDecodeError):
87
+ raw = data.decode("utf-8")
88
+ except UnicodeDecodeError:
77
89
  return None
78
90
 
79
- if suffix == ".jsonl":
91
+ if path.suffix.lower() == _JSON_LINES_SUFFIX:
80
92
  changed = False
81
93
  out_lines: list[str] = []
82
94
  for line in raw.splitlines(keepends=True):
@@ -0,0 +1,186 @@
1
+ """Ask an ACP server which models it offers before a conversation starts."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import time
9
+ from collections.abc import Awaitable, Callable, Mapping
10
+ from dataclasses import dataclass, field
11
+
12
+ from fastapi import APIRouter, HTTPException, Request, status
13
+ from pydantic import BaseModel, Field
14
+
15
+ from openhands.agent_server._secrets_exposure import get_config
16
+ from openhands.agent_server.config import Config
17
+ from openhands.agent_server.credential_binding import LocalVersionedCredentialBinding
18
+ from openhands.agent_server.persistence import get_secrets_store
19
+ from openhands.sdk.agent.acp_file_credentials import CODEX_AUTH_SECRET_NAME
20
+ from openhands.sdk.agent.acp_model_discovery import discover_acp_models
21
+ from openhands.sdk.agent.acp_models import ACPModelDiscovery
22
+ from openhands.sdk.credential import VersionedCredentialBinding
23
+ from openhands.sdk.logger import get_logger
24
+ from openhands.sdk.secret import SecretSource
25
+ from openhands.sdk.settings.model import ACPAgentSettings
26
+
27
+
28
+ logger = get_logger(__name__)
29
+
30
+ acp_router = APIRouter(prefix="/acp", tags=["ACP"])
31
+
32
+ _CACHE_TTL_SECONDS = 300.0
33
+ _MAX_CONCURRENT_DISCOVERIES = 2
34
+
35
+
36
+ class ACPModelDiscoveryRequest(BaseModel):
37
+ agent_settings: ACPAgentSettings = Field(
38
+ description=(
39
+ "The ACP agent to ask. Only the launch fields are used; "
40
+ "``acp_model``, MCP servers and agent context are ignored."
41
+ ),
42
+ )
43
+ secrets: dict[str, SecretSource] = Field(
44
+ default_factory=dict,
45
+ description=(
46
+ "Credentials for the server, in the same shape as a conversation "
47
+ "start request's ``secrets`` (typically ``LookupSecret`` references "
48
+ "to this server's stored secrets)."
49
+ ),
50
+ )
51
+ refresh: bool = Field(
52
+ default=False, description="Ask the server again instead of reusing a result."
53
+ )
54
+
55
+
56
+ @dataclass
57
+ class _DiscoveryCache:
58
+ results: dict[str, tuple[float, ACPModelDiscovery]] = field(default_factory=dict)
59
+ in_flight: dict[str, asyncio.Future[ACPModelDiscovery]] = field(
60
+ default_factory=dict
61
+ )
62
+ slots: asyncio.Semaphore = field(
63
+ default_factory=lambda: asyncio.Semaphore(_MAX_CONCURRENT_DISCOVERIES)
64
+ )
65
+
66
+ async def get(
67
+ self,
68
+ key: str,
69
+ discover: Callable[[], Awaitable[ACPModelDiscovery]],
70
+ *,
71
+ refresh: bool,
72
+ ) -> ACPModelDiscovery:
73
+ cached = self.results.get(key)
74
+ if not refresh and cached is not None and cached[0] > time.monotonic():
75
+ return cached[1]
76
+ pending = self.in_flight.get(key)
77
+ if pending is None:
78
+ pending = asyncio.ensure_future(self._run(key, discover))
79
+ self.in_flight[key] = pending
80
+ return await asyncio.shield(pending)
81
+
82
+ async def _run(
83
+ self, key: str, discover: Callable[[], Awaitable[ACPModelDiscovery]]
84
+ ) -> ACPModelDiscovery:
85
+ try:
86
+ async with self.slots:
87
+ result = await discover()
88
+ if result.error is None:
89
+ self.results[key] = (time.monotonic() + _CACHE_TTL_SECONDS, result)
90
+ return result
91
+ finally:
92
+ self.in_flight.pop(key, None)
93
+
94
+
95
+ def _discovery_cache(request: Request) -> _DiscoveryCache:
96
+ cache = getattr(request.app.state, "acp_model_discovery_cache", None)
97
+ if cache is None:
98
+ cache = _DiscoveryCache()
99
+ request.app.state.acp_model_discovery_cache = cache
100
+ return cache
101
+
102
+
103
+ def _resolve_secrets(secrets: Mapping[str, SecretSource]) -> dict[str, str]:
104
+ values: dict[str, str] = {}
105
+ for name, source in secrets.items():
106
+ try:
107
+ value = source.get_value()
108
+ except Exception:
109
+ logger.warning("Could not resolve secret %r for ACP model discovery", name)
110
+ continue
111
+ if value is not None:
112
+ values[name] = value
113
+ return values
114
+
115
+
116
+ def _cache_key(
117
+ settings: ACPAgentSettings, command: list[str], secrets: Mapping[str, str]
118
+ ) -> str:
119
+ payload = {
120
+ "command": command,
121
+ "args": list(settings.acp_args),
122
+ "session_mode": settings.acp_session_mode,
123
+ "isolate": settings.acp_isolate_data_dir,
124
+ "file_secrets": [
125
+ spec.model_dump(mode="json") for spec in settings.acp_file_secrets
126
+ ],
127
+ "secrets": sorted(secrets.items()),
128
+ }
129
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode()).hexdigest()
130
+
131
+
132
+ def _codex_bindings(
133
+ settings: ACPAgentSettings, config: Config, secrets: dict[str, str]
134
+ ) -> dict[str, VersionedCredentialBinding]:
135
+ if settings.acp_server != "codex":
136
+ return {}
137
+ store = get_secrets_store(config)
138
+ if store.get_secret(CODEX_AUTH_SECRET_NAME) is None:
139
+ return {}
140
+ # A stored ChatGPT login refreshes through the store, as in a conversation.
141
+ secrets.pop(CODEX_AUTH_SECRET_NAME, None)
142
+ return {
143
+ CODEX_AUTH_SECRET_NAME: LocalVersionedCredentialBinding(
144
+ store, CODEX_AUTH_SECRET_NAME
145
+ )
146
+ }
147
+
148
+
149
+ @acp_router.post("/models", response_model=ACPModelDiscovery)
150
+ async def discover_models(
151
+ body: ACPModelDiscoveryRequest, request: Request
152
+ ) -> ACPModelDiscovery:
153
+ """Start the ACP server in a throwaway session and report its models.
154
+
155
+ The server answers with its default model and the models it offers for the
156
+ given credentials; a launch or authentication failure comes back in
157
+ ``error`` rather than as an HTTP error.
158
+ """
159
+ config: Config = get_config(request)
160
+ if config.conversation_runtime == "docker":
161
+ raise HTTPException(
162
+ status.HTTP_501_NOT_IMPLEMENTED,
163
+ "ACP model discovery runs only where conversations run in-process",
164
+ )
165
+ settings = body.agent_settings
166
+ try:
167
+ command = settings.resolve_acp_command()
168
+ except ValueError as exc:
169
+ raise HTTPException(status.HTTP_422_UNPROCESSABLE_ENTITY, str(exc)) from exc
170
+
171
+ secrets = await asyncio.to_thread(_resolve_secrets, body.secrets)
172
+ bindings = await asyncio.to_thread(_codex_bindings, settings, config, secrets)
173
+ key = _cache_key(settings, command, secrets)
174
+
175
+ async def run() -> ACPModelDiscovery:
176
+ config.conversations_path.mkdir(parents=True, exist_ok=True)
177
+ return await asyncio.to_thread(
178
+ discover_acp_models,
179
+ settings,
180
+ secrets=secrets,
181
+ credential_bindings=bindings,
182
+ # Shares the conversations' npx cache.
183
+ work_root=config.conversations_path,
184
+ )
185
+
186
+ return await _discovery_cache(request).get(key, run, refresh=body.refresh)
@@ -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,
@@ -232,47 +233,103 @@ def _seed_default_llm_profile(llm: LLM, cipher: Cipher | None) -> str:
232
233
  return SEED_PROFILE_NAME
233
234
 
234
235
 
235
- def _seed_default_profile(
236
- store: AgentProfileStore,
237
- request: Request,
238
- settings: PersistedSettings,
239
- cipher: Cipher | None,
236
+ def _ensure_active_profile(
237
+ store: AgentProfileStore, config: Config, cipher: Cipher | None
240
238
  ) -> None:
241
- """Persist one default profile and point ``active_agent_profile_id`` at it.
239
+ """Keep ``active_agent_profile_id`` on a stored profile.
242
240
 
243
- The lock spans empty-check + save + pointer write so concurrent first
244
- requests seed exactly once and the pointer matches the persisted id.
241
+ A missing or dangling pointer moves to ``default``, which is seeded from the
242
+ current ``agent_settings`` when absent, so every launch has a profile. When
243
+ ``default`` is unreadable or the store is too full to seed it, the first
244
+ other profile is activated instead. The lock spans the check, the seed and
245
+ the pointer write, so concurrent callers seed once and agree on the pointer.
245
246
  """
247
+ settings_store = get_settings_store(config)
246
248
  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():
249
+ settings = settings_store.load() or PersistedSettings()
250
+ active_id = settings.active_agent_profile_id
251
+ if active_id is not None and store.name_for_id(active_id) is not None:
251
252
  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))
253
+ target = _profile_to_activate(store, settings, cipher)
254
+ if target is None:
255
+ return
256
+ name, profile_id = target
269
257
 
270
258
  def set_pointer(s: PersistedSettings) -> PersistedSettings:
271
259
  s.active_agent_profile_id = profile_id
272
260
  return s
273
261
 
274
262
  settings_store.update(set_pointer)
275
- logger.info(f"Seeded default agent profile '{profile.name}' (id={profile_id})")
263
+ logger.info(f"Activated agent profile '{name}' (id={profile_id})")
264
+
265
+
266
+ def _profile_to_activate(
267
+ store: AgentProfileStore, settings: PersistedSettings, cipher: Cipher | None
268
+ ) -> tuple[str, str] | None:
269
+ """Return the name and id of ``default``, seeding it if the store has room."""
270
+ try:
271
+ profile = store.load(SEED_PROFILE_NAME)
272
+ return profile.name, str(profile.id)
273
+ except FileNotFoundError:
274
+ try:
275
+ profile = _seed_default_profile(store, settings, cipher)
276
+ return profile.name, str(profile.id)
277
+ except ProfileLimitExceeded:
278
+ pass
279
+ except ValueError:
280
+ logger.warning(
281
+ f"Agent profile '{SEED_PROFILE_NAME}' exists but failed to load; "
282
+ "leaving it as-is"
283
+ )
284
+ first = next(
285
+ (
286
+ s
287
+ for s in store.list_summaries()
288
+ if s["id"] and s["name"] != SEED_PROFILE_NAME
289
+ ),
290
+ None,
291
+ )
292
+ return (first["name"], str(first["id"])) if first else None
293
+
294
+
295
+ def _seed_default_profile(
296
+ store: AgentProfileStore, settings: PersistedSettings, cipher: Cipher | None
297
+ ) -> OpenHandsAgentProfile | ACPAgentProfile:
298
+ active_llm_profile = settings.active_profile
299
+ # Falsy check (not `is None`): mirrors build_seed_profile's own
300
+ # `active_llm_profile or SEED_PROFILE_NAME` fallback. A stray empty
301
+ # string (e.g. a hand-edited/legacy settings.json, or a direct
302
+ # PersistedSettings(active_profile="") construction — the HTTP PATCH
303
+ # payload's pattern validator blocks "" but the stored field has no
304
+ # such constraint) is falsy there too, so the backfill must trigger
305
+ # on the same condition or the exact #3933 dangling ref reappears.
306
+ if not active_llm_profile and settings.agent_settings.agent_kind != "acp":
307
+ active_llm_profile = _seed_default_llm_profile(
308
+ settings.agent_settings.llm, cipher
309
+ )
310
+ profile = build_seed_profile(settings.agent_settings, active_llm_profile)
311
+ store.save(profile, max_profiles=MAX_AGENT_PROFILES)
312
+ logger.info(f"Seeded default agent profile '{profile.name}' (id={profile.id})")
313
+ return profile
314
+
315
+
316
+ def active_agent_profile(
317
+ config: Config, cipher: Cipher | None
318
+ ) -> OpenHandsAgentProfile | ACPAgentProfile | None:
319
+ """Return the active Agent Profile, activating ``default`` when none is."""
320
+ store = get_agent_profile_store()
321
+ _ensure_active_profile(store, config, cipher)
322
+ settings = get_settings_store(config).load() or PersistedSettings()
323
+ if settings.active_agent_profile_id is None:
324
+ return None
325
+ with store_errors():
326
+ name = store.name_for_id(settings.active_agent_profile_id)
327
+ if name is None:
328
+ return None
329
+ try:
330
+ return store.load(name)
331
+ except FileNotFoundError:
332
+ return None
276
333
 
277
334
 
278
335
  def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None:
@@ -289,21 +346,16 @@ def _summary_id_for_name(store: AgentProfileStore, name: str) -> str | None:
289
346
  async def list_agent_profiles(request: Request) -> AgentProfileListResponse:
290
347
  """List all stored agent profiles and the active pointer.
291
348
 
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).
349
+ Some profile is always active: with no valid pointer, ``default`` is
350
+ activated, and seeded from the current ``agent_settings`` when absent.
295
351
  """
296
352
  config = get_config(request)
297
353
  settings_store = get_settings_store(config)
298
354
  settings = settings_store.load() or PersistedSettings()
299
355
 
300
356
  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
357
+ _ensure_active_profile(store, config, get_cipher(request))
358
+ settings = settings_store.load() or settings
307
359
 
308
360
  with store_errors():
309
361
  summaries = store.list_summaries()
@@ -408,11 +460,12 @@ async def delete_agent_profile(
408
460
  ) -> AgentProfileMutationResponse:
409
461
  """Delete a stored profile (idempotent).
410
462
 
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.
463
+ If the deleted profile was the active one, ``default`` becomes active,
464
+ reseeded from the settings when it was the one deleted. If
465
+ ``agent_settings`` is itself left on a non-OpenHands variant, it is first
466
+ reset to default OpenHands agent settings so stale ACP configuration does
467
+ not outlive the profile it came from; the server-wide ``mcp_config`` is
468
+ carried over.
416
469
  """
417
470
  store = get_agent_profile_store()
418
471
  deleted_id = _summary_id_for_name(store, name)
@@ -448,6 +501,7 @@ async def delete_agent_profile(
448
501
 
449
502
  settings_store.update(clear_pointer_and_reset_settings)
450
503
  logger.info(f"Cleared active pointer for deleted profile '{name}'")
504
+ _ensure_active_profile(store, config, get_cipher(request))
451
505
 
452
506
  logger.info(f"Deleted agent profile '{name}'")
453
507
  return AgentProfileMutationResponse(