Commit 65f3c7d2 by sunqi02 Committed by 胡悦

feat:更新获取新消息的工具并添加程序固定触发的流程

1 parent 63e5ac49
# read_pending_messages 实施计划
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Agent 运行期间到达的消息不丢失,Agent 可主动感知(工具)或系统自动注入(hook)
**Architecture:** 运行时消息暂存 KV `intent_session`,存档时顺带持久化到 DB。主 Agent 持有 `read_pending_messages` 工具(主动拉取 + 清空),同时在 ReActAgent 的 `post_observe` hook 上挂载系统注入(每次 tool_result 后检查 `intent_session` 非空则注入 InMemoryMemory + SessionMemory)。天然防重:工具已清空 `intent_session`,hook 检测到空则跳过。
**Tech Stack:** Python 3.12+ / AgentScope (ReActAgent hooks) / pytest
**Plan location:** `docs/superpowers/sunqi/plans/`
---
### Task 0: `ActiveSessionService` — `intent_session` 持久化 + 冷恢复
**Files:**
- Modify: `app/agent_core/active_session_service.py:108-149`
- Modify: `app/agent_core/active_session_service.py:36-106`
- Test: `tests/test_session_persistence.py`
- [ ] **Step 0.1: `save_to_db()` 补写 `intent_session`**
修改 `save_to_db()` 方法,在写入 `conversation_history` 的同时顺带写入 `intent_session`:
```python
# active_session_service.py, save_to_db() method
# 在 existing.conversation_history = json.dumps(...) 之后添加:
if existing:
existing.room_id = data.get("room_id", "")
existing.channel = data.get("channel", "wechat_group")
existing.conversation_history = json.dumps(
data.get("conversation_history", []), ensure_ascii=False
)
existing.intent_session = json.dumps( # ← 新增
data.get("intent_session", []), # ← 新增
ensure_ascii=False, # ← 新增
) # ← 新增
else:
db_sess = Session(
session_id=session_id,
room_id=data.get("room_id", ""),
channel=data.get("channel", "wechat_group"),
conversation_history=json.dumps(
data.get("conversation_history", []), ensure_ascii=False
),
intent_session=json.dumps( # ← 新增
data.get("intent_session", []), # ← 新增
ensure_ascii=False, # ← 新增
), # ← 新增
)
db.add(db_sess)
```
- [ ] **Step 0.2: `get_or_create_session()` 补读 `intent_session`**
冷恢复时从 DB 恢复 `intent_session` 到 KV:
```python
# active_session_service.py, get_or_create_session(), DB 冷恢复分支
if db_sess:
payload = {
"session_id": db_sess.session_id,
"channel": db_sess.channel,
"room_id": db_sess.room_id,
"conversation_history": json.loads(
db_sess.conversation_history or "[]"
),
"intent_session": json.loads( # ← 新增
db_sess.intent_session or "[]", # ← 新增
), # ← 新增
"context_entities": {},
"created_at": ...,
"updated_at": ...,
}
```
- [ ] **Step 0.3: 编写 `intent_session` 持久化测试**
在 `tests/test_session_persistence.py` 中添加测试类:
```python
class TestIntentSessionPersistence:
"""intent_session 持久化与冷恢复"""
def test_save_to_db_writes_intent_session(self, db_session):
"""save_to_db 时将 intent_session 写入 DB"""
from app.model.session import Session
svc = ActiveSessionService(db_factory=lambda: db_session)
svc.get_or_create_session(session_id="sess_intent", room_id="r1")
data = svc.store.get("sess_intent")
data["intent_session"] = [
{"role": "user", "content": "测试消息1"},
{"role": "user", "content": "测试消息2"},
]
svc.store.set("sess_intent", data)
svc.save_to_db("sess_intent")
db_row = db_session.query(Session).filter(
Session.session_id == "sess_intent"
).first()
assert db_row is not None
restored = json.loads(db_row.intent_session)
assert len(restored) == 2
assert restored[0]["content"] == "测试消息1"
def test_cold_recovery_restores_intent_session(self, db_session):
"""冷恢复时 intent_session 从 DB 回到 KV"""
from app.model.session import Session
# 先写入 DB
db_sess_row = Session(
session_id="sess_cold_intent",
room_id="r1",
channel="wechat_group",
conversation_history="[]",
intent_session=json.dumps([
{"role": "user", "content": "恢复消息"},
], ensure_ascii=False),
)
db_session.add(db_sess_row)
db_session.commit()
# 新的 ActiveSessionService (KV 为空)冷恢复
svc2 = ActiveSessionService(db_factory=lambda: db_session)
svc2.get_or_create_session(session_id="sess_cold_intent", room_id="r1")
data = svc2.store.get("sess_cold_intent")
assert data is not None
assert data["intent_session"] == [
{"role": "user", "content": "恢复消息"},
]
def test_empty_intent_session_in_db(self, db_session):
"""intent_session 为空时冷恢复也不报错"""
from app.model.session import Session
db_sess_row = Session(
session_id="sess_empty_intent",
room_id="r1",
channel="wechat_group",
conversation_history="[]",
intent_session="",
)
db_session.add(db_sess_row)
db_session.commit()
svc = ActiveSessionService(db_factory=lambda: db_session)
svc.get_or_create_session(session_id="sess_empty_intent", room_id="r1")
data = svc.store.get("sess_empty_intent")
assert data["intent_session"] == []
```
- [ ] **Step 0.4: 运行测试确认通过**
Run:
```bash
cd ai-workflow/workspace/agent-admin/backend
PYTHONPATH=. python -m pytest tests/test_session_persistence.py -v --tb=short
```
Expected: 新增的 3 个测试 PASS
- [ ] **Step 0.5: 提交**
```bash
git add tests/test_session_persistence.py app/agent_core/active_session_service.py
git commit -m "feat: intent_session 持久化与冷恢复
- save_to_db() 顺带写入 intent_session 字段
- get_or_create_session() 冷恢复 intent_session
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### Task 1: `read_pending_messages` 工具注册
**Files:**
- Modify: `app/agent_core/agent_hub.py`
- Test: `tests/test_agent_hub.py`
- [ ] **Step 1.1: 实现 `_make_read_pending_messages_tool()` 方法**
在 `_make_call_sub_agent_tool()` 方法后面添加,注意 `read_pending_messages` 读取并清空 `intent_session`,不需要额外 import:
```python
# agent_hub.py, 在 _make_call_sub_agent_tool() 方法之后添加
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
```
- [ ] **Step 1.2: 注册到 toolkit**
在 `AgentHub.__init__()` 中,在 `call_sub_agent` 注册之后注册 `read_pending_messages`(约第 378 行之后):
```python
# agent_hub.py, __init__(), 在 call_sub_agent 注册之后
# Register read_pending_messages tool for the main agent
read_pm = self._make_read_pending_messages_tool()
self.toolkit.register_tool_function(
read_pm,
func_name="read_pending_messages",
group_name="basic",
)
```
注意:这也是 "basic" 组,所以所有 agent(含子 agent)都会看到。但子 agent 不会主动调用,不影响。
- [ ] **Step 1.3: 编写工具测试**
在 `tests/test_agent_hub.py` 中添加测试类:
```python
class TestReadPendingMessagesTool:
"""read_pending_messages 工具行为测试"""
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"
)
# 在 KV 中预置 intent_session 消息
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 = result.content[0].text
assert "2 条新消息" in text
assert "消息1" in text
assert "消息2" in text
finally:
_route_context_var.reset(token)
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)
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 = result.content[0].text
assert "无新消息" in text
finally:
_route_context_var.reset(token)
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 = result.content[0].text
assert "无新消息" in text
```
- [ ] **Step 1.4: 运行测试确认通过**
Run:
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestReadPendingMessagesTool -v --tb=short -s
```
Expected: 4 tests PASS
- [ ] **Step 1.5: 提交**
```bash
git add app/agent_core/agent_hub.py tests/test_agent_hub.py
git commit -m "feat: read_pending_messages 工具
- 读取并清空 intent_session,返回在途期间的新消息
- 注册到 basic 组,所有 Agent 可见
- 空时返回'无新消息',防重复注入
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
---
### Task 2: `post_observe` hook — 系统注入 `intent_session`
**Files:**
- Modify: `app/agent_core/agent_hub.py`
- Modify: `app/agent_core/memory.py` (确定 SessionMemory.add() 签名)
- Test: `tests/test_agent_hub.py`
- [ ] **Step 2.1: 实现 `_post_observe_intent_hook` 函数**
在 agent_hub.py 中,在 `_im_post_reasoning_hook` 函数之后添加新 hook 函数:
```python
async def _post_observe_intent_hook(
self, kwargs, output,
*, store, session_id, session_memory,
):
"""post_observe hook: 检查 intent_session 是否有新消息,有则注入到 Agent memory。
每次 tool 执行完毕后(_observe → post_observe),检查期间是否有新消息到达:
- 有 → 读取并清空 intent_session,注入 InMemoryMemory(LLM 感知)+ SessionMemory(持久化)
- 无 → 跳过,不影响流程
注入后不触发新工具调用:消息作为 system 上下文注入,LLM 自然看到,不开启新 ReAct 循环。
"""
data = store.get(session_id)
if not data:
return None
intent_msgs = data.get("intent_session", [])
if not intent_msgs:
return None
# 读取并清空
data["intent_session"] = []
store.set(session_id, data)
# 构造注入文本
text_lines = [f"[系统检测到 {len(intent_msgs)} 条新消息]"]
for m in intent_msgs:
text_lines.append(f"用户: {m.get('content', '')}")
content = "\n".join(text_lines)
# 写入 InMemoryMemory(让 LLM 下一轮推理感知)
# agent = self (ReActAgent 实例)
await self.memory.add(
Msg("system", content, "system"),
)
# 写入 SessionMemory → conversation_history(持久化存档)
session_memory.add("system", content, name="intent_hook")
logger.info(
"[intent_hook] session=%s 注入 %d 条新消息到 Agent memory + conversation_history",
session_id, len(intent_msgs),
)
return None
```
- [ ] **Step 2.2: 在 `process_message()` 中注册 hook**
在 `process_message()` 方法中,在 `_register_im_hooks` 调用之后注册 `post_observe` hook:
```python
# agent_hub.py, process_message(), 在 _register_im_hooks(agent, ...) 之后
# Register post_observe hook for intent_session injection
agent.register_instance_hook(
"post_observe", "intent_check",
partial(
_post_observe_intent_hook,
store=self.session_service.store,
session_id=session_id,
session_memory=memory,
),
)
```
- [ ] **Step 2.3: 编写 hook 测试**
在 `tests/test_agent_hub.py` 中添加测试类。使用 mock model 模拟 ReActAgent 执行,验证 hook 正确注入。
```python
class TestPostObserveIntentHook:
"""post_observe intent_session 注入测试"""
async def test_hook_injects_when_intent_nonempty(self):
"""intent_session 非空时 hook 注入到 memory"""
hub = _make_test_hub()
session_id = "sess_hook_inject"
hub.session_service.get_or_create_session(
session_id=session_id, room_id="r1"
)
# 预置 intent_session
data = hub.session_service.store.get(session_id)
data["intent_session"] = [
{"role": "user", "content": "hook测试消息"},
]
hub.session_service.store.set(session_id, data)
# 创建 mock agent
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
memory = InMemoryMemory()
agent = ReActAgent(
name="test_agent",
sys_prompt="test",
model=hub.model,
formatter=hub.formatter,
toolkit=hub.toolkit,
memory=memory,
max_iters=1,
)
# 注册 hook
from app.agent_core.memory import SessionMemory
session_memory = SessionMemory(
session_id=session_id,
store=hub.session_service.store,
)
agent.register_instance_hook(
"post_observe", "intent_check",
partial(
_post_observe_intent_hook,
store=hub.session_service.store,
session_id=session_id,
session_memory=session_memory,
),
)
# 触发 post_observe
await agent.observe({"content": "dummy"})
# 验证注入到了 InMemoryMemory
mem_msgs = await agent.memory.get_memory()
assert any("hook测试消息" in str(m.content) for m in mem_msgs)
# 验证 intent_session 已被清空
after = hub.session_service.store.get(session_id)
assert after["intent_session"] == []
# 验证注入到了 conversation_history
history = after.get("conversation_history", [])
assert any("hook测试消息" in str(h) for h in history)
async def test_hook_skips_when_intent_empty(self):
"""intent_session 为空时 hook 跳过"""
hub = _make_test_hub()
session_id = "sess_hook_skip"
hub.session_service.get_or_create_session(
session_id=session_id, room_id="r1"
)
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
memory = InMemoryMemory()
agent = ReActAgent(
name="test_agent",
sys_prompt="test",
model=hub.model,
formatter=hub.formatter,
toolkit=hub.toolkit,
memory=memory,
max_iters=1,
)
from app.agent_core.memory import SessionMemory
session_memory = SessionMemory(
session_id=session_id,
store=hub.session_service.store,
)
agent.register_instance_hook(
"post_observe", "intent_check",
partial(
_post_observe_intent_hook,
store=hub.session_service.store,
session_id=session_id,
session_memory=session_memory,
),
)
# intent_session 已空,触发 observe
await agent.observe({"content": "dummy"})
mem_msgs = await agent.memory.get_memory()
# 不应有任何注入踪迹
assert all("系统检测到" not in str(m.content) for m in mem_msgs)
async def test_tool_read_then_hook_skips(self):
"""read_pending_messages 工具执行后 intent_session 已空,hook 跳过
模拟完整链路:工具消费 → hook 检查 → 跳过
"""
hub = _make_test_hub()
session_id = "sess_hook_read_chain"
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)
# 模拟工具调用(读取并清空)
from app.infrastructure.session_store import SessionStore
store = SessionStore()
d = store.get(session_id)
d["intent_session"] = []
store.set(session_id, d)
# hook 应跳过
from app.agent_core.memory import SessionMemory
session_memory = SessionMemory(
session_id=session_id,
store=hub.session_service.store,
)
from agentscope.agent import ReActAgent
from agentscope.memory import InMemoryMemory
agent = ReActAgent(
name="test_agent",
sys_prompt="test",
model=hub.model,
formatter=hub.formatter,
toolkit=hub.toolkit,
memory=InMemoryMemory(),
max_iters=1,
)
agent.register_instance_hook(
"post_observe", "intent_check",
partial(
_post_observe_intent_hook,
store=hub.session_service.store,
session_id=session_id,
session_memory=session_memory,
),
)
await agent.observe({"content": "dummy"})
after = hub.session_service.store.get(session_id)
assert after["intent_session"] == []
# 不应有"工具已消费"以外的注入
history = after.get("conversation_history", [])
assert all("系统检测到" not in str(h) for h in history)
```
- [ ] **Step 2.4: 编写集成测试(可选,冒烟验证)**
验证 read_pending_messages 作为工具在 process_message 中正常注册的工作流:
```python
class TestReadPendingMessagesIntegration:
"""read_pending_messages 在 process_message 注册后的集成行为"""
async def test_tool_registered_in_toolkit(self):
"""工具已在 AgentHub toolkit 中注册"""
hub = _make_test_hub()
assert "read_pending_messages" in hub.toolkit.tools
assert hub.toolkit.tools["read_pending_messages"].name == "read_pending_messages"
async def test_tool_in_steward_toolkit(self):
"""主 Agent 的专属 toolkit 包含 read_pending_messages"""
hub = _make_test_hub()
steward_tk = hub.agent_toolkits.get(STEWARD_KEY)
assert steward_tk is not None
assert "read_pending_messages" in steward_tk.tools
```
- [ ] **Step 2.5: 运行测试确认通过**
Run:
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py::TestPostObserveIntentHook tests/test_agent_hub.py::TestReadPendingMessagesIntegration -v --tb=short -s
```
Expected: 5 tests PASS (3 hook + 2 integration)
- [ ] **Step 2.6: 全量冒烟**
Run:
```bash
PYTHONPATH=. python -m pytest tests/test_agent_hub.py tests/test_session_persistence.py -v --tb=short
```
Expected: 全部 PASS(原有测试不变 + 新增测试通过)
- [ ] **Step 2.7: 提交**
```bash
git add app/agent_core/agent_hub.py tests/test_agent_hub.py
git commit -m "feat: post_observe hook 系统注入 intent_session
- 每次 tool_result 后检查 intent_session,非空则注入
- 同时写入 InMemoryMemory(LLM 感知)和 SessionMemory(持久化)
- read_pending_messages 消费后 intent_session 已空,hook 跳过
- 全量冒烟通过
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>"
```
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!