matrixcode_core/tools/
plan_mode.rs1use anyhow::Result;
2use async_trait::async_trait;
3use serde_json::{Value, json};
4use std::sync::Arc;
5use tokio::sync::Mutex;
6
7use super::{Tool, ToolDefinition};
8use crate::approval::RiskLevel;
9
10#[derive(Debug, Clone, PartialEq)]
12pub enum PlanState {
13 None,
14 Active,
15 Committed,
16}
17
18#[derive(Debug, Clone)]
20pub struct PlanInfo {
21 pub state: PlanState,
22 pub plan_content: String,
23 pub files_to_modify: Vec<String>,
24 pub created_at: Option<std::time::Instant>,
25}
26
27static PLAN_STATE: std::sync::OnceLock<Arc<Mutex<PlanInfo>>> = std::sync::OnceLock::new();
28
29fn get_plan_state() -> Arc<Mutex<PlanInfo>> {
30 PLAN_STATE
31 .get_or_init(|| {
32 Arc::new(Mutex::new(PlanInfo {
33 state: PlanState::None,
34 plan_content: String::new(),
35 files_to_modify: Vec::new(),
36 created_at: None,
37 }))
38 })
39 .clone()
40}
41
42pub struct EnterPlanModeTool;
44
45#[async_trait]
46impl Tool for EnterPlanModeTool {
47 fn definition(&self) -> ToolDefinition {
48 ToolDefinition {
49 name: "enter_plan_mode".to_string(),
50 description: "进入规划模式,在执行前设计实现方案。适用于:(1) 需规划的非 trivial 实现任务;(2) 可受益于架构考量的问题;(3) 可能产生重大影响的变更。返回分步计划并识别关键文件。".to_string(),
51 parameters: json!({
52 "type": "object",
53 "properties": {}
54 }),
55 }
56 }
57
58 fn risk_level(&self) -> RiskLevel {
59 RiskLevel::Safe }
61
62 async fn execute(&self, _params: Value) -> Result<String> {
63 let plan = get_plan_state();
64 let mut state = plan.lock().await;
65
66 if state.state == PlanState::Active {
67 return Ok(
68 "Already in plan mode. Continue planning or use exit_plan_mode to finish."
69 .to_string(),
70 );
71 }
72
73 state.state = PlanState::Active;
74 state.plan_content = String::new();
75 state.files_to_modify = Vec::new();
76 state.created_at = Some(std::time::Instant::now());
77
78 Ok("Entered plan mode. Design your implementation approach:\n\n1. Analyze the task requirements\n2. Identify key files and components\n3. Consider architectural trade-offs\n4. Create step-by-step implementation plan\n5. Use exit_plan_mode to commit and execute\n\nNote: In plan mode, focus on analysis and design. Tool executions will be limited to read-only operations.".to_string())
79 }
80}
81
82pub struct ExitPlanModeTool;
84
85#[async_trait]
86impl Tool for ExitPlanModeTool {
87 fn definition(&self) -> ToolDefinition {
88 ToolDefinition {
89 name: "exit_plan_mode".to_string(),
90 description: "退出规划模式。若计划被批准,代理将执行计划的变更;若被拒绝,计划将被丢弃且不做任何修改。".to_string(),
91 parameters: json!({
92 "type": "object",
93 "properties": {
94 "plan": {
95 "type": "string",
96 "description": "要提交的实现计划(可选,若已记录)"
97 },
98 "files_to_modify": {
99 "type": "array",
100 "items": {"type": "string"},
101 "description": "将要修改的文件列表(可选)"
102 },
103 "approved": {
104 "type": "boolean",
105 "default": true,
106 "description": "是否批准执行计划"
107 }
108 }
109 }),
110 }
111 }
112
113 fn risk_level(&self) -> RiskLevel {
114 RiskLevel::Mutating
115 }
116
117 async fn execute(&self, params: Value) -> Result<String> {
118 let plan_content = params["plan"].as_str();
119 let files_to_modify = params["files_to_modify"].as_array().map(|arr| {
120 arr.iter()
121 .filter_map(|v| v.as_str().map(|s| s.to_string()))
122 .collect::<Vec<_>>()
123 });
124 let approved = params["approved"].as_bool().unwrap_or(true);
125
126 let plan = get_plan_state();
127 let mut state = plan.lock().await;
128
129 if state.state != PlanState::Active {
130 return Ok("Not in plan mode. Use enter_plan_mode first.".to_string());
131 }
132
133 if let Some(content) = plan_content {
135 state.plan_content = content.to_string();
136 }
137 if let Some(files) = files_to_modify {
138 state.files_to_modify = files;
139 }
140
141 if approved {
142 state.state = PlanState::Committed;
143
144 let files_str = if state.files_to_modify.is_empty() {
145 "No specific files identified".to_string()
146 } else {
147 state.files_to_modify.join(", ")
148 };
149
150 Ok(format!(
151 "Plan committed. Ready to execute.\n\nPlan: {}\nFiles to modify: {}\n\nNow proceeding with implementation...",
152 state.plan_content, files_str
153 ))
154 } else {
155 state.state = PlanState::None;
156 state.plan_content.clear();
157 state.files_to_modify.clear();
158
159 Ok(
160 "Plan rejected and discarded. Returning to normal mode without making changes."
161 .to_string(),
162 )
163 }
164 }
165}
166
167pub fn is_in_plan_mode() -> bool {
169 false }
172
173pub async fn get_current_plan_state() -> PlanState {
175 let plan = get_plan_state();
176 let state = plan.lock().await;
177 state.state.clone()
178}