Skip to main content

vtcode_skills/native_plugin/
mod.rs

1#![allow(
2    unsafe_code,
3    reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5
6//! Native Plugin System for VT Code Skills
7//!
8//! This module provides support for loading native code plugins as skills using libloading.
9//! Native plugins offer high-performance, pre-compiled skill logic that can be discovered
10//! and loaded dynamically at runtime.
11//!
12//! # Safety
13//!
14//! Loading native code plugins requires careful security considerations:
15//! - Plugins are loaded from canonicalized, explicitly trusted locations only
16//! - Callers must obtain user approval before loading an untrusted plugin
17//! - Plugin signatures can be verified (future enhancement)
18//! - This module does not sandbox plugin execution; native code runs with process privileges
19//! - VT Code serializes plugin FFI calls for ABI v1
20//! - All plugin operations go through VT Code's tool system
21//!
22//! The `unsafe` blocks in this module are necessary for FFI:
23//! - Loading dynamic libraries (`Library::new`)
24//! - Calling plugin functions (`version_fn`, `metadata_fn`, `execute_fn`,
25//!   `free_string_fn`)
26//! - Converting C strings (`CStr::from_ptr`)
27//!
28//! Symbol resolution is centralized in the safe `get_plugin_symbol` wrapper;
29//! the remaining raw calls cannot be made safe without losing the ability to
30//! load arbitrary plugin code. Each call site carries its own `// SAFETY:`
31//! comment documenting the specific invariant that justifies the unsafe
32//! operation.
33//!
34//! # Plugin Structure
35//!
36//! A native plugin skill consists of:
37//! - `plugin.json` - Metadata (name, description, version, author)
38//! - `lib<name>.dylib` (macOS) or `lib<name>.so` (Linux) or `<name>.dll` (Windows)
39//! - Optional: `README.md`, `scripts/`, `templates/`
40//!
41//! # Plugin ABI
42//!
43//! Plugins must export the following C-compatible symbols:
44//! - `vtcode_plugin_version()` - Returns ABI version
45//! - `vtcode_plugin_metadata()` - Returns plugin metadata JSON
46//! - `vtcode_plugin_execute()` - Main execution entry point
47//!
48//! # Example
49//!
50//! ```rust,ignore
51//! use vtcode_core::skills::native_plugin::{NativePlugin, PluginLoader};
52//!
53//! let mut loader = PluginLoader::new();
54//! let plugin = loader.load_plugin("/path/to/plugin").unwrap();
55//! let result = plugin.execute(&input).unwrap();
56//! ```
57
58use anyhow::{Context, Result, anyhow};
59use hashbrown::HashMap;
60use libloading::{Library, Symbol};
61use serde::{Deserialize, Serialize};
62use std::ffi::{CStr, CString};
63#[cfg(unix)]
64use std::os::unix::fs::PermissionsExt;
65use std::path::{Path, PathBuf};
66use std::ptr::NonNull;
67use std::sync::Mutex;
68use tracing::{debug, info, warn};
69use vtcode_commons::canonicalize;
70
71/// Current plugin ABI version
72/// Increment this when breaking changes are made to the plugin interface
73pub const PLUGIN_ABI_VERSION: u32 = 1;
74
75use std::os::raw::c_char;
76
77/// Plugin ABI v1 entry-point signatures.
78///
79/// `unsafe extern "C" fn` in type position marks that calling through these
80/// pointers is unsafe; neither `rustc`'s `unsafe_code` nor clippy's
81/// `undocumented_unsafe_blocks` fires here, so the contract is stated once,
82/// here. Each pointer is resolved only from a library that
83/// `PluginLoader::load_plugin` has canonicalized and verified as trusted, and is
84/// invoked exclusively through the wrappers in this module (`get_plugin_symbol`,
85/// `NativePlugin::new`, `NativePlugin::execute_ffi`), each of which carries its
86/// own call-site safety justification. Preconditions: the pointer was resolved
87/// from the matching symbol of the loaded library, the plugin's threading
88/// contract (`PluginMetadata::thread_safe`; otherwise serialized by
89/// `NativePlugin::execution_lock`) is honoured, the returned `*const c_char` is
90/// non-null and nul-terminated, and plugin-owned strings are released with the
91/// matching `free_string` symbol.
92type PluginVersionFn = unsafe extern "C" fn() -> u32;
93type PluginMetadataFn = unsafe extern "C" fn() -> *const c_char;
94type PluginExecuteFn = unsafe extern "C" fn(*const c_char) -> *const c_char;
95type PluginFreeStringFn = unsafe extern "C" fn(*const c_char);
96
97/// Plugin execution context passed to plugin functions
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct PluginContext {
100    /// Input data for the plugin
101    input: HashMap<String, serde_json::Value>,
102    /// Workspace root path
103    workspace_root: Option<String>,
104    /// Plugin configuration
105    config: HashMap<String, serde_json::Value>,
106}
107
108/// Plugin execution result
109#[derive(Debug, Clone, Serialize, Deserialize)]
110pub struct PluginResult {
111    /// Success flag
112    success: bool,
113    /// Output data
114    output: HashMap<String, serde_json::Value>,
115    /// Error message if failed
116    error: Option<String>,
117    /// Optional file references created by the plugin
118    files: Vec<String>,
119}
120
121/// Plugin metadata structure
122#[derive(Debug, Clone, Serialize, Deserialize)]
123pub struct PluginMetadata {
124    /// Plugin name (identifier)
125    pub name: String,
126    /// Human-readable description
127    pub description: String,
128    /// Plugin version (semver)
129    version: String,
130    /// Plugin author
131    author: Option<String>,
132    /// Plugin ABI version
133    abi_version: u32,
134    /// When to use this plugin
135    when_to_use: Option<String>,
136    /// When NOT to use this plugin
137    when_not_to_use: Option<String>,
138    /// Allowed tools for this plugin
139    allowed_tools: Option<Vec<String>>,
140    /// Whether the plugin is thread-safe (Sync).
141    /// If false, VT Code serializes all calls to this plugin instance.
142    #[serde(default)]
143    thread_safe: bool,
144}
145
146/// Native plugin trait for type-erased plugin operations
147pub trait NativePluginTrait: Send + Sync + std::fmt::Debug {
148    /// Get plugin metadata
149    fn metadata(&self) -> &PluginMetadata;
150
151    /// Get plugin path
152    fn path(&self) -> &Path;
153
154    /// Execute the plugin with given context
155    fn execute(&self, ctx: &PluginContext) -> Result<PluginResult>;
156}
157
158/// A loaded native plugin
159pub struct NativePlugin {
160    /// Loaded plugin library handle.
161    ///
162    /// # Lifetime invariant
163    ///
164    /// `_library` outlives `self`. `execute_fn` is a raw function pointer copied
165    /// out of this library and is only valid while `_library` remains loaded.
166    /// `NativePlugin` intentionally has no `Drop`: cleanup is delegated to
167    /// `Library`'s own `Drop` (`dlclose`), which runs after `self` is dropped,
168    /// guaranteeing the function pointer is never used after the library unloads.
169    _library: Library,
170    /// Plugin metadata
171    metadata: PluginMetadata,
172    /// Path to the plugin
173    path: PathBuf,
174    /// Plugin execute function pointer
175    execute_fn: PluginExecuteFn,
176    /// Optional plugin-owned deallocator for returned strings
177    free_string_fn: Option<PluginFreeStringFn>,
178    /// Serialize calls if the plugin is not reentrant.
179    execution_lock: Mutex<()>,
180    /// Optimized thread-safety flag from metadata.
181    thread_safe: bool,
182}
183
184fn ensure_non_null_c_string_ptr(ptr: *const c_char, context: &'static str) -> Result<NonNull<c_char>> {
185    NonNull::new(ptr.cast_mut()).ok_or_else(|| anyhow!("{context} returned null pointer"))
186}
187
188fn decode_plugin_c_string(
189    ptr: NonNull<c_char>,
190    free_string_fn: Option<PluginFreeStringFn>,
191    utf8_error_context: &'static str,
192) -> Result<String> {
193    let raw_ptr = ptr.as_ptr().cast_const();
194    // SAFETY:
195    // 1. `raw_ptr` is guaranteed to be non-null (validated by `ensure_non_null_c_string_ptr`).
196    // 2. We assume the plugin-returned pointer is a valid nul-terminated C string per the plugin ABI.
197    // 3. The reference created by `CStr::from_ptr` is only used to copy the data into a Rust `String`.
198    //    Since we own the only reference during this brief window and copy-then-release,
199    //    we avoid Undefined Behavior related to mutable aliasing that "Unsafe Rust is not C" warns about.
200    let decoded = unsafe { CStr::from_ptr(raw_ptr) }
201        .to_str()
202        .context(utf8_error_context)
203        .map(str::to_owned);
204
205    if let Some(free_fn) = free_string_fn {
206        // SAFETY: The pointer originated from the same plugin instance that provided `free_fn`.
207        // We call it only after we've finished reading the data into our own `String`.
208        unsafe { free_fn(raw_ptr) };
209    }
210
211    decoded
212}
213
214impl std::fmt::Debug for NativePlugin {
215    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216        f.debug_struct("NativePlugin")
217            .field("metadata", &self.metadata)
218            .field("path", &self.path)
219            .finish()
220    }
221}
222
223fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf> {
224    canonicalize(path).with_context(|| format!("Failed to resolve {label} '{}'", path.display()))
225}
226
227/// Resolve a C-ABI symbol from a trusted, already-validated plugin library.
228///
229/// Single wrapper around libloading's symbol lookup; every plugin symbol
230/// passage goes through here. `T` must be a `Copy` function-pointer type. The
231/// returned value is valid only while `library` (`NativePlugin._library`) is loaded.
232fn get_plugin_symbol<T: Copy>(library: &Library, name: &[u8]) -> Result<T> {
233    // SAFETY: symbol name and signature are defined by the plugin ABI; we trust
234    // the library (canonicalized/trusted location). `T: Copy` makes the deref safe.
235    let symbol: Symbol<T> = unsafe { library.get(name) }.with_context(|| {
236        format!("Failed to load plugin symbol: {:?}", String::from_utf8_lossy(name.trim_suffix(b"\0")))
237    })?;
238    Ok(*symbol)
239}
240
241fn normalize_trusted_dir(path: PathBuf) -> PathBuf {
242    canonicalize_existing_path(&path, "trusted plugin directory").unwrap_or_else(|_| {
243        if path.is_absolute() {
244            path
245        } else {
246            std::env::current_dir().map(|cwd| cwd.join(&path)).unwrap_or(path)
247        }
248    })
249}
250
251#[cfg(unix)]
252fn warn_if_insecure_trusted_dir(dir: &Path) {
253    if let Ok(metadata) = std::fs::metadata(dir) {
254        let mode = metadata.permissions().mode();
255        if mode & 0o022 != 0 {
256            let perm_octal = format!("{:o}", mode & 0o777);
257            warn!(
258                dir = ?dir,
259                mode = %perm_octal,
260                "trusted plugin directory is writable by group or others; a non-owner user could plant a malicious plugin via symlink or replacement"
261            );
262        }
263    }
264}
265
266#[cfg(not(unix))]
267fn warn_if_insecure_trusted_dir(_dir: &Path) {}
268
269impl NativePlugin {
270    /// Create a new native plugin from a loaded library
271    fn new(library: Library, path: PathBuf) -> Result<Self> {
272        // Verify ABI version
273        let version_fn = get_plugin_symbol::<PluginVersionFn>(&library, b"vtcode_plugin_version\0")?;
274
275        // SAFETY: function pointer was loaded from a validated ABI symbol.
276        let abi_version = unsafe { version_fn() };
277        if abi_version != PLUGIN_ABI_VERSION {
278            return Err(anyhow!("Plugin ABI version mismatch: expected {PLUGIN_ABI_VERSION}, got {abi_version}"));
279        }
280
281        // Optional cleanup function for plugin-owned strings.
282        let free_string_fn = get_plugin_symbol::<PluginFreeStringFn>(&library, b"vtcode_plugin_free_string\0").ok();
283
284        // Load metadata
285        let metadata_fn = get_plugin_symbol::<PluginMetadataFn>(&library, b"vtcode_plugin_metadata\0")?;
286
287        // SAFETY: function pointer loaded from the validated ABI symbol.
288        let metadata_ptr = ensure_non_null_c_string_ptr(unsafe { metadata_fn() }, "Plugin metadata function")?;
289        let metadata_json = decode_plugin_c_string(metadata_ptr, free_string_fn, "Plugin metadata is not valid UTF-8")?;
290
291        let metadata: PluginMetadata =
292            serde_json::from_str(&metadata_json).context("Failed to parse plugin metadata JSON")?;
293
294        // Load execute function
295        let execute_fn = get_plugin_symbol::<PluginExecuteFn>(&library, b"vtcode_plugin_execute\0")?;
296
297        Ok(Self {
298            _library: library,
299            metadata: metadata.clone(), // Clone metadata to store it
300            path,
301            execute_fn,
302            free_string_fn,
303            execution_lock: Mutex::new(()),
304            thread_safe: metadata.thread_safe, // Store the thread_safe flag
305        })
306    }
307
308    /// Execute the plugin with the given context
309    fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
310        let input_json = serde_json::to_string(ctx).context("Failed to serialize plugin context")?;
311        let input_cstr = CString::new(input_json).context("Plugin context contains internal null bytes")?;
312
313        // Serialization logic from Antithesis Part 2 (Challenge 2):
314        // If the plugin is not explicitly marked as thread-safe, we must serialize
315        // access through the execution lock to prevent unsynchronized shared access.
316        if !self.thread_safe {
317            let _execution_guard = self
318                .execution_lock
319                .lock()
320                .map_err(|_e| anyhow!("native plugin execution lock poisoned"))?;
321
322            self.execute_ffi(input_cstr)
323        } else {
324            // Reentrant plugins can skip the lock for multi-threaded performance.
325            self.execute_ffi(input_cstr)
326        }
327    }
328
329    /// Internal FFI bridge for plugin execution.
330    ///
331    /// # Safety
332    ///
333    /// This function performs the raw FFI call. Callers must ensure that
334    /// if the plugin is not thread-safe, it is called under a lock.
335    fn execute_ffi(&self, input_cstr: CString) -> Result<PluginResult> {
336        // SAFETY:
337        // 1. The `input_cstr` pointer is valid for the duration of this call.
338        // 2. The `execute_fn` obeys the plugin ABI and expects a nul-terminated string.
339        // 3. VT Code either holds `execution_lock` or the plugin is explicitly reentrant (thread_safe: true).
340        let result_ptr =
341            ensure_non_null_c_string_ptr(unsafe { (self.execute_fn)(input_cstr.as_ptr()) }, "Plugin execute function")?;
342        let result_json = decode_plugin_c_string(result_ptr, self.free_string_fn, "Plugin result is not valid UTF-8")?;
343
344        let result: PluginResult = serde_json::from_str(&result_json).context("Failed to parse plugin result JSON")?;
345
346        Ok(result)
347    }
348}
349
350impl NativePluginTrait for NativePlugin {
351    fn metadata(&self) -> &PluginMetadata {
352        &self.metadata
353    }
354
355    fn path(&self) -> &Path {
356        &self.path
357    }
358
359    fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
360        self.execute(ctx)
361    }
362}
363
364/// Plugin loader responsible for discovering and loading native plugins.
365///
366/// A trusted directory is an application-managed or explicitly user-approved
367/// installation location. Repository-controlled directories must not be added
368/// as trusted directories: loading a dynamic library executes its constructors
369/// before the plugin ABI can be inspected.
370pub struct PluginLoader {
371    /// Trusted plugin directories
372    trusted_dirs: Vec<PathBuf>,
373}
374
375impl PluginLoader {
376    /// Create a new plugin loader
377    pub fn new() -> Self {
378        Self { trusted_dirs: Vec::new() }
379    }
380
381    /// Add an explicitly trusted plugin directory.
382    ///
383    /// This method only enforces path containment after the directory is
384    /// trusted; it does not verify provenance or obtain user consent. Callers
385    /// must not pass paths selected from repository contents.
386    pub fn add_trusted_dir(&mut self, path: PathBuf) -> &mut Self {
387        let path = normalize_trusted_dir(path);
388        if !self.trusted_dirs.contains(&path) {
389            warn_if_insecure_trusted_dir(&path);
390            self.trusted_dirs.push(path);
391        }
392        self
393    }
394
395    /// Get trusted plugin directories
396    pub fn trusted_dirs(&self) -> &[PathBuf] {
397        &self.trusted_dirs
398    }
399
400    /// Load a plugin from a specific path.
401    ///
402    /// # Security
403    ///
404    /// `Library::new` can execute arbitrary native initialization code before
405    /// this function returns. The caller must establish explicit user consent
406    /// and provenance before calling this method; plugin metadata is not an
407    /// authorization mechanism.
408    pub fn load_plugin(&self, plugin_path: &Path) -> Result<Box<dyn NativePluginTrait>> {
409        debug!("Loading native plugin from {:?}", plugin_path);
410
411        let plugin_path = self.ensure_trusted_path(plugin_path, "Plugin path")?;
412
413        // Find the dynamic library file
414        let lib_path = self.find_library_file(&plugin_path)?;
415        let lib_path = self.ensure_trusted_path(&lib_path, "Plugin library path")?;
416
417        // SAFETY: Loading a dynamic library is inherently unsafe because:
418        // 1. The library code executes with full privileges.
419        // 2. `lib_path` is an existing canonical path under a trusted root, so
420        //    path traversal and symlink escapes were rejected before this point.
421        // 3. The library could have bugs or malicious intent.
422        //
423        // Risk Mitigation:
424        // - Only load from canonicalized trusted directories.
425        // - Verify ABI version compatibility in `NativePlugin::new`.
426        // - Validate metadata format.
427        let library = unsafe { Library::new(&lib_path) }
428            .with_context(|| format!("Failed to load dynamic library at {lib_path:?}"))?;
429
430        let plugin = NativePlugin::new(library, plugin_path.clone())?;
431
432        info!(
433            "Loaded native plugin '{}' v{} from {:?}",
434            plugin.metadata.name, plugin.metadata.version, plugin_path
435        );
436
437        Ok(Box::new(plugin))
438    }
439
440    /// Discover and load all plugins in trusted directories.
441    ///
442    /// Loading occurs during discovery, so callers must establish provenance
443    /// and explicit user consent before invoking this method.
444    pub fn discover_plugins(&self) -> Result<Vec<Box<dyn NativePluginTrait>>> {
445        let mut plugins = Vec::new();
446
447        for dir in &self.trusted_dirs {
448            warn_if_insecure_trusted_dir(dir);
449            if !dir.exists() {
450                continue;
451            }
452
453            match self.discover_plugins_in_dir(dir) {
454                Ok(mut dir_plugins) => plugins.append(&mut dir_plugins),
455                Err(e) => {
456                    warn!("Failed to discover plugins in {:?}: {}", dir, e);
457                }
458            }
459        }
460
461        Ok(plugins)
462    }
463
464    /// Check if a path is in a trusted directory
465    fn is_in_trusted_dir(&self, path: &Path) -> bool {
466        self.trusted_dirs.iter().any(|dir| path.starts_with(dir))
467    }
468
469    fn ensure_trusted_path(&self, path: &Path, label: &str) -> Result<PathBuf> {
470        let path = canonicalize_existing_path(path, label)?;
471        if self.is_in_trusted_dir(&path) {
472            Ok(path)
473        } else {
474            Err(anyhow!("{label} {path:?} is not in a trusted directory"))
475        }
476    }
477
478    /// Find the dynamic library file in a plugin directory
479    fn find_library_file(&self, plugin_dir: &Path) -> Result<PathBuf> {
480        if !plugin_dir.is_dir() {
481            return Err(anyhow!("Plugin path is not a directory"));
482        }
483
484        // Look for plugin.json to confirm this is a plugin directory
485        let metadata_path = plugin_dir.join("plugin.json");
486        if !metadata_path.exists() {
487            return Err(anyhow!("No plugin.json found in {plugin_dir:?}"));
488        }
489
490        // Look for dynamic library with platform-specific naming
491        let lib_name = self.get_library_name_from_metadata(&metadata_path)?;
492
493        let lib_path = plugin_dir.join(&lib_name);
494        if lib_path.exists() {
495            return Ok(lib_path);
496        }
497
498        // Try alternative naming patterns
499        let alternatives = self.get_alternative_library_names(&lib_name);
500        for alt in alternatives {
501            let alt_path = plugin_dir.join(alt);
502            if alt_path.exists() {
503                return Ok(alt_path);
504            }
505        }
506
507        Err(anyhow!("No dynamic library found in {plugin_dir:?}. Expected one of: {lib_name}, or alternatives"))
508    }
509
510    /// Get expected library name from plugin metadata
511    fn get_library_name_from_metadata(&self, metadata_path: &Path) -> Result<String> {
512        let metadata_content = std::fs::read_to_string(metadata_path).context("Failed to read plugin metadata")?;
513        let metadata: serde_json::Value =
514            serde_json::from_str(&metadata_content).context("Invalid plugin metadata JSON")?;
515
516        let name = metadata["name"]
517            .as_str()
518            .ok_or_else(|| anyhow!("Plugin metadata missing 'name' field"))?;
519
520        Ok(self.library_filename(name))
521    }
522
523    /// Get alternative library names to try
524    fn get_alternative_library_names(&self, base_name: &str) -> Vec<String> {
525        let mut alternatives = Vec::new();
526
527        // Try with and without "lib" prefix
528        if let Some(stripped) = base_name.strip_prefix("lib") {
529            alternatives.push(stripped.to_string());
530        } else {
531            alternatives.push(format!("lib{base_name}"));
532        }
533
534        // Try different extensions
535        let base = base_name.trim_prefix("lib");
536        #[cfg(target_os = "macos")]
537        {
538            alternatives.push(format!("{base}.dylib"));
539            alternatives.push(format!("lib{base}.dylib"));
540        }
541        #[cfg(target_os = "linux")]
542        {
543            alternatives.push(format!("{}.so", base));
544            alternatives.push(format!("lib{}.so", base));
545        }
546        #[cfg(target_os = "windows")]
547        {
548            alternatives.push(format!("{}.dll", base));
549            alternatives.push(format!("lib{}.dll", base));
550        }
551
552        alternatives
553    }
554
555    /// Discover plugins in a directory
556    fn discover_plugins_in_dir(&self, dir: &Path) -> Result<Vec<Box<dyn NativePluginTrait>>> {
557        let mut plugins = Vec::new();
558
559        for entry in std::fs::read_dir(dir)? {
560            let entry = entry?;
561            let path = entry.path();
562
563            // Trust the dirent type; only real plugin dirs get the manifest probe.
564            if vtcode_commons::walk::entry_is_dir(&entry) && path.join("plugin.json").exists() {
565                match self.load_plugin(&path) {
566                    Ok(plugin) => plugins.push(plugin),
567                    Err(e) => {
568                        warn!("Failed to load plugin at {:?}: {}", path, e);
569                    }
570                }
571            }
572        }
573
574        Ok(plugins)
575    }
576
577    /// Convert a plugin name to a library filename for the current platform
578    pub fn library_filename(&self, name: &str) -> String {
579        #[cfg(target_os = "macos")]
580        {
581            format!("lib{name}.dylib")
582        }
583        #[cfg(target_os = "linux")]
584        {
585            format!("lib{}.so", name)
586        }
587        #[cfg(target_os = "windows")]
588        {
589            format!("{}.dll", name)
590        }
591        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
592        {
593            format!("lib{}", name)
594        }
595    }
596}
597
598impl Default for PluginLoader {
599    fn default() -> Self {
600        Self::new()
601    }
602}
603
604/// Validate a plugin directory structure
605pub fn validate_plugin_structure(plugin_dir: &Path) -> Result<Vec<String>> {
606    let mut errors = Vec::new();
607
608    // Check for plugin.json
609    if !plugin_dir.join("plugin.json").exists() {
610        errors.push("Missing plugin.json".to_string());
611    }
612
613    // Check for dynamic library
614    let has_lib = std::fs::read_dir(plugin_dir)
615        .map(|entries| {
616            entries.filter_map(|e| e.ok()).any(|entry| {
617                let path = entry.path();
618                let ext = path.extension().and_then(|e| e.to_str());
619                matches!(ext, Some("dylib") | Some("so") | Some("dll"))
620            })
621        })
622        .unwrap_or(false);
623
624    if !has_lib {
625        errors.push("No dynamic library found (.dylib, .so, or .dll)".to_string());
626    }
627
628    // Validate plugin.json structure
629    if let Ok(content) = std::fs::read_to_string(plugin_dir.join("plugin.json")) {
630        if let Ok(metadata) = serde_json::from_str::<serde_json::Value>(&content) {
631            if metadata["name"].as_str().is_none() {
632                errors.push("plugin.json missing required 'name' field".to_string());
633            }
634            if metadata["description"].as_str().is_none() {
635                errors.push("plugin.json missing required 'description' field".to_string());
636            }
637            if metadata["version"].as_str().is_none() {
638                errors.push("plugin.json missing required 'version' field".to_string());
639            }
640        } else {
641            errors.push("Invalid JSON in plugin.json".to_string());
642        }
643    }
644
645    Ok(errors)
646}
647
648#[cfg(test)]
649mod tests;