1use crate::command_safety::shell_string_might_be_dangerous;
10use crate::config::constants::tools;
11use crate::core::loop_detector::LoopDetector;
12use crate::tools::apply_patch::decode_apply_patch_input;
13use crate::tools::command_args::{command_text, interactive_input_text};
14use crate::tools::tool_intent::{
15 self, classify_tool_intent, command_session_action, command_session_action_in, file_operation_action_in,
16 file_operation_action_is,
17};
18use anyhow::{Context, Result};
19use hashbrown::{HashMap, HashSet};
20use serde_json::Value;
21use std::collections::VecDeque;
22use std::path::{Path, PathBuf};
23use std::sync::{Arc, RwLock};
24use std::time::{Duration, Instant};
25use tracing::warn;
26
27const VERIFICATION_REQUIRED_TOOLS: &[&str] = &[
29 tools::WRITE_FILE,
30 tools::EDIT_FILE,
31 tools::UNIFIED_EXEC,
32 tools::CREATE_PTY_SESSION,
33];
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum AutonomousPolicy {
38 AutoExecute,
40 VerifyThenExecute,
42 RequireConfirmation,
44}
45
46#[derive(Debug, Clone, Default)]
48struct ToolStats {
49 total_attempts: usize,
50 successful_executions: usize,
51 failed_executions: usize,
52}
53
54impl ToolStats {
55 fn success_rate(&self) -> f64 {
56 if self.total_attempts == 0 {
57 0.0
58 } else {
59 self.successful_executions as f64 / self.total_attempts as f64
60 }
61 }
62}
63
64use crate::tools::circuit_breaker::CircuitBreaker;
65use crate::tools::validation::paths::validate_path_safety;
66use crate::utils::path::{normalize_path, resolve_workspace_path};
67
68pub struct AutonomousExecutor {
85 verification_tools: HashSet<String>,
86 loop_detector: Arc<RwLock<LoopDetector>>,
87 execution_stats: Arc<RwLock<HashMap<String, ToolStats>>>,
88 workspace_dir: Option<PathBuf>,
89 rate_limit_window: Duration,
90 rate_limit_max_calls: usize,
91 rate_history: Arc<RwLock<HashMap<String, VecDeque<Instant>>>>,
92 circuit_breaker: CircuitBreaker,
93}
94
95impl AutonomousExecutor {
96 #[inline]
97 fn canonical_tool_key(tool_name: &str) -> &str {
98 tool_intent::canonical_command_session_tool_name(tool_name).unwrap_or(tool_name)
99 }
100
101 #[inline]
102 fn is_command_session_run(tool_name: &str, args: &Value) -> bool {
103 tool_intent::is_command_run_tool_call(tool_name, args)
104 || (tool_name == tools::UNIFIED_EXEC && command_session_action(args).is_none())
105 }
106
107 pub fn new() -> Self {
108 Self::with_loop_detector(Arc::new(RwLock::new(LoopDetector::new())))
109 }
110
111 pub fn with_loop_detector(loop_detector: Arc<RwLock<LoopDetector>>) -> Self {
112 Self {
113 verification_tools: VERIFICATION_REQUIRED_TOOLS.iter().map(|s| s.to_string()).collect(),
114 loop_detector,
115 execution_stats: Arc::new(RwLock::new(HashMap::new())),
116 workspace_dir: std::env::var("WORKSPACE_DIR")
117 .ok()
118 .map(PathBuf::from)
119 .or_else(|| std::env::current_dir().ok()),
120 rate_limit_window: Duration::from_secs(10),
121 rate_limit_max_calls: 5,
122 rate_history: Arc::new(RwLock::new(HashMap::new())),
123 circuit_breaker: CircuitBreaker::default(),
124 }
125 }
126
127 pub fn set_workspace_dir(&mut self, dir: PathBuf) {
129 self.workspace_dir = Some(dir);
130 }
131
132 pub fn configure_loop_limits(&self, limits: &HashMap<String, usize>) {
134 if let Ok(mut detector) = self.loop_detector.write() {
135 for (tool, limit) in limits {
136 detector.set_tool_limit(Self::canonical_tool_key(tool), *limit);
137 }
138 } else {
139 tracing::warn!("Failed to acquire loop detector lock for configuration");
140 }
141 }
142
143 pub fn set_loop_limit(&self, tool_name: &str, limit: usize) {
144 let tool_key = Self::canonical_tool_key(tool_name);
145 if let Ok(mut detector) = self.loop_detector.write() {
146 detector.set_tool_limit(tool_key, limit);
147 } else {
148 tracing::warn!("Failed to acquire loop detector lock for configuration");
149 }
150 }
151
152 pub fn is_hard_limit_exceeded(&self, tool_name: &str) -> bool {
153 let tool_key = Self::canonical_tool_key(tool_name);
154 self.loop_detector
155 .read()
156 .map(|detector| detector.is_hard_limit_exceeded(tool_key))
157 .unwrap_or(false)
158 }
159
160 pub fn reset_turn_loop_detection(&self) {
162 if let Ok(mut detector) = self.loop_detector.write() {
163 detector.reset();
164 } else {
165 tracing::warn!("Failed to acquire loop detector lock for turn reset");
166 }
167 }
168
169 pub fn get_policy(&self, tool_name: &str, args: &Value) -> AutonomousPolicy {
171 if self.is_destructive_operation(tool_name, args) {
172 return AutonomousPolicy::RequireConfirmation;
173 }
174
175 if !classify_tool_intent(tool_name, args).mutating {
176 return AutonomousPolicy::AutoExecute;
177 }
178
179 if self.requires_preview(tool_name, args) {
180 return AutonomousPolicy::VerifyThenExecute;
181 }
182
183 AutonomousPolicy::RequireConfirmation
184 }
185
186 pub fn should_block(&self, tool_name: &str, _args: &Value) -> Option<String> {
189 let tool_key = Self::canonical_tool_key(tool_name);
190
191 if !self.circuit_breaker.allow_request_for_tool(tool_key) {
193 return Some(format!(
194 "Tool '{tool_key}' blocked by circuit breaker due to repeated failures. \
195 Cooling down before retrying."
196 ));
197 }
198
199 if self.is_rate_limited(tool_key) {
200 return Some(format!(
201 "Tool '{}' temporarily blocked: rate limit exceeded ({} calls in {:?}).",
202 tool_key, self.rate_limit_max_calls, self.rate_limit_window
203 ));
204 }
205
206 match self.loop_detector.try_read() {
208 Ok(detector) => {
209 if detector.is_hard_limit_exceeded(tool_key) {
211 return Some(format!("Tool '{tool_key}' blocked: hard limit exceeded. Agent is stuck in a loop."));
212 }
213
214 let count = detector.get_call_count(tool_key);
216 if count >= 3
217 && let Some(suggestion) = detector.suggest_alternative(tool_key)
218 {
219 return Some(format!(
220 "Tool '{tool_key}' called {count} times. Consider alternative approach:\n{suggestion}"
221 ));
222 }
223 }
224 Err(_) => {
225 tracing::debug!("Could not acquire loop detector read lock for {}", tool_key);
227 }
228 }
229 None
230 }
231
232 pub fn record_tool_call(&self, tool_name: &str, args: &Value) -> Option<String> {
235 let tool_key = Self::canonical_tool_key(tool_name);
236 self.record_rate_history(tool_key);
237 if let Ok(mut detector) = self.loop_detector.write() {
238 detector.record_call(tool_key, args)
239 } else {
240 None
241 }
242 }
243
244 fn is_destructive_operation(&self, tool_name: &str, args: &Value) -> bool {
246 match tool_name {
247 tools::APPLY_PATCH | tools::DELETE_FILE => true,
248 tools::UNIFIED_FILE => file_operation_action_in(args, &["delete"]),
249 _ if Self::is_command_session_run(tool_name, args) => command_text(args)
250 .ok()
251 .flatten()
252 .is_some_and(|cmd| self.is_destructive_command(&cmd)),
253 _ if tool_intent::is_command_session_tool(tool_name)
254 && command_session_action_in(args, &["write", "continue"]) =>
255 {
256 interactive_input_text(args).is_some_and(|input| self.is_destructive_command(input))
257 }
258 _ => false,
259 }
260 }
261
262 fn is_destructive_command(&self, cmd: &str) -> bool {
264 if shell_string_might_be_dangerous(cmd) {
265 return true;
266 }
267
268 let cmd_lower = cmd.to_lowercase();
269
270 let supplemental_patterns = [
273 "truncate",
274 "> /dev/",
275 "dd if=",
276 "mkfs",
277 "fdisk",
278 "format",
279 ">/",
281 "2>/",
282 "npm uninstall -g",
284 "cargo uninstall",
285 "pip uninstall",
286 "chmod -r",
288 "chown -r",
289 ];
290
291 supplemental_patterns.iter().any(|pattern| cmd_lower.contains(pattern))
292 }
293
294 pub fn validate_args(&self, tool_name: &str, args: &Value) -> Result<()> {
296 match tool_name {
297 tools::WRITE_FILE | tools::EDIT_FILE => self.validate_file_path(args.get("path"))?,
298 _ if Self::is_command_session_run(tool_name, args) => {
299 self.validate_command_text(
300 &command_text(args)
301 .map_err(anyhow::Error::msg)?
302 .context("Missing or invalid 'command' argument")?,
303 )?;
304 }
305 _ if tool_intent::is_command_session_tool(tool_name)
306 && command_session_action_in(args, &["write", "continue"]) =>
307 {
308 if let Some(input) = interactive_input_text(args) {
309 self.validate_command_text(input)?;
310 }
311 }
312 tools::UNIFIED_FILE if file_operation_action_in(args, &["write", "edit", "delete"]) => {
313 self.validate_file_path(args.get("path"))?;
314 }
315 tools::UNIFIED_FILE if file_operation_action_in(args, &["move", "copy"]) => {
316 self.validate_file_path(args.get("path"))?;
317 self.validate_file_path(args.get("destination"))?;
318 }
319 _ => {}
320 }
321 Ok(())
322 }
323
324 fn validate_file_path(&self, path: Option<&Value>) -> Result<()> {
329 let path_str = path.and_then(|v| v.as_str()).context("Missing or invalid 'path' argument")?;
330
331 validate_path_safety(path_str)?;
333
334 let path_obj = Path::new(path_str);
335
336 if path_obj.is_absolute() {
338 if path_obj.starts_with("/tmp/vtcode") {
341 return Ok(());
342 }
343
344 if let Some(workspace) = &self.workspace_dir
346 && (resolve_workspace_path(workspace, path_obj).is_ok()
347 || is_within_workspace_lexically(workspace, path_obj))
348 {
349 return Ok(());
350 }
351
352 anyhow::bail!(
353 "Absolute path outside workspace boundary: {path_str}. \
354 Only paths within WORKSPACE_DIR or /tmp/vtcode are allowed."
355 );
356 }
357
358 if path_str.contains("..") {
360 warn!("Path contains parent directory traversal: {}", path_str);
361
362 if let Some(workspace) = &self.workspace_dir {
364 let path_obj = Path::new(path_str);
365 let canonical_ok = resolve_workspace_path(workspace, &workspace.join(path_obj)).is_ok();
366 let lexical_ok = is_within_workspace_lexically(workspace, path_obj);
367 if !canonical_ok && !lexical_ok {
368 anyhow::bail!("Path traversal escapes workspace boundary: {path_str}");
369 }
370 } else {
371 anyhow::bail!("Path traversal blocked: workspace boundary is unknown for '{path_str}'");
372 }
373 }
374
375 if self.workspace_dir.is_none() {
377 anyhow::bail!(
378 "Workspace directory is not set; refusing to write to relative path '{path_str}'. \
379 Set WORKSPACE_DIR or call set_workspace_dir()."
380 );
381 }
382
383 Ok(())
384 }
385
386 fn validate_command_text(&self, cmd: &str) -> Result<()> {
388 if self.is_destructive_command(cmd) {
389 anyhow::bail!("Destructive command requires explicit confirmation: {cmd}");
390 }
391
392 Ok(())
393 }
394
395 pub fn generate_preview(&self, tool_name: &str, args: &Value) -> String {
397 if tool_name == tools::WRITE_FILE
398 || (tool_name == tools::UNIFIED_FILE && file_operation_action_is(args, "write"))
399 {
400 let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("unknown");
401 let content = args.get("content").and_then(|v| v.as_str()).unwrap_or("");
402 let lines = content.lines().count();
403 let size_kb = content.len() / 1024;
404
405 let preview = if lines > 10 {
406 let first_lines: Vec<_> = content.lines().take(5).collect();
407 format!("\n {}\n ... ({} more lines)", first_lines.join("\n "), lines - 5)
408 } else {
409 format!("\n {}", content.lines().collect::<Vec<_>>().join("\n "))
410 };
411
412 format!("Will write {lines} lines ({size_kb} KB) to: {path}\nPreview:{preview}")
413 } else if tool_name == tools::EDIT_FILE
414 || (tool_name == tools::UNIFIED_FILE && file_operation_action_is(args, "edit"))
415 {
416 let path = args.get("path").and_then(|v| v.as_str()).unwrap_or("unknown");
417 let old_str = args.get("old_str").and_then(|v| v.as_str()).unwrap_or("");
418 let new_str = args.get("new_str").and_then(|v| v.as_str()).unwrap_or("");
419
420 format!(
421 "Will edit file: {}\nReplacing:\n {}\nWith:\n {}",
422 path,
423 old_str.lines().take(3).collect::<Vec<_>>().join("\n "),
424 new_str.lines().take(3).collect::<Vec<_>>().join("\n ")
425 )
426 } else if Self::is_command_session_run(tool_name, args) {
427 let cmd = command_text(args).ok().flatten().unwrap_or_else(|| "unknown".to_string());
428 let is_destructive = self.is_destructive_command(&cmd);
429
430 let warning = if is_destructive {
431 "\n[WARN] WARNING: This command is potentially destructive!"
432 } else {
433 ""
434 };
435
436 format!("Will execute: {cmd}{warning}")
437 } else if tool_name == tools::APPLY_PATCH {
438 let patch = decode_apply_patch_input(args)
439 .ok()
440 .flatten()
441 .map(|patch| patch.text)
442 .unwrap_or_default();
443 let lines = patch.lines().count();
444 format!("Will apply patch with {lines} lines of changes")
445 } else {
446 format!("Will execute: {tool_name} with args: {args:?}")
447 }
448 }
449
450 fn requires_preview(&self, tool_name: &str, args: &Value) -> bool {
451 let canonical_tool_name = Self::canonical_tool_key(tool_name);
452 if self.verification_tools.contains(canonical_tool_name) {
453 return true;
454 }
455
456 match canonical_tool_name {
457 tools::UNIFIED_FILE => file_operation_action_in(args, &["write", "edit", "move", "copy"]),
458 tools::UNIFIED_EXEC => command_session_action_in(args, &["run", "code", "close"]),
459 _ => false,
460 }
461 }
462
463 pub fn record_execution(&self, tool_name: &str, success: bool) {
465 let tool_key = Self::canonical_tool_key(tool_name);
466
467 if success {
469 self.circuit_breaker.record_success_for_tool(tool_key);
470 } else {
471 self.circuit_breaker.record_failure_for_tool(tool_key, false);
474 }
475
476 if let Ok(mut stats) = self.execution_stats.write() {
477 let entry = stats.entry(tool_key.to_string()).or_default();
478 entry.total_attempts += 1;
479 if success {
480 entry.successful_executions += 1;
481 } else {
482 entry.failed_executions += 1;
483 }
484 }
485 }
486
487 pub fn get_success_rate(&self, tool_name: &str) -> f64 {
489 if let Ok(stats) = self.execution_stats.read() {
490 stats.get(tool_name).map(|s| s.success_rate()).unwrap_or(0.0)
491 } else {
492 0.0
493 }
494 }
495
496 pub fn get_tool_stats(&self, tool_name: &str) -> Option<(usize, usize, usize)> {
498 if let Ok(stats) = self.execution_stats.read() {
499 stats
500 .get(tool_name)
501 .map(|s| (s.total_attempts, s.successful_executions, s.failed_executions))
502 } else {
503 None
504 }
505 }
506}
507
508impl Default for AutonomousExecutor {
509 fn default() -> Self {
510 Self::new()
511 }
512}
513
514impl AutonomousExecutor {
515 fn record_rate_history(&self, tool_name: &str) {
516 let now = Instant::now();
517 if let Ok(mut history) = self.rate_history.write() {
518 let entries = history.entry(Self::canonical_tool_key(tool_name).to_string()).or_default();
519 entries.push_back(now);
520 prune_expired_timestamps(entries, now, self.rate_limit_window);
521 }
522 }
523
524 fn is_rate_limited(&self, tool_name: &str) -> bool {
525 let tool_key = Self::canonical_tool_key(tool_name);
526 let now = Instant::now();
527
528 if let Ok(history) = self.rate_history.read() {
531 if let Some(entries) = history.get(tool_key) {
532 let oldest_within_window = entries
534 .front()
535 .is_some_and(|front| now.duration_since(*front) <= self.rate_limit_window);
536 if oldest_within_window {
537 return entries.len() >= self.rate_limit_max_calls;
538 }
539 } else {
540 return false;
542 }
543 }
544
545 if let Ok(mut history) = self.rate_history.write() {
547 let entries = history.entry(tool_key.to_string()).or_default();
548 prune_expired_timestamps(entries, now, self.rate_limit_window);
549 return entries.len() >= self.rate_limit_max_calls;
550 }
551 false
552 }
553}
554
555fn prune_expired_timestamps(entries: &mut VecDeque<Instant>, now: Instant, window: Duration) {
556 while let Some(front) = entries.front() {
557 if now.duration_since(*front) > window {
558 entries.pop_front();
559 } else {
560 break;
561 }
562 }
563}
564
565fn is_within_workspace_lexically(workspace: &Path, candidate: &Path) -> bool {
566 let normalized_workspace = normalize_path(workspace);
567 let normalized_candidate = if candidate.is_absolute() {
568 normalize_path(candidate)
569 } else {
570 normalize_path(&normalized_workspace.join(candidate))
571 };
572 normalized_candidate.starts_with(&normalized_workspace)
573}
574
575#[cfg(test)]
576mod tests;