接口修改

This commit is contained in:
fengxiangdebaozi committed 2026-05-22 20:40:36 +08:00
1 parent ab6b6876aa
commit edb3238f3e
16 files changed
+2113 -54

No files matched your search

@@ -312,6 +312,37 @@ def _build_middlewares(
middlewares.append(SetupAgentApprovalMiddleware())
# SkillStopMiddleware — intercepts skill invocations and halts execution
# when a configured skill is about to run. Request-level options
# (skill_stop_names / skill_stop_message) take precedence; static
# config in ``app_config.skill_stop`` is the fallback.
skill_stop_names = cfg.get("skill_stop_names")
skill_stop_message = cfg.get("skill_stop_message")
if skill_stop_names:
from deerflow.agents.middlewares.skill_stop_middleware import SkillStopMiddleware
middlewares.append(
SkillStopMiddleware(
skill_names=skill_stop_names,
skills_root=resolved_app_config.skills.container_path or "/mnt/skills",
stop_message=skill_stop_message,
stop_on_match=True,
)
)
logger.info("SkillStopMiddleware enabled (from request): %s", skill_stop_names)
elif resolved_app_config.skill_stop.enabled and resolved_app_config.skill_stop.skill_names:
from deerflow.agents.middlewares.skill_stop_middleware import SkillStopMiddleware
middlewares.append(
SkillStopMiddleware(
skill_names=resolved_app_config.skill_stop.skill_names,
skills_root=resolved_app_config.skills.container_path or "/mnt/skills",
stop_message=resolved_app_config.skill_stop.stop_message,
stop_on_match=resolved_app_config.skill_stop.stop_on_match,
)
)
logger.info("SkillStopMiddleware enabled (from config): %s", resolved_app_config.skill_stop.skill_names)
# ClarificationMiddleware should always be last
middlewares.append(ClarificationMiddleware())
return middlewares
@@ -345,6 +376,7 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
if not isinstance(writing_artifact_path, str) or not writing_artifact_path.strip():
writing_artifact_path = None
agent_id = validate_agent_id(cfg.get("agent_id") or cfg.get("agent_name"))
requested_excluded_tools = cfg.get("excluded_tools") or None
try:
agent_config = load_agent_config(agent_id) if not is_bootstrap else None
@@ -415,6 +447,7 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
model_name=model_name,
subagent_enabled=subagent_enabled,
is_scheduled_run=cfg.get("is_scheduled_run", False),
excluded_tools=requested_excluded_tools,
app_config=resolved_app_config,
)
+ [setup_agent],
@@ -440,6 +473,7 @@ def _make_lead_agent(config: RunnableConfig, *, app_config: AppConfig):
groups=agent_config.tool_groups if agent_config else None,
subagent_enabled=subagent_enabled,
is_scheduled_run=cfg.get("is_scheduled_run", False),
excluded_tools=requested_excluded_tools,
app_config=resolved_app_config,
),
middleware=_build_middlewares(config, model_name=model_name, agent_name=agent_id, app_config=resolved_app_config),
@@ -0,0 +1,144 @@
"""Middleware for intercepting skill calls and stopping execution when specific skills are invoked."""
import logging
import re
from collections.abc import Callable
from typing import Any, override
from langchain.agents import AgentState
from langchain.agents.middleware import AgentMiddleware
from langchain_core.messages import ToolMessage
from langgraph.prebuilt.tool_node import ToolCallRequest
from langgraph.types import Command, interrupt
logger = logging.getLogger(__name__)
def extract_name_task(text: str) -> tuple[str, str]:
"""Extract `agent_name` and `task_content` from a bash invocation that triggers
a sub-agent via ``python3 scripts/agent_orchestration.py "<agent>" "<task>"``.
Returns empty strings when no match is found so the caller can treat the
absence of a match as "not a target skill call".
"""
try:
pattern = r'\.py\s+"([^"]*)"\s+"([^"]*)"'
match = re.search(pattern, text)
if match:
return match.group(1), match.group(2)
return "", ""
except Exception:
return "", ""
class SkillStopMiddlewareState(AgentState):
"""Compatible with the `ThreadState` schema."""
pass
class SkillStopMiddleware(AgentMiddleware[SkillStopMiddlewareState]):
"""Intercepts skill file reads and stops execution when specific skills are invoked.
When the model reads a file from a skill directory that matches one of the
configured skill names, this middleware:
1. Intercepts the tool call before execution
2. Returns a Command that stops execution (goes to END)
3. Optionally returns a message indicating which skill was triggered
This is useful for implementing "skill triggers" that pause the agent
when certain skills are about to be used.
"""
state_schema = SkillStopMiddlewareState
def __init__(
self,
*,
skill_names: list[str],
skills_root: str = "/mnt/skills",
stop_message: str | None = None,
stop_on_match: bool = True,
):
"""Initialize the skill stop middleware.
Args:
skill_names: List of skill names to intercept (e.g., ["newsletter-generation", "podcast-generation"]).
skills_root: Root directory where skills are located (default: "/mnt/skills").
stop_message: Optional message to return when stopping. If None, a default message is used.
stop_on_match: If True, stop when skill matches. If False, continue execution (for logging only).
"""
super().__init__()
self._skill_names = set(skill_names)
self._skills_root = skills_root.rstrip("/")
self._stop_message = stop_message
self._stop_on_match = stop_on_match
def _is_target_skill_call(self, tool_call: dict[str, Any]) -> str | None:
"""Return the matched skill name if this tool call invokes one of the
configured target skills, otherwise ``None``.
Matching today is bash-based: the lead agent reaches into a skill by
running ``python3 scripts/agent_orchestration.py "<skill-name>" "<task>"``,
so we only look at ``bash`` calls and extract the skill name from the
argv-style quoted form.
"""
name = tool_call.get("name") or ""
skill_name = ""
if name == "bash" and "args" in tool_call:
skill_name, _ = extract_name_task(str(tool_call["args"]))
if not skill_name:
return None
lowered_targets = {s.lower() for s in self._skill_names}
if skill_name in self._skill_names or skill_name.lower() in lowered_targets:
logger.info("SkillStopMiddleware: matched skill_name=%s", skill_name)
return skill_name
return None
def _handle_skill_stop(self, request: ToolCallRequest, skill_name: str) -> Command:
"""Build the stop response — an interrupt that includes a ToolMessage
describing which skill was triggered."""
logger.info("Skill stop triggered: skill_name=%s", skill_name)
tool_call_id = request.tool_call.get("id", "")
message_content = self._stop_message or f"⏹️ Skill '{skill_name}' triggered. Execution stopped."
tool_message = ToolMessage(
id=f"skill_stop:{tool_call_id}",
content=message_content,
tool_call_id=tool_call_id,
name="skill_stop",
)
return interrupt(
{
"messages": [tool_message],
"skill_name": skill_name,
}
)
@override
def wrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
matched_skill = self._is_target_skill_call(request.tool_call)
if matched_skill:
if self._stop_on_match:
return self._handle_skill_stop(request, matched_skill)
logger.info("Skill detected (not stopping): skill_name=%s", matched_skill)
return handler(request)
@override
async def awrap_tool_call(
self,
request: ToolCallRequest,
handler: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
matched_skill = self._is_target_skill_call(request.tool_call)
if matched_skill:
if self._stop_on_match:
return self._handle_skill_stop(request, matched_skill)
logger.info("Skill detected (not stopping): skill_name=%s", matched_skill)
return await handler(request)