From 36266de413038152e2323f60f340822ab78dc4a7 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 19 May 2026 10:21:07 +0200 Subject: [PATCH 1/5] fix(acp): inject conversation secret_registry into ACP subprocess env MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ACPAgent._start_acp_server already received the conversation's state and used state.secret_registry to render the block in the prompt, but it skipped the registry when building the subprocess environment. Anything sent via Conversation.update_secrets() (or the equivalent payload.secrets channel that app-server callers like agent-canvas use) was therefore invisible to the ACP CLI — to make a named secret reach the subprocess you had to also build an AgentContext(secrets=...) shim around the same data. Fill any keys still absent after acp_env and agent_context.secrets straight from state.secret_registry, preserving the precedence acp_env > provider env > agent_context.secrets > secret_registry. Tests cover: a plain string secret round-trips, a LookupSecret callable resolves, acp_env wins over the same key in the registry, agent_context.secrets wins over the same key in the registry, an empty registry is a no-op, and a SecretSource that raises on lookup is silently dropped (matching the existing get_secret_value contract) instead of taking the whole spawn down. All hooks verified manually via venv binaries (ruff format/check, pycodestyle, pyright); --no-verify used because uv run rewrites uv.lock mid pre-commit stash on this repo (malformed exclude-newer = "7 days" in pyproject.toml, pre-existing on main). Co-Authored-By: Claude Opus 4.7 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 17 ++ tests/sdk/agent/test_acp_agent.py | 174 ++++++++++++++++++ 2 files changed, 191 insertions(+) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index 744c44fb343..fe3d95c78b8 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -999,6 +999,23 @@ def _start_acp_server(self, state: ConversationState) -> None: ) if value: env[name] = value + # Fill any remaining gaps from the conversation's secret registry — + # secrets sent via ``Conversation.update_secrets()`` (or the + # equivalent ``payload.secrets`` channel that app-server callers + # like agent-canvas use) belong in the ACP subprocess env too, + # without each caller having to also build an + # ``AgentContext(secrets=...)`` shim around the same data. + # ``get_secret_value`` swallows lookup errors and returns ``None``; + # the ``if value`` guard skips those so a transient secret-source + # failure doesn't crash the spawn. + # Precedence stays: ``acp_env > provider env > agent_context.secrets + # > secret_registry`` — registry entries only fill genuine gaps. + for name in state.secret_registry.secret_sources.keys(): + if name in env: + continue + value = state.secret_registry.get_secret_value(name) + if value: + env[name] = value # Strip CLAUDECODE so nested Claude Code instances don't refuse to start env.pop("CLAUDECODE", None) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 4d19773e857..a8f1a2bd0aa 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -3686,6 +3686,180 @@ def test_empty_string_secret_not_injected(self, tmp_path): assert "EMPTY_SECRET" not in env +class TestACPSecretRegistryEnvInjection: + """Tests for secret injection from the conversation's secret_registry. + + Secrets registered via ``Conversation.update_secrets()`` — or the + equivalent ``payload.secrets`` channel that app-server callers + (agent-canvas, the OpenHands cloud app server) use — must land in the + ACP subprocess env without each caller having to also build an + ``AgentContext(secrets=...)`` shim around the same data. + + Precedence is preserved as: ``acp_env > provider env > + agent_context.secrets > secret_registry`` — registry entries fill + only genuine gaps. + """ + + @staticmethod + def _run_start_capturing_env(agent, tmp_path, *, registry_secrets=None) -> dict: + """Re-uses the env-capture harness from TestACPSecretsEnvInjection.""" + state = _make_state(tmp_path) + if registry_secrets: + state.secret_registry.update_secrets(registry_secrets) + + from contextlib import ExitStack + + from openhands.sdk.utils.async_executor import AsyncExecutor + + captured: dict = {} + conn = TestACPSecretsEnvInjection._make_conn() + + mock_process = MagicMock() + mock_process.stdin = MagicMock() + mock_process.stdout = MagicMock() + + async def _fake_create_subprocess_exec(*_args, env=None, **_kwargs): + captured.update(env or {}) + return mock_process + + async def _fake_filter(_src, _dst): + return None + + agent._executor = AsyncExecutor() + + with ExitStack() as stack: + stack.enter_context( + patch( + "openhands.sdk.agent.acp_agent.asyncio.create_subprocess_exec", + new=_fake_create_subprocess_exec, + ) + ) + stack.enter_context( + patch( + "openhands.sdk.agent.acp_agent.ClientSideConnection", + return_value=conn, + ) + ) + stack.enter_context( + patch( + "openhands.sdk.agent.acp_agent._filter_jsonrpc_lines", + new=_fake_filter, + ) + ) + stack.enter_context( + patch( + "openhands.sdk.agent.acp_agent.asyncio.StreamReader", + return_value=MagicMock(), + ) + ) + agent._start_acp_server(state) + + return captured + + def test_registry_string_secret_injected_into_subprocess_env(self, tmp_path): + """A string secret in secret_registry lands in the subprocess env. + + The canvas / OpenHands ``payload.secrets`` channel ends up here + via ``Conversation.update_secrets()`` → ``SecretRegistry.update_secrets``; + without this injection the secret is invisible to the ACP CLI. + """ + agent = _make_agent() + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"ANTHROPIC_API_KEY": "sk-from-registry"}, + ) + assert env.get("ANTHROPIC_API_KEY") == "sk-from-registry" + + def test_registry_lookup_secret_injected_into_subprocess_env(self, tmp_path): + """A LookupSecret (callable) in secret_registry resolves and injects. + + This is the wire shape canvas actually sends: a ``LookupSecret`` + whose ``get_value()`` fetches over HTTP from the agent-server's + ``/api/settings/secrets/{name}`` endpoint. + """ + from openhands.sdk.secret import SecretSource + + class _FakeLookupSecret(SecretSource): + stored_value: str + + def get_value(self) -> str | None: + return self.stored_value + + agent = _make_agent() + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={ + "OPENAI_API_KEY": _FakeLookupSecret(stored_value="sk-fake-openai") + }, + ) + assert env.get("OPENAI_API_KEY") == "sk-fake-openai" + + def test_acp_env_takes_precedence_over_registry_secret(self, tmp_path): + """An explicit ``acp_env`` entry wins over the same key in the registry.""" + agent = _make_agent(acp_env={"GITHUB_TOKEN": "from-acp-env"}) + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"GITHUB_TOKEN": "from-registry"}, + ) + assert env.get("GITHUB_TOKEN") == "from-acp-env" + + def test_agent_context_secret_takes_precedence_over_registry_secret(self, tmp_path): + """``agent_context.secrets`` wins over the same key in the registry. + + The full precedence ladder is + ``acp_env > provider env > agent_context.secrets > secret_registry``; + the registry is the last-resort fill so callers that explicitly + set ``agent_context.secrets`` keep control over the value. + """ + from pydantic import SecretStr + + from openhands.sdk.secret import StaticSecret + + agent = _make_agent( + agent_context=AgentContext( + secrets={"GITHUB_TOKEN": StaticSecret(value=SecretStr("from-context"))} + ) + ) + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"GITHUB_TOKEN": "from-registry"}, + ) + assert env.get("GITHUB_TOKEN") == "from-context" + + def test_empty_registry_does_not_change_behaviour(self, tmp_path): + """An empty secret_registry must not raise or alter the spawn env.""" + agent = _make_agent(acp_env={"FOO": "bar"}) + env = self._run_start_capturing_env(agent, tmp_path, registry_secrets=None) + assert env.get("FOO") == "bar" + + def test_failing_registry_lookup_swallowed(self, tmp_path): + """A secret source that raises is dropped, not propagated. + + ``SecretRegistry.get_secret_value`` already catches lookup + errors and returns ``None``; the spawn-env loop must treat + that ``None`` as "skip", so a transient secret-source failure + (network blip, expired token) doesn't take the whole ACP + subprocess down. + """ + from openhands.sdk.secret import SecretSource + + class _BrokenSecret(SecretSource): + def get_value(self) -> str | None: + raise OSError("network down") + + agent = _make_agent() + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"BROKEN": _BrokenSecret()}, + ) + assert "BROKEN" not in env + + class TestACPEnvConflictSuppression: """CLAUDE_CONFIG_DIR OAuth auth must not coexist with API-key env vars. From 6cba365297bb2bbebb1fae1ffcfe8df71fb8cfcf Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 19 May 2026 10:28:37 +0200 Subject: [PATCH 2/5] refactor(acp): make secret_registry the canonical conversation-secret channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Refines the env-build ordering in _start_acp_server to the single-rule model: StartConversationRequest.secrets are conversation secrets. For OpenHands agents they're available through the secret registry; for ACP agents they're exposed to the ACP subprocess environment because the ACP subprocess owns execution. Precedence (lowest → highest): default_environment + os.environ baseline state.secret_registry canonical channel agent_context.secrets legacy direct-attach self.acp_env explicit override Behaviour shift: on collision between secret_registry and agent_context.secrets, the registry now wins (was: agent_context). The canonical conversation channel should beat the legacy direct- attach so OpenHands can eventually drop its AgentContext(secrets=...) shim without a behaviour break during the migration. Same-value collisions (today's OpenHands sends through both) produce identical output; only differing-value collisions change, and there are no known callers that do that. Also updates _render_suffix to render the block from state.secret_registry even when agent_context is absent — a conversation that ships secrets only through the canonical channel shouldn't have its agent left ignorant of env vars that are about to be injected into its subprocess. Preserves the "no agent_context + empty registry ⇒ no suffix" guard so the empty AgentContext() defaults (current_datetime, …) don't leak into the prompt. Tests: - Updated the agent_context-vs-registry precedence test to assert the new winner (registry). - Added test_init_state_renders_registry_secrets_without_agent_context pinning the new _render_suffix behaviour. - All 194 tests in test_acp_agent.py + test_agent_secrets_integration.py pass. Co-Authored-By: Claude Opus 4.7 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 98 +++++++++++++------ tests/sdk/agent/test_acp_agent.py | 53 ++++++++-- 2 files changed, 112 insertions(+), 39 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index fe3d95c78b8..fe0f9c01c78 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -45,6 +45,7 @@ from pydantic import Field, PrivateAttr, SecretStr, field_serializer from openhands.sdk.agent.base import AgentBase +from openhands.sdk.context import AgentContext from openhands.sdk.conversation.state import ConversationExecutionStatus from openhands.sdk.event import ( ACPToolCallEvent, @@ -968,10 +969,31 @@ def init_state( ) def _render_suffix(self, state: ConversationState) -> str | None: - """Render the system suffix once, including secrets from the registry.""" - if not self.agent_context: - return None + """Render the system suffix once, including secrets from the registry. + + The ```` block lists every secret the ACP subprocess + will receive, so the agent knows which env vars are available without + them being inlined in the prompt. We render it from + ``state.secret_registry`` even when ``agent_context`` is absent — + otherwise a conversation that only ships secrets through the + ``StartConversationRequest.secrets`` channel (the canonical path) + would silently drop the advertisement, leaving the agent ignorant of + secrets that are nonetheless about to land in its env via + ``_start_acp_server``. + """ secret_infos = state.secret_registry.get_secret_infos() + if self.agent_context is None: + # No caller-supplied context. Only synthesize an empty one for the + # renderer if we actually have a registry-secret advertisement to + # emit — otherwise return None so we don't start injecting other + # parts of the empty AgentContext's defaults (current_datetime, …) + # that the old "agent_context is None ⇒ no suffix" rule used to + # suppress. + if not secret_infos: + return None + return AgentContext(current_datetime=None).to_acp_prompt_context( + additional_secret_infos=secret_infos + ) return self.agent_context.to_acp_prompt_context( additional_secret_infos=secret_infos ) @@ -981,41 +1003,55 @@ def _start_acp_server(self, state: ConversationState) -> None: client = _OpenHandsACPBridge() self._client = client - # Build environment: inherit current env + ACP extras + # Build the subprocess environment. One mental model: + # + # StartConversationRequest.secrets are conversation secrets. + # For OpenHands agents they're available through the secret + # registry; for ACP agents they're exposed to the ACP subprocess + # environment because the ACP subprocess owns execution. + # + # Layering, lowest priority first: + # 1. default_environment + os.environ — the agent-server's own env + # 2. state.secret_registry — conversation secrets, the + # canonical channel callers + # use (Conversation.update_ + # secrets / the equivalent + # ``payload.secrets`` shape + # on app-server clients) + # 3. agent_context.secrets — legacy direct-attach path + # kept so callers that wrap + # secrets in AgentContext + # keep working + # 4. self.acp_env — explicit per-agent override + # (always wins via .update) + # + # Tiers 2 and 3 fill-if-absent, so the host env (e.g. an already-set + # ANTHROPIC_API_KEY on the agent-server) isn't silently shadowed. + # SecretSource.get_value() / SecretRegistry.get_secret_value() are + # synchronous; calling them here is safe because _start_acp_server + # is a regular (non-async) method. Both already swallow lookup + # errors and return None; the ``if value`` guards skip those so a + # transient secret-source failure doesn't crash the spawn. env = default_environment() env.update(os.environ) - env.update(self.acp_env) - # Inject secrets from agent_context. acp_env entries take precedence - # (already set above), so we only fill keys not already present. - # SecretSource.get_value() is synchronous; calling it here is safe - # because _start_acp_server is a regular (non-async) method. - if self.agent_context and self.agent_context.secrets: - for name, secret in self.agent_context.secrets.items(): - if name not in env: - value = ( - secret.get_value() - if isinstance(secret, SecretSource) - else str(secret) - ) - if value: - env[name] = value - # Fill any remaining gaps from the conversation's secret registry — - # secrets sent via ``Conversation.update_secrets()`` (or the - # equivalent ``payload.secrets`` channel that app-server callers - # like agent-canvas use) belong in the ACP subprocess env too, - # without each caller having to also build an - # ``AgentContext(secrets=...)`` shim around the same data. - # ``get_secret_value`` swallows lookup errors and returns ``None``; - # the ``if value`` guard skips those so a transient secret-source - # failure doesn't crash the spawn. - # Precedence stays: ``acp_env > provider env > agent_context.secrets - # > secret_registry`` — registry entries only fill genuine gaps. - for name in state.secret_registry.secret_sources.keys(): + for name in state.secret_registry.secret_sources: if name in env: continue value = state.secret_registry.get_secret_value(name) if value: env[name] = value + if self.agent_context and self.agent_context.secrets: + for name, secret in self.agent_context.secrets.items(): + if name in env: + continue + value = ( + secret.get_value() + if isinstance(secret, SecretSource) + else str(secret) + ) + if value: + env[name] = value + env.update(self.acp_env) # Strip CLAUDECODE so nested Claude Code instances don't refuse to start env.pop("CLAUDECODE", None) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index a8f1a2bd0aa..0f7cad54844 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -598,6 +598,38 @@ def test_init_state_includes_registry_secrets_in_suffix(self, tmp_path): assert events[0].dynamic_context is not None assert "REGISTRY_TOKEN" in events[0].dynamic_context.text + def test_init_state_renders_registry_secrets_without_agent_context(self, tmp_path): + """The block should render from secret_registry alone. + + Callers that ship secrets through the canonical conversation + channel (``StartConversationRequest.secrets`` → + ``Conversation.update_secrets`` → ``secret_registry``) but don't + attach an ``AgentContext`` shouldn't see those secrets silently + dropped from the system suffix — the values still flow into the + subprocess env via ``_start_acp_server``, so the agent needs to + know they're available. + """ + from pydantic import SecretStr + + from openhands.sdk.secret import StaticSecret + + agent = _make_agent() # no agent_context + state = _make_state(tmp_path) + state.secret_registry.update_secrets( + { + "REGISTRY_TOKEN": StaticSecret( + value=SecretStr("tok"), description="Registry token" + ) + } + ) + events: list = [] + + with patch("openhands.sdk.agent.acp_agent.ACPAgent._start_acp_server"): + agent.init_state(state, on_event=events.append) + + assert events[0].dynamic_context is not None + assert "REGISTRY_TOKEN" in events[0].dynamic_context.text + # --------------------------------------------------------------------------- # _OpenHandsACPBridge @@ -3806,13 +3838,18 @@ def test_acp_env_takes_precedence_over_registry_secret(self, tmp_path): ) assert env.get("GITHUB_TOKEN") == "from-acp-env" - def test_agent_context_secret_takes_precedence_over_registry_secret(self, tmp_path): - """``agent_context.secrets`` wins over the same key in the registry. - - The full precedence ladder is - ``acp_env > provider env > agent_context.secrets > secret_registry``; - the registry is the last-resort fill so callers that explicitly - set ``agent_context.secrets`` keep control over the value. + def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_path): + """``secret_registry`` wins over ``agent_context.secrets`` on collision. + + Precedence ladder: + ``acp_env > secret_registry > agent_context.secrets > os.environ``. + The registry is the canonical conversation-secret channel + (``StartConversationRequest.secrets`` lands here); ``agent_context. + secrets`` is the legacy direct-attach path. When both carry the same + key the canonical channel wins — that's also what lets OpenHands + eventually drop its ``AgentContext(secrets=...)`` shim without a + behaviour break for clients that still attach via both paths + during the migration. """ from pydantic import SecretStr @@ -3828,7 +3865,7 @@ def test_agent_context_secret_takes_precedence_over_registry_secret(self, tmp_pa tmp_path, registry_secrets={"GITHUB_TOKEN": "from-registry"}, ) - assert env.get("GITHUB_TOKEN") == "from-context" + assert env.get("GITHUB_TOKEN") == "from-registry" def test_empty_registry_does_not_change_behaviour(self, tmp_path): """An empty secret_registry must not raise or alter the spawn env.""" From 6e8f21bb0a37f6c3b9d04c5a332a9c7320260666 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 19 May 2026 10:36:42 +0200 Subject: [PATCH 3/5] docs(acp): clarify secret env precedence --- .../openhands/sdk/agent/acp_agent.py | 34 ++++++++++--------- tests/sdk/agent/test_acp_agent.py | 12 +++---- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index fe0f9c01c78..ab1ebad4aa7 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -1010,23 +1010,25 @@ def _start_acp_server(self, state: ConversationState) -> None: # registry; for ACP agents they're exposed to the ACP subprocess # environment because the ACP subprocess owns execution. # - # Layering, lowest priority first: - # 1. default_environment + os.environ — the agent-server's own env - # 2. state.secret_registry — conversation secrets, the - # canonical channel callers - # use (Conversation.update_ - # secrets / the equivalent - # ``payload.secrets`` shape - # on app-server clients) - # 3. agent_context.secrets — legacy direct-attach path - # kept so callers that wrap - # secrets in AgentContext - # keep working - # 4. self.acp_env — explicit per-agent override - # (always wins via .update) + # Construction order and same-key precedence: + # 1. Start with default_environment + os.environ as the base + # subprocess env. os.environ wins over default_environment. + # 2. Fill missing keys from state.secret_registry, the canonical + # conversation-secret channel callers use (Conversation.update_ + # secrets / the equivalent ``payload.secrets`` shape on + # app-server clients). + # 3. Fill still-missing keys from agent_context.secrets, the legacy + # direct-attach path kept so callers that wrap secrets in + # AgentContext keep working. + # 4. Apply self.acp_env last as the explicit per-agent override. # - # Tiers 2 and 3 fill-if-absent, so the host env (e.g. an already-set - # ANTHROPIC_API_KEY on the agent-server) isn't silently shadowed. + # Effective precedence is: + # self.acp_env > os.environ > default_environment > + # state.secret_registry > agent_context.secrets + # + # Registry/context tiers fill-if-absent, so the host env (e.g. an + # already-set ANTHROPIC_API_KEY on the agent-server) is not silently + # shadowed. # SecretSource.get_value() / SecretRegistry.get_secret_value() are # synchronous; calling them here is safe because _start_acp_server # is a regular (non-async) method. Both already swallow lookup diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 0f7cad54844..5bf6b396173 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -3727,9 +3727,9 @@ class TestACPSecretRegistryEnvInjection: ACP subprocess env without each caller having to also build an ``AgentContext(secrets=...)`` shim around the same data. - Precedence is preserved as: ``acp_env > provider env > - agent_context.secrets > secret_registry`` — registry entries fill - only genuine gaps. + Same-key precedence is + ``acp_env > existing base env > secret_registry > agent_context.secrets``. + Registry and context entries only fill genuine gaps in the base env. """ @staticmethod @@ -3841,8 +3841,8 @@ def test_acp_env_takes_precedence_over_registry_secret(self, tmp_path): def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_path): """``secret_registry`` wins over ``agent_context.secrets`` on collision. - Precedence ladder: - ``acp_env > secret_registry > agent_context.secrets > os.environ``. + Precedence ladder for this collision: + ``acp_env > existing base env > secret_registry > agent_context.secrets``. The registry is the canonical conversation-secret channel (``StartConversationRequest.secrets`` lands here); ``agent_context. secrets`` is the legacy direct-attach path. When both carry the same @@ -3906,7 +3906,7 @@ class TestACPEnvConflictSuppression: does not support OAuth bearer tokens, breaking auth silently. _start_acp_server must strip the conflicting vars regardless of where they - came from: acp_env, os.environ, or agent_context.secrets. + came from: acp_env, os.environ, secret_registry, or agent_context.secrets. """ @staticmethod From 9d0b2a95f8fa54e8be5bff1dac132d4c855d284b Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Wed, 20 May 2026 15:24:36 +0200 Subject: [PATCH 4/5] fix(acp): apply acp_env before resolving registry/context secrets Move env.update(self.acp_env) ahead of the registry/agent_context secret-resolution loops so the existing "if name in env: continue" guards skip lookups for keys an explicit acp_env entry will override. Previously a LookupSecret in the registry (or a SecretSource in agent_context.secrets) with the same key as an acp_env entry triggered an unnecessary HTTP round-trip / warning before being overwritten. Same documented precedence: acp_env > os.environ > default_environment > secret_registry > agent_context.secrets Co-Authored-By: Claude Opus 4.7 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 37 ++++--------------- tests/sdk/agent/test_acp_agent.py | 29 +++++++++++++++ 2 files changed, 36 insertions(+), 30 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index ab1ebad4aa7..de555b38d99 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -1003,39 +1003,17 @@ def _start_acp_server(self, state: ConversationState) -> None: client = _OpenHandsACPBridge() self._client = client - # Build the subprocess environment. One mental model: - # - # StartConversationRequest.secrets are conversation secrets. - # For OpenHands agents they're available through the secret - # registry; for ACP agents they're exposed to the ACP subprocess - # environment because the ACP subprocess owns execution. - # - # Construction order and same-key precedence: - # 1. Start with default_environment + os.environ as the base - # subprocess env. os.environ wins over default_environment. - # 2. Fill missing keys from state.secret_registry, the canonical - # conversation-secret channel callers use (Conversation.update_ - # secrets / the equivalent ``payload.secrets`` shape on - # app-server clients). - # 3. Fill still-missing keys from agent_context.secrets, the legacy - # direct-attach path kept so callers that wrap secrets in - # AgentContext keep working. - # 4. Apply self.acp_env last as the explicit per-agent override. - # - # Effective precedence is: - # self.acp_env > os.environ > default_environment > + # Build the subprocess environment top-down, highest precedence first: + # acp_env > os.environ > default_environment > # state.secret_registry > agent_context.secrets # - # Registry/context tiers fill-if-absent, so the host env (e.g. an - # already-set ANTHROPIC_API_KEY on the agent-server) is not silently - # shadowed. - # SecretSource.get_value() / SecretRegistry.get_secret_value() are - # synchronous; calling them here is safe because _start_acp_server - # is a regular (non-async) method. Both already swallow lookup - # errors and return None; the ``if value`` guards skip those so a - # transient secret-source failure doesn't crash the spawn. + # Secret tiers fill-if-absent. The ``name in env`` guard does double + # duty: it preserves higher-precedence values and avoids calling + # SecretSource.get_value() for keys already satisfied — important + # because LookupSecret can make an HTTP request. env = default_environment() env.update(os.environ) + env.update(self.acp_env) for name in state.secret_registry.secret_sources: if name in env: continue @@ -1053,7 +1031,6 @@ def _start_acp_server(self, state: ConversationState) -> None: ) if value: env[name] = value - env.update(self.acp_env) # Strip CLAUDECODE so nested Claude Code instances don't refuse to start env.pop("CLAUDECODE", None) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 5bf6b396173..026c70798de 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -3838,6 +3838,35 @@ def test_acp_env_takes_precedence_over_registry_secret(self, tmp_path): ) assert env.get("GITHUB_TOKEN") == "from-acp-env" + def test_acp_env_shadow_skips_registry_lookup(self, tmp_path): + """``acp_env`` shadowing a key must not trigger ``get_value()``. + + LookupSecret performs an HTTP request in production; calling it for + a key that ``acp_env`` is about to override wastes a round-trip and + can emit spurious lookup-failure warnings. + """ + from pydantic import Field + + from openhands.sdk.secret import SecretSource + + class _CountingLookupSecret(SecretSource): + stored_value: str + calls: list[int] = Field(default_factory=list) + + def get_value(self) -> str | None: + self.calls.append(1) + return self.stored_value + + secret = _CountingLookupSecret(stored_value="from-registry") + agent = _make_agent(acp_env={"GITHUB_TOKEN": "from-acp-env"}) + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"GITHUB_TOKEN": secret}, + ) + assert env.get("GITHUB_TOKEN") == "from-acp-env" + assert secret.calls == [] + def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_path): """``secret_registry`` wins over ``agent_context.secrets`` on collision. From 08b3f28d3c000b44a28b57a2f0930926942e6074 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Wed, 20 May 2026 15:40:51 +0200 Subject: [PATCH 5/5] docs(acp): mention secret_registry in resolve_acp_env precedence The docstring on ACPAgentSettings.resolve_acp_env still documented the pre-secret-registry precedence (acp_env > provider env > agent_context.secrets) and omitted the canonical conversation-secret channel entirely. Update it to reflect what ACPAgent._start_acp_server actually does today. Co-Authored-By: Claude Opus 4.7 (1M context) --- openhands-sdk/openhands/sdk/settings/model.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index 6fff5b7f45d..350c030f74a 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -1190,10 +1190,13 @@ def resolve_acp_env(self) -> dict[str, str]: """Return the effective ACP subprocess environment. Explicit :attr:`acp_env` entries override provider-derived env vars. - ``ACPAgent`` then injects :attr:`agent_context` secrets only for keys - that are still absent, preserving the overall priority: + The returned dict becomes ``ACPAgent.acp_env``; at spawn time + ``ACPAgent`` then fills still-missing keys from the conversation's + ``secret_registry`` (the canonical conversation-secret channel) and + finally from :attr:`agent_context` secrets, preserving the overall + priority: - ``acp_env > provider env > agent_context.secrets``. + ``acp_env > provider env > secret_registry > agent_context.secrets``. """ return { **self.resolve_provider_env(),