goal_tool.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. """
  2. Goal 工具与目标树持久化入口。
  3. ToolRegistry 向 LLM 暴露 goal(),实际变更由 goal_tool() 执行;
  4. Recursive 还会在此阻止绕过待审核或已批准下一步的 Goal 修改。
  5. """
  6. import logging
  7. from typing import Optional, List, TYPE_CHECKING
  8. from cyber_agent.tools import tool
  9. from cyber_agent.core.agent_mode import policy_from_context
  10. from cyber_agent.core.task_protocol import ensure_task_protocol
  11. if TYPE_CHECKING:
  12. from .goal_models import GoalTree, Goal
  13. from .protocols import TraceStore
  14. logger = logging.getLogger(__name__)
  15. # ===== 知识注入 =====
  16. async def inject_knowledge_for_goal(
  17. goal: "Goal",
  18. tree: "GoalTree",
  19. store: Optional["TraceStore"] = None,
  20. trace_id: Optional[str] = None,
  21. knowledge_config: Optional[dict] = None,
  22. sequence: Optional[int] = None,
  23. ) -> Optional[str]:
  24. """
  25. 为指定 goal 注入相关知识。
  26. Args:
  27. goal: 目标对象
  28. tree: GoalTree
  29. store: TraceStore(用于持久化)
  30. trace_id: Trace ID
  31. knowledge_config: 知识管理配置(KnowledgeConfig 对象)
  32. sequence: 当前消息序列号(用于记录注入时机)
  33. Returns:
  34. 注入结果描述(如 "📚 已注入 3 条相关知识"),无结果返回 None
  35. """
  36. # 检查是否启用知识注入
  37. if knowledge_config and not getattr(knowledge_config, 'enable_injection', True):
  38. logger.debug(f"[Knowledge Inject] 知识注入已禁用,跳过")
  39. return None
  40. try:
  41. import re
  42. from cyber_agent.tools.builtin.subagent import _run_remote_agent
  43. logger.info(f"[Knowledge Inject] goal: {goal.id}, query: {goal.description[:80]}")
  44. # 通过统一 agent 工具调用远端 Librarian,明确走 ask 策略
  45. result = await _run_remote_agent(
  46. agent_type="remote_librarian",
  47. task=goal.description,
  48. messages=None,
  49. continue_from=None, # 知识注入每次独立查询,不续跑
  50. skills=["ask_strategy"],
  51. )
  52. if result.get("status") != "completed":
  53. logger.warning(f"[Knowledge Inject] 远端 Librarian 调用失败: {result.get('error')}")
  54. goal.knowledge = []
  55. return None
  56. response_text = result.get("summary", "")
  57. # 从 summary 中解析 source_ids(Librarian prompt 约定以 knowledge-xxx 形式引用)
  58. source_ids = re.findall(r'\[?(knowledge-[a-zA-Z0-9_-]+)\]?', response_text)
  59. source_ids = list(dict.fromkeys(source_ids)) # 去重保序
  60. if source_ids:
  61. goal.knowledge = [{"id": sid} for sid in source_ids]
  62. knowledge_count = len(source_ids)
  63. logger.info(f"[Knowledge Inject] 注入 {knowledge_count} 条知识到 goal {goal.id}")
  64. if store and trace_id:
  65. await store.update_goal_tree(trace_id, tree)
  66. if sequence is not None:
  67. await store.append_cognition_event(
  68. trace_id=trace_id,
  69. event={
  70. "type": "query",
  71. "sequence": sequence,
  72. "goal_id": goal.id,
  73. "query": goal.description,
  74. "response": response_text[:2000],
  75. "source_ids": source_ids,
  76. "sources": [],
  77. }
  78. )
  79. logger.info(f"[Knowledge Inject] 已记录 query 事件到 cognition_log")
  80. return f"📚 已注入 {knowledge_count} 条相关知识"
  81. else:
  82. goal.knowledge = []
  83. logger.info(f"[Knowledge Inject] 未找到相关知识")
  84. return None
  85. except Exception as e:
  86. logger.warning(f"[Knowledge Inject] 知识注入失败: {e}")
  87. goal.knowledge = []
  88. return None
  89. # ===== LLM 可调用的 goal 工具 =====
  90. @tool(description="管理执行计划,添加/完成/放弃目标,切换焦点", hidden_params=["context"], groups=["core"])
  91. async def goal(
  92. add: Optional[str] = None,
  93. reason: Optional[str] = None,
  94. after: Optional[str] = None,
  95. under: Optional[str] = None,
  96. done: Optional[str] = None,
  97. abandon: Optional[str] = None,
  98. focus: Optional[str] = None,
  99. context: Optional[dict] = None
  100. ) -> str:
  101. """
  102. LLM 可调用的计划管理工具,由 ToolRegistry 注入当前 GoalTree 和 Trace 上下文。
  103. 它只解析公开参数,再转交 goal_tool() 持久化状态并发送前端事件。
  104. Args:
  105. add: 添加目标(逗号分隔多个)
  106. reason: 创建理由(逗号分隔多个,与 add 一一对应)
  107. after: 在指定目标后面添加(同层级)
  108. under: 为指定目标添加子目标
  109. done: 完成当前目标,值为 summary
  110. abandon: 放弃当前目标,值为原因
  111. focus: 切换焦点到指定 ID
  112. context: 工具执行上下文(包含 store、trace_id、goal_tree)
  113. Returns:
  114. str: 更新后的计划状态文本
  115. """
  116. # GoalTree 从 context 获取,每个 agent 实例独立,不再依赖全局变量
  117. tree = context.get("goal_tree") if context else None
  118. if tree is None:
  119. return "错误:GoalTree 未初始化"
  120. # 从 context 获取 store、trace_id 和 knowledge_config
  121. store = context.get("store") if context else None
  122. trace_id = context.get("trace_id") if context else None
  123. knowledge_config = context.get("knowledge_config") if context else None
  124. return await goal_tool(
  125. tree=tree,
  126. store=store,
  127. trace_id=trace_id,
  128. add=add,
  129. reason=reason,
  130. after=after,
  131. under=under,
  132. done=done,
  133. abandon=abandon,
  134. focus=focus,
  135. knowledge_config=knowledge_config,
  136. context=context
  137. )
  138. # ===== 核心逻辑函数 =====
  139. async def goal_tool(
  140. tree: "GoalTree",
  141. store: Optional["TraceStore"] = None,
  142. trace_id: Optional[str] = None,
  143. add: Optional[str] = None,
  144. reason: Optional[str] = None,
  145. after: Optional[str] = None,
  146. under: Optional[str] = None,
  147. done: Optional[str] = None,
  148. abandon: Optional[str] = None,
  149. focus: Optional[str] = None,
  150. knowledge_config: Optional[object] = None,
  151. context: Optional[dict] = None,
  152. ) -> str:
  153. """
  154. Goal 工具的共用实现,更新 GoalTree、TraceStore 和实时事件。
  155. Recursive 会先读持久化协议状态,关闭自动父级完成与兄弟切换,把后续决策留给 TaskReview。
  156. Args:
  157. tree: GoalTree 实例
  158. store: TraceStore 实例(用于推送事件)
  159. trace_id: 当前 Trace ID
  160. add: 添加目标(逗号分隔多个)
  161. reason: 创建理由(逗号分隔多个,与 add 一一对应)
  162. after: 在指定目标后面添加(同层级)
  163. under: 为指定目标添加子目标
  164. done: 完成当前目标,值为 summary
  165. abandon: 放弃当前目标,值为原因
  166. focus: 切换焦点到指定 ID
  167. knowledge_config: 知识管理配置(KnowledgeConfig 对象)
  168. Returns:
  169. 更新后的计划状态文本
  170. """
  171. changes = []
  172. recursive_protocol = False
  173. if store and trace_id:
  174. trace = await store.get_trace(trace_id)
  175. if trace:
  176. recursive_protocol = policy_from_context(
  177. trace.context
  178. ).requires_task_protocol
  179. if recursive_protocol:
  180. state = ensure_task_protocol(trace.context)
  181. has_goal_mutation = any(
  182. value is not None
  183. for value in (add, done, abandon, focus)
  184. )
  185. if state["pending_reviews"] and has_goal_mutation:
  186. return (
  187. "错误:当前有子任务报告待审核,只允许调用 "
  188. "review_task_result。"
  189. )
  190. if state["next_actions"] and has_goal_mutation:
  191. return (
  192. "错误:当前有已批准的下一步待执行,只允许调用 "
  193. "agent 执行该 action。"
  194. )
  195. # 1. 处理 done(完成当前目标)
  196. if done is not None:
  197. if not tree.current_id:
  198. return f"错误:没有当前目标可以完成。当前焦点为空,请先使用 focus 参数切换到要完成的目标。\n\n当前计划:\n{tree.to_prompt()}"
  199. # 完成当前目标
  200. # 如果同时指定了 focus,则不清空焦点(后面会切换到新目标)
  201. # 如果只有 done,则清空焦点
  202. clear_focus = (focus is None)
  203. goal = tree.complete(
  204. tree.current_id,
  205. done,
  206. clear_focus=clear_focus,
  207. auto_advance=not recursive_protocol,
  208. cascade_parent=not recursive_protocol,
  209. )
  210. display_id = tree._generate_display_id(goal)
  211. changes.append(f"已完成: {display_id}. {goal.description}")
  212. # 推送事件
  213. if store and trace_id:
  214. await store.update_goal(
  215. trace_id,
  216. goal.id,
  217. cascade_completion=not recursive_protocol,
  218. status="completed",
  219. summary=done,
  220. )
  221. # 检查是否有级联完成的父目标(complete方法已经处理,这里只需要记录)
  222. if goal.parent_id and not recursive_protocol:
  223. parent = tree.find(goal.parent_id)
  224. if parent and parent.status == "completed":
  225. parent_display_id = tree._generate_display_id(parent)
  226. changes.append(f"自动完成: {parent_display_id}. {parent.description}(所有子目标已完成)")
  227. # 2. 处理 focus(切换焦点到新目标)
  228. if focus is not None:
  229. goal = tree.find_by_display_id(focus)
  230. if not goal:
  231. return f"错误:找不到目标 {focus}\n\n当前计划:\n{tree.to_prompt()}"
  232. tree.focus(goal.id)
  233. display_id = tree._generate_display_id(goal)
  234. changes.append(f"切换焦点: {display_id}. {goal.description}")
  235. # 自动注入知识
  236. inject_msg = await inject_knowledge_for_goal(
  237. goal, tree, store, trace_id, knowledge_config, sequence=context.get("sequence")
  238. )
  239. if inject_msg:
  240. changes.append(inject_msg)
  241. # 3. 处理 abandon(放弃当前目标)
  242. if abandon is not None:
  243. if not tree.current_id:
  244. return f"错误:没有当前目标可以放弃。当前焦点为空。\n\n当前计划:\n{tree.to_prompt()}"
  245. goal = tree.abandon(
  246. tree.current_id,
  247. abandon,
  248. auto_advance=not recursive_protocol,
  249. )
  250. display_id = tree._generate_display_id(goal)
  251. changes.append(f"已放弃: {display_id}. {goal.description}")
  252. # 推送事件
  253. if store and trace_id:
  254. await store.update_goal(trace_id, goal.id, status="abandoned", summary=abandon)
  255. # 4. 处理 add
  256. if add is not None:
  257. # 检查 after 和 under 互斥
  258. if after is not None and under is not None:
  259. return "错误:after 和 under 参数不能同时指定"
  260. descriptions = [d.strip() for d in add.split(",") if d.strip()]
  261. if descriptions:
  262. # 解析 reasons(与 descriptions 一一对应)
  263. reasons = None
  264. if reason:
  265. reasons = [r.strip() for r in reason.split(",")]
  266. # 如果 reasons 数量少于 descriptions,补空字符串
  267. while len(reasons) < len(descriptions):
  268. reasons.append("")
  269. # 确定添加位置
  270. if after is not None:
  271. # 在指定 goal 后面添加(同层级)
  272. target_goal = tree.find_by_display_id(after)
  273. if not target_goal:
  274. return f"错误:找不到目标 {after}\n\n当前计划:\n{tree.to_prompt()}"
  275. new_goals = tree.add_goals_after(target_goal.id, descriptions, reasons=reasons)
  276. changes.append(f"在 {tree._generate_display_id(target_goal)} 后面添加 {len(new_goals)} 个同级目标")
  277. elif under is not None:
  278. # 为指定 goal 添加子目标
  279. parent_goal = tree.find_by_display_id(under)
  280. if not parent_goal:
  281. return f"错误:找不到目标 {under}\n\n当前计划:\n{tree.to_prompt()}"
  282. new_goals = tree.add_goals(descriptions, reasons=reasons, parent_id=parent_goal.id)
  283. changes.append(f"在 {tree._generate_display_id(parent_goal)} 下添加 {len(new_goals)} 个子目标")
  284. else:
  285. # 默认行为:添加到当前焦点下(如果有焦点),否则添加到顶层
  286. parent_id = tree.current_id
  287. new_goals = tree.add_goals(descriptions, reasons=reasons, parent_id=parent_id)
  288. if parent_id:
  289. parent_display_id = tree._generate_display_id(tree.find(parent_id))
  290. changes.append(f"在 {parent_display_id} 下添加 {len(new_goals)} 个子目标")
  291. else:
  292. changes.append(f"添加 {len(new_goals)} 个顶层目标")
  293. # 推送事件
  294. if store and trace_id:
  295. for goal in new_goals:
  296. await store.add_goal(trace_id, goal)
  297. # 将完整内存树状态(含 current_id)同步到存储,
  298. # 因为 store.add_goal / update_goal 各自从磁盘加载,不包含 focus 等内存变更
  299. if store and trace_id and changes:
  300. await store.update_goal_tree(trace_id, tree)
  301. # 返回当前状态
  302. result = []
  303. if changes:
  304. result.append("## 更新")
  305. result.extend(f"- {c}" for c in changes)
  306. result.append("")
  307. result.append("## Current Plan")
  308. result.append(tree.to_prompt())
  309. return "\n".join(result)
  310. def create_goal_tool_schema() -> dict:
  311. """创建 goal 工具的 JSON Schema"""
  312. return {
  313. "name": "goal",
  314. "description": """管理执行计划。目标工具是灵活的支持系统,帮助你组织和追踪工作进度。
  315. 使用策略(按需选择):
  316. - 全局规划:先规划所有目标,再逐个执行
  317. - 渐进规划:走一步看一步,每次只创建下一个目标
  318. - 动态调整:行动中随时 abandon 不可行的目标,创建新目标
  319. 参数:
  320. - add: 添加目标(逗号分隔多个)
  321. - reason: 创建理由(逗号分隔,与 add 一一对应)
  322. - after: 在指定目标后面添加同级目标。使用目标 ID。
  323. - under: 为指定目标添加子目标。使用目标 ID。如已有子目标,追加到最后。
  324. - done: 完成当前目标,值为 summary(记录关键结论)
  325. - abandon: 放弃当前目标,值为原因
  326. - focus: 切换焦点到指定目标。使用目标 ID。
  327. 位置控制(优先使用 after):
  328. - 不指定 after/under: 添加到当前 focus 下作为子目标(无 focus 时添加到顶层)
  329. - after="X": 在目标 X 后面添加兄弟节点(同层级)
  330. - under="X": 为目标 X 添加子目标
  331. - after 和 under 不能同时指定
  332. 执行顺序:
  333. - done → focus → abandon → add
  334. - 如果同时指定 done 和 focus,会先完成当前目标,再切换焦点到新目标
  335. 示例:
  336. - goal(add="分析代码, 实现功能, 测试") - 添加顶层目标
  337. - goal(add="设计接口, 实现代码", under="2") - 为目标2添加子目标
  338. - goal(add="编写文档", after="3") - 在目标3后面添加同级任务
  339. - goal(add="集成测试", after="2.2") - 在目标2.2后面添加同级任务
  340. - goal(done="发现用户模型在 models/user.py") - 完成当前目标
  341. - goal(done="已完成调研", focus="2") - 完成当前目标,切换到目标2
  342. - goal(abandon="方案A需要Redis,环境没有") - 放弃当前目标
  343. 注意:
  344. - 目标 ID 的格式为 "1", "2", "2.1", "2.2" 等,在计划视图中可以看到
  345. - reason 应该与 add 的目标数量一致,如果数量不一致,缺少的 reason 将为空
  346. """,
  347. "parameters": {
  348. "type": "object",
  349. "properties": {
  350. "add": {
  351. "type": "string",
  352. "description": "添加目标(逗号分隔多个)"
  353. },
  354. "reason": {
  355. "type": "string",
  356. "description": "创建理由(逗号分隔多个,与 add 一一对应)。说明为什么要做这些目标。"
  357. },
  358. "after": {
  359. "type": "string",
  360. "description": "在指定目标后面添加(同层级)。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  361. },
  362. "under": {
  363. "type": "string",
  364. "description": "为指定目标添加子目标。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  365. },
  366. "done": {
  367. "type": "string",
  368. "description": "完成当前目标,值为 summary"
  369. },
  370. "abandon": {
  371. "type": "string",
  372. "description": "放弃当前目标,值为原因"
  373. },
  374. "focus": {
  375. "type": "string",
  376. "description": "切换焦点到指定目标。使用目标的 ID,如 \"2\" 或 \"2.1\"。"
  377. }
  378. },
  379. "required": []
  380. }
  381. }