diff --git a/crates/agent_core/src/runtime/tool_execution.rs b/crates/agent_core/src/runtime/tool_execution.rs index f7ce7b01e..b7f53c990 100644 --- a/crates/agent_core/src/runtime/tool_execution.rs +++ b/crates/agent_core/src/runtime/tool_execution.rs @@ -12,6 +12,7 @@ struct Invocation { registry: Arc, command_executor: Arc, permission_handler: Option>, + permissions: ToolPermissions, cancellation: tools_core::RunCancellation, session_id: Option, services: Box, @@ -59,6 +60,7 @@ impl Invocation { tool_id: Some(self.request.id.clone()), session_id: self.session_id, permission_handler: self.permission_handler.as_deref(), + permissions: Some(&self.permissions), extensions: Some(self.services.as_mut()), }; // The registry is immutable for this run and was checked in prepare. @@ -320,6 +322,7 @@ impl AgentRuntime { }), tools_core::Clearance::Allowed => self.permission_handler.clone(), }, + permissions: self.permissions.clone(), cancellation: self.cancellation.clone(), session_id: self.session_id.clone(), services, diff --git a/crates/code_assistant_core/src/agent/sub_agent/tests.rs b/crates/code_assistant_core/src/agent/sub_agent/tests.rs index 089288e1c..a4459ab97 100644 --- a/crates/code_assistant_core/src/agent/sub_agent/tests.rs +++ b/crates/code_assistant_core/src/agent/sub_agent/tests.rs @@ -156,6 +156,7 @@ async fn sub_agent_tool_retains_structured_failure_output() { tool_id: Some("child".into()), session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; let mut input = SpawnAgentInput { diff --git a/crates/code_assistant_core/src/mocks.rs b/crates/code_assistant_core/src/mocks.rs index 6afbed848..b65838009 100644 --- a/crates/code_assistant_core/src/mocks.rs +++ b/crates/code_assistant_core/src/mocks.rs @@ -1089,6 +1089,7 @@ pub struct ToolTestFixture { tool_id: Option, session_id: Option, permission_handler: Option>, + permissions: tools_core::ToolPermissions, services: crate::tools::ToolServices, } @@ -1112,6 +1113,7 @@ impl ToolTestFixture { tool_id: None, session_id: None, permission_handler: None, + permissions: tools_core::ToolPermissions::default(), services, } } @@ -1322,6 +1324,7 @@ impl ToolTestFixture { tool_id: self.tool_id.clone(), session_id: self.session_id.clone(), permission_handler: self.permission_handler.as_deref(), + permissions: Some(&self.permissions), extensions: Some(&mut self.services), } } diff --git a/crates/code_assistant_core/src/session/permissions.rs b/crates/code_assistant_core/src/session/permissions.rs index bd9202b6c..f0637779e 100644 --- a/crates/code_assistant_core/src/session/permissions.rs +++ b/crates/code_assistant_core/src/session/permissions.rs @@ -63,6 +63,28 @@ pub fn permission_options_for(reason: &PermissionRequestReason<'_>) -> Vec { + let verb = access.verb(); + vec![ + PermissionOption::new( + PermissionDecision::GrantedOnce, + "Allow once", + &format!("Allow this {verb}; ask again next time"), + ), + PermissionOption::new( + PermissionDecision::GrantedSession, + "Always (session)", + &format!( + "Let the agent {verb} outside the project for the rest of this session" + ), + ), + PermissionOption::new( + PermissionDecision::Denied, + "Deny", + &format!("Reject the {verb}; the agent is told not to retry"), + ), + ] + } PermissionRequestReason::ExecuteCommand { .. } | PermissionRequestReason::ToolInvocation { .. } | PermissionRequestReason::AutoModeBlocked { .. } => vec![ @@ -158,6 +180,15 @@ impl PendingPermissionRequests { } } +/// Paths joined for a one-line summary. +fn display_paths(paths: &[std::path::PathBuf]) -> String { + paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join(", ") +} + /// [`PermissionMediator`] for sessions driven through [`SessionService`]: /// publishes the request on the event stream and awaits the decision from /// `respond_permission`. @@ -225,6 +256,18 @@ impl SessionPermissionMediator { "reason": reason, }), ), + PermissionRequestReason::OutsideProject { access, paths } => ( + format!( + "{} outside the project: {}", + access.label(), + display_paths(paths) + ), + serde_json::json!({ + "type": "outside_project", + "access": access.verb(), + "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), + }), + ), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, diff --git a/crates/code_assistant_core/src/tests/format_on_save_tests.rs b/crates/code_assistant_core/src/tests/format_on_save_tests.rs index cd7ef18a9..549d48433 100644 --- a/crates/code_assistant_core/src/tests/format_on_save_tests.rs +++ b/crates/code_assistant_core/src/tests/format_on_save_tests.rs @@ -194,6 +194,7 @@ async fn test_edit_tool_parameter_update_after_formatting() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -266,6 +267,7 @@ async fn test_write_file_with_format_on_save() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -335,6 +337,7 @@ async fn test_replace_in_file_with_format_on_save() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -411,6 +414,7 @@ async fn test_no_format_when_pattern_doesnt_match() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -481,6 +485,7 @@ async fn test_format_on_save_multiple_patterns() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -575,6 +580,7 @@ async fn test_format_on_save_glob_patterns() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; @@ -661,6 +667,7 @@ async fn test_format_on_save_with_conflicting_matches() -> Result<()> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; diff --git a/crates/code_assistant_core/src/tools/impls/delete_files.rs b/crates/code_assistant_core/src/tools/impls/delete_files.rs index 0fe6ae42c..d447ba501 100644 --- a/crates/code_assistant_core/src/tools/impls/delete_files.rs +++ b/crates/code_assistant_core/src/tools/impls/delete_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -110,7 +111,7 @@ impl Tool for DeleteFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to the files relative to the project root directory", + "description": "Paths to the files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is deleted only after the user approves it.", "items": { "type": "string" } @@ -158,18 +159,33 @@ impl Tool for DeleteFilesTool { let mut failed = Vec::new(); let mut deleted_contents = Vec::new(); - // Process each path - for path_str in input.paths.clone() { + // Deleting outside the project needs the user's approval, asked once + // for all such paths of this call. + let root_dir = explorer.root_dir(); + let resolved = super::outside_project::resolve_and_approve( + context, + "delete_files", + tools_core::FileAccess::Write, + &root_dir, + input.paths.iter().map(std::path::Path::new), + ) + .await; + + for (path_str, resolved) in input.paths.clone().into_iter().zip(resolved) { let path = PathBuf::from(&path_str); - // Check for absolute paths - if path.is_absolute() { - failed.push((path.clone(), "Absolute paths are not allowed".to_string())); - continue; - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let outside_explorer; + let (explorer, full_path, inside) = match resolved { + Resolved::Refused(denial) => { + failed.push((path, denial)); + continue; + } + Resolved::Outside(outside) => { + outside_explorer = super::outside_project::explorer_for(&outside); + (outside_explorer.as_ref(), outside, false) + } + Resolved::Inside => (explorer.as_ref(), root_dir.join(&path), true), + }; // Capture the content before deletion (best effort; binary or // unreadable files simply render without a diff) @@ -178,11 +194,7 @@ impl Tool for DeleteFilesTool { // Delete the file, unless it changed since this agent last saw it match context .seen_files() - .change( - explorer.as_ref(), - &full_path, - explorer.delete_file(&full_path), - ) + .change(explorer, &full_path, explorer.delete_file(&full_path)) .await { Ok(_) => { @@ -191,8 +203,8 @@ impl Tool for DeleteFilesTool { deleted_contents.push((path.clone(), content)); } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let Some(ui) = context.ui().filter(|_| inside) { let _ = ui .send_event(crate::ui::UiEvent::ResourceDeleted { project: input.project.clone(), @@ -352,10 +364,11 @@ mod tests { .find(|(path, _)| path == &PathBuf::from("non-existing.txt")); assert!(non_existing.is_some()); - // One failure should be the absolute path + // One failure should be the path outside the project, since nobody + // can approve deleting it let absolute_path = result.failed.iter().find(|(path, error)| { path == &PathBuf::from("/absolute/path.txt") - && error.contains("Absolute paths are not allowed") + && error.contains("Access outside project root is not allowed") }); assert!(absolute_path.is_some()); diff --git a/crates/code_assistant_core/src/tools/impls/edit.rs b/crates/code_assistant_core/src/tools/impls/edit.rs index 974271b15..206708767 100644 --- a/crates/code_assistant_core/src/tools/impls/edit.rs +++ b/crates/code_assistant_core/src/tools/impls/edit.rs @@ -114,7 +114,7 @@ impl Tool for EditTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to the file to modify (relative to project root)" + "description": "Path to the file to modify (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "old_text": { "type": "string", @@ -171,21 +171,22 @@ impl Tool for EditTool { .get_project(&input.project)? .ok_or_else(|| anyhow!("Project not found: {}", input.project))?; - // Check for absolute path + // A path outside the project is edited only once the user approves. let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(EditOutput { - project: input.project.clone(), - path, - error: Some(FileUpdaterError::Other( - "Absolute paths are not allowed".to_string(), - )), - match_start_lines: Vec::new(), - }); - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let target = + match super::outside_project::write_target(context, "edit", explorer, &path).await { + Ok(target) => target, + Err(error) => { + return Ok(EditOutput { + project: input.project.clone(), + path, + error: Some(FileUpdaterError::Other(error)), + match_start_lines: Vec::new(), + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Create a FileReplacement from the input let replacements = [FileReplacement { @@ -204,7 +205,11 @@ impl Tool for EditTool { // Apply with or without formatting, based on project configuration, // unless the file changed since this agent last saw it. let apply = async { - if let Some(format_command) = project_config.format_command_for(&path) { + if let Some(format_command) = target + .project_path + .as_deref() + .and_then(|project_path| project_config.format_command_for(project_path)) + { explorer .apply_replacements_with_formatting( &full_path, @@ -236,12 +241,12 @@ impl Tool for EditTool { input.replace_all = updated_replacement.replace_all; } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/code_assistant_core/src/tools/impls/glob_files.rs b/crates/code_assistant_core/src/tools/impls/glob_files.rs index 845df317c..fe7ac3dcc 100644 --- a/crates/code_assistant_core/src/tools/impls/glob_files.rs +++ b/crates/code_assistant_core/src/tools/impls/glob_files.rs @@ -5,7 +5,7 @@ use crate::tools::core::{ use anyhow::{Result, anyhow}; use serde::{Deserialize, Serialize}; use serde_json::json; -use std::path::PathBuf; +use std::path::{Component, Path, PathBuf}; // Input type for the glob_files tool #[derive(Deserialize, Serialize)] @@ -84,7 +84,7 @@ impl Tool for GlobFilesTool { }, "pattern": { "type": "string", - "description": "Glob pattern to match files against. Examples: '*.rs', '**/*.json', 'src/**/*.ts'" + "description": "Glob pattern to match files against. Examples: '*.rs', '**/*.json', 'src/**/*.ts'. A pattern whose leading folders lie outside the project (absolute, or '../') matches there only after the user approves it." } }, "required": ["project", "pattern"] @@ -126,8 +126,31 @@ impl Tool for GlobFilesTool { // Get the root directory of the project let root_dir = explorer.root_dir(); + // A pattern whose leading directories leave the project (absolute, or + // `..`) matches below that folder, once the user approves it. An + // absolute pattern inside the project matches like its relative form. + let (base, rest) = split_literal_base(&input.pattern); + let (walk_root, pattern) = match fs_explorer::resolve_outside_root(&root_dir, &base) { + Some(outside) => { + super::outside_project::approve( + context, + "glob_files", + tools_core::FileAccess::Read, + std::slice::from_ref(&outside), + ) + .await + .map_err(|denial| anyhow!(denial))?; + (outside, rest) + } + None if base.is_absolute() => { + let base = super::outside_project::relative_to_root(&root_dir, &base); + (root_dir.clone(), join_pattern(&base, &rest)) + } + None => (root_dir.clone(), input.pattern.clone()), + }; + // Find files matching the glob pattern - let files = find_files_matching_pattern(&root_dir, &input.pattern)?; + let files = find_files_matching_pattern(&walk_root, &pattern)?; // Convert absolute paths to relative paths for cleaner output let mut relative_files = Vec::new(); @@ -147,8 +170,40 @@ impl Tool for GlobFilesTool { } } +/// Split a glob pattern into its leading directories without wildcards and +/// the rest, e.g. `../other/src/**/*.rs` into `../other/src` and `**/*.rs`. +/// The last component always stays in the pattern. Splits at the platform's +/// separators, so `..\\other\\*.rs` works on Windows too. +fn split_literal_base(pattern: &str) -> (PathBuf, String) { + let components: Vec = Path::new(pattern).components().collect(); + let literal = components + .iter() + .take(components.len().saturating_sub(1)) + .take_while(|c| { + !c.as_os_str() + .to_string_lossy() + .contains(['*', '?', '[', '{']) + }) + .count(); + let rest: PathBuf = components[literal..].iter().collect(); + (components[..literal].iter().collect(), glob_string(&rest)) +} + +/// `rest` below the folder `base`, as a glob pattern. +fn join_pattern(base: &Path, rest: &str) -> String { + glob_string(&base.join(rest)) +} + +/// A relative path as a glob pattern: components joined with `/`. +fn glob_string(path: &Path) -> String { + path.components() + .map(|c| c.as_os_str().to_string_lossy()) + .collect::>() + .join("/") +} + // Helper function to find all files (text and binary) matching a glob pattern -fn find_files_matching_pattern(root_dir: &std::path::Path, pattern: &str) -> Result> { +fn find_files_matching_pattern(root_dir: &Path, pattern: &str) -> Result> { use glob::{MatchOptions, Pattern}; use ignore::WalkBuilder; @@ -399,4 +454,29 @@ mod tests { Ok(()) } + + #[test] + fn splits_a_pattern_at_its_first_wildcard_folder() { + let split = |pattern| { + let (base, rest) = split_literal_base(pattern); + (base.to_string_lossy().into_owned(), rest) + }; + assert_eq!( + split("../other/src/**/*.rs"), + ("../other/src".into(), "**/*.rs".into()) + ); + assert_eq!(split("*.rs"), ("".into(), "*.rs".into())); + assert_eq!(split("src/*.rs"), ("src".into(), "*.rs".into())); + assert_eq!(split("/abs/dir/*.rs"), ("/abs/dir".into(), "*.rs".into())); + assert_eq!(split("../note.txt"), ("..".into(), "note.txt".into())); + assert_eq!(split("src/{a,b}/*.rs"), ("src".into(), "{a,b}/*.rs".into())); + } + + #[cfg(windows)] + #[test] + fn splits_a_windows_pattern() { + let (base, rest) = split_literal_base(r"..\other\*.rs"); + assert_eq!(base, std::path::Path::new(r"..\other")); + assert_eq!(rest, "*.rs"); + } } diff --git a/crates/code_assistant_core/src/tools/impls/list_files.rs b/crates/code_assistant_core/src/tools/impls/list_files.rs index d1f1b20c7..e0baa941c 100644 --- a/crates/code_assistant_core/src/tools/impls/list_files.rs +++ b/crates/code_assistant_core/src/tools/impls/list_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -104,7 +105,7 @@ impl Tool for ListFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Directory paths relative to project root", + "description": "Directory paths relative to project root. A path outside the project (absolute, or leading out with `..`) is listed only after the user approves it.", "items": { "type": "string" } @@ -172,20 +173,35 @@ impl Tool for ListFilesTool { // Convert max_depth from u64 to usize if present let max_depth = input.max_depth.map(|d| d as usize); - for path_str in input.paths.clone() { + // Listing outside the project needs the user's approval, asked once + // for all such paths of this call. + let root_dir = explorer.root_dir(); + let resolved = super::outside_project::resolve_and_approve( + context, + "list_files", + tools_core::FileAccess::Read, + &root_dir, + input.paths.iter().map(std::path::Path::new), + ) + .await; + + for (path_str, resolved) in input.paths.clone().into_iter().zip(resolved) { let path = PathBuf::from(&path_str); - // Check if path is absolute and handle it properly - if path.is_absolute() { - failed_paths.push(( - path.display().to_string(), - "Path must be relative to project root".to_string(), - )); - continue; - } - - let full_path = explorer.root_dir().join(&path); - match explorer.list_files(&full_path, max_depth).await { + let listing = match resolved { + Resolved::Refused(denial) => { + failed_paths.push((path_str, denial)); + continue; + } + // Approved: list through an explorer rooted at that folder. + Resolved::Outside(outside) => { + super::outside_project::explorer_for(&outside) + .list_files(&outside, max_depth) + .await + } + Resolved::Inside => explorer.list_files(&root_dir.join(&path), max_depth).await, + }; + match listing { Ok(tree_entry) => { expanded_paths.push((path, tree_entry)); } diff --git a/crates/code_assistant_core/src/tools/impls/mod.rs b/crates/code_assistant_core/src/tools/impls/mod.rs index ebb87523a..f53d4af03 100644 --- a/crates/code_assistant_core/src/tools/impls/mod.rs +++ b/crates/code_assistant_core/src/tools/impls/mod.rs @@ -12,6 +12,7 @@ pub mod list_skills; mod mcp_resources; pub mod monitor; pub mod name_session; +mod outside_project; pub mod perplexity_ask; pub mod read_files; pub mod read_skill; diff --git a/crates/code_assistant_core/src/tools/impls/outside_project.rs b/crates/code_assistant_core/src/tools/impls/outside_project.rs new file mode 100644 index 000000000..b617367fe --- /dev/null +++ b/crates/code_assistant_core/src/tools/impls/outside_project.rs @@ -0,0 +1,594 @@ +//! Files outside the project a file tool works in: read or written only +//! after the user approves it. + +use crate::tools::core::ToolContext; +use fs_explorer::CodeExplorer; +use std::path::{Path, PathBuf}; +use tools_core::{FileAccess, PermissionRequestReason}; + +/// Session grant key: an "always" answer lets every file tool read (or +/// write) outside the project for the rest of the session. Reads and writes +/// are granted separately. +fn grant_key(access: FileAccess) -> String { + format!("{}_outside_project", access.verb()) +} + +/// Ask the user, once for all of `paths`, to let `tool_name` read or write +/// them outside the project. `Err` carries the message to report for each +/// refused path. +pub(crate) async fn approve( + context: &mut ToolContext<'_>, + tool_name: &str, + access: FileAccess, + paths: &[PathBuf], +) -> Result<(), String> { + if paths.is_empty() { + return Ok(()); + } + let mut paths = paths.to_vec(); + paths.sort(); + paths.dedup(); + match context + .request_escalation( + &grant_key(access), + tool_name, + PermissionRequestReason::OutsideProject { + access, + paths: &paths, + }, + ) + .await + { + Ok(true) => Ok(()), + Ok(false) => Err(format!( + "The user denied the {} outside the project. Do not simply retry; \ + ask the user how to proceed.", + access.verb() + )), + Err(e) => Err(format!("Access outside project root is not allowed ({e})")), + } +} + +/// Where a path a file tool was given leads. +#[derive(Debug)] +pub(crate) enum Resolved { + /// Inside the project: the tool resolves it as usual. + Inside, + /// Outside the project, and the user allowed it: where it really points. + Outside(PathBuf), + /// Outside the project, and refused: the message to report for it. + Refused(String), +} + +/// Resolve each of `paths` (relative to `root`, or absolute) and ask the +/// user, once for all that leave the project, to let `tool_name` reach them. +/// The result is in the order of `paths`. Each path is resolved only here, +/// so a tool touches exactly what the user approved, even if a symlink +/// changes while the question is open. +pub(crate) async fn resolve_and_approve<'p>( + context: &mut ToolContext<'_>, + tool_name: &str, + access: FileAccess, + root: &Path, + paths: impl IntoIterator, +) -> Vec { + let outside: Vec> = paths + .into_iter() + .map(|path| fs_explorer::resolve_outside_root(root, path)) + .collect(); + let asked: Vec = outside.iter().flatten().cloned().collect(); + let denial = approve(context, tool_name, access, &asked).await.err(); + outside + .into_iter() + .map(|outside| match (outside, &denial) { + (None, _) => Resolved::Inside, + (Some(_), Some(denial)) => Resolved::Refused(denial.clone()), + (Some(path), None) => Resolved::Outside(path), + }) + .collect() +} + +/// Where a file tool writes a file: inside the project, or outside it. +pub(crate) struct WriteTarget { + pub explorer: Box, + pub full_path: PathBuf, + /// The path relative to the project root, for format-on-save and + /// resource events; `None` outside the project, which gets neither. + pub project_path: Option, +} + +/// Where `tool_name` writes `path`: inside the project through `explorer`, +/// or — once the user approves — outside it through an explorer rooted at +/// the file's folder. `Err` carries the message for a refused path. +pub(crate) async fn write_target( + context: &mut ToolContext<'_>, + tool_name: &str, + explorer: Box, + path: &Path, +) -> Result { + let root = explorer.root_dir(); + let Some(outside) = fs_explorer::resolve_outside_root(&root, path) else { + let project_path = relative_to_root(&root, path); + return Ok(WriteTarget { + explorer, + full_path: root.join(&project_path), + project_path: Some(project_path), + }); + }; + approve( + context, + tool_name, + FileAccess::Write, + std::slice::from_ref(&outside), + ) + .await?; + Ok(WriteTarget { + explorer: explorer_for(&outside), + full_path: outside, + project_path: None, + }) +} + +/// `path`, known to lie inside `root`, relative to it: an absolute path +/// loses the root (also when it reaches the root through a symlink, such as +/// macOS's `/tmp`). Falls back to `path` itself when that fails. +pub(crate) fn relative_to_root(root: &Path, path: &Path) -> PathBuf { + if !path.is_absolute() { + return path.to_path_buf(); + } + let canonical = || { + path.canonicalize().ok().or_else(|| { + let parent = path.parent()?.canonicalize().ok()?; + Some(parent.join(path.file_name()?)) + }) + }; + path.strip_prefix(root) + .ok() + .map(Path::to_path_buf) + .or_else(|| { + canonical() + .and_then(|canonical| canonical.strip_prefix(root).ok().map(Path::to_path_buf)) + }) + .unwrap_or_else(|| path.to_path_buf()) +} + +/// An explorer for a path outside the project: rooted at the path itself +/// when it is a folder, else at its parent. +pub(crate) fn explorer_for(path: &Path) -> Box { + let dir = if path.is_dir() { + path + } else { + path.parent().unwrap_or(path) + }; + Box::new(fs_explorer::Explorer::new(dir.to_path_buf())) +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use crate::mocks::ToolTestFixture; + use serde_json::json; + use std::sync::{Arc, Mutex}; + use tools_core::{PermissionDecision, PermissionMediator, PermissionRequest}; + + /// Answers every request with one decision and records the paths asked + /// about. + pub(crate) struct OutsideAccessMediator { + decision: PermissionDecision, + pub(crate) asked: Mutex>>, + pub(crate) accesses: Mutex>, + /// Runs while the question is open, before the answer. + while_asking: Option>, + } + + impl OutsideAccessMediator { + pub(crate) fn new(decision: PermissionDecision) -> Arc { + Arc::new(Self { + decision, + asked: Default::default(), + accesses: Default::default(), + while_asking: None, + }) + } + + /// Like [`Self::new`], running `while_asking` before each answer. + pub(crate) fn while_asking( + decision: PermissionDecision, + while_asking: impl Fn() + Send + Sync + 'static, + ) -> Arc { + Arc::new(Self { + decision, + asked: Default::default(), + accesses: Default::default(), + while_asking: Some(Box::new(while_asking)), + }) + } + } + + #[async_trait::async_trait] + impl PermissionMediator for OutsideAccessMediator { + async fn request_permission( + &self, + request: PermissionRequest<'_>, + ) -> anyhow::Result { + let PermissionRequestReason::OutsideProject { access, paths } = request.reason else { + panic!("unexpected permission request: {:?}", request.reason); + }; + self.asked.lock().unwrap().push(paths.to_vec()); + self.accesses.lock().unwrap().push(access); + if let Some(while_asking) = &self.while_asking { + while_asking(); + } + Ok(self.decision) + } + } + + /// The smallest PNG: one pixel. + const PIXEL_PNG: &[u8] = &[ + 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, 0, 1, 0, 0, 0, 1, 8, 2, + 0, 0, 0, 144, 119, 83, 222, 0, 0, 0, 12, 73, 68, 65, 84, 120, 156, 99, 248, 207, 192, 0, 0, + 3, 1, 1, 0, 201, 254, 146, 239, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130, + ]; + + /// A project folder `proj` with `inside.txt`, next to `outside.txt` and a + /// folder `other` holding `note.txt` and `pixel.png`. + pub(crate) fn outside_setup() -> (tempfile::TempDir, ToolTestFixture) { + let dir = tempfile::tempdir().unwrap(); + let project = dir.path().join("proj"); + std::fs::create_dir(&project).unwrap(); + std::fs::write(project.join("inside.txt"), "inside").unwrap(); + std::fs::write(dir.path().join("outside.txt"), "one\ntwo\nthree").unwrap(); + let other = dir.path().join("other"); + std::fs::create_dir(&other).unwrap(); + std::fs::write(other.join("note.txt"), "a needle here").unwrap(); + std::fs::write(other.join("pixel.png"), PIXEL_PNG).unwrap(); + let manager = crate::mocks::MockProjectManager::default().with_project_path( + "proj", + project.clone(), + Box::new(fs_explorer::Explorer::new(project)), + ); + (dir, ToolTestFixture::with_project_manager(manager)) + } + + /// One call per file tool, each reaching into `other`. + fn outside_calls() -> Vec<(&'static str, serde_json::Value, &'static str)> { + vec![ + ( + "read_files", + json!({"paths": ["../other/note.txt"]}), + "needle", + ), + ("list_files", json!({"paths": ["../other"]}), "note.txt"), + ( + "search_files", + json!({"regex": "needle", "paths": ["../other"]}), + "note.txt", + ), + ( + "glob_files", + json!({"pattern": "../other/*.txt"}), + "note.txt", + ), + ( + "view_images", + json!({"paths": ["../other/pixel.png"]}), + "pixel.png", + ), + ] + } + + async fn invoke( + fixture: &mut ToolTestFixture, + tool: &str, + mut params: serde_json::Value, + ) -> anyhow::Result { + params["project"] = json!("proj"); + let registry = crate::tools::test_registry(); + let result = registry + .get(tool) + .unwrap() + .invoke(&mut fixture.context(), &mut params) + .await?; + let output = result + .as_render() + .render(&mut tools_core::ResourcesTracker::new()); + anyhow::ensure!(result.is_success(), "{output}"); + Ok(output) + } + + #[tokio::test] + async fn every_file_tool_reads_outside_the_project_once_allowed() { + for (tool, params, expected) in outside_calls() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let output = invoke(&mut fixture, tool, params).await.unwrap(); + + assert!(output.contains(expected), "{tool}: {output}"); + let asked = mediator.asked.lock().unwrap(); + assert_eq!(asked.len(), 1, "{tool} should ask once"); + let other = dir.path().join("other").canonicalize().unwrap(); + assert!(asked[0][0].starts_with(&other), "{tool}: {asked:?}"); + } + } + + #[tokio::test] + async fn every_file_tool_refuses_outside_the_project_when_denied() { + for (tool, params, _) in outside_calls() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + let error = error.to_string(); + assert!(error.contains("denied"), "{tool}: {error}"); + assert!(!error.contains("needle"), "{tool}: {error}"); + } + } + + #[tokio::test] + async fn file_tools_refuse_outside_the_project_when_nobody_can_be_asked() { + for (tool, params, _) in outside_calls() { + let (_dir, mut fixture) = outside_setup(); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!( + error.to_string().contains("outside project root"), + "{tool}: {error}" + ); + } + } + + #[tokio::test] + async fn a_session_grant_covers_every_file_tool() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + for (tool, params, expected) in outside_calls() { + let output = invoke(&mut fixture, tool, params).await.unwrap(); + assert!(output.contains(expected), "{tool}: {output}"); + } + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn absolute_paths_inside_the_project_need_no_approval() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let inside = dir.path().join("proj/inside.txt"); + + let output = invoke( + &mut fixture, + "read_files", + json!({"paths": [inside.to_str().unwrap()]}), + ) + .await + .unwrap(); + + assert!(output.contains("inside")); + assert!(mediator.asked.lock().unwrap().is_empty()); + } + + /// One call per writing tool, each changing something in `other`, with + /// a check of the result on disk. + #[allow(clippy::type_complexity)] + fn outside_writes() -> Vec<(&'static str, serde_json::Value, fn(&Path) -> bool)> { + vec![ + ( + "write_file", + json!({"path": "../other/new.txt", "content": "written"}), + |other| { + std::fs::read_to_string(other.join("new.txt")) + .is_ok_and(|content| content.trim_end() == "written") + }, + ), + ( + "edit", + json!({"path": "../other/note.txt", "old_text": "needle", "new_text": "pin"}), + |other| { + std::fs::read_to_string(other.join("note.txt")) + .unwrap() + .trim_end() + == "a pin here" + }, + ), + ( + "replace_in_file", + json!({ + "path": "../other/note.txt", + "diff": "<<<<<<< SEARCH\nneedle\n=======\npin\n>>>>>>> REPLACE" + }), + |other| { + std::fs::read_to_string(other.join("note.txt")) + .unwrap() + .trim_end() + == "a pin here" + }, + ), + ( + "delete_files", + json!({"paths": ["../other/note.txt"]}), + |other| !other.join("note.txt").exists(), + ), + ] + } + + #[tokio::test] + async fn every_writing_tool_writes_outside_the_project_once_allowed() { + for (tool, params, written) in outside_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + invoke(&mut fixture, tool, params).await.unwrap(); + + assert!(written(&dir.path().join("other")), "{tool} did not write"); + assert_eq!( + *mediator.accesses.lock().unwrap(), + vec![FileAccess::Write], + "{tool}" + ); + } + } + + #[tokio::test] + async fn every_writing_tool_leaves_outside_files_alone_when_denied() { + for (tool, params, written) in outside_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!(error.to_string().contains("denied"), "{tool}: {error}"); + assert!(!written(&dir.path().join("other")), "{tool} wrote anyway"); + assert_eq!( + std::fs::read_to_string(dir.path().join("other/note.txt")).unwrap(), + "a needle here" + ); + } + } + + #[tokio::test] + async fn writing_tools_refuse_outside_the_project_when_nobody_can_be_asked() { + for (tool, params, written) in outside_writes() { + let (dir, mut fixture) = outside_setup(); + + let error = invoke(&mut fixture, tool, params).await.unwrap_err(); + + assert!( + error.to_string().contains("outside project root"), + "{tool}: {error}" + ); + assert!(!written(&dir.path().join("other")), "{tool} wrote anyway"); + } + } + + #[tokio::test] + async fn a_session_grant_for_reads_does_not_allow_writes() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let read = json!({"paths": ["../other/note.txt"]}); + invoke(&mut fixture, "read_files", read.clone()) + .await + .unwrap(); + let write = json!({"path": "../other/new.txt", "content": "written"}); + invoke(&mut fixture, "write_file", write.clone()) + .await + .unwrap(); + // Both grants are remembered now: neither asks again. + invoke(&mut fixture, "read_files", read).await.unwrap(); + invoke(&mut fixture, "write_file", write).await.unwrap(); + + assert_eq!( + *mediator.accesses.lock().unwrap(), + vec![FileAccess::Read, FileAccess::Write] + ); + assert!(dir.path().join("other/new.txt").exists()); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_tool_uses_the_path_the_user_approved_even_if_a_symlink_changes_meanwhile() { + let (dir, fixture) = outside_setup(); + let first = dir.path().join("first"); + let second = dir.path().join("second"); + for folder in [&first, &second] { + std::fs::create_dir(folder).unwrap(); + std::fs::write(folder.join("x.txt"), "x").unwrap(); + } + let link = dir.path().join("proj/link"); + std::os::unix::fs::symlink(&first, &link).unwrap(); + let mediator = { + let (link, second) = (link.clone(), second.clone()); + OutsideAccessMediator::while_asking(PermissionDecision::GrantedOnce, move || { + std::fs::remove_file(&link).unwrap(); + std::os::unix::fs::symlink(&second, &link).unwrap(); + }) + }; + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + invoke( + &mut fixture, + "delete_files", + json!({"paths": ["link/x.txt"]}), + ) + .await + .unwrap(); + + assert!( + !first.join("x.txt").exists(), + "the approved file is deleted" + ); + assert!(second.join("x.txt").exists(), "the other file is not"); + } + + #[tokio::test] + async fn search_files_says_nothing_about_an_outside_path_before_it_is_approved() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + let error = invoke( + &mut fixture, + "search_files", + json!({"regex": "x", "paths": ["../missing"]}), + ) + .await + .unwrap_err() + .to_string(); + + assert!(error.contains("denied"), "{error}"); + assert!(!error.contains("not found"), "{error}"); + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } + + #[tokio::test] + async fn an_absolute_glob_inside_the_project_matches_without_asking() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let pattern = dir.path().join("proj").join("*.txt"); + + let output = invoke( + &mut fixture, + "glob_files", + json!({"pattern": pattern.to_str().unwrap()}), + ) + .await + .unwrap(); + + assert!(output.contains("inside.txt"), "{output}"); + assert!(mediator.asked.lock().unwrap().is_empty()); + } + + #[test] + fn absolute_paths_inside_the_root_become_relative() { + let dir = tempfile::tempdir().unwrap(); + std::fs::create_dir(dir.path().join("src")).unwrap(); + std::fs::write(dir.path().join("src/lib.rs"), "").unwrap(); + // The explorer's root is canonical; on macOS the temp dir is not. + let root = dir.path().canonicalize().unwrap(); + + for path in [ + dir.path().join("src/lib.rs"), + root.join("src/lib.rs"), + dir.path().join("src/new.rs"), + ] { + let relative = relative_to_root(&root, &path); + assert!(relative.is_relative(), "{}", path.display()); + assert!(relative.starts_with("src"), "{}", relative.display()); + } + assert_eq!( + relative_to_root(&root, Path::new("src/lib.rs")), + Path::new("src/lib.rs") + ); + } +} diff --git a/crates/code_assistant_core/src/tools/impls/read_files.rs b/crates/code_assistant_core/src/tools/impls/read_files.rs index dc4a2f346..1df52daea 100644 --- a/crates/code_assistant_core/src/tools/impls/read_files.rs +++ b/crates/code_assistant_core/src/tools/impls/read_files.rs @@ -1,13 +1,15 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, }; use crate::tools::parse::PathWithLineRange; use anyhow::{Result, anyhow}; +use fs_explorer::CodeExplorer; use serde::{Deserialize, Serialize}; use serde_json::json; use std::collections::HashMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// Prefix each line of content with its line number. /// Format: " N | line content" where N is right-aligned based on max line number width. @@ -26,6 +28,21 @@ fn prefix_lines_with_numbers(content: &str, start_line: usize) -> String { .join("\n") } +/// Read a file, or only the requested lines of it. +async fn read_lines( + explorer: &dyn CodeExplorer, + full_path: &Path, + parsed: &PathWithLineRange, +) -> Result { + if parsed.start_line.is_some() || parsed.end_line.is_some() { + explorer + .read_file_range(full_path, parsed.start_line, parsed.end_line) + .await + } else { + explorer.read_file(full_path).await + } +} + /// Maximum file size in bytes before requiring explicit opt-in const MAX_FILE_SIZE: usize = 200 * 1024; // 200KB @@ -328,7 +345,7 @@ impl Tool for ReadFilesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to the files relative to the project root directory. Can include line ranges using 'file.txt:10-20' syntax.", + "description": "Paths to the files relative to the project root directory. Can include line ranges using 'file.txt:10-20' syntax. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -381,43 +398,48 @@ impl Tool for ReadFilesTool { let mut loaded_files = HashMap::new(); let mut failed_files = Vec::new(); - // Process each path + // Parse each path string to extract line range information + let root = explorer.root_dir(); + let mut requests = Vec::new(); for path_str in input.paths.clone() { - // Parse the path string to extract line range information - let parsed_path = match PathWithLineRange::parse(&path_str) { - Ok(parsed) => parsed, - Err(e) => { - failed_files.push((PathBuf::from(path_str), e.to_string())); - continue; - } - }; - - let path = &parsed_path.path; - - // Check for absolute paths - if path.is_absolute() { - failed_files.push((path.clone(), "Absolute paths are not allowed".to_string())); - continue; + match PathWithLineRange::parse(&path_str) { + Ok(parsed) => requests.push((path_str, parsed)), + Err(e) => failed_files.push((PathBuf::from(path_str), e.to_string())), } + } - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(path); - + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let resolved = super::outside_project::resolve_and_approve( + context, + "read_files", + tools_core::FileAccess::Read, + &root, + requests.iter().map(|(_, parsed)| parsed.path.as_path()), + ) + .await; + + // Files inside the project, announced to the UI as resources + let mut project_files = Vec::new(); + for ((path_str, parsed_path), resolved) in requests.into_iter().zip(resolved) { // Determine the start line for line numbering // If a start_line is specified, use it; otherwise default to 1 let start_line = parsed_path.start_line.unwrap_or(1); - // Use either read_file_range or read_file based on whether we have line range info - let read_result = if parsed_path.start_line.is_some() || parsed_path.end_line.is_some() - { - // We have line range information, use read_file_range - explorer - .read_file_range(&full_path, parsed_path.start_line, parsed_path.end_line) - .await - } else { - // No line range specified, read the whole file - explorer.read_file(&full_path).await + let outside_explorer; + let (file_explorer, full_path, inside) = match resolved { + Resolved::Refused(denial) => { + failed_files.push((PathBuf::from(&path_str), denial)); + continue; + } + // Approved: read through an explorer rooted at the file's folder. + Resolved::Outside(full_path) => { + outside_explorer = super::outside_project::explorer_for(&full_path); + (outside_explorer.as_ref(), full_path, false) + } + Resolved::Inside => (explorer.as_ref(), root.join(&parsed_path.path), true), }; + let read_result = read_lines(file_explorer, &full_path, &parsed_path).await; match read_result { Ok(content) => { @@ -450,7 +472,7 @@ impl Tool for ReadFilesTool { // The agent saw the file now: a later change to it by // someone else makes its own next change fail. if has_line_range { - if let Ok(whole) = explorer.read_file(&full_path).await { + if let Ok(whole) = file_explorer.read_file(&full_path).await { context.seen_files().saw(&full_path, &whole); } } else { @@ -463,6 +485,9 @@ impl Tool for ReadFilesTool { start_line, }, ); + if inside { + project_files.push(parsed_path.path); + } } Err(e) => { failed_files.push((PathBuf::from(&path_str), e.to_string())); @@ -470,20 +495,13 @@ impl Tool for ReadFilesTool { } } - // Emit resource events for loaded files + // Emit resource events for loaded files inside the project if let Some(ui) = context.ui() { - for path in loaded_files.keys() { - // Get the base path without any line range information - let base_path = - if let Ok(parsed) = PathWithLineRange::parse(path.to_str().unwrap_or("")) { - parsed.path.clone() - } else { - path.clone() - }; + for path in project_files { let _ = ui .send_event(crate::ui::UiEvent::ResourceLoaded { project: input.project.clone(), - path: base_path, + path, }) .await; } @@ -1169,4 +1187,98 @@ mod tests { Ok(()) } + + use super::super::outside_project::tests::{OutsideAccessMediator, outside_setup}; + + fn read_input(paths: &[&str]) -> ReadFilesInput { + ReadFilesInput { + project: "proj".into(), + paths: paths.iter().map(|p| p.to_string()).collect(), + prefix_line_numbers: false, + ignore_size_limit: false, + } + } + + #[tokio::test] + async fn reading_outside_the_project_asks_once_and_reads_when_allowed() { + let (dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::GrantedOnce); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + let absolute = dir.path().join("outside.txt"); + let absolute = absolute.to_str().unwrap(); + let mut input = read_input(&["inside.txt", "../outside.txt:2", absolute]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!(output.failed_files.is_empty(), "{:?}", output.failed_files); + assert_eq!( + output.loaded_files[&PathBuf::from("inside.txt")].content, + "inside" + ); + assert_eq!( + output.loaded_files[&PathBuf::from("../outside.txt:2")].content, + "two" + ); + assert_eq!( + output.loaded_files[&PathBuf::from(absolute)].content, + "one\ntwo\nthree" + ); + let canonical = dir.path().join("outside.txt").canonicalize().unwrap(); + assert_eq!(*mediator.asked.lock().unwrap(), vec![vec![canonical]]); + } + + #[tokio::test] + async fn denied_outside_read_fails_only_the_outside_paths() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::Denied); + let mut fixture = fixture.with_permission_handler(mediator); + let mut input = read_input(&["inside.txt", "../outside.txt"]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!( + output + .loaded_files + .contains_key(&PathBuf::from("inside.txt")) + ); + assert_eq!(output.failed_files.len(), 1); + assert!(output.failed_files[0].1.contains("denied")); + } + + #[tokio::test] + async fn outside_read_without_a_permission_handler_is_rejected() { + let (_dir, mut fixture) = outside_setup(); + let mut input = read_input(&["../outside.txt"]); + + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + + assert!(output.loaded_files.is_empty()); + assert!(output.failed_files[0].1.contains("outside project root")); + } + + #[tokio::test] + async fn session_grant_for_outside_reads_stops_asking() { + let (_dir, fixture) = outside_setup(); + let mediator = OutsideAccessMediator::new(tools_core::PermissionDecision::GrantedSession); + let mut fixture = fixture.with_permission_handler(mediator.clone()); + + for _ in 0..2 { + let mut input = read_input(&["../outside.txt"]); + let output = ReadFilesTool + .execute(&mut fixture.context(), &mut input) + .await + .unwrap(); + assert!(output.failed_files.is_empty(), "{:?}", output.failed_files); + } + assert_eq!(mediator.asked.lock().unwrap().len(), 1); + } } diff --git a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs index 2cde3c73b..00cb8c0b2 100644 --- a/crates/code_assistant_core/src/tools/impls/replace_in_file.rs +++ b/crates/code_assistant_core/src/tools/impls/replace_in_file.rs @@ -146,7 +146,7 @@ impl Tool for ReplaceInFileTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to the file to modify (relative to project root)" + "description": "Path to the file to modify (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "diff": { "type": "string", @@ -208,21 +208,24 @@ impl Tool for ReplaceInFileTool { } }; - // Check for absolute path + // A path outside the project is edited only once the user approves. let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(ReplaceInFileOutput { - project: input.project.clone(), - path, - error: Some(FileUpdaterError::Other( - "Absolute paths are not allowed".to_string(), - )), - match_start_lines: Vec::new(), - }); - } - - // Join with root_dir to get full path - let full_path = explorer.root_dir().join(&path); + let target = + match super::outside_project::write_target(context, "replace_in_file", explorer, &path) + .await + { + Ok(target) => target, + Err(error) => { + return Ok(ReplaceInFileOutput { + project: input.project.clone(), + path, + error: Some(FileUpdaterError::Other(error)), + match_start_lines: Vec::new(), + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Compute match start line numbers before applying (need the original content) let match_start_lines = if let Ok(content) = std::fs::read_to_string(&full_path) { @@ -234,7 +237,11 @@ impl Tool for ReplaceInFileTool { // If format-on-save applies, use format-aware path; nothing happens if // the file changed since this agent last saw it. let apply = async { - if let Some(command_line) = project_config.format_command_for(&path) { + if let Some(command_line) = target + .project_path + .as_deref() + .and_then(|project_path| project_config.format_command_for(project_path)) + { explorer .apply_replacements_with_formatting( &full_path, @@ -262,12 +269,12 @@ impl Tool for ReplaceInFileTool { input.diff = render_diff_from_replacements(&updated); } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/code_assistant_core/src/tools/impls/search_files.rs b/crates/code_assistant_core/src/tools/impls/search_files.rs index 1617baefa..185882e2b 100644 --- a/crates/code_assistant_core/src/tools/impls/search_files.rs +++ b/crates/code_assistant_core/src/tools/impls/search_files.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -413,7 +414,7 @@ impl Tool for SearchFilesTool { "items": { "type": "string" }, - "description": "Optional: Restrict search to specific paths within the project (e.g., ['src/', 'tests/']). Use with caution - only when you're certain the search should be limited to specific directories. Omitting this parameter searches the entire project, which is usually preferred to avoid missing relevant matches." + "description": "Optional: Restrict search to specific paths within the project (e.g., ['src/', 'tests/']). Use with caution - only when you're certain the search should be limited to specific directories. Omitting this parameter searches the entire project, which is usually preferred to avoid missing relevant matches. A path outside the project (absolute, or leading out with `..`) is searched only after the user approves it." } }, "required": ["project", "regex"] @@ -454,21 +455,33 @@ impl Tool for SearchFilesTool { let root_dir = explorer.root_dir(); - // Determine search paths + // Determine search paths. Those that leave the project need the + // user's approval (asked once for all of them) before anything about + // them reaches the agent, not even whether they exist. let search_paths = if let Some(paths) = &input.paths { - // Validate and convert relative paths to absolute - let mut absolute_paths = Vec::new(); - for path in paths { - let absolute_path = root_dir.join(path); - if absolute_path.exists() { - absolute_paths.push(absolute_path); - } else { + let resolved = super::outside_project::resolve_and_approve( + context, + "search_files", + tools_core::FileAccess::Read, + &root_dir, + paths.iter().map(std::path::Path::new), + ) + .await; + let mut search_paths = Vec::new(); + for (path, resolved) in paths.iter().zip(resolved) { + let (search_path, outside) = match resolved { + Resolved::Refused(denial) => return Err(anyhow!(denial)), + Resolved::Outside(outside) => (outside, true), + Resolved::Inside => (root_dir.join(path), false), + }; + if !search_path.exists() { return Err(anyhow!("Path not found: {path}")); } + search_paths.push((search_path, outside)); } - absolute_paths + search_paths } else { - vec![root_dir.clone()] + vec![(root_dir.clone(), false)] }; // Set up search options with a reasonable initial limit @@ -482,8 +495,15 @@ impl Tool for SearchFilesTool { // Perform searches across all specified paths let mut all_results = Vec::new(); - for search_path in search_paths { - let mut path_results = explorer.search(&search_path, options.clone()).await?; + for (search_path, outside) in search_paths { + let mut path_results = if outside { + // Approved: search through an explorer rooted at that path. + super::outside_project::explorer_for(&search_path) + .search(&search_path, options.clone()) + .await? + } else { + explorer.search(&search_path, options.clone()).await? + }; all_results.append(&mut path_results); } diff --git a/crates/code_assistant_core/src/tools/impls/view_documents.rs b/crates/code_assistant_core/src/tools/impls/view_documents.rs index 9c1fd4b4c..22698df32 100644 --- a/crates/code_assistant_core/src/tools/impls/view_documents.rs +++ b/crates/code_assistant_core/src/tools/impls/view_documents.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities, @@ -32,10 +33,6 @@ fn document_format_for_extension(ext: &str) -> Option<&'static str> { /// Resolve a path relative to the project root and verify it stays within bounds. fn resolve_project_path(root_dir: &std::path::Path, rel_path: &std::path::Path) -> Result { - if rel_path.is_absolute() { - anyhow::bail!("Absolute paths are not allowed"); - } - let candidate = root_dir.join(rel_path); let canonical = candidate @@ -182,7 +179,7 @@ impl Tool for ViewDocumentsTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to document files relative to the project root directory", + "description": "Paths to document files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -227,9 +224,20 @@ impl Tool for ViewDocumentsTool { let mut converted_documents = Vec::new(); let mut failed_documents = Vec::new(); let root_dir = explorer.root_dir(); + + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let resolved = super::outside_project::resolve_and_approve( + context, + "view_documents", + tools_core::FileAccess::Read, + &root_dir, + input.paths.iter().map(std::path::Path::new), + ) + .await; let mut total_output_chars: usize = 0; - for path_str in &input.paths { + for (path_str, resolved) in input.paths.iter().zip(resolved) { let path = PathBuf::from(path_str); // Check extension @@ -258,12 +266,19 @@ impl Tool for ViewDocumentsTool { }; // Resolve and validate the path - let full_path = match resolve_project_path(&root_dir, &path) { - Ok(p) => p, - Err(e) => { - failed_documents.push((path_str.clone(), e.to_string())); + let full_path = match resolved { + Resolved::Refused(denial) => { + failed_documents.push((path_str.clone(), denial)); continue; } + Resolved::Outside(outside) => outside, + Resolved::Inside => match resolve_project_path(&root_dir, &path) { + Ok(p) => p, + Err(e) => { + failed_documents.push((path_str.clone(), e.to_string())); + continue; + } + }, }; // Check file size before reading diff --git a/crates/code_assistant_core/src/tools/impls/view_images.rs b/crates/code_assistant_core/src/tools/impls/view_images.rs index cdff65fdb..21d21d6f0 100644 --- a/crates/code_assistant_core/src/tools/impls/view_images.rs +++ b/crates/code_assistant_core/src/tools/impls/view_images.rs @@ -1,3 +1,4 @@ +use super::outside_project::Resolved; use crate::tools::ToolServicesAccess; use crate::tools::core::{ ImageData, MAX_IMAGE_EDGE, Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, @@ -28,13 +29,10 @@ fn mime_type_for_extension(ext: &str) -> Option<&'static str> { } /// Resolve a path relative to the project root and verify it stays within bounds. -/// Returns the resolved absolute path. Rejects absolute paths, `..` traversals -/// that escape the root, and symlinks pointing outside the project. +/// Returns the resolved absolute path. Rejects `..` traversals +/// that escape the root, and symlinks pointing outside the project; those +/// are read only after the user approves them (see `outside_project`). fn resolve_project_path(root_dir: &std::path::Path, rel_path: &std::path::Path) -> Result { - if rel_path.is_absolute() { - anyhow::bail!("Absolute paths are not allowed"); - } - let candidate = root_dir.join(rel_path); // Canonicalize to resolve symlinks and .. components. @@ -197,7 +195,7 @@ impl Tool for ViewImagesTool { "paths": { "examples": ["File path here"], "type": "array", - "description": "Paths to image files relative to the project root directory", + "description": "Paths to image files relative to the project root directory. A path outside the project (absolute, or leading out with `..`) is read only after the user approves it.", "items": { "type": "string" } @@ -243,7 +241,18 @@ impl Tool for ViewImagesTool { let mut failed_images = Vec::new(); let root_dir = explorer.root_dir(); - for path_str in &input.paths { + // Reading outside the project needs the user's approval, asked once + // for all such paths of this call. + let resolved = super::outside_project::resolve_and_approve( + context, + "view_images", + tools_core::FileAccess::Read, + &root_dir, + input.paths.iter().map(std::path::Path::new), + ) + .await; + + for (path_str, resolved) in input.paths.iter().zip(resolved) { let path = PathBuf::from(path_str); // Check extension @@ -272,12 +281,19 @@ impl Tool for ViewImagesTool { }; // Resolve and validate the path stays within the project root - let full_path = match resolve_project_path(&root_dir, &path) { - Ok(p) => p, - Err(e) => { - failed_images.push((path_str.clone(), e.to_string())); + let full_path = match resolved { + Resolved::Refused(denial) => { + failed_images.push((path_str.clone(), denial)); continue; } + Resolved::Outside(outside) => outside, + Resolved::Inside => match resolve_project_path(&root_dir, &path) { + Ok(p) => p, + Err(e) => { + failed_images.push((path_str.clone(), e.to_string())); + continue; + } + }, }; // Read the raw bytes @@ -534,7 +550,7 @@ mod tests { let mut tracker = ResourcesTracker::new(); let output = result.as_render().render(&mut tracker); - assert!(output.contains("Absolute paths are not allowed")); + assert!(output.contains("Access outside project root is not allowed")); Ok(()) } diff --git a/crates/code_assistant_core/src/tools/impls/write_file.rs b/crates/code_assistant_core/src/tools/impls/write_file.rs index 2c84123e5..42642dcb8 100644 --- a/crates/code_assistant_core/src/tools/impls/write_file.rs +++ b/crates/code_assistant_core/src/tools/impls/write_file.rs @@ -99,7 +99,7 @@ impl Tool for WriteFileTool { "path": { "examples": ["File path here"], "type": "string", - "description": "Path to create or overwrite (relative to project root)" + "description": "Path to create or overwrite (relative to project root). A path outside the project (absolute, or leading out with `..`) is written only after the user approves it." }, "content": { "type": "string", @@ -177,21 +177,30 @@ impl Tool for WriteFileTool { // entry (and thus no format-on-save). let project_config = context.project_manager().get_project(&input.project)?; - // Check for absolute path let path = PathBuf::from(&input.path); - if path.is_absolute() { - return Ok(WriteFileOutput { - path, - content: String::new(), - error: Some("Absolute paths are not allowed".to_string()), - original_content: None, - }); - } - let project_root = explorer.root_dir(); - // Join with root_dir to get full path - let full_path = project_root.join(&path); + // A path outside the project is written only once the user approves. + let target = match super::outside_project::write_target( + context, + "write_file", + explorer, + &path, + ) + .await + { + Ok(target) => target, + Err(error) => { + return Ok(WriteFileOutput { + path, + content: String::new(), + error: Some(error), + original_content: None, + }); + } + }; + let explorer = target.explorer; + let full_path = target.full_path; // Read the original content before writing (if the file exists and we're not appending). // This allows the UI to show a proper diff for overwrites. @@ -205,7 +214,8 @@ impl Tool for WriteFileTool { // one change, so the formatted content counts as seen. let format_command = project_config .as_ref() - .and_then(|config| config.format_command_for(&path)); + .zip(target.project_path.as_deref()) + .and_then(|(config, project_path)| config.format_command_for(project_path)); let write = async { explorer .write_file(&full_path, &input.content, input.append) @@ -234,12 +244,12 @@ impl Tool for WriteFileTool { input.content = updated; } - // Emit resource event - if let Some(ui) = context.ui() { + // Emit resource event (files outside the project are no resource of it) + if let (Some(ui), Some(project_path)) = (context.ui(), &target.project_path) { let _ = ui .send_event(crate::ui::UiEvent::ResourceWritten { project: input.project.clone(), - path: path.clone(), + path: project_path.clone(), }) .await; } diff --git a/crates/fs_explorer/src/explorer.rs b/crates/fs_explorer/src/explorer.rs index 82e60b1a2..206daf809 100644 --- a/crates/fs_explorer/src/explorer.rs +++ b/crates/fs_explorer/src/explorer.rs @@ -400,6 +400,20 @@ impl Explorer { } } +/// Where `path` (relative to `root`, or absolute) really points when that +/// lies outside `root`, following symlinks. `None` when it stays inside, or +/// when it cannot be resolved (reading it then fails as usual). +pub fn resolve_outside_root(root: &Path, path: &Path) -> Option { + let root = root.canonicalize().unwrap_or_else(|_| root.clean()); + let candidate = if path.is_absolute() { + path.to_path_buf() + } else { + root.join(path) + }; + let canonical = canonicalize_with_existing_parent(&candidate.clean()).ok()?; + (!canonical.starts_with(&root)).then_some(canonical) +} + fn canonicalize_with_existing_parent(path: &Path) -> std::io::Result { if path.exists() { return path.canonicalize(); diff --git a/crates/fs_explorer/src/lib.rs b/crates/fs_explorer/src/lib.rs index f6e5170ee..544335f8e 100644 --- a/crates/fs_explorer/src/lib.rs +++ b/crates/fs_explorer/src/lib.rs @@ -8,6 +8,6 @@ pub mod locks; pub mod types; pub mod watch; -pub use explorer::{Explorer, is_path_gitignored}; +pub use explorer::{Explorer, is_path_gitignored, resolve_outside_root}; pub use file_updater::*; pub use types::*; diff --git a/crates/mcp_client/src/tests.rs b/crates/mcp_client/src/tests.rs index 186828940..c47f23776 100644 --- a/crates/mcp_client/src/tests.rs +++ b/crates/mcp_client/src/tests.rs @@ -129,6 +129,7 @@ fn test_context() -> ToolContext<'static> { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: None, } } diff --git a/crates/mcp_server/src/handler.rs b/crates/mcp_server/src/handler.rs index 94f47fe43..ef7cc52b8 100644 --- a/crates/mcp_server/src/handler.rs +++ b/crates/mcp_server/src/handler.rs @@ -273,6 +273,7 @@ impl MessageHandler { tool_id: None, session_id: None, permission_handler: None, + permissions: None, extensions: Some(&mut services), }; diff --git a/crates/tools_core/src/lib.rs b/crates/tools_core/src/lib.rs index 02f54ab62..3ff54b9e0 100644 --- a/crates/tools_core/src/lib.rs +++ b/crates/tools_core/src/lib.rs @@ -25,9 +25,9 @@ pub mod tool; pub use dyn_tool::{AnyOutput, DynTool}; pub use image::{MAX_IMAGE_EDGE, cap_base64_image, cap_image_data, svg_to_png}; pub use permissions::{ - Clearance, PermissionDecision, PermissionMediator, PermissionRequest, PermissionRequestReason, - PermissionTier, ReviewVerdict, ReviewedCallMediator, ToolCallReview, ToolCallReviewer, - ToolPermissions, + Clearance, FileAccess, PermissionDecision, PermissionMediator, PermissionRequest, + PermissionRequestReason, PermissionTier, ReviewVerdict, ReviewedCallMediator, ToolCallReview, + ToolCallReviewer, ToolPermissions, }; pub use registry::ToolRegistry; pub use render::{ImageData, Render, ResourcesTracker}; diff --git a/crates/tools_core/src/permissions.rs b/crates/tools_core/src/permissions.rs index 54053ba3c..04616e568 100644 --- a/crates/tools_core/src/permissions.rs +++ b/crates/tools_core/src/permissions.rs @@ -5,7 +5,7 @@ use anyhow::Result; use async_trait::async_trait; use serde::{Deserialize, Serialize}; use std::collections::HashSet; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; /// When to ask the user for permission before running a tool. @@ -129,6 +129,9 @@ pub struct ToolPermissions { /// asks the user about every call it would have reviewed. pub reviewer: Option>, granted_tools: Arc>>, + /// Held while a tool asks for an escalation of its own, see + /// [`ToolPermissions::escalation_turn`]. + escalations: Arc>, } impl ToolPermissions { @@ -137,9 +140,17 @@ impl ToolPermissions { tier, reviewer: None, granted_tools: Arc::default(), + escalations: Arc::default(), } } + /// Wait until no other tool call of the session is asking the user for + /// an escalation. Parallel calls so ask one after another, and a call + /// waiting behind an "always (session)" answer passes without asking. + pub async fn escalation_turn(&self) -> tokio::sync::OwnedMutexGuard<()> { + self.escalations.clone().lock_owned().await + } + pub fn is_granted(&self, tool_name: &str) -> bool { self.granted_tools.lock().unwrap().contains(tool_name) } @@ -251,6 +262,13 @@ pub enum PermissionRequestReason<'a> { params: &'a serde_json::Value, reason: &'a str, }, + /// A tool wants to read or write files outside the project it works in. + /// Asked independently of the tier, since the project root is the + /// boundary the file tools otherwise enforce. + OutsideProject { + access: FileAccess, + paths: &'a [PathBuf], + }, /// Approve loading a project's local `.mcp.json`, which launches the MCP /// servers it defines — i.e. runs project-supplied commands. Not tied to a /// tool invocation; raised before a project's registry is built. @@ -260,6 +278,31 @@ pub enum PermissionRequestReason<'a> { }, } +/// What a tool wants to do with files outside its project. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum FileAccess { + Read, + Write, +} + +impl FileAccess { + /// `"read"` or `"write"`, for prompts and request metadata. + pub fn verb(self) -> &'static str { + match self { + FileAccess::Read => "read", + FileAccess::Write => "write", + } + } + + /// `"Read"` or `"Write"`, to start a prompt with. + pub fn label(self) -> &'static str { + match self { + FileAccess::Read => "Read", + FileAccess::Write => "Write", + } + } +} + /// Request payload passed to a [`PermissionMediator`]. #[derive(Debug)] pub struct PermissionRequest<'a> { diff --git a/crates/tools_core/src/tool.rs b/crates/tools_core/src/tool.rs index a910778c6..473106679 100644 --- a/crates/tools_core/src/tool.rs +++ b/crates/tools_core/src/tool.rs @@ -1,7 +1,10 @@ use super::render::Render; use super::result::ToolResult; use super::spec::ToolSpec; -use crate::permissions::PermissionMediator; +use crate::permissions::{ + PermissionDecision, PermissionMediator, PermissionRequest, PermissionRequestReason, + ToolPermissions, +}; use anyhow::{Result, anyhow}; use command_executor::CommandExecutor; use serde::{Deserialize, Serialize, de::DeserializeOwned}; @@ -22,6 +25,9 @@ pub struct ToolContext<'a> { pub session_id: Option, /// Optional permission handler for potentially sensitive operations pub permission_handler: Option<&'a dyn PermissionMediator>, + /// The session's permission state, for tools that ask for escalations + /// of their own and remember an "always (session)" answer. + pub permissions: Option<&'a ToolPermissions>, /// Application-specific services for tools that need more than the fields /// above. Tools downcast this to the concrete type they were registered /// with, keeping the context itself application-agnostic. @@ -42,6 +48,50 @@ impl<'a> ToolContext<'a> { .as_deref_mut() .and_then(|ext| ext.downcast_mut::()) } + + /// Ask the user for an escalation a tool needs regardless of the tier + /// (e.g. reading outside the project). An "always (session)" answer is + /// remembered under `grant_key`, so later requests pass without asking. + /// + /// Returns whether the escalation was granted, or an error when this + /// frontend cannot ask the user. `&mut` for `Send`: the context is not + /// `Sync`. + pub async fn request_escalation( + &mut self, + grant_key: &str, + tool_name: &str, + reason: PermissionRequestReason<'_>, + ) -> Result { + // One question at a time per session; the grant is checked after + // waiting, since the question before may have granted it. + let _turn = match self.permissions { + Some(permissions) => Some(permissions.escalation_turn().await), + None => None, + }; + if self.permissions.is_some_and(|p| p.is_granted(grant_key)) { + return Ok(true); + } + let handler = self + .permission_handler + .ok_or_else(|| anyhow!("This frontend cannot ask the user for permission"))?; + let decision = handler + .request_permission(PermissionRequest { + tool_id: self.tool_id.as_deref(), + tool_name, + reason, + }) + .await?; + Ok(match decision { + PermissionDecision::Denied => false, + PermissionDecision::GrantedOnce => true, + PermissionDecision::GrantedSession | PermissionDecision::GrantedPersistent => { + if let Some(permissions) = self.permissions { + permissions.grant(grant_key); + } + true + } + }) + } } /// Core trait for tools, defining the execution interface @@ -69,3 +119,62 @@ pub trait Tool: Send + Sync + 'static { serde_json::from_value(json).map_err(|e| anyhow!("Failed to deserialize output: {e}")) } } + +#[cfg(test)] +mod escalation_tests { + use super::*; + use crate::permissions::FileAccess; + use std::path::PathBuf; + use std::sync::atomic::{AtomicUsize, Ordering}; + + /// Answers "always (session)" after giving other tasks a chance to run, + /// counting the questions. + struct SlowSessionGrant { + asked: AtomicUsize, + } + + #[async_trait::async_trait] + impl PermissionMediator for SlowSessionGrant { + async fn request_permission( + &self, + _request: PermissionRequest<'_>, + ) -> Result { + self.asked.fetch_add(1, Ordering::SeqCst); + for _ in 0..10 { + tokio::task::yield_now().await; + } + Ok(PermissionDecision::GrantedSession) + } + } + + #[tokio::test] + async fn parallel_escalations_ask_once_when_the_first_answer_grants_the_session() { + let executor = command_executor::DefaultCommandExecutor; + let mediator = SlowSessionGrant { + asked: AtomicUsize::new(0), + }; + let permissions = ToolPermissions::default(); + let paths = [PathBuf::from("/elsewhere")]; + let context = || ToolContext { + command_executor: &executor, + tool_id: None, + session_id: None, + permission_handler: Some(&mediator), + permissions: Some(&permissions), + extensions: None, + }; + let reason = || PermissionRequestReason::OutsideProject { + access: FileAccess::Read, + paths: &paths, + }; + let (mut first, mut second) = (context(), context()); + + let (a, b) = tokio::join!( + first.request_escalation("key", "tool", reason()), + second.request_escalation("key", "tool", reason()), + ); + + assert!(a.unwrap() && b.unwrap()); + assert_eq!(mediator.asked.load(Ordering::SeqCst), 1); + } +} diff --git a/crates/ui_acp/src/permissions.rs b/crates/ui_acp/src/permissions.rs index 63fd0a32f..1cd6d30a7 100644 --- a/crates/ui_acp/src/permissions.rs +++ b/crates/ui_acp/src/permissions.rs @@ -107,6 +107,15 @@ impl AcpPermissionMediator { serde_json::to_string_pretty(params).unwrap_or_else(|_| params.to_string()) ) } + PermissionRequestReason::OutsideProject { access, paths } => format!( + "{} files outside the project:\n{}", + access.label(), + paths + .iter() + .map(|p| p.display().to_string()) + .collect::>() + .join("\n") + ), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, @@ -141,6 +150,11 @@ impl AcpPermissionMediator { "params": params, "reason": reason, }), + PermissionRequestReason::OutsideProject { access, paths } => json!({ + "type": "outside_project", + "access": access.verb(), + "paths": paths.iter().map(|p| p.display().to_string()).collect::>(), + }), PermissionRequestReason::TrustLocalMcp { project_dir, server_names, diff --git a/docs/permission-tiers.md b/docs/permission-tiers.md index 186ce37da..65cd569a5 100644 --- a/docs/permission-tiers.md +++ b/docs/permission-tiers.md @@ -96,6 +96,22 @@ parent gave them. `ask_user_approval` (sandbox bypass) keeps using the mediator directly, independent of the tier — except under `auto`, where a call the reviewer allowed gets its escalation granted (see above). +- **Files outside the project**: the file tools ask before reaching a + path that leads out of the project (absolute, `..`, or a symlink), in + every tier including `bypass-all` — one prompt per call for all such + paths (`PermissionRequestReason::OutsideProject`, shared helper + `tools::impls::outside_project`). Reading (`read_files`, `list_files`, + `search_files`, `glob_files`, `view_images`, `view_documents`) and + writing (`write_file`, `edit`, `replace_in_file`, `delete_files`) are + asked and granted separately (`FileAccess`). *Always (session)* covers + every tool of that kind and is remembered in the session's + `ToolPermissions` (reached by tools through + `ToolContext::request_escalation`). Files written outside get no + format-on-save and no resource events. Without a mediator the access is + rejected as before. Each path is resolved once, before the question, and + the tool uses exactly that path. Parallel calls ask one after another + (`ToolPermissions::escalation_turn`), so a call behind an *always* answer + does not ask again. ## Frontend surfaces