Skip to main content

vtcode_webmcp/filesystem/
runtime_adapter.rs

1//! The WebMCP runtime adapter for the filesystem workspace.
2//!
3//! Bridges the workspace's file operations to the runtime protocol the
4//! WebMCP bridge speaks.
5
6use super::*;
7
8#[async_trait]
9impl RuntimeAdapter for FilesystemWorkspace {
10    async fn status(&self) -> Result<RuntimeStatus> {
11        Ok(RuntimeStatus {
12            explanations_available: false,
13            workspace_root: self.root.display().to_string(),
14            connected: true,
15            turns_available: false,
16            mutations_allowed: self.mutations_allowed,
17            checks_allowed: self.checks_allowed,
18            approval_authority: if self.mutations_allowed {
19                "headless full-auto allowlist".into()
20            } else {
21                "headless policy (mutations disabled)".into()
22            },
23        })
24    }
25
26    async fn list_files(&self) -> Result<Vec<WorkspaceFile>> {
27        let root = self.root.clone();
28        let root_dir = self.root_dir.clone();
29        let limits = self.limits;
30        tokio::task::spawn_blocking(move || list_files_blocking(&root, &root_dir, limits))
31            .await
32            .map_err(|error| WebmcpError::Adapter(format!("file listing task failed: {error}")))?
33    }
34
35    async fn read_file(&self, path: &str) -> Result<FileSnapshot> {
36        self.read_snapshot(path).await
37    }
38
39    async fn propose_changes(&self, changes: Vec<FileChange>) -> Result<PatchProposal> {
40        let _mutation_guard = self.mutation_lock.lock().await;
41        if changes.is_empty() || changes.len() > self.limits.max_changes {
42            return Err(WebmcpError::LimitExceeded);
43        }
44        {
45            let state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
46            if state.proposals.len() >= MAX_STORED_PROPOSALS {
47                return Err(WebmcpError::LimitExceeded);
48            }
49        }
50        let mut paths = HashSet::with_capacity(changes.len());
51        let mut before = Vec::with_capacity(changes.len());
52        let mut proposal_bytes = 0usize;
53        for change in &changes {
54            if change.content.len() > self.limits.max_change_bytes || !paths.insert(change.path.clone()) {
55                return Err(WebmcpError::LimitExceeded);
56            }
57            let snapshot = self.read_snapshot(&change.path).await?;
58            if snapshot.digest != change.base_digest {
59                return Err(WebmcpError::Conflict {
60                    path: change.path.clone(),
61                    expected: change.base_digest.clone(),
62                    actual: snapshot.digest,
63                });
64            }
65            proposal_bytes = proposal_bytes
66                .checked_add(snapshot.content.len())
67                .and_then(|bytes| bytes.checked_add(change.content.len()))
68                .ok_or(WebmcpError::LimitExceeded)?;
69            if proposal_bytes > self.limits.max_total_bytes {
70                return Err(WebmcpError::LimitExceeded);
71            }
72            before.push(snapshot);
73        }
74
75        let unified_diff = Self::proposal_diff(&before, &changes);
76        if unified_diff.len() > self.limits.max_total_bytes {
77            return Err(WebmcpError::LimitExceeded);
78        }
79        let stored_size_bytes = proposal_bytes
80            .checked_add(unified_diff.len())
81            .ok_or(WebmcpError::LimitExceeded)?;
82        let mut state = self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
83        if state
84            .proposal_bytes
85            .checked_add(stored_size_bytes)
86            .is_none_or(|bytes| bytes > MAX_STORED_PROPOSAL_BYTES)
87        {
88            return Err(WebmcpError::LimitExceeded);
89        }
90        let proposal = PatchProposal {
91            proposal_id: Uuid::new_v4().simple().to_string(),
92            unified_diff,
93            changes,
94        };
95        state.proposal_bytes += stored_size_bytes;
96        drop(state.proposals.insert(
97            proposal.proposal_id.clone(),
98            StoredProposal {
99                proposal: proposal.clone(),
100                before,
101                size_bytes: stored_size_bytes,
102            },
103        ));
104        Ok(proposal)
105    }
106
107    async fn apply_proposal(&self, proposal_id: &str) -> Result<AppliedChange> {
108        if !self.mutations_allowed {
109            return Err(WebmcpError::ApprovalRequired);
110        }
111        let workspace = self.clone();
112        let proposal_id = proposal_id.to_string();
113        tokio::spawn(async move { workspace.apply_proposal_inner(&proposal_id).await })
114            .await
115            .map_err(|error| WebmcpError::Adapter(format!("WebMCP apply task failed: {error}")))?
116    }
117
118    async fn run_checks(&self, command: &str) -> Result<CheckResult> {
119        let args = parse_safe_command(command, &self.allowed_commands)?;
120        if !self.checks_allowed {
121            return Err(WebmcpError::ApprovalRequired);
122        }
123        let _mutation_guard = self.mutation_lock.lock().await;
124        let (program, arguments) = args
125            .split_first()
126            .ok_or_else(|| WebmcpError::InvalidRequest("check command cannot be empty".to_string()))?;
127        let executable = resolve_check_executable(program, self.root.as_ref())?;
128        // Capture host toolchain locations before replacing HOME with the
129        // workspace sandbox HOME. This keeps checks reproducible without
130        // allowing the child to inherit the caller's complete environment.
131        let host_home = std::env::var_os("HOME")
132            .or_else(|| std::env::var_os("USERPROFILE"))
133            .map(PathBuf::from);
134        let mut environment = SandboxEnvironment::new();
135        let _ = environment.insert("PATH".to_string(), trusted_executable_path(&executable)?);
136        let _ = environment.insert("HOME".to_string(), self.root.display().to_string());
137        let _ = environment.insert("CARGO_NET_OFFLINE".to_string(), "true".to_string());
138        let _ = environment.insert("CARGO_TERM_COLOR".to_string(), "never".to_string());
139        let cargo_home = host_home
140            .as_ref()
141            .and_then(|home| trusted_toolchain_directory(&home.join(".cargo"), self.root.as_ref()));
142        if let Some(cargo_home) = cargo_home {
143            let _ = environment.insert("CARGO_HOME".to_string(), cargo_home.to_string_lossy().into_owned());
144        }
145        let rustup_home = host_home
146            .as_ref()
147            .and_then(|home| trusted_toolchain_directory(&home.join(".rustup"), self.root.as_ref()));
148        if let Some(rustup_home) = rustup_home {
149            let _ = environment.insert("RUSTUP_HOME".to_string(), rustup_home.to_string_lossy().into_owned());
150        }
151        let spec = CommandSpec::new(executable)
152            .with_args(arguments.iter().cloned())
153            .with_cwd(self.root.as_ref().to_path_buf())
154            .with_env(environment)
155            .with_expiration(ExecExpiration::Timeout(CHECK_TIMEOUT));
156        let linux_launcher = LinuxSandboxLauncher::resolve();
157        let check_policy = check_sandbox_policy(self.root.as_ref())
158            .map_err(|error| WebmcpError::Adapter(format!("failed to build WebMCP check sandbox: {error}")))?;
159        let exec_env = SandboxManager::new()
160            .transform(spec, &check_policy, self.root.as_ref(), linux_launcher.as_ref())
161            .map_err(|error| WebmcpError::Adapter(format!("failed to sandbox WebMCP check: {error}")))?;
162        let mut child = Command::new(exec_env.program)
163            .args(exec_env.args)
164            .current_dir(exec_env.cwd)
165            .env_clear()
166            .envs(exec_env.env)
167            .stdin(Stdio::null())
168            .stdout(Stdio::piped())
169            .stderr(Stdio::piped())
170            .kill_on_drop(true)
171            .spawn()?;
172        let stdout = child
173            .stdout
174            .take()
175            .ok_or_else(|| WebmcpError::Adapter("check process stdout was not captured".to_string()))?;
176        let stderr = child
177            .stderr
178            .take()
179            .ok_or_else(|| WebmcpError::Adapter("check process stderr was not captured".to_string()))?;
180        let output = Box::pin(tokio::time::timeout(CHECK_TIMEOUT, async {
181            let (status, stdout, stderr) =
182                tokio::join!(child.wait(), read_process_output(stdout), read_process_output(stderr));
183            Ok::<_, WebmcpError>((status?, stdout?, stderr?))
184        }))
185        .await;
186        let (status, stdout, stderr) = match output {
187            Ok(result) => result?,
188            Err(_elapsed) => {
189                drop(child.kill().await);
190                drop(child.wait().await);
191                return Err(WebmcpError::Timeout(CHECK_TIMEOUT));
192            }
193        };
194        Ok(CheckResult {
195            command: command.to_string(),
196            exit_code: status.code(),
197            stdout: String::from_utf8_lossy(&stdout).into_owned(),
198            stderr: String::from_utf8_lossy(&stderr).into_owned(),
199        })
200    }
201
202    async fn revert_last_change(&self, change_id: &str) -> Result<AppliedChange> {
203        if !self.mutations_allowed {
204            return Err(WebmcpError::ApprovalRequired);
205        }
206        let workspace = self.clone();
207        let change_id = change_id.to_string();
208        tokio::spawn(async move { workspace.revert_last_change_inner(&change_id).await })
209            .await
210            .map_err(|error| WebmcpError::Adapter(format!("WebMCP revert task failed: {error}")))?
211    }
212
213    async fn request_turn(&self, prompt: &str, _proposal_id: Option<&str>) -> Result<TurnResult> {
214        if prompt.trim().is_empty() {
215            return Err(WebmcpError::InvalidRequest("agent turn prompt cannot be empty".to_string()));
216        }
217        if prompt.len() > 16 * 1024 {
218            return Err(WebmcpError::LimitExceeded);
219        }
220        Err(WebmcpError::Unsupported(
221            "agent turns require an active VT Code runtime; start `vtcode chat` and run `/webmcp pair <origin>` in that same session. The standalone `vtcode webmcp serve` command exposes workspace operations only".to_string(),
222        ))
223    }
224}