mirror of
https://gitee.com/wanwujie/deer-flow
synced 2026-04-03 06:12:14 +08:00
* 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>
292 lines
12 KiB
Python
292 lines
12 KiB
Python
"""Tests for token usage tracking in DeerFlowClient."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from unittest.mock import MagicMock, patch
|
|
|
|
from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
|
|
|
|
from deerflow.client import DeerFlowClient
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _serialize_message — usage_metadata passthrough
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestSerializeMessageUsageMetadata:
|
|
"""Verify _serialize_message includes usage_metadata when present."""
|
|
|
|
def test_ai_message_with_usage_metadata(self):
|
|
msg = AIMessage(
|
|
content="Hello",
|
|
id="msg-1",
|
|
usage_metadata={"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
|
|
)
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["type"] == "ai"
|
|
assert result["usage_metadata"] == {
|
|
"input_tokens": 100,
|
|
"output_tokens": 50,
|
|
"total_tokens": 150,
|
|
}
|
|
|
|
def test_ai_message_without_usage_metadata(self):
|
|
msg = AIMessage(content="Hello", id="msg-2")
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["type"] == "ai"
|
|
assert "usage_metadata" not in result
|
|
|
|
def test_tool_message_never_has_usage_metadata(self):
|
|
msg = ToolMessage(content="result", tool_call_id="tc-1", name="search")
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["type"] == "tool"
|
|
assert "usage_metadata" not in result
|
|
|
|
def test_human_message_never_has_usage_metadata(self):
|
|
msg = HumanMessage(content="Hi")
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["type"] == "human"
|
|
assert "usage_metadata" not in result
|
|
|
|
def test_ai_message_with_tool_calls_and_usage(self):
|
|
msg = AIMessage(
|
|
content="",
|
|
id="msg-3",
|
|
tool_calls=[{"name": "search", "args": {"q": "test"}, "id": "tc-1"}],
|
|
usage_metadata={"input_tokens": 200, "output_tokens": 30, "total_tokens": 230},
|
|
)
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["type"] == "ai"
|
|
assert result["tool_calls"] == [{"name": "search", "args": {"q": "test"}, "id": "tc-1"}]
|
|
assert result["usage_metadata"]["input_tokens"] == 200
|
|
|
|
def test_ai_message_with_zero_usage(self):
|
|
"""usage_metadata with zero token counts should be included."""
|
|
msg = AIMessage(
|
|
content="Hello",
|
|
id="msg-4",
|
|
usage_metadata={"input_tokens": 0, "output_tokens": 0, "total_tokens": 0},
|
|
)
|
|
result = DeerFlowClient._serialize_message(msg)
|
|
assert result["usage_metadata"] == {
|
|
"input_tokens": 0,
|
|
"output_tokens": 0,
|
|
"total_tokens": 0,
|
|
}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cumulative usage tracking (simulated, no real agent)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
class TestCumulativeUsageTracking:
|
|
"""Test cumulative usage aggregation logic."""
|
|
|
|
def test_single_message_usage(self):
|
|
"""Single AI message usage should be the total."""
|
|
cumulative = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
|
|
usage = {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150}
|
|
cumulative["input_tokens"] += usage.get("input_tokens", 0) or 0
|
|
cumulative["output_tokens"] += usage.get("output_tokens", 0) or 0
|
|
cumulative["total_tokens"] += usage.get("total_tokens", 0) or 0
|
|
assert cumulative == {"input_tokens": 100, "output_tokens": 50, "total_tokens": 150}
|
|
|
|
def test_multiple_messages_usage(self):
|
|
"""Multiple AI messages should accumulate."""
|
|
cumulative = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
|
|
messages_usage = [
|
|
{"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
|
|
{"input_tokens": 200, "output_tokens": 30, "total_tokens": 230},
|
|
{"input_tokens": 150, "output_tokens": 80, "total_tokens": 230},
|
|
]
|
|
for usage in messages_usage:
|
|
cumulative["input_tokens"] += usage.get("input_tokens", 0) or 0
|
|
cumulative["output_tokens"] += usage.get("output_tokens", 0) or 0
|
|
cumulative["total_tokens"] += usage.get("total_tokens", 0) or 0
|
|
assert cumulative == {"input_tokens": 450, "output_tokens": 160, "total_tokens": 610}
|
|
|
|
def test_missing_usage_keys_treated_as_zero(self):
|
|
"""Missing keys in usage dict should be treated as 0."""
|
|
cumulative = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
|
|
usage = {"input_tokens": 50} # missing output_tokens, total_tokens
|
|
cumulative["input_tokens"] += usage.get("input_tokens", 0) or 0
|
|
cumulative["output_tokens"] += usage.get("output_tokens", 0) or 0
|
|
cumulative["total_tokens"] += usage.get("total_tokens", 0) or 0
|
|
assert cumulative == {"input_tokens": 50, "output_tokens": 0, "total_tokens": 0}
|
|
|
|
def test_empty_usage_metadata_stays_zero(self):
|
|
"""No usage metadata should leave cumulative at zero."""
|
|
cumulative = {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
|
|
# Simulate: AI message without usage_metadata
|
|
usage = None
|
|
if usage:
|
|
cumulative["input_tokens"] += usage.get("input_tokens", 0) or 0
|
|
assert cumulative == {"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# stream() integration — usage_metadata in end event and messages-tuple
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _make_agent_mock(chunks):
|
|
"""Create a mock agent whose .stream() yields the given chunks."""
|
|
agent = MagicMock()
|
|
agent.stream.return_value = iter(chunks)
|
|
return agent
|
|
|
|
|
|
def _mock_app_config():
|
|
"""Provide a minimal AppConfig mock."""
|
|
model = MagicMock()
|
|
model.name = "test-model"
|
|
model.model = "test-model"
|
|
model.supports_thinking = False
|
|
model.supports_reasoning_effort = False
|
|
model.model_dump.return_value = {"name": "test-model", "use": "langchain_openai:ChatOpenAI"}
|
|
config = MagicMock()
|
|
config.models = [model]
|
|
return config
|
|
|
|
|
|
class TestStreamUsageIntegration:
|
|
"""Test that stream() emits usage_metadata in messages-tuple and end events."""
|
|
|
|
def _make_client(self):
|
|
with patch("deerflow.client.get_app_config", return_value=_mock_app_config()):
|
|
return DeerFlowClient()
|
|
|
|
def test_stream_emits_usage_in_messages_tuple(self):
|
|
"""messages-tuple AI event should include usage_metadata when present."""
|
|
client = self._make_client()
|
|
ai = AIMessage(
|
|
content="Hello!",
|
|
id="ai-1",
|
|
usage_metadata={"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
|
|
)
|
|
chunks = [
|
|
{"messages": [HumanMessage(content="hi", id="h-1"), ai]},
|
|
]
|
|
agent = _make_agent_mock(chunks)
|
|
|
|
with (
|
|
patch.object(client, "_ensure_agent"),
|
|
patch.object(client, "_agent", agent),
|
|
):
|
|
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!"]
|
|
assert len(ai_text_events) == 1
|
|
event_data = ai_text_events[0].data
|
|
assert "usage_metadata" in event_data
|
|
assert event_data["usage_metadata"] == {
|
|
"input_tokens": 100,
|
|
"output_tokens": 50,
|
|
"total_tokens": 150,
|
|
}
|
|
|
|
def test_stream_cumulative_usage_in_end_event(self):
|
|
"""end event should include cumulative usage across all AI messages."""
|
|
client = self._make_client()
|
|
ai1 = AIMessage(
|
|
content="First",
|
|
id="ai-1",
|
|
usage_metadata={"input_tokens": 100, "output_tokens": 50, "total_tokens": 150},
|
|
)
|
|
ai2 = AIMessage(
|
|
content="Second",
|
|
id="ai-2",
|
|
usage_metadata={"input_tokens": 200, "output_tokens": 30, "total_tokens": 230},
|
|
)
|
|
chunks = [
|
|
{"messages": [HumanMessage(content="hi", id="h-1"), ai1]},
|
|
{"messages": [HumanMessage(content="hi", id="h-1"), ai1, ai2]},
|
|
]
|
|
agent = _make_agent_mock(chunks)
|
|
|
|
with (
|
|
patch.object(client, "_ensure_agent"),
|
|
patch.object(client, "_agent", agent),
|
|
):
|
|
events = list(client.stream("hi", thread_id="t1"))
|
|
|
|
# Find the end event
|
|
end_events = [e for e in events if e.type == "end"]
|
|
assert len(end_events) == 1
|
|
end_data = end_events[0].data
|
|
assert "usage" in end_data
|
|
assert end_data["usage"] == {
|
|
"input_tokens": 300,
|
|
"output_tokens": 80,
|
|
"total_tokens": 380,
|
|
}
|
|
|
|
def test_stream_no_usage_metadata_no_usage_in_events(self):
|
|
"""When AI messages have no usage_metadata, events should not include it."""
|
|
client = self._make_client()
|
|
ai = AIMessage(content="Hello!", id="ai-1")
|
|
chunks = [
|
|
{"messages": [HumanMessage(content="hi", id="h-1"), ai]},
|
|
]
|
|
agent = _make_agent_mock(chunks)
|
|
|
|
with (
|
|
patch.object(client, "_ensure_agent"),
|
|
patch.object(client, "_agent", agent),
|
|
):
|
|
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!"]
|
|
assert len(ai_text_events) == 1
|
|
assert "usage_metadata" not in ai_text_events[0].data
|
|
|
|
# end event should still exist but with zero usage
|
|
end_events = [e for e in events if e.type == "end"]
|
|
assert len(end_events) == 1
|
|
usage = end_events[0].data.get("usage", {})
|
|
assert usage.get("input_tokens", 0) == 0
|
|
assert usage.get("output_tokens", 0) == 0
|
|
assert usage.get("total_tokens", 0) == 0
|
|
|
|
def test_stream_usage_with_tool_calls(self):
|
|
"""Usage should be tracked even when AI message has tool calls."""
|
|
client = self._make_client()
|
|
ai_tool = AIMessage(
|
|
content="",
|
|
id="ai-1",
|
|
tool_calls=[{"name": "search", "args": {"q": "test"}, "id": "tc-1"}],
|
|
usage_metadata={"input_tokens": 150, "output_tokens": 25, "total_tokens": 175},
|
|
)
|
|
tool_result = ToolMessage(content="result", id="tm-1", tool_call_id="tc-1", name="search")
|
|
ai_final = AIMessage(
|
|
content="Here is the answer.",
|
|
id="ai-2",
|
|
usage_metadata={"input_tokens": 200, "output_tokens": 100, "total_tokens": 300},
|
|
)
|
|
chunks = [
|
|
{"messages": [HumanMessage(content="search", id="h-1"), ai_tool]},
|
|
{"messages": [HumanMessage(content="search", id="h-1"), ai_tool, tool_result]},
|
|
{"messages": [HumanMessage(content="search", id="h-1"), ai_tool, tool_result, ai_final]},
|
|
]
|
|
agent = _make_agent_mock(chunks)
|
|
|
|
with (
|
|
patch.object(client, "_ensure_agent"),
|
|
patch.object(client, "_agent", agent),
|
|
):
|
|
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."]
|
|
assert len(ai_text_events) == 1
|
|
assert ai_text_events[0].data["usage_metadata"]["total_tokens"] == 300
|
|
|
|
# end event should have cumulative usage
|
|
end_events = [e for e in events if e.type == "end"]
|
|
assert end_events[0].data["usage"]["input_tokens"] == 350
|
|
assert end_events[0].data["usage"]["output_tokens"] == 125
|
|
assert end_events[0].data["usage"]["total_tokens"] == 475
|