From 2629c0bb782952f934d6b1cfb2328edf2ad54528 Mon Sep 17 00:00:00 2001 From: ZephyrWang <152375907+Wang-Zephyr@users.noreply.github.com> Date: Wed, 25 Nov 2026 16:59:06 +0800 Subject: [PATCH] fix(acp): select the configured model before prompting (#8600) * fix(acp): select the configured model before prompting * fix(acp): verify configured session model selection --- .../tools/builtins/invoke_acp_agent_tool.py | 30 +++++- backend/tests/test_invoke_acp_agent_tool.py | 96 ++++++++++++++++++- docs/guide/configuration.md | 3 +- 3 files changed, 121 insertions(+), 8 deletions(-) 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 6330a6d3cd..f7359f95e6 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 @@ -23,6 +23,30 @@ class _InvokeACPAgentInput(BaseModel): prompt: str = Field(description="The concise task prompt to send to the agent") +class _ModelSelectionError(ValueError): + """A local model-selection check failed, without including agent-supplied text.""" + + +async def _select_session_model(conn, session, model: str) -> None: + select_options = [option for option in (getattr(session, "config_options", None) or []) if option.type == "select"] + model_option = next((option for option in select_options if option.category == "model"), None) + if model_option is None: + # The category is optional; a conventional ID can identify the + # selector, but an option explicitly categorized otherwise cannot. + model_option = next((option for option in select_options if option.category is None and option.id == "model"), None) + if model_option is None: + await conn.set_session_model(model_id=model, session_id=session.session_id) + return + + # ACP exposes either a list of choices or a list of named choice groups. + if not any(choice.value == model for item in model_option.options for choice in getattr(item, "options", (item,))): + raise _ModelSelectionError("The configured model is not an advertised choice") + + result = await conn.set_config_option(config_id=model_option.id, session_id=session.session_id, value=model) + if not any(option.id == model_option.id and option.type == "select" and option.current_value == model for option in result.config_options): + raise _ModelSelectionError("The agent did not confirm the configured model") + + def _get_work_dir(thread_id: str | None) -> str: """Get the per-thread ACP workspace directory. @@ -204,6 +228,8 @@ 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 isinstance(exc, _ModelSelectionError): + return f"Error invoking ACP agent '{agent}': {exc}. Check `acp_agents.{agent}.model` in config.yaml." if not isinstance(exc, FileNotFoundError): return f"Error invoking ACP agent '{agent}' ({type(exc).__name__}). Check the agent's configuration and authentication." @@ -331,9 +357,9 @@ def build_invoke_acp_agent_tool(agents: dict) -> BaseTool: client_info=Implementation(name="deerflow", title="DeerFlow", version="0.1.0"), ) session_kwargs: dict[str, Any] = {"cwd": physical_cwd, "mcp_servers": mcp_servers} - if agent_config.model: - session_kwargs["model"] = agent_config.model session = await conn.new_session(**session_kwargs) + if agent_config.model: + await _select_session_model(conn, session, agent_config.model) await conn.prompt( session_id=session.session_id, prompt=[text_block(prompt)], diff --git a/backend/tests/test_invoke_acp_agent_tool.py b/backend/tests/test_invoke_acp_agent_tool.py index fada4c6614..79308fcc19 100644 --- a/backend/tests/test_invoke_acp_agent_tool.py +++ b/backend/tests/test_invoke_acp_agent_tool.py @@ -298,6 +298,9 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path): captured["new_session"] = kwargs return SimpleNamespace(session_id="session-1") + async def set_session_model(self, **kwargs): + captured["set_session_model"] = kwargs + async def prompt(self, **kwargs): captured["prompt"] = kwargs client = captured["client"] @@ -393,8 +396,8 @@ async def test_invoke_acp_agent_uses_fixed_acp_workspace(monkeypatch, tmp_path): "env": [], } ], - "model": "gpt-5-codex", } + assert captured["set_session_model"] == {"session_id": "session-1", "model_id": "gpt-5-codex"} assert captured["prompt"] == { "session_id": "session-1", "prompt": [{"type": "text", "text": "Implement the fix"}], @@ -920,8 +923,12 @@ from pathlib import Path import acp from acp.schema import InitializeResponse, NewSessionResponse, PromptResponse +model_api = sys.argv[4] if len(sys.argv) > 4 else "" + class _TestAgent: + _model = "default" + def on_connect(self, conn): self._conn = conn @@ -941,14 +948,58 @@ class _TestAgent: async def new_session(self, cwd, additional_directories=None, mcp_servers=None, **kwargs): await self._enter_phase("new_session") + if model_api.startswith("config"): + return NewSessionResponse(session_id="test-session", config_options=self._model_options()) + if model_api == "legacy": + return NewSessionResponse(session_id="test-session", models={ + "currentModelId": self._model, + "availableModels": [{"modelId": value, "name": value} for value in ("default", "chosen")], + }) return NewSessionResponse(session_id="test-session") + def _model_options(self): + choices = [{"value": value, "name": value} for value in ("default", "chosen")] + option = { + "id": "llm-model", "name": "Model", "category": "model", "type": "select", + "currentValue": self._model, "options": choices, + } + if model_api == "config-no-category": + option["id"] = "model" + del option["category"] + if model_api == "config-grouped": + option["options"] = [ + {"group": choice["value"], "name": choice["name"], "options": [choice]} + for choice in choices + ] + return [option] + + async def set_config_option(self, config_id, session_id, value, **kwargs): + assert config_id == self._model_options()[0]["id"] + if model_api == "config-no-change": + await self._enter_phase("select_model") + else: + await self._select_model(value) + return {"configOptions": [] if model_api == "config-no-confirmation" else self._model_options()} + + async def set_session_model(self, model_id, session_id, **kwargs): + assert model_api == "legacy" + await self._select_model(model_id) + return {} + + async def _select_model(self, model): + await self._enter_phase("select_model") + if model not in ("default", "chosen"): + raise ValueError("Unknown model") + self._model = model + async def prompt(self, session_id, prompt, **kwargs): await self._enter_phase("prompt") + if model_api: + await self._conn.session_update(session_id=session_id, update=acp.update_agent_message_text(self._model)) return PromptResponse(stop_reason="end_turn") -asyncio.run(acp.run_agent(_TestAgent())) +asyncio.run(acp.run_agent(_TestAgent(), use_unstable_protocol=model_api == "legacy")) """ @@ -986,14 +1037,17 @@ def acp_subprocess_tool(monkeypatch, tmp_path): monkeypatch.setattr(acp_module, "spawn_agent_process", _spying_spawn_agent_process) - def build_tool(hang_phase="", phase_delay=0, timeout_seconds=2): + def build_tool(hang_phase="", phase_delay=0, timeout_seconds=2, model=None, model_api=""): + if hang_phase == "select_model": + model, model_api = "chosen", "config" tool = build_invoke_acp_agent_tool( { "test": ACPAgentConfig( command=sys.executable, - args=[str(script_path), hang_phase, str(phase_delay), str(phase_path)], + args=[str(script_path), hang_phase, str(phase_delay), str(phase_path), model_api], description="Test ACP agent", timeout_seconds=timeout_seconds, + model=model, ) } ) @@ -1003,7 +1057,39 @@ def acp_subprocess_tool(monkeypatch, tmp_path): @pytest.mark.anyio -@pytest.mark.parametrize("phase", ["initialize", "new_session", "prompt"]) +@pytest.mark.parametrize( + ("model_api", "model", "rejected_phase"), + [ + ("config", None, None), + ("config", "chosen", None), + ("config", "missing", "new_session"), + ("config-no-category", "chosen", None), + ("config-grouped", "chosen", None), + ("config-grouped", "missing", "new_session"), + ("config-no-change", "chosen", "select_model"), + ("config-no-confirmation", "chosen", "select_model"), + ("legacy", None, None), + ("legacy", "chosen", None), + ("legacy", "missing", "select_model"), + ], +) +async def test_invoke_acp_agent_selects_model_before_prompt(acp_subprocess_tool, model_api, model, rejected_phase): + tool = acp_subprocess_tool.build_tool(model=model, model_api=model_api) + result = await asyncio.wait_for(tool.ainvoke({"agent": "test", "prompt": "do work"}), timeout=15) + if rejected_phase: + assert result.startswith("Error invoking ACP agent") + assert acp_subprocess_tool.phase_path.read_text(encoding="utf-8") == rejected_phase + if rejected_phase == "new_session": + assert "not an advertised choice" in result + elif model_api.startswith("config"): + assert "did not confirm the configured model" in result + else: + assert result == (model or "default") + assert acp_subprocess_tool.captured["proc"].returncode is not None + + +@pytest.mark.anyio +@pytest.mark.parametrize("phase", ["initialize", "new_session", "select_model", "prompt"]) async def test_invoke_acp_agent_times_out_and_kills_hung_subprocess(acp_subprocess_tool, phase): tool = acp_subprocess_tool.build_tool(hang_phase=phase) start = time.monotonic() diff --git a/docs/guide/configuration.md b/docs/guide/configuration.md index 493c168402..638eb00532 100644 --- a/docs/guide/configuration.md +++ b/docs/guide/configuration.md @@ -397,7 +397,8 @@ fences, including unclosed fences, in complete and streamed replies. - 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` - 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..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. + - Set `acp_agents..model` to an external agent's model ID to select it after session creation and before the prompt. DeerFlow uses an advertised `category: model` select option, or a select option with ID `model` if its category is omitted. For these options, the model must be an advertised choice and the agent must confirm it as the current selection before DeerFlow sends the prompt. If no model option is advertised, DeerFlow uses the legacy `session/set_model` interface. A rejected selection fails the invocation before the prompt; omitting `model` keeps the agent's default. + - Each ACP agent's `timeout_seconds` (default: 1800) is one shared budget for initialization, session creation, model selection, 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: