diff --git a/openhands-sdk/openhands/sdk/agent/acp_agent.py b/openhands-sdk/openhands/sdk/agent/acp_agent.py index 77592758475..5808da43a71 100644 --- a/openhands-sdk/openhands/sdk/agent/acp_agent.py +++ b/openhands-sdk/openhands/sdk/agent/acp_agent.py @@ -76,6 +76,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, @@ -832,7 +833,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") @@ -1328,26 +1334,50 @@ 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 + # + # 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. # - # 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. + # 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) - 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 + 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." + ), + ) + # 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() @@ -1356,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 bde93041dde..ab99e45a529 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", @@ -1103,8 +1110,14 @@ 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 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." ), ) @@ -1164,21 +1177,34 @@ 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. + + .. 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. """ - return { - **self.resolve_provider_env(), - **dict(self.acp_env), - } + 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]: """Return the effective subprocess command for this settings block. @@ -1208,18 +1234,59 @@ 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, StaticSecret] = { + 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, 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, - 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..a69a25edd57 100644 --- a/tests/sdk/agent/test_acp_agent.py +++ b/tests/sdk/agent/test_acp_agent.py @@ -5236,7 +5236,11 @@ 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. + 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. """ @@ -5284,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", @@ -5313,7 +5322,12 @@ 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.""" + """A StaticSecret in agent_context.secrets lands in the subprocess env. + + 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 from openhands.sdk.secret import StaticSecret @@ -5343,7 +5357,8 @@ def test_acp_env_takes_precedence_over_agent_context_secret(self, tmp_path): secrets={"MY_TOKEN": StaticSecret(value=SecretStr("secret-panel"))} ), ) - 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-wins" def test_none_value_secret_not_injected(self, tmp_path): @@ -5372,6 +5387,23 @@ def test_empty_string_secret_not_injected(self, tmp_path): 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.""" + agent = _make_agent(acp_env={"MY_TOKEN": "acp-env-value"}) + 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. @@ -5383,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: @@ -5415,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", @@ -5525,15 +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); ``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. + 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 @@ -5541,7 +5580,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 +5592,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 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.""" @@ -5580,6 +5623,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. @@ -5613,7 +5690,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 +5712,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: @@ -5660,8 +5741,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 @@ -5699,8 +5784,36 @@ 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_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"}, + ) + 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 + 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.""" + """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 @@ -5718,7 +5831,8 @@ def test_claude_config_dir_suppresses_api_key_from_secrets(self, tmp_path): } ), ) - 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 "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..a56a6cb4fc6 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,96 @@ 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 == {"OPENAI_API_KEY": "sk-openai"} - assert agent.agent_context == context + 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.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: