1use crate::error::{Result, WebmcpError};
2use crate::protocol::FileChange;
3use crate::runtime::{
4 AppliedChange, CheckResult, FileSnapshot, PatchProposal, RuntimeAdapter, RuntimeStatus, TurnResult, WorkspaceFile,
5};
6use async_trait::async_trait;
7use hashbrown::HashMap as SandboxEnvironment;
8use sha2::{Digest, Sha256};
9use std::collections::HashSet;
10use std::io::Read;
11use std::path::{Component, Path, PathBuf};
12use std::process::Stdio;
13use std::sync::{Arc, Mutex};
14use std::time::Duration;
15use tokio::io::{AsyncRead, AsyncReadExt};
16use tokio::process::Command;
17use tokio::sync::Mutex as AsyncMutex;
18use uuid::Uuid;
19use vtcode_commons::exclusions::{SENSITIVE_FILES, is_sensitive_file};
20use vtcode_diff::{DiffDocument, DiffOptions, format_unified_hunks};
21use vtcode_safety::sandboxing::{
22 CommandSpec, ExecExpiration, LinuxSandboxLauncher, SandboxManager, SandboxPolicy, SensitivePath,
23 default_sensitive_paths,
24};
25
26const CHECK_TIMEOUT: Duration = Duration::from_secs(30);
27const MAX_CHECK_OUTPUT_BYTES: usize = 512 * 1024;
28const MAX_DIRECTORY_DEPTH: usize = 64;
29const MAX_VISITED_DIRECTORIES: usize = 16_384;
30const MAX_CHECK_SENSITIVE_PATHS: usize = 4096;
31const MAX_STORED_PROPOSALS: usize = 64;
32const MAX_STORED_PROPOSAL_BYTES: usize = 128 * 1024 * 1024;
33const IGNORED_DIRECTORY_NAMES: &[&str] = &[
34 ".cargo",
35 ".cache",
36 ".codegraph",
37 ".git",
38 ".mypy_cache",
39 ".opencode",
40 ".pytest_cache",
41 ".ruff_cache",
42 ".superpowers",
43 ".vscode",
44 ".worktrees",
45 ".vtcode",
46 "__pycache__",
47 "dist",
48 "node_modules",
49 "target",
50];
51const SENSITIVE_DIRECTORY_NAMES: &[&str] = &[
52 ".aws",
53 ".azure",
54 ".config",
55 ".docker",
56 ".gnupg",
57 ".kube",
58 ".pki",
59 ".secrets",
60 ".ssh",
61 ".terraform.d",
62];
63
64mod policy;
65mod runtime_adapter;
66mod secure_open;
67
68pub use policy::is_public_evidence_path;
69use policy::*;
70use secure_open::{
71 open_root_directory, open_workspace_file, read_snapshot_blocking, replace_snapshot_if_current_blocking,
72};
73
74#[derive(Debug, Clone, Copy)]
76pub struct FilesystemLimits {
77 pub max_files: usize,
79 pub max_file_bytes: usize,
81 pub max_total_bytes: usize,
83 pub max_changes: usize,
85 pub max_change_bytes: usize,
87}
88
89impl Default for FilesystemLimits {
90 fn default() -> Self {
91 Self {
92 max_files: 8192,
93 max_file_bytes: 2 * 1024 * 1024,
94 max_total_bytes: 64 * 1024 * 1024,
95 max_changes: 32,
96 max_change_bytes: 2 * 1024 * 1024,
97 }
98 }
99}
100
101#[derive(Debug, Clone)]
102struct StoredProposal {
103 proposal: PatchProposal,
104 before: Vec<FileSnapshot>,
105 size_bytes: usize,
106}
107
108#[derive(Debug, Clone)]
109struct StoredChange {
110 change_id: String,
111 before: Vec<FileSnapshot>,
112 after: Vec<FileSnapshot>,
113}
114
115#[derive(Debug, Default)]
116struct FilesystemState {
117 proposals: std::collections::HashMap<String, StoredProposal>,
118 proposal_bytes: usize,
119 last_change: Option<StoredChange>,
120}
121
122#[derive(Clone)]
124pub struct FilesystemWorkspace {
125 root: Arc<PathBuf>,
126 root_dir: Arc<std::fs::File>,
127 allowed_roots: Arc<Vec<PathBuf>>,
128 limits: FilesystemLimits,
129 mutations_allowed: bool,
130 checks_allowed: bool,
131 allowed_commands: Arc<HashSet<String>>,
132 state: Arc<Mutex<FilesystemState>>,
133 mutation_lock: Arc<AsyncMutex<()>>,
134}
135
136impl std::fmt::Debug for FilesystemWorkspace {
137 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
138 formatter
139 .debug_struct("FilesystemWorkspace")
140 .field("root", &self.root)
141 .field("allowed_roots", &self.allowed_roots)
142 .field("limits", &self.limits)
143 .field("mutations_allowed", &self.mutations_allowed)
144 .field("checks_allowed", &self.checks_allowed)
145 .finish_non_exhaustive()
146 }
147}
148
149impl FilesystemWorkspace {
150 pub async fn new<I>(root: impl AsRef<Path>, allowed_roots: I, mutations_allowed: bool) -> Result<Self>
153 where
154 I: IntoIterator<Item = PathBuf>,
155 {
156 let root = vtcode_commons::canonicalize_async(root.as_ref().to_path_buf()).await?;
157 if !tokio::fs::metadata(&root).await?.is_dir() {
158 return Err(WebmcpError::PathRejected("workspace root is not a directory".to_string()));
159 }
160
161 let allowed_roots = allowed_roots.into_iter().collect::<Vec<_>>();
162 if allowed_roots.len() > 1 {
163 return Err(WebmcpError::InvalidRequest(
164 "headless WebMCP currently supports one workspace root".to_string(),
165 ));
166 }
167 let roots = if allowed_roots.is_empty() {
168 vec![root.clone()]
169 } else {
170 let mut roots = Vec::with_capacity(allowed_roots.len());
171 for allowed_root in allowed_roots {
172 let canonical = vtcode_commons::canonicalize_async(allowed_root).await?;
173 if !tokio::fs::metadata(&canonical).await?.is_dir() {
174 return Err(WebmcpError::PathRejected("allowed root is not a directory".to_string()));
175 }
176 roots.push(canonical);
177 }
178 roots
179 };
180 if !roots.iter().any(|allowed| root.starts_with(allowed)) {
181 return Err(WebmcpError::PathRejected("workspace root is not in the allowed roots".to_string()));
182 }
183 let root_dir = open_root_directory(&root)?;
184 if !root_dir.metadata()?.is_dir() {
185 return Err(WebmcpError::PathRejected("workspace root is not a directory".to_string()));
186 }
187
188 Ok(Self {
189 root: Arc::new(root),
190 root_dir: Arc::new(root_dir),
191 allowed_roots: Arc::new(roots),
192 limits: FilesystemLimits::default(),
193 mutations_allowed,
194 checks_allowed: mutations_allowed,
195 allowed_commands: Arc::new(["cargo"].into_iter().map(str::to_string).collect()),
196 state: Arc::new(Mutex::new(FilesystemState::default())),
197 mutation_lock: Arc::new(AsyncMutex::new(())),
198 })
199 }
200
201 pub fn with_limits(mut self, limits: FilesystemLimits) -> Self {
203 self.limits = limits;
204 self
205 }
206
207 pub fn with_allowed_commands<I, S>(mut self, commands: I) -> Self
209 where
210 I: IntoIterator<Item = S>,
211 S: Into<String>,
212 {
213 self.allowed_commands = Arc::new(commands.into_iter().map(Into::into).collect());
214 self
215 }
216
217 pub fn with_checks_allowed(mut self, checks_allowed: bool) -> Self {
219 self.checks_allowed = checks_allowed;
220 self
221 }
222
223 pub async fn proposal_for_turn(&self, proposal_id: &str) -> Result<PatchProposal> {
229 let _mutation_guard = self.mutation_lock.lock().await;
230 let stored = {
231 let state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
232 state.proposals.get(proposal_id).cloned().ok_or(WebmcpError::ProposalNotFound)?
233 };
234 for expected in &stored.before {
235 let current = self.read_snapshot(&expected.path).await?;
236 if current.digest != expected.digest {
237 return Err(WebmcpError::Conflict {
238 path: expected.path.clone(),
239 expected: expected.digest.clone(),
240 actual: current.digest,
241 });
242 }
243 }
244 Ok(stored.proposal)
245 }
246
247 pub fn root(&self) -> &Path {
249 self.root.as_ref()
250 }
251
252 async fn read_snapshot(&self, path: &str) -> Result<FileSnapshot> {
253 let root = self.root.clone();
254 let root_dir = self.root_dir.clone();
255 let path = path.to_string();
256 let limits = self.limits;
257 tokio::task::spawn_blocking(move || read_snapshot_blocking(&root, &root_dir, &path, limits))
258 .await
259 .map_err(|error| WebmcpError::Adapter(format!("file read task failed: {error}")))?
260 }
261
262 async fn replace_snapshot_if_current(&self, update: &FileSnapshot, expected: &FileSnapshot) -> Result<()> {
263 let root = self.root.clone();
264 let root_dir = self.root_dir.clone();
265 let update = update.clone();
266 let expected = expected.clone();
267 tokio::task::spawn_blocking(move || replace_snapshot_if_current_blocking(&root, &root_dir, &update, &expected))
268 .await
269 .map_err(|error| WebmcpError::Adapter(format!("compare-and-replace task failed: {error}")))?
270 }
271
272 async fn apply_snapshots_if_current(&self, updates: &[FileSnapshot], expected: &[FileSnapshot]) -> Result<()> {
273 if updates.len() != expected.len() {
274 return Err(WebmcpError::Adapter("snapshot compare-and-swap lengths do not match".to_string()));
275 }
276 let mut applied = Vec::with_capacity(updates.len());
277 for (index, (update, expected_snapshot)) in updates.iter().zip(expected).enumerate() {
278 if let Err(error) = self.replace_snapshot_if_current(update, expected_snapshot).await {
279 let rollback_error = self
280 .rollback_snapshots(&applied, expected.get(..index).unwrap_or(&[]))
281 .await
282 .err();
283 return Err(rollback_error.unwrap_or(error));
284 }
285 applied.push(update.clone());
286 }
287 Ok(())
288 }
289
290 async fn apply_proposal_inner(&self, proposal_id: &str) -> Result<AppliedChange> {
291 let _mutation_guard = self.mutation_lock.lock().await;
292 let stored = {
293 let state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
294 state.proposals.get(proposal_id).cloned().ok_or(WebmcpError::ProposalNotFound)?
295 };
296
297 let after = stored
298 .proposal
299 .changes
300 .iter()
301 .map(|change| FileSnapshot {
302 path: change.path.clone(),
303 content: change.content.clone(),
304 digest: digest_text(&change.content),
305 })
306 .collect::<Vec<_>>();
307 self.apply_snapshots_if_current(&after, &stored.before).await?;
308
309 let change_id = Uuid::new_v4().simple().to_string();
310 let result = AppliedChange {
311 change_id: change_id.clone(),
312 paths: after.iter().map(|snapshot| snapshot.path.clone()).collect(),
313 };
314 let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
315 if let Some(removed) = state.proposals.remove(proposal_id) {
316 state.proposal_bytes = state.proposal_bytes.saturating_sub(removed.size_bytes);
317 }
318 state.last_change = Some(StoredChange { change_id, before: stored.before, after });
319 Ok(result)
320 }
321
322 async fn revert_last_change_inner(&self, change_id: &str) -> Result<AppliedChange> {
323 let _mutation_guard = self.mutation_lock.lock().await;
324 let stored = {
325 let state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
326 state.last_change.clone().ok_or(WebmcpError::ChangeNotFound)?
327 };
328 if stored.change_id != change_id {
329 return Err(WebmcpError::ChangeNotFound);
330 }
331 self.apply_snapshots_if_current(&stored.before, &stored.after).await?;
332 let reverted = AppliedChange {
333 change_id: stored.change_id.clone(),
334 paths: stored.before.iter().map(|snapshot| snapshot.path.clone()).collect(),
335 };
336 let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
337 state.last_change = None;
338 Ok(reverted)
339 }
340
341 async fn rollback_snapshots(&self, applied: &[FileSnapshot], originals: &[FileSnapshot]) -> Result<()> {
342 let mut failed = false;
343 for (applied_snapshot, original) in applied.iter().zip(originals).rev() {
344 if let Err(error) = self.replace_snapshot_if_current(original, applied_snapshot).await {
345 tracing::error!(
346 path = %original.path,
347 error = %error,
348 "failed to roll back a partially applied WebMCP change"
349 );
350 failed = true;
351 }
352 }
353 if failed { Err(WebmcpError::PartialApply) } else { Ok(()) }
354 }
355
356 fn proposal_diff(before: &[FileSnapshot], changes: &[FileChange]) -> String {
357 let mut diff = String::new();
358 for (snapshot, change) in before.iter().zip(changes) {
359 let old_label = format!("a/{}", snapshot.path);
360 let new_label = format!("b/{}", change.path);
361 let options = DiffOptions {
362 context_lines: 3,
363 old_label: Some(old_label.as_str()),
364 new_label: Some(new_label.as_str()),
365 ..DiffOptions::default()
366 };
367 let document = DiffDocument::between(&snapshot.content, &change.content, options.clone());
368 if document.hunks.is_empty() {
369 continue;
370 }
371 diff.push_str(&format_unified_hunks(&document.hunks, &options));
372 }
373 diff
374 }
375}
376
377#[cfg(test)]
378mod tests;