Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 56 additions & 16 deletions openhands-sdk/openhands/sdk/agent/acp_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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(
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved
"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()
Expand All @@ -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)

Expand Down
105 changes: 86 additions & 19 deletions openhands-sdk/openhands/sdk/settings/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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."
),
)

Expand Down Expand Up @@ -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)
Comment thread
simonrosenberg marked this conversation as resolved.
Resolved

def resolve_acp_command(self) -> list[str]:
"""Return the effective subprocess command for this settings block.
Expand Down Expand Up @@ -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,
)


Expand Down
Loading
Loading