agent_hub.py 21.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
import logging
import time
from functools import partial
from pathlib import Path
from typing import Dict, List, Optional, Any
from app.config.loader import ConfigLoader
from app.service.active_session_service import ActiveSessionService
from agentscope.tool import Toolkit
from app.hooks.post_reply import PostReplyHook
from app.service.memory import SessionMemory
from agentscope.model import OpenAIChatModel
from agentscope.formatter import OpenAIChatFormatter
from agentscope.message import Msg
from agentscope.message._message_block import TextBlock
from agentscope.tool._response import ToolResponse
from agentscope.tool import execute_python_code, execute_shell_command
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory


logger = logging.getLogger(__name__)


async def _im_post_reasoning_hook(
    self, kwargs, output,
    *, im_service, account_mapping, room_id, user_id, bot_id_mapping,
):
    """AgentScope native hook: 推理完成后通过 IM 发送 thinking 文本。"""
    logger.info(f"[Hook 触发] agent={self.name} 时机=post_reasoning")
    bot_id = (bot_id_mapping.get(self.name) or account_mapping.get(self.name))
    if not bot_id:
        return None
    # 只提取 ThinkingBlock,跳过 tool_use 等其他 block
    content_parts = []
    if output and hasattr(output, "content"):
        blocks = output.content if isinstance(output.content, list) else []
        for block in blocks:
            if isinstance(block, dict) and block.get("type") == "thinking":
                content_parts.append(block.get("thinking", ""))
    content = "\n".join(content_parts) if content_parts else None
    if not content:
        return None
    # 中间过程只发前10个字符 + 省略号
    content = content[:25] + "..." if len(content) > 10 else content
    # 删除"下载"这个词
    content = content.replace("下载", "点击")
    logger.info(f"[Hook 发送 IM] agent={self.name} bot_id={bot_id} content={content[:50]}...")
    try:
        await im_service.send_message(
            bot_id=bot_id, content=content,
            contact_id=room_id, at_list="",
        )
    except Exception:
        logger.warning(
            "[Hook IM 发送失败] agent=%s room=%s(不影响推理流程)",
            self.name, room_id, exc_info=True,
        )


async def _im_pre_acting_hook(
    self, kwargs,
    *, im_service, account_mapping, room_id, user_id, bot_id_mapping,
):
    """AgentScope native hook: 工具调用前通过 IM 发送即将执行的工具信息。"""
    logger.info(f"[Hook 触发] agent={self.name} 时机=pre_acting")
    bot_id = (bot_id_mapping.get(self.name) or account_mapping.get(self.name))
    if not bot_id:
        return None
    tool_call = kwargs.get("tool_call")
    if not tool_call:
        return None
    content = str(tool_call)
    logger.info(f"[Hook 发送 IM] agent={self.name} bot_id={bot_id} tool_call={tool_call}")
    try:
        await im_service.send_message(
            bot_id=bot_id, content=content,
            contact_id=room_id, at_list="",
        )
    except Exception:
        logger.warning(
            "[Hook IM 发送失败] agent=%s room=%s(不影响推理流程)",
            self.name, room_id, exc_info=True,
        )


class AgentHubError(Exception):
    """Raised when AgentHub processing fails."""
    pass


class AgentHub:
    """
    中央调度器 - 唯一运行的 Agent 运行时

    持有所有 Agent 的配置,负责:
    1. 提示词组装
    2. 模型调用
    3. 消息路由和分发
    4. 通过 Hook 发送消息
    """

    def __init__(
        self,
        config_loader: ConfigLoader,
        session_service: ActiveSessionService,
        im_service,
    ):
        self.config_loader = config_loader
        self.session_service = session_service
        self.im_service = im_service

        self.agents = config_loader.load_agents()
        self.main_model_config = config_loader.load_models()["main"]
        agent_to_account, account_to_agent = config_loader.load_account_mappings()
        self.agent_to_account = agent_to_account
        self.account_to_agent = account_to_agent

        self.post_reply_hook = PostReplyHook(
            im_service=im_service,
            account_mapping=agent_to_account
        )

        self.toolkit = Toolkit()
        self.model = OpenAIChatModel(
            model_name=self.main_model_config.model_name,
            api_key=self.main_model_config.api_key,
            stream=False,
            client_kwargs={"base_url": self.main_model_config.api_base}
        )
        self.formatter = OpenAIChatFormatter()

        # Register all skills from skills/ directory to Toolkit
        skills_dir = Path(__file__).parent.parent.parent / "skills"
        logger.info(f"扫描 skills 目录并注册到全局 Toolkit: {skills_dir}")
        for skill_entry in sorted(skills_dir.iterdir()):
            if skill_entry.is_dir() and not skill_entry.name.startswith('.'):
                skill_md = skill_entry / "SKILL.md"
                if skill_md.exists():
                    try:
                        self.toolkit.register_agent_skill(str(skill_entry))
                    except Exception as e:
                        logger.warning(
                            f"跳过 skill {skill_entry.name}: {e}"
                        )

        # Load skills metadata from Toolkit
        self.skills = config_loader.load_skills_from_toolkit(self.toolkit)

        # Register built-in coding tools (shared by all agents)
        self.toolkit.register_tool_function(
            execute_python_code,
            group_name="basic",
        )
        self.toolkit.register_tool_function(
            execute_shell_command,
            group_name="basic",
        )

        # Register call_sub_agent as a tool for serial chain collaboration
        call_sub = self._make_call_sub_agent_tool()
        self.toolkit.register_tool_function(
            call_sub,
            func_name="call_sub_agent",
            group_name="basic",
            json_schema={
                "type": "function",
                "function": {
                    "name": "call_sub_agent",
                    "description": "调用子Agent处理特定任务。当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。",
                    "parameters": {
                        "type": "object",
                        "properties": {
                            "agent_code": {
                                "type": "string",
                                "description": "子Agent调用码,必须从可用子Agent列表中选择,如 \"meeting\"",
                            },
                            "instruction": {
                                "type": "string",
                                "description": "给子Agent的具体指令,必须包含用户需求的完整描述",
                            },
                        },
                        "required": ["agent_code", "instruction"],
                    },
                },
            },
        )

        # Register sandboxed read_file tool for reading project files
        read_file = self._make_read_file_tool()
        self.toolkit.register_tool_function(
            read_file,
            func_name="read_file",
            group_name="basic",
        )

        # 构建每个 agent 的专属 toolkit(按 skills 字段过滤)
        self.agent_toolkits: Dict[str, Toolkit] = {}
        for agent_code, agent_config in self.agents.items():
            logger.info(f"构建 agent '{agent_code}' 的专属 Toolkit (skills: {agent_config.skills})")
            agent_tk = Toolkit()
            # 复制 basic 组工具(所有 agent 共用)
            for name, tool in self.toolkit.tools.items():
                if tool.group == "basic":
                    agent_tk.register_tool_function(
                        tool.original_func,
                        group_name=tool.group,
                        func_name=tool.name,
                        preset_kwargs=tool.preset_kwargs,
                        json_schema=tool.json_schema,
                    )
            # 只复制该 agent 配置的 skills
            for skill_name in agent_config.skills:
                if skill_name in self.toolkit.skills:
                    skill_info = self.toolkit.skills[skill_name]
                    skill_dir = skill_info.get("dir", "")
                    if skill_dir:
                        agent_tk.register_agent_skill(skill_dir)
            self.agent_toolkits[agent_code] = agent_tk

    def _register_im_hooks(
        self,
        agent,
        room_id: str,
        user_id: str,
        bot_id_mapping: Optional[Dict[str, str]],
    ):
        """为 Agent 实例注册 IM 发送 hook。"""
        logger.info(f"[Hook 注册] agent={agent.name} 时机=post_reasoning")
        route_ctx = dict(
            im_service=self.im_service,
            account_mapping=self.agent_to_account,
            room_id=room_id,
            user_id=user_id,
            bot_id_mapping=bot_id_mapping or {},
        )
        agent.register_instance_hook(
            "post_reasoning", "im_post_reasoning",
            partial(_im_post_reasoning_hook, **route_ctx),
        )
        # pre_acting hook 保留未启用,需要时取消注释
        # agent.register_instance_hook(
        #     "pre_acting", "im_pre_acting",
        #     partial(_im_pre_acting_hook, **route_ctx),
        # )

    def _build_main_prompt(
        self,
        context: Dict[str, Any],
        allowed_agent_codes: Optional[list] = None,
    ) -> str:
        """
        Build the main agent's prompt including sub-agent duty descriptions.
        When allowed_agent_codes is set, only agents in that list are advertised.
        """
        main_agent = self.agents.get("main")
        if not main_agent:
            raise AgentHubError("主 Agent 配置未找到")

        # Collect duties from sub-agents, filtered by position if applicable
        duty_lines = []
        for code, agent in self.agents.items():
            if code == "main":
                continue
            if allowed_agent_codes is not None and code not in allowed_agent_codes:
                continue
            # 使用简洁职责描述,避免原样拼入 prompt_template 中的 {company}/{duties} 占位符
            sub_desc = f"负责{agent.role}相关任务"
            duty_lines.append(
                f"- {agent.name}(调用码: {code}): {sub_desc}"
            )

        duties_text = "\n".join(duty_lines) if duty_lines else "暂无子Agent"

        prompt = main_agent.prompt_template.format(
            company="公司",
            duties=duties_text,
        )

        review_guide = """
## 收到子Agent返回后

1. 判断结果是否完整,是否还需要其他子Agent协作
2. 如果已经可以回复,整合所有结果用自然语言回复用户
3. 不要再调用同一个子Agent重复处理
"""

        return prompt + review_guide

    def _build_sub_agent_prompt(self, agent_code: str, context: Dict[str, Any]) -> str:
        """Build prompt for a sub-agent when handling a routed query."""
        agent = self.agents.get(agent_code)
        if not agent:
            raise AgentHubError(f"Agent {agent_code} 配置未找到")

        # Build duties from ALL agents (for context)
        duty_lines = []
        for code, a in self.agents.items():
            duty_lines.append(f"- {a.name}({a.role})")

        prompt = agent.prompt_template.format(
            company="公司",
            duties="\n".join(duty_lines),
        )

        return prompt

    def _dict_to_msg(self, m: dict) -> Msg:
        """SessionStore dict → AgentScope Msg。只处理 user/assistant 文本消息。"""
        role = m.get("role", "user")
        if role not in ("user", "assistant", "system"):
            role = "user"
        content = m.get("content") or ""
        return Msg(name=role, role=role, content=content)

    async def process_message(
        self,
        session_id: str,
        room_id: str,
        user_id: str,
        user_query: str,
        mentioned_agent_code: Optional[str] = None,
        channel: str = "wechat_group",
        file_url: Optional[str] = None,
        allowed_agent_codes: Optional[list] = None,
        bot_id_mapping: Optional[Dict[str, str]] = None,
    ) -> Dict[str, Any]:
        """
        Process a user message end-to-end.

        Flow:
        1. Get or create session
        2. Load conversation history
        3. If @mentioned a specific agent → route directly
        4. Otherwise → main agent judges intent
        5. If intent is "route" → sub-agent handles
        6. Send reply via post_reply hook
        """
        start_time = time.time()

        # 暂存路由上下文,供 _call_sub_agent 创建子 Agent 时注册 hook
        self._current_route_ctx = dict(
            room_id=room_id, user_id=user_id, bot_id_mapping=bot_id_mapping or {},
        )

        session = self.session_service.get_or_create_session(
            session_id=session_id,
            room_id=room_id,
            channel=channel
        )

        memory = SessionMemory(
            session_id=session_id,
            store=self.session_service.store,
            max_rounds=20,
        )

        messages = memory.get_messages(max_rounds=10)

        # 始终路由到 main agent
        target_agent = "main"
        routing_reason = "default"

        context = {
            "user_query": user_query,
            "messages": messages,
            "room_id": room_id,
            "user_id": user_id
        }

        logger.debug(
            "路由决策: target=%s reason=%s position_restricted=%s allowed=%s",
            target_agent, routing_reason,
            allowed_agent_codes is not None, allowed_agent_codes,
        )

        # Build prompt based on target agent
        if target_agent == "main":
            system_prompt = self._build_main_prompt(context, allowed_agent_codes=allowed_agent_codes)
        else:
            system_prompt = self._build_sub_agent_prompt(target_agent, context)

        # Bridge: convert SessionStore dict history → AgentScope Msg[]
        agent_memory = InMemoryMemory()
        recent = messages[-10:]
        history_msgs = [self._dict_to_msg(m) for m in recent]
        if history_msgs:
            await agent_memory.add(history_msgs)

        # Create per-request ReActAgent with per-agent toolkit
        agent = ReActAgent(
            name=target_agent,
            sys_prompt=system_prompt,
            model=self.model,
            formatter=self.formatter,
            toolkit=self.agent_toolkits.get(target_agent, self.toolkit),
            memory=agent_memory,
            max_iters=10,
        )

        # Register IM hooks for this agent instance
        self._register_im_hooks(agent, room_id, user_id, bot_id_mapping)

        # Run ReAct loop via framework
        # If there's an image URL, append it to the query so the agent can see it
        effective_query = user_query
        if file_url:
            effective_query = f"{user_query}\n\n[用户发送了一张图片: {file_url}]"

        user_msg = Msg("user", effective_query, "user")

        # Store user message BEFORE agent call so it persists even on error
        memory.add("user", user_query, agent_code="main")
        try:
            response_msg = await agent.reply(user_msg)
            response_content = response_msg.get_text_content() or ""
            memory.add("assistant", response_content, agent_code=target_agent)
        finally:
            # 持久化到 DB — always save what we have
            self.session_service.save_to_db(session_id)

        # Send via hook
        try:
            await self.post_reply_hook.execute({
                "agent_name": target_agent,
                "response_content": response_content,
                "room_id": room_id,
                "mentioned_list": [user_id],
                "bot_id_mapping": bot_id_mapping or {},
            })
        except Exception:
            logger.warning(
                "[最终回复 IM 发送失败] agent=%s session=%s room=%s",
                target_agent, session_id, room_id, exc_info=True,
            )

        processing_time_ms = (time.time() - start_time) * 1000

        return {
            "session_id": session.session_id,
            "response_agent_code": target_agent,
            "response_content": response_content,
            "routing_reason": routing_reason,
            "processing_time_ms": round(processing_time_ms, 2)
        }

    async def _call_sub_agent(self, agent_code: str, instruction: str) -> str:
        """通过 ReActAgent 调用子 Agent。"""
        if agent_code not in self.agents:
            valid = [c for c in self.agents if c != "main"]
            return (
                f"错误:子 Agent '{agent_code}' 不存在。"
                f"可用调用码: {valid}"
            )

        sub_prompt = self._build_sub_agent_prompt(agent_code, {})
        sub_memory = InMemoryMemory()

        # All agents use the shared toolkit
        sub_toolkit = self.toolkit

        sub_agent = ReActAgent(
            name=agent_code,
            sys_prompt=sub_prompt,
            model=self.model,
            formatter=self.formatter,
            toolkit=self.agent_toolkits.get(agent_code, self.toolkit),
            memory=sub_memory,
            max_iters=10,
        )

        # 为子 Agent 注册 IM hook
        ctx = self._current_route_ctx
        self._register_im_hooks(sub_agent, ctx["room_id"], ctx["user_id"], ctx["bot_id_mapping"])

        response = await sub_agent.reply(Msg("user", instruction, "user"))
        return response.get_text_content()

    def _make_read_file_tool(self):
        """Create a sandboxed read_file tool function.

        The sandbox root is the backend project directory (parent of app/).
        """
        root_dir = Path(__file__).parent.parent.parent.resolve()

        async def read_file(file_path: str) -> ToolResponse:
            """Read the content of a local file. Path is relative to the project root.

            Use this to read SKILL.md files, MEMORY.md, configuration files, etc.
            Example: read_file('skills/get_weather/SKILL.md')

            Args:
                file_path: File path relative to the project root,
                    e.g. 'skills/meeting_minutes/SKILL.md' or 'config/agents.json'

            Returns:
                File content as text, truncated to 10000 characters if too large.
            """
            try:
                # Normalize: convert backslashes, strip single leading ./
                normalized = file_path.replace("\\", "/")
                if normalized.startswith("./"):
                    normalized = normalized[2:]
                full_path = (root_dir / normalized).resolve()

                # Sandbox check: prevent path traversal (must be BEFORE exists check)
                if not str(full_path).startswith(str(root_dir)):
                    return ToolResponse(
                        content=[TextBlock(
                            type="text",
                            text="❌ Access denied: path escapes project root"
                        )]
                    )

                if not full_path.exists():
                    return ToolResponse(
                        content=[TextBlock(
                            type="text",
                            text=f"❌ File not found: {file_path}"
                        )]
                    )

                if not full_path.is_file():
                    return ToolResponse(
                        content=[TextBlock(
                            type="text",
                            text=f"❌ Not a file: {file_path}"
                        )]
                    )

                content = full_path.read_text(encoding="utf-8")
                if len(content) > 10000:
                    content = content[:10000] + "\n...[truncated]"

                return ToolResponse(
                    content=[TextBlock(type="text", text=content)]
                )

            except Exception as e:
                return ToolResponse(
                    content=[TextBlock(
                        type="text",
                        text=f"❌ Error reading file: {str(e)}"
                    )]
                )

        return read_file

    def _make_call_sub_agent_tool(self):
        """Create closure tool function for registration to Toolkit."""
        async def call_sub_agent(agent_code: str = "", instruction: str = "") -> ToolResponse:
            """调用子Agent处理特定任务。

            当用户问题属于某个子Agent的职责范围时,必须调用此工具委托处理。

            Args:
                agent_code: 子Agent调用码,必须从可用子Agent列表中选择,如 "meeting"
                instruction: 给子Agent的具体指令,必须包含用户需求的完整描述

            Returns:
                子Agent的处理结果
            """
            if not agent_code or not instruction:
                return ToolResponse(
                    content=[TextBlock(type="text", text=(
                        "错误:agent_code 和 instruction 都是必填参数。\n"
                        "正确示例:call_sub_agent(agent_code=\"meeting\", instruction=\"请帮我整理会议纪要\")"
                    ))]
                )
            result = await self._call_sub_agent(agent_code, instruction)
            return ToolResponse(
                content=[TextBlock(type="text", text=result)]
            )

        return call_sub_agent

    def register_skill_tool(self, skill_name: str, tool_func, func_name: str):
        """将工具注册到所有拥有该 skill 的 agent toolkit"""
        for agent_code, agent_config in self.agents.items():
            if skill_name in agent_config.skills:
                self.agent_toolkits[agent_code].register_tool_function(
                    tool_func,
                    func_name=func_name,
                    group_name="basic",
                )

    async def close(self):
        """Clean up resources (no-op with AgentScope)."""
        pass