# Plugin System

The Multi-Swarm Framework provides a robust plugin system that allows you to extend agent capabilities through custom tools and integrations.

## Overview

The plugin system consists of three main components:

1. **PluginBase**: Base class for creating plugins
2. **PluginMetadata**: Configuration and metadata for plugins
3. **PluginRegistry**: Central registry for managing plugins

## Creating Plugins

### Basic Plugin Structure

```python
from multi_swarm.plugins.base import PluginBase, PluginMetadata

class MyPlugin(PluginBase):
    """Custom plugin implementation."""
    def __init__(self):
        metadata = PluginMetadata(
            name="my_plugin",
            version="1.0.0",
            description="My custom plugin",
            author="Your Name",
            requirements=["required-package"],
            dependencies=[],
            tags=["custom", "example"],
            config_schema={}
        )
        super().__init__(metadata=metadata)
    
    def initialize(self) -> None:
        """Initialize plugin resources."""
        pass
    
    def cleanup(self) -> None:
        """Clean up plugin resources."""
        pass
    
    def get_capabilities(self) -> List[str]:
        """Define plugin capabilities."""
        return ["my_capability"]
```

### Plugin Metadata

The `PluginMetadata` class defines essential information about your plugin:

- `name`: Unique identifier for the plugin
- `version`: Plugin version (semantic versioning recommended)
- `description`: Brief description of plugin functionality
- `author`: Plugin author or organization
- `requirements`: List of required Python packages
- `dependencies`: List of other plugins this plugin depends on
- `tags`: List of tags for plugin categorization
- `config_schema`: JSON schema for plugin configuration

### Plugin Lifecycle

Plugins have a defined lifecycle managed by the registry:

1. **Registration**: Plugin is registered with the registry
2. **Initialization**: `initialize()` is called when plugin is first used
3. **Operation**: Plugin is used by agents
4. **Cleanup**: `cleanup()` is called when plugin is unregistered or system shuts down

## Using the Plugin Registry

### Registering Plugins

```python
from multi_swarm.plugins.registry import PluginRegistry

# Create registry
registry = PluginRegistry()

# Register a plugin
registry.register_plugin(MyPlugin)

# Get plugin instance
plugin = registry.get_plugin("my_plugin")
```

### Plugin Discovery

The registry can automatically discover plugins in specified directories:

```python
# Add plugin search path
registry.add_plugin_path("/path/to/plugins")

# Discover plugins
discovered_plugins = registry.discover_plugins()
```

### Plugin Management

```python
# Get plugins by tag
data_plugins = registry.get_plugins_by_tag("data")

# Get plugins by capability
analysis_plugins = registry.get_plugins_by_capability("analysis")

# Check plugin health
health_status = registry.health_check_all()

# Cleanup plugins
registry.cleanup_all()
```

## Creating Agent Tools

Tools are specialized plugins that provide specific capabilities to agents:

```python
from multi_swarm.plugins.base import PluginBase, PluginMetadata

class DataAnalysisTool(PluginBase):
    """Tool for data analysis capabilities."""
    def __init__(self):
        metadata = PluginMetadata(
            name="data_analysis_tool",
            version="1.0.0",
            description="Provides data analysis capabilities",
            author="Your Name",
            requirements=["pandas", "numpy"],
            tags=["data", "analysis"],
            config_schema={
                "type": "object",
                "properties": {
                    "max_rows": {"type": "integer"},
                    "precision": {"type": "number"}
                }
            }
        )
        super().__init__(metadata=metadata)
    
    def analyze_data(self, data: Any) -> Dict[str, Any]:
        """Implement tool-specific functionality."""
        # Tool implementation
        pass
```

## Plugin Configuration

### Configuration Schema

Define configuration requirements using JSON schema:

```python
config_schema = {
    "type": "object",
    "properties": {
        "api_key": {
            "type": "string",
            "description": "API key for external service"
        },
        "max_retries": {
            "type": "integer",
            "minimum": 1,
            "maximum": 10
        },
        "timeout": {
            "type": "number",
            "minimum": 0
        }
    },
    "required": ["api_key"]
}
```

### Validating Configuration

```python
def validate_config(self) -> bool:
    """Validate plugin configuration."""
    try:
        # Validate against schema
        return super().validate_config(self.config)
    except Exception as e:
        print(f"Configuration validation failed: {str(e)}")
        return False
```

## Built-in Plugins

### Git Tool

Example of using the built-in Git tool:

```python
from multi_swarm.plugins.tools.development import GitTool

# Create Git tool instance
git_tool = GitTool()

# Initialize repository
result = git_tool.initialize("/path/to/repo")

# Commit changes
result = git_tool.commit_changes(
    repo_path="/path/to/repo",
    message="Update documentation",
    files=["docs/api/plugins.md"]
)

# Get repository status
status = git_tool.get_status("/path/to/repo")
```

## Best Practices

1. **Plugin Design**
   - Keep plugins focused and single-purpose
   - Implement proper cleanup in the `cleanup()` method
   - Use clear, descriptive names for capabilities
   - Document plugin functionality thoroughly

2. **Resource Management**
   - Initialize resources lazily
   - Clean up resources properly
   - Handle errors gracefully
   - Monitor plugin health

3. **Configuration**
   - Use JSON schema for configuration validation
   - Provide sensible defaults
   - Document configuration options
   - Validate configuration early

4. **Error Handling**
   - Catch and handle plugin-specific errors
   - Provide meaningful error messages
   - Fail gracefully when possible
   - Log errors appropriately

## Plugin Development Guidelines

1. **Naming Conventions**
   - Use descriptive, unique names
   - Follow Python naming conventions
   - Include plugin type in name (e.g., `AnalysisTool`, `StoragePlugin`)

2. **Documentation**
   - Document plugin purpose and functionality
   - Include usage examples
   - Document configuration options
   - List dependencies and requirements

3. **Testing**
   - Write unit tests for plugin functionality
   - Test initialization and cleanup
   - Test configuration validation
   - Test error handling

4. **Version Management**
   - Use semantic versioning
   - Document breaking changes
   - Maintain backwards compatibility when possible
   - Update dependencies appropriately

## Example Plugins

Check out these example plugins in the framework:

1. [Git Tool](https://github.com/bartvanspitaels99/multi-swarm/blob/main/src/multi_swarm/plugins/tools/development/git.py)
2. [Docker Tool](https://github.com/bartvanspitaels99/multi-swarm/blob/main/src/multi_swarm/plugins/tools/development/docker.py)
3. [File Storage Plugin](https://github.com/bartvanspitaels99/multi-swarm/blob/main/src/multi_swarm/plugins/storage/file.py) 