From c3e0818107de2d048037c8bc83e15bc133f0bea0 Mon Sep 17 00:00:00 2001 From: ethereal49 Date: Sat, 31 Oct 2026 03:38:31 -1000 Subject: [PATCH 1/2] fix(agent): include plugin tools in proactive cron requests Cron and background wakes build their own ProviderRequest, so tools registered through @llm_tool could be missing and the model printed raw tool-call text. Merge the active registered tool set for proactive builds before the session plugin filter runs. --- astrbot/core/astr_agent_tool_exec.py | 1 + astrbot/core/astr_main_agent.py | 37 +++++++- astrbot/core/cron/manager.py | 1 + tests/unit/test_astr_main_agent.py | 128 +++++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 4 deletions(-) diff --git a/astrbot/core/astr_agent_tool_exec.py b/astrbot/core/astr_agent_tool_exec.py index d5407c69fa2..eaca6e27a5e 100644 --- a/astrbot/core/astr_agent_tool_exec.py +++ b/astrbot/core/astr_agent_tool_exec.py @@ -613,6 +613,7 @@ async def _wake_main_agent_for_background_result( computer_use_runtime=provider_settings.get("computer_use_runtime", "none"), sandbox_cfg=provider_settings.get("sandbox", {}), provider_settings=provider_settings, + proactive=True, ) req = ProviderRequest() diff --git a/astrbot/core/astr_main_agent.py b/astrbot/core/astr_main_agent.py index 1610308187e..f55e8ad86c9 100644 --- a/astrbot/core/astr_main_agent.py +++ b/astrbot/core/astr_main_agent.py @@ -42,6 +42,7 @@ from astrbot.core.platform.message_type import MessageType from astrbot.core.provider import Provider from astrbot.core.provider.entities import ProviderRequest +from astrbot.core.provider.func_tool_manager import FunctionToolManager from astrbot.core.provider.register import llm_tools from astrbot.core.skills.skill_manager import ( SkillInfo, @@ -238,6 +239,8 @@ class MainAgentBuildConfig: sandbox_cfg: dict = field(default_factory=dict) add_cron_tools: bool = True """This will add cron job management tools to the main agent for proactive cron job execution.""" + proactive: bool = False + """Whether this build serves a proactive cron/background wake request.""" provider_settings: dict = field(default_factory=dict) fallback_provider_ids: list[str] = field(default_factory=list) request_max_retries: int = 5 @@ -655,10 +658,7 @@ async def _ensure_persona_and_skills( # inject toolset in the persona if (persona and persona.get("tools") is None) or not persona: - persona_toolset = tmgr.get_full_tool_set() - for tool in list(persona_toolset): - if not tool.active: - persona_toolset.remove_tool(tool.name) + persona_toolset = _active_registered_tool_set(tmgr) else: persona_toolset = ToolSet() if persona["tools"]: @@ -1115,6 +1115,32 @@ def _plugin_tool_fix(event: AstrMessageEvent, req: ProviderRequest) -> None: req.func_tool = new_tool_set +def _active_registered_tool_set(tool_mgr: FunctionToolManager) -> ToolSet: + """Return the registered plugin/MCP tools that are currently active.""" + tool_set = tool_mgr.get_full_tool_set() + for tool in list(tool_set): + if not tool.active: + tool_set.remove_tool(tool.name) + return tool_set + + +def _apply_proactive_registered_tools( + req: ProviderRequest, + plugin_context: Context, +) -> None: + """Give proactive runs the plugin tools registered for this session. + + Cron and background wakes build their own ``ProviderRequest`` instead of + starting from a user message, so their tool set can miss tools registered + through ``@llm_tool`` and the model may print raw tool-call text instead. + """ + if req.func_tool is None: + req.func_tool = ToolSet() + req.func_tool.merge( + _active_registered_tool_set(plugin_context.get_llm_tool_manager()) + ) + + async def _handle_webchat( event: AstrMessageEvent, req: ProviderRequest, prov: Provider ) -> None: @@ -1879,6 +1905,9 @@ async def build_main_agent( if not req.session_id: req.session_id = event.unified_msg_origin + if config.proactive: + _apply_proactive_registered_tools(req, plugin_context) + _plugin_tool_fix(event, req) await _apply_web_search_tools(event, req, plugin_context) diff --git a/astrbot/core/cron/manager.py b/astrbot/core/cron/manager.py index e73a0ffa44e..d36be172bae 100644 --- a/astrbot/core/cron/manager.py +++ b/astrbot/core/cron/manager.py @@ -566,6 +566,7 @@ async def _woke_main_agent( ), sandbox_cfg=provider_settings.get("sandbox", {}), provider_settings=provider_settings, + proactive=True, ) req = ProviderRequest() conv = await _get_session_conv(event=cron_event, plugin_context=self.ctx) diff --git a/tests/unit/test_astr_main_agent.py b/tests/unit/test_astr_main_agent.py index a02d3054c54..1bdccb04df2 100644 --- a/tests/unit/test_astr_main_agent.py +++ b/tests/unit/test_astr_main_agent.py @@ -1976,6 +1976,134 @@ async def test_build_main_agent_basic( assert result is not None assert isinstance(result, module.MainAgentBuildResult) + @pytest.mark.asyncio + async def test_proactive_build_gets_registered_plugin_tools( + self, mock_event, mock_context, mock_provider + ): + """Proactive builds must carry tools registered through @llm_tool.""" + module = ama + plugin_tool = FunctionTool( + name="search_memes", + description="Search memes", + parameters={"type": "object", "properties": {}}, + ) + inactive_tool = FunctionTool( + name="disabled_meme_tool", + description="Disabled", + parameters={"type": "object", "properties": {}}, + active=False, + ) + tool_mgr = MagicMock() + tool_mgr.get_full_tool_set.return_value = ToolSet([plugin_tool, inactive_tool]) + tool_mgr.get_builtin_tool.side_effect = lambda cls, **kwargs: cls(**kwargs) + mock_context.get_llm_tool_manager.return_value = tool_mgr + mock_context.persona_manager.resolve_selected_persona = AsyncMock( + return_value=( + "locked", + {"name": "locked", "prompt": "No tools.", "tools": []}, + None, + False, + ) + ) + mock_event.platform_meta.support_proactive_message = False + mock_context.get_config.return_value = {"provider_settings": {}} + + req = ProviderRequest(prompt="run scheduled task") + req.conversation = MagicMock(persona_id="locked", history="[]") + config = module.MainAgentBuildConfig( + tool_call_timeout=60, + provider_settings={"web_search": False}, + computer_use_runtime="none", + add_cron_tools=True, + proactive=True, + ) + + with ( + patch("astrbot.core.astr_main_agent.AgentRunner") as mock_runner_cls, + patch("astrbot.core.astr_main_agent.AstrAgentContext"), + ): + mock_runner = MagicMock() + mock_runner.reset = AsyncMock() + mock_runner_cls.return_value = mock_runner + result = await module.build_main_agent( + event=mock_event, + plugin_context=mock_context, + config=config, + provider=mock_provider, + req=req, + apply_reset=False, + ) + + assert result is not None + try: + names = result.provider_request.func_tool.names() + assert "search_memes" in names + assert "disabled_meme_tool" not in names + assert "future_task" in names + finally: + if result.reset_coro: + result.reset_coro.close() + + @pytest.mark.asyncio + async def test_interactive_build_does_not_force_registered_plugin_tools( + self, mock_event, mock_context, mock_provider + ): + """Interactive builds keep their persona-filtered tool set.""" + module = ama + plugin_tool = FunctionTool( + name="search_memes", + description="Search memes", + parameters={"type": "object", "properties": {}}, + ) + tool_mgr = MagicMock() + tool_mgr.get_full_tool_set.return_value = ToolSet([plugin_tool]) + tool_mgr.get_builtin_tool.side_effect = lambda cls, **kwargs: cls(**kwargs) + mock_context.get_llm_tool_manager.return_value = tool_mgr + mock_context.persona_manager.resolve_selected_persona = AsyncMock( + return_value=( + "locked", + {"name": "locked", "prompt": "No tools.", "tools": []}, + None, + False, + ) + ) + mock_event.platform_meta.support_proactive_message = False + mock_context.get_config.return_value = {"provider_settings": {}} + + req = ProviderRequest(prompt="hello") + req.conversation = MagicMock(persona_id="locked", history="[]") + config = module.MainAgentBuildConfig( + tool_call_timeout=60, + provider_settings={"web_search": False}, + computer_use_runtime="none", + add_cron_tools=True, + ) + + with ( + patch("astrbot.core.astr_main_agent.AgentRunner") as mock_runner_cls, + patch("astrbot.core.astr_main_agent.AstrAgentContext"), + ): + mock_runner = MagicMock() + mock_runner.reset = AsyncMock() + mock_runner_cls.return_value = mock_runner + result = await module.build_main_agent( + event=mock_event, + plugin_context=mock_context, + config=config, + provider=mock_provider, + req=req, + apply_reset=False, + ) + + assert result is not None + try: + names = result.provider_request.func_tool.names() + assert "search_memes" not in names + assert "future_task" in names + finally: + if result.reset_coro: + result.reset_coro.close() + @pytest.mark.asyncio async def test_build_main_agent_passes_max_context_length_to_runner( self, mock_event, mock_context, mock_provider From 99c0a9709ef8c40ae7750a474d8deb1c06a067bb Mon Sep 17 00:00:00 2001 From: ethereal49 Date: Sat, 31 Oct 2026 04:08:42 -1000 Subject: [PATCH 2/2] fix(agent): keep subagent tool dedup for proactive builds Move the proactive tool merge before subagent deduplication so tools assigned to subagents are not added back to the main agent when remove_main_duplicate_tools is enabled. --- astrbot/core/astr_main_agent.py | 7 ++- tests/unit/test_astr_main_agent.py | 89 ++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+), 3 deletions(-) diff --git a/astrbot/core/astr_main_agent.py b/astrbot/core/astr_main_agent.py index f55e8ad86c9..240c76ff9f0 100644 --- a/astrbot/core/astr_main_agent.py +++ b/astrbot/core/astr_main_agent.py @@ -1889,6 +1889,10 @@ async def build_main_agent( ) if captioned_ref: captioned_refs.add(captioned_ref) + + if config.proactive: + _apply_proactive_registered_tools(req, plugin_context) + captioned_refs.update( await _decorate_llm_request( event, @@ -1905,9 +1909,6 @@ async def build_main_agent( if not req.session_id: req.session_id = event.unified_msg_origin - if config.proactive: - _apply_proactive_registered_tools(req, plugin_context) - _plugin_tool_fix(event, req) await _apply_web_search_tools(event, req, plugin_context) diff --git a/tests/unit/test_astr_main_agent.py b/tests/unit/test_astr_main_agent.py index 1bdccb04df2..e6359eaab5b 100644 --- a/tests/unit/test_astr_main_agent.py +++ b/tests/unit/test_astr_main_agent.py @@ -2104,6 +2104,95 @@ async def test_interactive_build_does_not_force_registered_plugin_tools( if result.reset_coro: result.reset_coro.close() + @pytest.mark.asyncio + @pytest.mark.parametrize( + ("remove_duplicate", "proactive", "assigned_tool_present"), + [ + (True, True, False), + (False, True, True), + (True, False, False), + ], + ) + async def test_proactive_merge_respects_subagent_tool_assignment( + self, + mock_event, + mock_context, + mock_provider, + remove_duplicate, + proactive, + assigned_tool_present, + ): + """Proactive tool merge must not undo subagent duplicate removal.""" + module = ama + plugin_tool = FunctionTool( + name="search_memes", + description="Search memes", + parameters={"type": "object", "properties": {}}, + ) + handoff_tool = FunctionTool( + name="transfer_to_meme_agent", + description="Delegate to the meme agent", + parameters={"type": "object", "properties": {}}, + ) + tool_mgr = MagicMock() + tool_mgr.get_full_tool_set.return_value = ToolSet([plugin_tool]) + tool_mgr.get_builtin_tool.side_effect = lambda cls, **kwargs: cls(**kwargs) + mock_context.get_llm_tool_manager.return_value = tool_mgr + mock_context.persona_manager.resolve_selected_persona = AsyncMock( + return_value=( + "locked", + {"name": "locked", "prompt": "No tools.", "tools": []}, + None, + False, + ) + ) + mock_context.subagent_orchestrator = SimpleNamespace(handoffs=[handoff_tool]) + mock_context.get_config.return_value = { + "provider_settings": {}, + "subagent_orchestrator": { + "main_enable": True, + "remove_main_duplicate_tools": remove_duplicate, + "agents": [{"tools": ["search_memes"]}], + }, + } + mock_event.platform_meta.support_proactive_message = False + + req = ProviderRequest(prompt="run scheduled task") + req.conversation = MagicMock(persona_id="locked", history="[]") + config = module.MainAgentBuildConfig( + tool_call_timeout=60, + provider_settings={"web_search": False}, + computer_use_runtime="none", + add_cron_tools=True, + proactive=proactive, + ) + + with ( + patch("astrbot.core.astr_main_agent.AgentRunner") as mock_runner_cls, + patch("astrbot.core.astr_main_agent.AstrAgentContext"), + ): + mock_runner = MagicMock() + mock_runner.reset = AsyncMock() + mock_runner_cls.return_value = mock_runner + result = await module.build_main_agent( + event=mock_event, + plugin_context=mock_context, + config=config, + provider=mock_provider, + req=req, + apply_reset=False, + ) + + assert result is not None + try: + names = result.provider_request.func_tool.names() + assert ("search_memes" in names) is assigned_tool_present + assert "transfer_to_meme_agent" in names + assert "future_task" in names + finally: + if result.reset_coro: + result.reset_coro.close() + @pytest.mark.asyncio async def test_build_main_agent_passes_max_context_length_to_runner( self, mock_event, mock_context, mock_provider