From 8ad6a9d1f1b90b3b779337d9f0c3062fcdf65452 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Thu, 28 May 2026 09:15:27 -0700 Subject: [PATCH 01/11] Add granular per-path write permissions for agent terminal sandbox --- crates/acp_thread/src/terminal.rs | 9 +- crates/agent/src/sandboxing.rs | 160 ++++++++++ crates/agent/src/templates.rs | 3 +- crates/agent/src/templates/system_prompt.hbs | 9 +- crates/agent/src/thread.rs | 98 ++++++ crates/agent/src/tools/terminal_tool.rs | 302 +++++++++++++++---- 6 files changed, 512 insertions(+), 69 deletions(-) diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs index 32496b8f446455..ffe3108a7f5964 100644 --- a/crates/acp_thread/src/terminal.rs +++ b/crates/acp_thread/src/terminal.rs @@ -35,9 +35,15 @@ pub struct SandboxWrap { /// here — *not* the command's working directory, which is model- /// controlled and would let the model widen its own writable scope. pub writable_paths: Vec, + /// Additional write subtrees the user explicitly approved for this + /// command (per-path write grants). Kept separate from `writable_paths` + /// to make the trust boundary explicit: these originate from + /// model-requested paths that passed a user-approval prompt. They are + /// merged with `writable_paths` when generating the sandbox policy. + pub extra_write_paths: Vec, /// Allow outbound network access for this command. pub allow_network: bool, - /// Allow unrestricted filesystem writes (ignores `writable_paths`). + /// Allow unrestricted filesystem writes (ignores all writable paths). pub allow_fs_write: bool, } @@ -70,6 +76,7 @@ pub(crate) fn apply_sandbox_wrap( let writable: Vec<&std::path::Path> = sandbox_wrap .writable_paths .iter() + .chain(sandbox_wrap.extra_write_paths.iter()) .map(|p| p.as_path()) .collect(); let permissions = sandbox::macos_seatbelt::SandboxPermissions { diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index a0a6a17377fb39..b488ec11d1831a 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -17,9 +17,169 @@ use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag}; use gpui::App; +use std::path::PathBuf; /// Whether agent-run terminal commands should be wrapped in an OS-level /// sandbox for this process. See module docs for the policy. pub(crate) fn sandboxing_enabled(cx: &App) -> bool { cfg!(target_os = "macos") && cx.has_flag::() } + +/// A request for elevated sandbox permissions for a single terminal command. +/// +/// Built from the model-controlled `terminal` tool input after the user has +/// authorized the baseline command. All paths here have already been resolved +/// to absolute, canonicalized paths by the caller — never raw, model-provided +/// strings, and never the model-controlled working directory. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct SandboxRequest { + /// Allow outbound network access for this command. + pub network: bool, + /// Allow unrestricted filesystem writes (the broad escape hatch). + pub allow_fs_write_all: bool, + /// Concrete paths the command needs to write to. Each grants its whole + /// subtree. These are never globs — write access is always a concrete + /// path subtree (mirroring Codex's model). + pub write_paths: Vec, +} + +impl SandboxRequest { + /// Whether this request asks for anything beyond the default sandbox + /// scope, and therefore needs user approval. + pub fn needs_escalation(&self) -> bool { + self.network || self.allow_fs_write_all || !self.write_paths.is_empty() + } +} + +/// In-memory record of the sandbox permissions the user approved "for the +/// rest of the conversation". +/// +/// Lives on the `Thread` and is shared (via `Rc>`) with each tool +/// call's event stream so a later command requesting an already-granted +/// permission can skip the approval prompt. This is deliberately **never** +/// persisted to settings — it dies with the conversation, unlike the global +/// `always_allow` tool-permission rules. +#[derive(Default)] +pub(crate) struct ConversationSandboxGrants { + network: bool, + allow_fs_write_all: bool, + /// Canonicalized paths granted write access for the conversation. Each + /// covers its whole subtree; redundant children are pruned on insert. + write_paths: Vec, +} + +impl ConversationSandboxGrants { + /// Whether everything `request` asks for has already been granted for the + /// conversation, so the command can run without prompting again. + /// + /// Write coverage is pure subtree containment (Codex-style): every + /// requested path must sit under some granted path. This is fully + /// deterministic and never widens scope, because grants are concrete + /// paths rather than globs. + pub fn covers(&self, request: &SandboxRequest) -> bool { + if request.network && !self.network { + return false; + } + if request.allow_fs_write_all && !self.allow_fs_write_all { + return false; + } + // A conversation-wide all-access write grant covers any concrete + // write request. + if self.allow_fs_write_all { + return true; + } + request.write_paths.iter().all(|requested| { + self.write_paths + .iter() + .any(|granted| requested.starts_with(granted)) + }) + } + + /// Record everything in `request` as granted for the rest of the + /// conversation, pruning paths that become redundant. + pub fn record(&mut self, request: &SandboxRequest) { + self.network |= request.network; + self.allow_fs_write_all |= request.allow_fs_write_all; + for path in &request.write_paths { + // Already covered by an existing (broader or equal) grant. + if self + .write_paths + .iter() + .any(|granted| path.starts_with(granted)) + { + continue; + } + // Drop any existing grants that are now subsumed by this path. + self.write_paths + .retain(|granted| !granted.starts_with(path)); + self.write_paths.push(path.clone()); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(network: bool, all: bool, paths: &[&str]) -> SandboxRequest { + SandboxRequest { + network, + allow_fs_write_all: all, + write_paths: paths.iter().map(PathBuf::from).collect(), + } + } + + #[test] + fn empty_grants_cover_nothing() { + let grants = ConversationSandboxGrants::default(); + assert!(!grants.covers(&request(true, false, &[]))); + assert!(!grants.covers(&request(false, true, &[]))); + assert!(!grants.covers(&request(false, false, &["/tmp/build"]))); + } + + #[test] + fn subtree_containment_covers_children() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, false, &["/tmp/build"])); + + // Exact match and any descendant are covered. + assert!(grants.covers(&request(false, false, &["/tmp/build"]))); + assert!(grants.covers(&request(false, false, &["/tmp/build/cache"]))); + // A sibling / parent is not. + assert!(!grants.covers(&request(false, false, &["/tmp/other"]))); + assert!(!grants.covers(&request(false, false, &["/tmp"]))); + } + + #[test] + fn record_prunes_redundant_children() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, false, &["/tmp/build/cache"])); + grants.record(&request(false, false, &["/tmp/build"])); + assert_eq!(grants.write_paths, vec![PathBuf::from("/tmp/build")]); + } + + #[test] + fn record_keeps_existing_broader_grant() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, false, &["/tmp/build"])); + grants.record(&request(false, false, &["/tmp/build/cache"])); + assert_eq!(grants.write_paths, vec![PathBuf::from("/tmp/build")]); + } + + #[test] + fn all_access_covers_any_concrete_write() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, true, &[])); + assert!(grants.covers(&request(false, false, &["/anywhere/at/all"]))); + // But not network, which wasn't granted. + assert!(!grants.covers(&request(true, false, &[]))); + } + + #[test] + fn network_grant_tracked_independently() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(true, false, &[])); + assert!(grants.covers(&request(true, false, &[]))); + assert!(!grants.covers(&request(true, false, &["/tmp/build"]))); + } +} diff --git a/crates/agent/src/templates.rs b/crates/agent/src/templates.rs index 0d3e617d01c9b5..e9a4b80a392d88 100644 --- a/crates/agent/src/templates.rs +++ b/crates/agent/src/templates.rs @@ -193,7 +193,8 @@ mod tests { assert!(rendered.contains("`/tmp/alpha`")); assert!(rendered.contains("`/tmp/beta`")); assert!(rendered.contains("allow_network: true")); - assert!(rendered.contains("allow_fs_write: true")); + assert!(rendered.contains("fs_write_paths")); + assert!(rendered.contains("allow_fs_write_all: true")); assert!(rendered.contains("unsandboxed: true")); assert!(rendered.contains("remain in effect for the entire duration")); } diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbs index 7326937ab0980d..aaba183dde2de9 100644 --- a/crates/agent/src/templates/system_prompt.hbs +++ b/crates/agent/src/templates/system_prompt.hbs @@ -200,7 +200,14 @@ The `terminal` tool runs commands inside a sandbox with these permissions: Writes anywhere else on the filesystem are blocked.{{else}}. No project directories are currently writable.{{/if}} - Network: outbound network access is blocked. -You can request elevated permissions on individual `terminal` calls by setting `allow_network: true`, `allow_fs_write: true`, or `unsandboxed: true`. The user will be prompted to approve before the command runs. +You can request elevated permissions on individual `terminal` calls: + +- `allow_network: true` — allow outbound network access. +- `fs_write_paths: ["/abs/or/worktree-relative/path", ...]` — allow writes to specific paths (each directory grants its whole subtree). Prefer this whenever you know which paths the command needs to write. +- `allow_fs_write_all: true` — allow unrestricted filesystem writes. Only use this when the specific paths can't be enumerated up front. +- `unsandboxed: true` — run the command with no sandbox at all. Use only when none of the above suffice. + +The user will be prompted to approve before the command runs, and can grant a write request either just for that command or for the rest of the conversation. Once a write path is granted for the conversation, later commands writing under that path won't prompt again. These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told. diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 5eb2c170a12388..1138d99c34ff62 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -14,6 +14,7 @@ use feature_flags::{ UpdateTitleToolFeatureFlag, }; +use crate::sandboxing::{ConversationSandboxGrants, SandboxRequest}; use agent_client_protocol::schema as acp; use agent_settings::{ AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, @@ -51,6 +52,7 @@ use serde::{Deserialize, Serialize}; use settings::{ LanguageModelSelection, Settings, SettingsStore, ToolPermissionMode, update_settings_file, }; +use std::cell::RefCell; use std::fmt::Write; use std::{ collections::BTreeMap, @@ -1008,6 +1010,11 @@ pub struct Thread { running_subagents: Vec>, inherits_parent_model_settings: bool, sandboxed_terminal_temp_dir: Option, + /// Sandbox permissions the user approved "for the rest of the + /// conversation". Shared with each tool call's event stream so repeated + /// requests for already-granted permissions skip the approval prompt. + /// Never persisted — lives and dies with this thread. + sandbox_grants: Rc>, } impl Thread { @@ -1135,6 +1142,7 @@ impl Thread { running_subagents: Vec::new(), inherits_parent_model_settings: true, sandboxed_terminal_temp_dir: None, + sandbox_grants: Rc::new(RefCell::new(ConversationSandboxGrants::default())), } } @@ -1328,6 +1336,7 @@ impl Thread { stream.clone(), Some(self.project.read(cx).fs().clone()), cancellation_rx, + self.sandbox_grants.clone(), ); tool.replay(tool_use.input.clone(), output, tool_event_stream, cx) .log_err(); @@ -1478,6 +1487,7 @@ impl Thread { running_subagents: Vec::new(), inherits_parent_model_settings: true, sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir, + sandbox_grants: Rc::new(RefCell::new(ConversationSandboxGrants::default())), } } @@ -2581,6 +2591,7 @@ impl Thread { event_stream.clone(), Some(fs), cancellation_rx, + self.sandbox_grants.clone(), ); tool_event_stream.update_fields( acp::ToolCallUpdateFields::new().status(acp::ToolCallStatus::InProgress), @@ -3833,6 +3844,8 @@ pub struct ToolCallEventStream { stream: ThreadEventStream, fs: Option>, cancellation_rx: watch::Receiver, + /// Shared, conversation-scoped sandbox grants (see [`Thread::sandbox_grants`]). + sandbox_grants: Rc>, } impl ToolCallEventStream { @@ -3852,6 +3865,7 @@ impl ToolCallEventStream { ThreadEventStream(events_tx), None, cancellation_rx, + Rc::new(RefCell::new(ConversationSandboxGrants::default())), ); ( @@ -3872,12 +3886,14 @@ impl ToolCallEventStream { stream: ThreadEventStream, fs: Option>, cancellation_rx: watch::Receiver, + sandbox_grants: Rc>, ) -> Self { Self { tool_use_id, stream, fs, cancellation_rx, + sandbox_grants, } } @@ -4060,6 +4076,88 @@ impl ToolCallEventStream { self.run_authorization_loop(title, options, Some(context), None, cx) } + /// Gate a sandbox *escalation* (network access, per-path writes, or full + /// filesystem write access) on user approval. + /// + /// Unlike [`Self::authorize`] / [`Self::authorize_always_prompt`], the + /// decision is never read from or written to settings. Instead it offers + /// the user two grant lifetimes — "once" and "for the rest of this + /// conversation" — and records conversation grants in the shared, + /// in-memory [`ConversationSandboxGrants`]. A request already covered by + /// a prior conversation grant resolves immediately without prompting. + pub(crate) fn authorize_sandbox( + &self, + title: impl Into, + request: SandboxRequest, + cx: &mut App, + ) -> Task> { + // Already approved for this conversation — run without prompting. + if self.sandbox_grants.borrow().covers(&request) { + return Task::ready(Ok(())); + } + + let title = title.into(); + let options = acp_thread::PermissionOptions::Flat(vec![ + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow"), + "Allow once", + acp::PermissionOptionKind::AllowOnce, + ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow_conversation"), + "Allow for this conversation", + acp::PermissionOptionKind::AllowAlways, + ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("deny"), + "Deny", + acp::PermissionOptionKind::RejectOnce, + ), + ]); + + let stream = self.stream.clone(); + let tool_use_id = self.tool_use_id.clone(); + let sandbox_grants = self.sandbox_grants.clone(); + cx.spawn(async move |_cx| { + let (response_tx, response_rx) = oneshot::channel(); + if let Err(error) = stream + .0 + .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization( + ToolCallAuthorization { + tool_call: acp::ToolCallUpdate::new( + tool_use_id.to_string(), + acp::ToolCallUpdateFields::new().title(title), + ), + options, + response: response_tx, + context: None, + kind: acp_thread::AuthorizationKind::PermissionGrant, + }, + ))) + { + log::error!("Failed to send sandbox authorization: {error}"); + return Err(anyhow!("Failed to send sandbox authorization: {error}")); + } + + let outcome = response_rx + .await + .map_err(|_| anyhow!("authorization channel closed"))?; + + match outcome.option_id.0.as_ref() { + "allow" => Ok(()), + "allow_conversation" => { + sandbox_grants.borrow_mut().record(&request); + Ok(()) + } + "deny" => Err(anyhow!("Permission to run tool denied by user")), + other => { + debug_assert!(false, "unexpected sandbox permission option_id: {other}"); + Err(anyhow!("Permission to run tool denied by user")) + } + } + }) + } + /// Prompts the user to choose between an explicit set of actions and /// returns the chosen `option_id`. /// diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 9944b57e0bd88f..e0df60832de0c4 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -59,24 +59,37 @@ pub struct TerminalToolInput { /// to approve before the command runs. #[serde(default)] pub allow_network: Option, - /// Request unrestricted filesystem-write access for this command. + /// Request write access to specific paths for this command. /// /// Only meaningful when the system prompt's "Terminal sandbox" section /// is present — ignored otherwise. By default sandboxed commands can /// only write to the project worktree directories and a per-command - /// temporary directory; set this to `true` only when the command - /// needs to write elsewhere. The user will be prompted to approve - /// before the command runs. + /// temporary directory. List the absolute (or worktree-relative) paths + /// the command needs to write to here; each directory grants write + /// access to its whole subtree. Prefer this over `allow_fs_write_all` + /// whenever the set of paths is known. The user will be prompted to + /// approve before the command runs, and can grant access for just this + /// command or for the rest of the conversation. #[serde(default)] - pub allow_fs_write: Option, + pub fs_write_paths: Vec, + /// Request unrestricted filesystem-write access for this command. + /// + /// Only meaningful when the system prompt's "Terminal sandbox" section + /// is present — ignored otherwise. This is the broad escape hatch: use + /// it only when the specific paths to write can't be enumerated up + /// front; otherwise prefer `fs_write_paths`. The user will be prompted + /// to approve before the command runs. + #[serde(default)] + pub allow_fs_write_all: Option, /// Request to run this command outside the sandbox entirely. /// /// Only meaningful when the system prompt's "Terminal sandbox" section - /// is present — ignored otherwise. Prefer `allow_network: true` or - /// `allow_fs_write: true` when one of those is enough. Set this to - /// `true` ONLY when the command needs behavior that the sandbox can't - /// grant on a per-permission basis. The user will be prompted to - /// approve before the command runs without sandbox restrictions. + /// is present — ignored otherwise. Prefer `allow_network: true`, + /// `fs_write_paths`, or `allow_fs_write_all: true` when one of those is + /// enough. Set this to `true` ONLY when the command needs behavior that + /// the sandbox can't grant on a per-permission basis. The user will be + /// prompted to approve before the command runs without sandbox + /// restrictions. #[serde(default)] pub unsandboxed: Option, } @@ -144,37 +157,68 @@ impl AgentTool for TerminalTool { // change runtime behavior by setting flags described as a no-op // in the system prompt. let want_network = sandboxing && input.allow_network == Some(true); - let want_fs_write = sandboxing && input.allow_fs_write == Some(true); + let want_fs_write_all = sandboxing && input.allow_fs_write_all == Some(true); let want_unsandboxed = sandboxing && input.unsandboxed == Some(true); - // `unsandboxed: true` bypasses the wrap entirely; per-permission - // requests are only meaningful when the command is still being - // sandboxed. - let escalate = !want_unsandboxed && (want_network || want_fs_write); + // Resolve the requested write paths against the project up front: + // we need them both for the approval prompt and the sandbox + // policy. Skipped when running unsandboxed (no wrap is applied) + // or when sandboxing is off (the flags are a no-op). Resolution + // is done against the project worktrees / working directory, and + // the user approves the concrete resolved paths. + let write_paths: Vec = if sandboxing && !want_unsandboxed { + cx.update(|cx| { + resolve_write_paths( + &input.fs_write_paths, + working_dir.as_deref(), + &self.project, + cx, + ) + }) + } else { + Vec::new() + }; - if want_unsandboxed || escalate { - let title = sandbox_approval_title(want_network, want_fs_write, want_unsandboxed); + // `unsandboxed: true` bypasses the wrap entirely, so the + // per-permission requests below are moot — it gets its own, + // always-prompt confirmation as the strongest trust boundary. + if want_unsandboxed { let approve = cx.update(|cx| { let context = crate::ToolPermissionContext::new( Self::NAME, vec![input.command.clone()], ); - // Sandbox escalations always prompt, even if the user - // has `always_allow` rules for this command — the - // escalation is a stronger trust boundary than the - // baseline command approval. - event_stream.authorize_always_prompt(title, context, cx) + event_stream.authorize_always_prompt( + "Allow this command to run outside the sandbox?", + context, + cx, + ) }); if let Err(error) = approve.await { - return Ok(if want_unsandboxed { - format!( - "Command cancelled: user denied permission to run outside the sandbox ({error})." - ) - } else { - format!( + return Ok(format!( + "Command cancelled: user denied permission to run outside the sandbox ({error})." + )); + } + } else { + let request = crate::sandboxing::SandboxRequest { + network: want_network, + allow_fs_write_all: want_fs_write_all, + write_paths: write_paths.clone(), + }; + if request.needs_escalation() { + let title = sandbox_approval_title(&request); + // Sandbox escalations always prompt (unless already + // granted for the conversation), independent of any + // `always_allow` tool-permission rules — the escalation + // is a stronger trust boundary than the baseline command + // approval. + let approve = + cx.update(|cx| event_stream.authorize_sandbox(title, request, cx)); + if let Err(error) = approve.await { + return Ok(format!( "Command cancelled: user denied the requested sandbox permissions ({error})." - ) - }); + )); + } } } @@ -205,8 +249,9 @@ impl AgentTool for TerminalTool { }); Some(acp_thread::SandboxWrap { writable_paths, + extra_write_paths: write_paths, allow_network: want_network, - allow_fs_write: want_fs_write, + allow_fs_write: want_fs_write_all, }) } else { None @@ -288,26 +333,87 @@ impl AgentTool for TerminalTool { } } -/// User-facing title for the sandbox-escalation approval prompt. +/// Resolve model-requested write paths into absolute paths. /// -/// `want_unsandboxed` wins over the per-permission flags because -/// `unsandboxed: true` bypasses the per-permission machinery entirely. -fn sandbox_approval_title( - want_network: bool, - want_fs_write: bool, - want_unsandboxed: bool, -) -> &'static str { - if want_unsandboxed { - "Allow this command to run outside the sandbox?" +/// Relative paths are resolved against the command's working directory when +/// known, otherwise against the project's first worktree root. Paths that +/// can't be made absolute (relative paths with no base) are dropped. The +/// resulting paths are shown to the user for approval, so resolving against +/// model-controlled inputs is safe — nothing is granted without that prompt. +fn resolve_write_paths( + raw_paths: &[String], + working_dir: Option<&Path>, + project: &Entity, + cx: &App, +) -> Vec { + if raw_paths.is_empty() { + return Vec::new(); + } + let base = working_dir.map(Path::to_path_buf).or_else(|| { + project + .read(cx) + .worktrees(cx) + .next() + .map(|worktree| worktree.read(cx).abs_path().to_path_buf()) + }); + join_write_paths(raw_paths, base.as_deref()) +} + +/// Pure path-joining step of [`resolve_write_paths`], split out so it can be +/// unit-tested without a `Project`/`App`. +fn join_write_paths(raw_paths: &[String], base: Option<&Path>) -> Vec { + raw_paths + .iter() + .filter_map(|raw| { + let path = Path::new(raw); + if path.is_absolute() { + Some(path.to_path_buf()) + } else { + base.map(|base| base.join(path)) + } + }) + .collect() +} + +/// User-facing title for the sandbox-escalation approval prompt. Only called +/// when the request actually asks for something (see +/// [`crate::sandboxing::SandboxRequest::needs_escalation`]). +fn sandbox_approval_title(request: &crate::sandboxing::SandboxRequest) -> String { + let mut parts: Vec = Vec::new(); + if request.network { + parts.push("network access".to_string()); + } + if request.allow_fs_write_all { + parts.push("unrestricted filesystem writes".to_string()); + } else if !request.write_paths.is_empty() { + parts.push(format!( + "write access to {}", + describe_paths(&request.write_paths) + )); + } + match parts.as_slice() { + // Unreachable in practice: the caller only prompts when at least one + // permission is requested. + [] => "Allow this command extra permissions?".to_string(), + [only] => format!("Allow {only}?"), + [first, second] => format!("Allow {first} and {second}?"), + _ => format!("Allow {}?", parts.join(", ")), + } +} + +/// Render a short, human-readable summary of requested write paths for the +/// approval prompt, capping the number listed so the title stays readable. +fn describe_paths(paths: &[PathBuf]) -> String { + const MAX_SHOWN: usize = 3; + let shown: Vec = paths + .iter() + .take(MAX_SHOWN) + .map(|path| path.display().to_string()) + .collect(); + if paths.len() > MAX_SHOWN { + format!("{} (+{} more)", shown.join(", "), paths.len() - MAX_SHOWN) } else { - match (want_network, want_fs_write) { - (true, true) => "Allow network access and arbitrary filesystem writes?", - (true, false) => "Allow network access?", - (false, true) => "Allow arbitrary filesystem writes?", - // Caller only invokes this when at least one flag is set, so - // this fallback is unreachable in practice. - (false, false) => "Allow this command to run?", - } + shown.join(", ") } } @@ -1572,33 +1678,92 @@ mod tests { ); } + fn sandbox_request( + network: bool, + all: bool, + paths: &[&str], + ) -> crate::sandboxing::SandboxRequest { + crate::sandboxing::SandboxRequest { + network, + allow_fs_write_all: all, + write_paths: paths.iter().map(PathBuf::from).collect(), + } + } + #[test] - fn test_sandbox_approval_title_unsandboxed_wins() { - // `unsandboxed: true` skips the sandbox entirely, so the title should - // reflect that even when other flags are also set — they're moot. - assert_eq!( - sandbox_approval_title(true, true, true), - "Allow this command to run outside the sandbox?" + fn test_join_write_paths_resolves_relative_and_absolute() { + let base = PathBuf::from("/project"); + let joined = join_write_paths( + &[ + "/abs/path".to_string(), + "relative/dir".to_string(), + "file.txt".to_string(), + ], + Some(base.as_path()), ); assert_eq!( - sandbox_approval_title(false, false, true), - "Allow this command to run outside the sandbox?" + joined, + vec![ + PathBuf::from("/abs/path"), + PathBuf::from("/project/relative/dir"), + PathBuf::from("/project/file.txt"), + ] ); } #[test] - fn test_sandbox_approval_title_per_permission_flags() { + fn test_join_write_paths_drops_relative_without_base() { + // Absolute paths still pass through; relative ones are dropped when + // there's no base to resolve them against. + let joined = join_write_paths( + &["/abs/keep".to_string(), "relative/drop".to_string()], + None, + ); + assert_eq!(joined, vec![PathBuf::from("/abs/keep")]); + } + + #[test] + fn test_sandbox_approval_title_all_access_and_network() { assert_eq!( - sandbox_approval_title(true, true, false), - "Allow network access and arbitrary filesystem writes?" + sandbox_approval_title(&sandbox_request(true, true, &[])), + "Allow network access and unrestricted filesystem writes?" ); assert_eq!( - sandbox_approval_title(true, false, false), + sandbox_approval_title(&sandbox_request(true, false, &[])), "Allow network access?" ); assert_eq!( - sandbox_approval_title(false, true, false), - "Allow arbitrary filesystem writes?" + sandbox_approval_title(&sandbox_request(false, true, &[])), + "Allow unrestricted filesystem writes?" + ); + } + + #[test] + fn test_sandbox_approval_title_per_path_writes() { + assert_eq!( + sandbox_approval_title(&sandbox_request(false, false, &["/tmp/build"])), + "Allow write access to /tmp/build?" + ); + assert_eq!( + sandbox_approval_title(&sandbox_request(true, false, &["/tmp/build"])), + "Allow network access and write access to /tmp/build?" + ); + } + + #[test] + fn test_sandbox_approval_title_caps_listed_paths() { + let title = + sandbox_approval_title(&sandbox_request(false, false, &["/a", "/b", "/c", "/d"])); + assert_eq!(title, "Allow write access to /a, /b, /c (+1 more)?"); + } + + #[test] + fn test_all_access_takes_precedence_over_paths_in_title() { + // When all-access is requested, the specific paths are redundant and + // should not be listed. + assert_eq!( + sandbox_approval_title(&sandbox_request(false, true, &["/tmp/build"])), + "Allow unrestricted filesystem writes?" ); } @@ -1615,8 +1780,12 @@ mod tests { "schema should advertise allow_network: {schema}" ); assert!( - schema.contains("allow_fs_write"), - "schema should advertise allow_fs_write: {schema}" + schema.contains("fs_write_paths"), + "schema should advertise fs_write_paths: {schema}" + ); + assert!( + schema.contains("allow_fs_write_all"), + "schema should advertise allow_fs_write_all: {schema}" ); assert!( schema.contains("unsandboxed"), @@ -1636,7 +1805,8 @@ mod tests { })) .expect("minimal input should deserialize"); assert_eq!(input.allow_network, None); - assert_eq!(input.allow_fs_write, None); + assert!(input.fs_write_paths.is_empty()); + assert_eq!(input.allow_fs_write_all, None); assert_eq!(input.unsandboxed, None); } } From 39028efe05bf39a88d6c945a86f3a8b599072ec3 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Thu, 28 May 2026 09:28:50 -0700 Subject: [PATCH 02/11] improve how allow for conversation works --- crates/agent/src/sandboxing.rs | 85 ++++++++++++++++++++----- crates/agent/src/thread.rs | 12 ++++ crates/agent/src/tools/terminal_tool.rs | 51 ++++++++------- 3 files changed, 109 insertions(+), 39 deletions(-) diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index b488ec11d1831a..5915b74df7ce3c 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -38,8 +38,7 @@ pub(crate) struct SandboxRequest { /// Allow unrestricted filesystem writes (the broad escape hatch). pub allow_fs_write_all: bool, /// Concrete paths the command needs to write to. Each grants its whole - /// subtree. These are never globs — write access is always a concrete - /// path subtree (mirroring Codex's model). + /// subtree. These are never globs — write access is always a concrete path subtree pub write_paths: Vec, } @@ -72,7 +71,7 @@ impl ConversationSandboxGrants { /// Whether everything `request` asks for has already been granted for the /// conversation, so the command can run without prompting again. /// - /// Write coverage is pure subtree containment (Codex-style): every + /// Write coverage is pure subtree containment: every /// requested path must sit under some granted path. This is fully /// deterministic and never widens scope, because grants are concrete /// paths rather than globs. @@ -101,22 +100,43 @@ impl ConversationSandboxGrants { self.network |= request.network; self.allow_fs_write_all |= request.allow_fs_write_all; for path in &request.write_paths { - // Already covered by an existing (broader or equal) grant. - if self - .write_paths - .iter() - .any(|granted| path.starts_with(granted)) - { - continue; - } - // Drop any existing grants that are now subsumed by this path. - self.write_paths - .retain(|granted| !granted.starts_with(path)); - self.write_paths.push(path.clone()); + add_write_path(&mut self.write_paths, path); + } + } + + /// Compute the effective sandbox permissions to actually enforce for a + /// command: the union of everything granted for the conversation and + /// what this specific command requested. + /// + /// This is what makes a conversation grant "stick": every sandboxed + /// command applies the accumulated grants, so the model can write to a + /// previously approved path without re-requesting it. Passing the current `request` in + /// also covers "allow once" grants, which are enforced for this command + /// without being recorded for the conversation. + pub fn effective(&self, request: &SandboxRequest) -> SandboxRequest { + let mut write_paths = self.write_paths.clone(); + for path in &request.write_paths { + add_write_path(&mut write_paths, path); + } + SandboxRequest { + network: self.network || request.network, + allow_fs_write_all: self.allow_fs_write_all || request.allow_fs_write_all, + write_paths, } } } +/// Insert `path` into a set of write-grant subtrees, keeping it minimal: +/// a no-op if already covered by a broader grant, otherwise added with any +/// now-subsumed child grants pruned. +fn add_write_path(write_paths: &mut Vec, path: &std::path::Path) { + if write_paths.iter().any(|granted| path.starts_with(granted)) { + return; + } + write_paths.retain(|granted| !granted.starts_with(path)); + write_paths.push(path.to_path_buf()); +} + #[cfg(test)] mod tests { use super::*; @@ -182,4 +202,39 @@ mod tests { assert!(grants.covers(&request(true, false, &[]))); assert!(!grants.covers(&request(true, false, &["/tmp/build"]))); } + + #[test] + fn effective_applies_conversation_grants_to_empty_request() { + // The core fix: a command that requests nothing still gets the + // conversation's granted write paths in its enforced policy. + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, false, &["/tmp/build"])); + + let effective = grants.effective(&request(false, false, &[])); + assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); + } + + #[test] + fn effective_unions_grants_with_once_request() { + // An "allow once" path (passed via `request`, never recorded) is + // enforced for this command alongside the standing grants. + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(true, false, &["/tmp/build"])); + + let effective = grants.effective(&request(false, false, &["/tmp/once"])); + assert!(effective.network); + assert_eq!( + effective.write_paths, + vec![PathBuf::from("/tmp/build"), PathBuf::from("/tmp/once")] + ); + } + + #[test] + fn effective_dedupes_request_already_covered_by_grant() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(false, false, &["/tmp/build"])); + + let effective = grants.effective(&request(false, false, &["/tmp/build/cache"])); + assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); + } } diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 1138d99c34ff62..7868d523746301 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -4158,6 +4158,18 @@ impl ToolCallEventStream { }) } + /// The sandbox permissions to actually enforce for a command: the union + /// of this command's `request` and everything granted "for the rest of + /// the conversation". + /// + /// Callers must apply this to the enforced sandbox policy (rather than + /// the raw `request`) so a conversation grant keeps working for later + /// commands that write to a previously approved path without + /// re-requesting it. + pub(crate) fn effective_sandbox_request(&self, request: &SandboxRequest) -> SandboxRequest { + self.sandbox_grants.borrow().effective(request) + } + /// Prompts the user to choose between an explicit set of actions and /// returns the chosen `option_id`. /// diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index e0df60832de0c4..f9b28cc6caeaff 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -179,8 +179,14 @@ impl AgentTool for TerminalTool { Vec::new() }; + let request = crate::sandboxing::SandboxRequest { + network: want_network, + allow_fs_write_all: want_fs_write_all, + write_paths, + }; + // `unsandboxed: true` bypasses the wrap entirely, so the - // per-permission requests below are moot — it gets its own, + // per-permission requests are moot — it gets its own, // always-prompt confirmation as the strongest trust boundary. if want_unsandboxed { let approve = cx.update(|cx| { @@ -199,26 +205,18 @@ impl AgentTool for TerminalTool { "Command cancelled: user denied permission to run outside the sandbox ({error})." )); } - } else { - let request = crate::sandboxing::SandboxRequest { - network: want_network, - allow_fs_write_all: want_fs_write_all, - write_paths: write_paths.clone(), - }; - if request.needs_escalation() { - let title = sandbox_approval_title(&request); - // Sandbox escalations always prompt (unless already - // granted for the conversation), independent of any - // `always_allow` tool-permission rules — the escalation - // is a stronger trust boundary than the baseline command - // approval. - let approve = - cx.update(|cx| event_stream.authorize_sandbox(title, request, cx)); - if let Err(error) = approve.await { - return Ok(format!( - "Command cancelled: user denied the requested sandbox permissions ({error})." - )); - } + } else if request.needs_escalation() { + let title = sandbox_approval_title(&request); + // Sandbox escalations always prompt (unless already granted + // for the conversation), independent of any `always_allow` + // tool-permission rules — the escalation is a stronger trust + // boundary than the baseline command approval. + let approve = + cx.update(|cx| event_stream.authorize_sandbox(title, request.clone(), cx)); + if let Err(error) = approve.await { + return Ok(format!( + "Command cancelled: user denied the requested sandbox permissions ({error})." + )); } } @@ -240,6 +238,11 @@ impl AgentTool for TerminalTool { // let the model widen its own write permissions outside the // project. let sandbox_wrap = if sandboxing && !want_unsandboxed { + // Apply the conversation's standing grants on top of this + // command's request, so a path approved "for the rest of the + // conversation" stays writable for later commands even when + // the model doesn't re-request it. + let effective = event_stream.effective_sandbox_request(&request); let writable_paths: Vec = cx.update(|cx| { self.project .read(cx) @@ -249,9 +252,9 @@ impl AgentTool for TerminalTool { }); Some(acp_thread::SandboxWrap { writable_paths, - extra_write_paths: write_paths, - allow_network: want_network, - allow_fs_write: want_fs_write_all, + extra_write_paths: effective.write_paths, + allow_network: effective.network, + allow_fs_write: effective.allow_fs_write_all, }) } else { None From 06a55e08c353b167751cdde5b99828134d41f107 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Thu, 28 May 2026 09:51:06 -0700 Subject: [PATCH 03/11] Make terminal sandbox param descriptions instructive to the model --- crates/agent/src/tools/terminal_tool.rs | 61 +++++++++++++------------ 1 file changed, 31 insertions(+), 30 deletions(-) diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index f9b28cc6caeaff..5aec83bdcc5f52 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -50,46 +50,47 @@ pub struct TerminalToolInput { pub cd: String, /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed. pub timeout_ms: Option, - /// Request network access for this command. + /// Set to `true` only if the command needs outbound network access. /// - /// Only meaningful when the system prompt's "Terminal sandbox" section - /// is present — ignored otherwise. By default sandboxed commands - /// cannot make outbound network connections; set this to `true` only - /// when the command needs network access. The user will be prompted - /// to approve before the command runs. + /// Only relevant when the system prompt includes a "Terminal sandbox" + /// section; otherwise leave unset. Sandboxed commands cannot reach the + /// network by default, so set this when running commands that fetch or + /// upload (installing dependencies, cloning, pushing, downloading, + /// etc.). Requesting it triggers a user approval prompt, so only set it + /// when you expect the command to need network. #[serde(default)] pub allow_network: Option, - /// Request write access to specific paths for this command. + /// Paths the command needs to write to outside the default-writable + /// locations. /// - /// Only meaningful when the system prompt's "Terminal sandbox" section - /// is present — ignored otherwise. By default sandboxed commands can - /// only write to the project worktree directories and a per-command - /// temporary directory. List the absolute (or worktree-relative) paths - /// the command needs to write to here; each directory grants write - /// access to its whole subtree. Prefer this over `allow_fs_write_all` - /// whenever the set of paths is known. The user will be prompted to - /// approve before the command runs, and can grant access for just this - /// command or for the rest of the conversation. + /// Only relevant when the system prompt includes a "Terminal sandbox" + /// section; otherwise leave empty. Sandboxed commands can already write + /// to the project worktree directories and a per-command temporary + /// directory, so only list paths outside those. Provide absolute or + /// worktree-relative paths; each directory grants write access to its + /// whole subtree. Prefer this over `allow_fs_write_all` whenever you can + /// enumerate the paths. Requesting paths triggers a user approval + /// prompt. #[serde(default)] pub fs_write_paths: Vec, - /// Request unrestricted filesystem-write access for this command. + /// Set to `true` only when the command needs to write outside the + /// default-writable locations but the specific paths cannot be + /// enumerated up front. /// - /// Only meaningful when the system prompt's "Terminal sandbox" section - /// is present — ignored otherwise. This is the broad escape hatch: use - /// it only when the specific paths to write can't be enumerated up - /// front; otherwise prefer `fs_write_paths`. The user will be prompted - /// to approve before the command runs. + /// Only relevant when the system prompt includes a "Terminal sandbox" + /// section; otherwise leave unset. This is a broad escape hatch — prefer + /// `fs_write_paths` whenever the set of paths is known. Requesting it + /// triggers a user approval prompt. #[serde(default)] pub allow_fs_write_all: Option, - /// Request to run this command outside the sandbox entirely. + /// Set to `true` only as a last resort, to run the command fully outside + /// the sandbox. /// - /// Only meaningful when the system prompt's "Terminal sandbox" section - /// is present — ignored otherwise. Prefer `allow_network: true`, - /// `fs_write_paths`, or `allow_fs_write_all: true` when one of those is - /// enough. Set this to `true` ONLY when the command needs behavior that - /// the sandbox can't grant on a per-permission basis. The user will be - /// prompted to approve before the command runs without sandbox - /// restrictions. + /// Only relevant when the system prompt includes a "Terminal sandbox" + /// section; otherwise leave unset. First try the narrower options + /// (`allow_network`, `fs_write_paths`, `allow_fs_write_all`); use this + /// only when the command needs behavior the sandbox can't grant on a + /// per-permission basis. Requesting it triggers a user approval prompt. #[serde(default)] pub unsandboxed: Option, } From 0129684538cbd56deecf0414196f8a9cba2dc709 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Thu, 28 May 2026 11:23:59 -0700 Subject: [PATCH 04/11] Split terminal tool into plain and sandboxed variants behind sandbox flag --- crates/agent/src/tests/mod.rs | 6 - crates/agent/src/thread.rs | 41 ++- crates/agent/src/tools/terminal_tool.rs | 385 +++++++++++++++--------- 3 files changed, 283 insertions(+), 149 deletions(-) diff --git a/crates/agent/src/tests/mod.rs b/crates/agent/src/tests/mod.rs index 16faa56c786484..5c529567ef9801 100644 --- a/crates/agent/src/tests/mod.rs +++ b/crates/agent/src/tests/mod.rs @@ -324,7 +324,6 @@ async fn test_terminal_tool_timeout_kills_handle(cx: &mut TestAppContext) { command: "sleep 1000".to_string(), cd: ".".to_string(), timeout_ms: Some(5), - ..Default::default() }), event_stream, cx, @@ -392,7 +391,6 @@ async fn test_terminal_tool_without_timeout_does_not_kill_handle(cx: &mut TestAp command: "sleep 1000".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -4898,7 +4896,6 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) { command: "rm -rf /".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -4951,7 +4948,6 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) { command: "echo hello".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -5010,7 +5006,6 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) { command: "sudo rm file".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -5058,7 +5053,6 @@ async fn test_terminal_tool_permission_rules(cx: &mut TestAppContext) { command: "echo hello".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 7868d523746301..c9506e871887b3 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -2,9 +2,10 @@ use crate::{ ApplyCodeActionTool, CodeActionStore, ContextServerRegistry, CopyPathTool, CreateDirectoryTool, DbLanguageModel, DbThread, DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool, - ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, SpawnAgentTool, - SystemPromptTemplate, Template, Templates, TerminalTool, ToolPermissionDecision, - UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings, + ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, + SandboxedTerminalTool, SpawnAgentTool, SystemPromptTemplate, Template, Templates, TerminalTool, + ToolPermissionDecision, UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, + decide_permission_from_settings, }; use acp_thread::{MentionUri, UserMessageId}; use action_log::ActionLog; @@ -14,7 +15,7 @@ use feature_flags::{ UpdateTitleToolFeatureFlag, }; -use crate::sandboxing::{ConversationSandboxGrants, SandboxRequest}; +use crate::sandboxing::{ConversationSandboxGrants, SandboxRequest, sandboxing_enabled}; use agent_client_protocol::schema as acp; use agent_settings::{ AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, @@ -1737,7 +1738,13 @@ impl Thread { self.action_log.clone(), update_agent_location, )); + // Register both terminal tool variants; `enabled_tools` exposes the + // one matching the current sandbox state to the model as `terminal`. self.add_tool(TerminalTool::new(self.project.clone(), environment.clone())); + self.add_tool(SandboxedTerminalTool::new( + self.project.clone(), + environment.clone(), + )); self.add_tool(WebSearchTool); self.add_tool(DiagnosticsTool::new(self.project.clone())); @@ -3066,14 +3073,36 @@ impl Thread { } } + // When sandboxing is enabled we expose the sandboxed terminal tool + // (which advertises the sandbox-escalation params) to the model under + // the canonical `terminal` name; otherwise we expose the plain one. + // Both are always registered, so we drop whichever variant isn't + // selected here. + let use_sandboxed_terminal = sandboxing_enabled(cx); + let mut tools = self .tools .iter() .filter_map(|(tool_name, tool)| { + // The sandboxed terminal tool is configured by users under the + // canonical `terminal` name, so check the profile against that. + let profile_tool_name = if tool_name == SandboxedTerminalTool::NAME { + TerminalTool::NAME + } else { + tool_name.as_ref() + }; + if tool.supports_provider(&model.provider_id()) - && profile.is_tool_enabled(tool_name) + && profile.is_tool_enabled(profile_tool_name) { - Some((truncate(tool_name), tool.clone())) + match (tool_name.as_ref(), use_sandboxed_terminal) { + (SandboxedTerminalTool::NAME, false) | (TerminalTool::NAME, true) => None, + (SandboxedTerminalTool::NAME, true) => { + // Expose the sandboxed terminal tool as `terminal`. + Some((SharedString::from(TerminalTool::NAME), tool.clone())) + } + _ => Some((truncate(tool_name), tool.clone())), + } } else { None } diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 5aec83bdcc5f52..8744d8368e1cf3 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -1,7 +1,7 @@ use agent_client_protocol::schema as acp; use anyhow::Result; use futures::FutureExt as _; -use gpui::{App, Entity, SharedString, Task}; +use gpui::{App, AsyncApp, Entity, SharedString, Task}; use project::Project; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; @@ -50,47 +50,74 @@ pub struct TerminalToolInput { pub cd: String, /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed. pub timeout_ms: Option, +} + +/// Executes a shell one-liner and returns the combined output. +/// +/// This tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result. +/// +/// The output results will be shown to the user already, only list it again if necessary, avoid being redundant. +/// +/// Make sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error. +/// +/// Do not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use. +/// +/// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own. +/// +/// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs. +/// +/// Remember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations. +/// +/// The terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this: +/// +/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`). +/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`). +/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly. +#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] +pub struct SandboxedTerminalToolInput { + /// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user. + /// + /// REMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang. + pub command: String, + /// Working directory for the command. This must be one of the root directories of the project. + pub cd: String, + /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed. + pub timeout_ms: Option, /// Set to `true` only if the command needs outbound network access. /// - /// Only relevant when the system prompt includes a "Terminal sandbox" - /// section; otherwise leave unset. Sandboxed commands cannot reach the - /// network by default, so set this when running commands that fetch or - /// upload (installing dependencies, cloning, pushing, downloading, - /// etc.). Requesting it triggers a user approval prompt, so only set it - /// when you expect the command to need network. + /// Sandboxed commands cannot reach the network by default, so set this + /// when running commands that fetch or upload (installing dependencies, + /// cloning, pushing, downloading, etc.). Requesting it triggers a user + /// approval prompt, so only set it when you expect the command to need + /// network. #[serde(default)] pub allow_network: Option, /// Paths the command needs to write to outside the default-writable /// locations. /// - /// Only relevant when the system prompt includes a "Terminal sandbox" - /// section; otherwise leave empty. Sandboxed commands can already write - /// to the project worktree directories and a per-command temporary - /// directory, so only list paths outside those. Provide absolute or - /// worktree-relative paths; each directory grants write access to its - /// whole subtree. Prefer this over `allow_fs_write_all` whenever you can - /// enumerate the paths. Requesting paths triggers a user approval - /// prompt. + /// Sandboxed commands can already write to the project worktree + /// directories and a per-command temporary directory, so only list paths + /// outside those. Provide absolute or worktree-relative paths; each + /// directory grants write access to its whole subtree. Prefer this over + /// `allow_fs_write_all` whenever you can enumerate the paths. Requesting + /// paths triggers a user approval prompt. #[serde(default)] pub fs_write_paths: Vec, /// Set to `true` only when the command needs to write outside the /// default-writable locations but the specific paths cannot be /// enumerated up front. /// - /// Only relevant when the system prompt includes a "Terminal sandbox" - /// section; otherwise leave unset. This is a broad escape hatch — prefer - /// `fs_write_paths` whenever the set of paths is known. Requesting it - /// triggers a user approval prompt. + /// This is a broad escape hatch — prefer `fs_write_paths` whenever the + /// set of paths is known. Requesting it triggers a user approval prompt. #[serde(default)] pub allow_fs_write_all: Option, /// Set to `true` only as a last resort, to run the command fully outside /// the sandbox. /// - /// Only relevant when the system prompt includes a "Terminal sandbox" - /// section; otherwise leave unset. First try the narrower options - /// (`allow_network`, `fs_write_paths`, `allow_fs_write_all`); use this - /// only when the command needs behavior the sandbox can't grant on a - /// per-permission basis. Requesting it triggers a user approval prompt. + /// First try the narrower options (`allow_network`, `fs_write_paths`, + /// `allow_fs_write_all`); use this only when the command needs behavior + /// the sandbox can't grant on a per-permission basis. Requesting it + /// triggers a user approval prompt. #[serde(default)] pub unsandboxed: Option, } @@ -140,11 +167,92 @@ impl AgentTool for TerminalTool { cx.spawn(async move |cx| { let input = input.recv().await.map_err(|e| e.to_string())?; - let (working_dir, authorize, sandboxing) = cx.update(|cx| { + let (working_dir, authorize) = cx.update(|cx| { let working_dir = - working_dir(&input, &self.project, cx).map_err(|err| err.to_string())?; + working_dir(&input.cd, &self.project, cx).map_err(|err| err.to_string())?; let context = crate::ToolPermissionContext::new(Self::NAME, vec![input.command.clone()]); + let authorize = + event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx); + Result::<_, String>::Ok((working_dir, authorize)) + })?; + + authorize.await.map_err(|e| e.to_string())?; + + // This tool is only handed to the model when sandboxing is off, so + // commands run without any sandbox wrap. + run_terminal_command( + &self.environment, + input.command, + working_dir, + input.timeout_ms, + None, + &event_stream, + cx, + ) + .await + }) + } +} + +pub struct SandboxedTerminalTool { + project: Entity, + environment: Rc, +} + +impl SandboxedTerminalTool { + pub fn new(project: Entity, environment: Rc) -> Self { + Self { + project, + environment, + } + } +} + +impl AgentTool for SandboxedTerminalTool { + type Input = SandboxedTerminalToolInput; + type Output = String; + + // Distinct internal registry name so both terminal tool variants can be + // registered at once; `Thread::enabled_tools` exposes the selected variant + // to the model under the canonical `terminal` name. + const NAME: &'static str = "sandboxed_terminal"; + + fn kind() -> acp::ToolKind { + acp::ToolKind::Execute + } + + fn initial_title( + &self, + input: Result, + _cx: &mut App, + ) -> SharedString { + if let Ok(input) = input { + input.command.into() + } else { + "".into() + } + } + + fn run( + self: Arc, + input: ToolInput, + event_stream: ToolCallEventStream, + cx: &mut App, + ) -> Task> { + cx.spawn(async move |cx| { + let input = input.recv().await.map_err(|e| e.to_string())?; + + let (working_dir, authorize, sandboxing) = cx.update(|cx| { + let working_dir = + working_dir(&input.cd, &self.project, cx).map_err(|err| err.to_string())?; + // Authorize under the canonical `terminal` name so the + // terminal-specific permission rules and UI apply, regardless + // of this tool's internal registry name. + let context = crate::ToolPermissionContext::new( + TerminalTool::NAME, + vec![input.command.clone()], + ); let authorize = event_stream.authorize(self.initial_title(Ok(input.clone()), cx), context, cx); let sandboxing = sandboxing_enabled(cx); @@ -153,10 +261,13 @@ impl AgentTool for TerminalTool { authorize.await.map_err(|e| e.to_string())?; - // Sandbox flags only do anything when sandboxing is on. When - // off, we treat them as `None` so the model can't surreptitiously - // change runtime behavior by setting flags described as a no-op - // in the system prompt. + // Sandbox flags only do anything when sandboxing is on. This tool + // is normally only exposed to the model while sandboxing is + // enabled, but the flag could flip between selection and + // execution, so we re-check here. When off, we treat the flags as + // `None` so the model can't surreptitiously change runtime + // behavior by setting flags described as a no-op in the system + // prompt. let want_network = sandboxing && input.allow_network == Some(true); let want_fs_write_all = sandboxing && input.allow_fs_write_all == Some(true); let want_unsandboxed = sandboxing && input.unsandboxed == Some(true); @@ -192,7 +303,7 @@ impl AgentTool for TerminalTool { if want_unsandboxed { let approve = cx.update(|cx| { let context = crate::ToolPermissionContext::new( - Self::NAME, + TerminalTool::NAME, vec![input.command.clone()], ); event_stream.authorize_always_prompt( @@ -221,16 +332,6 @@ impl AgentTool for TerminalTool { } } - // The per-thread scratch directory (and the `$TMPDIR`/`TMP`/ - // `TEMP` environment variables pointing at it) is provisioned by - // the thread environment in `create_terminal`, which also adds it - // to the sandbox's writable scope. We must not set `$TMPDIR` here: - // the environment overrides it with the per-thread directory, so a - // per-command directory set here would never be the `$TMPDIR` the - // command actually sees and would be left out of the writable - // scope, breaking writes into `$TMPDIR`. - let extra_env = Vec::new(); - // Build the writable scope from the project's worktrees. The // per-thread temp directory is appended by the thread environment // (which owns it and points `$TMPDIR` at it). Crucially we do @@ -261,80 +362,110 @@ impl AgentTool for TerminalTool { None }; - let terminal = self - .environment - .create_terminal( - input.command.clone(), - extra_env, - working_dir, - Some(COMMAND_OUTPUT_LIMIT), - sandbox_wrap, - cx, - ) - .await - .map_err(|e| e.to_string())?; - - let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?; - event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![ - acp::ToolCallContent::Terminal(acp::Terminal::new(terminal_id)), - ])); - - let timeout = input.timeout_ms.map(Duration::from_millis); - - let mut timed_out = false; - let mut user_stopped_via_signal = false; - let wait_for_exit = terminal.wait_for_exit(cx).map_err(|e| e.to_string())?; - - match timeout { - Some(timeout) => { - let timeout_task = cx.background_executor().timer(timeout); - - futures::select! { - _ = wait_for_exit.clone().fuse() => {}, - _ = timeout_task.fuse() => { - timed_out = true; - terminal.kill(cx).map_err(|e| e.to_string())?; - wait_for_exit.await; - } - _ = event_stream.cancelled_by_user().fuse() => { - user_stopped_via_signal = true; - terminal.kill(cx).map_err(|e| e.to_string())?; - wait_for_exit.await; - } - } + run_terminal_command( + &self.environment, + input.command, + working_dir, + input.timeout_ms, + sandbox_wrap, + &event_stream, + cx, + ) + .await + }) + } +} + +/// Shared execution path for both terminal tool variants: create the terminal, +/// surface it to the UI, wait for it to exit (honoring an optional timeout and +/// user cancellation), then format the captured output. +/// +/// Callers are responsible for having already authorized the command and, for +/// the sandboxed variant, resolved any `sandbox_wrap`. A `None` wrap runs the +/// command without an OS-level sandbox. +async fn run_terminal_command( + environment: &Rc, + command: String, + working_dir: Option, + timeout_ms: Option, + sandbox_wrap: Option, + event_stream: &ToolCallEventStream, + cx: &mut AsyncApp, +) -> Result { + // The per-thread scratch directory (and the `$TMPDIR`/`TMP`/`TEMP` + // environment variables pointing at it) is provisioned by the thread + // environment in `create_terminal`, which also adds it to the sandbox's + // writable scope. We must not set `$TMPDIR` here: the environment + // overrides it with the per-thread directory, so a per-command directory + // set here would never be the `$TMPDIR` the command actually sees and + // would be left out of the writable scope, breaking writes into `$TMPDIR`. + let extra_env = Vec::new(); + + let terminal = environment + .create_terminal( + command.clone(), + extra_env, + working_dir, + Some(COMMAND_OUTPUT_LIMIT), + sandbox_wrap, + cx, + ) + .await + .map_err(|e| e.to_string())?; + + let terminal_id = terminal.id(cx).map_err(|e| e.to_string())?; + event_stream.update_fields(acp::ToolCallUpdateFields::new().content(vec![ + acp::ToolCallContent::Terminal(acp::Terminal::new(terminal_id)), + ])); + + let timeout = timeout_ms.map(Duration::from_millis); + + let mut timed_out = false; + let mut user_stopped_via_signal = false; + let wait_for_exit = terminal.wait_for_exit(cx).map_err(|e| e.to_string())?; + + match timeout { + Some(timeout) => { + let timeout_task = cx.background_executor().timer(timeout); + + futures::select! { + _ = wait_for_exit.clone().fuse() => {}, + _ = timeout_task.fuse() => { + timed_out = true; + terminal.kill(cx).map_err(|e| e.to_string())?; + wait_for_exit.await; } - None => { - futures::select! { - _ = wait_for_exit.clone().fuse() => {}, - _ = event_stream.cancelled_by_user().fuse() => { - user_stopped_via_signal = true; - terminal.kill(cx).map_err(|e| e.to_string())?; - wait_for_exit.await; - } - } + _ = event_stream.cancelled_by_user().fuse() => { + user_stopped_via_signal = true; + terminal.kill(cx).map_err(|e| e.to_string())?; + wait_for_exit.await; } - }; + } + } + None => { + futures::select! { + _ = wait_for_exit.clone().fuse() => {}, + _ = event_stream.cancelled_by_user().fuse() => { + user_stopped_via_signal = true; + terminal.kill(cx).map_err(|e| e.to_string())?; + wait_for_exit.await; + } + } + } + }; - // Check if user stopped - we check both: - // 1. The cancellation signal from RunningTurn::cancel (e.g. user pressed main Stop button) - // 2. The terminal's user_stopped flag (e.g. user clicked Stop on the terminal card) - // Note: user_stopped_via_signal is already set above if we detected cancellation in the select! - // but we also check was_cancelled_by_user() for cases where cancellation happened after wait_for_exit completed - let user_stopped_via_signal = - user_stopped_via_signal || event_stream.was_cancelled_by_user(); - let user_stopped_via_terminal = terminal.was_stopped_by_user(cx).unwrap_or(false); - let user_stopped = user_stopped_via_signal || user_stopped_via_terminal; - - let output = terminal.current_output(cx).map_err(|e| e.to_string())?; - - Ok(process_content( - output, - &input.command, - timed_out, - user_stopped, - )) - }) - } + // Check if user stopped - we check both: + // 1. The cancellation signal from RunningTurn::cancel (e.g. user pressed main Stop button) + // 2. The terminal's user_stopped flag (e.g. user clicked Stop on the terminal card) + // Note: user_stopped_via_signal is already set above if we detected cancellation in the select! + // but we also check was_cancelled_by_user() for cases where cancellation happened after wait_for_exit completed + let user_stopped_via_signal = user_stopped_via_signal || event_stream.was_cancelled_by_user(); + let user_stopped_via_terminal = terminal.was_stopped_by_user(cx).unwrap_or(false); + let user_stopped = user_stopped_via_signal || user_stopped_via_terminal; + + let output = terminal.current_output(cx).map_err(|e| e.to_string())?; + + Ok(process_content(output, &command, timed_out, user_stopped)) } /// Resolve model-requested write paths into absolute paths. @@ -497,13 +628,8 @@ fn process_content( content } -fn working_dir( - input: &TerminalToolInput, - project: &Entity, - cx: &mut App, -) -> Result> { +fn working_dir(cd: &str, project: &Entity, cx: &mut App) -> Result> { let project = project.read(cx); - let cd = &input.cd; if cd == "." || cd.is_empty() { // Accept "." or "" as meaning "the one worktree" if we only have one worktree. @@ -549,7 +675,6 @@ mod tests { .to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }; let title = format_initial_title(Ok(input)); @@ -609,7 +734,6 @@ mod tests { command: cmd.to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }; let title = format_initial_title(Ok(input)); @@ -647,7 +771,6 @@ mod tests { command: "echo 'hello world'".to_string(), cd: ".".to_string(), timeout_ms: None, - ..Default::default() }; let title = format_initial_title(Ok(input)); @@ -677,7 +800,6 @@ mod tests { command: long_command, cd: ".".to_string(), timeout_ms: None, - ..Default::default() }; let title = format_initial_title(Ok(input)); @@ -884,7 +1006,6 @@ mod tests { command: "echo $HOME".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -952,7 +1073,6 @@ mod tests { command: "echo $HOME".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1014,7 +1134,6 @@ mod tests { command: "echo $(rm -rf /)".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1084,7 +1203,6 @@ mod tests { command: "PAGER=blah git log --oneline".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1158,7 +1276,6 @@ mod tests { command: "PAGER=blah git log".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1266,7 +1383,6 @@ mod tests { command: command.to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1434,7 +1550,6 @@ mod tests { command: "echo $(whoami)".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1507,7 +1622,6 @@ mod tests { command: "PAGER=other git log".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1574,7 +1688,6 @@ mod tests { command: "A=1 B=2 git log".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1652,7 +1765,6 @@ mod tests { command: "PAGER=\"less -R\" git log".to_string(), cd: "root".to_string(), timeout_ms: None, - ..Default::default() }), event_stream, cx, @@ -1773,11 +1885,10 @@ mod tests { #[test] fn test_input_schema_includes_sandbox_flags() { - // The model only sees these fields when the sandboxing prompt - // section is rendered, but they're always present in the schema so - // input validation doesn't reject them when sent. Guard against + // The sandboxed terminal tool advertises these fields so the model can + // request escalations when the sandbox is in effect. Guard against // accidentally renaming or removing them. - let schema = serde_json::to_string(&schemars::schema_for!(TerminalToolInput)) + let schema = serde_json::to_string(&schemars::schema_for!(SandboxedTerminalToolInput)) .expect("input schema should serialize"); assert!( schema.contains("allow_network"), @@ -1803,7 +1914,7 @@ mod tests { // calls. Make sure deserialization doesn't reject the minimal // payload and that the fields default to `None` (which the tool // interprets as "no escalation requested"). - let input: TerminalToolInput = serde_json::from_value(serde_json::json!({ + let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({ "command": "echo hi", "cd": ".", })) From a172f5f8103dfc66a92dcd730dc7c703cca4fe53 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Thu, 28 May 2026 11:41:39 -0700 Subject: [PATCH 05/11] fix test --- crates/agent/src/tools/terminal_tool.rs | 31 +++++++++++++++++-------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 8744d8368e1cf3..72004dd138df4b 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -1808,10 +1808,19 @@ mod tests { #[test] fn test_join_write_paths_resolves_relative_and_absolute() { - let base = PathBuf::from("/project"); + let base = PathBuf::from(if cfg!(windows) { + "C:\\project" + } else { + "/project" + }); + let abs = if cfg!(windows) { + "C:\\abs\\path" + } else { + "/abs/path" + }; let joined = join_write_paths( &[ - "/abs/path".to_string(), + abs.to_string(), "relative/dir".to_string(), "file.txt".to_string(), ], @@ -1820,9 +1829,9 @@ mod tests { assert_eq!( joined, vec![ - PathBuf::from("/abs/path"), - PathBuf::from("/project/relative/dir"), - PathBuf::from("/project/file.txt"), + PathBuf::from(abs), + base.join("relative/dir"), + base.join("file.txt"), ] ); } @@ -1831,11 +1840,13 @@ mod tests { fn test_join_write_paths_drops_relative_without_base() { // Absolute paths still pass through; relative ones are dropped when // there's no base to resolve them against. - let joined = join_write_paths( - &["/abs/keep".to_string(), "relative/drop".to_string()], - None, - ); - assert_eq!(joined, vec![PathBuf::from("/abs/keep")]); + let abs = if cfg!(windows) { + "C:\\abs\\keep" + } else { + "/abs/keep" + }; + let joined = join_write_paths(&[abs.to_string(), "relative/drop".to_string()], None); + assert_eq!(joined, vec![PathBuf::from(abs)]); } #[test] From 7c63f487f5b193d2f0a416e01e7de0d9a97b93e2 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 12:45:02 -0700 Subject: [PATCH 06/11] persistant option --- crates/agent/src/sandboxing.rs | 153 +++++++++---- crates/agent/src/templates/system_prompt.hbs | 2 +- crates/agent/src/thread.rs | 207 +++++++++++++++--- crates/agent/src/tool_permissions.rs | 1 + crates/agent/src/tools/terminal_tool.rs | 16 +- crates/agent_settings/src/agent_settings.rs | 102 ++++++++- crates/agent_ui/src/agent_ui.rs | 1 + crates/agent_ui/src/conversation_view.rs | 54 ++++- .../src/conversation_view/thread_view.rs | 6 +- crates/settings_content/src/agent.rs | 94 ++++++++ 10 files changed, 557 insertions(+), 79 deletions(-) diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index 5915b74df7ce3c..2166930d9b2aad 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -15,6 +15,7 @@ //! Naming note: this module is about agent terminal sandboxing specifically. //! Other agent operations (e.g. file edits) are gated separately. +use agent_settings::SandboxPermissions; use feature_flags::{FeatureFlagAppExt as _, SandboxingFeatureFlag}; use gpui::App; use std::path::PathBuf; @@ -55,9 +56,8 @@ impl SandboxRequest { /// /// Lives on the `Thread` and is shared (via `Rc>`) with each tool /// call's event stream so a later command requesting an already-granted -/// permission can skip the approval prompt. This is deliberately **never** -/// persisted to settings — it dies with the conversation, unlike the global -/// `always_allow` tool-permission rules. +/// permission can skip the approval prompt. Persistent "allow always" grants +/// are stored separately in [`SandboxPermissions`]. #[derive(Default)] pub(crate) struct ConversationSandboxGrants { network: bool, @@ -68,28 +68,33 @@ pub(crate) struct ConversationSandboxGrants { } impl ConversationSandboxGrants { - /// Whether everything `request` asks for has already been granted for the - /// conversation, so the command can run without prompting again. + /// Whether the union of conversation grants and persistent "allow always" + /// grants covers everything `request` asks for, so the command can run + /// without prompting again. /// - /// Write coverage is pure subtree containment: every - /// requested path must sit under some granted path. This is fully - /// deterministic and never widens scope, because grants are concrete - /// paths rather than globs. - pub fn covers(&self, request: &SandboxRequest) -> bool { - if request.network && !self.network { + /// Write coverage is pure subtree containment: every requested path must + /// sit under some granted path. This is fully deterministic and never + /// widens scope, because grants are concrete paths rather than globs. + pub fn covers_with_persistent( + &self, + request: &SandboxRequest, + persistent: &SandboxPermissions, + ) -> bool { + if request.network && !(self.network || persistent.allow_network) { return false; } - if request.allow_fs_write_all && !self.allow_fs_write_all { + if request.allow_fs_write_all && !(self.allow_fs_write_all || persistent.allow_fs_write_all) + { return false; } - // A conversation-wide all-access write grant covers any concrete - // write request. - if self.allow_fs_write_all { + // A full-access write grant covers any concrete write request. + if self.allow_fs_write_all || persistent.allow_fs_write_all { return true; } request.write_paths.iter().all(|requested| { self.write_paths .iter() + .chain(persistent.write_paths.iter()) .any(|granted| requested.starts_with(granted)) }) } @@ -104,23 +109,32 @@ impl ConversationSandboxGrants { } } - /// Compute the effective sandbox permissions to actually enforce for a - /// command: the union of everything granted for the conversation and - /// what this specific command requested. + /// Compute the effective sandbox permissions to enforce for a command: the + /// union of persistent "allow always" grants, conversation grants, and this + /// specific command's request. /// - /// This is what makes a conversation grant "stick": every sandboxed - /// command applies the accumulated grants, so the model can write to a - /// previously approved path without re-requesting it. Passing the current `request` in + /// This is what makes standing grants "stick": every sandboxed command + /// applies the accumulated grants, so the model can write to a previously + /// approved path without re-requesting it. Passing the current `request` in /// also covers "allow once" grants, which are enforced for this command /// without being recorded for the conversation. - pub fn effective(&self, request: &SandboxRequest) -> SandboxRequest { - let mut write_paths = self.write_paths.clone(); + pub fn effective_with_persistent( + &self, + request: &SandboxRequest, + persistent: &SandboxPermissions, + ) -> SandboxRequest { + let mut write_paths = persistent.write_paths.clone(); + for path in &self.write_paths { + add_write_path(&mut write_paths, path); + } for path in &request.write_paths { add_write_path(&mut write_paths, path); } SandboxRequest { - network: self.network || request.network, - allow_fs_write_all: self.allow_fs_write_all || request.allow_fs_write_all, + network: persistent.allow_network || self.network || request.network, + allow_fs_write_all: persistent.allow_fs_write_all + || self.allow_fs_write_all + || request.allow_fs_write_all, write_paths, } } @@ -149,12 +163,20 @@ mod tests { } } + fn covers(grants: &ConversationSandboxGrants, request: &SandboxRequest) -> bool { + grants.covers_with_persistent(request, &SandboxPermissions::default()) + } + + fn effective(grants: &ConversationSandboxGrants, request: &SandboxRequest) -> SandboxRequest { + grants.effective_with_persistent(request, &SandboxPermissions::default()) + } + #[test] fn empty_grants_cover_nothing() { let grants = ConversationSandboxGrants::default(); - assert!(!grants.covers(&request(true, false, &[]))); - assert!(!grants.covers(&request(false, true, &[]))); - assert!(!grants.covers(&request(false, false, &["/tmp/build"]))); + assert!(!covers(&grants, &request(true, false, &[]))); + assert!(!covers(&grants, &request(false, true, &[]))); + assert!(!covers(&grants, &request(false, false, &["/tmp/build"]))); } #[test] @@ -163,11 +185,14 @@ mod tests { grants.record(&request(false, false, &["/tmp/build"])); // Exact match and any descendant are covered. - assert!(grants.covers(&request(false, false, &["/tmp/build"]))); - assert!(grants.covers(&request(false, false, &["/tmp/build/cache"]))); + assert!(covers(&grants, &request(false, false, &["/tmp/build"]))); + assert!(covers( + &grants, + &request(false, false, &["/tmp/build/cache"]) + )); // A sibling / parent is not. - assert!(!grants.covers(&request(false, false, &["/tmp/other"]))); - assert!(!grants.covers(&request(false, false, &["/tmp"]))); + assert!(!covers(&grants, &request(false, false, &["/tmp/other"]))); + assert!(!covers(&grants, &request(false, false, &["/tmp"]))); } #[test] @@ -190,17 +215,53 @@ mod tests { fn all_access_covers_any_concrete_write() { let mut grants = ConversationSandboxGrants::default(); grants.record(&request(false, true, &[])); - assert!(grants.covers(&request(false, false, &["/anywhere/at/all"]))); + assert!(covers( + &grants, + &request(false, false, &["/anywhere/at/all"]) + )); // But not network, which wasn't granted. - assert!(!grants.covers(&request(true, false, &[]))); + assert!(!covers(&grants, &request(true, false, &[]))); } #[test] fn network_grant_tracked_independently() { let mut grants = ConversationSandboxGrants::default(); grants.record(&request(true, false, &[])); - assert!(grants.covers(&request(true, false, &[]))); - assert!(!grants.covers(&request(true, false, &["/tmp/build"]))); + assert!(covers(&grants, &request(true, false, &[]))); + assert!(!covers(&grants, &request(true, false, &["/tmp/build"]))); + } + + #[test] + fn persistent_grants_combine_with_conversation_grants() { + let mut grants = ConversationSandboxGrants::default(); + grants.record(&request(true, false, &[])); + let persistent = SandboxPermissions { + allow_network: false, + allow_fs_write_all: false, + write_paths: vec![PathBuf::from("/tmp/build")], + }; + + assert!( + grants + .covers_with_persistent(&request(true, false, &["/tmp/build/cache"]), &persistent) + ); + assert!( + !grants.covers_with_persistent(&request(true, false, &["/tmp/other"]), &persistent) + ); + } + + #[test] + fn persistent_all_access_covers_concrete_writes() { + let grants = ConversationSandboxGrants::default(); + let persistent = SandboxPermissions { + allow_network: false, + allow_fs_write_all: true, + write_paths: Vec::new(), + }; + + assert!(grants.covers_with_persistent(&request(false, false, &["/anywhere"]), &persistent)); + assert!(grants.covers_with_persistent(&request(false, true, &[]), &persistent)); + assert!(!grants.covers_with_persistent(&request(true, false, &[]), &persistent)); } #[test] @@ -210,7 +271,7 @@ mod tests { let mut grants = ConversationSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); - let effective = grants.effective(&request(false, false, &[])); + let effective = effective(&grants, &request(false, false, &[])); assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); } @@ -221,7 +282,7 @@ mod tests { let mut grants = ConversationSandboxGrants::default(); grants.record(&request(true, false, &["/tmp/build"])); - let effective = grants.effective(&request(false, false, &["/tmp/once"])); + let effective = effective(&grants, &request(false, false, &["/tmp/once"])); assert!(effective.network); assert_eq!( effective.write_paths, @@ -229,12 +290,26 @@ mod tests { ); } + #[test] + fn effective_applies_persistent_grants_to_empty_request() { + let grants = ConversationSandboxGrants::default(); + let persistent = SandboxPermissions { + allow_network: true, + allow_fs_write_all: false, + write_paths: vec![PathBuf::from("/tmp/always")], + }; + + let effective = grants.effective_with_persistent(&request(false, false, &[]), &persistent); + assert!(effective.network); + assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/always")]); + } + #[test] fn effective_dedupes_request_already_covered_by_grant() { let mut grants = ConversationSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); - let effective = grants.effective(&request(false, false, &["/tmp/build/cache"])); + let effective = effective(&grants, &request(false, false, &["/tmp/build/cache"])); assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); } } diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbs index aaba183dde2de9..b3c2d97030040c 100644 --- a/crates/agent/src/templates/system_prompt.hbs +++ b/crates/agent/src/templates/system_prompt.hbs @@ -207,7 +207,7 @@ You can request elevated permissions on individual `terminal` calls: - `allow_fs_write_all: true` — allow unrestricted filesystem writes. Only use this when the specific paths can't be enumerated up front. - `unsandboxed: true` — run the command with no sandbox at all. Use only when none of the above suffice. -The user will be prompted to approve before the command runs, and can grant a write request either just for that command or for the rest of the conversation. Once a write path is granted for the conversation, later commands writing under that path won't prompt again. +The user will be prompted to approve before the command runs, and can grant a sandbox request for that command, for the rest of the conversation, or always. Once a write path is granted for the conversation or always, later commands writing under that path won't prompt again. These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told. diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index c9506e871887b3..033c94aca6b7de 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -4108,20 +4108,18 @@ impl ToolCallEventStream { /// Gate a sandbox *escalation* (network access, per-path writes, or full /// filesystem write access) on user approval. /// - /// Unlike [`Self::authorize`] / [`Self::authorize_always_prompt`], the - /// decision is never read from or written to settings. Instead it offers - /// the user two grant lifetimes — "once" and "for the rest of this - /// conversation" — and records conversation grants in the shared, - /// in-memory [`ConversationSandboxGrants`]. A request already covered by - /// a prior conversation grant resolves immediately without prompting. + /// Offers the user three grant lifetimes — "once", "for the rest of this + /// conversation", and "always". Conversation grants live in the shared, + /// in-memory [`ConversationSandboxGrants`]. Always grants are persisted in + /// agent settings and are also observed while a prompt is pending, matching + /// the settings-driven authorization flow for regular tools. pub(crate) fn authorize_sandbox( &self, title: impl Into, request: SandboxRequest, cx: &mut App, ) -> Task> { - // Already approved for this conversation — run without prompting. - if self.sandbox_grants.borrow().covers(&request) { + if Self::sandbox_request_covered_by_grants(&request, &self.sandbox_grants, cx) { return Task::ready(Ok(())); } @@ -4137,6 +4135,11 @@ impl ToolCallEventStream { "Allow for this conversation", acp::PermissionOptionKind::AllowAlways, ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow_always"), + "Allow always", + acp::PermissionOptionKind::AllowAlways, + ), acp::PermissionOption::new( acp::PermissionOptionId::new("deny"), "Deny", @@ -4144,11 +4147,12 @@ impl ToolCallEventStream { ), ]); + let fs = self.fs.clone(); let stream = self.stream.clone(); let tool_use_id = self.tool_use_id.clone(); let sandbox_grants = self.sandbox_grants.clone(); - cx.spawn(async move |_cx| { - let (response_tx, response_rx) = oneshot::channel(); + cx.spawn(async move |cx| { + let (response_tx, mut response_rx) = oneshot::channel(); if let Err(error) = stream .0 .unbounded_send(Ok(ThreadEvent::ToolCallAuthorization( @@ -4168,35 +4172,135 @@ impl ToolCallEventStream { return Err(anyhow!("Failed to send sandbox authorization: {error}")); } - let outcome = response_rx - .await - .map_err(|_| anyhow!("authorization channel closed"))?; + let (mut settings_tx, mut settings_rx) = watch::channel(()); + let _settings_subscription = cx.update(|cx| { + cx.observe_global::(move |_cx| { + settings_tx.send(()).ok(); + }) + }); - match outcome.option_id.0.as_ref() { - "allow" => Ok(()), - "allow_conversation" => { - sandbox_grants.borrow_mut().record(&request); - Ok(()) - } - "deny" => Err(anyhow!("Permission to run tool denied by user")), - other => { - debug_assert!(false, "unexpected sandbox permission option_id: {other}"); - Err(anyhow!("Permission to run tool denied by user")) + loop { + let settings_changed = async { + if settings_rx.changed().await.is_err() { + std::future::pending::<()>().await; + } + }; + futures::select_biased! { + outcome = (&mut response_rx).fuse() => { + let outcome = outcome + .map_err(|_| anyhow!("authorization channel closed"))?; + return Self::handle_sandbox_permission_outcome( + &outcome, + &request, + sandbox_grants.clone(), + fs.clone(), + cx, + ); + } + _ = settings_changed.fuse() => { + if cx.update(|cx| Self::sandbox_request_covered_by_grants( + &request, + &sandbox_grants, + cx, + )) { + drop(response_rx); + stream.update_tool_call_fields( + &tool_use_id, + acp::ToolCallUpdateFields::new() + .status(acp::ToolCallStatus::InProgress), + None, + ); + return Ok(()); + } + } } } }) } + fn sandbox_request_covered_by_grants( + request: &SandboxRequest, + sandbox_grants: &Rc>, + cx: &App, + ) -> bool { + let settings = AgentSettings::get_global(cx); + sandbox_grants + .borrow() + .covers_with_persistent(request, &settings.sandbox_permissions) + } + + fn handle_sandbox_permission_outcome( + outcome: &acp_thread::SelectedPermissionOutcome, + request: &SandboxRequest, + sandbox_grants: Rc>, + fs: Option>, + cx: &AsyncApp, + ) -> Result<()> { + debug_assert!( + outcome.params.is_none(), + "unexpected params for sandbox permission" + ); + + match outcome.option_id.0.as_ref() { + "allow" => Ok(()), + "allow_conversation" => { + sandbox_grants.borrow_mut().record(request); + Ok(()) + } + "allow_always" => { + sandbox_grants.borrow_mut().record(request); + Self::persist_sandbox_always_permission(request, fs, cx); + Ok(()) + } + "deny" => Err(anyhow!("Permission to run tool denied by user")), + other => { + debug_assert!(false, "unexpected sandbox permission option_id: {other}"); + Err(anyhow!("Permission to run tool denied by user")) + } + } + } + + fn persist_sandbox_always_permission( + request: &SandboxRequest, + fs: Option>, + cx: &AsyncApp, + ) { + let Some(fs) = fs else { + return; + }; + + let request = request.clone(); + cx.update(|cx| { + update_settings_file(fs, cx, move |settings, _| { + let agent = settings.agent.get_or_insert_default(); + if request.network { + agent.allow_sandbox_network(); + } + if request.allow_fs_write_all { + agent.allow_sandbox_fs_write_all(); + } + for path in request.write_paths { + agent.add_sandbox_write_path(path); + } + }); + }); + } + /// The sandbox permissions to actually enforce for a command: the union - /// of this command's `request` and everything granted "for the rest of - /// the conversation". + /// of this command's `request`, everything granted "for the rest of the + /// conversation", and persistent "allow always" sandbox grants. /// /// Callers must apply this to the enforced sandbox policy (rather than - /// the raw `request`) so a conversation grant keeps working for later - /// commands that write to a previously approved path without - /// re-requesting it. - pub(crate) fn effective_sandbox_request(&self, request: &SandboxRequest) -> SandboxRequest { - self.sandbox_grants.borrow().effective(request) + /// the raw `request`) so standing grants keep working for later commands + /// that write to a previously approved path without re-requesting it. + pub(crate) fn effective_sandbox_request( + &self, + request: &SandboxRequest, + persistent: &agent_settings::SandboxPermissions, + ) -> SandboxRequest { + self.sandbox_grants + .borrow() + .effective_with_persistent(request, persistent) } /// Prompts the user to choose between an explicit set of actions and @@ -4741,6 +4845,49 @@ mod tests { } } + #[gpui::test] + async fn test_authorize_sandbox_allow_always_records_current_grant(cx: &mut TestAppContext) { + crate::tests::init_test(cx); + + let (event_stream, mut receiver) = ToolCallEventStream::test(); + let request = SandboxRequest { + network: false, + allow_fs_write_all: false, + write_paths: vec![PathBuf::from("/tmp/build")], + }; + + let authorize = cx.update(|cx| { + event_stream.authorize_sandbox("Allow write access?", request.clone(), cx) + }); + let authorization = receiver.expect_authorization().await; + let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { + panic!("expected flat sandbox permission options"); + }; + let option_ids = options + .iter() + .map(|option| option.option_id.0.as_ref()) + .collect::>(); + assert_eq!( + option_ids, + vec!["allow", "allow_conversation", "allow_always", "deny"] + ); + + let send_result = authorization + .response + .send(acp_thread::SelectedPermissionOutcome::new( + acp::PermissionOptionId::new("allow_always"), + acp::PermissionOptionKind::AllowAlways, + )); + assert!(send_result.is_ok()); + authorize.await.unwrap(); + + let effective = event_stream.effective_sandbox_request( + &SandboxRequest::default(), + &agent_settings::SandboxPermissions::default(), + ); + assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); + } + #[gpui::test] async fn test_replay_tool_call_replays_image_content(cx: &mut TestAppContext) { let (thread, _event_stream) = setup_thread_for_test(cx).await; diff --git a/crates/agent/src/tool_permissions.rs b/crates/agent/src/tool_permissions.rs index e2b3d6cb5bccd3..07a9e756fbb73a 100644 --- a/crates/agent/src/tool_permissions.rs +++ b/crates/agent/src/tool_permissions.rs @@ -596,6 +596,7 @@ mod tests { use_modifier_to_send: true, message_editor_min_lines: 1, tool_permissions, + sandbox_permissions: Default::default(), show_turn_stats: false, show_merge_conflict_indicator: true, sidebar_side: Default::default(), diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 72004dd138df4b..cfedc1aff463aa 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -5,7 +5,6 @@ use gpui::{App, AsyncApp, Entity, SharedString, Task}; use project::Project; use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -#[cfg(test)] use settings::Settings; use std::{ path::{Path, PathBuf}, @@ -340,11 +339,16 @@ impl AgentTool for SandboxedTerminalTool { // let the model widen its own write permissions outside the // project. let sandbox_wrap = if sandboxing && !want_unsandboxed { - // Apply the conversation's standing grants on top of this - // command's request, so a path approved "for the rest of the - // conversation" stays writable for later commands even when - // the model doesn't re-request it. - let effective = event_stream.effective_sandbox_request(&request); + // Apply standing grants on top of this command's request, so + // a path approved "for the rest of the conversation" or + // "always" stays writable for later commands even when the + // model doesn't re-request it. + let sandbox_permissions = cx.update(|cx| { + agent_settings::AgentSettings::get_global(cx) + .sandbox_permissions + .clone() + }); + let effective = event_stream.effective_sandbox_request(&request, &sandbox_permissions); let writable_paths: Vec = cx.update(|cx| { self.project .read(cx) diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs index d7b9d0ed0182f4..c82b0bf1357412 100644 --- a/crates/agent_settings/src/agent_settings.rs +++ b/crates/agent_settings/src/agent_settings.rs @@ -1,7 +1,7 @@ mod agent_profile; mod user_agents_md; -use std::path::{Component, Path}; +use std::path::{Component, Path, PathBuf}; use std::sync::{Arc, LazyLock}; use agent_client_protocol::schema as acp; @@ -170,6 +170,7 @@ pub struct AgentSettings { pub show_turn_stats: bool, pub show_merge_conflict_indicator: bool, pub tool_permissions: ToolPermissions, + pub sandbox_permissions: SandboxPermissions, } impl AgentSettings { @@ -336,6 +337,32 @@ impl Default for AgentProfileId { } } +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct SandboxPermissions { + pub allow_network: bool, + pub allow_fs_write_all: bool, + pub write_paths: Vec, +} + +impl SandboxPermissions { + pub fn covers(&self, network: bool, allow_fs_write_all: bool, write_paths: &[PathBuf]) -> bool { + if network && !self.allow_network { + return false; + } + if allow_fs_write_all && !self.allow_fs_write_all { + return false; + } + if self.allow_fs_write_all { + return true; + } + write_paths.iter().all(|requested| { + self.write_paths + .iter() + .any(|granted| requested.starts_with(granted)) + }) + } +} + #[derive(Clone, Debug, Default)] pub struct ToolPermissions { /// Global default permission when no tool-specific rules or patterns match. @@ -674,10 +701,38 @@ impl Settings for AgentSettings { show_turn_stats: agent.show_turn_stats.unwrap(), show_merge_conflict_indicator: agent.show_merge_conflict_indicator.unwrap(), tool_permissions: compile_tool_permissions(agent.tool_permissions), + sandbox_permissions: compile_sandbox_permissions(agent.sandbox_permissions), } } } +fn compile_sandbox_permissions( + content: Option, +) -> SandboxPermissions { + let Some(content) = content else { + return SandboxPermissions::default(); + }; + + let mut write_paths = Vec::new(); + for path in content.write_paths.map(|paths| paths.0).unwrap_or_default() { + add_sandbox_write_path(&mut write_paths, &path); + } + + SandboxPermissions { + allow_network: content.allow_network.unwrap_or(false), + allow_fs_write_all: content.allow_fs_write_all.unwrap_or(false), + write_paths, + } +} + +fn add_sandbox_write_path(write_paths: &mut Vec, path: &Path) { + if write_paths.iter().any(|granted| path.starts_with(granted)) { + return; + } + write_paths.retain(|granted| !granted.starts_with(path)); + write_paths.push(path.to_path_buf()); +} + fn compile_tool_permissions(content: Option) -> ToolPermissions { let Some(content) = content else { return ToolPermissions::default(); @@ -852,6 +907,51 @@ mod tests { assert_eq!(permissions.default, ToolPermissionMode::Confirm); } + #[test] + fn test_sandbox_permissions_empty() { + let permissions = compile_sandbox_permissions(None); + assert_eq!(permissions, SandboxPermissions::default()); + assert!(!permissions.covers(true, false, &[])); + assert!(!permissions.covers(false, true, &[])); + assert!(!permissions.covers(false, false, &[PathBuf::from("/tmp/build")])); + } + + #[test] + fn test_sandbox_permissions_parsing_and_pruning() { + let json = json!({ + "allow_network": true, + "write_paths": [ + "/tmp/build/cache", + "/tmp/build", + "/var/log" + ] + }); + + let content: settings::SandboxPermissionsContent = serde_json::from_value(json).unwrap(); + let permissions = compile_sandbox_permissions(Some(content)); + + assert!(permissions.allow_network); + assert!(!permissions.allow_fs_write_all); + assert_eq!( + permissions.write_paths, + vec![PathBuf::from("/tmp/build"), PathBuf::from("/var/log")] + ); + assert!(permissions.covers(true, false, &[PathBuf::from("/tmp/build/cache")])) + } + + #[test] + fn test_sandbox_permissions_all_write_covers_paths() { + let json = json!({ + "allow_fs_write_all": true, + }); + + let content: settings::SandboxPermissionsContent = serde_json::from_value(json).unwrap(); + let permissions = compile_sandbox_permissions(Some(content)); + + assert!(permissions.covers(false, true, &[])); + assert!(permissions.covers(false, false, &[PathBuf::from("/anywhere")])) + } + #[test] fn test_tool_rules_default_returns_confirm() { let default_rules = ToolRules::default(); diff --git a/crates/agent_ui/src/agent_ui.rs b/crates/agent_ui/src/agent_ui.rs index fc67e12904a667..4d78b607055b0c 100644 --- a/crates/agent_ui/src/agent_ui.rs +++ b/crates/agent_ui/src/agent_ui.rs @@ -876,6 +876,7 @@ mod tests { use_modifier_to_send: true, message_editor_min_lines: 1, tool_permissions: Default::default(), + sandbox_permissions: Default::default(), show_turn_stats: false, show_merge_conflict_indicator: true, sidebar_side: Default::default(), diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 568b94c1240b01..5fc82dfe6562d7 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -391,7 +391,7 @@ impl Conversation { ) -> Option<()> { let (authorize_session_id, tool_call_id, options) = self.pending_tool_call(session_id, cx)?; - let option = options.first_option_of_kind(kind)?; + let option = permission_option_for_action(options, kind)?; self.authorize_tool_call( authorize_session_id, tool_call_id, @@ -455,6 +455,22 @@ pub(crate) struct RootThreadUpdated; impl EventEmitter for ConversationView {} +fn permission_option_for_action( + options: &PermissionOptions, + kind: acp::PermissionOptionKind, +) -> Option<&acp::PermissionOption> { + if kind == acp::PermissionOptionKind::AllowAlways + && let PermissionOptions::Flat(options) = options + && let Some(option) = options + .iter() + .find(|option| option.option_id.0.as_ref() == "allow_always") + { + return Some(option); + } + + options.first_option_of_kind(kind) +} + fn resolve_outcome_from_selection( options: &PermissionOptions, selection: Option<&thread_view::PermissionSelection>, @@ -7536,6 +7552,42 @@ pub(crate) mod tests { ]) } + fn sandbox_permission_options() -> PermissionOptions { + PermissionOptions::Flat(vec![ + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow"), + "Allow once", + acp::PermissionOptionKind::AllowOnce, + ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow_conversation"), + "Allow for this conversation", + acp::PermissionOptionKind::AllowAlways, + ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("allow_always"), + "Allow always", + acp::PermissionOptionKind::AllowAlways, + ), + acp::PermissionOption::new( + acp::PermissionOptionId::new("deny"), + "Deny", + acp::PermissionOptionKind::RejectOnce, + ), + ]) + } + + #[test] + fn permission_option_for_action_prefers_explicit_sandbox_allow_always() { + let options = sandbox_permission_options(); + + let option = + super::permission_option_for_action(&options, acp::PermissionOptionKind::AllowAlways) + .unwrap(); + + assert_eq!(option.option_id.0.as_ref(), "allow_always"); + } + #[test] fn resolve_outcome_from_selection_flat_allow_picks_allow_once() { let options = flat_allow_deny_options(); diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index a90fef49bd9915..37229bf102b908 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -7853,7 +7853,11 @@ impl ThreadView { Icon::new(IconName::CheckDouble) .size(IconSize::XSmall) .color(Color::Success), - Some(&AllowAlways as &dyn Action), + if option.option_id.0.as_ref() == "allow_conversation" { + None + } else { + Some(&AllowAlways as &dyn Action) + }, ), acp::PermissionOptionKind::RejectOnce => ( Icon::new(IconName::Close) diff --git a/crates/settings_content/src/agent.rs b/crates/settings_content/src/agent.rs index 917ca5e0530ddd..6985a550a373d0 100644 --- a/crates/settings_content/src/agent.rs +++ b/crates/settings_content/src/agent.rs @@ -211,6 +211,11 @@ pub struct AgentSettingsContent { /// `always_confirm`) match against the tool's text input (command, path, /// URL, etc.). pub tool_permissions: Option, + + /// Persistent sandbox permission grants for agent-run terminal commands. + /// These are populated when choosing "Allow always" from a sandbox + /// escalation prompt. + pub sandbox_permissions: Option, } impl AgentSettingsContent { @@ -313,6 +318,33 @@ impl AgentSettingsContent { }); } } + + pub fn allow_sandbox_network(&mut self) { + self.sandbox_permissions + .get_or_insert_default() + .allow_network = Some(true); + } + + pub fn allow_sandbox_fs_write_all(&mut self) { + self.sandbox_permissions + .get_or_insert_default() + .allow_fs_write_all = Some(true); + } + + pub fn add_sandbox_write_path(&mut self, path: PathBuf) { + let write_paths = &mut self + .sandbox_permissions + .get_or_insert_default() + .write_paths + .get_or_insert_default() + .0; + + if write_paths.iter().any(|granted| path.starts_with(granted)) { + return; + } + write_paths.retain(|granted| !granted.starts_with(&path)); + write_paths.push(path); + } } #[with_fallible_options] @@ -567,6 +599,25 @@ pub enum CustomAgentServerSettings { }, } +#[with_fallible_options] +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)] +pub struct SandboxPermissionsContent { + /// Whether sandboxed terminal commands may always use outbound network + /// access without prompting. + /// Default: false + pub allow_network: Option, + + /// Whether sandboxed terminal commands may always write anywhere on the + /// filesystem without prompting. + /// Default: false + pub allow_fs_write_all: Option, + + /// Directory subtrees that sandboxed terminal commands may always write + /// to without prompting. Paths written by Zed are absolute. + /// Default: [] + pub write_paths: Option>, +} + #[with_fallible_options] #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, JsonSchema, MergeFrom)] pub struct ToolPermissionsContent { @@ -832,4 +883,47 @@ mod tests { assert_eq!(always_deny.0.len(), 1); assert_eq!(always_deny.0[0].pattern, "^rm\\s"); } + + #[test] + fn test_allow_sandbox_permissions_create_structure() { + let mut settings = AgentSettingsContent::default(); + assert!(settings.sandbox_permissions.is_none()); + + settings.allow_sandbox_network(); + settings.allow_sandbox_fs_write_all(); + settings.add_sandbox_write_path(PathBuf::from("/tmp/build")); + + let sandbox_permissions = settings.sandbox_permissions.as_ref().unwrap(); + assert_eq!(sandbox_permissions.allow_network, Some(true)); + assert_eq!(sandbox_permissions.allow_fs_write_all, Some(true)); + assert_eq!( + sandbox_permissions + .write_paths + .as_ref() + .unwrap() + .0 + .as_slice(), + &[PathBuf::from("/tmp/build")] + ); + } + + #[test] + fn test_add_sandbox_write_path_prunes_redundant_paths() { + let mut settings = AgentSettingsContent::default(); + + settings.add_sandbox_write_path(PathBuf::from("/tmp/build/cache")); + settings.add_sandbox_write_path(PathBuf::from("/tmp/build")); + settings.add_sandbox_write_path(PathBuf::from("/tmp/build/output")); + + let write_paths = settings + .sandbox_permissions + .as_ref() + .unwrap() + .write_paths + .as_ref() + .unwrap() + .0 + .as_slice(); + assert_eq!(write_paths, &[PathBuf::from("/tmp/build")]); + } } From 54fec1fe3235ba30ddb2cbbeb5618302d60ad02c Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 13:36:58 -0700 Subject: [PATCH 07/11] better ui for requesting permissions Co-authored-by: Anant Goel --- crates/acp_thread/src/acp_thread.rs | 33 ++++++ crates/agent/src/thread.rs | 35 +++++- crates/agent/src/tools/terminal_tool.rs | 24 ++--- .../src/conversation_view/thread_view.rs | 102 +++++++++++++++++- 4 files changed, 174 insertions(+), 20 deletions(-) diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index c42694cd8c6c16..14f6779541471a 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -77,6 +77,30 @@ pub fn meta_with_tool_name(tool_name: &str) -> acp::Meta { /// Key used in ACP ToolCall meta to store the session id and message indexes pub const SUBAGENT_SESSION_INFO_META_KEY: &str = "subagent_session_info"; +pub const SANDBOX_AUTHORIZATION_META_KEY: &str = "sandbox_authorization"; + +#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] +pub struct SandboxAuthorizationDetails { + pub network: bool, + pub allow_fs_write_all: bool, + pub write_paths: Vec, +} + +pub fn meta_with_sandbox_authorization(details: SandboxAuthorizationDetails) -> acp::Meta { + acp::Meta::from_iter([( + SANDBOX_AUTHORIZATION_META_KEY.into(), + serde_json::to_value(details).unwrap_or_default(), + )]) +} + +pub fn sandbox_authorization_details_from_meta( + meta: &Option, +) -> Option { + meta.as_ref() + .and_then(|m| m.get(SANDBOX_AUTHORIZATION_META_KEY)) + .and_then(|v| serde_json::from_value(v.clone()).ok()) +} + #[derive(Clone, Debug, Deserialize, Serialize)] pub struct SubagentSessionInfo { /// The session id of the subagent sessiont that was spawned @@ -265,6 +289,7 @@ pub struct ToolCall { pub raw_output: Option, pub tool_name: Option, pub subagent_session_info: Option, + pub sandbox_authorization_details: Option, } impl ToolCall { @@ -306,6 +331,8 @@ impl ToolCall { let tool_name = tool_name_from_meta(&tool_call.meta); let subagent_session_info = subagent_session_info_from_meta(&tool_call.meta); + let sandbox_authorization_details = + sandbox_authorization_details_from_meta(&tool_call.meta); let label = if tool_call.kind == acp::ToolKind::Execute { cx.new(|cx| Markdown::new_text(title.into(), cx)) @@ -326,6 +353,7 @@ impl ToolCall { raw_output: tool_call.raw_output, tool_name, subagent_session_info, + sandbox_authorization_details, }; Ok(result) } @@ -361,6 +389,10 @@ impl ToolCall { if let Some(subagent_session_info) = subagent_session_info_from_meta(&meta) { self.subagent_session_info = Some(subagent_session_info); } + if let Some(sandbox_authorization_details) = sandbox_authorization_details_from_meta(&meta) + { + self.sandbox_authorization_details = Some(sandbox_authorization_details); + } if let Some(title) = title { if self.kind == acp::ToolKind::Execute { @@ -1946,6 +1978,7 @@ impl AcpThread { raw_output: None, tool_name: None, subagent_session_info: None, + sandbox_authorization_details: None, }; self.push_entry(AgentThreadEntry::ToolCall(failed_tool_call), cx); return Ok(()); diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 033c94aca6b7de..19504207dff435 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -4124,6 +4124,11 @@ impl ToolCallEventStream { } let title = title.into(); + let sandbox_authorization_details = acp_thread::SandboxAuthorizationDetails { + network: request.network, + allow_fs_write_all: request.allow_fs_write_all, + write_paths: request.write_paths.clone(), + }; let options = acp_thread::PermissionOptions::Flat(vec![ acp::PermissionOption::new( acp::PermissionOptionId::new("allow"), @@ -4160,7 +4165,10 @@ impl ToolCallEventStream { tool_call: acp::ToolCallUpdate::new( tool_use_id.to_string(), acp::ToolCallUpdateFields::new().title(title), - ), + ) + .meta(acp_thread::meta_with_sandbox_authorization( + sandbox_authorization_details, + )), options, response: response_tx, context: None, @@ -4853,13 +4861,26 @@ mod tests { let request = SandboxRequest { network: false, allow_fs_write_all: false, - write_paths: vec![PathBuf::from("/tmp/build")], + write_paths: vec![ + PathBuf::from("/tmp/build"), + PathBuf::from("/tmp/cache"), + PathBuf::from("/tmp/logs"), + PathBuf::from("/tmp/secret"), + ], }; let authorize = cx.update(|cx| { event_stream.authorize_sandbox("Allow write access?", request.clone(), cx) }); let authorization = receiver.expect_authorization().await; + let details = + acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta) + .expect("sandbox authorization should include request details"); + assert_eq!(details.network, request.network); + assert_eq!(details.allow_fs_write_all, request.allow_fs_write_all); + assert_eq!(details.write_paths, request.write_paths); + assert!(authorization.tool_call.fields.content.is_none()); + let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { panic!("expected flat sandbox permission options"); }; @@ -4885,7 +4906,15 @@ mod tests { &SandboxRequest::default(), &agent_settings::SandboxPermissions::default(), ); - assert_eq!(effective.write_paths, vec![PathBuf::from("/tmp/build")]); + assert_eq!( + effective.write_paths, + vec![ + PathBuf::from("/tmp/build"), + PathBuf::from("/tmp/cache"), + PathBuf::from("/tmp/logs"), + PathBuf::from("/tmp/secret"), + ] + ); } #[gpui::test] diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index cfedc1aff463aa..82af4361543ead 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -527,7 +527,7 @@ fn sandbox_approval_title(request: &crate::sandboxing::SandboxRequest) -> String } else if !request.write_paths.is_empty() { parts.push(format!( "write access to {}", - describe_paths(&request.write_paths) + write_path_summary(&request.write_paths) )); } match parts.as_slice() { @@ -540,19 +540,11 @@ fn sandbox_approval_title(request: &crate::sandboxing::SandboxRequest) -> String } } -/// Render a short, human-readable summary of requested write paths for the -/// approval prompt, capping the number listed so the title stays readable. -fn describe_paths(paths: &[PathBuf]) -> String { - const MAX_SHOWN: usize = 3; - let shown: Vec = paths - .iter() - .take(MAX_SHOWN) - .map(|path| path.display().to_string()) - .collect(); - if paths.len() > MAX_SHOWN { - format!("{} (+{} more)", shown.join(", "), paths.len() - MAX_SHOWN) - } else { - shown.join(", ") +fn write_path_summary(paths: &[PathBuf]) -> String { + match paths { + [] => "0 paths".to_string(), + [path] => path.display().to_string(), + paths => format!("{} paths", paths.len()), } } @@ -1882,10 +1874,10 @@ mod tests { } #[test] - fn test_sandbox_approval_title_caps_listed_paths() { + fn test_sandbox_approval_title_summarizes_multiple_paths_by_count() { let title = sandbox_approval_title(&sandbox_request(false, false, &["/a", "/b", "/c", "/d"])); - assert_eq!(title, "Allow write access to /a, /b, /c (+1 more)?"); + assert_eq!(title, "Allow write access to 4 paths?"); } #[test] diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 37229bf102b908..cec374af2023ef 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -7,7 +7,7 @@ use crate::{ use agent_client_protocol::schema as acp; use std::cell::RefCell; -use acp_thread::{ContentBlock, PlanEntry}; +use acp_thread::{ContentBlock, PlanEntry, SandboxAuthorizationDetails}; use agent::{SkillLoadingError, SkillLoadingErrorsUpdated}; use agent_settings::UserAgentsMd; use cloud_api_types::{SubmitAgentThreadFeedbackBody, SubmitAgentThreadFeedbackCommentsBody}; @@ -571,6 +571,7 @@ pub struct ThreadView { /// Used for showing/hiding tool call results, terminal output, etc. pub expanded_tool_calls: HashSet, pub expanded_tool_call_raw_inputs: HashSet, + collapsed_sandbox_authorization_details: HashSet, pub expanded_thinking_blocks: HashSet<(usize, usize)>, auto_expanded_thinking_block: Option<(usize, usize)>, user_toggled_thinking_blocks: HashSet<(usize, usize)>, @@ -887,6 +888,7 @@ impl ThreadView { thread_feedback: Default::default(), expanded_tool_calls: HashSet::default(), expanded_tool_call_raw_inputs: HashSet::default(), + collapsed_sandbox_authorization_details: HashSet::default(), expanded_thinking_blocks: HashSet::default(), auto_expanded_thinking_block: None, user_toggled_thinking_blocks: HashSet::default(), @@ -7020,6 +7022,17 @@ impl ThreadView { .into_any_element() }), ) + .when_some( + tool_call.sandbox_authorization_details.as_ref(), + |this, details| { + this.child(self.render_sandbox_authorization_details( + entry_ix, + &tool_call.id, + details, + cx, + )) + }, + ) .when(should_show_raw_input, |this| { let is_raw_input_expanded = self.expanded_tool_call_raw_inputs.contains(&tool_call.id); @@ -7385,6 +7398,93 @@ impl ThreadView { .children(tool_output_display) } + fn render_sandbox_authorization_details( + &self, + entry_ix: usize, + tool_call_id: &acp::ToolCallId, + details: &SandboxAuthorizationDetails, + cx: &Context, + ) -> AnyElement { + if details.write_paths.is_empty() { + return Empty.into_any_element(); + } + + let is_open = !self + .collapsed_sandbox_authorization_details + .contains(tool_call_id); + let paths = details + .write_paths + .iter() + .map(|path| path.display().to_string()) + .collect::>(); + + v_flex() + .p_2() + .gap_1() + .border_t_1() + .border_color(self.tool_card_border_color(cx)) + .child( + h_flex() + .id(("sandbox-authorization-details-header", entry_ix)) + .gap_1() + .pl_0p5() + .rounded_xs() + .hover(|style| style.bg(cx.theme().colors().element_hover)) + .child( + Disclosure::new(("sandbox-authorization-details", entry_ix), is_open) + .opened_icon(IconName::ChevronUp) + .closed_icon(IconName::ChevronDown), + ) + .child( + Label::new("Paths") + .size(LabelSize::XSmall) + .color(Color::Muted) + .buffer_font(cx), + ) + .on_click(cx.listener({ + let tool_call_id = tool_call_id.clone(); + move |this, _event, _window, cx| { + if this + .collapsed_sandbox_authorization_details + .remove(&tool_call_id) + { + cx.notify(); + return; + } + + this.collapsed_sandbox_authorization_details + .insert(tool_call_id.clone()); + cx.notify(); + } + })), + ) + .when(is_open, |this| { + this.child( + v_flex() + .gap_0p5() + .pl_5() + .children(paths.into_iter().enumerate().map(|(path_ix, path)| { + h_flex() + .gap_1() + .child(Label::new("•").size(LabelSize::Small).color(Color::Muted)) + .child( + div() + .id(format!( + "sandbox-authorization-path-{entry_ix}-{path_ix}" + )) + .w_full() + .max_w_full() + .overflow_x_scroll() + .child( + Label::new(path).buffer_font(cx).size(LabelSize::Small), + ), + ) + })), + ) + }) + .into_any_element() + } + fn render_permission_buttons( &self, session_id: acp::SessionId, From db413c56e6aa3a573aeef28b9255d95bb71ef032 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 13:46:52 -0700 Subject: [PATCH 08/11] change conversation -> thread --- crates/agent/src/sandboxing.rs | 58 +++++++++---------- crates/agent/src/templates.rs | 4 +- crates/agent/src/templates/system_prompt.hbs | 6 +- crates/agent/src/thread.rs | 42 +++++++------- crates/agent/src/tools/terminal_tool.rs | 8 +-- crates/agent_ui/src/conversation_view.rs | 4 +- .../src/conversation_view/thread_view.rs | 2 +- 7 files changed, 62 insertions(+), 62 deletions(-) diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index 2166930d9b2aad..ed36af5604a515 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -52,25 +52,25 @@ impl SandboxRequest { } /// In-memory record of the sandbox permissions the user approved "for the -/// rest of the conversation". +/// rest of the thread". /// /// Lives on the `Thread` and is shared (via `Rc>`) with each tool /// call's event stream so a later command requesting an already-granted /// permission can skip the approval prompt. Persistent "allow always" grants /// are stored separately in [`SandboxPermissions`]. #[derive(Default)] -pub(crate) struct ConversationSandboxGrants { +pub(crate) struct ThreadSandboxGrants { network: bool, allow_fs_write_all: bool, - /// Canonicalized paths granted write access for the conversation. Each - /// covers its whole subtree; redundant children are pruned on insert. + /// Canonicalized paths granted write access for the thread. Each covers its + /// whole subtree; redundant children are pruned on insert. write_paths: Vec, } -impl ConversationSandboxGrants { - /// Whether the union of conversation grants and persistent "allow always" - /// grants covers everything `request` asks for, so the command can run - /// without prompting again. +impl ThreadSandboxGrants { + /// Whether the union of thread grants and persistent "allow always" grants + /// covers everything `request` asks for, so the command can run without + /// prompting again. /// /// Write coverage is pure subtree containment: every requested path must /// sit under some granted path. This is fully deterministic and never @@ -99,8 +99,8 @@ impl ConversationSandboxGrants { }) } - /// Record everything in `request` as granted for the rest of the - /// conversation, pruning paths that become redundant. + /// Record everything in `request` as granted for the rest of the thread, + /// pruning paths that become redundant. pub fn record(&mut self, request: &SandboxRequest) { self.network |= request.network; self.allow_fs_write_all |= request.allow_fs_write_all; @@ -110,14 +110,14 @@ impl ConversationSandboxGrants { } /// Compute the effective sandbox permissions to enforce for a command: the - /// union of persistent "allow always" grants, conversation grants, and this + /// union of persistent "allow always" grants, thread grants, and this /// specific command's request. /// /// This is what makes standing grants "stick": every sandboxed command /// applies the accumulated grants, so the model can write to a previously /// approved path without re-requesting it. Passing the current `request` in /// also covers "allow once" grants, which are enforced for this command - /// without being recorded for the conversation. + /// without being recorded for the thread. pub fn effective_with_persistent( &self, request: &SandboxRequest, @@ -163,17 +163,17 @@ mod tests { } } - fn covers(grants: &ConversationSandboxGrants, request: &SandboxRequest) -> bool { + fn covers(grants: &ThreadSandboxGrants, request: &SandboxRequest) -> bool { grants.covers_with_persistent(request, &SandboxPermissions::default()) } - fn effective(grants: &ConversationSandboxGrants, request: &SandboxRequest) -> SandboxRequest { + fn effective(grants: &ThreadSandboxGrants, request: &SandboxRequest) -> SandboxRequest { grants.effective_with_persistent(request, &SandboxPermissions::default()) } #[test] fn empty_grants_cover_nothing() { - let grants = ConversationSandboxGrants::default(); + let grants = ThreadSandboxGrants::default(); assert!(!covers(&grants, &request(true, false, &[]))); assert!(!covers(&grants, &request(false, true, &[]))); assert!(!covers(&grants, &request(false, false, &["/tmp/build"]))); @@ -181,7 +181,7 @@ mod tests { #[test] fn subtree_containment_covers_children() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); // Exact match and any descendant are covered. @@ -197,7 +197,7 @@ mod tests { #[test] fn record_prunes_redundant_children() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build/cache"])); grants.record(&request(false, false, &["/tmp/build"])); assert_eq!(grants.write_paths, vec![PathBuf::from("/tmp/build")]); @@ -205,7 +205,7 @@ mod tests { #[test] fn record_keeps_existing_broader_grant() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); grants.record(&request(false, false, &["/tmp/build/cache"])); assert_eq!(grants.write_paths, vec![PathBuf::from("/tmp/build")]); @@ -213,7 +213,7 @@ mod tests { #[test] fn all_access_covers_any_concrete_write() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, true, &[])); assert!(covers( &grants, @@ -225,15 +225,15 @@ mod tests { #[test] fn network_grant_tracked_independently() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(true, false, &[])); assert!(covers(&grants, &request(true, false, &[]))); assert!(!covers(&grants, &request(true, false, &["/tmp/build"]))); } #[test] - fn persistent_grants_combine_with_conversation_grants() { - let mut grants = ConversationSandboxGrants::default(); + fn persistent_grants_combine_with_thread_grants() { + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(true, false, &[])); let persistent = SandboxPermissions { allow_network: false, @@ -252,7 +252,7 @@ mod tests { #[test] fn persistent_all_access_covers_concrete_writes() { - let grants = ConversationSandboxGrants::default(); + let grants = ThreadSandboxGrants::default(); let persistent = SandboxPermissions { allow_network: false, allow_fs_write_all: true, @@ -265,10 +265,10 @@ mod tests { } #[test] - fn effective_applies_conversation_grants_to_empty_request() { + fn effective_applies_thread_grants_to_empty_request() { // The core fix: a command that requests nothing still gets the - // conversation's granted write paths in its enforced policy. - let mut grants = ConversationSandboxGrants::default(); + // thread's granted write paths in its enforced policy. + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); let effective = effective(&grants, &request(false, false, &[])); @@ -279,7 +279,7 @@ mod tests { fn effective_unions_grants_with_once_request() { // An "allow once" path (passed via `request`, never recorded) is // enforced for this command alongside the standing grants. - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(true, false, &["/tmp/build"])); let effective = effective(&grants, &request(false, false, &["/tmp/once"])); @@ -292,7 +292,7 @@ mod tests { #[test] fn effective_applies_persistent_grants_to_empty_request() { - let grants = ConversationSandboxGrants::default(); + let grants = ThreadSandboxGrants::default(); let persistent = SandboxPermissions { allow_network: true, allow_fs_write_all: false, @@ -306,7 +306,7 @@ mod tests { #[test] fn effective_dedupes_request_already_covered_by_grant() { - let mut grants = ConversationSandboxGrants::default(); + let mut grants = ThreadSandboxGrants::default(); grants.record(&request(false, false, &["/tmp/build"])); let effective = effective(&grants, &request(false, false, &["/tmp/build/cache"])); diff --git a/crates/agent/src/templates.rs b/crates/agent/src/templates.rs index e9a4b80a392d88..a946c404dc7593 100644 --- a/crates/agent/src/templates.rs +++ b/crates/agent/src/templates.rs @@ -44,7 +44,7 @@ pub struct SystemPromptTemplate<'a> { /// platform equivalent), if present and non-empty. pub user_agents_md: Option, /// Whether agent-run terminal commands are wrapped in an OS-level - /// sandbox for this conversation. When `true`, the rendered prompt + /// sandbox for this thread. When `true`, the rendered prompt /// describes the sandbox's read/write/network rules and the /// per-command flags the model can request to relax them. When /// `false`, the prompt omits the sandbox section entirely. @@ -196,7 +196,7 @@ mod tests { assert!(rendered.contains("fs_write_paths")); assert!(rendered.contains("allow_fs_write_all: true")); assert!(rendered.contains("unsandboxed: true")); - assert!(rendered.contains("remain in effect for the entire duration")); + assert!(rendered.contains("for the rest of the thread")); } #[test] diff --git a/crates/agent/src/templates/system_prompt.hbs b/crates/agent/src/templates/system_prompt.hbs index b3c2d97030040c..38d96632f27c79 100644 --- a/crates/agent/src/templates/system_prompt.hbs +++ b/crates/agent/src/templates/system_prompt.hbs @@ -193,7 +193,7 @@ The current project contains the following root directories: The `terminal` tool runs commands inside a sandbox with these permissions: - Reads: any path on the filesystem is readable. -- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this conversation{{#if worktrees}}, along with these project directories: +- Writes: a per-thread temporary directory exposed via `$TMPDIR`, `$TMP`, and `$TEMP` is writable and persists across `terminal` calls in this thread{{#if worktrees}}, along with these project directories: {{#each worktrees}} - `{{abs_path}}` {{/each}} @@ -207,9 +207,9 @@ You can request elevated permissions on individual `terminal` calls: - `allow_fs_write_all: true` — allow unrestricted filesystem writes. Only use this when the specific paths can't be enumerated up front. - `unsandboxed: true` — run the command with no sandbox at all. Use only when none of the above suffice. -The user will be prompted to approve before the command runs, and can grant a sandbox request for that command, for the rest of the conversation, or always. Once a write path is granted for the conversation or always, later commands writing under that path won't prompt again. +The user will be prompted to approve before the command runs, and can grant a sandbox request for that command, for the rest of the thread, or always. Once a write path is granted for the thread or always, later commands in this thread writing under that path won't prompt again. -These sandbox settings are guaranteed to remain in effect for the entire duration of this conversation. If they ever change, you will be told. +These sandbox settings are guaranteed to remain in effect for the entire duration of this thread. If they ever change, you will be told. {{/if}} {{#if model_name}} diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 19504207dff435..1b4cabc005a0b0 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -15,7 +15,7 @@ use feature_flags::{ UpdateTitleToolFeatureFlag, }; -use crate::sandboxing::{ConversationSandboxGrants, SandboxRequest, sandboxing_enabled}; +use crate::sandboxing::{SandboxRequest, ThreadSandboxGrants, sandboxing_enabled}; use agent_client_protocol::schema as acp; use agent_settings::{ AgentProfileId, AgentSettings, SUMMARIZE_THREAD_DETAILED_PROMPT, SUMMARIZE_THREAD_PROMPT, @@ -1011,11 +1011,11 @@ pub struct Thread { running_subagents: Vec>, inherits_parent_model_settings: bool, sandboxed_terminal_temp_dir: Option, - /// Sandbox permissions the user approved "for the rest of the - /// conversation". Shared with each tool call's event stream so repeated - /// requests for already-granted permissions skip the approval prompt. + /// Sandbox permissions the user approved "for the rest of the thread". + /// Shared with each tool call's event stream so repeated requests for + /// already-granted permissions skip the approval prompt. /// Never persisted — lives and dies with this thread. - sandbox_grants: Rc>, + sandbox_grants: Rc>, } impl Thread { @@ -1143,7 +1143,7 @@ impl Thread { running_subagents: Vec::new(), inherits_parent_model_settings: true, sandboxed_terminal_temp_dir: None, - sandbox_grants: Rc::new(RefCell::new(ConversationSandboxGrants::default())), + sandbox_grants: Rc::new(RefCell::new(ThreadSandboxGrants::default())), } } @@ -1488,7 +1488,7 @@ impl Thread { running_subagents: Vec::new(), inherits_parent_model_settings: true, sandboxed_terminal_temp_dir: db_thread.sandboxed_terminal_temp_dir, - sandbox_grants: Rc::new(RefCell::new(ConversationSandboxGrants::default())), + sandbox_grants: Rc::new(RefCell::new(ThreadSandboxGrants::default())), } } @@ -3873,8 +3873,8 @@ pub struct ToolCallEventStream { stream: ThreadEventStream, fs: Option>, cancellation_rx: watch::Receiver, - /// Shared, conversation-scoped sandbox grants (see [`Thread::sandbox_grants`]). - sandbox_grants: Rc>, + /// Shared, thread-scoped sandbox grants (see [`Thread::sandbox_grants`]). + sandbox_grants: Rc>, } impl ToolCallEventStream { @@ -3894,7 +3894,7 @@ impl ToolCallEventStream { ThreadEventStream(events_tx), None, cancellation_rx, - Rc::new(RefCell::new(ConversationSandboxGrants::default())), + Rc::new(RefCell::new(ThreadSandboxGrants::default())), ); ( @@ -3915,7 +3915,7 @@ impl ToolCallEventStream { stream: ThreadEventStream, fs: Option>, cancellation_rx: watch::Receiver, - sandbox_grants: Rc>, + sandbox_grants: Rc>, ) -> Self { Self { tool_use_id, @@ -4109,10 +4109,10 @@ impl ToolCallEventStream { /// filesystem write access) on user approval. /// /// Offers the user three grant lifetimes — "once", "for the rest of this - /// conversation", and "always". Conversation grants live in the shared, - /// in-memory [`ConversationSandboxGrants`]. Always grants are persisted in - /// agent settings and are also observed while a prompt is pending, matching - /// the settings-driven authorization flow for regular tools. + /// thread", and "always". Thread grants live in the shared, in-memory + /// [`ThreadSandboxGrants`]. Always grants are persisted in agent settings + /// and are also observed while a prompt is pending, matching the + /// settings-driven authorization flow for regular tools. pub(crate) fn authorize_sandbox( &self, title: impl Into, @@ -4136,8 +4136,8 @@ impl ToolCallEventStream { acp::PermissionOptionKind::AllowOnce, ), acp::PermissionOption::new( - acp::PermissionOptionId::new("allow_conversation"), - "Allow for this conversation", + acp::PermissionOptionId::new("allow_thread"), + "Allow for this thread", acp::PermissionOptionKind::AllowAlways, ), acp::PermissionOption::new( @@ -4228,7 +4228,7 @@ impl ToolCallEventStream { fn sandbox_request_covered_by_grants( request: &SandboxRequest, - sandbox_grants: &Rc>, + sandbox_grants: &Rc>, cx: &App, ) -> bool { let settings = AgentSettings::get_global(cx); @@ -4240,7 +4240,7 @@ impl ToolCallEventStream { fn handle_sandbox_permission_outcome( outcome: &acp_thread::SelectedPermissionOutcome, request: &SandboxRequest, - sandbox_grants: Rc>, + sandbox_grants: Rc>, fs: Option>, cx: &AsyncApp, ) -> Result<()> { @@ -4251,7 +4251,7 @@ impl ToolCallEventStream { match outcome.option_id.0.as_ref() { "allow" => Ok(()), - "allow_conversation" => { + "allow_thread" => { sandbox_grants.borrow_mut().record(request); Ok(()) } @@ -4890,7 +4890,7 @@ mod tests { .collect::>(); assert_eq!( option_ids, - vec!["allow", "allow_conversation", "allow_always", "deny"] + vec!["allow", "allow_thread", "allow_always", "deny"] ); let send_result = authorization diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 82af4361543ead..f3a08e3bd7ba8d 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -319,7 +319,7 @@ impl AgentTool for SandboxedTerminalTool { } else if request.needs_escalation() { let title = sandbox_approval_title(&request); // Sandbox escalations always prompt (unless already granted - // for the conversation), independent of any `always_allow` + // for the thread), independent of any `always_allow` // tool-permission rules — the escalation is a stronger trust // boundary than the baseline command approval. let approve = @@ -340,9 +340,9 @@ impl AgentTool for SandboxedTerminalTool { // project. let sandbox_wrap = if sandboxing && !want_unsandboxed { // Apply standing grants on top of this command's request, so - // a path approved "for the rest of the conversation" or - // "always" stays writable for later commands even when the - // model doesn't re-request it. + // a path approved "for the rest of the thread" or "always" + // stays writable for later commands even when the model + // doesn't re-request it. let sandbox_permissions = cx.update(|cx| { agent_settings::AgentSettings::get_global(cx) .sandbox_permissions diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index 5fc82dfe6562d7..f2be7805803463 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -7560,8 +7560,8 @@ pub(crate) mod tests { acp::PermissionOptionKind::AllowOnce, ), acp::PermissionOption::new( - acp::PermissionOptionId::new("allow_conversation"), - "Allow for this conversation", + acp::PermissionOptionId::new("allow_thread"), + "Allow for this thread", acp::PermissionOptionKind::AllowAlways, ), acp::PermissionOption::new( diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index cec374af2023ef..b579205b6349c5 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -7953,7 +7953,7 @@ impl ThreadView { Icon::new(IconName::CheckDouble) .size(IconSize::XSmall) .color(Color::Success), - if option.option_id.0.as_ref() == "allow_conversation" { + if option.option_id.0.as_ref() == "allow_thread" { None } else { Some(&AllowAlways as &dyn Action) From f4da3657b2a1510c2c3bdf822c5207d070214018 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 14:04:34 -0700 Subject: [PATCH 09/11] Support legacy sandbox filesystem write flag --- crates/agent/src/thread.rs | 27 +++++- crates/agent/src/tools/terminal_tool.rs | 105 +++++++++++++++++++++++- 2 files changed, 127 insertions(+), 5 deletions(-) diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 1b4cabc005a0b0..e30af0fc462242 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -4884,13 +4884,32 @@ mod tests { let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { panic!("expected flat sandbox permission options"); }; - let option_ids = options + let options = options .iter() - .map(|option| option.option_id.0.as_ref()) + .map(|option| { + ( + option.option_id.0.as_ref(), + option.name.as_ref(), + option.kind, + ) + }) .collect::>(); assert_eq!( - option_ids, - vec!["allow", "allow_thread", "allow_always", "deny"] + options, + vec![ + ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce), + ( + "allow_thread", + "Allow for this thread", + acp::PermissionOptionKind::AllowAlways, + ), + ( + "allow_always", + "Allow always", + acp::PermissionOptionKind::AllowAlways, + ), + ("deny", "Deny", acp::PermissionOptionKind::RejectOnce), + ] ); let send_result = authorization diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index f3a08e3bd7ba8d..318a8cafadb1a2 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -108,7 +108,7 @@ pub struct SandboxedTerminalToolInput { /// /// This is a broad escape hatch — prefer `fs_write_paths` whenever the /// set of paths is known. Requesting it triggers a user approval prompt. - #[serde(default)] + #[serde(default, alias = "allow_fs_write")] pub allow_fs_write_all: Option, /// Set to `true` only as a last resort, to run the command fully outside /// the sandbox. @@ -1931,4 +1931,107 @@ mod tests { assert_eq!(input.allow_fs_write_all, None); assert_eq!(input.unsandboxed, None); } + + #[test] + fn test_legacy_allow_fs_write_aliases_to_allow_fs_write_all() { + let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({ + "command": "echo hi", + "cd": ".", + "allow_fs_write": true, + })) + .expect("legacy allow_fs_write should deserialize"); + + assert_eq!(input.allow_fs_write_all, Some(true)); + } + + #[cfg(target_os = "macos")] + #[gpui::test] + async fn test_legacy_allow_fs_write_uses_sandbox_permission_options( + cx: &mut gpui::TestAppContext, + ) { + use feature_flags::FeatureFlagAppExt as _; + + crate::tests::init_test(cx); + cx.update(|cx| { + cx.update_flags(true, vec!["sandboxing".to_string()]); + let mut settings = agent_settings::AgentSettings::get_global(cx).clone(); + settings.tool_permissions.default = settings::ToolPermissionMode::Allow; + settings.tool_permissions.tools.remove(TerminalTool::NAME); + agent_settings::AgentSettings::override_global(settings, cx); + }); + + let fs = fs::FakeFs::new(cx.executor()); + fs.insert_tree("/root", serde_json::json!({})).await; + let project = project::Project::test(fs, ["/root".as_ref()], cx).await; + + let environment = std::rc::Rc::new(cx.update(|cx| { + crate::tests::FakeThreadEnvironment::default().with_terminal( + crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0), + ) + })); + #[allow(clippy::arc_with_non_send_sync)] + let tool = std::sync::Arc::new(SandboxedTerminalTool::new(project, environment.clone())); + let (event_stream, mut receiver) = crate::ToolCallEventStream::test(); + let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({ + "command": "echo hi", + "cd": "root", + "allow_fs_write": true, + })) + .expect("legacy allow_fs_write should deserialize"); + + let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx)); + + let authorization = receiver.expect_authorization().await; + let details = + acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta) + .expect("legacy allow_fs_write should request sandbox authorization details"); + assert!(!details.network); + assert!(details.allow_fs_write_all); + assert!(details.write_paths.is_empty()); + + let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { + panic!("expected flat sandbox permission options"); + }; + let options = options + .iter() + .map(|option| { + ( + option.option_id.0.as_ref(), + option.name.as_ref(), + option.kind, + ) + }) + .collect::>(); + assert_eq!( + options, + vec![ + ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce), + ( + "allow_thread", + "Allow for this thread", + acp::PermissionOptionKind::AllowAlways, + ), + ( + "allow_always", + "Allow always", + acp::PermissionOptionKind::AllowAlways, + ), + ("deny", "Deny", acp::PermissionOptionKind::RejectOnce), + ] + ); + + authorization + .response + .send(acp_thread::SelectedPermissionOutcome::new( + acp::PermissionOptionId::new("deny"), + acp::PermissionOptionKind::RejectOnce, + )) + .expect("authorization response should send"); + + let result = task + .await + .expect("denied sandbox request returns model-readable output"); + assert!(result.contains("user denied the requested sandbox permissions")); + assert_eq!(environment.terminal_creation_count(), 0); + } } From 6b026b579781b3fffb5cb1002f265ea76a08b6c2 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 14:46:35 -0700 Subject: [PATCH 10/11] remove terminaltoolwithouttail --- crates/agent/src/thread.rs | 49 ++---- crates/agent/src/tools/terminal_tool.rs | 222 ------------------------ 2 files changed, 11 insertions(+), 260 deletions(-) diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index 1efb0f956e3063..fb57704906ae2f 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -3,9 +3,9 @@ use crate::{ DbLanguageModel, DbThread, DeletePathTool, DiagnosticsTool, EditFileTool, FetchTool, FindPathTool, FindReferencesTool, GetCodeActionsTool, GoToDefinitionTool, GrepTool, ListDirectoryTool, MovePathTool, ProjectSnapshot, ReadFileTool, RenameTool, - SandboxedTerminalTool, SandboxedTerminalToolWithoutTail, SpawnAgentTool, SystemPromptTemplate, - Template, Templates, TerminalTool, TerminalToolWithoutTail, ToolPermissionDecision, - UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, decide_permission_from_settings, + SandboxedTerminalTool, SpawnAgentTool, SystemPromptTemplate, Template, Templates, TerminalTool, + ToolPermissionDecision, UpdatePlanTool, UpdateTitleTool, WebSearchTool, WriteFileTool, + decide_permission_from_settings, }; use acp_thread::{MentionUri, UserMessageId}; use action_log::ActionLog; @@ -1762,22 +1762,13 @@ impl Thread { self.action_log.clone(), update_agent_location, )); - // Register all terminal tool variants; `enabled_tools` exposes the - // one matching the current sandbox and terminal-tail feature state to - // the model as `terminal`. + // Register terminal tool variants; `enabled_tools` exposes the one + // matching the current sandbox state to the model as `terminal`. self.add_tool(TerminalTool::new(self.project.clone(), environment.clone())); - self.add_tool(TerminalToolWithoutTail::new( - self.project.clone(), - environment.clone(), - )); self.add_tool(SandboxedTerminalTool::new( self.project.clone(), environment.clone(), )); - self.add_tool(SandboxedTerminalToolWithoutTail::new( - self.project.clone(), - environment.clone(), - )); self.add_tool(WebSearchTool); self.add_tool(DiagnosticsTool::new(self.project.clone())); @@ -3106,10 +3097,9 @@ impl Thread { } // Terminal variants are configured by users under the canonical - // `terminal` name. Expose the one matching the current sandbox and - // terminal-tail feature state to the model under that name. + // `terminal` name. Expose the one matching the current sandbox state + // to the model under that name. let use_sandboxed_terminal = sandboxing_enabled(cx); - let use_terminal_tail = cx.has_flag::(); let mut tools = self .tools @@ -3117,10 +3107,7 @@ impl Thread { .filter_map(|(tool_name, tool)| { let terminal_variant = matches!( tool_name.as_ref(), - TerminalTool::NAME - | TerminalToolWithoutTail::NAME - | SandboxedTerminalTool::NAME - | SandboxedTerminalToolWithoutTail::NAME + TerminalTool::NAME | SandboxedTerminalTool::NAME ); let profile_tool_name = if terminal_variant { TerminalTool::NAME @@ -3131,25 +3118,11 @@ impl Thread { if tool.supports_provider(&model.provider_id()) && profile.is_tool_enabled(profile_tool_name) { - match ( - tool_name.as_ref(), - use_sandboxed_terminal, - use_terminal_tail, - ) { - (TerminalTool::NAME, false, true) - | (TerminalToolWithoutTail::NAME, false, false) - | (SandboxedTerminalTool::NAME, true, true) - | (SandboxedTerminalToolWithoutTail::NAME, true, false) => { + match (tool_name.as_ref(), use_sandboxed_terminal) { + (TerminalTool::NAME, false) | (SandboxedTerminalTool::NAME, true) => { Some((SharedString::from(TerminalTool::NAME), tool.clone())) } - ( - TerminalTool::NAME - | TerminalToolWithoutTail::NAME - | SandboxedTerminalTool::NAME - | SandboxedTerminalToolWithoutTail::NAME, - _, - _, - ) => None, + (TerminalTool::NAME | SandboxedTerminalTool::NAME, _) => None, _ => Some((truncate(tool_name), tool.clone())), } } else { diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 1e7ec8d8f5695c..9ac3607e9996c2 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -59,51 +59,6 @@ pub struct TerminalToolInput { pub tail_lines: Option, } -/// Executes a shell one-liner and returns the combined output. -/// -/// This tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result. -/// -/// The output results will be shown to the user already, only list it again if necessary, avoid being redundant. -/// -/// Make sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error. -/// -/// Do not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values before calling this tool, or ask the user for the literal value to use. -/// -/// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own. -/// -/// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs. -/// -/// Remember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations. -/// -/// The terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this: -/// -/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`). -/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`). -/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly. -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] -pub struct TerminalToolInputWithoutTail { - /// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user for the literal value to use. - /// - /// REMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang. - pub command: String, - /// Working directory for the command. This must be one of the root directories of the project. - pub cd: String, - /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed. - pub timeout_ms: Option, -} - -impl From for TerminalToolInput { - fn from(input: TerminalToolInputWithoutTail) -> Self { - Self { - command: input.command, - cd: input.cd, - timeout_ms: input.timeout_ms, - head_lines: None, - tail_lines: None, - } - } -} - /// Executes a shell one-liner and returns the combined output. /// /// This tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result. @@ -182,67 +137,6 @@ pub struct SandboxedTerminalToolInput { pub unsandboxed: Option, } -/// Executes a shell one-liner and returns the combined output. -/// -/// This tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result. -/// -/// The output results will be shown to the user already, only list it again if necessary, avoid being redundant. -/// -/// Make sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error. -/// -/// Do not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values first or ask the user for the literal value to use. -/// -/// Do not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own. -/// -/// For potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs. -/// -/// Remember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations. -/// -/// The terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this: -/// -/// - Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`). -/// - Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`). -/// - For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly. -#[derive(Clone, Debug, Default, Serialize, Deserialize, JsonSchema)] -pub struct SandboxedTerminalToolInputWithoutTail { - /// The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user for the literal value to use. - /// - /// REMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang. - pub command: String, - /// Working directory for the command. This must be one of the root directories of the project. - pub cd: String, - /// Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed. - pub timeout_ms: Option, - /// Set to `true` only if the command needs outbound network access. - #[serde(default)] - pub allow_network: Option, - /// Paths the command needs to write to outside the default-writable locations. - #[serde(default)] - pub fs_write_paths: Vec, - /// Set to `true` only when the command needs to write outside the default-writable locations but the specific paths cannot be enumerated up front. - #[serde(default, alias = "allow_fs_write")] - pub allow_fs_write_all: Option, - /// Set to `true` only as a last resort, to run the command fully outside the sandbox. - #[serde(default)] - pub unsandboxed: Option, -} - -impl From for SandboxedTerminalToolInput { - fn from(input: SandboxedTerminalToolInputWithoutTail) -> Self { - Self { - command: input.command, - cd: input.cd, - timeout_ms: input.timeout_ms, - head_lines: None, - tail_lines: None, - allow_network: input.allow_network, - fs_write_paths: input.fs_write_paths, - allow_fs_write_all: input.allow_fs_write_all, - unsandboxed: input.unsandboxed, - } - } -} - #[derive(Clone, Debug, Default)] struct TerminalSandboxInput { allow_network: Option, @@ -274,12 +168,6 @@ impl From for TerminalToolRequest { } } -impl From for TerminalToolRequest { - fn from(input: TerminalToolInputWithoutTail) -> Self { - TerminalToolInput::from(input).into() - } -} - impl From for TerminalToolRequest { fn from(input: SandboxedTerminalToolInput) -> Self { Self { @@ -300,12 +188,6 @@ impl From for TerminalToolRequest { } } -impl From for TerminalToolRequest { - fn from(input: SandboxedTerminalToolInputWithoutTail) -> Self { - SandboxedTerminalToolInput::from(input).into() - } -} - pub struct TerminalTool { project: Entity, environment: Rc, @@ -320,20 +202,6 @@ impl TerminalTool { } } -pub struct TerminalToolWithoutTail { - project: Entity, - environment: Rc, -} - -impl TerminalToolWithoutTail { - pub fn new(project: Entity, environment: Rc) -> Self { - Self { - project, - environment, - } - } -} - pub struct SandboxedTerminalTool { project: Entity, environment: Rc, @@ -348,20 +216,6 @@ impl SandboxedTerminalTool { } } -pub struct SandboxedTerminalToolWithoutTail { - project: Entity, - environment: Rc, -} - -impl SandboxedTerminalToolWithoutTail { - pub fn new(project: Entity, environment: Rc) -> Self { - Self { - project, - environment, - } - } -} - impl AgentTool for TerminalTool { type Input = TerminalToolInput; type Output = String; @@ -400,44 +254,6 @@ impl AgentTool for TerminalTool { } } -impl AgentTool for TerminalToolWithoutTail { - type Input = TerminalToolInputWithoutTail; - type Output = String; - - const NAME: &'static str = "terminal_without_tail"; - - fn kind() -> acp::ToolKind { - acp::ToolKind::Execute - } - - fn initial_title( - &self, - input: Result, - _cx: &mut App, - ) -> SharedString { - terminal_initial_title(input.map(|input| input.command)) - } - - fn run( - self: Arc, - input: ToolInput, - event_stream: ToolCallEventStream, - cx: &mut App, - ) -> Task> { - cx.spawn(async move |cx| { - let input = input.recv().await.map_err(|e| e.to_string())?; - run_terminal_tool( - self.project.clone(), - self.environment.clone(), - input.into(), - event_stream, - cx, - ) - .await - }) - } -} - impl AgentTool for SandboxedTerminalTool { type Input = SandboxedTerminalToolInput; type Output = String; @@ -476,44 +292,6 @@ impl AgentTool for SandboxedTerminalTool { } } -impl AgentTool for SandboxedTerminalToolWithoutTail { - type Input = SandboxedTerminalToolInputWithoutTail; - type Output = String; - - const NAME: &'static str = "sandboxed_terminal_without_tail"; - - fn kind() -> acp::ToolKind { - acp::ToolKind::Execute - } - - fn initial_title( - &self, - input: Result, - _cx: &mut App, - ) -> SharedString { - terminal_initial_title(input.map(|input| input.command)) - } - - fn run( - self: Arc, - input: ToolInput, - event_stream: ToolCallEventStream, - cx: &mut App, - ) -> Task> { - cx.spawn(async move |cx| { - let input = input.recv().await.map_err(|e| e.to_string())?; - run_terminal_tool( - self.project.clone(), - self.environment.clone(), - input.into(), - event_stream, - cx, - ) - .await - }) - } -} - fn terminal_initial_title(input: Result) -> SharedString { if let Ok(command) = input { command.into() From ffce2ea08463f9ca4c9472fa35567eb84959d801 Mon Sep 17 00:00:00 2001 From: Martin Ye Date: Mon, 1 Jun 2026 15:00:26 -0700 Subject: [PATCH 11/11] fix allow_unsandboxed --- crates/acp_thread/src/acp_thread.rs | 5 + crates/agent/src/sandboxing.rs | 48 ++++++- crates/agent/src/thread.rs | 6 + crates/agent/src/tools/terminal_tool.rs | 140 +++++++++++++++++--- crates/agent_settings/src/agent_settings.rs | 28 +++- crates/settings_content/src/agent.rs | 13 ++ 6 files changed, 213 insertions(+), 27 deletions(-) diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index b439b73feaa5b6..6a8f509f75c760 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -81,8 +81,13 @@ pub const SANDBOX_AUTHORIZATION_META_KEY: &str = "sandbox_authorization"; #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct SandboxAuthorizationDetails { + #[serde(default)] pub network: bool, + #[serde(default)] pub allow_fs_write_all: bool, + #[serde(default)] + pub unsandboxed: bool, + #[serde(default)] pub write_paths: Vec, } diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index ed36af5604a515..d36813c4bbef0a 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -38,6 +38,8 @@ pub(crate) struct SandboxRequest { pub network: bool, /// Allow unrestricted filesystem writes (the broad escape hatch). pub allow_fs_write_all: bool, + /// Run the command fully outside the sandbox. + pub unsandboxed: bool, /// Concrete paths the command needs to write to. Each grants its whole /// subtree. These are never globs — write access is always a concrete path subtree pub write_paths: Vec, @@ -47,7 +49,7 @@ impl SandboxRequest { /// Whether this request asks for anything beyond the default sandbox /// scope, and therefore needs user approval. pub fn needs_escalation(&self) -> bool { - self.network || self.allow_fs_write_all || !self.write_paths.is_empty() + self.network || self.allow_fs_write_all || self.unsandboxed || !self.write_paths.is_empty() } } @@ -62,6 +64,7 @@ impl SandboxRequest { pub(crate) struct ThreadSandboxGrants { network: bool, allow_fs_write_all: bool, + unsandboxed: bool, /// Canonicalized paths granted write access for the thread. Each covers its /// whole subtree; redundant children are pruned on insert. write_paths: Vec, @@ -80,6 +83,9 @@ impl ThreadSandboxGrants { request: &SandboxRequest, persistent: &SandboxPermissions, ) -> bool { + if request.unsandboxed { + return self.unsandboxed || persistent.allow_unsandboxed; + } if request.network && !(self.network || persistent.allow_network) { return false; } @@ -104,6 +110,7 @@ impl ThreadSandboxGrants { pub fn record(&mut self, request: &SandboxRequest) { self.network |= request.network; self.allow_fs_write_all |= request.allow_fs_write_all; + self.unsandboxed |= request.unsandboxed; for path in &request.write_paths { add_write_path(&mut self.write_paths, path); } @@ -135,6 +142,7 @@ impl ThreadSandboxGrants { allow_fs_write_all: persistent.allow_fs_write_all || self.allow_fs_write_all || request.allow_fs_write_all, + unsandboxed: request.unsandboxed, write_paths, } } @@ -159,10 +167,20 @@ mod tests { SandboxRequest { network, allow_fs_write_all: all, + unsandboxed: false, write_paths: paths.iter().map(PathBuf::from).collect(), } } + fn unsandboxed_request() -> SandboxRequest { + SandboxRequest { + network: false, + allow_fs_write_all: false, + unsandboxed: true, + write_paths: Vec::new(), + } + } + fn covers(grants: &ThreadSandboxGrants, request: &SandboxRequest) -> bool { grants.covers_with_persistent(request, &SandboxPermissions::default()) } @@ -176,6 +194,7 @@ mod tests { let grants = ThreadSandboxGrants::default(); assert!(!covers(&grants, &request(true, false, &[]))); assert!(!covers(&grants, &request(false, true, &[]))); + assert!(!covers(&grants, &unsandboxed_request())); assert!(!covers(&grants, &request(false, false, &["/tmp/build"]))); } @@ -231,6 +250,15 @@ mod tests { assert!(!covers(&grants, &request(true, false, &["/tmp/build"]))); } + #[test] + fn unsandboxed_grant_tracked_independently() { + let mut grants = ThreadSandboxGrants::default(); + grants.record(&unsandboxed_request()); + assert!(covers(&grants, &unsandboxed_request())); + assert!(!covers(&grants, &request(true, false, &[]))); + assert!(!covers(&grants, &request(false, true, &[]))); + } + #[test] fn persistent_grants_combine_with_thread_grants() { let mut grants = ThreadSandboxGrants::default(); @@ -238,6 +266,7 @@ mod tests { let persistent = SandboxPermissions { allow_network: false, allow_fs_write_all: false, + allow_unsandboxed: false, write_paths: vec![PathBuf::from("/tmp/build")], }; @@ -256,6 +285,7 @@ mod tests { let persistent = SandboxPermissions { allow_network: false, allow_fs_write_all: true, + allow_unsandboxed: false, write_paths: Vec::new(), }; @@ -264,6 +294,21 @@ mod tests { assert!(!grants.covers_with_persistent(&request(true, false, &[]), &persistent)); } + #[test] + fn persistent_unsandboxed_covers_unsandboxed_requests_only() { + let grants = ThreadSandboxGrants::default(); + let persistent = SandboxPermissions { + allow_network: false, + allow_fs_write_all: false, + allow_unsandboxed: true, + write_paths: Vec::new(), + }; + + assert!(grants.covers_with_persistent(&unsandboxed_request(), &persistent)); + assert!(!grants.covers_with_persistent(&request(true, false, &[]), &persistent)); + assert!(!grants.covers_with_persistent(&request(false, true, &[]), &persistent)); + } + #[test] fn effective_applies_thread_grants_to_empty_request() { // The core fix: a command that requests nothing still gets the @@ -296,6 +341,7 @@ mod tests { let persistent = SandboxPermissions { allow_network: true, allow_fs_write_all: false, + allow_unsandboxed: false, write_paths: vec![PathBuf::from("/tmp/always")], }; diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index fb57704906ae2f..8fca230be1d1ee 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -4291,6 +4291,7 @@ impl ToolCallEventStream { let sandbox_authorization_details = acp_thread::SandboxAuthorizationDetails { network: request.network, allow_fs_write_all: request.allow_fs_write_all, + unsandboxed: request.unsandboxed, write_paths: request.write_paths.clone(), }; let options = acp_thread::PermissionOptions::Flat(vec![ @@ -4451,6 +4452,9 @@ impl ToolCallEventStream { if request.allow_fs_write_all { agent.allow_sandbox_fs_write_all(); } + if request.unsandboxed { + agent.allow_sandbox_unsandboxed(); + } for path in request.write_paths { agent.add_sandbox_write_path(path); } @@ -5240,6 +5244,7 @@ mod tests { let request = SandboxRequest { network: false, allow_fs_write_all: false, + unsandboxed: false, write_paths: vec![ PathBuf::from("/tmp/build"), PathBuf::from("/tmp/cache"), @@ -5257,6 +5262,7 @@ mod tests { .expect("sandbox authorization should include request details"); assert_eq!(details.network, request.network); assert_eq!(details.allow_fs_write_all, request.allow_fs_write_all); + assert_eq!(details.unsandboxed, request.unsandboxed); assert_eq!(details.write_paths, request.write_paths); assert!(authorization.tool_call.fields.content.is_none()); diff --git a/crates/agent/src/tools/terminal_tool.rs b/crates/agent/src/tools/terminal_tool.rs index 9ac3607e9996c2..2644be6b0e21cc 100644 --- a/crates/agent/src/tools/terminal_tool.rs +++ b/crates/agent/src/tools/terminal_tool.rs @@ -340,30 +340,21 @@ async fn run_terminal_tool( }; let request = crate::sandboxing::SandboxRequest { - network: want_network, - allow_fs_write_all: want_fs_write_all, + network: !want_unsandboxed && want_network, + allow_fs_write_all: !want_unsandboxed && want_fs_write_all, + unsandboxed: want_unsandboxed, write_paths, }; - if want_unsandboxed { - let approve = cx.update(|cx| { - let context = - crate::ToolPermissionContext::new(TerminalTool::NAME, vec![input.command.clone()]); - event_stream.authorize_always_prompt( - "Allow this command to run outside the sandbox?", - context, - cx, - ) - }); - if let Err(error) = approve.await { - return Ok(format!( - "Command cancelled: user denied permission to run outside the sandbox ({error})." - )); - } - } else if request.needs_escalation() { + if request.needs_escalation() { let title = sandbox_approval_title(&request); let approve = cx.update(|cx| event_stream.authorize_sandbox(title, request.clone(), cx)); if let Err(error) = approve.await { + if want_unsandboxed { + return Ok(format!( + "Command cancelled: user denied permission to run outside the sandbox ({error})." + )); + } return Ok(format!( "Command cancelled: user denied the requested sandbox permissions ({error})." )); @@ -516,6 +507,10 @@ fn join_write_paths(raw_paths: &[String], base: Option<&Path>) -> Vec { /// when the request actually asks for something (see /// [`crate::sandboxing::SandboxRequest::needs_escalation`]). fn sandbox_approval_title(request: &crate::sandboxing::SandboxRequest) -> String { + if request.unsandboxed { + return "Allow this command to run outside the sandbox?".to_string(); + } + let mut parts: Vec = Vec::new(); if request.network { parts.push("network access".to_string()); @@ -1582,7 +1577,6 @@ mod tests { timeout_ms: None, head_lines: Some(1), tail_lines: Some(1), - ..Default::default() }), event_stream, cx, @@ -2258,6 +2252,7 @@ mod tests { crate::sandboxing::SandboxRequest { network, allow_fs_write_all: all, + unsandboxed: false, write_paths: paths.iter().map(PathBuf::from).collect(), } } @@ -2305,6 +2300,16 @@ mod tests { assert_eq!(joined, vec![PathBuf::from(abs)]); } + #[test] + fn test_sandbox_approval_title_unsandboxed() { + let mut request = sandbox_request(true, true, &["/tmp/build"]); + request.unsandboxed = true; + assert_eq!( + sandbox_approval_title(&request), + "Allow this command to run outside the sandbox?" + ); + } + #[test] fn test_sandbox_approval_title_all_access_and_network() { assert_eq!( @@ -2447,6 +2452,7 @@ mod tests { .expect("legacy allow_fs_write should request sandbox authorization details"); assert!(!details.network); assert!(details.allow_fs_write_all); + assert!(!details.unsandboxed); assert!(details.write_paths.is_empty()); let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { @@ -2494,4 +2500,100 @@ mod tests { assert!(result.contains("user denied the requested sandbox permissions")); assert_eq!(environment.terminal_creation_count(), 0); } + + #[cfg(target_os = "macos")] + #[gpui::test] + async fn test_unsandboxed_uses_sandbox_permission_options(cx: &mut gpui::TestAppContext) { + use feature_flags::FeatureFlagAppExt as _; + + crate::tests::init_test(cx); + cx.update(|cx| { + cx.update_flags(true, vec!["sandboxing".to_string()]); + let mut settings = agent_settings::AgentSettings::get_global(cx).clone(); + settings.tool_permissions.default = settings::ToolPermissionMode::Allow; + settings.tool_permissions.tools.remove(TerminalTool::NAME); + agent_settings::AgentSettings::override_global(settings, cx); + }); + + let fs = fs::FakeFs::new(cx.executor()); + fs.insert_tree("/root", serde_json::json!({})).await; + let project = project::Project::test(fs, ["/root".as_ref()], cx).await; + + let environment = std::rc::Rc::new(cx.update(|cx| { + crate::tests::FakeThreadEnvironment::default().with_terminal( + crate::tests::FakeTerminalHandle::new_with_immediate_exit(cx, 0), + ) + })); + #[allow(clippy::arc_with_non_send_sync)] + let tool = std::sync::Arc::new(SandboxedTerminalTool::new(project, environment.clone())); + let (event_stream, mut receiver) = crate::ToolCallEventStream::test(); + let input: SandboxedTerminalToolInput = serde_json::from_value(serde_json::json!({ + "command": "echo hi", + "cd": "root", + "allow_network": true, + "allow_fs_write_all": true, + "unsandboxed": true, + })) + .expect("unsandboxed input should deserialize"); + + let task = cx.update(|cx| tool.run(crate::ToolInput::resolved(input), event_stream, cx)); + + let authorization = receiver.expect_authorization().await; + assert_eq!( + authorization.tool_call.fields.title.as_deref(), + Some("Allow this command to run outside the sandbox?") + ); + let details = + acp_thread::sandbox_authorization_details_from_meta(&authorization.tool_call.meta) + .expect("unsandboxed should request sandbox authorization details"); + assert!(!details.network); + assert!(!details.allow_fs_write_all); + assert!(details.unsandboxed); + assert!(details.write_paths.is_empty()); + + let acp_thread::PermissionOptions::Flat(options) = &authorization.options else { + panic!("expected flat sandbox permission options"); + }; + let options = options + .iter() + .map(|option| { + ( + option.option_id.0.as_ref(), + option.name.as_ref(), + option.kind, + ) + }) + .collect::>(); + assert_eq!( + options, + vec![ + ("allow", "Allow once", acp::PermissionOptionKind::AllowOnce), + ( + "allow_thread", + "Allow for this thread", + acp::PermissionOptionKind::AllowAlways, + ), + ( + "allow_always", + "Allow always", + acp::PermissionOptionKind::AllowAlways, + ), + ("deny", "Deny", acp::PermissionOptionKind::RejectOnce), + ] + ); + + authorization + .response + .send(acp_thread::SelectedPermissionOutcome::new( + acp::PermissionOptionId::new("deny"), + acp::PermissionOptionKind::RejectOnce, + )) + .expect("authorization response should send"); + + let result = task + .await + .expect("denied sandbox request returns model-readable output"); + assert!(result.contains("user denied permission to run outside the sandbox")); + assert_eq!(environment.terminal_creation_count(), 0); + } } diff --git a/crates/agent_settings/src/agent_settings.rs b/crates/agent_settings/src/agent_settings.rs index e45364aab5586f..b25081080fb9d6 100644 --- a/crates/agent_settings/src/agent_settings.rs +++ b/crates/agent_settings/src/agent_settings.rs @@ -342,11 +342,21 @@ impl Default for AgentProfileId { pub struct SandboxPermissions { pub allow_network: bool, pub allow_fs_write_all: bool, + pub allow_unsandboxed: bool, pub write_paths: Vec, } impl SandboxPermissions { - pub fn covers(&self, network: bool, allow_fs_write_all: bool, write_paths: &[PathBuf]) -> bool { + pub fn covers( + &self, + network: bool, + allow_fs_write_all: bool, + unsandboxed: bool, + write_paths: &[PathBuf], + ) -> bool { + if unsandboxed { + return self.allow_unsandboxed; + } if network && !self.allow_network { return false; } @@ -723,6 +733,7 @@ fn compile_sandbox_permissions( SandboxPermissions { allow_network: content.allow_network.unwrap_or(false), allow_fs_write_all: content.allow_fs_write_all.unwrap_or(false), + allow_unsandboxed: content.allow_unsandboxed.unwrap_or(false), write_paths, } } @@ -913,15 +924,17 @@ mod tests { fn test_sandbox_permissions_empty() { let permissions = compile_sandbox_permissions(None); assert_eq!(permissions, SandboxPermissions::default()); - assert!(!permissions.covers(true, false, &[])); - assert!(!permissions.covers(false, true, &[])); - assert!(!permissions.covers(false, false, &[PathBuf::from("/tmp/build")])); + assert!(!permissions.covers(true, false, false, &[])); + assert!(!permissions.covers(false, true, false, &[])); + assert!(!permissions.covers(false, false, true, &[])); + assert!(!permissions.covers(false, false, false, &[PathBuf::from("/tmp/build")])); } #[test] fn test_sandbox_permissions_parsing_and_pruning() { let json = json!({ "allow_network": true, + "allow_unsandboxed": true, "write_paths": [ "/tmp/build/cache", "/tmp/build", @@ -934,11 +947,12 @@ mod tests { assert!(permissions.allow_network); assert!(!permissions.allow_fs_write_all); + assert!(permissions.allow_unsandboxed); assert_eq!( permissions.write_paths, vec![PathBuf::from("/tmp/build"), PathBuf::from("/var/log")] ); - assert!(permissions.covers(true, false, &[PathBuf::from("/tmp/build/cache")])) + assert!(permissions.covers(true, false, true, &[PathBuf::from("/tmp/build/cache")])) } #[test] @@ -950,8 +964,8 @@ mod tests { let content: settings::SandboxPermissionsContent = serde_json::from_value(json).unwrap(); let permissions = compile_sandbox_permissions(Some(content)); - assert!(permissions.covers(false, true, &[])); - assert!(permissions.covers(false, false, &[PathBuf::from("/anywhere")])) + assert!(permissions.covers(false, true, false, &[])); + assert!(permissions.covers(false, false, false, &[PathBuf::from("/anywhere")])) } #[test] diff --git a/crates/settings_content/src/agent.rs b/crates/settings_content/src/agent.rs index a65e00df9acc1d..bd859908b3e952 100644 --- a/crates/settings_content/src/agent.rs +++ b/crates/settings_content/src/agent.rs @@ -334,6 +334,12 @@ impl AgentSettingsContent { .allow_fs_write_all = Some(true); } + pub fn allow_sandbox_unsandboxed(&mut self) { + self.sandbox_permissions + .get_or_insert_default() + .allow_unsandboxed = Some(true); + } + pub fn add_sandbox_write_path(&mut self, path: PathBuf) { let write_paths = &mut self .sandbox_permissions @@ -615,6 +621,11 @@ pub struct SandboxPermissionsContent { /// Default: false pub allow_fs_write_all: Option, + /// Whether terminal commands may always run outside the sandbox without + /// prompting when they request `unsandboxed: true`. + /// Default: false + pub allow_unsandboxed: Option, + /// Directory subtrees that sandboxed terminal commands may always write /// to without prompting. Paths written by Zed are absolute. /// Default: [] @@ -894,11 +905,13 @@ mod tests { settings.allow_sandbox_network(); settings.allow_sandbox_fs_write_all(); + settings.allow_sandbox_unsandboxed(); settings.add_sandbox_write_path(PathBuf::from("/tmp/build")); let sandbox_permissions = settings.sandbox_permissions.as_ref().unwrap(); assert_eq!(sandbox_permissions.allow_network, Some(true)); assert_eq!(sandbox_permissions.allow_fs_write_all, Some(true)); + assert_eq!(sandbox_permissions.allow_unsandboxed, Some(true)); assert_eq!( sandbox_permissions .write_paths