JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(btw): pass tools schema to preserve cache key, discard tool_use
ldstyle84257e5cd2eaf
diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex d8b16881d7..de8c8bd0d0 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -6744,8 +6744,11 @@ class JiuWenSwarmDeepAdapter:if not messages:return {"status": "no_turn"}+ # 透传主 agent tools schema 保 cache key(工具执行由单轮 + tool_use 丢弃禁止)+ tools = await self._get_agent_tools(session_id)+prompt = build_recap_prompt(memory=None, language=self._resolve_prompt_language())- summary_text = await self._call_model_for_recap(messages, prompt)+ summary_text = await self._call_model_for_recap(messages, prompt, tools=tools or None)if not summary_text:return {"status": "failed", "error": "Model returned empty response"}@@ -6854,6 +6857,49 @@ class JiuWenSwarmDeepAdapter:logger.debug("[JiuWenSwarmDeepAdapter] _get_recent_messages disk fallback failed: %s", exc)return []+ async def _get_agent_tools(self, session_id: str) -> list[Any]:+ """取主 agent 当前 tools 列表(List[ToolInfo]),用于 btw/recap 透传给模型。++ 透传 tools schema 是为了与主 agent 保持 cache key 一致(openjiuwen 的+ prompt cache 布局为 tools → system → messages,tools 段缺失会破坏前缀+ 匹配)。工具执行仍被禁用:btw/recap 单轮 + tool_use 检测丢弃。++ 查找顺序与 _get_recent_messages 一致:先当前 adapter 的 react_agent,+ 再 session-scoped child adapter(btw 在 parent 执行时 tools 在 child)。+ 返回空列表表示无工具可用,调用方应按不传 tools 处理(tools or None)。+ """+ async def _from(inst: Any) -> list[Any]:+ ra = getattr(inst, "react_agent", None)+ if ra is None:+ return []+ am = getattr(ra, "ability_manager", None)+ if am is None or not callable(getattr(am, "list_tool_info", None)):+ return []+ try:+ return list(await am.list_tool_info() or [])+ except Exception as exc:+ logger.debug(+ "[JiuWenSwarmDeepAdapter] _get_agent_tools list_tool_info failed: %s",+ exc,+ )+ return []++ # 1) 当前 adapter+ if self._instance is not None:+ tools = await _from(self._instance)+ if tools:+ return tools++ # 2) session-scoped child adapter(btw 等侧查询在 parent 执行时 tools 在 child)+ if not getattr(self, "_is_session_scoped_adapter", False):+ session_adapter = self._get_cached_session_adapter(session_id)+ if session_adapter is not None:+ inst = getattr(session_adapter, "_instance", None)+ if inst is not None:+ return await _from(inst)++ return []+def _get_agent_system_prompt(self) -> str:"""Return the current agent's system prompt, or empty string if unavailable.@@ -6880,12 +6926,14 @@ class JiuWenSwarmDeepAdapter:prompt: str,system_prompt: str = "",enable_prompt_caching: bool = True,+ tools: list[Any] | None = None,) -> str | None:- """调用 model 生成简短回答(单轮、无工具)。+ """调用 model 生成简短回答(单轮、禁工具执行)。- system_prompt 非空时以 SystemMessage 形式前置- prompt 作为最后一条 user message 追加到对话末尾- - 不传 tools(通过 btw prompt 中的 <system-reminder> 告知模型无工具可用)+ - tools 非空时透传给模型以保 cache key(与主 agent 一致),但单轮 ++ tool_use 检测丢弃 = 工具不被执行(对齐 claude-code canUseTool:deny)- 不设置 temperature(继承模型默认值,与主 agent 保持一致以复用 prompt cache)prompt cache 策略:@@ -6944,7 +6992,22 @@ class JiuWenSwarmDeepAdapter:try:# No temperature override — inherit model default to match main agent# API params (thinking config is part of the Anthropic cache key).- result = await self._model.invoke(recap_messages)+ result = await self._model.invoke(recap_messages, tools=tools)+ # Tool-use guard: tools schema is passed only to preserve the cache+ # key (matches the main agent). Single turn + discard any tool_use+ # the model emits → tools are never executed. Aligned with+ # claude-code's canUseTool:{behavior:'deny'} + tool_use fallback.+ tool_calls = getattr(result, "tool_calls", None)+ if tool_calls:+ names = ", ".join(getattr(tc, "name", "tool") for tc in tool_calls)+ logger.info(+ "[btw/recap] model emitted tool_use despite no-tool constraint: %s",+ names,+ )+ return (+ f"(模型尝试调用工具 {names} 而非直接回答。"+ "请重新措辞或在主对话中提问。)"+ )content = getattr(result, "content", None) or str(result)# Log cache metrics for observabilityusage = getattr(result, "usage_metadata", None)@@ -6968,7 +7031,7 @@ class JiuWenSwarmDeepAdapter:- 保持消息原始格式(含 structured content blocks)以实现 byte-identical 前缀- 最后一条 pre-prompt 消息添加 cache_control marker(ephemeral)- btw prompt 不添加 cache_control(skipCacheWrite)- - 直接调用模型(无工具、单轮)+ - 透传主 agent tools schema 保 cache key,但单轮 + tool_use 丢弃 = 禁止执行- 不修改对话历史(read-only)Args:@@ -6991,6 +7054,10 @@ class JiuWenSwarmDeepAdapter:if not messages and not system_prompt:return {"status": "no_context"}+ # 2.5) 取主 agent tools(透传给模型以保 cache key;工具执行由单轮 ++ # tool_use 检测丢弃禁止,对齐 claude-code canUseTool:deny)+ tools = await self._get_agent_tools(session_id)+# 3) 构建 btw prompt(system prompt 通过 SystemMessage 传递,不嵌入文本)prompt = _build_btw_prompt(question=question,@@ -7001,6 +7068,7 @@ class JiuWenSwarmDeepAdapter:# enable_prompt_caching=True 启用 cache_control markeranswer = await self._call_model_for_recap(messages, prompt, system_prompt=system_prompt, enable_prompt_caching=True,+ tools=tools or None,)if not answer:return {"status": "failed", "error": "Model returned empty response"}diff --git a/tests/unit_tests/agentserver/test_btw_command.py b/tests/unit_tests/agentserver/test_btw_command.pyindex 81ea8c9c79..0e564b4729 100644--- a/tests/unit_tests/agentserver/test_btw_command.py+++ b/tests/unit_tests/agentserver/test_btw_command.py@@ -108,6 +108,9 @@ def _make_adapter(**overrides: Any) -> Any:adapter._last_system_prompt = overrides.get("_last_system_prompt", "")adapter._model = overrides.get("_model", None)adapter._resolve_prompt_language = MagicMock(return_value="en")+ # _get_agent_tools touches _session_adapters/_get_cached_session_adapter which+ # the bare test object lacks; default to returning no tools (→ tools=None path).+ adapter._get_agent_tools = AsyncMock(return_value=[])return adapter@@ -394,6 +397,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -419,6 +423,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -444,6 +449,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -464,6 +470,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -482,6 +489,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -500,6 +508,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -527,6 +536,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -554,6 +564,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -570,6 +581,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -587,6 +599,8 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_use+ mock_result.tool_calls = None # no tool_use → cache-log path, not fallbackmock_usage = MagicMock()mock_usage.cache_tokens = 42mock_usage.input_tokens = 100@@ -625,6 +639,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -643,6 +658,7 @@ class TestCallModelForRecap:mock_model = AsyncMock()mock_result = MagicMock()mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_usemock_model.invoke.return_value = mock_resultadapter._model = mock_model@@ -659,6 +675,123 @@ class TestCallModelForRecap:# Should contain UserMessage, AssistantMessage, UserMessage for systemassert "user" in roles_found or any("UserMessage" in str(type(m)) for m in invoke_args)+ @pytest.mark.asyncio+ async def test_passes_tools_to_model_invoke(self):+ """tools arg must be forwarded to model.invoke to preserve the cache key."""+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_use+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ sentinel_tools = [{"name": "Read"}]+ await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ tools=sentinel_tools,+ )++ assert mock_model.invoke.call_args[1]["tools"] is sentinel_tools++ @pytest.mark.asyncio+ async def test_default_tools_is_none_keeps_no_tools_path(self):+ """Omitting tools (recap path) must pass tools=None — no tools in request."""+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "answer"+ mock_result.tool_calls = None # MagicMock auto-attr guard: no tool_use+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ )++ assert mock_model.invoke.call_args[1]["tools"] is None++ @pytest.mark.asyncio+ async def test_tool_use_emitted_returns_fallback_not_tool_content(self):+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "" # no text — only tool_use+ tool_call = MagicMock()+ tool_call.name = "Read"+ mock_result.tool_calls = [tool_call]+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ result = await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ tools=[{"name": "Read"}],+ )++ # Fallback surfaced to the user, mentioning the attempted tool name+ assert result is not None+ assert "Read" in result+ assert "工具" in result or "tool" in result.lower()++ @pytest.mark.asyncio+ async def test_tool_use_discarded_even_with_text_content(self):+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "let me read that for you"+ tool_call = MagicMock()+ tool_call.name = "Read"+ mock_result.tool_calls = [tool_call]+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ result = await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ tools=[{"name": "Read"}],+ )++ assert "Read" in result+ # The action-promise text must NOT be returned as the answer+ assert "let me read that for you" not in result++ @pytest.mark.asyncio+ async def test_no_tool_calls_returns_normal_content(self):+ """When tool_calls is absent/None, return content as before."""+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "plain answer"+ mock_result.tool_calls = None+ mock_result.usage_metadata = None # avoid MagicMock auto-attr in cache-log guard+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ result = await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ tools=[{"name": "Read"}],+ )++ assert result == "plain answer"++ @pytest.mark.asyncio+ async def test_empty_tool_calls_list_returns_normal_content(self):+ """An empty tool_calls list must not trigger the fallback path."""+ adapter = _make_adapter()+ mock_model = AsyncMock()+ mock_result = MagicMock()+ mock_result.content = "plain answer"+ mock_result.tool_calls = []+ mock_result.usage_metadata = None # avoid MagicMock auto-attr in cache-log guard+ mock_model.invoke.return_value = mock_result+ adapter._model = mock_model++ result = await adapter._call_model_for_recap(+ [_make_msg(role="user", content="hello")], "prompt",+ tools=[{"name": "Read"}],+ )++ assert result == "plain answer"+# =============================================================================# Section E: generate_btw_answer flow@@ -705,7 +838,7 @@ class TestGenerateBtwAnswer:return [_make_msg(role="user", content="hello")]adapter._get_recent_messages = _get_recent_messages- async def _call_model(messages, prompt, system_prompt="", enable_prompt_caching=True):+ async def _call_model(messages, prompt, system_prompt="", enable_prompt_caching=True, **kwargs):return " \n the answer \n "adapter._call_model_for_recap = _call_model@@ -731,6 +864,46 @@ class TestGenerateBtwAnswer:await adapter.generate_btw_answer("s1", "q?")assert received_kwargs.get("enable_prompt_caching") is True+ @pytest.mark.asyncio+ async def test_fetches_and_forwards_tools(self):+ adapter = _make_adapter(_last_system_prompt="sys")++ def _get_recent_messages(session_id, window=30):+ return [_make_msg()]+ adapter._get_recent_messages = _get_recent_messages++ fetched_tools = [{"name": "Read"}, {"name": "Bash"}]+ adapter._get_agent_tools = AsyncMock(return_value=fetched_tools)++ received_kwargs = {}++ async def _capture_call(*args, **kwargs):+ received_kwargs.update(kwargs)+ return "answer"++ adapter._call_model_for_recap = _capture_call+ await adapter.generate_btw_answer("s1", "q?")+ assert received_kwargs.get("tools") is fetched_tools++ @pytest.mark.asyncio+ async def test_empty_tools_normalized_to_none(self):+ adapter = _make_adapter(_last_system_prompt="sys")++ def _get_recent_messages(session_id, window=30):+ return [_make_msg()]+ adapter._get_recent_messages = _get_recent_messages+ adapter._get_agent_tools = AsyncMock(return_value=[])++ received_kwargs = {}++ async def _capture_call(*args, **kwargs):+ received_kwargs.update(kwargs)+ return "answer"++ adapter._call_model_for_recap = _capture_call+ await adapter.generate_btw_answer("s1", "q?")+ assert received_kwargs.get("tools") is None+@pytest.mark.asyncioasync def test_no_context_with_messages_but_no_system_prompt_still_calls_model(self):"""Even without system_prompt, if messages exist, we should call the model."""