goal_tool.py 17 KB

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