goal.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. """
  2. Goal 数据模型
  3. Goal: 执行计划中的目标节点
  4. GoalTree: 目标树,管理整个执行计划
  5. GoalStats: 目标统计信息
  6. """
  7. from dataclasses import dataclass, field
  8. from datetime import datetime
  9. from typing import Dict, Any, List, Optional, Literal
  10. import json
  11. # Goal 状态
  12. GoalStatus = Literal["pending", "in_progress", "completed", "abandoned"]
  13. # Goal 类型
  14. GoalType = Literal["normal", "agent_call"]
  15. @dataclass
  16. class GoalStats:
  17. """目标统计信息"""
  18. message_count: int = 0 # 消息数量
  19. total_tokens: int = 0 # Token 总数
  20. total_cost: float = 0.0 # 总成本
  21. preview: Optional[str] = None # 工具调用摘要,如 "read_file → edit_file → bash"
  22. def to_dict(self) -> Dict[str, Any]:
  23. return {
  24. "message_count": self.message_count,
  25. "total_tokens": self.total_tokens,
  26. "total_cost": self.total_cost,
  27. "preview": self.preview,
  28. }
  29. @classmethod
  30. def from_dict(cls, data: Dict[str, Any]) -> "GoalStats":
  31. return cls(
  32. message_count=data.get("message_count", 0),
  33. total_tokens=data.get("total_tokens", 0),
  34. total_cost=data.get("total_cost", 0.0),
  35. preview=data.get("preview"),
  36. )
  37. @dataclass
  38. class Goal:
  39. """
  40. 执行目标
  41. 使用扁平列表 + parent_id 构建层级结构。
  42. agent_call 类型用于标记启动了 Sub-Trace 的 Goal。
  43. """
  44. id: str # 内部唯一 ID,纯自增("1", "2", "3"...)
  45. description: str # 目标描述
  46. reason: str = "" # 创建理由(为什么做)
  47. parent_id: Optional[str] = None # 父 Goal ID(层级关系)
  48. type: GoalType = "normal" # Goal 类型
  49. status: GoalStatus = "pending" # 状态
  50. summary: Optional[str] = None # 完成/放弃时的总结
  51. # agent_call 特有
  52. sub_trace_ids: Optional[List[str]] = None # 启动的 Sub-Trace IDs
  53. agent_call_mode: Optional[str] = None # "explore" | "delegate" | "sequential" | "evaluation"
  54. sub_trace_metadata: Optional[Dict[str, Dict[str, Any]]] = None # Sub-Trace 元数据
  55. # evaluation 特有字段
  56. target_goal_id: Optional[str] = None # 评估哪个 goal
  57. evaluation_input: Optional[Dict] = None # 主 Agent 提供的结构化输入
  58. evaluation_result: Optional[Dict] = None # 评估 Agent 返回的结构化结果
  59. # 统计(后端维护,用于可视化边的数据)
  60. self_stats: GoalStats = field(default_factory=GoalStats) # 自身统计(仅直接关联的 messages)
  61. cumulative_stats: GoalStats = field(default_factory=GoalStats) # 累计统计(自身 + 所有后代)
  62. created_at: datetime = field(default_factory=datetime.now)
  63. completed_at: Optional[datetime] = None # 完成时间
  64. def to_dict(self) -> Dict[str, Any]:
  65. """转换为字典"""
  66. return {
  67. "id": self.id,
  68. "description": self.description,
  69. "reason": self.reason,
  70. "parent_id": self.parent_id,
  71. "type": self.type,
  72. "status": self.status,
  73. "summary": self.summary,
  74. "sub_trace_ids": self.sub_trace_ids,
  75. "agent_call_mode": self.agent_call_mode,
  76. "sub_trace_metadata": self.sub_trace_metadata,
  77. "target_goal_id": self.target_goal_id,
  78. "evaluation_input": self.evaluation_input,
  79. "evaluation_result": self.evaluation_result,
  80. "self_stats": self.self_stats.to_dict(),
  81. "cumulative_stats": self.cumulative_stats.to_dict(),
  82. "created_at": self.created_at.isoformat() if self.created_at else None,
  83. "completed_at": self.completed_at.isoformat() if self.completed_at else None,
  84. }
  85. @classmethod
  86. def from_dict(cls, data: Dict[str, Any]) -> "Goal":
  87. """从字典创建"""
  88. created_at = data.get("created_at")
  89. if isinstance(created_at, str):
  90. created_at = datetime.fromisoformat(created_at)
  91. completed_at = data.get("completed_at")
  92. if isinstance(completed_at, str):
  93. completed_at = datetime.fromisoformat(completed_at)
  94. self_stats = data.get("self_stats", {})
  95. if isinstance(self_stats, dict):
  96. self_stats = GoalStats.from_dict(self_stats)
  97. cumulative_stats = data.get("cumulative_stats", {})
  98. if isinstance(cumulative_stats, dict):
  99. cumulative_stats = GoalStats.from_dict(cumulative_stats)
  100. return cls(
  101. id=data["id"],
  102. description=data["description"],
  103. reason=data.get("reason", ""),
  104. parent_id=data.get("parent_id"),
  105. type=data.get("type", "normal"),
  106. status=data.get("status", "pending"),
  107. summary=data.get("summary"),
  108. sub_trace_ids=data.get("sub_trace_ids"),
  109. agent_call_mode=data.get("agent_call_mode"),
  110. sub_trace_metadata=data.get("sub_trace_metadata"),
  111. target_goal_id=data.get("target_goal_id"),
  112. evaluation_input=data.get("evaluation_input"),
  113. evaluation_result=data.get("evaluation_result"),
  114. self_stats=self_stats,
  115. cumulative_stats=cumulative_stats,
  116. created_at=created_at or datetime.now(),
  117. completed_at=completed_at,
  118. )
  119. @dataclass
  120. class GoalTree:
  121. """
  122. 目标树 - 管理整个执行计划
  123. 使用扁平列表 + parent_id 构建层级结构
  124. """
  125. mission: str # 总任务描述
  126. goals: List[Goal] = field(default_factory=list) # 扁平列表(通过 parent_id 构建层级)
  127. current_id: Optional[str] = None # 当前焦点 goal ID
  128. _next_id: int = 1 # 内部 ID 计数器(私有字段)
  129. created_at: datetime = field(default_factory=datetime.now)
  130. def find(self, goal_id: str) -> Optional[Goal]:
  131. """按 ID 查找 Goal"""
  132. for goal in self.goals:
  133. if goal.id == goal_id:
  134. return goal
  135. return None
  136. def find_by_display_id(self, display_id: str) -> Optional[Goal]:
  137. """按显示 ID 查找 Goal(如 "1", "2.1", "2.2")"""
  138. for goal in self.goals:
  139. if self._generate_display_id(goal) == display_id:
  140. return goal
  141. return None
  142. def find_parent(self, goal_id: str) -> Optional[Goal]:
  143. """查找指定 Goal 的父节点"""
  144. goal = self.find(goal_id)
  145. if not goal or not goal.parent_id:
  146. return None
  147. return self.find(goal.parent_id)
  148. def get_children(self, parent_id: Optional[str]) -> List[Goal]:
  149. """获取指定父节点的所有子节点"""
  150. return [g for g in self.goals if g.parent_id == parent_id]
  151. def get_current(self) -> Optional[Goal]:
  152. """获取当前焦点 Goal"""
  153. if self.current_id:
  154. return self.find(self.current_id)
  155. return None
  156. def _generate_id(self) -> str:
  157. """生成新的 Goal ID(纯自增)"""
  158. new_id = str(self._next_id)
  159. self._next_id += 1
  160. return new_id
  161. def _generate_display_id(self, goal: Goal) -> str:
  162. """生成显示序号(1, 2, 2.1, 2.2...)"""
  163. if not goal.parent_id:
  164. # 顶层目标:找到在同级中的序号
  165. siblings = [g for g in self.goals if g.parent_id is None and g.status != "abandoned"]
  166. try:
  167. index = [g.id for g in siblings].index(goal.id) + 1
  168. return str(index)
  169. except ValueError:
  170. return "?"
  171. else:
  172. # 子目标:父序号 + "." + 在同级中的序号
  173. parent = self.find(goal.parent_id)
  174. if not parent:
  175. return "?"
  176. parent_display = self._generate_display_id(parent)
  177. siblings = [g for g in self.goals if g.parent_id == goal.parent_id and g.status != "abandoned"]
  178. try:
  179. index = [g.id for g in siblings].index(goal.id) + 1
  180. return f"{parent_display}.{index}"
  181. except ValueError:
  182. return f"{parent_display}.?"
  183. def add_goals(
  184. self,
  185. descriptions: List[str],
  186. reasons: Optional[List[str]] = None,
  187. parent_id: Optional[str] = None
  188. ) -> List[Goal]:
  189. """
  190. 添加目标
  191. 如果 parent_id 为 None,添加到顶层
  192. 如果 parent_id 有值,添加为该 goal 的子目标
  193. """
  194. if parent_id:
  195. parent = self.find(parent_id)
  196. if not parent:
  197. raise ValueError(f"Parent goal not found: {parent_id}")
  198. # 创建新目标
  199. new_goals = []
  200. for i, desc in enumerate(descriptions):
  201. goal_id = self._generate_id()
  202. reason = reasons[i] if reasons and i < len(reasons) else ""
  203. goal = Goal(
  204. id=goal_id,
  205. description=desc.strip(),
  206. reason=reason,
  207. parent_id=parent_id
  208. )
  209. self.goals.append(goal)
  210. new_goals.append(goal)
  211. return new_goals
  212. def add_goals_after(
  213. self,
  214. target_id: str,
  215. descriptions: List[str],
  216. reasons: Optional[List[str]] = None
  217. ) -> List[Goal]:
  218. """
  219. 在指定 Goal 后面添加兄弟节点
  220. 新创建的 goals 与 target 有相同的 parent_id,
  221. 并插入到 goals 列表中 target 的后面。
  222. """
  223. target = self.find(target_id)
  224. if not target:
  225. raise ValueError(f"Target goal not found: {target_id}")
  226. # 创建新 goals(parent_id 与 target 相同)
  227. new_goals = []
  228. for i, desc in enumerate(descriptions):
  229. goal_id = self._generate_id()
  230. reason = reasons[i] if reasons and i < len(reasons) else ""
  231. goal = Goal(
  232. id=goal_id,
  233. description=desc.strip(),
  234. reason=reason,
  235. parent_id=target.parent_id # 同层级
  236. )
  237. new_goals.append(goal)
  238. # 插入到 target 后面(调整 goals 列表顺序)
  239. target_index = self.goals.index(target)
  240. for i, goal in enumerate(new_goals):
  241. self.goals.insert(target_index + 1 + i, goal)
  242. return new_goals
  243. def focus(self, goal_id: str) -> Goal:
  244. """切换焦点到指定 Goal,并将其状态设为 in_progress"""
  245. goal = self.find(goal_id)
  246. if not goal:
  247. raise ValueError(f"Goal not found: {goal_id}")
  248. # 更新状态
  249. if goal.status == "pending":
  250. goal.status = "in_progress"
  251. self.current_id = goal_id
  252. return goal
  253. def complete(self, goal_id: str, summary: str, clear_focus: bool = True) -> Goal:
  254. """
  255. 完成指定 Goal
  256. Args:
  257. goal_id: 要完成的目标 ID
  258. summary: 完成总结
  259. clear_focus: 如果完成的是当前焦点,是否清除焦点(默认 True)
  260. """
  261. goal = self.find(goal_id)
  262. if not goal:
  263. raise ValueError(f"Goal not found: {goal_id}")
  264. goal.status = "completed"
  265. goal.summary = summary
  266. # 如果完成的是当前焦点,根据参数决定是否清除焦点
  267. if clear_focus and self.current_id == goal_id:
  268. self.current_id = None
  269. # 检查是否所有兄弟都完成了,如果是则自动完成父节点
  270. if goal.parent_id:
  271. siblings = self.get_children(goal.parent_id)
  272. all_completed = all(g.status == "completed" for g in siblings)
  273. if all_completed:
  274. parent = self.find(goal.parent_id)
  275. if parent and parent.status != "completed":
  276. # 自动级联完成父节点
  277. parent.status = "completed"
  278. if not parent.summary:
  279. parent.summary = "所有子目标已完成"
  280. return goal
  281. def abandon(self, goal_id: str, reason: str) -> Goal:
  282. """放弃指定 Goal"""
  283. goal = self.find(goal_id)
  284. if not goal:
  285. raise ValueError(f"Goal not found: {goal_id}")
  286. goal.status = "abandoned"
  287. goal.summary = reason
  288. # 如果放弃的是当前焦点,清除焦点
  289. if self.current_id == goal_id:
  290. self.current_id = None
  291. return goal
  292. def to_prompt(self, include_abandoned: bool = False) -> str:
  293. """
  294. 格式化为 Prompt 注入文本
  295. 展示策略:
  296. - 过滤掉 abandoned 目标(除非明确要求)
  297. - 完整展示所有顶层目标
  298. - 完整展示当前 focus 目标的父链及其所有子孙
  299. - 其他分支的子目标折叠显示(只显示数量和状态)
  300. """
  301. lines = []
  302. lines.append(f"**Mission**: {self.mission}")
  303. if self.current_id:
  304. current = self.find(self.current_id)
  305. if current:
  306. display_id = self._generate_display_id(current)
  307. lines.append(f"**Current**: {display_id} {current.description}")
  308. lines.append("")
  309. lines.append("**Progress**:")
  310. # 获取当前焦点的祖先链(从根到当前节点的路径)
  311. current_path = set()
  312. if self.current_id:
  313. goal = self.find(self.current_id)
  314. while goal:
  315. current_path.add(goal.id)
  316. if goal.parent_id:
  317. goal = self.find(goal.parent_id)
  318. else:
  319. break
  320. def format_goal(goal: Goal, indent: int = 0) -> List[str]:
  321. # 跳过废弃的目标(除非明确要求包含)
  322. if goal.status == "abandoned" and not include_abandoned:
  323. return []
  324. prefix = " " * indent
  325. # 状态图标
  326. if goal.status == "completed":
  327. icon = "[✓]"
  328. elif goal.status == "in_progress":
  329. icon = "[→]"
  330. elif goal.status == "abandoned":
  331. icon = "[✗]"
  332. else:
  333. icon = "[ ]"
  334. # 生成显示序号
  335. display_id = self._generate_display_id(goal)
  336. # 当前焦点标记
  337. current_mark = " ← current" if goal.id == self.current_id else ""
  338. result = [f"{prefix}{icon} {display_id}. {goal.description}{current_mark}"]
  339. # 显示 summary(如果有)
  340. if goal.summary:
  341. result.append(f"{prefix} → {goal.summary}")
  342. # 递归处理子目标
  343. children = self.get_children(goal.id)
  344. # 判断是否需要折叠
  345. # 如果当前 goal 或其子孙在焦点路径上,完整展示
  346. should_expand = goal.id in current_path or any(
  347. child.id in current_path for child in self._get_all_descendants(goal.id)
  348. )
  349. if should_expand or not children:
  350. # 完整展示子目标
  351. for child in children:
  352. result.extend(format_goal(child, indent + 1))
  353. else:
  354. # 折叠显示:只显示子目标的统计
  355. non_abandoned = [c for c in children if c.status != "abandoned"]
  356. if non_abandoned:
  357. completed = sum(1 for c in non_abandoned if c.status == "completed")
  358. in_progress = sum(1 for c in non_abandoned if c.status == "in_progress")
  359. pending = sum(1 for c in non_abandoned if c.status == "pending")
  360. status_parts = []
  361. if completed > 0:
  362. status_parts.append(f"{completed} completed")
  363. if in_progress > 0:
  364. status_parts.append(f"{in_progress} in progress")
  365. if pending > 0:
  366. status_parts.append(f"{pending} pending")
  367. status_str = ", ".join(status_parts)
  368. result.append(f"{prefix} ({len(non_abandoned)} subtasks: {status_str})")
  369. return result
  370. # 处理所有顶层目标
  371. top_goals = self.get_children(None)
  372. for goal in top_goals:
  373. lines.extend(format_goal(goal))
  374. return "\n".join(lines)
  375. def _get_all_descendants(self, goal_id: str) -> List[Goal]:
  376. """获取指定 Goal 的所有子孙节点"""
  377. descendants = []
  378. children = self.get_children(goal_id)
  379. for child in children:
  380. descendants.append(child)
  381. descendants.extend(self._get_all_descendants(child.id))
  382. return descendants
  383. def to_dict(self) -> Dict[str, Any]:
  384. """转换为字典"""
  385. return {
  386. "mission": self.mission,
  387. "goals": [g.to_dict() for g in self.goals],
  388. "current_id": self.current_id,
  389. "_next_id": self._next_id,
  390. "created_at": self.created_at.isoformat() if self.created_at else None,
  391. }
  392. @classmethod
  393. def from_dict(cls, data: Dict[str, Any]) -> "GoalTree":
  394. """从字典创建"""
  395. goals = [Goal.from_dict(g) for g in data.get("goals", [])]
  396. created_at = data.get("created_at")
  397. if isinstance(created_at, str):
  398. created_at = datetime.fromisoformat(created_at)
  399. return cls(
  400. mission=data["mission"],
  401. goals=goals,
  402. current_id=data.get("current_id"),
  403. _next_id=data.get("_next_id", 1),
  404. created_at=created_at or datetime.now(),
  405. )
  406. def save(self, path: str) -> None:
  407. """保存到 JSON 文件"""
  408. with open(path, "w", encoding="utf-8") as f:
  409. json.dump(self.to_dict(), f, ensure_ascii=False, indent=2)
  410. @classmethod
  411. def load(cls, path: str) -> "GoalTree":
  412. """从 JSON 文件加载"""
  413. with open(path, "r", encoding="utf-8") as f:
  414. data = json.load(f)
  415. return cls.from_dict(data)