openhands-agent-server 1.52.0__tar.gz → 1.54.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.52.0 → openhands_agent_server-1.54.0}/PKG-INFO +1 -1
  2. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/_secret_redaction.py +24 -12
  3. openhands_agent_server-1.54.0/openhands/agent_server/acp_router.py +186 -0
  4. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/api.py +43 -7
  5. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions/backend.py +163 -22
  6. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions/installed.py +20 -0
  7. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions/manifest.py +85 -8
  8. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions_router.py +48 -0
  9. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/config.py +29 -0
  10. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/conversation_service.py +16 -0
  11. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker/Dockerfile +13 -12
  12. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/registry.py +58 -7
  13. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/routers.py +6 -0
  14. openhands_agent_server-1.54.0/openhands/agent_server/docker_runtime/storage.py +96 -0
  15. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/event_service.py +3 -2
  16. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/file_router.py +39 -8
  17. openhands_agent_server-1.54.0/openhands/agent_server/local_storage.py +75 -0
  18. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/profiles_router.py +8 -6
  19. openhands_agent_server-1.54.0/openhands/agent_server/storage/__init__.py +8 -0
  20. openhands_agent_server-1.54.0/openhands/agent_server/storage/model.py +27 -0
  21. openhands_agent_server-1.54.0/openhands/agent_server/storage/reclaimer.py +195 -0
  22. openhands_agent_server-1.54.0/openhands/agent_server/storage/selectors.py +84 -0
  23. openhands_agent_server-1.54.0/openhands/agent_server/storage/trash.py +84 -0
  24. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/PKG-INFO +1 -1
  25. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/SOURCES.txt +16 -0
  26. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/pyproject.toml +1 -1
  27. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/__init__.py +0 -0
  28. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/__main__.py +0 -0
  29. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/_secrets_exposure.py +0 -0
  30. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/agent_profiles_router.py +0 -0
  31. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/auth_router.py +0 -0
  32. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/bash_router.py +0 -0
  33. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/bash_service.py +0 -0
  34. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions/__init__.py +0 -0
  35. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions/bridge.py +0 -0
  36. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/canvas_extensions_bridge_router.py +0 -0
  37. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/conversation_lease.py +0 -0
  38. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/conversation_registry.py +0 -0
  39. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/conversation_router.py +0 -0
  40. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/credential_binding.py +0 -0
  41. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/dependencies.py +0 -0
  42. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker/build.py +0 -0
  43. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/__init__.py +0 -0
  44. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/mediation.py +0 -0
  45. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/provisioning.py +0 -0
  46. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/docker_runtime/proxy.py +0 -0
  47. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/env_parser.py +0 -0
  48. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/event_router.py +0 -0
  49. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/git_provider_service.py +0 -0
  50. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/git_router.py +0 -0
  51. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/hooks_router.py +0 -0
  52. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/hooks_service.py +0 -0
  53. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/init_router.py +0 -0
  54. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/launch.py +0 -0
  55. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/llm_router.py +0 -0
  56. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/local_secret_resolver.py +0 -0
  57. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/logging_config.py +0 -0
  58. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/managed_llm_key.py +0 -0
  59. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/mcp_oauth_store.py +0 -0
  60. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/mcp_router.py +0 -0
  61. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/meta_profiles_router.py +0 -0
  62. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/middleware.py +0 -0
  63. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/models.py +0 -0
  64. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/openai/__init__.py +0 -0
  65. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/openai/models.py +0 -0
  66. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/openai/router.py +0 -0
  67. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/openai/service.py +0 -0
  68. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/openapi.py +0 -0
  69. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/persistence/__init__.py +0 -0
  70. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/persistence/models.py +0 -0
  71. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/persistence/store.py +0 -0
  72. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/plugins_router.py +0 -0
  73. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/plugins_service.py +0 -0
  74. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/provider_connections_router.py +0 -0
  75. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/pub_sub.py +0 -0
  76. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/py.typed +0 -0
  77. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/runtime_router.py +0 -0
  78. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/server_details_router.py +0 -0
  79. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/session_protocol.py +0 -0
  80. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/session_socket.py +0 -0
  81. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/settings_router.py +0 -0
  82. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/skills_router.py +0 -0
  83. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/skills_service.py +0 -0
  84. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/sockets.py +0 -0
  85. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/sub_agents_router.py +0 -0
  86. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/__init__.py +0 -0
  87. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/factory.py +0 -0
  88. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/http_exporter.py +0 -0
  89. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/models.py +0 -0
  90. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/policy.py +0 -0
  91. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/posthog_exporter.py +0 -0
  92. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/sanitizer.py +0 -0
  93. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/service.py +0 -0
  94. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/sink.py +0 -0
  95. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry/subscriber.py +0 -0
  96. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/telemetry_types.py +0 -0
  97. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/tool_preload_service.py +0 -0
  98. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/tool_router.py +0 -0
  99. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/utils.py +0 -0
  100. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/vscode_extensions/openhands-settings/extension.js +0 -0
  101. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/vscode_extensions/openhands-settings/package.json +0 -0
  102. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/vscode_router.py +0 -0
  103. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/vscode_service.py +0 -0
  104. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/workspace_router.py +0 -0
  105. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands/agent_server/workspaces_router.py +0 -0
  106. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/dependency_links.txt +0 -0
  107. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/entry_points.txt +0 -0
  108. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/requires.txt +0 -0
  109. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/openhands_agent_server.egg-info/top_level.txt +0 -0
  110. {openhands_agent_server-1.52.0 → openhands_agent_server-1.54.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: openhands-agent-server
3
- Version: 1.52.0
3
+ Version: 1.54.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
@@ -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)
@@ -1,5 +1,6 @@
1
1
  import asyncio
2
2
  import os
3
+ import sys
3
4
  import tempfile
4
5
  import traceback
5
6
  import uuid
@@ -17,6 +18,7 @@ from fastapi.responses import JSONResponse, RedirectResponse
17
18
  from fastapi.staticfiles import StaticFiles
18
19
  from starlette.requests import Request
19
20
 
21
+ from openhands.agent_server.acp_router import acp_router
20
22
  from openhands.agent_server.agent_profiles_router import agent_profiles_router
21
23
  from openhands.agent_server.auth_router import auth_router
22
24
  from openhands.agent_server.bash_router import bash_router
@@ -113,22 +115,51 @@ from openhands.tools.terminal.constants import TMUX_SOCKET_NAME
113
115
  logger = get_logger(__name__)
114
116
 
115
117
 
118
+ # tmux binds $TMUX_TMPDIR/tmux-<uid>/<socket name>, and fails with "File name
119
+ # too long" when that does not fit sockaddr_un.sun_path (108 bytes on Linux,
120
+ # 104 on macOS and the BSDs, NUL included).
121
+ _MAX_TMUX_SOCKET_PATH = 107 if sys.platform.startswith("linux") else 103
122
+ _MAX_TMUX_SOCKET_NAME = len(f"{TMUX_SOCKET_NAME}-{uuid.uuid4().hex}")
123
+ _SHORT_TMUX_TMPDIR_ROOT = Path("/tmp")
124
+
125
+
126
+ def _fits_tmux_socket(tmux_tmpdir: Path) -> bool:
127
+ if os.name != "posix":
128
+ return True
129
+ socket_dir = Path(os.path.realpath(tmux_tmpdir)) / f"tmux-{os.getuid()}"
130
+ socket_path_len = len(os.fsencode(socket_dir)) + 1 + _MAX_TMUX_SOCKET_NAME
131
+ return socket_path_len <= _MAX_TMUX_SOCKET_PATH
132
+
133
+
116
134
  def _default_server_tmux_tmpdir() -> Path:
117
- return Path(tempfile.gettempdir()) / f"openhands-agent-server-{os.getpid()}"
135
+ name = f"openhands-agent-server-{os.getpid()}"
136
+ tmux_tmpdir = Path(tempfile.gettempdir()) / name
137
+ if _fits_tmux_socket(tmux_tmpdir):
138
+ return tmux_tmpdir
139
+ # macOS's per-user $TMPDIR (/var/folders/...) is too deep for a socket.
140
+ return _SHORT_TMUX_TMPDIR_ROOT / name
118
141
 
119
142
 
120
143
  def _ensure_server_tmux_tmpdir() -> tuple[Path, bool]:
121
144
  existing = os.getenv("TMUX_TMPDIR")
122
- if existing:
145
+ if existing and _fits_tmux_socket(Path(existing)):
123
146
  return Path(existing), False
124
147
 
125
148
  tmux_tmpdir = _default_server_tmux_tmpdir()
126
149
  tmux_tmpdir.mkdir(parents=True, exist_ok=True)
127
150
  os.environ["TMUX_TMPDIR"] = str(tmux_tmpdir)
128
- logger.info(
129
- "TMUX_TMPDIR not set; defaulting to per-server tmux directory %s",
130
- tmux_tmpdir,
131
- )
151
+ if existing:
152
+ logger.warning(
153
+ "TMUX_TMPDIR %s is too long for tmux socket paths; "
154
+ "using per-server tmux directory %s instead",
155
+ existing,
156
+ tmux_tmpdir,
157
+ )
158
+ else:
159
+ logger.info(
160
+ "TMUX_TMPDIR not set; defaulting to per-server tmux directory %s",
161
+ tmux_tmpdir,
162
+ )
132
163
  return tmux_tmpdir, True
133
164
 
134
165
 
@@ -157,6 +188,7 @@ def _cleanup_stale_tmux_sessions() -> None:
157
188
 
158
189
  @asynccontextmanager
159
190
  async def api_lifespan(api: FastAPI) -> AsyncIterator[None]:
191
+ original_tmux_tmpdir = os.environ.get("TMUX_TMPDIR")
160
192
  tmux_tmpdir, tmux_tmpdir_was_defaulted = _ensure_server_tmux_tmpdir()
161
193
  secret_resolution: local_secret_resolution | None = None
162
194
  try:
@@ -319,7 +351,10 @@ async def api_lifespan(api: FastAPI) -> AsyncIterator[None]:
319
351
  if tmux_tmpdir_was_defaulted and os.environ.get("TMUX_TMPDIR") == str(
320
352
  tmux_tmpdir
321
353
  ):
322
- os.environ.pop("TMUX_TMPDIR", None)
354
+ if original_tmux_tmpdir is None:
355
+ os.environ.pop("TMUX_TMPDIR", None)
356
+ else:
357
+ os.environ["TMUX_TMPDIR"] = original_tmux_tmpdir
323
358
 
324
359
 
325
360
  def _emit_request_failed(request: Request, exc: Exception, error_id: str) -> None:
@@ -462,6 +497,7 @@ def _add_api_routes(app: FastAPI) -> None:
462
497
  api_router.include_router(canvas_extensions_router)
463
498
  api_router.include_router(hooks_router)
464
499
  api_router.include_router(llm_router)
500
+ api_router.include_router(acp_router)
465
501
  api_router.include_router(provider_connections_router)
466
502
  api_router.include_router(mcp_router)
467
503
  api_router.include_router(settings_router)
@@ -13,8 +13,9 @@ import time
13
13
  import urllib.error
14
14
  import urllib.request
15
15
  from collections import deque
16
- from pathlib import Path
16
+ from pathlib import Path, PurePosixPath
17
17
  from typing import Final, Literal
18
+ from urllib.parse import urljoin, urlsplit
18
19
 
19
20
  from pydantic import BaseModel, Field
20
21
 
@@ -40,6 +41,15 @@ _SAFE_INHERITED_ENV: Final[frozenset[str]] = frozenset(
40
41
  )
41
42
  _MAX_LOG_BYTES: Final[int] = 256 * 1024
42
43
  _STOP_TIMEOUT_SECONDS: Final[float] = 5
44
+ _ARTIFACT_DOWNLOAD_TIMEOUT_SECONDS: Final[float] = 120
45
+ _MAX_ARTIFACT_BYTES: Final[int] = 1024 * 1024 * 1024
46
+ _MAX_ARTIFACT_REDIRECTS: Final[int] = 5
47
+
48
+
49
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
50
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
51
+ del req, fp, code, msg, headers, newurl
52
+ return None
43
53
 
44
54
 
45
55
  class BackendRevisionRequest(BaseModel):
@@ -99,6 +109,9 @@ class CanvasExtensionBackendManager:
99
109
  self,
100
110
  installed_dir: Path | None = None,
101
111
  state_dir: Path | None = None,
112
+ *,
113
+ allow_insecure_artifact_urls: bool = False,
114
+ max_artifact_bytes: int = _MAX_ARTIFACT_BYTES,
102
115
  ) -> None:
103
116
  self.installed_dir = installed_dir or get_installed_canvas_extensions_dir()
104
117
  root = (
@@ -106,8 +119,11 @@ class CanvasExtensionBackendManager:
106
119
  )
107
120
  self.state_dir = root
108
121
  self.artifacts_dir = root / "artifacts"
122
+ self.downloads_dir = root / "downloads"
109
123
  self.data_dir = root / "data"
110
124
  self.approvals_dir = root / "approvals"
125
+ self.allow_insecure_artifact_urls = allow_insecure_artifact_urls
126
+ self.max_artifact_bytes = max_artifact_bytes
111
127
  self._runtimes: dict[str, _Runtime] = {}
112
128
  self._locks: dict[str, asyncio.Lock] = {}
113
129
 
@@ -198,24 +214,129 @@ class CanvasExtensionBackendManager:
198
214
  return digest.hexdigest()
199
215
 
200
216
  @staticmethod
201
- def _extract_archive(archive: Path, destination: Path) -> None:
217
+ def _validate_download_url(url: str, allow_http: bool) -> None:
218
+ parsed = urlsplit(url)
219
+ schemes = {"https", "http"} if allow_http else {"https"}
220
+ if (
221
+ parsed.scheme not in schemes
222
+ or not parsed.hostname
223
+ or parsed.username is not None
224
+ or parsed.password is not None
225
+ or parsed.fragment
226
+ ):
227
+ raise ValueError("backend artifact URL is not allowed")
228
+
229
+ def _download_archive(self, url: str, expected_sha256: str) -> Path:
230
+ self.downloads_dir.mkdir(parents=True, exist_ok=True)
231
+ destination = self.downloads_dir / f"{expected_sha256}.tar.gz"
232
+ if destination.is_file() and self._sha256(destination) == expected_sha256:
233
+ return destination
234
+ destination.unlink(missing_ok=True)
235
+ temporary = destination.with_name(f".{destination.name}.{os.getpid()}.tmp")
236
+ opener = urllib.request.build_opener(_NoRedirect)
237
+ current_url = url
238
+ try:
239
+ for redirect_count in range(_MAX_ARTIFACT_REDIRECTS + 1):
240
+ self._validate_download_url(
241
+ current_url, self.allow_insecure_artifact_urls
242
+ )
243
+ request = urllib.request.Request(
244
+ current_url,
245
+ headers={
246
+ "Accept": "application/octet-stream",
247
+ "Accept-Encoding": "identity",
248
+ "User-Agent": "OpenHands-Agent-Server",
249
+ },
250
+ )
251
+ try:
252
+ response = opener.open(
253
+ request, timeout=_ARTIFACT_DOWNLOAD_TIMEOUT_SECONDS
254
+ )
255
+ except urllib.error.HTTPError as exc:
256
+ if exc.code not in {301, 302, 303, 307, 308}:
257
+ raise ValueError(
258
+ f"backend artifact download failed with HTTP {exc.code}"
259
+ ) from exc
260
+ location = exc.headers.get("Location")
261
+ if not location or redirect_count == _MAX_ARTIFACT_REDIRECTS:
262
+ raise ValueError(
263
+ "backend artifact redirect limit exceeded"
264
+ ) from exc
265
+ current_url = urljoin(current_url, location)
266
+ continue
267
+ with response:
268
+ length = response.headers.get("Content-Length")
269
+ if length is not None and int(length) > self.max_artifact_bytes:
270
+ raise ValueError("backend artifact exceeds maximum size")
271
+ digest = hashlib.sha256()
272
+ received = 0
273
+ with temporary.open("wb") as stream:
274
+ while chunk := response.read(1024 * 1024):
275
+ received += len(chunk)
276
+ if received > self.max_artifact_bytes:
277
+ raise ValueError(
278
+ "backend artifact exceeds maximum size"
279
+ )
280
+ digest.update(chunk)
281
+ stream.write(chunk)
282
+ if digest.hexdigest() != expected_sha256:
283
+ raise ValueError(
284
+ "backend artifact checksum does not match manifest"
285
+ )
286
+ os.replace(temporary, destination)
287
+ return destination
288
+ raise ValueError("backend artifact redirect limit exceeded")
289
+ except (OSError, urllib.error.URLError) as exc:
290
+ raise ValueError("backend artifact download failed") from exc
291
+ finally:
292
+ temporary.unlink(missing_ok=True)
293
+
294
+ @staticmethod
295
+ def _extract_archive(
296
+ archive: Path, destination: Path, strip_components: int = 0
297
+ ) -> None:
202
298
  root = destination.resolve()
299
+ seen: set[PurePosixPath] = set()
300
+ extracted = 0
203
301
  with tarfile.open(archive, mode="r:gz") as tar:
204
- members = tar.getmembers()
205
- for member in members:
206
- target = (root / member.name).resolve()
207
- if (
208
- member.name.startswith("/")
209
- or not target.is_relative_to(root)
210
- or not (member.isfile() or member.isdir())
211
- ):
302
+ for member in tar:
303
+ original = PurePosixPath(member.name)
304
+ if original.is_absolute() or ".." in original.parts:
212
305
  raise ValueError(
213
306
  "backend artifact contains an unsafe archive entry"
214
307
  )
215
- tar.extractall(destination, members=members, filter="data")
216
- for path in destination.rglob("*"):
217
- mode = path.stat().st_mode
218
- path.chmod(mode & (0o555 if path.is_file() else 0o755))
308
+ parts = original.parts[strip_components:]
309
+ if not parts:
310
+ continue
311
+ relative = PurePosixPath(*parts)
312
+ if relative in seen or not (member.isfile() or member.isdir()):
313
+ raise ValueError(
314
+ "backend artifact contains an unsafe archive entry"
315
+ )
316
+ seen.add(relative)
317
+ target = (root / Path(*relative.parts)).resolve()
318
+ if not target.is_relative_to(root):
319
+ raise ValueError(
320
+ "backend artifact contains an unsafe archive entry"
321
+ )
322
+ if member.isdir():
323
+ target.mkdir(parents=True, exist_ok=True)
324
+ else:
325
+ source = tar.extractfile(member)
326
+ if source is None:
327
+ raise ValueError(
328
+ "backend artifact contains an unsafe archive entry"
329
+ )
330
+ target.parent.mkdir(parents=True, exist_ok=True)
331
+ with source, target.open("wb") as output:
332
+ shutil.copyfileobj(source, output)
333
+ target.chmod(member.mode & 0o555)
334
+ extracted += 1
335
+ if not extracted:
336
+ raise ValueError("backend artifact contains no files after stripping")
337
+ for path in sorted(destination.rglob("*"), reverse=True):
338
+ if path.is_dir():
339
+ path.chmod(0o555)
219
340
  destination.chmod(0o555)
220
341
 
221
342
  async def prepare(self, name: str, revision: str) -> BackendStatus:
@@ -238,10 +359,19 @@ class CanvasExtensionBackendManager:
238
359
  assert parts is not None
239
360
  _, artifact, current_platform = parts
240
361
  package_root = self.installed_dir / name
241
- archive = self._resolve_contained(package_root, artifact.path)
242
- actual_sha256 = await asyncio.to_thread(self._sha256, archive)
243
- if actual_sha256 != artifact.sha256:
244
- raise ValueError("backend artifact checksum does not match manifest")
362
+ if artifact.path:
363
+ archive = self._resolve_contained(package_root, artifact.path)
364
+ actual_sha256 = await asyncio.to_thread(self._sha256, archive)
365
+ if actual_sha256 != artifact.sha256:
366
+ raise ValueError(
367
+ "backend artifact checksum does not match manifest"
368
+ )
369
+ else:
370
+ assert artifact.url is not None
371
+ archive = await asyncio.to_thread(
372
+ self._download_archive, artifact.url, artifact.sha256
373
+ )
374
+ actual_sha256 = artifact.sha256
245
375
 
246
376
  artifact_dir = self.artifacts_dir / name / actual_sha256
247
377
  if not artifact_dir.exists():
@@ -252,7 +382,12 @@ class CanvasExtensionBackendManager:
252
382
  )
253
383
  )
254
384
  try:
255
- await asyncio.to_thread(self._extract_archive, archive, temporary)
385
+ await asyncio.to_thread(
386
+ self._extract_archive,
387
+ archive,
388
+ temporary,
389
+ artifact.strip_components,
390
+ )
256
391
  try:
257
392
  os.replace(temporary, artifact_dir)
258
393
  except OSError:
@@ -337,18 +472,24 @@ class CanvasExtensionBackendManager:
337
472
  sock.bind(("127.0.0.1", 0))
338
473
  return int(sock.getsockname()[1])
339
474
 
340
- def _environment(self, backend: CanvasExtensionBackend) -> dict[str, str]:
475
+ def _environment(
476
+ self, backend: CanvasExtensionBackend, data_dir: Path
477
+ ) -> dict[str, str]:
341
478
  disallowed = set(backend.inherit_environment) - _SAFE_INHERITED_ENV
342
479
  if disallowed:
343
480
  names = ", ".join(sorted(disallowed))
344
481
  raise ValueError(
345
482
  f"backend requests disallowed environment variables: {names}"
346
483
  )
347
- return {
484
+ home = data_dir / "home"
485
+ home.mkdir(parents=True, exist_ok=True)
486
+ environment = {
348
487
  name: os.environ[name]
349
488
  for name in backend.inherit_environment
350
489
  if name in os.environ
351
490
  }
491
+ environment["HOME"] = str(home)
492
+ return environment
352
493
 
353
494
  @staticmethod
354
495
  def _expand_argv(
@@ -501,7 +642,7 @@ class CanvasExtensionBackendManager:
501
642
  runtime.process = await asyncio.create_subprocess_exec(
502
643
  *self._expand_argv(backend, port, data_dir, artifact_dir),
503
644
  cwd=package_root,
504
- env=self._environment(backend),
645
+ env=self._environment(backend, data_dir),
505
646
  stdout=asyncio.subprocess.PIPE,
506
647
  stderr=asyncio.subprocess.PIPE,
507
648
  start_new_session=True,
@@ -18,6 +18,7 @@ directory in one rename), rolling back if the second fails.
18
18
 
19
19
  import os
20
20
  import shutil
21
+ from contextlib import suppress
21
22
  from pathlib import Path
22
23
 
23
24
  from pydantic import BaseModel, Field, ValidationError
@@ -26,6 +27,7 @@ from openhands.agent_server.canvas_extensions.manifest import (
26
27
  MANIFEST_FILENAME,
27
28
  CanvasExtensionManifest,
28
29
  resolve_entrypoint,
30
+ resolve_icon,
29
31
  )
30
32
  from openhands.sdk.extensions.fetch import fetch_with_resolution
31
33
  from openhands.sdk.extensions.installation import (
@@ -248,6 +250,24 @@ def get_canvas_extension_bundle_path(
248
250
  return resolve_entrypoint(manifest, installed_dir / name)
249
251
 
250
252
 
253
+ def get_canvas_extension_icon_path(
254
+ name: str, installed_dir: Path | None = None
255
+ ) -> Path | None:
256
+ """Resolve *name*'s icon file, re-checking containment like the bundle.
257
+
258
+ Returns:
259
+ None if not installed, no icon is declared, or the icon doesn't resolve
260
+ to a contained file. A broken icon never affects the manifest itself.
261
+ """
262
+ installed_dir = _resolve_installed_dir(installed_dir)
263
+ manifest = get_installed_canvas_extension_manifest(name, installed_dir)
264
+ if manifest is None:
265
+ return None
266
+ with suppress(ValueError, OSError):
267
+ return resolve_icon(manifest, installed_dir / name)
268
+ return None
269
+
270
+
251
271
  class CanvasExtensionUpdateCheck(BaseModel):
252
272
  """Result of ``check_canvas_extension_update``.
253
273