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    /// Plugin metadata
161    metadata: PluginMetadata,
162    /// Path to the plugin
163    path: PathBuf,
164    /// Plugin execute function pointer
165    execute_fn: PluginExecuteFn,
166    /// Optional plugin-owned deallocator for returned strings
167    free_string_fn: Option<PluginFreeStringFn>,
168    /// Serialize calls if the plugin is not reentrant.
169    execution_lock: Mutex<()>,
170    /// Optimized thread-safety flag from metadata.
171    thread_safe: bool,
172    /// Loaded plugin library handle.
173    ///
174    /// # Lifetime invariant
175    ///
176    /// `execute_fn` and `free_string_fn` are raw function pointers copied out
177    /// of this library and are only valid while it remains loaded. This field
178    /// is declared last on purpose: Rust drops struct fields in declaration
179    /// order, so `Library`'s `Drop` (`dlclose`) runs after every other field
180    /// is gone. `NativePlugin` has no `Drop`, so no field destructor can call
181    /// into a library that has already unloaded. Keep this field last.
182    _library: Library,
183}
184
185fn ensure_non_null_c_string_ptr(ptr: *const c_char, context: &'static str) -> Result<NonNull<c_char>> {
186    NonNull::new(ptr.cast_mut()).ok_or_else(|| anyhow!("{context} returned null pointer"))
187}
188
189/// A plugin-returned C string paired with its matching plugin deallocator.
190///
191/// This is the safety boundary's ownership contract made structural: keeping
192/// the buffer and its deallocator in one owned value means `Drop` releases the
193/// plugin memory on *every* exit path (success, decode error, or unwind). A
194/// plain "decode, then call `free`" sequence is correct today but one early
195/// return away from becoming a leak; the guard removes that class of bug.
196///
197/// `NonNull` is deliberately `!Send`/`!Sync`, so a plugin string cannot be
198/// retained or shared past the call that produced it — the safe wrapper never
199/// holds a reference to plugin-owned memory after the bridge call completes.
200struct PluginOwnedCString {
201    ptr: NonNull<c_char>,
202    free: Option<PluginFreeStringFn>,
203}
204
205impl PluginOwnedCString {
206    fn new(ptr: NonNull<c_char>, free: Option<PluginFreeStringFn>) -> Self {
207        Self { ptr, free }
208    }
209
210    /// Copy the plugin buffer into an owned Rust `String`.
211    ///
212    /// The borrow from `CStr::from_ptr` ends at `to_owned`, before `Drop`
213    /// releases the buffer, so no reference outlives the deallocation.
214    fn decode(&self, utf8_error_context: &'static str) -> Result<String> {
215        let raw_ptr = self.ptr.as_ptr().cast_const();
216        // SAFETY:
217        // 1. `raw_ptr` is non-null (validated by `ensure_non_null_c_string_ptr`).
218        // 2. The plugin ABI guarantees a nul-terminated C string until the
219        //    matching deallocator runs, which `Drop` does only after this
220        //    borrow ends.
221        // 3. We copy into a Rust `String`; no reference survives this call.
222        unsafe { CStr::from_ptr(raw_ptr) }
223            .to_str()
224            .context(utf8_error_context)
225            .map(str::to_owned)
226    }
227}
228
229impl Drop for PluginOwnedCString {
230    fn drop(&mut self) {
231        if let Some(free_fn) = self.free {
232            // SAFETY: `ptr` came from the same plugin instance that supplied
233            // `free_fn`; it is released exactly once, after any decoding.
234            unsafe { free_fn(self.ptr.as_ptr().cast_const()) };
235        }
236    }
237}
238
239/// Decode a plugin-owned C string into an owned Rust `String`, then release
240/// the plugin buffer through its matching deallocator (if one was exported).
241fn decode_plugin_c_string(
242    ptr: NonNull<c_char>,
243    free_string_fn: Option<PluginFreeStringFn>,
244    utf8_error_context: &'static str,
245) -> Result<String> {
246    PluginOwnedCString::new(ptr, free_string_fn).decode(utf8_error_context)
247}
248
249impl std::fmt::Debug for NativePlugin {
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        f.debug_struct("NativePlugin")
252            .field("metadata", &self.metadata)
253            .field("path", &self.path)
254            .finish()
255    }
256}
257
258fn canonicalize_existing_path(path: &Path, label: &str) -> Result<PathBuf> {
259    canonicalize(path).with_context(|| format!("Failed to resolve {label} '{}'", path.display()))
260}
261
262/// Resolve a C-ABI symbol from a trusted, already-validated plugin library.
263///
264/// Single wrapper around libloading's symbol lookup; every plugin symbol
265/// passage goes through here. `T` must be a `Copy` function-pointer type. The
266/// returned value is valid only while `library` (`NativePlugin._library`) is loaded.
267fn get_plugin_symbol<T: Copy>(library: &Library, name: &[u8]) -> Result<T> {
268    // SAFETY: symbol name and signature are defined by the plugin ABI; we trust
269    // the library (canonicalized/trusted location). `T: Copy` makes the deref safe.
270    let symbol: Symbol<T> = unsafe { library.get(name) }.with_context(|| {
271        format!("Failed to load plugin symbol: {:?}", String::from_utf8_lossy(name.trim_suffix(b"\0")))
272    })?;
273    Ok(*symbol)
274}
275
276fn normalize_trusted_dir(path: PathBuf) -> PathBuf {
277    canonicalize_existing_path(&path, "trusted plugin directory").unwrap_or_else(|_| {
278        if path.is_absolute() {
279            path
280        } else {
281            std::env::current_dir().map(|cwd| cwd.join(&path)).unwrap_or(path)
282        }
283    })
284}
285
286#[cfg(unix)]
287fn warn_if_insecure_trusted_dir(dir: &Path) {
288    if let Ok(metadata) = std::fs::metadata(dir) {
289        let mode = metadata.permissions().mode();
290        if mode & 0o022 != 0 {
291            let perm_octal = format!("{:o}", mode & 0o777);
292            warn!(
293                dir = ?dir,
294                mode = %perm_octal,
295                "trusted plugin directory is writable by group or others; a non-owner user could plant a malicious plugin via symlink or replacement"
296            );
297        }
298    }
299}
300
301#[cfg(not(unix))]
302fn warn_if_insecure_trusted_dir(_dir: &Path) {}
303
304impl NativePlugin {
305    /// Create a new native plugin from a loaded library
306    fn new(library: Library, path: PathBuf) -> Result<Self> {
307        // Verify ABI version
308        let version_fn = get_plugin_symbol::<PluginVersionFn>(&library, b"vtcode_plugin_version\0")?;
309
310        // SAFETY: function pointer was loaded from a validated ABI symbol.
311        let abi_version = unsafe { version_fn() };
312        if abi_version != PLUGIN_ABI_VERSION {
313            return Err(anyhow!("Plugin ABI version mismatch: expected {PLUGIN_ABI_VERSION}, got {abi_version}"));
314        }
315
316        // Optional cleanup function for plugin-owned strings.
317        let free_string_fn = get_plugin_symbol::<PluginFreeStringFn>(&library, b"vtcode_plugin_free_string\0").ok();
318
319        // Load metadata
320        let metadata_fn = get_plugin_symbol::<PluginMetadataFn>(&library, b"vtcode_plugin_metadata\0")?;
321
322        // SAFETY: function pointer loaded from the validated ABI symbol.
323        let metadata_ptr = ensure_non_null_c_string_ptr(unsafe { metadata_fn() }, "Plugin metadata function")?;
324        let metadata_json = decode_plugin_c_string(metadata_ptr, free_string_fn, "Plugin metadata is not valid UTF-8")?;
325
326        let metadata: PluginMetadata =
327            serde_json::from_str(&metadata_json).context("Failed to parse plugin metadata JSON")?;
328
329        // Load execute function
330        let execute_fn = get_plugin_symbol::<PluginExecuteFn>(&library, b"vtcode_plugin_execute\0")?;
331
332        Ok(Self {
333            _library: library,
334            metadata: metadata.clone(), // Clone metadata to store it
335            path,
336            execute_fn,
337            free_string_fn,
338            execution_lock: Mutex::new(()),
339            thread_safe: metadata.thread_safe, // Store the thread_safe flag
340        })
341    }
342
343    /// Execute the plugin with the given context
344    fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
345        let input_json = serde_json::to_string(ctx).context("Failed to serialize plugin context")?;
346        let input_cstr = CString::new(input_json).context("Plugin context contains internal null bytes")?;
347
348        // Serialization logic from Antithesis Part 2 (Challenge 2):
349        // If the plugin is not explicitly marked as thread-safe, we must serialize
350        // access through the execution lock to prevent unsynchronized shared access.
351        if !self.thread_safe {
352            let _execution_guard = self
353                .execution_lock
354                .lock()
355                .map_err(|_e| anyhow!("native plugin execution lock poisoned"))?;
356
357            self.execute_ffi(input_cstr)
358        } else {
359            // Reentrant plugins can skip the lock for multi-threaded performance.
360            self.execute_ffi(input_cstr)
361        }
362    }
363
364    /// Internal FFI bridge for plugin execution.
365    ///
366    /// # Safety
367    ///
368    /// This function performs the raw FFI call. Callers must ensure that
369    /// if the plugin is not thread-safe, it is called under a lock.
370    fn execute_ffi(&self, input_cstr: CString) -> Result<PluginResult> {
371        // SAFETY:
372        // 1. The `input_cstr` pointer is valid for the duration of this call.
373        // 2. The `execute_fn` obeys the plugin ABI and expects a nul-terminated string.
374        // 3. VT Code either holds `execution_lock` or the plugin is explicitly reentrant (thread_safe: true).
375        let result_ptr =
376            ensure_non_null_c_string_ptr(unsafe { (self.execute_fn)(input_cstr.as_ptr()) }, "Plugin execute function")?;
377        let result_json = decode_plugin_c_string(result_ptr, self.free_string_fn, "Plugin result is not valid UTF-8")?;
378
379        let result: PluginResult = serde_json::from_str(&result_json).context("Failed to parse plugin result JSON")?;
380
381        Ok(result)
382    }
383}
384
385impl NativePluginTrait for NativePlugin {
386    fn metadata(&self) -> &PluginMetadata {
387        &self.metadata
388    }
389
390    fn path(&self) -> &Path {
391        &self.path
392    }
393
394    fn execute(&self, ctx: &PluginContext) -> Result<PluginResult> {
395        self.execute(ctx)
396    }
397}
398
399/// Plugin loader responsible for discovering and loading native plugins.
400///
401/// A trusted directory is an application-managed or explicitly user-approved
402/// installation location. Repository-controlled directories must not be added
403/// as trusted directories: loading a dynamic library executes its constructors
404/// before the plugin ABI can be inspected.
405pub struct PluginLoader {
406    /// Trusted plugin directories
407    trusted_dirs: Vec<PathBuf>,
408}
409
410impl PluginLoader {
411    /// Create a new plugin loader
412    pub fn new() -> Self {
413        Self { trusted_dirs: Vec::new() }
414    }
415
416    /// Add an explicitly trusted plugin directory.
417    ///
418    /// This method only enforces path containment after the directory is
419    /// trusted; it does not verify provenance or obtain user consent. Callers
420    /// must not pass paths selected from repository contents.
421    pub fn add_trusted_dir(&mut self, path: PathBuf) -> &mut Self {
422        let path = normalize_trusted_dir(path);
423        if !self.trusted_dirs.contains(&path) {
424            warn_if_insecure_trusted_dir(&path);
425            self.trusted_dirs.push(path);
426        }
427        self
428    }
429
430    /// Get trusted plugin directories
431    pub fn trusted_dirs(&self) -> &[PathBuf] {
432        &self.trusted_dirs
433    }
434
435    /// Load a plugin from a specific path.
436    ///
437    /// # Security
438    ///
439    /// `Library::new` can execute arbitrary native initialization code before
440    /// this function returns. The caller must establish explicit user consent
441    /// and provenance before calling this method; plugin metadata is not an
442    /// authorization mechanism.
443    pub fn load_plugin(&self, plugin_path: &Path) -> Result<Box<dyn NativePluginTrait>> {
444        debug!("Loading native plugin from {:?}", plugin_path);
445
446        let plugin_path = self.ensure_trusted_path(plugin_path, "Plugin path")?;
447
448        // Find the dynamic library file
449        let lib_path = self.find_library_file(&plugin_path)?;
450        let lib_path = self.ensure_trusted_path(&lib_path, "Plugin library path")?;
451
452        // SAFETY: Loading a dynamic library is inherently unsafe because:
453        // 1. The library code executes with full privileges.
454        // 2. `lib_path` is an existing canonical path under a trusted root, so
455        //    path traversal and symlink escapes were rejected before this point.
456        // 3. The library could have bugs or malicious intent.
457        //
458        // Risk Mitigation:
459        // - Only load from canonicalized trusted directories.
460        // - Verify ABI version compatibility in `NativePlugin::new`.
461        // - Validate metadata format.
462        let library = unsafe { Library::new(&lib_path) }
463            .with_context(|| format!("Failed to load dynamic library at {lib_path:?}"))?;
464
465        let plugin = NativePlugin::new(library, plugin_path.clone())?;
466
467        info!(
468            "Loaded native plugin '{}' v{} from {:?}",
469            plugin.metadata.name, plugin.metadata.version, plugin_path
470        );
471
472        Ok(Box::new(plugin))
473    }
474
475    /// Discover and load all plugins in trusted directories.
476    ///
477    /// Loading occurs during discovery, so callers must establish provenance
478    /// and explicit user consent before invoking this method.
479    pub fn discover_plugins(&self) -> Result<Vec<Box<dyn NativePluginTrait>>> {
480        let mut plugins = Vec::new();
481
482        for dir in &self.trusted_dirs {
483            warn_if_insecure_trusted_dir(dir);
484            if !dir.exists() {
485                continue;
486            }
487
488            match self.discover_plugins_in_dir(dir) {
489                Ok(mut dir_plugins) => plugins.append(&mut dir_plugins),
490                Err(e) => {
491                    warn!("Failed to discover plugins in {:?}: {}", dir, e);
492                }
493            }
494        }
495
496        Ok(plugins)
497    }
498
499    /// Check if a path is in a trusted directory
500    fn is_in_trusted_dir(&self, path: &Path) -> bool {
501        self.trusted_dirs.iter().any(|dir| path.starts_with(dir))
502    }
503
504    fn ensure_trusted_path(&self, path: &Path, label: &str) -> Result<PathBuf> {
505        let path = canonicalize_existing_path(path, label)?;
506        if self.is_in_trusted_dir(&path) {
507            Ok(path)
508        } else {
509            Err(anyhow!("{label} {path:?} is not in a trusted directory"))
510        }
511    }
512
513    /// Find the dynamic library file in a plugin directory
514    fn find_library_file(&self, plugin_dir: &Path) -> Result<PathBuf> {
515        if !plugin_dir.is_dir() {
516            return Err(anyhow!("Plugin path is not a directory"));
517        }
518
519        // Look for plugin.json to confirm this is a plugin directory
520        let metadata_path = plugin_dir.join("plugin.json");
521        if !metadata_path.exists() {
522            return Err(anyhow!("No plugin.json found in {plugin_dir:?}"));
523        }
524
525        // Look for dynamic library with platform-specific naming
526        let lib_name = self.get_library_name_from_metadata(&metadata_path)?;
527
528        let lib_path = plugin_dir.join(&lib_name);
529        if lib_path.exists() {
530            return Ok(lib_path);
531        }
532
533        // Try alternative naming patterns
534        let alternatives = self.get_alternative_library_names(&lib_name);
535        for alt in alternatives {
536            let alt_path = plugin_dir.join(alt);
537            if alt_path.exists() {
538                return Ok(alt_path);
539            }
540        }
541
542        Err(anyhow!("No dynamic library found in {plugin_dir:?}. Expected one of: {lib_name}, or alternatives"))
543    }
544
545    /// Get expected library name from plugin metadata
546    fn get_library_name_from_metadata(&self, metadata_path: &Path) -> Result<String> {
547        let metadata_content = std::fs::read_to_string(metadata_path).context("Failed to read plugin metadata")?;
548        let metadata: serde_json::Value =
549            serde_json::from_str(&metadata_content).context("Invalid plugin metadata JSON")?;
550
551        let name = metadata["name"]
552            .as_str()
553            .ok_or_else(|| anyhow!("Plugin metadata missing 'name' field"))?;
554
555        Ok(self.library_filename(name))
556    }
557
558    /// Get alternative library names to try
559    fn get_alternative_library_names(&self, base_name: &str) -> Vec<String> {
560        let mut alternatives = Vec::new();
561
562        // Try with and without "lib" prefix
563        if let Some(stripped) = base_name.strip_prefix("lib") {
564            alternatives.push(stripped.to_string());
565        } else {
566            alternatives.push(format!("lib{base_name}"));
567        }
568
569        // Try different extensions
570        let base = base_name.trim_prefix("lib");
571        #[cfg(target_os = "macos")]
572        {
573            alternatives.push(format!("{base}.dylib"));
574            alternatives.push(format!("lib{base}.dylib"));
575        }
576        #[cfg(target_os = "linux")]
577        {
578            alternatives.push(format!("{}.so", base));
579            alternatives.push(format!("lib{}.so", base));
580        }
581        #[cfg(target_os = "windows")]
582        {
583            alternatives.push(format!("{}.dll", base));
584            alternatives.push(format!("lib{}.dll", base));
585        }
586
587        alternatives
588    }
589
590    /// Discover plugins in a directory
591    fn discover_plugins_in_dir(&self, dir: &Path) -> Result<Vec<Box<dyn NativePluginTrait>>> {
592        let mut plugins = Vec::new();
593
594        for entry in std::fs::read_dir(dir)? {
595            let entry = entry?;
596            let path = entry.path();
597
598            // Trust the dirent type; only real plugin dirs get the manifest probe.
599            if vtcode_commons::walk::entry_is_dir(&entry) && path.join("plugin.json").exists() {
600                match self.load_plugin(&path) {
601                    Ok(plugin) => plugins.push(plugin),
602                    Err(e) => {
603                        warn!("Failed to load plugin at {:?}: {}", path, e);
604                    }
605                }
606            }
607        }
608
609        Ok(plugins)
610    }
611
612    /// Convert a plugin name to a library filename for the current platform
613    pub fn library_filename(&self, name: &str) -> String {
614        #[cfg(target_os = "macos")]
615        {
616            format!("lib{name}.dylib")
617        }
618        #[cfg(target_os = "linux")]
619        {
620            format!("lib{}.so", name)
621        }
622        #[cfg(target_os = "windows")]
623        {
624            format!("{}.dll", name)
625        }
626        #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
627        {
628            format!("lib{}", name)
629        }
630    }
631}
632
633impl Default for PluginLoader {
634    fn default() -> Self {
635        Self::new()
636    }
637}
638
639/// Validate a plugin directory structure
640pub fn validate_plugin_structure(plugin_dir: &Path) -> Result<Vec<String>> {
641    let mut errors = Vec::new();
642
643    // Check for plugin.json
644    if !plugin_dir.join("plugin.json").exists() {
645        errors.push("Missing plugin.json".to_string());
646    }
647
648    // Check for dynamic library
649    let has_lib = std::fs::read_dir(plugin_dir)
650        .map(|entries| {
651            entries.filter_map(|e| e.ok()).any(|entry| {
652                let path = entry.path();
653                let ext = path.extension().and_then(|e| e.to_str());
654                matches!(ext, Some("dylib") | Some("so") | Some("dll"))
655            })
656        })
657        .unwrap_or(false);
658
659    if !has_lib {
660        errors.push("No dynamic library found (.dylib, .so, or .dll)".to_string());
661    }
662
663    // Validate plugin.json structure
664    if let Ok(content) = std::fs::read_to_string(plugin_dir.join("plugin.json")) {
665        if let Ok(metadata) = serde_json::from_str::<serde_json::Value>(&content) {
666            if metadata["name"].as_str().is_none() {
667                errors.push("plugin.json missing required 'name' field".to_string());
668            }
669            if metadata["description"].as_str().is_none() {
670                errors.push("plugin.json missing required 'description' field".to_string());
671            }
672            if metadata["version"].as_str().is_none() {
673                errors.push("plugin.json missing required 'version' field".to_string());
674            }
675        } else {
676            errors.push("Invalid JSON in plugin.json".to_string());
677        }
678    }
679
680    Ok(errors)
681}
682
683#[cfg(test)]
684mod tests;