diff --git a/backend/packages/harness/deerflow/config/acp_config.py b/backend/packages/harness/deerflow/config/acp_config.py index b4902e6..de4b1e8 100644 --- a/backend/packages/harness/deerflow/config/acp_config.py +++ b/backend/packages/harness/deerflow/config/acp_config.py @@ -13,6 +13,7 @@ class ACPAgentConfig(BaseModel): command: str = Field(description="Command to launch the ACP agent subprocess") args: list[str] = Field(default_factory=list, description="Additional command arguments") + env: dict[str, str] = Field(default_factory=dict, description="Environment variables to inject into the agent subprocess. Values starting with $ are resolved from host environment variables.") description: str = Field(description="Description of the agent's capabilities (shown in tool description)") model: str | None = Field(default=None, description="Model hint passed to the agent (optional)") auto_approve_permissions: bool = Field( diff --git a/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py b/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py index 21eb092..b64b775 100644 --- a/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py +++ b/backend/packages/harness/deerflow/tools/builtins/invoke_acp_agent_tool.py @@ -1,6 +1,7 @@ """Built-in tool for invoking external ACP-compatible agents.""" import logging +import os import shutil from typing import Annotated, Any @@ -173,11 +174,14 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool: args = agent_config.args or [] physical_cwd = _get_work_dir(thread_id) mcp_servers = _build_mcp_servers() + agent_env: dict[str, str] | None = None + if agent_config.env: + agent_env = {k: (os.environ.get(v[1:], "") if v.startswith("$") else v) for k, v in agent_config.env.items()} try: from acp import spawn_agent_process - async with spawn_agent_process(client, cmd, *args, cwd=physical_cwd) as (conn, proc): + async with spawn_agent_process(client, cmd, *args, env=agent_env, cwd=physical_cwd) as (conn, proc): logger.info("Spawning ACP agent '%s' with command '%s' and args %s in cwd %s", agent, cmd, args, physical_cwd) await conn.initialize( protocol_version=PROTOCOL_VERSION, diff --git a/backend/tests/test_acp_config.py b/backend/tests/test_acp_config.py index c2a041d..16fbfad 100644 --- a/backend/tests/test_acp_config.py +++ b/backend/tests/test_acp_config.py @@ -64,10 +64,36 @@ def test_load_acp_config_none_clears_agents(): def test_acp_agent_config_defaults(): cfg = ACPAgentConfig(command="my-agent", description="My agent") assert cfg.args == [] + assert cfg.env == {} assert cfg.model is None assert cfg.auto_approve_permissions is False +def test_acp_agent_config_env_literal(): + cfg = ACPAgentConfig(command="my-agent", description="desc", env={"OPENAI_API_KEY": "sk-test"}) + assert cfg.env == {"OPENAI_API_KEY": "sk-test"} + + +def test_acp_agent_config_env_default_is_empty(): + cfg = ACPAgentConfig(command="my-agent", description="desc") + assert cfg.env == {} + + +def test_load_acp_config_preserves_env(): + load_acp_config_from_dict( + { + "codex": { + "command": "codex-acp", + "args": [], + "description": "Codex CLI", + "env": {"OPENAI_API_KEY": "$OPENAI_API_KEY", "FOO": "bar"}, + } + } + ) + cfg = get_acp_agents()["codex"] + assert cfg.env == {"OPENAI_API_KEY": "$OPENAI_API_KEY", "FOO": "bar"} + + def test_acp_agent_config_with_model(): cfg = ACPAgentConfig(command="my-agent", description="desc", model="claude-opus-4") assert cfg.model == "claude-opus-4" diff --git a/backend/tests/test_invoke_acp_agent_tool.py b/backend/tests/test_invoke_acp_agent_tool.py index 81f2bf7..6c36635 100644 --- a/backend/tests/test_invoke_acp_agent_tool.py +++ b/backend/tests/test_invoke_acp_agent_tool.py @@ -206,7 +206,7 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path): PROTOCOL_VERSION="2026-03-24", Client=DummyClient, RequestError=DummyRequestError, - spawn_agent_process=lambda client, cmd, *args, cwd: DummyProcessContext(client, cmd, *args, cwd=cwd), + spawn_agent_process=lambda client, cmd, *args, env=None, cwd: DummyProcessContext(client, cmd, *args, cwd=cwd), text_block=lambda text: {"type": "text", "text": text}, ), ) @@ -323,7 +323,7 @@ async def test_invoke_acp_agent_uses_per_thread_workspace_when_thread_id_in_conf PROTOCOL_VERSION="2026-03-24", Client=DummyClient, RequestError=DummyRequestError, - spawn_agent_process=lambda client, cmd, *args, cwd: DummyProcessContext(client, cmd, *args, cwd=cwd), + spawn_agent_process=lambda client, cmd, *args, env=None, cwd: DummyProcessContext(client, cmd, *args, cwd=cwd), text_block=lambda text: {"type": "text", "text": text}, ), ) @@ -355,6 +355,183 @@ async def test_invoke_acp_agent_uses_per_thread_workspace_when_thread_id_in_conf assert captured["cwd"] == expected_cwd +@pytest.mark.anyio +async def test_invoke_acp_agent_passes_env_to_spawn(monkeypatch, tmp_path): + """env map in ACPAgentConfig is passed to spawn_agent_process; $VAR values are resolved.""" + from deerflow.config import paths as paths_module + + monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path)) + monkeypatch.setattr( + "deerflow.config.extensions_config.ExtensionsConfig.from_file", + classmethod(lambda cls: ExtensionsConfig(mcp_servers={}, skills={})), + ) + monkeypatch.setenv("TEST_OPENAI_KEY", "sk-from-env") + + captured: dict[str, object] = {} + + class DummyClient: + def __init__(self) -> None: + self._chunks: list[str] = [] + + @property + def collected_text(self) -> str: + return "" + + async def session_update(self, session_id, update, **kwargs): + pass + + async def request_permission(self, options, session_id, tool_call, **kwargs): + raise AssertionError("should not be called") + + class DummyConn: + async def initialize(self, **kwargs): + pass + + async def new_session(self, **kwargs): + return SimpleNamespace(session_id="s1") + + async def prompt(self, **kwargs): + pass + + class DummyProcessContext: + def __init__(self, client, cmd, *args, env=None, cwd): + captured["env"] = env + + async def __aenter__(self): + return DummyConn(), object() + + async def __aexit__(self, exc_type, exc, tb): + return False + + class DummyRequestError(Exception): + @staticmethod + def method_not_found(method): + return DummyRequestError(method) + + monkeypatch.setitem( + sys.modules, + "acp", + SimpleNamespace( + PROTOCOL_VERSION="2026-03-24", + Client=DummyClient, + RequestError=DummyRequestError, + spawn_agent_process=lambda client, cmd, *args, env=None, cwd: DummyProcessContext(client, cmd, *args, env=env, cwd=cwd), + text_block=lambda text: {"type": "text", "text": text}, + ), + ) + monkeypatch.setitem( + sys.modules, + "acp.schema", + SimpleNamespace( + ClientCapabilities=lambda: {}, + Implementation=lambda **kwargs: kwargs, + TextContentBlock=type("TextContentBlock", (), {"__init__": lambda self, text: setattr(self, "text", text)}), + ), + ) + + tool = build_invoke_acp_agent_tool( + { + "codex": ACPAgentConfig( + command="codex-acp", + description="Codex CLI", + env={"OPENAI_API_KEY": "$TEST_OPENAI_KEY", "FOO": "bar"}, + ) + } + ) + + try: + await tool.coroutine(agent="codex", prompt="Do something") + finally: + sys.modules.pop("acp", None) + sys.modules.pop("acp.schema", None) + + assert captured["env"] == {"OPENAI_API_KEY": "sk-from-env", "FOO": "bar"} + + +@pytest.mark.anyio +async def test_invoke_acp_agent_passes_none_env_when_not_configured(monkeypatch, tmp_path): + """When env is empty, None is passed to spawn_agent_process (subprocess inherits parent env).""" + from deerflow.config import paths as paths_module + + monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path)) + monkeypatch.setattr( + "deerflow.config.extensions_config.ExtensionsConfig.from_file", + classmethod(lambda cls: ExtensionsConfig(mcp_servers={}, skills={})), + ) + + captured: dict[str, object] = {} + + class DummyClient: + def __init__(self) -> None: + self._chunks: list[str] = [] + + @property + def collected_text(self) -> str: + return "" + + async def session_update(self, session_id, update, **kwargs): + pass + + async def request_permission(self, options, session_id, tool_call, **kwargs): + raise AssertionError("should not be called") + + class DummyConn: + async def initialize(self, **kwargs): + pass + + async def new_session(self, **kwargs): + return SimpleNamespace(session_id="s1") + + async def prompt(self, **kwargs): + pass + + class DummyProcessContext: + def __init__(self, client, cmd, *args, env=None, cwd): + captured["env"] = env + + async def __aenter__(self): + return DummyConn(), object() + + async def __aexit__(self, exc_type, exc, tb): + return False + + class DummyRequestError(Exception): + @staticmethod + def method_not_found(method): + return DummyRequestError(method) + + monkeypatch.setitem( + sys.modules, + "acp", + SimpleNamespace( + PROTOCOL_VERSION="2026-03-24", + Client=DummyClient, + RequestError=DummyRequestError, + spawn_agent_process=lambda client, cmd, *args, env=None, cwd: DummyProcessContext(client, cmd, *args, env=env, cwd=cwd), + text_block=lambda text: {"type": "text", "text": text}, + ), + ) + monkeypatch.setitem( + sys.modules, + "acp.schema", + SimpleNamespace( + ClientCapabilities=lambda: {}, + Implementation=lambda **kwargs: kwargs, + TextContentBlock=type("TextContentBlock", (), {"__init__": lambda self, text: setattr(self, "text", text)}), + ), + ) + + tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI")}) + + try: + await tool.coroutine(agent="codex", prompt="Do something") + finally: + sys.modules.pop("acp", None) + sys.modules.pop("acp.schema", None) + + assert captured["env"] is None + + def test_get_available_tools_includes_invoke_acp_agent_when_agents_configured(monkeypatch): from deerflow.config.acp_config import load_acp_config_from_dict diff --git a/config.example.yaml b/config.example.yaml index 6a3ec9f..6a0a89c 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -406,6 +406,8 @@ sandbox: # description: Claude Code for implementation, refactoring, and debugging # model: null # # auto_approve_permissions: false # Set to true to auto-approve ACP permission requests +# # env: # Optional: inject environment variables into the agent subprocess +# # ANTHROPIC_API_KEY: $ANTHROPIC_API_KEY # $VAR resolves from host environment # # codex: # # DeerFlow expects an ACP adapter here. The standard `codex` CLI does not @@ -415,6 +417,8 @@ sandbox: # description: Codex CLI for repository tasks and code generation # model: null # # auto_approve_permissions: false # Set to true to auto-approve ACP permission requests +# # env: # Optional: inject environment variables into the agent subprocess +# # OPENAI_API_KEY: $OPENAI_API_KEY # $VAR resolves from host environment # ============================================================================ # Skills Configuration