Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions crates/agent_core/src/runtime/tool_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ struct Invocation {
registry: Arc<ToolRegistry>,
command_executor: Arc<dyn CommandExecutor>,
permission_handler: Option<Arc<dyn PermissionMediator>>,
permissions: ToolPermissions,
cancellation: tools_core::RunCancellation,
session_id: Option<String>,
services: Box<dyn Any + Send>,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions crates/code_assistant_core/src/agent/sub_agent/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions crates/code_assistant_core/src/mocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,7 @@ pub struct ToolTestFixture {
tool_id: Option<String>,
session_id: Option<String>,
permission_handler: Option<Arc<dyn PermissionMediator>>,
permissions: tools_core::ToolPermissions,
services: crate::tools::ToolServices,
}

Expand All @@ -1112,6 +1113,7 @@ impl ToolTestFixture {
tool_id: None,
session_id: None,
permission_handler: None,
permissions: tools_core::ToolPermissions::default(),
services,
}
}
Expand Down Expand Up @@ -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),
}
}
Expand Down
43 changes: 43 additions & 0 deletions crates/code_assistant_core/src/session/permissions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,28 @@ pub fn permission_options_for(reason: &PermissionRequestReason<'_>) -> Vec<Permi
"Skip these servers; the agent runs without them",
),
],
PermissionRequestReason::OutsideProject { access, .. } => {
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![
Expand Down Expand Up @@ -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::<Vec<_>>()
.join(", ")
}

/// [`PermissionMediator`] for sessions driven through [`SessionService`]:
/// publishes the request on the event stream and awaits the decision from
/// `respond_permission`.
Expand Down Expand Up @@ -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::<Vec<_>>(),
}),
),
PermissionRequestReason::TrustLocalMcp {
project_dir,
server_names,
Expand Down
7 changes: 7 additions & 0 deletions crates/code_assistant_core/src/tests/format_on_save_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down Expand Up @@ -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),
};

Expand Down
53 changes: 33 additions & 20 deletions crates/code_assistant_core/src/tools/impls/delete_files.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use super::outside_project::Resolved;
use crate::tools::ToolServicesAccess;
use crate::tools::core::{
Render, ResourcesTracker, Tool, ToolContext, ToolResult, ToolSpec, capabilities,
Expand Down Expand Up @@ -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"
}
Expand Down Expand Up @@ -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)
Expand All @@ -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(_) => {
Expand All @@ -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(),
Expand Down Expand Up @@ -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());

Expand Down
43 changes: 24 additions & 19 deletions crates/code_assistant_core/src/tools/impls/edit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
Expand Down Expand Up @@ -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;
}
Expand Down
Loading
Loading