feat(harness): integration ACP agent tool (#1344)

* refactor: extract shared utils to break harness→app cross-layer imports

Move _validate_skill_frontmatter to src/skills/validation.py and
CONVERTIBLE_EXTENSIONS + convert_file_to_markdown to src/utils/file_conversion.py.
This eliminates the two reverse dependencies from client.py (harness layer)
into gateway/routers/ (app layer), preparing for the harness/app package split.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: split backend/src into harness (deerflow.*) and app (app.*)

Physically split the monolithic backend/src/ package into two layers:

- **Harness** (`packages/harness/deerflow/`): publishable agent framework
  package with import prefix `deerflow.*`. Contains agents, sandbox, tools,
  models, MCP, skills, config, and all core infrastructure.

- **App** (`app/`): unpublished application code with import prefix `app.*`.
  Contains gateway (FastAPI REST API) and channels (IM integrations).

Key changes:
- Move 13 harness modules to packages/harness/deerflow/ via git mv
- Move gateway + channels to app/ via git mv
- Rename all imports: src.* → deerflow.* (harness) / app.* (app layer)
- Set up uv workspace with deerflow-harness as workspace member
- Update langgraph.json, config.example.yaml, all scripts, Docker files
- Add build-system (hatchling) to harness pyproject.toml
- Add PYTHONPATH=. to gateway startup commands for app.* resolution
- Update ruff.toml with known-first-party for import sorting
- Update all documentation to reflect new directory structure

Boundary rule enforced: harness code never imports from app.
All 429 tests pass. Lint clean.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* chore: add harness→app boundary check test and update docs

Add test_harness_boundary.py that scans all Python files in
packages/harness/deerflow/ and fails if any `from app.*` or
`import app.*` statement is found. This enforces the architectural
rule that the harness layer never depends on the app layer.

Update CLAUDE.md to document the harness/app split architecture,
import conventions, and the boundary enforcement test.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* feat: add config versioning with auto-upgrade on startup

When config.example.yaml schema changes, developers' local config.yaml
files can silently become outdated. This adds a config_version field and
auto-upgrade mechanism so breaking changes (like src.* → deerflow.*
renames) are applied automatically before services start.

- Add config_version: 1 to config.example.yaml
- Add startup version check warning in AppConfig.from_file()
- Add scripts/config-upgrade.sh with migration registry for value replacements
- Add `make config-upgrade` target
- Auto-run config-upgrade in serve.sh and start-daemon.sh before starting services
- Add config error hints in service failure messages

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix comments

* fix: update src.* import in test_sandbox_tools_security to deerflow.*

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: handle empty config and search parent dirs for config.example.yaml

Address Copilot review comments on PR #1131:
- Guard against yaml.safe_load() returning None for empty config files
- Search parent directories for config.example.yaml instead of only
  looking next to config.yaml, fixing detection in common setups

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: correct skills root path depth and config_version type coercion

- loader.py: fix get_skills_root_path() to use 5 parent levels (was 3)
  after harness split, file lives at packages/harness/deerflow/skills/
  so parent×3 resolved to backend/packages/harness/ instead of backend/
- app_config.py: coerce config_version to int() before comparison in
  _check_config_version() to prevent TypeError when YAML stores value
  as string (e.g. config_version: "1")
- tests: add regression tests for both fixes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: update test imports from src.* to deerflow.*/app.* after harness refactor

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(harness): add tool-first ACP agent invocation (#37)

* feat(harness): add tool-first ACP agent invocation

* build(harness): make ACP dependency required

* fix(harness): address ACP review feedback

* feat(harness): decouple ACP agent workspace from thread data

ACP agents (codex, claude-code) previously used per-thread workspace
directories, causing path resolution complexity and coupling task
execution to DeerFlow's internal thread data layout. This change:

- Replace _resolve_cwd() with a fixed _get_work_dir() that always uses
  {base_dir}/acp-workspace/, eliminating virtual path translation and
  thread_id lookups
- Introduce /mnt/acp-workspace virtual path for lead agent read-only
  access to ACP agent output files (same pattern as /mnt/skills)
- Add security guards: read-only validation, path traversal prevention,
  command path allowlisting, and output masking for acp-workspace
- Update system prompt and tool description to guide LLM: send
  self-contained tasks to ACP agents, copy results via /mnt/acp-workspace
- Add 11 new security tests for ACP workspace path handling

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor(prompt): inject ACP section only when ACP agents are configured

The ACP agent guidance in the system prompt is now conditionally built
by _build_acp_section(), which checks get_acp_agents() and returns an
empty string when no ACP agents are configured. This avoids polluting
the prompt with irrelevant instructions for users who don't use ACP.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix lint

* fix(harness): address Copilot review comments on sandbox path handling and ACP tool

- local_sandbox: fix path-segment boundary bug in _resolve_path (== or startswith +"/")
  and add lookahead in _resolve_paths_in_command regex to prevent /mnt/skills matching
  inside /mnt/skills-extra
- local_sandbox_provider: replace print() with logger.warning(..., exc_info=True)
- invoke_acp_agent_tool: guard getattr(option, "optionId") with None default + continue;
  move full prompt from INFO to DEBUG level (truncated to 200 chars)
- sandbox/tools: fix _get_acp_workspace_host_path docstring to match implementation;
  remove misleading "read-only" language from validate_local_bash_command_paths

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(acp): thread-isolated workspaces, permission guardrail, and ContextVar registry

P1.1 – ACP workspace thread isolation
- Add `Paths.acp_workspace_dir(thread_id)` for per-thread paths
- `_get_work_dir(thread_id)` in invoke_acp_agent_tool now uses
  `{base_dir}/threads/{thread_id}/acp-workspace/`; falls back to
  global workspace when thread_id is absent or invalid
- `_invoke` extracts thread_id from `RunnableConfig` via
  `Annotated[RunnableConfig, InjectedToolArg]`
- `sandbox/tools.py`: `_get_acp_workspace_host_path(thread_id)`,
  `_resolve_acp_workspace_path(path, thread_id)`, and all callers
  (`replace_virtual_paths_in_command`, `mask_local_paths_in_output`,
  `ls_tool`, `read_file_tool`) now resolve ACP paths per-thread

P1.2 – ACP permission guardrail
- New `auto_approve_permissions: bool = False` field in `ACPAgentConfig`
- `_build_permission_response(options, *, auto_approve: bool)` now
  defaults to deny; only approves when `auto_approve=True`
- Document field in `config.example.yaml`

P2 – Deferred tool registry race condition
- Replace module-level `_registry` global with `contextvars.ContextVar`
- Each asyncio request context gets its own registry; worker threads
  inherit the context automatically via `loop.run_in_executor`
- Expose `get_deferred_registry` / `set_deferred_registry` /
  `reset_deferred_registry` helpers

Tests: 831 pass (57 for affected modules, 3 new tests)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(sandbox): mount /mnt/acp-workspace in docker sandbox container

The AioSandboxProvider was not mounting the ACP workspace into the
sandbox container, so /mnt/acp-workspace was inaccessible when the lead
agent tried to read ACP results in docker mode.

Changes:
- `ensure_thread_dirs`: also create `acp-workspace/` (chmod 0o777) so
  the directory exists before the sandbox container starts — required
  for Docker volume mounts
- `_get_thread_mounts`: add read-only `/mnt/acp-workspace` mount using
  the per-thread host path (`host_paths.acp_workspace_dir(thread_id)`)
- Update stale CLAUDE.md description (was "fixed global workspace")

Tests: `test_aio_sandbox_provider.py` (4 new tests)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(lint): remove unused imports in test_aio_sandbox_provider

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix config

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
DanielWalnut
2026-03-26 14:20:18 +08:00
committed by GitHub
parent 792c49e6af
commit d119214fee
46 changed files with 1565 additions and 218 deletions

View File

@@ -0,0 +1,139 @@
"""Unit tests for ACP agent configuration."""
import json
import pytest
import yaml
from pydantic import ValidationError
from deerflow.config.acp_config import ACPAgentConfig, get_acp_agents, load_acp_config_from_dict
from deerflow.config.app_config import AppConfig
def setup_function():
"""Reset ACP config before each test."""
load_acp_config_from_dict({})
def test_load_acp_config_sets_agents():
load_acp_config_from_dict(
{
"claude_code": {
"command": "claude-code-acp",
"args": [],
"description": "Claude Code for coding tasks",
"model": None,
}
}
)
agents = get_acp_agents()
assert "claude_code" in agents
assert agents["claude_code"].command == "claude-code-acp"
assert agents["claude_code"].description == "Claude Code for coding tasks"
assert agents["claude_code"].model is None
def test_load_acp_config_multiple_agents():
load_acp_config_from_dict(
{
"claude_code": {"command": "claude-code-acp", "args": [], "description": "Claude Code"},
"codex": {"command": "codex-acp", "args": ["--flag"], "description": "Codex CLI"},
}
)
agents = get_acp_agents()
assert len(agents) == 2
assert agents["codex"].args == ["--flag"]
def test_load_acp_config_empty_clears_agents():
load_acp_config_from_dict({"agent": {"command": "cmd", "args": [], "description": "desc"}})
assert len(get_acp_agents()) == 1
load_acp_config_from_dict({})
assert len(get_acp_agents()) == 0
def test_load_acp_config_none_clears_agents():
load_acp_config_from_dict({"agent": {"command": "cmd", "args": [], "description": "desc"}})
assert len(get_acp_agents()) == 1
load_acp_config_from_dict(None)
assert get_acp_agents() == {}
def test_acp_agent_config_defaults():
cfg = ACPAgentConfig(command="my-agent", description="My agent")
assert cfg.args == []
assert cfg.model is None
assert cfg.auto_approve_permissions is False
def test_acp_agent_config_with_model():
cfg = ACPAgentConfig(command="my-agent", description="desc", model="claude-opus-4")
assert cfg.model == "claude-opus-4"
def test_acp_agent_config_auto_approve_permissions():
"""P1.2: auto_approve_permissions can be explicitly enabled."""
cfg = ACPAgentConfig(command="my-agent", description="desc", auto_approve_permissions=True)
assert cfg.auto_approve_permissions is True
def test_acp_agent_config_missing_command_raises():
with pytest.raises(ValidationError):
ACPAgentConfig(description="No command provided")
def test_acp_agent_config_missing_description_raises():
with pytest.raises(ValidationError):
ACPAgentConfig(command="my-agent")
def test_get_acp_agents_returns_empty_by_default():
"""After clearing, should return empty dict."""
load_acp_config_from_dict({})
assert get_acp_agents() == {}
def test_app_config_reload_without_acp_agents_clears_previous_state(tmp_path, monkeypatch):
config_path = tmp_path / "config.yaml"
extensions_path = tmp_path / "extensions_config.json"
extensions_path.write_text(json.dumps({"mcpServers": {}, "skills": {}}), encoding="utf-8")
config_with_acp = {
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"models": [
{
"name": "test-model",
"use": "langchain_openai:ChatOpenAI",
"model": "gpt-test",
}
],
"acp_agents": {
"codex": {
"command": "codex-acp",
"args": [],
"description": "Codex CLI",
}
},
}
config_without_acp = {
"sandbox": {"use": "deerflow.sandbox.local:LocalSandboxProvider"},
"models": [
{
"name": "test-model",
"use": "langchain_openai:ChatOpenAI",
"model": "gpt-test",
}
],
}
monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(extensions_path))
config_path.write_text(yaml.safe_dump(config_with_acp), encoding="utf-8")
AppConfig.from_file(str(config_path))
assert set(get_acp_agents()) == {"codex"}
config_path.write_text(yaml.safe_dump(config_without_acp), encoding="utf-8")
AppConfig.from_file(str(config_path))
assert get_acp_agents() == {}

View File

@@ -0,0 +1,73 @@
"""Tests for AioSandboxProvider mount helpers."""
import importlib
from unittest.mock import MagicMock, patch
from deerflow.config.paths import Paths
# ── ensure_thread_dirs ───────────────────────────────────────────────────────
def test_ensure_thread_dirs_creates_acp_workspace(tmp_path):
"""ACP workspace directory must be created alongside user-data dirs."""
paths = Paths(base_dir=tmp_path)
paths.ensure_thread_dirs("thread-1")
assert (tmp_path / "threads" / "thread-1" / "user-data" / "workspace").exists()
assert (tmp_path / "threads" / "thread-1" / "user-data" / "uploads").exists()
assert (tmp_path / "threads" / "thread-1" / "user-data" / "outputs").exists()
assert (tmp_path / "threads" / "thread-1" / "acp-workspace").exists()
def test_ensure_thread_dirs_acp_workspace_is_world_writable(tmp_path):
"""ACP workspace must be chmod 0o777 so the ACP subprocess can write into it."""
paths = Paths(base_dir=tmp_path)
paths.ensure_thread_dirs("thread-2")
acp_dir = tmp_path / "threads" / "thread-2" / "acp-workspace"
mode = oct(acp_dir.stat().st_mode & 0o777)
assert mode == oct(0o777)
# ── _get_thread_mounts ───────────────────────────────────────────────────────
def _make_provider(tmp_path):
"""Build a minimal AioSandboxProvider instance without starting the idle checker."""
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
with patch.object(aio_mod.AioSandboxProvider, "_start_idle_checker"):
provider = aio_mod.AioSandboxProvider.__new__(aio_mod.AioSandboxProvider)
provider._config = {}
provider._sandboxes = {}
provider._lock = MagicMock()
provider._idle_checker_stop = MagicMock()
return provider
def test_get_thread_mounts_includes_acp_workspace(tmp_path, monkeypatch):
"""_get_thread_mounts must include /mnt/acp-workspace (read-only) for docker sandbox."""
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
monkeypatch.setattr(aio_mod, "get_paths", lambda: Paths(base_dir=tmp_path))
mounts = aio_mod.AioSandboxProvider._get_thread_mounts("thread-3")
container_paths = {m[1]: (m[0], m[2]) for m in mounts}
assert "/mnt/acp-workspace" in container_paths, "ACP workspace mount is missing"
expected_host = str(tmp_path / "threads" / "thread-3" / "acp-workspace")
actual_host, read_only = container_paths["/mnt/acp-workspace"]
assert actual_host == expected_host
assert read_only is True, "ACP workspace should be read-only inside the sandbox"
def test_get_thread_mounts_includes_user_data_dirs(tmp_path, monkeypatch):
"""Baseline: user-data mounts must still be present after the ACP workspace change."""
aio_mod = importlib.import_module("deerflow.community.aio_sandbox.aio_sandbox_provider")
monkeypatch.setattr(aio_mod, "get_paths", lambda: Paths(base_dir=tmp_path))
mounts = aio_mod.AioSandboxProvider._get_thread_mounts("thread-4")
container_paths = {m[1] for m in mounts}
assert "/mnt/user-data/workspace" in container_paths
assert "/mnt/user-data/uploads" in container_paths
assert "/mnt/user-data/outputs" in container_paths

View File

@@ -146,6 +146,4 @@ def test_codex_provider_parses_valid_tool_arguments(monkeypatch):
}
)
assert result.generations[0].message.tool_calls == [
{"name": "bash", "args": {"cmd": "pwd"}, "id": "tc-1", "type": "tool_call"}
]
assert result.generations[0].message.tool_calls == [{"name": "bash", "args": {"cmd": "pwd"}, "id": "tc-1", "type": "tool_call"}]

View File

@@ -64,13 +64,7 @@ class TestClientInit:
def test_custom_params(self, mock_app_config):
with patch("deerflow.client.get_app_config", return_value=mock_app_config):
c = DeerFlowClient(
model_name="gpt-4",
thinking_enabled=False,
subagent_enabled=True,
plan_mode=True,
agent_name="test-agent"
)
c = DeerFlowClient(model_name="gpt-4", thinking_enabled=False, subagent_enabled=True, plan_mode=True, agent_name="test-agent")
assert c._model_name == "gpt-4"
assert c._thinking_enabled is False
assert c._subagent_enabled is True
@@ -210,7 +204,7 @@ class TestStream:
patch.object(client, "_agent", agent),
):
list(client.stream("hi", thread_id="t1"))
# Verify context passed to agent.stream
agent.stream.assert_called_once()
call_kwargs = agent.stream.call_args.kwargs
@@ -755,7 +749,8 @@ class TestUploads:
return client.upload_files("thread-async", [first, second])
with (
patch("deerflow.client.get_uploads_dir", return_value=uploads_dir), patch("deerflow.client.ensure_uploads_dir", return_value=uploads_dir),
patch("deerflow.client.get_uploads_dir", return_value=uploads_dir),
patch("deerflow.client.ensure_uploads_dir", return_value=uploads_dir),
patch("deerflow.utils.file_conversion.CONVERTIBLE_EXTENSIONS", {".pdf"}),
patch("deerflow.utils.file_conversion.convert_file_to_markdown", side_effect=fake_convert),
patch("concurrent.futures.ThreadPoolExecutor", FakeExecutor),
@@ -1492,7 +1487,8 @@ class TestScenarioEdgeCases:
pdf_file.write_bytes(b"%PDF-1.4 fake content")
with (
patch("deerflow.client.get_uploads_dir", return_value=uploads_dir), patch("deerflow.client.ensure_uploads_dir", return_value=uploads_dir),
patch("deerflow.client.get_uploads_dir", return_value=uploads_dir),
patch("deerflow.client.ensure_uploads_dir", return_value=uploads_dir),
patch("deerflow.utils.file_conversion.CONVERTIBLE_EXTENSIONS", {".pdf"}),
patch("deerflow.utils.file_conversion.convert_file_to_markdown", side_effect=Exception("conversion failed")),
):
@@ -1719,7 +1715,6 @@ class TestGatewayConformance:
assert parsed.data.version == "1.0"
# ===========================================================================
# Hardening — install_skill security gates
# ===========================================================================
@@ -1743,6 +1738,7 @@ class TestInstallSkillSecurity:
# Patch max_total_size to a small value to trigger the bomb check.
from deerflow.skills import installer as _installer
orig = _installer.safe_extract_skill_archive
def patched_extract(zf, dest, max_total_size=100):

View File

@@ -213,36 +213,23 @@ class TestToolCallFlow:
def test_tool_call_produces_events(self, client):
"""When the LLM decides to use a tool, we see tool call + result events."""
# Give a clear instruction that forces a tool call
events = list(client.stream(
"Use the bash tool to run: echo hello_e2e_test"
))
events = list(client.stream("Use the bash tool to run: echo hello_e2e_test"))
types = [e.type for e in events]
assert types[-1] == "end"
# Should have at least one tool call event
tool_call_events = [
e for e in events
if e.type == "messages-tuple" and e.data.get("tool_calls")
]
tool_result_events = [
e for e in events
if e.type == "messages-tuple" and e.data.get("type") == "tool"
]
tool_call_events = [e for e in events if e.type == "messages-tuple" and e.data.get("tool_calls")]
tool_result_events = [e for e in events if e.type == "messages-tuple" and e.data.get("type") == "tool"]
assert len(tool_call_events) >= 1, "Expected at least one tool_call event"
assert len(tool_result_events) >= 1, "Expected at least one tool result event"
@requires_llm
def test_tool_call_event_structure(self, client):
"""Tool call events contain name, args, and id fields."""
events = list(client.stream(
"Use the read_file tool to read /mnt/user-data/workspace/nonexistent.txt"
))
events = list(client.stream("Use the read_file tool to read /mnt/user-data/workspace/nonexistent.txt"))
tc_events = [
e for e in events
if e.type == "messages-tuple" and e.data.get("tool_calls")
]
tc_events = [e for e in events if e.type == "messages-tuple" and e.data.get("tool_calls")]
if tc_events:
tc = tc_events[0].data["tool_calls"][0]
assert "name" in tc
@@ -274,6 +261,7 @@ class TestFileUploadIntegration:
# Physically exists
from deerflow.config.paths import get_paths
assert (get_paths().sandbox_uploads_dir(tid) / "readme.txt").exists()
def test_upload_duplicate_rename(self, e2e_env, tmp_path):
@@ -410,6 +398,7 @@ class TestMiddlewareChain:
# ThreadDataMiddleware should have set paths in the state.
# We verify the paths singleton can resolve the thread dir.
from deerflow.config.paths import get_paths
thread_dir = get_paths().thread_dir(tid)
assert str(thread_dir).endswith(tid)
@@ -422,10 +411,7 @@ class TestMiddlewareChain:
types = [e.type for e in events]
assert types[-1] == "end"
# Should have at least one AI response
ai_events = [
e for e in events
if e.type == "messages-tuple" and e.data.get("type") == "ai"
]
ai_events = [e for e in events if e.type == "messages-tuple" and e.data.get("type") == "ai"]
assert len(ai_events) >= 1
@@ -552,9 +538,7 @@ class TestSkillInstallation:
"""Create a minimal valid .skill archive."""
skill_dir = tmp_path / "build" / skill_name
skill_dir.mkdir(parents=True)
(skill_dir / "SKILL.md").write_text(
f"---\nname: {skill_name}\ndescription: E2E test skill\n---\n\nTest content.\n"
)
(skill_dir / "SKILL.md").write_text(f"---\nname: {skill_name}\ndescription: E2E test skill\n---\n\nTest content.\n")
archive_path = tmp_path / f"{skill_name}.skill"
with zipfile.ZipFile(archive_path, "w") as zf:
for file in skill_dir.rglob("*"):
@@ -680,6 +664,7 @@ class TestConfigManagement:
# Force reload so the singleton picks up our test file
from deerflow.config.extensions_config import reload_extensions_config
reload_extensions_config()
c = DeerFlowClient(checkpointer=None, thinking_enabled=False)
@@ -705,6 +690,7 @@ class TestConfigManagement:
monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(config_file))
from deerflow.config.extensions_config import reload_extensions_config
reload_extensions_config()
c = DeerFlowClient(checkpointer=None, thinking_enabled=False)
@@ -732,6 +718,7 @@ class TestConfigManagement:
monkeypatch.setenv("DEER_FLOW_EXTENSIONS_CONFIG_PATH", str(config_file))
from deerflow.config.extensions_config import reload_extensions_config
reload_extensions_config()
c = DeerFlowClient(checkpointer=None, thinking_enabled=False)

View File

@@ -18,7 +18,7 @@ def test_feishu_on_message_plain_text():
event.event.message.message_id = "msg_1"
event.event.message.root_id = None
event.event.sender.sender_id.open_id = "user_1"
# Plain text content
content_dict = {"text": "Hello world"}
event.event.message.content = json.dumps(content_dict)
@@ -32,7 +32,7 @@ def test_feishu_on_message_plain_text():
mock_make_inbound = MagicMock()
m.setattr(channel, "_make_inbound", mock_make_inbound)
channel._on_message(event)
mock_make_inbound.assert_called_once()
assert mock_make_inbound.call_args[1]["text"] == "Hello world"
@@ -48,33 +48,22 @@ def test_feishu_on_message_rich_text():
event.event.message.message_id = "msg_1"
event.event.message.root_id = None
event.event.sender.sender_id.open_id = "user_1"
# Rich text content (topic group / post)
content_dict = {
"content": [
[
{"tag": "text", "text": "Paragraph 1, part 1."},
{"tag": "text", "text": "Paragraph 1, part 2."}
],
[
{"tag": "at", "text": "@bot"},
{"tag": "text", "text": " Paragraph 2."}
]
]
}
content_dict = {"content": [[{"tag": "text", "text": "Paragraph 1, part 1."}, {"tag": "text", "text": "Paragraph 1, part 2."}], [{"tag": "at", "text": "@bot"}, {"tag": "text", "text": " Paragraph 2."}]]}
event.event.message.content = json.dumps(content_dict)
with pytest.MonkeyPatch.context() as m:
mock_make_inbound = MagicMock()
m.setattr(channel, "_make_inbound", mock_make_inbound)
channel._on_message(event)
mock_make_inbound.assert_called_once()
parsed_text = mock_make_inbound.call_args[1]["text"]
# Expected text:
# Paragraph 1, part 1. Paragraph 1, part 2.
#
#
# @bot Paragraph 2.
assert "Paragraph 1, part 1. Paragraph 1, part 2." in parsed_text
assert "@bot Paragraph 2." in parsed_text

View File

@@ -157,7 +157,7 @@ class TestInfoQuestClient:
mock_config.get_tool_config.side_effect = [
MagicMock(model_extra={"search_time_range": 24}), # web_search config
MagicMock(model_extra={"fetch_time": 10, "timeout": 30, "navigation_timeout": 60}), # web_fetch config
MagicMock(model_extra={"image_search_time_range": 7, "image_size": "l"}) # image_search config
MagicMock(model_extra={"image_search_time_range": 7, "image_size": "l"}), # image_search config
]
mock_get_app_config.return_value = mock_config

View File

@@ -0,0 +1,386 @@
"""Tests for the built-in ACP invocation tool."""
import sys
from types import SimpleNamespace
import pytest
from deerflow.config.acp_config import ACPAgentConfig
from deerflow.config.extensions_config import ExtensionsConfig, McpServerConfig, set_extensions_config
from deerflow.tools.builtins.invoke_acp_agent_tool import (
_build_mcp_servers,
_build_permission_response,
_get_work_dir,
build_invoke_acp_agent_tool,
)
from deerflow.tools.tools import get_available_tools
def test_build_mcp_servers_filters_disabled_and_maps_transports():
set_extensions_config(ExtensionsConfig(mcp_servers={"stale": McpServerConfig(enabled=True, type="stdio", command="echo")}, skills={}))
fresh_config = ExtensionsConfig(
mcp_servers={
"stdio": McpServerConfig(enabled=True, type="stdio", command="npx", args=["srv"]),
"http": McpServerConfig(enabled=True, type="http", url="https://example.com/mcp"),
"disabled": McpServerConfig(enabled=False, type="stdio", command="echo"),
},
skills={},
)
monkeypatch = pytest.MonkeyPatch()
monkeypatch.setattr(
"deerflow.config.extensions_config.ExtensionsConfig.from_file",
classmethod(lambda cls: fresh_config),
)
try:
assert _build_mcp_servers() == {
"stdio": {"transport": "stdio", "command": "npx", "args": ["srv"]},
"http": {"transport": "http", "url": "https://example.com/mcp"},
}
finally:
monkeypatch.undo()
set_extensions_config(ExtensionsConfig(mcp_servers={}, skills={}))
def test_build_permission_response_prefers_allow_once():
response = _build_permission_response(
[
SimpleNamespace(kind="reject_once", optionId="deny"),
SimpleNamespace(kind="allow_always", optionId="always"),
SimpleNamespace(kind="allow_once", optionId="once"),
],
auto_approve=True,
)
assert response.outcome.outcome == "selected"
assert response.outcome.option_id == "once"
def test_build_permission_response_denies_when_no_allow_option():
response = _build_permission_response(
[
SimpleNamespace(kind="reject_once", optionId="deny"),
SimpleNamespace(kind="reject_always", optionId="deny-forever"),
],
auto_approve=True,
)
assert response.outcome.outcome == "cancelled"
def test_build_permission_response_denies_when_auto_approve_false():
"""P1.2: When auto_approve=False, permission is always denied regardless of options."""
response = _build_permission_response(
[
SimpleNamespace(kind="allow_once", optionId="once"),
SimpleNamespace(kind="allow_always", optionId="always"),
],
auto_approve=False,
)
assert response.outcome.outcome == "cancelled"
@pytest.mark.anyio
async def test_build_invoke_tool_description_and_unknown_agent_error():
tool = build_invoke_acp_agent_tool(
{
"codex": ACPAgentConfig(command="codex-acp", description="Codex CLI"),
"claude_code": ACPAgentConfig(command="claude-code-acp", description="Claude Code"),
}
)
assert "Available agents:" in tool.description
assert "- codex: Codex CLI" in tool.description
assert "- claude_code: Claude Code" in tool.description
assert "Do NOT include /mnt/user-data paths" in tool.description
assert "/mnt/acp-workspace/" in tool.description
result = await tool.coroutine(agent="missing", prompt="do work")
assert result == "Error: Unknown agent 'missing'. Available: codex, claude_code"
def test_get_work_dir_uses_base_dir_when_no_thread_id(monkeypatch, tmp_path):
"""_get_work_dir(None) uses {base_dir}/acp-workspace/ (global fallback)."""
from deerflow.config import paths as paths_module
monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path))
result = _get_work_dir(None)
expected = tmp_path / "acp-workspace"
assert result == str(expected)
assert expected.exists()
def test_get_work_dir_uses_per_thread_path_when_thread_id_given(monkeypatch, tmp_path):
"""P1.1: _get_work_dir(thread_id) uses {base_dir}/threads/{thread_id}/acp-workspace/."""
from deerflow.config import paths as paths_module
monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path))
result = _get_work_dir("thread-abc-123")
expected = tmp_path / "threads" / "thread-abc-123" / "acp-workspace"
assert result == str(expected)
assert expected.exists()
def test_get_work_dir_falls_back_to_global_for_invalid_thread_id(monkeypatch, tmp_path):
"""P1.1: Invalid thread_id (e.g. path traversal chars) falls back to global workspace."""
from deerflow.config import paths as paths_module
monkeypatch.setattr(paths_module, "get_paths", lambda: paths_module.Paths(base_dir=tmp_path))
result = _get_work_dir("../../evil")
expected = tmp_path / "acp-workspace"
assert result == str(expected)
assert expected.exists()
@pytest.mark.anyio
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
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={"github": McpServerConfig(enabled=True, type="stdio", command="npx", args=["github-mcp"])},
skills={},
)
),
)
captured: dict[str, object] = {}
class DummyClient:
def __init__(self) -> None:
self._chunks: list[str] = []
@property
def collected_text(self) -> str:
return "".join(self._chunks)
async def session_update(self, session_id: str, update, **kwargs) -> None:
if hasattr(update, "content") and hasattr(update.content, "text"):
self._chunks.append(update.content.text)
async def request_permission(self, options, session_id: str, tool_call, **kwargs):
raise AssertionError("request_permission should not be called in this test")
class DummyConn:
async def initialize(self, **kwargs):
captured["initialize"] = kwargs
async def new_session(self, **kwargs):
captured["new_session"] = kwargs
return SimpleNamespace(session_id="session-1")
async def prompt(self, **kwargs):
captured["prompt"] = kwargs
client = captured["client"]
await client.session_update(
"session-1",
SimpleNamespace(content=text_content_block("ACP result")),
)
class DummyProcessContext:
def __init__(self, client, cmd, *args, cwd):
captured["client"] = client
captured["spawn"] = {"cmd": cmd, "args": list(args), "cwd": cwd}
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: str):
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, cwd: DummyProcessContext(client, cmd, *args, cwd=cwd),
text_block=lambda text: {"type": "text", "text": text},
),
)
monkeypatch.setitem(
sys.modules,
"acp.schema",
SimpleNamespace(
ClientCapabilities=lambda: {"supports": []},
Implementation=lambda **kwargs: kwargs,
TextContentBlock=type(
"TextContentBlock",
(),
{"__init__": lambda self, text: setattr(self, "text", text)},
),
),
)
text_content_block = sys.modules["acp.schema"].TextContentBlock
expected_cwd = str(tmp_path / "acp-workspace")
tool = build_invoke_acp_agent_tool(
{
"codex": ACPAgentConfig(
command="codex-acp",
args=["--json"],
description="Codex CLI",
model="gpt-5-codex",
)
}
)
try:
result = await tool.coroutine(
agent="codex",
prompt="Implement the fix",
)
finally:
sys.modules.pop("acp", None)
sys.modules.pop("acp.schema", None)
assert result == "ACP result"
assert captured["spawn"] == {"cmd": "codex-acp", "args": ["--json"], "cwd": expected_cwd}
assert captured["new_session"] == {
"cwd": expected_cwd,
"mcp_servers": {
"github": {"transport": "stdio", "command": "npx", "args": ["github-mcp"]},
},
"model": "gpt-5-codex",
}
assert captured["prompt"] == {
"session_id": "session-1",
"prompt": [{"type": "text", "text": "Implement the fix"}],
}
@pytest.mark.anyio
async def test_invoke_acp_agent_uses_per_thread_workspace_when_thread_id_in_config(monkeypatch, tmp_path):
"""P1.1: When thread_id is in the RunnableConfig, ACP agent uses per-thread workspace."""
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 "".join(self._chunks)
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):
captured["new_session"] = kwargs
return SimpleNamespace(session_id="s1")
async def prompt(self, **kwargs):
pass
class DummyProcessContext:
def __init__(self, client, cmd, *args, cwd):
captured["cwd"] = cwd
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, cwd: DummyProcessContext(client, cmd, *args, 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)}),
),
)
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")})
try:
await tool.coroutine(
agent="codex",
prompt="Do something",
config={"configurable": {"thread_id": thread_id}},
)
finally:
sys.modules.pop("acp", None)
sys.modules.pop("acp.schema", None)
assert captured["cwd"] == expected_cwd
def test_get_available_tools_includes_invoke_acp_agent_when_agents_configured(monkeypatch):
from deerflow.config.acp_config import load_acp_config_from_dict
load_acp_config_from_dict(
{
"codex": {
"command": "codex-acp",
"args": [],
"description": "Codex CLI",
}
}
)
fake_config = SimpleNamespace(
tools=[],
models=[],
tool_search=SimpleNamespace(enabled=False),
get_model_config=lambda name: None,
)
monkeypatch.setattr("deerflow.tools.tools.get_app_config", lambda: fake_config)
monkeypatch.setattr(
"deerflow.config.extensions_config.ExtensionsConfig.from_file",
classmethod(lambda cls: ExtensionsConfig(mcp_servers={}, skills={})),
)
tools = get_available_tools(include_mcp=True, subagent_enabled=False)
assert "invoke_acp_agent" in [tool.name for tool in tools]
load_acp_config_from_dict({})

View File

@@ -23,7 +23,7 @@ def test_read_file_uses_utf8_on_windows_locale(tmp_path, monkeypatch):
def test_write_file_uses_utf8_on_windows_locale(tmp_path, monkeypatch):
path = tmp_path / "utf8.txt"
text = "emoji \U0001F600"
text = "emoji \U0001f600"
base = builtins.open
monkeypatch.setattr(local_sandbox, "open", lambda file, mode="r", *args, **kwargs: _open(base, file, mode, *args, **kwargs), raising=False)

View File

@@ -14,6 +14,7 @@ class MockArgs(BaseModel):
def test_mcp_tool_sync_wrapper_generation():
"""Test that get_mcp_tools correctly adds a sync func to async-only tools."""
async def mock_coro(x: int):
return f"result: {x}"
@@ -22,27 +23,28 @@ def test_mcp_tool_sync_wrapper_generation():
description="test description",
args_schema=MockArgs,
func=None, # Sync func is missing
coroutine=mock_coro
coroutine=mock_coro,
)
mock_client_instance = MagicMock()
# Use AsyncMock for get_tools as it's awaited (Fix for Comment 5)
mock_client_instance.get_tools = AsyncMock(return_value=[mock_tool])
with patch("langchain_mcp_adapters.client.MultiServerMCPClient", return_value=mock_client_instance), \
patch("deerflow.config.extensions_config.ExtensionsConfig.from_file"), \
patch("deerflow.mcp.tools.build_servers_config", return_value={"test-server": {}}), \
patch("deerflow.mcp.tools.get_initial_oauth_headers", new_callable=AsyncMock, return_value={}):
with (
patch("langchain_mcp_adapters.client.MultiServerMCPClient", return_value=mock_client_instance),
patch("deerflow.config.extensions_config.ExtensionsConfig.from_file"),
patch("deerflow.mcp.tools.build_servers_config", return_value={"test-server": {}}),
patch("deerflow.mcp.tools.get_initial_oauth_headers", new_callable=AsyncMock, return_value={}),
):
# Run the async function manually with asyncio.run
tools = asyncio.run(get_mcp_tools())
assert len(tools) == 1
patched_tool = tools[0]
# Verify func is now populated
assert patched_tool.func is not None
# Verify it works (sync call)
result = patched_tool.func(x=42)
assert result == "result: 42"
@@ -50,6 +52,7 @@ def test_mcp_tool_sync_wrapper_generation():
def test_mcp_tool_sync_wrapper_in_running_loop():
"""Test the actual helper function from production code (Fix for Comment 1 & 3)."""
async def mock_coro(x: int):
await asyncio.sleep(0.01)
return f"async_result: {x}"
@@ -68,6 +71,7 @@ def test_mcp_tool_sync_wrapper_in_running_loop():
def test_mcp_tool_sync_wrapper_exception_logging():
"""Test the actual helper's error logging (Fix for Comment 3)."""
async def error_coro():
raise ValueError("Tool failure")

View File

@@ -119,4 +119,3 @@ def test_format_memory_skips_non_string_content_facts() -> None:
# The formatted line for a list content would be "- [knowledge | 0.85] ['list']".
assert "| 0.85]" not in result
assert "Valid fact" in result

View File

@@ -163,7 +163,7 @@ class TestExtractText:
assert _extract_text(["raw string"]) == "raw string"
def test_list_string_chunks_join_without_separator(self):
content = ["{\"user\"", ': "alice"}']
content = ['{"user"', ': "alice"}']
assert _extract_text(content) == '{"user": "alice"}'
def test_list_mixed_strings_and_blocks(self):

View File

@@ -591,8 +591,8 @@ def test_codex_provider_strips_unsupported_max_tokens(monkeypatch):
factory_module.create_chat_model(name="codex", thinking_enabled=True)
assert "max_tokens" not in FakeChatModel.captured_kwargs
def test_openai_responses_api_settings_are_passed_to_chatopenai(monkeypatch):
model = ModelConfig(
name="gpt-5-responses",

View File

@@ -5,8 +5,10 @@ import pytest
from deerflow.sandbox.tools import (
VIRTUAL_PATH_PREFIX,
_is_acp_workspace_path,
_is_skills_path,
_reject_path_traversal,
_resolve_acp_workspace_path,
_resolve_and_validate_user_data_path,
_resolve_skills_path,
mask_local_paths_in_output,
@@ -27,10 +29,7 @@ _THREAD_DATA = {
def test_replace_virtual_path_maps_virtual_root_and_subpaths() -> None:
assert (
Path(replace_virtual_path("/mnt/user-data/workspace/a.txt", _THREAD_DATA)).as_posix()
== "/tmp/deer-flow/threads/t1/user-data/workspace/a.txt"
)
assert Path(replace_virtual_path("/mnt/user-data/workspace/a.txt", _THREAD_DATA)).as_posix() == "/tmp/deer-flow/threads/t1/user-data/workspace/a.txt"
assert Path(replace_virtual_path("/mnt/user-data", _THREAD_DATA)).as_posix() == "/tmp/deer-flow/threads/t1/user-data"
@@ -322,3 +321,105 @@ def test_validate_local_tool_path_skills_custom_container_path() -> None:
_THREAD_DATA,
read_only=True,
)
# ---------- ACP workspace path tests ----------
def test_is_acp_workspace_path_recognises_prefix() -> None:
assert _is_acp_workspace_path("/mnt/acp-workspace") is True
assert _is_acp_workspace_path("/mnt/acp-workspace/hello.py") is True
assert _is_acp_workspace_path("/mnt/acp-workspace-extra/foo") is False
assert _is_acp_workspace_path("/mnt/user-data/workspace") is False
def test_validate_local_tool_path_allows_acp_workspace_read_only() -> None:
"""read_file / ls should be able to access /mnt/acp-workspace paths."""
validate_local_tool_path(
"/mnt/acp-workspace/hello_world.py",
_THREAD_DATA,
read_only=True,
)
def test_validate_local_tool_path_blocks_acp_workspace_write() -> None:
"""write_file / str_replace must NOT write to ACP workspace paths."""
with pytest.raises(PermissionError, match="Write access to ACP workspace is not allowed"):
validate_local_tool_path(
"/mnt/acp-workspace/hello_world.py",
_THREAD_DATA,
read_only=False,
)
def test_validate_local_bash_command_paths_allows_acp_workspace() -> None:
"""bash commands referencing /mnt/acp-workspace should be allowed."""
validate_local_bash_command_paths(
"cp /mnt/acp-workspace/hello_world.py /mnt/user-data/outputs/hello_world.py",
_THREAD_DATA,
)
def test_validate_local_bash_command_paths_blocks_traversal_in_acp_workspace() -> None:
"""Bash commands with traversal in ACP workspace paths should be blocked."""
with pytest.raises(PermissionError, match="path traversal"):
validate_local_bash_command_paths(
"cat /mnt/acp-workspace/../../etc/passwd",
_THREAD_DATA,
)
def test_resolve_acp_workspace_path_resolves_correctly(tmp_path: Path) -> None:
"""ACP workspace virtual path should resolve to host path."""
acp_dir = tmp_path / "acp-workspace"
acp_dir.mkdir()
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=str(acp_dir)):
resolved = _resolve_acp_workspace_path("/mnt/acp-workspace/hello.py")
assert resolved == str(acp_dir / "hello.py")
def test_resolve_acp_workspace_path_resolves_root(tmp_path: Path) -> None:
"""ACP workspace root should resolve to host directory."""
acp_dir = tmp_path / "acp-workspace"
acp_dir.mkdir()
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=str(acp_dir)):
resolved = _resolve_acp_workspace_path("/mnt/acp-workspace")
assert resolved == str(acp_dir)
def test_resolve_acp_workspace_path_raises_when_not_available() -> None:
"""Should raise FileNotFoundError when ACP workspace does not exist."""
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=None):
with pytest.raises(FileNotFoundError, match="ACP workspace directory not available"):
_resolve_acp_workspace_path("/mnt/acp-workspace/hello.py")
def test_resolve_acp_workspace_path_blocks_traversal(tmp_path: Path) -> None:
"""Path traversal in ACP workspace paths must be rejected."""
acp_dir = tmp_path / "acp-workspace"
acp_dir.mkdir()
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=str(acp_dir)):
with pytest.raises(PermissionError, match="path traversal"):
_resolve_acp_workspace_path("/mnt/acp-workspace/../../etc/passwd")
def test_replace_virtual_paths_in_command_replaces_acp_workspace() -> None:
"""ACP workspace virtual paths in commands should be resolved to host paths."""
acp_host = "/home/user/.deer-flow/acp-workspace"
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=acp_host):
cmd = "cp /mnt/acp-workspace/hello.py /mnt/user-data/outputs/hello.py"
result = replace_virtual_paths_in_command(cmd, _THREAD_DATA)
assert "/mnt/acp-workspace" not in result
assert f"{acp_host}/hello.py" in result
assert "/tmp/deer-flow/threads/t1/user-data/outputs/hello.py" in result
def test_mask_local_paths_in_output_hides_acp_workspace_host_paths() -> None:
"""ACP workspace host paths in bash output should be masked to virtual paths."""
acp_host = "/home/user/.deer-flow/acp-workspace"
with patch("deerflow.sandbox.tools._get_acp_workspace_host_path", return_value=acp_host):
output = f"Copied: {acp_host}/hello.py"
masked = mask_local_paths_in_output(output, _THREAD_DATA)
assert acp_host not in masked
assert "/mnt/acp-workspace/hello.py" in masked

View File

@@ -53,7 +53,7 @@ class TestSerializeToolMessageContent:
def test_string_chunks_are_joined_without_newlines(self):
"""Chunked string payloads should not get artificial separators."""
msg = ToolMessage(
content=["{\"a\"", ": \"b\"}"] ,
content=['{"a"', ': "b"}'],
tool_call_id="tc1",
name="search",
)
@@ -118,9 +118,7 @@ class TestExtractText:
assert DeerFlowClient._extract_text("hello") == "hello"
def test_list_text_blocks(self):
assert DeerFlowClient._extract_text(
[{"type": "text", "text": "hi"}]
) == "hi"
assert DeerFlowClient._extract_text([{"type": "text", "text": "hi"}]) == "hi"
def test_empty_list(self):
assert DeerFlowClient._extract_text([]) == ""

View File

@@ -144,10 +144,13 @@ class TestSafeExtract:
assert not (dest / "link.txt").exists()
def test_normal_archive(self, tmp_path):
zip_path = self._make_zip(tmp_path, {
"my-skill/SKILL.md": "---\nname: test\ndescription: x\n---\n# Test",
"my-skill/README.md": "readme",
})
zip_path = self._make_zip(
tmp_path,
{
"my-skill/SKILL.md": "---\nname: test\ndescription: x\n---\n# Test",
"my-skill/README.md": "readme",
},
)
dest = tmp_path / "out"
dest.mkdir()
with zipfile.ZipFile(zip_path) as zf:

View File

@@ -16,9 +16,7 @@ def test_get_skills_root_path_points_to_project_root_skills():
"""get_skills_root_path() should point to deer-flow/skills (sibling of backend/), not backend/packages/skills."""
path = get_skills_root_path()
assert path.name == "skills", f"Expected 'skills', got '{path.name}'"
assert (path.parent / "backend").is_dir(), (
f"Expected skills path's parent to be project root containing 'backend/', but got {path}"
)
assert (path.parent / "backend").is_dir(), f"Expected skills path's parent to be project root containing 'backend/', but got {path}"
def test_load_skills_discovers_nested_skills_and_sets_container_paths(tmp_path: Path):

View File

@@ -177,12 +177,7 @@ class TestStreamUsageIntegration:
events = list(client.stream("hi", thread_id="t1"))
# Find the AI text messages-tuple event
ai_text_events = [
e for e in events
if e.type == "messages-tuple"
and e.data.get("type") == "ai"
and e.data.get("content") == "Hello!"
]
ai_text_events = [e for e in events if e.type == "messages-tuple" and e.data.get("type") == "ai" and e.data.get("content") == "Hello!"]
assert len(ai_text_events) == 1
event_data = ai_text_events[0].data
assert "usage_metadata" in event_data
@@ -244,12 +239,7 @@ class TestStreamUsageIntegration:
events = list(client.stream("hi", thread_id="t1"))
# messages-tuple AI event should NOT have usage_metadata
ai_text_events = [
e for e in events
if e.type == "messages-tuple"
and e.data.get("type") == "ai"
and e.data.get("content") == "Hello!"
]
ai_text_events = [e for e in events if e.type == "messages-tuple" and e.data.get("type") == "ai" and e.data.get("content") == "Hello!"]
assert len(ai_text_events) == 1
assert "usage_metadata" not in ai_text_events[0].data
@@ -290,12 +280,7 @@ class TestStreamUsageIntegration:
events = list(client.stream("search", thread_id="t1"))
# Final AI text event should have usage_metadata
ai_text_events = [
e for e in events
if e.type == "messages-tuple"
and e.data.get("type") == "ai"
and e.data.get("content") == "Here is the answer."
]
ai_text_events = [e for e in events if e.type == "messages-tuple" and e.data.get("type") == "ai" and e.data.get("content") == "Here is the answer."]
assert len(ai_text_events) == 1
assert ai_text_events[0].data["usage_metadata"]["total_tokens"] == 300

View File

@@ -168,6 +168,37 @@ class TestSingleton:
reset_deferred_registry()
assert get_deferred_registry() is None
def test_contextvar_isolation_across_contexts(self, registry):
"""P2: Each async context gets its own independent registry value."""
import contextvars
reg_a = DeferredToolRegistry()
reg_a.register(_make_mock_tool("tool_a", "Tool A"))
reg_b = DeferredToolRegistry()
reg_b.register(_make_mock_tool("tool_b", "Tool B"))
seen: dict[str, object] = {}
def run_in_context_a():
set_deferred_registry(reg_a)
seen["ctx_a"] = get_deferred_registry()
def run_in_context_b():
set_deferred_registry(reg_b)
seen["ctx_b"] = get_deferred_registry()
ctx_a = contextvars.copy_context()
ctx_b = contextvars.copy_context()
ctx_a.run(run_in_context_a)
ctx_b.run(run_in_context_b)
# Each context got its own registry, neither bleeds into the other
assert seen["ctx_a"] is reg_a
assert seen["ctx_b"] is reg_b
# The current context is unchanged
assert get_deferred_registry() is None
# ── tool_search Tool Tests ──