Commit 6c03d232 by sunqi02

feat: read_pending_messages 工具

- 读取并清空 intent_session,返回在途期间的新消息
- 注册到 basic 组,所有 Agent 可见
- 空时返回'无新消息',防重复注入

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent 49c6054b
......@@ -376,6 +376,14 @@ class AgentHub:
},
)
# Register read_pending_messages tool for reading messages during busy periods
read_pm = self._make_read_pending_messages_tool()
self.toolkit.register_tool_function(
read_pm,
func_name="read_pending_messages",
group_name="basic",
)
# Register sandboxed read_file tool for reading project files
read_file = self._make_read_file_tool()
self.toolkit.register_tool_function(
......@@ -993,6 +1001,60 @@ class AgentHub:
return call_sub_agent
def _make_read_pending_messages_tool(self):
"""Create read_pending_messages tool function."""
from app.infrastructure.session_store import SessionStore
async def read_pending_messages() -> ToolResponse:
"""读取在途任务期间到达的新消息。
在 Agent 运行期间,用户可能发送了后续消息。调用此工具获取这些消息,
避免追问用户已发送的信息。
Returns:
在途期间到达的消息列表,无新消息时返回提示
"""
ctx = _route_context_var.get(None)
if not ctx:
return ToolResponse(
content=[TextBlock(type="text", text="无新消息")]
)
session_id = ctx.get("session_id")
if not session_id:
return ToolResponse(
content=[TextBlock(type="text", text="无新消息")]
)
store = SessionStore()
data = store.get(session_id)
if not data:
return ToolResponse(
content=[TextBlock(type="text", text="无新消息")]
)
intent_msgs = data.get("intent_session", [])
if not intent_msgs:
return ToolResponse(
content=[TextBlock(type="text", text="无新消息")]
)
# 清空 intent_session
data["intent_session"] = []
store.set(session_id, data)
# 构造返回文本
lines = [f"检测到期间有 {len(intent_msgs)} 条新消息:"]
for i, m in enumerate(intent_msgs, 1):
content = m.get("content", "")
lines.append(f"[{i}] 用户: {content}")
return ToolResponse(
content=[TextBlock(type="text", text="\n".join(lines))]
)
return read_pending_messages
async def _summarize_thinking(self, thinking_text: str) -> str:
"""将思考过程总结为简短的状态更新,不暴露内部推理细节。"""
try:
......
......@@ -12,6 +12,14 @@ from app.agent_core.agent_hub import AgentHub, AgentHubError, _route_context_var
from app.agent_core.memory import SessionMemory
def _extract_text(resp):
"""Extract text from ToolResponse (content blocks may be dicts or TextBlock)."""
block = resp.content[0]
if isinstance(block, dict):
return block["text"]
return block.text
async def _drain_background_tasks():
"""等待所有 fire-and-forget 后台任务完成(测试用)。"""
tasks = list(_background_tasks)
......@@ -1255,3 +1263,87 @@ class TestConcurrentSessions:
f"两个子Agent 回复发到同一房间!存在串群 Bug: {sub_agent_rooms}\n"
f"全部 post_replies: {post_replies}"
)
class TestReadPendingMessagesTool:
"""read_pending_messages 工具行为测试"""
@pytest.mark.asyncio
async def test_read_returns_messages(self):
"""工具能读取 intent_session 中的消息"""
hub = _make_test_hub()
session_id = "sess_read_test"
hub.session_service.get_or_create_session(
session_id=session_id, room_id="r1"
)
data = hub.session_service.store.get(session_id)
data["intent_session"] = [
{"role": "user", "content": "消息1"},
{"role": "user", "content": "消息2"},
]
hub.session_service.store.set(session_id, data)
token = _route_context_var.set({"session_id": session_id, "call_count": 0})
try:
tool_fn = hub._make_read_pending_messages_tool()
result = await tool_fn()
assert result is not None
text = _extract_text(result)
assert "2 条新消息" in text
assert "消息1" in text
assert "消息2" in text
finally:
_route_context_var.reset(token)
@pytest.mark.asyncio
async def test_read_clears_intent_session(self):
"""工具读取后清空 intent_session"""
hub = _make_test_hub()
session_id = "sess_read_clear"
hub.session_service.get_or_create_session(
session_id=session_id, room_id="r1"
)
data = hub.session_service.store.get(session_id)
data["intent_session"] = [
{"role": "user", "content": "消息"},
]
hub.session_service.store.set(session_id, data)
token = _route_context_var.set({"session_id": session_id, "call_count": 0})
try:
tool_fn = hub._make_read_pending_messages_tool()
await tool_fn()
after = hub.session_service.store.get(session_id)
assert after["intent_session"] == []
finally:
_route_context_var.reset(token)
@pytest.mark.asyncio
async def test_read_when_empty_returns_no_new_messages(self):
"""intent_session 为空时返回'无新消息'"""
hub = _make_test_hub()
session_id = "sess_read_empty"
hub.session_service.get_or_create_session(
session_id=session_id, room_id="r1"
)
token = _route_context_var.set({"session_id": session_id, "call_count": 0})
try:
tool_fn = hub._make_read_pending_messages_tool()
result = await tool_fn()
text = _extract_text(result)
assert "无新消息" in text
finally:
_route_context_var.reset(token)
@pytest.mark.asyncio
async def test_read_when_no_context_returns_no_new_messages(self):
"""无路由上下文时返回'无新消息'"""
hub = _make_test_hub()
tool_fn = hub._make_read_pending_messages_tool()
result = await tool_fn()
text = _extract_text(result)
assert "无新消息" in text
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!