From 791c1a94e86e012796d3e596508c37ebbab795b0 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 16:30:39 +0200 Subject: [PATCH 1/7] fix(acp): route provider creds through secret_registry, not acp_env MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ACP folded provider credentials (llm.api_key/base_url) into `acp_env`, which is persisted inside `agent_settings`. SaaS stores dump `agent_settings` via `model_dump(mode='json')` with no cipher context, so `acp_env` is redacted to `**********` at persist — silently dropping cloud-injected creds. `acp_env` is also not masked in subprocess output. Re-route consumption onto `state.secret_registry` — the single, cipher-protected channel the regular agent uses — while KEEPING the public `acp_env` field as the user-facing arbitrary-env-var input (non-breaking; canvas / ts-client / OpenHands schema unchanged). - `ACPAgentSettings.create_agent()` folds provider creds into `agent_context.secrets` (wrapped as StaticSecret) instead of `acp_env`. They ride the canonical `agent_context.secrets` -> `create_request` -> `request.secrets` -> `state.secret_registry` lift, encrypted across the conversation-start boundary, exactly like the LLM api_key. - `resolve_acp_env()` no longer folds provider env in; it returns only the user's explicit `acp_env` entries. - `_start_acp_server` drops the direct `agent_context.secrets` -> env drain; `agent_context.secrets` is now prompt-only (advertised, injected via the registry), matching the regular agent. `acp_env` injection is kept. Fixes the cloud at-rest credential drop by construction. Implements pre-cloud refactor P0-1 of OpenHands/agent-canvas#1022. Pairs with #1020. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 27 ++-- openhands-sdk/openhands/sdk/settings/model.py | 70 +++++++--- tests/sdk/agent/test_acp_agent.py | 131 ++++++++---------- tests/sdk/test_settings.py | 87 +++++++++++- 4 files changed, 200 insertions(+), 115 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index 77592758475..149c4d723b2 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -68,7 +68,6 @@ from openhands.sdk.llm import LLM, ImageContent, Message, MessageToolCall, TextContent from openhands.sdk.logger import get_logger from openhands.sdk.observability.laminar import maybe_init_laminar, observe -from openhands.sdk.secret import SecretSource from openhands.sdk.settings.acp_providers import ( build_session_model_meta, detect_acp_provider_by_agent_name, @@ -1329,11 +1328,18 @@ def _start_acp_server(self, state: ConversationState) -> None: self._client = client # Build the subprocess environment top-down, highest precedence first: - # acp_env > os.environ > default_environment > - # state.secret_registry > agent_context.secrets + # acp_env > os.environ > default_environment > state.secret_registry # - # Secret tiers fill-if-absent. The ``name in env`` guard does double - # duty: it preserves higher-precedence values and avoids calling + # All conversation credentials (provider api_key/base_url, git tokens, + # …) arrive via state.secret_registry — the single, cipher-protected + # channel the regular agent uses. agent_context.secrets is NOT drained + # into env here: it stays prompt-only (names/descriptions advertised in + # the system suffix), matching the regular agent. It still reaches the + # registry on the conversation-start path because create_request lifts + # agent_context.secrets → request.secrets → state.secret_registry. + # + # The registry tier fills-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() @@ -1345,17 +1351,6 @@ def _start_acp_server(self, state: ConversationState) -> None: 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 # Strip CLAUDECODE so nested Claude Code instances don't refuse to start env.pop("CLAUDECODE", None) diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index bde93041dde..88503a1a89c 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -1103,8 +1103,12 @@ def _serialize_acp_env(self, value: dict[str, str], info): agent_context: AgentContext | None = Field( default=None, description=( - "Prompt-only context for the ACP server. Secrets are injected into " - "the subprocess environment by ACPAgent." + "Prompt-only context for the ACP server. ``secrets`` here are " + "advertised to the agent (names/descriptions) and reach the " + "subprocess env via ``state.secret_registry`` — create_request " + "lifts ``agent_context.secrets`` into the registry — not by a " + "direct ACPAgent drain. create_agent also folds provider " + "credentials into these secrets." ), ) @@ -1164,21 +1168,17 @@ def resolve_provider_env(self) -> dict[str, str]: return env def resolve_acp_env(self) -> dict[str, str]: - """Return the effective ACP subprocess environment. - - Explicit :attr:`acp_env` entries override provider-derived env vars. - 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 > secret_registry > agent_context.secrets``. + """Return the user-supplied ACP subprocess env vars. + + Only the explicit :attr:`acp_env` entries — the user-facing + arbitrary-env-var input that becomes ``ACPAgent.acp_env``. Provider + credentials are **no longer** folded in here; :meth:`create_agent` + routes them through :attr:`agent_context` secrets → + ``state.secret_registry`` instead (the canonical, cipher-protected + channel the regular agent uses). At spawn time ``ACPAgent`` injects + ``acp_env`` and the registry secrets into the subprocess env. """ - return { - **self.resolve_provider_env(), - **dict(self.acp_env), - } + return dict(self.acp_env) def resolve_acp_command(self) -> list[str]: """Return the effective subprocess command for this settings block. @@ -1208,8 +1208,44 @@ def create_agent(self) -> ACPAgent: The subprocess command is resolved via :meth:`resolve_acp_command` which maps :attr:`acp_server` to a default when no explicit :attr:`acp_command` is set. + + Provider credentials (``llm.api_key`` → :attr:`api_key_env_var`, + ``llm.base_url`` → :attr:`base_url_env_var`) are folded into + :attr:`agent_context` secrets rather than ``acp_env``. They then ride + the canonical ``agent_context.secrets`` → ``create_request`` → + ``request.secrets`` → ``state.secret_registry`` channel (encrypted + across the conversation-start boundary), exactly like the regular + agent's credentials, and reach the subprocess from the registry. + ``acp_env`` carries only the user's explicit arbitrary env vars. """ from openhands.sdk.agent import ACPAgent + from openhands.sdk.secret import StaticSecret + + # Fold provider creds into agent_context.secrets (not acp_env): on + # acp_env they would be dropped to ``**********`` by stores that dump + # agent_settings without cipher context; on agent_context.secrets they + # ride the StoredConversation.secrets + agent-server Cipher boundary. + # Wrap as StaticSecret (a SecretSource) so they validate when + # create_request lifts agent_context.secrets into request.secrets + # (typed dict[str, SecretSource]). + provider_secrets: dict[str, Any] = { + name: StaticSecret(value=SecretStr(value)) + for name, value in self.resolve_provider_env().items() + } + agent_context = self.agent_context + if provider_secrets: + existing = ( + dict(agent_context.secrets) + if agent_context is not None and agent_context.secrets + else {} + ) + # Explicit context secrets win over provider-derived ones. + merged_secrets = {**provider_secrets, **existing} + agent_context = ( + agent_context.model_copy(update={"secrets": merged_secrets}) + if agent_context is not None + else AgentContext(current_datetime=None, secrets=merged_secrets) + ) return ACPAgent( llm=self.llm, @@ -1219,7 +1255,7 @@ def create_agent(self) -> ACPAgent: acp_model=self.acp_model, acp_session_mode=self.acp_session_mode, acp_prompt_timeout=self.acp_prompt_timeout, - agent_context=self.agent_context, + agent_context=agent_context, ) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 734179c3c5b..9a499072b37 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5233,11 +5233,15 @@ def test_roundtrip_via_conversation_state_persistence(self, tmp_path): class TestACPSecretsEnvInjection: - """Tests for secret injection into the ACP subprocess environment. - - Secrets passed via ``agent_context.secrets`` must land in the subprocess - env so the ACP server (Claude Code, Codex CLI, etc.) can use them. - ``acp_env`` entries take precedence over agent_context secrets. + """``agent_context.secrets`` is prompt-only — NOT drained into the env. + + Credentials reach the ACP subprocess exclusively via + ``state.secret_registry`` (the canonical channel; ``agent_context.secrets`` + reaches it on the conversation-start path because ``create_request`` lifts + ``agent_context.secrets`` → ``request.secrets`` → ``state.secret_registry``). + ``_start_acp_server`` must therefore NOT read ``agent_context.secrets`` + directly — matching the regular agent, where context secrets are advertised + in the prompt but injected only through the registry. """ @staticmethod @@ -5312,8 +5316,15 @@ async def _fake_filter(_src, _dst): return captured - def test_static_secret_injected_into_subprocess_env(self, tmp_path): - """A StaticSecret in agent_context.secrets lands in the subprocess env.""" + def test_agent_context_secrets_not_drained_into_env(self, tmp_path): + """``agent_context.secrets`` are NOT injected directly by the spawn path. + + With the drain removed, a secret that lives only on + ``agent_context.secrets`` (and never made it into ``state.secret_registry``) + does not reach the subprocess env. In production it always reaches the + registry first via ``create_request``; this guards that the spawn path + itself no longer reads ``agent_context.secrets``. + """ from pydantic import SecretStr from openhands.sdk.secret import StaticSecret @@ -5329,48 +5340,13 @@ def test_static_secret_injected_into_subprocess_env(self, tmp_path): ) ) env = self._run_start_capturing_env(agent, tmp_path) - assert env.get("GITHUB_TOKEN") == "ghp_test123" - - def test_acp_env_takes_precedence_over_agent_context_secret(self, tmp_path): - """An explicit acp_env entry wins over the same key in agent_context.secrets.""" - from pydantic import SecretStr - - from openhands.sdk.secret import StaticSecret - - agent = _make_agent( - acp_env={"MY_TOKEN": "acp-env-wins"}, - agent_context=AgentContext( - secrets={"MY_TOKEN": StaticSecret(value=SecretStr("secret-panel"))} - ), - ) - env = self._run_start_capturing_env(agent, tmp_path) - assert env.get("MY_TOKEN") == "acp-env-wins" + assert "GITHUB_TOKEN" not in env - def test_none_value_secret_not_injected(self, tmp_path): - """A StaticSecret with value=None is not added to the subprocess env.""" - from openhands.sdk.secret import StaticSecret - - agent = _make_agent( - agent_context=AgentContext( - secrets={"ABSENT_SECRET": StaticSecret(value=None)} - ) - ) + def test_acp_env_still_injected(self, tmp_path): + """``acp_env`` (user arbitrary env vars) is still injected at spawn.""" + agent = _make_agent(acp_env={"MY_TOKEN": "acp-env-value"}) env = self._run_start_capturing_env(agent, tmp_path) - assert "ABSENT_SECRET" not in env - - def test_empty_string_secret_not_injected(self, tmp_path): - """Empty string secrets are not injected into the subprocess env.""" - from pydantic import SecretStr - - from openhands.sdk.secret import StaticSecret - - agent = _make_agent( - agent_context=AgentContext( - secrets={"EMPTY_SECRET": StaticSecret(value=SecretStr(""))} - ) - ) - env = self._run_start_capturing_env(agent, tmp_path) - assert "EMPTY_SECRET" not in env + assert env.get("MY_TOKEN") == "acp-env-value" class TestACPSecretRegistryEnvInjection: @@ -5522,18 +5498,15 @@ def get_value(self) -> str | None: 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. + def test_registry_is_sole_cred_source_not_agent_context(self, tmp_path): + """Only ``secret_registry`` feeds env — ``agent_context.secrets`` does not. - 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 - 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. + (``StartConversationRequest.secrets`` lands here, and ``create_request`` + lifts ``agent_context.secrets`` into it). ``_start_acp_server`` reads the + registry only: a key present in both ``agent_context.secrets`` and the + registry resolves to the registry value, and a key present only in + ``agent_context.secrets`` (here a distinct one) is never drained. """ from pydantic import SecretStr @@ -5541,7 +5514,10 @@ def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_pa agent = _make_agent( agent_context=AgentContext( - secrets={"GITHUB_TOKEN": StaticSecret(value=SecretStr("from-context"))} + secrets={ + "GITHUB_TOKEN": StaticSecret(value=SecretStr("from-context")), + "CONTEXT_ONLY": StaticSecret(value=SecretStr("ctx-value")), + } ) ) env = self._run_start_capturing_env( @@ -5550,6 +5526,7 @@ def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_pa registry_secrets={"GITHUB_TOKEN": "from-registry"}, ) assert env.get("GITHUB_TOKEN") == "from-registry" + assert "CONTEXT_ONLY" not in env def test_empty_registry_does_not_change_behaviour(self, tmp_path): """An empty secret_registry must not raise or alter the spawn env.""" @@ -5590,7 +5567,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, secret_registry, or agent_context.secrets. + came from: acp_env, os.environ, or secret_registry. """ @staticmethod @@ -5613,7 +5590,9 @@ def _make_conn(): return conn @staticmethod - def _run_start_capturing_env(agent, tmp_path, *, extra_os_env=None) -> dict: + def _run_start_capturing_env( + agent, tmp_path, *, extra_os_env=None, registry_secrets=None + ) -> dict: from contextlib import ExitStack from openhands.sdk.utils.async_executor import AsyncExecutor @@ -5633,6 +5612,8 @@ async def _fake_filter(_src, _dst): return None state = _make_state(tmp_path) + if registry_secrets: + state.secret_registry.update_secrets(registry_secrets) agent._executor = AsyncExecutor() with ExitStack() as stack: @@ -5699,26 +5680,24 @@ def test_claude_config_dir_suppresses_api_key_from_os_environ(self, tmp_path): assert "ANTHROPIC_API_KEY" not in env assert "ANTHROPIC_BASE_URL" not in env - def test_claude_config_dir_suppresses_api_key_from_secrets(self, tmp_path): - """ANTHROPIC_API_KEY injected via agent_context.secrets is stripped too.""" - from pydantic import SecretStr - - from openhands.sdk.secret import StaticSecret + def test_claude_config_dir_suppresses_api_key_from_registry(self, tmp_path): + """ANTHROPIC_API_KEY injected via secret_registry is stripped too. + This is the channel provider creds now travel on (folded into + ``agent_context.secrets`` by ``create_agent`` → lifted into the + registry by ``create_request``). + """ agent = _make_agent( acp_env={"CLAUDE_CONFIG_DIR": "/tmp/claude-creds"}, - agent_context=AgentContext( - secrets={ - "ANTHROPIC_API_KEY": StaticSecret( - value=SecretStr("sk-from-secret") - ), - "ANTHROPIC_BASE_URL": StaticSecret( - value=SecretStr("https://proxy.example.com") - ), - } - ), ) - env = self._run_start_capturing_env(agent, tmp_path) + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={ + "ANTHROPIC_API_KEY": "sk-from-registry", + "ANTHROPIC_BASE_URL": "https://proxy.example.com", + }, + ) assert "CLAUDE_CONFIG_DIR" in env assert "ANTHROPIC_API_KEY" not in env diff --git a/tests/sdk/test_settings.py b/tests/sdk/test_settings.py index 2f8222d72fe..cae78ba308f 100644 --- a/tests/sdk/test_settings.py +++ b/tests/sdk/test_settings.py @@ -23,6 +23,7 @@ from openhands.sdk.context.condenser import LLMSummarizingCondenser from openhands.sdk.critic.base import IterativeRefinementConfig from openhands.sdk.critic.impl.api import APIBasedCritic +from openhands.sdk.secret import StaticSecret from openhands.sdk.security.confirmation_policy import AlwaysConfirm, ConfirmRisky from openhands.sdk.security.llm_analyzer import LLMSecurityAnalyzer from openhands.sdk.settings import ( @@ -243,6 +244,30 @@ def test_conversation_settings_create_request_with_acp_agent() -> None: assert request.security_analyzer is None +def test_acp_create_request_lifts_provider_creds_into_request_secrets() -> None: + # End-to-end: provider creds folded into agent_context.secrets by + # create_agent are lifted into request.secrets by create_request — the + # channel that lands them in state.secret_registry on the agent-server, + # from where _start_acp_server injects them into the subprocess env. + agent = ACPAgentSettings( + acp_server="claude-code", + llm=LLM(model="claude-opus-4-6", api_key=SecretStr("sk-provider")), + agent_context=AgentContext( + secrets={"GITHUB_TOKEN": StaticSecret(value=SecretStr("ghp_x"))} + ), + ).create_agent() + + request = ConversationSettings().create_request( + StartConversationRequest, + agent=agent, + workspace=LocalWorkspace(working_dir="/tmp"), + ) + + assert set(request.secrets) == {"ANTHROPIC_API_KEY", "GITHUB_TOKEN"} + assert request.secrets["ANTHROPIC_API_KEY"].get_value() == "sk-provider" + assert request.secrets["GITHUB_TOKEN"].get_value() == "ghp_x" + + # --------------------------------------------------------------------------- # Schema export — combined (discriminated union) # --------------------------------------------------------------------------- @@ -641,28 +666,78 @@ def test_acp_resolve_provider_env_custom_server_empty() -> None: assert settings.resolve_provider_env() == {} -def test_acp_resolve_acp_env_explicit_entries_override_provider_env() -> None: +def test_acp_resolve_acp_env_returns_only_user_entries() -> None: + # Provider creds are no longer folded into acp_env; resolve_acp_env returns + # only the user's explicit env vars. The provider api_key now flows through + # agent_context.secrets instead (see create_agent). settings = ACPAgentSettings( acp_server="claude-code", llm=LLM(model="claude-opus-4-6", api_key=SecretStr("sk-ui-key")), - acp_env={"ANTHROPIC_API_KEY": "sk-explicit-override"}, + acp_env={"MY_CUSTOM_VAR": "value"}, ) - assert settings.resolve_acp_env() == {"ANTHROPIC_API_KEY": "sk-explicit-override"} + assert settings.resolve_acp_env() == {"MY_CUSTOM_VAR": "value"} -def test_acp_create_agent_passes_resolved_env_and_agent_context() -> None: +def test_acp_create_agent_folds_provider_creds_into_agent_context_secrets() -> None: context = AgentContext(secrets={"GITHUB_TOKEN": "ghp_test"}) settings = ACPAgentSettings( acp_server="codex", llm=LLM(model="gpt-5.4", api_key=SecretStr("sk-openai")), agent_context=context, + acp_env={"MY_VAR": "v"}, + ) + + agent = settings.create_agent() + + # acp_env carries only the user's explicit env vars — not provider creds. + assert agent.acp_env == {"MY_VAR": "v"} + # Provider creds are folded into agent_context.secrets (wrapped as + # SecretSource) alongside the caller's secrets, so they ride the + # create_request → request.secrets → state.secret_registry channel and + # reach the subprocess from the registry. + assert agent.agent_context is not None + secrets = dict(agent.agent_context.secrets or {}) + assert set(secrets) == {"OPENAI_API_KEY", "GITHUB_TOKEN"} + openai_secret = secrets["OPENAI_API_KEY"] + assert isinstance(openai_secret, StaticSecret) + assert openai_secret.get_value() == "sk-openai" + assert secrets["GITHUB_TOKEN"] == "ghp_test" + + +def test_acp_create_agent_synthesizes_context_for_provider_creds() -> None: + # No caller agent_context, but provider creds exist → create_agent + # synthesizes a minimal AgentContext carrying them (current_datetime=None so + # it doesn't start injecting datetime the absent-context path suppressed). + settings = ACPAgentSettings( + acp_server="claude-code", + llm=LLM(model="claude-opus-4-6", api_key=SecretStr("sk-ui-key")), + ) + + agent = settings.create_agent() + + assert agent.acp_env == {} + assert agent.agent_context is not None + assert agent.agent_context.current_datetime is None + secrets = dict(agent.agent_context.secrets or {}) + assert set(secrets) == {"ANTHROPIC_API_KEY"} + anthropic_secret = secrets["ANTHROPIC_API_KEY"] + assert isinstance(anthropic_secret, StaticSecret) + assert anthropic_secret.get_value() == "sk-ui-key" + + +def test_acp_create_agent_no_provider_creds_keeps_context_none() -> None: + # Custom server (no api_key_env_var) → no provider secrets → agent_context + # stays None when the caller supplied none. + settings = ACPAgentSettings( + acp_server="custom", + acp_command=["custom-acp"], + llm=LLM(model="m", api_key=SecretStr("sk-test")), ) agent = settings.create_agent() - assert agent.acp_env == {"OPENAI_API_KEY": "sk-openai"} - assert agent.agent_context == context + assert agent.agent_context is None def test_llm_agent_settings_public_alias_removed() -> None: From a536aa07070f27e4204016a15760054d59ef4cb3 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 16:44:45 +0200 Subject: [PATCH 2/7] chore: tighten provider_secrets type to dict[str, StaticSecret] (#3464) Address PR review: every value is a StaticSecret, so the dict[str, Any] annotation was broader than necessary. Co-Authored-By: Claude Opus 4.8 (1M context) --- openhands-sdk/openhands/sdk/settings/model.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index 88503a1a89c..1849cc16429 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -1228,7 +1228,7 @@ def create_agent(self) -> ACPAgent: # Wrap as StaticSecret (a SecretSource) so they validate when # create_request lifts agent_context.secrets into request.secrets # (typed dict[str, SecretSource]). - provider_secrets: dict[str, Any] = { + provider_secrets: dict[str, StaticSecret] = { name: StaticSecret(value=SecretStr(value)) for name, value in self.resolve_provider_env().items() } From 4b3bbdcbb3babf3d7f438d05bd351ce63496f64f Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 19:22:48 +0200 Subject: [PATCH 3/7] chore(acp): deprecate acp_env in favor of state.secret_registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Now that provider creds (and the regular secret channel) flow through state.secret_registry, acp_env is a redundant, persist-unsafe channel. Mark it deprecated so a future PR can delete it once the API-breakage checker's 5-minor-release runway has elapsed. - warn_deprecated("ACPAgentSettings.acp_env" / "ACPAgent.acp_env", deprecated_in="1.24.0", removed_in="1.29.0") fires when a non-empty acp_env is actually used (resolve_acp_env / _start_acp_server); empty acp_env is silent. This registers the qualified-name deprecation metadata the check_sdk_api_breakage.py runway requires for a clean removal at >=1.29.0. - Field descriptions on both classes note the deprecation + migration path (metadata-only; non-breaking). - The field still works (still injected at spawn) — this commit only warns. Tests: assert the warning fires on use and stays silent when acp_env is empty. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 19 +++++++++++++- openhands-sdk/openhands/sdk/settings/model.py | 26 ++++++++++++++++++- tests/sdk/agent/test_acp_agent.py | 13 +++++++++- tests/sdk/test_settings.py | 18 +++++++++++++ 4 files changed, 73 insertions(+), 3 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index 149c4d723b2..abb0ea55786 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -75,6 +75,7 @@ from openhands.sdk.tool import Tool # noqa: TC002 from openhands.sdk.tool.builtins.finish import FinishAction, FinishObservation from openhands.sdk.utils import maybe_truncate +from openhands.sdk.utils.deprecation import warn_deprecated from openhands.sdk.utils.pydantic_secrets import ( serialize_secret, validate_secret_dict, @@ -831,7 +832,12 @@ class ACPAgent(AgentBase): ) acp_env: dict[str, str] = Field( default_factory=dict, - description="Additional environment variables for the ACP server process", + description=( + "DEPRECATED (removed in 1.29.0): additional environment variables for " + "the ACP server process. Route subprocess env/credentials through " + "state.secret_registry (e.g. agent_context.secrets / " + "StartConversationRequest.secrets) instead." + ), ) @field_validator("acp_env", mode="before") @@ -1344,6 +1350,17 @@ def _start_acp_server(self, state: ConversationState) -> None: # because LookupSecret can make an HTTP request. env = default_environment() env.update(os.environ) + if self.acp_env: + warn_deprecated( + "ACPAgent.acp_env", + deprecated_in="1.24.0", + removed_in="1.29.0", + details=( + "Route ACP subprocess env/credentials through " + "state.secret_registry (e.g. agent_context.secrets / " + "StartConversationRequest.secrets) instead." + ), + ) env.update(self.acp_env) for name in state.secret_registry.secret_sources: if name in env: diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index 1849cc16429..93bf99d5eb0 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -40,6 +40,7 @@ from openhands.sdk.subagent.schema import AgentDefinition from openhands.sdk.tool import Tool from openhands.sdk.utils.cipher import Cipher +from openhands.sdk.utils.deprecation import warn_deprecated from openhands.sdk.utils.pydantic_secrets import ( MissingCipherError, decrypt_str_with_cipher_or_keep, @@ -999,7 +1000,13 @@ class ACPAgentSettings(AgentSettingsBase): ) acp_env: dict[str, str] = Field( default_factory=dict, - description="Extra environment variables passed to the ACP subprocess.", + description=( + "DEPRECATED (removed in 1.29.0): extra environment variables passed " + "to the ACP subprocess. Provide arbitrary subprocess env vars through " + "the conversation secrets channel (agent_context.secrets / " + "StartConversationRequest.secrets, which route through " + "state.secret_registry) instead." + ), json_schema_extra={ SETTINGS_METADATA_KEY: SettingsFieldMetadata( label="ACP environment variables", @@ -1177,7 +1184,24 @@ def resolve_acp_env(self) -> dict[str, str]: ``state.secret_registry`` instead (the canonical, cipher-protected channel the regular agent uses). At spawn time ``ACPAgent`` injects ``acp_env`` and the registry secrets into the subprocess env. + + .. deprecated:: 1.24.0 + :attr:`acp_env` is deprecated and will be removed in 1.29.0. Pass + arbitrary subprocess env vars through the conversation secrets + channel instead. """ + if self.acp_env: + warn_deprecated( + "ACPAgentSettings.acp_env", + deprecated_in="1.24.0", + removed_in="1.29.0", + details=( + "Provide arbitrary ACP subprocess env vars through the " + "conversation secrets channel (agent_context.secrets / " + "StartConversationRequest.secrets, which route through " + "state.secret_registry) instead." + ), + ) return dict(self.acp_env) def resolve_acp_command(self) -> list[str]: diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 9a499072b37..a1e4fed5623 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5345,9 +5345,20 @@ def test_agent_context_secrets_not_drained_into_env(self, tmp_path): def test_acp_env_still_injected(self, tmp_path): """``acp_env`` (user arbitrary env vars) is still injected at spawn.""" agent = _make_agent(acp_env={"MY_TOKEN": "acp-env-value"}) - env = self._run_start_capturing_env(agent, tmp_path) + with pytest.warns(DeprecationWarning, match=r"ACPAgent\.acp_env"): + env = self._run_start_capturing_env(agent, tmp_path) assert env.get("MY_TOKEN") == "acp-env-value" + def test_empty_acp_env_does_not_warn(self, tmp_path): + """An empty ``acp_env`` must not emit the deprecation warning.""" + import warnings + + agent = _make_agent() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + self._run_start_capturing_env(agent, tmp_path) + assert not [w for w in caught if "acp_env" in str(w.message)] + class TestACPSecretRegistryEnvInjection: """Tests for secret injection from the conversation's secret_registry. diff --git a/tests/sdk/test_settings.py b/tests/sdk/test_settings.py index cae78ba308f..a56a6cb4fc6 100644 --- a/tests/sdk/test_settings.py +++ b/tests/sdk/test_settings.py @@ -740,6 +740,24 @@ def test_acp_create_agent_no_provider_creds_keeps_context_none() -> None: assert agent.agent_context is None +def test_acp_env_emits_deprecation_warning() -> None: + # acp_env is deprecated (removed in 1.29.0); using it warns so callers + # migrate to the secret_registry channel before the field is deleted. + settings = ACPAgentSettings(acp_server="claude-code", acp_env={"MY_VAR": "v"}) + with pytest.warns(DeprecationWarning, match=r"ACPAgentSettings\.acp_env"): + assert settings.resolve_acp_env() == {"MY_VAR": "v"} + + +def test_acp_env_empty_does_not_warn() -> None: + import warnings + + settings = ACPAgentSettings(acp_server="claude-code") + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + settings.resolve_acp_env() + assert not [w for w in caught if "acp_env" in str(w.message)] + + def test_llm_agent_settings_public_alias_removed() -> None: """The deprecated ``LLMAgentSettings`` public import aliases were removed in v1.24.0; the class itself is retained (internal-only) for the union.""" From 41cecba4c57fb68812f6fedb187015e9c172b8f2 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 19:40:03 +0200 Subject: [PATCH 4/7] fix(acp): restore agent_context.secrets drain (canvas-local regression) Deleting the agent_context.secrets -> env drain in _start_acp_server (relying on create_request to lift agent_context.secrets -> request.secrets -> state.secret_registry) regressed the canvas-local path: - canvas builds StartConversationRequest in TypeScript and sets the provider key on llm.api_key (agent-server-adapter.ts:598-600); it never calls the Python create_request lift. - the agent-server seeds the registry ONLY from request.secrets (event_service.py:762); there is no server-side agent_context.secrets -> registry merge. So on canvas the folded ANTHROPIC_API_KEY landed in agent_context.secrets, was never lifted into the registry, and -- with the drain gone -- never reached the CLI (auth failure). Verified end-to-end: with the registry empty and the key only in agent_context.secrets, the restored drain delivers it and a real claude-agent-acp call succeeds. Keep the create_agent at-rest fix (provider creds -> agent_context.secrets, off the redacted acp_env). Restore the drain: it runs AFTER the registry loop and is fill-if-absent, so OpenHands (creds already in the registry) skips it and canvas backfills -- no double-injection. An ACP subprocess is a black box the SDK can't name-scan per command, so upfront injection is required; the drain is the correct mechanism, not a shim. It can be removed only once a server-side agent_context.secrets -> registry lift exists on every path. Revert the tests that asserted the drain was gone. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 46 +++++-- tests/sdk/agent/test_acp_agent.py | 123 ++++++++++++++---- 2 files changed, 132 insertions(+), 37 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index abb0ea55786..cf8bc231986 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -68,6 +68,7 @@ from openhands.sdk.llm import LLM, ImageContent, Message, MessageToolCall, TextContent from openhands.sdk.logger import get_logger from openhands.sdk.observability.laminar import maybe_init_laminar, observe +from openhands.sdk.secret import SecretSource from openhands.sdk.settings.acp_providers import ( build_session_model_meta, detect_acp_provider_by_agent_name, @@ -1334,20 +1335,30 @@ def _start_acp_server(self, state: ConversationState) -> None: self._client = client # Build the subprocess environment top-down, highest precedence first: - # acp_env > os.environ > default_environment > state.secret_registry + # acp_env > os.environ > default_environment > + # state.secret_registry > agent_context.secrets # - # All conversation credentials (provider api_key/base_url, git tokens, - # …) arrive via state.secret_registry — the single, cipher-protected - # channel the regular agent uses. agent_context.secrets is NOT drained - # into env here: it stays prompt-only (names/descriptions advertised in - # the system suffix), matching the regular agent. It still reaches the - # registry on the conversation-start path because create_request lifts - # agent_context.secrets → request.secrets → state.secret_registry. + # An ACP subprocess is a black box we cannot name-scan per command (unlike + # the regular agent's bash tool, which injects secrets lazily by matching + # names in each command), so ALL credentials must be injected upfront. + # They arrive through two complementary channels: + # - state.secret_registry: the canonical conversation-secret channel + # (StartConversationRequest.secrets); also where create_request lifts + # agent_context.secrets on the Python-caller path (OpenHands cloud). + # - agent_context.secrets drain (below): the ONLY thing that delivers + # agent_context.secrets to the subprocess on paths that do NOT call + # create_request — notably canvas-local, which builds the request in + # TypeScript and relies on the server's create_agent() to fold + # llm.api_key into agent_context.secrets. There is no server-side + # agent_context.secrets → registry lift, so without this drain the + # provider key never reaches the CLI there (auth failure). Keep it + # until such a server-side lift exists. # - # The registry tier fills-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. + # Both secret tiers fill-if-absent. The ``name in env`` guard preserves + # higher-precedence values (so the registry wins over the drain, and + # neither double-injects) 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) if self.acp_env: @@ -1368,6 +1379,17 @@ def _start_acp_server(self, state: ConversationState) -> None: 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 # 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 a1e4fed5623..7e4b5f913a4 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5233,15 +5233,15 @@ def test_roundtrip_via_conversation_state_persistence(self, tmp_path): class TestACPSecretsEnvInjection: - """``agent_context.secrets`` is prompt-only — NOT drained into the env. - - Credentials reach the ACP subprocess exclusively via - ``state.secret_registry`` (the canonical channel; ``agent_context.secrets`` - reaches it on the conversation-start path because ``create_request`` lifts - ``agent_context.secrets`` → ``request.secrets`` → ``state.secret_registry``). - ``_start_acp_server`` must therefore NOT read ``agent_context.secrets`` - directly — matching the regular agent, where context secrets are advertised - in the prompt but injected only through the registry. + """Tests for secret injection into the ACP subprocess environment. + + Secrets passed via ``agent_context.secrets`` must land in the subprocess + env so the ACP server (Claude Code, Codex CLI, etc.) can use them. This + drain is the only thing that delivers ``agent_context.secrets`` to the CLI + on paths that don't call ``create_request`` (e.g. canvas-local, which folds + ``llm.api_key`` into ``agent_context.secrets`` server-side via + ``create_agent`` but never lifts it into ``state.secret_registry``). + ``acp_env`` entries take precedence over agent_context secrets. """ @staticmethod @@ -5316,14 +5316,12 @@ async def _fake_filter(_src, _dst): return captured - def test_agent_context_secrets_not_drained_into_env(self, tmp_path): - """``agent_context.secrets`` are NOT injected directly by the spawn path. + def test_static_secret_injected_into_subprocess_env(self, tmp_path): + """A StaticSecret in agent_context.secrets lands in the subprocess env. - With the drain removed, a secret that lives only on - ``agent_context.secrets`` (and never made it into ``state.secret_registry``) - does not reach the subprocess env. In production it always reaches the - registry first via ``create_request``; this guards that the spawn path - itself no longer reads ``agent_context.secrets``. + This drain is what delivers ``agent_context.secrets`` to the CLI on + paths that don't lift them into ``state.secret_registry`` via + ``create_request`` (e.g. canvas-local). """ from pydantic import SecretStr @@ -5340,7 +5338,49 @@ def test_agent_context_secrets_not_drained_into_env(self, tmp_path): ) ) env = self._run_start_capturing_env(agent, tmp_path) - assert "GITHUB_TOKEN" not in env + assert env.get("GITHUB_TOKEN") == "ghp_test123" + + def test_acp_env_takes_precedence_over_agent_context_secret(self, tmp_path): + """An explicit acp_env entry wins over the same key in agent_context.secrets.""" + from pydantic import SecretStr + + from openhands.sdk.secret import StaticSecret + + agent = _make_agent( + acp_env={"MY_TOKEN": "acp-env-wins"}, + agent_context=AgentContext( + secrets={"MY_TOKEN": StaticSecret(value=SecretStr("secret-panel"))} + ), + ) + with pytest.warns(DeprecationWarning, match=r"ACPAgent\.acp_env"): + env = self._run_start_capturing_env(agent, tmp_path) + assert env.get("MY_TOKEN") == "acp-env-wins" + + def test_none_value_secret_not_injected(self, tmp_path): + """A StaticSecret with value=None is not added to the subprocess env.""" + from openhands.sdk.secret import StaticSecret + + agent = _make_agent( + agent_context=AgentContext( + secrets={"ABSENT_SECRET": StaticSecret(value=None)} + ) + ) + env = self._run_start_capturing_env(agent, tmp_path) + assert "ABSENT_SECRET" not in env + + def test_empty_string_secret_not_injected(self, tmp_path): + """Empty string secrets are not injected into the subprocess env.""" + from pydantic import SecretStr + + from openhands.sdk.secret import StaticSecret + + agent = _make_agent( + agent_context=AgentContext( + secrets={"EMPTY_SECRET": StaticSecret(value=SecretStr(""))} + ) + ) + env = self._run_start_capturing_env(agent, tmp_path) + assert "EMPTY_SECRET" not in env def test_acp_env_still_injected(self, tmp_path): """``acp_env`` (user arbitrary env vars) is still injected at spawn.""" @@ -5509,15 +5549,17 @@ def get_value(self) -> str | None: assert env.get("GITHUB_TOKEN") == "from-acp-env" assert secret.calls == [] - def test_registry_is_sole_cred_source_not_agent_context(self, tmp_path): - """Only ``secret_registry`` feeds env — ``agent_context.secrets`` does not. + def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_path): + """``secret_registry`` wins over ``agent_context.secrets`` on collision. + 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, and ``create_request`` - lifts ``agent_context.secrets`` into it). ``_start_acp_server`` reads the - registry only: a key present in both ``agent_context.secrets`` and the - registry resolves to the registry value, and a key present only in - ``agent_context.secrets`` (here a distinct one) is never drained. + (``StartConversationRequest.secrets`` lands here); the + ``agent_context.secrets`` drain runs after it and is fill-if-absent, so on + a key collision the registry value is kept and a context-only key is still + backfilled (proving the drain coexists with the registry without + double-injecting). """ from pydantic import SecretStr @@ -5537,7 +5579,7 @@ def test_registry_is_sole_cred_source_not_agent_context(self, tmp_path): registry_secrets={"GITHUB_TOKEN": "from-registry"}, ) assert env.get("GITHUB_TOKEN") == "from-registry" - assert "CONTEXT_ONLY" not in env + assert env.get("CONTEXT_ONLY") == "ctx-value" def test_empty_registry_does_not_change_behaviour(self, tmp_path): """An empty secret_registry must not raise or alter the spawn env.""" @@ -5714,6 +5756,37 @@ def test_claude_config_dir_suppresses_api_key_from_registry(self, tmp_path): assert "ANTHROPIC_API_KEY" not in env assert "ANTHROPIC_BASE_URL" not in env + def test_claude_config_dir_suppresses_api_key_from_secrets(self, tmp_path): + """ANTHROPIC_API_KEY drained from agent_context.secrets is stripped too. + + Covers the canvas-local channel: provider creds folded into + ``agent_context.secrets`` reach env via the drain, and must still be + stripped when CLAUDE_CONFIG_DIR is active. + """ + from pydantic import SecretStr + + from openhands.sdk.secret import StaticSecret + + agent = _make_agent( + acp_env={"CLAUDE_CONFIG_DIR": "/tmp/claude-creds"}, + agent_context=AgentContext( + secrets={ + "ANTHROPIC_API_KEY": StaticSecret( + value=SecretStr("sk-from-secret") + ), + "ANTHROPIC_BASE_URL": StaticSecret( + value=SecretStr("https://proxy.example.com") + ), + } + ), + ) + with pytest.warns(DeprecationWarning, match=r"ACPAgent\.acp_env"): + env = self._run_start_capturing_env(agent, tmp_path) + + assert "CLAUDE_CONFIG_DIR" in env + assert "ANTHROPIC_API_KEY" not in env + assert "ANTHROPIC_BASE_URL" not in env + def test_no_suppression_without_claude_config_dir(self, tmp_path): """Without CLAUDE_CONFIG_DIR, ANTHROPIC_API_KEY passes through unchanged.""" agent = _make_agent( From 9d62d99a18bfca285460bb2423cbafa52ccdd431 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 19:42:28 +0200 Subject: [PATCH 5/7] chore(acp): emit acp_env deprecation once per code path create_agent() now passes dict(self.acp_env) instead of resolve_acp_env(), so the create_agent path warns only once (ACPAgent.acp_env at spawn). resolve_acp_env() keeps its ACPAgentSettings.acp_env warning for explicit callers of that public method. Addresses PR review (double-warn). Co-Authored-By: Claude Opus 4.8 (1M context) --- openhands-sdk/openhands/sdk/settings/model.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index 93bf99d5eb0..4c91ba5377f 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -1275,7 +1275,12 @@ def create_agent(self) -> ACPAgent: llm=self.llm, acp_command=self.resolve_acp_command(), acp_args=list(self.acp_args), - acp_env=self.resolve_acp_env(), + # Pass acp_env directly rather than via resolve_acp_env() so the + # deprecation warning is not emitted twice on the create_agent path: + # _start_acp_server already warns (ACPAgent.acp_env) at spawn, and + # resolve_acp_env()'s warning (ACPAgentSettings.acp_env) is reserved + # for explicit callers of that public method. + acp_env=dict(self.acp_env), acp_model=self.acp_model, acp_session_mode=self.acp_session_mode, acp_prompt_timeout=self.acp_prompt_timeout, From 86d1d9ba73e3bd84c8691ee8526274ba95d3ecdd Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 20:55:07 +0200 Subject: [PATCH 6/7] fix(acp): conversation secrets override ambient os.environ; doc+test fixes (review) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Addresses enyst's /codereview. Precedence (the main concern): provider/conversation creds used to ride acp_env (applied after os.environ) and thus won over an ambient ANTHROPIC_API_KEY etc. Routing them through state.secret_registry / agent_context.secrets as fill-if-absent *after* env.update(os.environ) let an ambient process env var silently beat the explicit credential — and since this PR also deprecates acp_env, that left no way to override an ambient var. Reordered _start_acp_server so the registry and the agent_context drain OVERRIDE os.environ; acp_env stays highest. New precedence: acp_env > state.secret_registry > agent_context.secrets > os.environ > default_environment The registry still wins over the drain on collision; both skip keys a higher tier will set to avoid a redundant LookupSecret.get_value() HTTP call. Docs: corrected the ACPAgentSettings.agent_context description (it claimed secrets reach env "not by a direct ACPAgent drain" — the PR relies on that drain for canvas-local); documented the new precedence in _start_acp_server and the test class docstring. Tests: made the three env-capture harnesses hermetic (clear os.environ so the runner's ambient GITHUB_TOKEN/ANTHROPIC_API_KEY can't shadow values under test — the failure enyst reproduced), and added tests that a registry secret and an agent_context.secrets value each override a same-named ambient os.environ var. Co-Authored-By: Claude Opus 4.8 (1M context) --- .../openhands/sdk/agent/acp_agent.py | 68 ++++++++++--------- openhands-sdk/openhands/sdk/settings/model.py | 12 ++-- tests/sdk/agent/test_acp_agent.py | 63 +++++++++++++++-- 3 files changed, 102 insertions(+), 41 deletions(-) diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index cf8bc231986..5808da43a71 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -1334,31 +1334,29 @@ def _start_acp_server(self, state: ConversationState) -> None: client = _OpenHandsACPBridge() self._client = client - # Build the subprocess environment top-down, highest precedence first: - # acp_env > os.environ > default_environment > - # state.secret_registry > agent_context.secrets + # Build the subprocess environment. Precedence, highest first: + # acp_env > state.secret_registry > agent_context.secrets + # > os.environ > default_environment # - # An ACP subprocess is a black box we cannot name-scan per command (unlike - # the regular agent's bash tool, which injects secrets lazily by matching - # names in each command), so ALL credentials must be injected upfront. - # They arrive through two complementary channels: - # - state.secret_registry: the canonical conversation-secret channel - # (StartConversationRequest.secrets); also where create_request lifts - # agent_context.secrets on the Python-caller path (OpenHands cloud). - # - agent_context.secrets drain (below): the ONLY thing that delivers - # agent_context.secrets to the subprocess on paths that do NOT call - # create_request — notably canvas-local, which builds the request in - # TypeScript and relies on the server's create_agent() to fold - # llm.api_key into agent_context.secrets. There is no server-side - # agent_context.secrets → registry lift, so without this drain the - # provider key never reaches the CLI there (auth failure). Keep it - # until such a server-side lift exists. + # Conversation credentials (the registry and the agent_context drain) + # intentionally OVERRIDE ambient os.environ: an explicit per-conversation + # / provider secret must win over a same-named variable in the + # agent-server's own environment (os.environ is the wrong process for a + # remote server). acp_env (deprecated) stays highest. # - # Both secret tiers fill-if-absent. The ``name in env`` guard preserves - # higher-precedence values (so the registry wins over the drain, and - # neither double-injects) and avoids calling SecretSource.get_value() for - # keys already satisfied — important because LookupSecret can make an - # HTTP request. + # Two conversation channels, because an ACP subprocess is a black box we + # cannot name-scan per command (unlike the regular agent's bash tool), so + # credentials must be injected upfront: + # - state.secret_registry: the canonical channel + # (StartConversationRequest.secrets; also where create_request lifts + # agent_context.secrets on the Python-caller path / OpenHands cloud). + # - agent_context.secrets drain: the ONLY channel that delivers + # agent_context.secrets on paths that do NOT call create_request — + # notably canvas-local, which builds the request in TypeScript and + # relies on the server's create_agent() to fold llm.api_key into + # agent_context.secrets. There is no server-side agent_context.secrets + # → registry lift, so keep this drain until one exists. + # On a key collision the registry wins over the drain. env = default_environment() env.update(os.environ) if self.acp_env: @@ -1372,16 +1370,14 @@ def _start_acp_server(self, state: ConversationState) -> None: "StartConversationRequest.secrets) instead." ), ) - env.update(self.acp_env) - 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 + # agent_context.secrets drain (lower precedence than the registry). + # Skip keys a higher tier will set — acp_env (applied last) and the + # registry (applied next) — to avoid a wasted SecretSource.get_value() + # (LookupSecret can make an HTTP request). + registry_names = set(state.secret_registry.secret_sources) if self.agent_context and self.agent_context.secrets: for name, secret in self.agent_context.secrets.items(): - if name in env: + if name in self.acp_env or name in registry_names: continue value = ( secret.get_value() @@ -1390,6 +1386,16 @@ def _start_acp_server(self, state: ConversationState) -> None: ) if value: env[name] = value + # state.secret_registry overrides the drain and ambient os.environ. Skip + # keys acp_env will set (avoids a redundant LookupSecret.get_value()). + for name in state.secret_registry.secret_sources: + if name in self.acp_env: + continue + value = state.secret_registry.get_secret_value(name) + if value: + env[name] = value + # acp_env (deprecated) has highest precedence. + env.update(self.acp_env) # Strip CLAUDECODE so nested Claude Code instances don't refuse to start env.pop("CLAUDECODE", None) diff --git a/openhands-sdk/openhands/sdk/settings/model.py b/openhands-sdk/openhands/sdk/settings/model.py index 4c91ba5377f..ab99e45a529 100644 --- a/openhands-sdk/openhands/sdk/settings/model.py +++ b/openhands-sdk/openhands/sdk/settings/model.py @@ -1111,11 +1111,13 @@ def _serialize_acp_env(self, value: dict[str, str], info): default=None, description=( "Prompt-only context for the ACP server. ``secrets`` here are " - "advertised to the agent (names/descriptions) and reach the " - "subprocess env via ``state.secret_registry`` — create_request " - "lifts ``agent_context.secrets`` into the registry — not by a " - "direct ACPAgent drain. create_agent also folds provider " - "credentials into these secrets." + "advertised to the agent (names/descriptions) and injected into the " + "subprocess env through two channels: ``state.secret_registry`` (on " + "the Python path, ``create_request`` lifts ``agent_context.secrets`` " + "into the registry) and a direct drain in " + "``ACPAgent._start_acp_server`` for callers that build the request " + "outside Python (e.g. canvas-local). ``create_agent`` also folds " + "provider credentials into these secrets." ), ) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index 7e4b5f913a4..d30673f5f84 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5288,6 +5288,11 @@ async def _fake_filter(_src, _dst): agent._executor = AsyncExecutor() with ExitStack() as stack: + # Hermetic: exclude the runner's ambient env (e.g. a real + # GITHUB_TOKEN / ANTHROPIC_API_KEY) so it can't shadow the + # registry/drain values under test — env.update(os.environ) runs + # before the fill-if-absent secret tiers in _start_acp_server. + stack.enter_context(patch.dict("os.environ", {}, clear=True)) stack.enter_context( patch( "openhands.sdk.agent.acp_agent.asyncio.create_subprocess_exec", @@ -5410,12 +5415,16 @@ class TestACPSecretRegistryEnvInjection: ``AgentContext(secrets=...)`` shim around the same data. 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. + ``acp_env > secret_registry > agent_context.secrets > os.environ``. + Conversation secrets (registry + the agent_context drain) override ambient + ``os.environ`` so an explicit per-conversation/provider secret wins over a + same-named server env var; the registry wins over the drain on collision. """ @staticmethod - def _run_start_capturing_env(agent, tmp_path, *, registry_secrets=None) -> dict: + def _run_start_capturing_env( + agent, tmp_path, *, registry_secrets=None, extra_os_env=None + ) -> dict: """Re-uses the env-capture harness from TestACPSecretsEnvInjection.""" state = _make_state(tmp_path) if registry_secrets: @@ -5442,6 +5451,12 @@ async def _fake_filter(_src, _dst): agent._executor = AsyncExecutor() with ExitStack() as stack: + # Hermetic: replace the runner's ambient env with extra_os_env (or + # nothing), so it can't shadow the registry values under test and so + # tests can inject a controlled ambient var to assert precedence. + stack.enter_context( + patch.dict("os.environ", extra_os_env or {}, clear=True) + ) stack.enter_context( patch( "openhands.sdk.agent.acp_agent.asyncio.create_subprocess_exec", @@ -5610,6 +5625,40 @@ def get_value(self) -> str | None: ) assert "BROKEN" not in env + def test_registry_secret_overrides_ambient_os_environ(self, tmp_path): + """A registry secret overrides a same-named ambient os.environ var. + + Conversation/provider creds must win over the agent-server's own + environment (os.environ is the wrong process for a remote server). + Before this change the ambient value silently won. + """ + agent = _make_agent() + env = self._run_start_capturing_env( + agent, + tmp_path, + registry_secrets={"ANTHROPIC_API_KEY": "from-registry"}, + extra_os_env={"ANTHROPIC_API_KEY": "ambient-should-lose"}, + ) + assert env.get("ANTHROPIC_API_KEY") == "from-registry" + + def test_agent_context_secret_overrides_ambient_os_environ(self, tmp_path): + """An agent_context.secrets drain value overrides ambient os.environ.""" + 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, + extra_os_env={"GITHUB_TOKEN": "ambient-should-lose"}, + ) + assert env.get("GITHUB_TOKEN") == "from-context" + class TestACPEnvConflictSuppression: """CLAUDE_CONFIG_DIR OAuth auth must not coexist with API-key env vars. @@ -5694,8 +5743,12 @@ async def _fake_filter(_src, _dst): return_value=MagicMock(), ) ) - if extra_os_env: - stack.enter_context(patch.dict("os.environ", extra_os_env, clear=False)) + # Hermetic: clear the runner's ambient env so it can't shadow the + # values under test; extra_os_env is the only os.environ content + # (used by the test that injects ANTHROPIC_API_KEY via os.environ). + stack.enter_context( + patch.dict("os.environ", extra_os_env or {}, clear=True) + ) agent._start_acp_server(state) return captured From 26994524505e829ec32221312371c5b7594a3012 Mon Sep 17 00:00:00 2001 From: Debug Agent Date: Tue, 2 Jun 2026 21:04:15 +0200 Subject: [PATCH 7/7] docs(acp): fix stale precedence/source-list comments in tests (review) Two docstrings lagged the precedence change: - test_registry_secret_takes_precedence_over_agent_context_secret still showed 'acp_env > existing base env > secret_registry > agent_context.secrets'; updated to 'acp_env > secret_registry > agent_context.secrets > os.environ'. - TestACPEnvConflictSuppression listed sources 'acp_env, os.environ, or secret_registry'; re-added agent_context.secrets (the drain + its test exist). Co-Authored-By: Claude Opus 4.8 (1M context) --- tests/sdk/agent/test_acp_agent.py | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/tests/sdk/agent/test_acp_agent.py b/tests/sdk/agent/test_acp_agent.py index d30673f5f84..a69a25edd57 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5567,14 +5567,12 @@ def get_value(self) -> str | None: def test_registry_secret_takes_precedence_over_agent_context_secret(self, tmp_path): """``secret_registry`` wins over ``agent_context.secrets`` on collision. - 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); the - ``agent_context.secrets`` drain runs after it and is fill-if-absent, so on - a key collision the registry value is kept and a context-only key is still - backfilled (proving the drain coexists with the registry without - double-injecting). + Precedence: ``acp_env > secret_registry > agent_context.secrets > + os.environ``. The registry is the canonical conversation-secret channel + (``StartConversationRequest.secrets`` lands here). On a key collision the + registry value is used (the drain skips keys the registry will set); a + context-only key is still injected by the drain — proving the two + channels coexist without double-injecting. """ from pydantic import SecretStr @@ -5669,7 +5667,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 secret_registry. + came from: acp_env, os.environ, secret_registry, or agent_context.secrets. """ @staticmethod