Skip to main content

vtcode_core/plugins/
components.rs

1//! Plugin component handlers for VT Code
2//!
3//! This module handles the different types of components that plugins can provide:
4//! - Commands (slash commands)
5//! - Agents (specialized profiles)
6//! - Skills (model-invoked capabilities)
7//! - Hooks (event handlers)
8//! - MCP servers (Model Context Protocol)
9
10use std::path::{Path, PathBuf};
11
12use anyhow::Result;
13use tokio::fs;
14
15use crate::plugins::PluginManifest;
16
17/// Handler for plugin commands (slash commands)
18pub struct CommandsHandler;
19
20impl CommandsHandler {
21    /// Process plugin commands from the plugin directory
22    pub async fn process_commands(plugin_path: &Path, manifest_commands: Option<Vec<String>>) -> Result<Vec<PathBuf>> {
23        let mut command_files = Vec::new();
24
25        // Add commands from manifest paths
26        if let Some(manifest_paths) = manifest_commands {
27            for path in manifest_paths {
28                let full_path = plugin_path.join(&path);
29                if fs::metadata(&full_path)
30                    .await
31                    .map(|metadata| metadata.is_file())
32                    .unwrap_or(false)
33                {
34                    command_files.push(full_path);
35                }
36            }
37        }
38
39        // Also look for commands in the default commands/ directory
40        let default_commands_dir = plugin_path.join("commands");
41        if fs::metadata(&default_commands_dir)
42            .await
43            .map(|metadata| metadata.is_dir())
44            .unwrap_or(false)
45        {
46            let mut entries = fs::read_dir(&default_commands_dir).await?;
47            while let Some(entry) = entries.next_entry().await? {
48                let path = entry.path();
49                if fs::metadata(&path).await.map(|metadata| metadata.is_file()).unwrap_or(false)
50                    && path.extension().is_some_and(|ext| ext == "md")
51                {
52                    command_files.push(path);
53                }
54            }
55        }
56
57        Ok(command_files)
58    }
59}
60
61/// Handler for plugin agents.
62pub struct AgentsHandler;
63
64impl AgentsHandler {
65    /// Process plugin agents from the plugin directory.
66    ///
67    /// Manifest entries must stay inside the plugin root: absolute paths and
68    /// parent-directory escapes are skipped, and symlinks are never followed,
69    /// so a crafted manifest cannot smuggle outside files into agent specs.
70    pub async fn process_agents(plugin_path: &Path, manifest_agents: Option<Vec<String>>) -> Result<Vec<PathBuf>> {
71        let mut agent_files = Vec::new();
72
73        // Add agents from manifest paths
74        if let Some(manifest_paths) = manifest_agents {
75            for path in manifest_paths {
76                let relative = Path::new(&path);
77                if relative.is_absolute()
78                    || relative
79                        .components()
80                        .any(|component| matches!(component, std::path::Component::ParentDir))
81                {
82                    continue;
83                }
84                let full_path = plugin_path.join(relative);
85                if fs::symlink_metadata(&full_path)
86                    .await
87                    .map(|metadata| metadata.is_file())
88                    .unwrap_or(false)
89                {
90                    agent_files.push(full_path);
91                }
92            }
93        }
94
95        // Also look for agents in the default agents/ directory
96        let default_agents_dir = plugin_path.join("agents");
97        if fs::symlink_metadata(&default_agents_dir)
98            .await
99            .map(|metadata| metadata.is_dir())
100            .unwrap_or(false)
101        {
102            let mut entries = fs::read_dir(&default_agents_dir).await?;
103            while let Some(entry) = entries.next_entry().await? {
104                let path = entry.path();
105                if fs::symlink_metadata(&path)
106                    .await
107                    .map(|metadata| metadata.is_file())
108                    .unwrap_or(false)
109                    && path.extension().is_some_and(|ext| ext == "md")
110                {
111                    agent_files.push(path);
112                }
113            }
114        }
115
116        Ok(agent_files)
117    }
118}
119
120/// Handler for plugin skills
121pub struct SkillsHandler;
122
123impl SkillsHandler {
124    /// Process plugin skills from the plugin directory
125    pub async fn process_skills(plugin_path: &Path, manifest_skills: Option<Vec<String>>) -> Result<Vec<PathBuf>> {
126        let mut skill_dirs = Vec::new();
127
128        // Add skills from manifest paths
129        if let Some(manifest_paths) = manifest_skills {
130            for path in manifest_paths {
131                let full_path = plugin_path.join(&path);
132                if fs::metadata(&full_path)
133                    .await
134                    .map(|metadata| metadata.is_dir())
135                    .unwrap_or(false)
136                {
137                    skill_dirs.push(full_path);
138                }
139            }
140        }
141
142        // Also look for skills in the default skills/ directory
143        let default_skills_dir = plugin_path.join("skills");
144        if fs::metadata(&default_skills_dir)
145            .await
146            .map(|metadata| metadata.is_dir())
147            .unwrap_or(false)
148        {
149            let mut entries = fs::read_dir(&default_skills_dir).await?;
150            while let Some(entry) = entries.next_entry().await? {
151                let path = entry.path();
152                if fs::metadata(&path).await.map(|metadata| metadata.is_dir()).unwrap_or(false) {
153                    // Check if it contains a SKILL.md file
154                    let skill_md = path.join("SKILL.md");
155                    if fs::metadata(&skill_md)
156                        .await
157                        .map(|metadata| metadata.is_file())
158                        .unwrap_or(false)
159                    {
160                        skill_dirs.push(path);
161                    }
162                }
163            }
164        }
165
166        Ok(skill_dirs)
167    }
168}
169
170/// Handler for plugin hooks
171pub struct HooksHandler;
172
173impl HooksHandler {
174    /// Process plugin hooks from the plugin directory
175    pub async fn process_hooks(
176        plugin_path: &Path,
177        manifest_hooks: Option<serde_json::Value>,
178    ) -> Result<Option<PathBuf>> {
179        // Check for hooks in manifest
180        if let Some(hooks_config) = manifest_hooks {
181            // If hooks config is a string, treat it as a path
182            if let Some(path_str) = hooks_config.as_str() {
183                let hooks_path = plugin_path.join(path_str);
184                if fs::metadata(&hooks_path)
185                    .await
186                    .map(|metadata| metadata.is_file())
187                    .unwrap_or(false)
188                {
189                    return Ok(Some(hooks_path));
190                }
191            }
192        }
193
194        // Look for hooks in the default hooks/ directory
195        let default_hooks_path = plugin_path.join("hooks/hooks.json");
196        if fs::metadata(&default_hooks_path)
197            .await
198            .map(|metadata| metadata.is_file())
199            .unwrap_or(false)
200        {
201            return Ok(Some(default_hooks_path));
202        }
203
204        Ok(None)
205    }
206}
207
208/// Handler for plugin MCP servers
209pub struct McpServersHandler;
210
211impl McpServersHandler {
212    /// Process plugin MCP servers from the plugin directory
213    pub async fn process_mcp_servers(
214        plugin_path: &Path,
215        manifest_mcp: Option<serde_json::Value>,
216    ) -> Result<Option<PathBuf>> {
217        // Check for MCP config in manifest
218        if let Some(mcp_config) = manifest_mcp {
219            // If MCP config is a string, treat it as a path
220            if let Some(path_str) = mcp_config.as_str() {
221                let mcp_path = plugin_path.join(path_str);
222                if fs::metadata(&mcp_path)
223                    .await
224                    .map(|metadata| metadata.is_file())
225                    .unwrap_or(false)
226                {
227                    return Ok(Some(mcp_path));
228                }
229            }
230        }
231
232        // Look for MCP config in the default .mcp.json file
233        let default_mcp_path = plugin_path.join(".mcp.json");
234        if fs::metadata(&default_mcp_path)
235            .await
236            .map(|metadata| metadata.is_file())
237            .unwrap_or(false)
238        {
239            return Ok(Some(default_mcp_path));
240        }
241
242        Ok(None)
243    }
244}
245
246/// Handler for plugin LSP servers
247pub struct LspServersHandler;
248
249impl LspServersHandler {
250    /// Process plugin LSP servers from the plugin directory
251    pub async fn process_lsp_servers(
252        plugin_path: &Path,
253        manifest_lsp: Option<serde_json::Value>,
254    ) -> Result<Option<PathBuf>> {
255        // Check for LSP config in manifest
256        if let Some(lsp_config) = manifest_lsp {
257            // If LSP config is a string, treat it as a path
258            if let Some(path_str) = lsp_config.as_str() {
259                let lsp_path = plugin_path.join(path_str);
260                if fs::metadata(&lsp_path)
261                    .await
262                    .map(|metadata| metadata.is_file())
263                    .unwrap_or(false)
264                {
265                    return Ok(Some(lsp_path));
266                }
267            }
268        }
269
270        // Look for LSP config in the default .lsp.json file
271        let default_lsp_path = plugin_path.join(".lsp.json");
272        if fs::metadata(&default_lsp_path)
273            .await
274            .map(|metadata| metadata.is_file())
275            .unwrap_or(false)
276        {
277            return Ok(Some(default_lsp_path));
278        }
279
280        Ok(None)
281    }
282}
283
284/// A comprehensive handler that processes all plugin components
285pub struct PluginComponentsHandler;
286
287impl PluginComponentsHandler {
288    /// Process all components for a plugin
289    pub async fn process_all_components<P: AsRef<Path>>(
290        plugin_path: P,
291        manifest: &PluginManifest,
292    ) -> Result<PluginComponents> {
293        let path_buf = plugin_path.as_ref().to_path_buf();
294        let commands = CommandsHandler::process_commands(&path_buf, manifest.commands.clone()).await?;
295
296        let agents = AgentsHandler::process_agents(&path_buf, manifest.agents.clone()).await?;
297
298        let skills = SkillsHandler::process_skills(&path_buf, manifest.skills.clone()).await?;
299
300        let hooks = HooksHandler::process_hooks(
301            &path_buf,
302            manifest.hooks.as_ref().map(|h| match h {
303                crate::plugins::manifest::HookConfig::Path(path) => serde_json::Value::String(path.clone()),
304                crate::plugins::manifest::HookConfig::Inline(_) => serde_json::Value::Null, // For inline, we'll handle separately
305            }),
306        )
307        .await?;
308
309        let mcp_servers = McpServersHandler::process_mcp_servers(
310            &path_buf,
311            manifest.mcp_servers.as_ref().map(|m| match m {
312                crate::plugins::manifest::McpServerConfig::Path(path) => serde_json::Value::String(path.clone()),
313                crate::plugins::manifest::McpServerConfig::Inline(_) => serde_json::Value::Null, // For inline, we'll handle separately
314            }),
315        )
316        .await?;
317
318        let lsp_servers = LspServersHandler::process_lsp_servers(
319            &path_buf,
320            manifest.lsp_servers.as_ref().map(|l| match l {
321                crate::plugins::manifest::LspServerConfig::Path(path) => serde_json::Value::String(path.clone()),
322                crate::plugins::manifest::LspServerConfig::Inline(_) => serde_json::Value::Null, // For inline, we'll handle separately
323            }),
324        )
325        .await?;
326
327        Ok(PluginComponents {
328            commands,
329            agents,
330            skills,
331            hooks,
332            mcp_servers,
333            lsp_servers,
334        })
335    }
336}
337
338/// Structure containing all plugin components
339pub struct PluginComponents {
340    pub commands: Vec<PathBuf>,
341    pub agents: Vec<PathBuf>,
342    pub skills: Vec<PathBuf>,
343    pub hooks: Option<PathBuf>,
344    pub mcp_servers: Option<PathBuf>,
345    pub lsp_servers: Option<PathBuf>,
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351    use tempfile::TempDir;
352
353    /// Plugin root at `<dir>/plugin` with a sibling file outside it, so
354    /// `../sibling.md` escapes the root while staying inside the temp dir.
355    async fn plugin_fixture() -> (TempDir, PathBuf) {
356        let dir = TempDir::new().expect("temp dir");
357        let root = dir.path().join("plugin");
358        fs::create_dir_all(root.join("agents")).await.expect("agents dir");
359        fs::create_dir_all(root.join("nested")).await.expect("nested dir");
360        fs::write(root.join("agents").join("ok.md"), "ok").await.expect("write ok");
361        fs::write(root.join("agents").join("notes.txt"), "not markdown")
362            .await
363            .expect("write txt");
364        fs::write(root.join("nested").join("custom.md"), "custom")
365            .await
366            .expect("write custom");
367        fs::write(dir.path().join("sibling.md"), "outside")
368            .await
369            .expect("write sibling");
370        (dir, root)
371    }
372
373    #[tokio::test]
374    async fn manifest_agent_paths_stay_contained() {
375        let (_dir, root) = plugin_fixture().await;
376        let outside = _dir.path().join("sibling.md");
377
378        let files = AgentsHandler::process_agents(
379            &root,
380            Some(vec![
381                "nested/custom.md".to_string(),
382                "../sibling.md".to_string(),
383                outside.to_string_lossy().into_owned(),
384                "missing.md".to_string(),
385            ]),
386        )
387        .await
388        .expect("process");
389
390        assert!(files.iter().all(|p| p.starts_with(&root)), "all results stay under the plugin root: {files:?}");
391        assert!(files.contains(&root.join("nested/custom.md")), "legit nested entry kept: {files:?}");
392        assert!(files.contains(&root.join("agents/ok.md")), "default dir scan kept: {files:?}");
393        assert!(
394            !files.iter().any(|p| p.ends_with("sibling.md")),
395            "traversal and absolute entries dropped: {files:?}"
396        );
397        assert!(!files.iter().any(|p| p.ends_with("notes.txt")), "non-markdown default files skipped: {files:?}");
398    }
399
400    #[cfg(unix)]
401    #[tokio::test]
402    async fn manifest_agent_symlinks_are_skipped() {
403        let (_dir, root) = plugin_fixture().await;
404        let outside = _dir.path().join("sibling.md");
405        std::os::unix::fs::symlink(&outside, root.join("agents").join("link.md")).expect("symlink");
406
407        let files = AgentsHandler::process_agents(&root, Some(vec!["agents/link.md".to_string()]))
408            .await
409            .expect("process");
410
411        assert!(
412            !files.iter().any(|p| p.ends_with("link.md")),
413            "symlinked entries must not escape via following: {files:?}"
414        );
415        assert!(files.contains(&root.join("agents/ok.md")), "regular files still collected: {files:?}");
416    }
417}