turboclaudeagent 0.3.0

Interactive Agent SDK for TurboClaude - Use Claude agents in your Rust applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
//! Plugin system for extending Claude Code with custom functionality
//!
//! Plugins allow extending Claude Code with custom commands, agents, skills, and hooks.
//! Currently, the system supports loading local plugins from the filesystem.
//!
//! # Plugin Structure
//!
//! A plugin directory should have the following structure:
//! ```text
//! my-plugin/
//! ├── .claude-plugin/
//! │   └── plugin.json
//! └── commands/
//!     └── my-command.md
//! ```
//!
//! # Example
//!
//! ```rust
//! use turboclaudeagent::plugins::SdkPluginConfig;
//! use std::path::PathBuf;
//!
//! let plugin_config = SdkPluginConfig {
//!     plugin_type: "local".to_string(),
//!     path: "/path/to/my-plugin".to_string(),
//! };
//! ```

use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

/// SDK plugin configuration
///
/// Specifies a plugin to be loaded. Currently only local plugins are supported.
///
/// # Fields
///
/// * `plugin_type` - The type of plugin (currently only "local" is supported)
/// * `path` - Path to the plugin directory (relative or absolute)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SdkPluginConfig {
    /// Plugin type (currently "local")
    #[serde(rename = "type")]
    pub plugin_type: String,

    /// Path to plugin directory
    pub path: String,
}

impl SdkPluginConfig {
    /// Create a new local plugin configuration
    ///
    /// # Arguments
    /// * `path` - Path to the plugin directory
    ///
    /// # Example
    /// ```rust
    /// use turboclaudeagent::plugins::SdkPluginConfig;
    ///
    /// let config = SdkPluginConfig::local("./plugins/my-plugin");
    /// ```
    pub fn local(path: impl Into<String>) -> Self {
        Self {
            plugin_type: "local".to_string(),
            path: path.into(),
        }
    }

    /// Validate that the plugin path exists and is a directory
    pub fn validate(&self) -> Result<(), String> {
        if self.plugin_type != "local" {
            return Err(format!(
                "Unsupported plugin type: {}. Only 'local' is supported.",
                self.plugin_type
            ));
        }

        let path = Path::new(&self.path);
        if !path.exists() {
            return Err(format!("Plugin path does not exist: {}", self.path));
        }

        if !path.is_dir() {
            return Err(format!("Plugin path is not a directory: {}", self.path));
        }

        Ok(())
    }
}

/// Metadata about a plugin
///
/// Loaded from `.claude-plugin/plugin.json` in the plugin directory.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginMetadata {
    /// Plugin name
    pub name: String,

    /// Plugin description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    /// Plugin version
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,

    /// Plugin author
    #[serde(skip_serializing_if = "Option::is_none")]
    pub author: Option<String>,
}

/// A loaded plugin
///
/// Represents a plugin that has been discovered and loaded from the filesystem.
#[derive(Debug, Clone)]
pub struct Plugin {
    /// Plugin metadata
    pub metadata: PluginMetadata,

    /// Path to the plugin directory
    pub path: PathBuf,

    /// List of available commands
    pub commands: Vec<String>,
}

impl Plugin {
    /// Load a plugin from the specified path
    ///
    /// # Arguments
    /// * `path` - Path to the plugin directory
    ///
    /// # Errors
    /// Returns an error if:
    /// - The plugin directory doesn't exist
    /// - The .claude-plugin/plugin.json file is missing or invalid
    /// - JSON parsing fails
    ///
    /// # Example
    /// ```no_run
    /// use turboclaudeagent::plugins::Plugin;
    ///
    /// let plugin = Plugin::from_path("./plugins/my-plugin")
    ///     .expect("Failed to load plugin");
    /// ```
    pub fn from_path(path: impl AsRef<Path>) -> Result<Self, String> {
        let path = path.as_ref();

        if !path.is_dir() {
            return Err(format!("Plugin path is not a directory: {:?}", path));
        }

        // Load plugin metadata
        let metadata_path = path.join(".claude-plugin").join("plugin.json");
        let metadata_content = fs::read_to_string(&metadata_path)
            .map_err(|e| format!("Failed to read plugin.json: {}", e))?;

        let metadata: PluginMetadata = serde_json::from_str(&metadata_content)
            .map_err(|e| format!("Invalid plugin.json: {}", e))?;

        // Discover commands
        let mut commands = Vec::new();
        let commands_dir = path.join("commands");

        if commands_dir.exists()
            && commands_dir.is_dir()
            && let Ok(entries) = fs::read_dir(&commands_dir)
        {
            for entry in entries.flatten() {
                if let Ok(file_type) = entry.file_type()
                    && file_type.is_file()
                    && let Some(file_name) = entry.file_name().to_str()
                    && file_name.ends_with(".md")
                {
                    // Remove .md extension
                    let command_name = file_name.trim_end_matches(".md").to_string();
                    commands.push(command_name);
                }
            }
        }

        commands.sort();

        Ok(Plugin {
            metadata,
            path: path.to_path_buf(),
            commands,
        })
    }
}

/// Plugin loader for discovering and loading plugins
///
/// Handles loading plugins from filesystem paths and discovering available commands.
pub struct PluginLoader {
    config: SdkPluginConfig,
}

impl PluginLoader {
    /// Create a new plugin loader
    pub fn new(config: SdkPluginConfig) -> Self {
        Self { config }
    }

    /// Get the plugin configuration
    pub fn config(&self) -> &SdkPluginConfig {
        &self.config
    }

    /// Load the plugin
    ///
    /// # Errors
    /// Returns an error if the plugin cannot be loaded or the configuration is invalid
    pub fn load(&self) -> Result<Plugin, String> {
        self.config.validate()?;
        Plugin::from_path(&self.config.path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ===== SdkPluginConfig Tests =====

    #[test]
    fn test_sdk_plugin_config_local() {
        let config = SdkPluginConfig::local("./plugins/test");
        assert_eq!(config.plugin_type, "local");
        assert_eq!(config.path, "./plugins/test");
    }

    #[test]
    fn test_sdk_plugin_config_serialization() {
        let config = SdkPluginConfig::local("./my-plugin");
        let json = serde_json::to_string(&config).unwrap();
        assert!(json.contains("\"type\":\"local\""));
        assert!(json.contains("\"path\":\"./my-plugin\""));
    }

    #[test]
    fn test_sdk_plugin_config_deserialization() {
        let json = r#"{"type":"local","path":"/path/to/plugin"}"#;
        let config: SdkPluginConfig = serde_json::from_str(json).unwrap();
        assert_eq!(config.plugin_type, "local");
        assert_eq!(config.path, "/path/to/plugin");
    }

    #[test]
    fn test_sdk_plugin_config_equality() {
        let config1 = SdkPluginConfig::local("./plugin");
        let config2 = SdkPluginConfig::local("./plugin");
        assert_eq!(config1, config2);
    }

    #[test]
    fn test_sdk_plugin_config_validate_invalid_type() {
        let config = SdkPluginConfig {
            plugin_type: "remote".to_string(),
            path: "./plugin".to_string(),
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_sdk_plugin_config_validate_nonexistent_path() {
        let config = SdkPluginConfig::local("/nonexistent/path/12345");
        assert!(config.validate().is_err());
    }

    // ===== PluginMetadata Tests =====

    #[test]
    fn test_plugin_metadata_creation() {
        let metadata = PluginMetadata {
            name: "test-plugin".to_string(),
            description: Some("Test description".to_string()),
            version: Some("1.0.0".to_string()),
            author: Some("Test Author".to_string()),
        };
        assert_eq!(metadata.name, "test-plugin");
        assert_eq!(metadata.description, Some("Test description".to_string()));
    }

    #[test]
    fn test_plugin_metadata_serialization() {
        let metadata = PluginMetadata {
            name: "my-plugin".to_string(),
            description: Some("A test plugin".to_string()),
            version: Some("1.0.0".to_string()),
            author: None,
        };
        let json = serde_json::to_string(&metadata).unwrap();
        assert!(json.contains("\"name\":\"my-plugin\""));
        assert!(json.contains("\"description\":\"A test plugin\""));
        assert!(json.contains("\"version\":\"1.0.0\""));
        assert!(!json.contains("\"author\""));
    }

    #[test]
    fn test_plugin_metadata_deserialization() {
        let json =
            r#"{"name":"test","description":"Test plugin","version":"1.0","author":"Author"}"#;
        let metadata: PluginMetadata = serde_json::from_str(json).unwrap();
        assert_eq!(metadata.name, "test");
        assert_eq!(metadata.description, Some("Test plugin".to_string()));
        assert_eq!(metadata.version, Some("1.0".to_string()));
        assert_eq!(metadata.author, Some("Author".to_string()));
    }

    #[test]
    fn test_plugin_metadata_minimal() {
        let json = r#"{"name":"minimal"}"#;
        let metadata: PluginMetadata = serde_json::from_str(json).unwrap();
        assert_eq!(metadata.name, "minimal");
        assert!(metadata.description.is_none());
        assert!(metadata.version.is_none());
        assert!(metadata.author.is_none());
    }

    // ===== Plugin Tests =====

    #[test]
    fn test_plugin_creation() {
        let metadata = PluginMetadata {
            name: "test-plugin".to_string(),
            description: None,
            version: None,
            author: None,
        };
        let plugin = Plugin {
            metadata,
            path: PathBuf::from("./plugin"),
            commands: vec!["cmd1".to_string(), "cmd2".to_string()],
        };
        assert_eq!(plugin.metadata.name, "test-plugin");
        assert_eq!(plugin.commands.len(), 2);
    }

    #[test]
    fn test_plugin_commands_sorted() {
        let metadata = PluginMetadata {
            name: "test".to_string(),
            description: None,
            version: None,
            author: None,
        };
        let mut plugin = Plugin {
            metadata,
            path: PathBuf::from("./plugin"),
            commands: vec![
                "zebra".to_string(),
                "apple".to_string(),
                "monkey".to_string(),
            ],
        };
        plugin.commands.sort();
        assert_eq!(plugin.commands[0], "apple");
        assert_eq!(plugin.commands[2], "zebra");
    }

    // ===== PluginLoader Tests =====

    #[test]
    fn test_plugin_loader_creation() {
        let config = SdkPluginConfig::local("./plugin");
        let loader = PluginLoader::new(config);
        assert_eq!(loader.config.plugin_type, "local");
    }

    #[test]
    fn test_plugin_loader_load_nonexistent() {
        let config = SdkPluginConfig::local("/nonexistent/plugin");
        let loader = PluginLoader::new(config);
        assert!(loader.load().is_err());
    }

    // ===== Integration Tests =====

    #[test]
    fn test_plugin_config_and_loader_workflow() {
        // Create a plugin config
        let config = SdkPluginConfig::local("./my-plugin");

        // Validate the config (will fail for this test since path doesn't exist)
        match config.validate() {
            Ok(_) => {
                // If validation passes, we could load
                let loader = PluginLoader::new(config);
                let _ = loader.load();
            }
            Err(_) => {
                // Expected for this test
                assert_eq!(config.plugin_type, "local");
            }
        }
    }

    #[test]
    fn test_multiple_plugins_configs() {
        let config1 = SdkPluginConfig::local("./plugin1");
        let config2 = SdkPluginConfig::local("./plugin2");

        assert_ne!(config1.path, config2.path);
        assert_eq!(config1.plugin_type, config2.plugin_type);
    }

    #[test]
    fn test_plugin_metadata_round_trip() {
        let original = PluginMetadata {
            name: "round-trip".to_string(),
            description: Some("Test".to_string()),
            version: Some("2.0.0".to_string()),
            author: Some("Test Author".to_string()),
        };

        let json = serde_json::to_string(&original).unwrap();
        let deserialized: PluginMetadata = serde_json::from_str(&json).unwrap();

        assert_eq!(original.name, deserialized.name);
        assert_eq!(original.description, deserialized.description);
        assert_eq!(original.version, deserialized.version);
        assert_eq!(original.author, deserialized.author);
    }
}