mirror of
https://gitee.com/wanwujie/deer-flow
synced 2026-04-02 22:02:13 +08:00
feat(acp): add env field to ACPAgentConfig for subprocess env injection (#1447)
Allow per-agent environment variables to be declared in config.yaml under acp_agents.<name>.env. Values prefixed with $ are resolved from the host environment at invocation time, consistent with other config fields. Passes None to spawn_agent_process when env is empty so the subprocess inherits the parent environment unchanged. Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -13,6 +13,7 @@ class ACPAgentConfig(BaseModel):
|
|||||||
|
|
||||||
command: str = Field(description="Command to launch the ACP agent subprocess")
|
command: str = Field(description="Command to launch the ACP agent subprocess")
|
||||||
args: list[str] = Field(default_factory=list, description="Additional command arguments")
|
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)")
|
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)")
|
model: str | None = Field(default=None, description="Model hint passed to the agent (optional)")
|
||||||
auto_approve_permissions: bool = Field(
|
auto_approve_permissions: bool = Field(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"""Built-in tool for invoking external ACP-compatible agents."""
|
"""Built-in tool for invoking external ACP-compatible agents."""
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
from typing import Annotated, Any
|
from typing import Annotated, Any
|
||||||
|
|
||||||
@@ -173,11 +174,14 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool:
|
|||||||
args = agent_config.args or []
|
args = agent_config.args or []
|
||||||
physical_cwd = _get_work_dir(thread_id)
|
physical_cwd = _get_work_dir(thread_id)
|
||||||
mcp_servers = _build_mcp_servers()
|
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:
|
try:
|
||||||
from acp import spawn_agent_process
|
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)
|
logger.info("Spawning ACP agent '%s' with command '%s' and args %s in cwd %s", agent, cmd, args, physical_cwd)
|
||||||
await conn.initialize(
|
await conn.initialize(
|
||||||
protocol_version=PROTOCOL_VERSION,
|
protocol_version=PROTOCOL_VERSION,
|
||||||
|
|||||||
@@ -64,10 +64,36 @@ def test_load_acp_config_none_clears_agents():
|
|||||||
def test_acp_agent_config_defaults():
|
def test_acp_agent_config_defaults():
|
||||||
cfg = ACPAgentConfig(command="my-agent", description="My agent")
|
cfg = ACPAgentConfig(command="my-agent", description="My agent")
|
||||||
assert cfg.args == []
|
assert cfg.args == []
|
||||||
|
assert cfg.env == {}
|
||||||
assert cfg.model is None
|
assert cfg.model is None
|
||||||
assert cfg.auto_approve_permissions is False
|
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():
|
def test_acp_agent_config_with_model():
|
||||||
cfg = ACPAgentConfig(command="my-agent", description="desc", model="claude-opus-4")
|
cfg = ACPAgentConfig(command="my-agent", description="desc", model="claude-opus-4")
|
||||||
assert cfg.model == "claude-opus-4"
|
assert cfg.model == "claude-opus-4"
|
||||||
|
|||||||
@@ -206,7 +206,7 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path):
|
|||||||
PROTOCOL_VERSION="2026-03-24",
|
PROTOCOL_VERSION="2026-03-24",
|
||||||
Client=DummyClient,
|
Client=DummyClient,
|
||||||
RequestError=DummyRequestError,
|
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},
|
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",
|
PROTOCOL_VERSION="2026-03-24",
|
||||||
Client=DummyClient,
|
Client=DummyClient,
|
||||||
RequestError=DummyRequestError,
|
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},
|
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
|
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):
|
def test_get_available_tools_includes_invoke_acp_agent_when_agents_configured(monkeypatch):
|
||||||
from deerflow.config.acp_config import load_acp_config_from_dict
|
from deerflow.config.acp_config import load_acp_config_from_dict
|
||||||
|
|
||||||
|
|||||||
@@ -406,6 +406,8 @@ sandbox:
|
|||||||
# description: Claude Code for implementation, refactoring, and debugging
|
# description: Claude Code for implementation, refactoring, and debugging
|
||||||
# model: null
|
# model: null
|
||||||
# # auto_approve_permissions: false # Set to true to auto-approve ACP permission requests
|
# # 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:
|
# codex:
|
||||||
# # DeerFlow expects an ACP adapter here. The standard `codex` CLI does not
|
# # 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
|
# description: Codex CLI for repository tasks and code generation
|
||||||
# model: null
|
# model: null
|
||||||
# # auto_approve_permissions: false # Set to true to auto-approve ACP permission requests
|
# # 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
|
# Skills Configuration
|
||||||
|
|||||||
Reference in New Issue
Block a user