mirror of
https://github.com/bytedance/deer-flow.git
synced 2026-11-27 17:00:37 +00:00
fix(acp): resolve configured launchers before starting the agent (#8524)
* fix(acp): resolve configured launchers before starting the agent * fix(acp): clarify launcher path and permission guidance --------- Co-authored-by: Totoro-qaq <279883115+Totoro-qaq@users.noreply.github.com>
This commit is contained in:
parent
1e72197a5a
commit
b7d1c577e3
@ -84,7 +84,7 @@ make test-blocking-io
|
||||
adapter.
|
||||
- **Drain the agent's stderr for the whole call.** The SDK opens the pipe and does
|
||||
not read it, so an agent that logs enough blocks on a write and the call stalls.
|
||||
The stderr tail goes to the Gateway log, never into model-visible text.
|
||||
Report the agent's exit status or timeout in the Gateway log.
|
||||
- **Race the exchange against process exit.** The SDK does not fail pending
|
||||
requests when the agent exits.
|
||||
- **Keep the SDK process context outside the timeout**, so teardown finishes
|
||||
|
||||
@ -4,6 +4,7 @@ import asyncio
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
from typing import Annotated, Any
|
||||
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
@ -12,8 +13,6 @@ from pydantic import BaseModel, Field
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Bytes of agent stderr kept for the Gateway log when an invocation fails.
|
||||
_STDERR_TAIL_BYTES = 8 * 1024
|
||||
# After the agent process exits, how long the SDK receive loop may keep reading
|
||||
# responses still buffered in the stdout pipe before the call is declared failed.
|
||||
_EXIT_DRAIN_SECONDS = 2.0
|
||||
@ -149,77 +148,23 @@ def _agent_path(env: dict[str, str] | None) -> str | None:
|
||||
|
||||
|
||||
def _resolve_agent_command(command: str, path: str | None = None) -> str:
|
||||
r"""Return the host path to spawn for a configured ACP agent command.
|
||||
"""Locate the configured launcher using the Gateway's working directory.
|
||||
|
||||
``asyncio.create_subprocess_exec``, which the ACP SDK's stdio transport
|
||||
uses, does not apply ``PATHEXT`` on Windows: a bare ``npx`` or ``mcode``
|
||||
raises ``FileNotFoundError`` even though the npm shim (``npx.cmd``) is on
|
||||
``PATH``, and an absolute ``C:\npm\mcode`` spawns npm's extensionless shell
|
||||
script instead of ``mcode.CMD`` and dies with ``WinError 193``. Resolve
|
||||
the command the way the MCP Python SDK normalizes stdio commands, and keep
|
||||
the configured value when nothing matches so the not-found remediation
|
||||
still fires.
|
||||
|
||||
Bare names and absolute paths are resolved. A relative configured path is
|
||||
handed to the spawn unchanged: it refers to the ACP workspace the spawn
|
||||
runs in, not to the Gateway's cwd. An absolute path keeps its own
|
||||
directory -- ``shutil.which`` searches that directory and probes
|
||||
``PATHEXT`` there.
|
||||
|
||||
``path`` is the ``PATH`` the agent subprocess will actually see (see
|
||||
``_agent_path``); the Gateway's own is only the fallback. A successful
|
||||
lookup is returned absolute: for a relative ``PATH`` entry ``shutil.which``
|
||||
yields a result relative to the Gateway's cwd, while the spawn runs with
|
||||
``cwd`` set to the ACP workspace, where that path resolves elsewhere -- or
|
||||
not at all.
|
||||
|
||||
An already-absolute result is returned unchanged: a lexical ``abspath``
|
||||
would collapse a ``..`` that follows a symlink, changing which file the
|
||||
spawn actually runs.
|
||||
|
||||
The lookup stats the filesystem (``shutil.which`` -> ``os.access``), so
|
||||
callers must run it off the event loop.
|
||||
Resolve the executable before changing the child's working directory.
|
||||
shutil.which also selects Windows PATHEXT shims. Keep symlink/..
|
||||
traversal intact when anchoring a relative PATH entry.
|
||||
"""
|
||||
if os.path.dirname(command) and not os.path.isabs(command):
|
||||
return command
|
||||
try:
|
||||
resolved = shutil.which(command, path=path)
|
||||
except OSError:
|
||||
return command
|
||||
resolved = shutil.which(command, path=path)
|
||||
if not resolved:
|
||||
return command
|
||||
return resolved if os.path.isabs(resolved) else os.path.abspath(resolved)
|
||||
raise FileNotFoundError(command)
|
||||
# Path.absolute also anchors drive-relative and rooted Windows paths.
|
||||
return str(Path(resolved).absolute())
|
||||
|
||||
|
||||
class _StderrTail:
|
||||
"""Drain an agent's stderr pipe, keeping only a bounded tail.
|
||||
|
||||
The SDK spawns agents with ``stderr=PIPE`` but never reads it. Once an agent
|
||||
has logged more than asyncio's pipe buffering absorbs, its next stderr write
|
||||
blocks, the agent stops answering, and the invocation stalls until the
|
||||
timeout. Draining continuously keeps verbose agents running.
|
||||
"""
|
||||
|
||||
def __init__(self, stream: asyncio.StreamReader | None) -> None:
|
||||
self._data = bytearray()
|
||||
self._task = asyncio.create_task(self._drain(stream)) if stream is not None else None
|
||||
|
||||
async def _drain(self, stream: asyncio.StreamReader) -> None:
|
||||
while chunk := await stream.read(65536):
|
||||
self._data += chunk
|
||||
del self._data[:-_STDERR_TAIL_BYTES]
|
||||
|
||||
async def text(self, *, wait: float = 0.0) -> str:
|
||||
"""Return the tail, waiting up to ``wait`` seconds for the pipe to reach EOF."""
|
||||
if self._task is not None and wait > 0:
|
||||
await asyncio.wait({self._task}, timeout=wait)
|
||||
return self._data.decode("utf-8", errors="replace").strip()
|
||||
|
||||
async def aclose(self) -> None:
|
||||
if self._task is not None:
|
||||
# A descendant can keep the pipe open after the agent itself is reaped.
|
||||
self._task.cancel()
|
||||
await asyncio.gather(self._task, return_exceptions=True)
|
||||
async def _drain_agent_stderr(stream: asyncio.StreamReader) -> None:
|
||||
"""Keep a verbose subprocess's stderr pipe flowing without retaining its contents."""
|
||||
while await stream.read(65536):
|
||||
pass
|
||||
|
||||
|
||||
class _AgentExitedError(Exception):
|
||||
@ -257,8 +202,13 @@ async def _await_while_agent_runs(awaitable: Any, proc: asyncio.subprocess.Proce
|
||||
|
||||
def _format_invocation_error(agent: str, cmd: str, exc: Exception) -> str:
|
||||
"""Return a user-facing ACP invocation error with actionable remediation."""
|
||||
if isinstance(exc, TimeoutError):
|
||||
return f"Error invoking ACP agent '{agent}': SDK transport timed out"
|
||||
if not isinstance(exc, FileNotFoundError):
|
||||
return f"Error invoking ACP agent '{agent}': {exc}"
|
||||
return f"Error invoking ACP agent '{agent}' ({type(exc).__name__}). Check the agent's configuration and authentication."
|
||||
|
||||
if os.path.dirname(cmd):
|
||||
return f"Error invoking ACP agent '{agent}': Could not start the file configured in `acp_agents.{agent}.command`. Check that the file exists and the Gateway account has execute permission."
|
||||
|
||||
message = f"Error invoking ACP agent '{agent}': Command '{cmd}' was not found on PATH."
|
||||
if cmd == "codex-acp" and shutil.which("codex"):
|
||||
@ -312,13 +262,12 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool:
|
||||
_agents = dict(agents)
|
||||
|
||||
async def _invoke(agent: str, prompt: str, config: Annotated[RunnableConfig, InjectedToolArg] = None) -> str:
|
||||
logger.info("Invoking ACP agent %s (prompt length: %d)", agent, len(prompt))
|
||||
logger.debug("Invoking ACP agent %s with prompt: %.200s%s", agent, prompt, "..." if len(prompt) > 200 else "")
|
||||
if agent not in _agents:
|
||||
available = ", ".join(_agents.keys())
|
||||
return f"Error: Unknown agent '{agent}'. Available: {available}"
|
||||
|
||||
agent_config = _agents[agent]
|
||||
logger.info("Invoking ACP agent %s (prompt length: %d)", agent, len(prompt))
|
||||
thread_id: str | None = ((config or {}).get("configurable") or {}).get("thread_id")
|
||||
|
||||
try:
|
||||
@ -363,16 +312,15 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool:
|
||||
agent_env = dict(agent_config.env)
|
||||
# Resolve against the PATH the agent subprocess will see, not the Gateway's:
|
||||
# the SDK merges agent_env over its inherited environment at spawn time.
|
||||
cmd = await asyncio.to_thread(_resolve_agent_command, agent_config.command, _agent_path(agent_env))
|
||||
args = agent_config.args or []
|
||||
physical_cwd = await asyncio.to_thread(_get_work_dir, thread_id)
|
||||
try:
|
||||
mcp_servers = await asyncio.to_thread(_build_acp_mcp_servers)
|
||||
except ValueError as exc:
|
||||
logger.warning(
|
||||
"Invalid MCP server configuration for ACP agent '%s'; continuing without MCP servers: %s",
|
||||
"Invalid MCP server configuration for ACP agent '%s'; continuing without MCP servers (%s)",
|
||||
agent,
|
||||
exc,
|
||||
type(exc).__name__,
|
||||
)
|
||||
mcp_servers = []
|
||||
|
||||
@ -391,60 +339,46 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool:
|
||||
prompt=[text_block(prompt)],
|
||||
)
|
||||
|
||||
stderr_tail: _StderrTail | None = None
|
||||
stderr_drain: asyncio.Task[None] | None = None
|
||||
timed_out = False
|
||||
try:
|
||||
from acp import spawn_agent_process
|
||||
|
||||
cmd = await asyncio.to_thread(_resolve_agent_command, agent_config.command, _agent_path(agent_env))
|
||||
async with spawn_agent_process(client, cmd, *args, env=agent_env, cwd=physical_cwd) as (conn, proc):
|
||||
stderr_tail = _StderrTail(proc.stderr)
|
||||
logger.info("Spawning ACP agent '%s' with command '%s' and args %s in cwd %s", agent, cmd, args, physical_cwd)
|
||||
if proc.stderr is not None:
|
||||
stderr_drain = asyncio.create_task(_drain_agent_stderr(proc.stderr))
|
||||
try:
|
||||
async with asyncio.timeout(agent_config.timeout_seconds) as deadline:
|
||||
await _await_while_agent_runs(_converse(conn), proc)
|
||||
except TimeoutError:
|
||||
if not deadline.expired():
|
||||
raise
|
||||
# Leave the SDK context first: it terminates and reaps the
|
||||
# agent, so the lines a stalled agent wrote last reach the tail.
|
||||
# Leave the SDK context first so the stalled process is reaped.
|
||||
timed_out = True
|
||||
except _AgentExitedError as exc:
|
||||
status = f"exited with code {exc.returncode}" if exc.returncode is not None else "closed its ACP connection"
|
||||
logger.error(
|
||||
"ACP agent '%s' %s before completing the ACP invocation. stderr tail:\n%s",
|
||||
agent,
|
||||
status,
|
||||
await stderr_tail.text(wait=_EXIT_DRAIN_SECONDS),
|
||||
)
|
||||
return (
|
||||
f"Error: ACP agent '{agent}' {status} before completing the ACP invocation. "
|
||||
f"Check that the agent is installed and authenticated and that acp_agents.{agent} in config.yaml is correct; "
|
||||
"the agent's stderr is recorded in the Gateway log."
|
||||
)
|
||||
logger.error("ACP agent '%s' %s before completing the ACP invocation", agent, status)
|
||||
return f"Error: ACP agent '{agent}' {status} before completing the ACP invocation. Check that the agent is installed and authenticated and that acp_agents.{agent} in config.yaml is correct."
|
||||
if timed_out:
|
||||
logger.error(
|
||||
"ACP agent '%s' timed out after %s seconds during initialization, session creation, or prompt; subprocess terminated. stderr tail:\n%s",
|
||||
agent,
|
||||
agent_config.timeout_seconds,
|
||||
await stderr_tail.text(wait=_EXIT_DRAIN_SECONDS),
|
||||
)
|
||||
logger.error("ACP agent '%s' timed out after %s seconds during initialization, session creation, or prompt", agent, agent_config.timeout_seconds)
|
||||
return (
|
||||
f"Error: ACP agent '{agent}' timed out after {agent_config.timeout_seconds} seconds "
|
||||
"without completing the ACP invocation. The agent subprocess has been terminated. If this agent handles "
|
||||
f"long-running tasks, increase acp_agents.{agent}.timeout_seconds in config.yaml."
|
||||
)
|
||||
result = client.collected_text
|
||||
logger.info("ACP agent '%s' returned %s", agent, result[:1000])
|
||||
logger.info("ACP agent '%s' returned %d characters", agent, len(result))
|
||||
return result or "(no response)"
|
||||
except Exception as e:
|
||||
logger.error("ACP agent '%s' invocation failed: %s", agent, e)
|
||||
logger.error("ACP agent '%s' invocation failed (%s)", agent, type(e).__name__)
|
||||
# Report the configured command, not the resolved path: remediation
|
||||
# text has to match what the operator wrote in config.yaml.
|
||||
return await asyncio.to_thread(_format_invocation_error, agent, agent_config.command, e)
|
||||
finally:
|
||||
if stderr_tail is not None:
|
||||
await stderr_tail.aclose()
|
||||
if stderr_drain is not None:
|
||||
stderr_drain.cancel()
|
||||
await asyncio.gather(stderr_drain, return_exceptions=True)
|
||||
|
||||
return StructuredTool.from_function(
|
||||
name="invoke_acp_agent",
|
||||
|
||||
@ -261,9 +261,6 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path):
|
||||
"""ACP agent uses {base_dir}/acp-workspace/ when no thread_id is available (no config)."""
|
||||
from deerflow.config import paths as paths_module
|
||||
|
||||
# An empty PATH directory keeps the configured command unresolvable, so the
|
||||
# spawn assertion below checks the configuration rather than the host PATH.
|
||||
monkeypatch.setenv("PATH", str(tmp_path / "empty-bin"))
|
||||
monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path))
|
||||
|
||||
monkeypatch.setattr(
|
||||
@ -366,7 +363,7 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path):
|
||||
tool = build_invoke_acp_agent_tool(
|
||||
{
|
||||
"codex": ACPAgentConfig(
|
||||
command="codex-acp",
|
||||
command=sys.executable,
|
||||
args=["--json"],
|
||||
description="Codex CLI",
|
||||
model="gpt-5-codex",
|
||||
@ -384,7 +381,7 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path):
|
||||
sys.modules.pop("acp.schema", None)
|
||||
|
||||
assert result == "ACP result"
|
||||
assert captured["spawn"] == {"cmd": "codex-acp", "args": ["--json"], "cwd": expected_cwd}
|
||||
assert captured["spawn"] == {"cmd": sys.executable, "args": ["--json"], "cwd": expected_cwd}
|
||||
assert captured["new_session"] == {
|
||||
"cwd": expected_cwd,
|
||||
"mcp_servers": [
|
||||
@ -484,7 +481,7 @@ async def test_invoke_acp_agent_uses_per_thread_workspace_when_thread_id_in_conf
|
||||
thread_id = "thread-xyz-789"
|
||||
expected_cwd = str(tmp_path / "threads" / thread_id / "acp-workspace")
|
||||
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI")})
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command=sys.executable, description="Codex CLI")})
|
||||
|
||||
try:
|
||||
await tool.coroutine(
|
||||
@ -577,7 +574,7 @@ async def test_invoke_acp_agent_passes_env_to_spawn(monkeypatch, tmp_path):
|
||||
tool = build_invoke_acp_agent_tool(
|
||||
{
|
||||
"codex": ACPAgentConfig(
|
||||
command="codex-acp",
|
||||
command=sys.executable,
|
||||
description="Codex CLI",
|
||||
env=AppConfig.resolve_env_variables({"OPENAI_API_KEY": "$TEST_OPENAI_KEY", "FOO": "bar"}),
|
||||
)
|
||||
@ -667,7 +664,7 @@ async def test_invoke_acp_agent_skips_invalid_mcp_servers(monkeypatch, tmp_path,
|
||||
),
|
||||
)
|
||||
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI")})
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command=sys.executable, description="Codex CLI")})
|
||||
caplog.set_level("WARNING")
|
||||
|
||||
try:
|
||||
@ -678,7 +675,8 @@ async def test_invoke_acp_agent_skips_invalid_mcp_servers(monkeypatch, tmp_path,
|
||||
|
||||
assert captured["new_session"]["mcp_servers"] == []
|
||||
assert "continuing without MCP servers" in caplog.text
|
||||
assert "missing command" in caplog.text
|
||||
assert "ValueError" in caplog.text
|
||||
assert "missing command" not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@ -754,7 +752,7 @@ async def test_invoke_acp_agent_passes_none_env_when_not_configured(monkeypatch,
|
||||
),
|
||||
)
|
||||
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI")})
|
||||
tool = build_invoke_acp_agent_tool({"codex": ACPAgentConfig(command=sys.executable, description="Codex CLI")})
|
||||
|
||||
try:
|
||||
await tool.coroutine(agent="codex", prompt="Do something")
|
||||
@ -868,7 +866,7 @@ def test_get_available_tools_sync_invoke_acp_agent_preserves_thread_workspace(mo
|
||||
skill_evolution=SimpleNamespace(enabled=False),
|
||||
sandbox=SimpleNamespace(),
|
||||
get_model_config=lambda name: None,
|
||||
acp_agents={"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI")},
|
||||
acp_agents={"codex": ACPAgentConfig(command=sys.executable, description="Codex CLI")},
|
||||
)
|
||||
tools = get_available_tools(include_mcp=False, subagent_enabled=False, app_config=explicit_config)
|
||||
tool = next(tool for tool in tools if tool.name == "invoke_acp_agent")
|
||||
@ -1055,16 +1053,17 @@ async def test_invoke_acp_agent_cancellation_closes_subprocess(acp_subprocess_to
|
||||
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("phase", ["initialize", "new_session", "prompt"])
|
||||
async def test_invoke_acp_agent_preserves_sdk_timeout_errors(acp_subprocess_tool, monkeypatch, phase):
|
||||
async def test_invoke_acp_agent_preserves_sdk_timeout_errors(acp_subprocess_tool, monkeypatch, phase, caplog):
|
||||
from acp.client.connection import ClientSideConnection
|
||||
|
||||
async def raise_sdk_timeout(self, *args, **kwargs):
|
||||
raise TimeoutError("SDK transport timed out")
|
||||
raise TimeoutError("Private timeout details from provider")
|
||||
|
||||
monkeypatch.setattr(ClientSideConnection, phase, raise_sdk_timeout)
|
||||
tool = acp_subprocess_tool.build_tool(timeout_seconds=60)
|
||||
result = await asyncio.wait_for(tool.coroutine(agent="test", prompt="do work"), timeout=15)
|
||||
assert result == "Error invoking ACP agent 'test': SDK transport timed out"
|
||||
assert "Private timeout details from provider" not in caplog.text
|
||||
assert "timeout_seconds" not in result
|
||||
assert acp_subprocess_tool.captured["proc"].returncode is not None
|
||||
|
||||
@ -1129,12 +1128,12 @@ def acp_stderr_tool(monkeypatch, tmp_path):
|
||||
script_path = tmp_path / "stderr_acp_agent.py"
|
||||
script_path.write_text(_STDERR_ACP_AGENT_SCRIPT, encoding="utf-8")
|
||||
|
||||
def build_tool(stop_phase="", stderr_bytes=0, stop="exit", timeout_seconds=60):
|
||||
def build_tool(stop_phase="", stderr_bytes=0, stop="exit", timeout_seconds=60, extra_args=()):
|
||||
return build_invoke_acp_agent_tool(
|
||||
{
|
||||
"test": ACPAgentConfig(
|
||||
command=sys.executable,
|
||||
args=[str(script_path), stop_phase, str(stderr_bytes), stop],
|
||||
args=[str(script_path), stop_phase, str(stderr_bytes), stop, *extra_args],
|
||||
description="Test ACP agent",
|
||||
timeout_seconds=timeout_seconds,
|
||||
)
|
||||
@ -1147,8 +1146,6 @@ def acp_stderr_tool(monkeypatch, tmp_path):
|
||||
@pytest.mark.anyio
|
||||
@pytest.mark.parametrize("phase", ["initialize", "new_session", "prompt"])
|
||||
async def test_invoke_acp_agent_reports_an_agent_that_exits_mid_invocation(acp_stderr_tool, caplog, phase):
|
||||
# More stderr than the retained tail, so the fatal line (written last) is
|
||||
# only logged if the tail keeps the end of the stream rather than its start.
|
||||
tool = acp_stderr_tool(stop_phase=phase, stderr_bytes=40 * 1024)
|
||||
start = time.monotonic()
|
||||
with caplog.at_level(logging.ERROR, logger="deerflow.tools.builtins.invoke_acp_agent_tool"):
|
||||
@ -1157,28 +1154,33 @@ async def test_invoke_acp_agent_reports_an_agent_that_exits_mid_invocation(acp_s
|
||||
assert time.monotonic() - start < 15
|
||||
assert result.startswith("Error: ACP agent 'test' exited with code 3 before completing the ACP invocation.")
|
||||
assert "timeout_seconds" not in result
|
||||
# The agent's diagnostics reach the operator log, not the model.
|
||||
assert f"fatal: cannot {phase} without credentials" in caplog.text
|
||||
assert "exited with code 3" in caplog.text
|
||||
assert f"fatal: cannot {phase} without credentials" not in caplog.text
|
||||
assert "credentials" not in result
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_invoke_acp_agent_logs_the_stderr_of_a_stalled_agent(acp_stderr_tool, caplog):
|
||||
async def test_invoke_acp_agent_logs_timeout_without_forwarding_stderr(acp_stderr_tool, caplog):
|
||||
tool = acp_stderr_tool(stop_phase="prompt", stderr_bytes=40 * 1024, stop="hang", timeout_seconds=3)
|
||||
with caplog.at_level(logging.ERROR, logger="deerflow.tools.builtins.invoke_acp_agent_tool"):
|
||||
result = await asyncio.wait_for(tool.coroutine(agent="test", prompt="do work"), timeout=30)
|
||||
assert "timed out after 3 seconds" in result
|
||||
# The last line the agent wrote before stalling is the one an operator needs.
|
||||
assert "stalled: waiting for prompt login" in caplog.text
|
||||
assert "timed out after 3 seconds" in caplog.text
|
||||
assert "stalled: waiting for prompt login" not in caplog.text
|
||||
assert "login" not in result
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_invoke_acp_agent_drains_verbose_stderr(acp_stderr_tool):
|
||||
# Far beyond what an unread stderr pipe absorbs before the agent's writes block.
|
||||
tool = acp_stderr_tool(stderr_bytes=1024 * 1024, timeout_seconds=20)
|
||||
result = await asyncio.wait_for(tool.coroutine(agent="test", prompt="do work"), timeout=40)
|
||||
async def test_invoke_acp_agent_drains_verbose_stderr(acp_stderr_tool, caplog):
|
||||
# Exercise both the real subprocess pipe and the operator-facing success logs.
|
||||
tool = acp_stderr_tool(stderr_bytes=1024 * 1024, timeout_seconds=20, extra_args=["private-launch-argument"])
|
||||
with caplog.at_level(logging.DEBUG, logger="deerflow.tools.builtins.invoke_acp_agent_tool"):
|
||||
result = await asyncio.wait_for(tool.coroutine(agent="test", prompt="private-test-prompt"), timeout=40)
|
||||
assert result == "done"
|
||||
assert "returned 4 characters" in caplog.text
|
||||
assert "returned done" not in caplog.text
|
||||
assert "private-test-prompt" not in caplog.text
|
||||
assert "private-launch-argument" not in caplog.text
|
||||
|
||||
|
||||
def _write_launcher_shim(directory: Path, name: str, command: str) -> Path:
|
||||
@ -1287,12 +1289,13 @@ async def test_invoke_acp_agent_spawns_an_absolute_command_without_an_extension(
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_invoke_acp_agent_reports_guidance_for_an_unresolvable_command(monkeypatch, tmp_path):
|
||||
"""A command PATH cannot resolve still reports the configured name.
|
||||
|
||||
``_resolve_agent_command`` falls back to the configured value when nothing
|
||||
matches, so the not-found guidance must name what the user configured.
|
||||
"""
|
||||
@pytest.mark.parametrize(
|
||||
"installed",
|
||||
[False, pytest.param(True, marks=pytest.mark.skipif(os.name != "posix" or os.geteuid() == 0, reason="requires POSIX permission bits and an unprivileged account"))],
|
||||
ids=["missing", "not-executable"],
|
||||
)
|
||||
async def test_invoke_acp_agent_reports_guidance_for_an_unresolvable_command(monkeypatch, tmp_path, installed):
|
||||
"""A launcher lookup failure gives remediation before reaching the process transport."""
|
||||
from deerflow.config import paths as paths_module
|
||||
|
||||
monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path))
|
||||
@ -1301,10 +1304,24 @@ async def test_invoke_acp_agent_reports_guidance_for_an_unresolvable_command(mon
|
||||
classmethod(lambda cls: ExtensionsConfig(mcp_servers={}, skills={})),
|
||||
)
|
||||
|
||||
tool = build_invoke_acp_agent_tool({"probe": ACPAgentConfig(command="deerflow-missing-acp-agent", description="Probe", timeout_seconds=30)})
|
||||
def unexpected_spawn(*args, **kwargs):
|
||||
pytest.fail("An unresolved launcher reached the process transport")
|
||||
|
||||
monkeypatch.setattr("acp.spawn_agent_process", unexpected_spawn)
|
||||
command = "deerflow-missing-acp-agent"
|
||||
if installed:
|
||||
launcher = tmp_path / "agent"
|
||||
launcher.touch()
|
||||
launcher.chmod(0o644)
|
||||
command = str(launcher)
|
||||
tool = build_invoke_acp_agent_tool({"probe": ACPAgentConfig(command=command, description="Probe", timeout_seconds=30)})
|
||||
result = await asyncio.wait_for(tool.coroutine(agent="probe", prompt="do work"), timeout=20)
|
||||
|
||||
assert "Command 'deerflow-missing-acp-agent' was not found on PATH" in result
|
||||
if installed:
|
||||
assert "execute permission" in result
|
||||
assert "not found" not in result
|
||||
else:
|
||||
assert "Command 'deerflow-missing-acp-agent' was not found on PATH" in result
|
||||
assert "acp_agents.probe.command" in result
|
||||
|
||||
|
||||
@ -1317,17 +1334,11 @@ def test_agent_path_reads_the_configured_override_case_insensitively():
|
||||
assert _agent_path({"Path": "/agent-bin"}) == "/agent-bin"
|
||||
|
||||
|
||||
def test_resolve_agent_command_leaves_relative_paths_to_the_spawn(monkeypatch, tmp_path):
|
||||
"""A relative configured path is left to the spawn, which runs in the ACP workspace."""
|
||||
resolved_dir = tmp_path / "resolved"
|
||||
monkeypatch.setattr(
|
||||
"deerflow.tools.builtins.invoke_acp_agent_tool.shutil.which",
|
||||
lambda command, path=None: str(resolved_dir / command),
|
||||
)
|
||||
|
||||
assert _resolve_agent_command("npx") == str(resolved_dir / "npx")
|
||||
assert _resolve_agent_command("bin/agent") == "bin/agent"
|
||||
assert _resolve_agent_command("./bin/agent") == "./bin/agent"
|
||||
def test_resolve_agent_command_anchors_relative_launchers_in_gateway_directory(monkeypatch, tmp_path):
|
||||
monkeypatch.chdir(tmp_path)
|
||||
launcher = _write_launcher_shim(tmp_path / "bin", "agent", "echo")
|
||||
assert Path(_resolve_agent_command(os.path.join("bin", "agent"))) == launcher
|
||||
assert Path(_resolve_agent_command("agent", "bin")) == launcher
|
||||
|
||||
|
||||
def test_resolve_agent_command_resolves_absolute_paths_through_the_lookup(monkeypatch, tmp_path):
|
||||
|
||||
@ -394,9 +394,10 @@ fences, including unclosed fences, in complete and streamed replies.
|
||||
- `CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR` accepts a UTF-8 token handoff and reuses it for later model instances in the same process. Undecodable handoffs are skipped so Claude Code can still try its override or default credentials file.
|
||||
- CLI credential JSON files accept UTF-8 with or without a BOM, independently of the host locale. `make doctor` accepts the same files when checking CLI authentication. Invalid text encoding is treated as an unreadable source; Claude Code can still try its default file after an invalid override.
|
||||
- ACP agent entries are separate from model providers — if you configure `acp_agents.codex`, point it at a Codex ACP adapter such as `npx -y @zed-industries/codex-acp`
|
||||
- A bare or absolute ACP agent `command` is resolved before the agent starts, so npm-installed launchers work on Windows too: `npx` or `mcode` is spawned as its `npx.cmd`/`mcode.cmd` shim instead of failing with a command-not-found error, and an absolute path such as `C:\Users\me\AppData\Roaming\npm\mcode` resolves to the `mcode.cmd` shim beside npm's extensionless shell script instead of failing with `WinError 193`. The lookup uses the `PATH` the agent subprocess will actually see (`acp_agents.<name>.env.PATH` when set, otherwise the Gateway's) and hands the spawn an absolute path, so a relative `PATH` entry cannot be re-interpreted inside the agent's own workspace. A relative `command` (for example `bin/mcode`) is used as configured, and a command that cannot be resolved is still reported with the install guidance below.
|
||||
- Each ACP agent's `timeout_seconds` (default: 1800) is one shared budget for initialization, session creation, and the prompt, starting after the subprocess launches. On timeout, DeerFlow aborts the invocation and closes the subprocess before returning an error. Workspace/MCP preparation and subprocess cleanup are outside this budget. A `TimeoutError` raised by the SDK before this deadline expires retains its own error message.
|
||||
- If an ACP agent exits before answering (for example because it is not authenticated or a configured argument is wrong), DeerFlow reports its exit code within a few seconds instead of waiting for `timeout_seconds`, and records the end of the agent's stderr in the Gateway log. Agent stderr is read continuously, so an agent that logs heavily cannot stall on a full pipe.
|
||||
- The ACP agent `command` is resolved before the agent starts, so npm-installed launchers work on Windows too: `npx` or `mcode` is spawned as its `npx.cmd`/`mcode.cmd` shim instead of failing with a command-not-found error, and an absolute path such as `C:\Users\me\AppData\Roaming\npm\mcode` resolves to the `mcode.cmd` shim beside npm's extensionless shell script instead of failing with `WinError 193`. The lookup uses the `PATH` the agent subprocess will actually see (`acp_agents.<name>.env.PATH` when set, otherwise the Gateway's) and hands the spawn an absolute path, so a relative `PATH` entry cannot be re-interpreted inside the agent's own workspace. Relative launchers (for example `bin/mcode`) are resolved from the Gateway working directory. Install launchers outside writable task workspaces and use an absolute path if the Gateway working directory can vary. If a configured path fails to launch, check that the file exists and the Gateway account can execute it.
|
||||
- Each ACP agent's `timeout_seconds` (default: 1800) is one shared budget for initialization, session creation, and the prompt, starting after the subprocess launches. On timeout, DeerFlow aborts the invocation and closes the subprocess before returning an error. Workspace/MCP preparation and subprocess cleanup are outside this budget. A transport timeout raised before the deadline is reported separately.
|
||||
- If an ACP agent exits before answering (for example because it is not authenticated or a configured argument is wrong), DeerFlow reports its exit code within a few seconds instead of waiting for `timeout_seconds`, and records the exit status in the Gateway log. DeerFlow drains agent stderr continuously to keep the subprocess responsive.
|
||||
- Keep Gateway launch configuration writable only by operators. ACP launchers run with the Gateway OS user, independently of the thread sandbox provider.
|
||||
- MiniMax Code speaks ACP directly. Install and authenticate it, then add it as an ACP agent:
|
||||
|
||||
```bash
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user