""" 上下文工具 - 获取当前执行上下文 提供 get_current_context 工具,让 Agent 可以主动获取: - 当前计划(GoalTree) - 焦点提醒 - 协作者状态 框架也会在特定轮次自动调用此工具进行周期性上下文刷新。 """ from agent.tools import tool, ToolResult, ToolContext @tool( description="获取当前执行上下文,包括计划状态、焦点提醒、协作者信息等。当你感到困惑或需要回顾当前任务状态时调用。", hidden_params=["context"] ) async def get_current_context( context: ToolContext, ) -> ToolResult: """ 获取当前执行上下文 Returns: ToolResult: 包含 GoalTree、焦点提醒、协作者状态等信息 """ runner = context.get("runner") goal_tree = context.get("goal_tree") trace_id = context.get("trace_id") if not runner: return ToolResult( title="❌ 无法获取上下文", output="Runner 未初始化", error="Runner not available" ) # 获取 trace 对象 trace = None if runner.trace_store and trace_id: trace = await runner.trace_store.get_trace(trace_id) # 构建上下文内容(复用 runner 的 _build_context_injection 方法) if hasattr(runner, '_build_context_injection'): context_content = runner._build_context_injection(trace, goal_tree) else: # Fallback:只返回 GoalTree if goal_tree and goal_tree.goals: context_content = f"## Current Plan\n\n{goal_tree.to_prompt()}" else: context_content = "暂无计划信息" # 注入 trace_id 和 trace_dir,供需要写入 trace 目录的工具(如输出 JSON)使用 trace_dir = "" if runner.trace_store and hasattr(runner.trace_store, "base_path"): trace_dir = str(runner.trace_store.base_path) extra = [ f"## 当前执行信息", f"- **trace_id**: `{trace_id or '(未知)'}`", f"- **trace_dir**: `{trace_dir or '(未知)'}`", f"- **输出路径示例**: `{trace_dir}/{trace_id}/output.json`(若需写入当次 trace 目录)", ] context_content = (context_content or "") + "\n\n" + "\n".join(extra) return ToolResult( title="📋 当前执行上下文", output=context_content, long_term_memory="已刷新执行上下文", )