# CodeBuddy Plugin System

CodeBuddy Code supports a powerful plugin system that allows you to extend and customize the CLI's functionality. Through plugins, you can add new commands, skills, and hooks, creating a personalized development environment that fits your workflow.

## Core Concepts

### What is a Plugin?

A plugin is a reusable functionality package that can contain the following components:

- **Commands**: Slash commands that users can manually trigger
- **Skills**: Specialized capabilities that the AI automatically recognizes and invokes
- **Hooks**: Operations that automatically execute when specific events are triggered

### What is a Plugin Marketplace?

A plugin marketplace is a publishing and distribution channel for plugins. CodeBuddy supports multiple types of plugin marketplaces:

- **Local Directory Marketplace**: Load plugins from the local filesystem
- **GitHub Repository Marketplace**: Fetch plugins from GitHub repositories
- **HTTP/HTTPS Marketplace**: Fetch plugin manifests and packages from HTTP(S) servers

## Quick Start

There are three ways to manage plugins: **Team Configuration Auto-Installation**, **Interactive Interface**, and **Command-Line Subcommands**.

### Method 1: Team Configuration Auto-Installation (Recommended)

Teams can configure `extraKnownMarketplaces` and `enabledPlugins` in the project's `.codebuddy/settings.json` to enable automatic plugin installation and activation. When team members start CodeBuddy, the system automatically installs the plugin marketplaces and plugins specified in the configuration.

#### Configuration Example

Add the following configuration to `.codebuddy/settings.json`:

```json
{
  "extraKnownMarketplaces": {
    "team-marketplace": {
      "source": {
        "source": "github",
        "repo": "your-org/team-plugins-marketplace"
      }
    },
    "custom-marketplace": {
      "source": {
        "source": "git",
        "url": "https://git.example.com/plugins-marketplace"
      }
    }
  },
  "enabledPlugins": {
    "team-plugin-a@team-marketplace": true,
    "team-plugin-b@team-marketplace": true
  }
}
```

#### Configuration Explanation

- **`extraKnownMarketplaces`**: Define additional plugin marketplaces
  - Key is the marketplace name (e.g., `team-marketplace`)
  - `source.source`: Marketplace type, supports `github`, `git`, and `url`
  - `source.repo`: GitHub repository path (format: `owner/repo`, only when source is `github`)
  - `source.url`: Git repository URL or HTTP(S) marketplace.json URL (only when source is `git` or `url`)

- **`enabledPlugins`**: Specify plugins to enable
  - Key format: `plugin-name@marketplace-name`
  - Value `true` means enabled, `false` means disabled

#### Automatic Installation Flow

1. **Startup Detection**: CodeBuddy automatically detects the configuration file on startup
2. **Marketplace Installation**: Automatically installs marketplaces from `extraKnownMarketplaces` that are not yet installed
3. **Plugin Installation**: Automatically installs enabled plugins from `enabledPlugins` that are not yet installed
4. **Background Execution**: The installation process executes asynchronously in the background without blocking the startup flow
5. **Logging**: The installation process logs detailed information, viewable with `--debug`

#### Advantages

- **Team Consistency**: Ensures team members use the same plugin configuration
- **Automation**: No manual installation needed, improving development efficiency
- **Version Control**: Configuration files can be committed to Git for team collaboration
- **Flexible Override**: Individuals can override team configuration in their local configuration

### Method 2: Interactive Interface

Enter `/plugin` in CodeBuddy conversation to open the interactive plugin management interface.

#### Opening the Management Interface

```bash
/plugin
```

#### Interface Features

The interactive interface contains the following 6 tabs:

1. **Discover** - Browse all available plugins, view installation counts, descriptions, and more
   - Real-time plugin search
   - Display plugin installation statistics
   - Quick plugin installation

2. **Browse** - Browse and install plugins from configured marketplaces
   - Browse by marketplace category
   - View plugin details
   - Install plugins

3. **Installed** - Manage installed plugins
   - View installed plugin list and status
   - Enable/disable plugins
   - Uninstall plugins
   - View plugin details

4. **Marketplaces** - Manage plugin marketplaces
   - View configured marketplace list
   - Update marketplace information
   - Remove marketplaces

5. **Add Marketplace** - Add new plugin marketplace sources
   - Support local paths, GitHub repositories, Git URLs, and HTTP URLs
   - Automatic marketplace source type detection
   - Set marketplace display name

6. **Errors** - View errors that occurred during plugin loading and operations
   - Detailed error information and error types
   - Error timestamps and related context
   - Help diagnose and resolve issues

#### Interactive Command Examples

```bash
/plugin                                    # Open management interface
/plugin install my-plugin                  # Install plugin
/plugin install my-plugin@marketplace      # Install from specified marketplace
/plugin enable my-plugin                   # Enable disabled plugin
/plugin disable my-plugin                  # Disable enabled plugin
/plugin uninstall my-plugin                # Uninstall plugin
/plugin marketplace add <source>           # Add marketplace
/plugin marketplace list                   # List marketplaces
/plugin marketplace update <name>          # Update marketplace
/plugin marketplace remove <name>          # Remove marketplace
```

### Method 3: Command-Line Subcommands

Use the `codebuddy plugin` command in the terminal for management.

#### Plugin Operations

```bash
# Install plugin
codebuddy plugin install <plugin>              # Install from default marketplace
codebuddy plugin install <plugin>@<marketplace> # Install from specified marketplace
codebuddy plugin i <plugin>                    # Shorthand form

# Enable and disable plugins
codebuddy plugin enable <plugin>               # Enable plugin
codebuddy plugin disable <plugin>              # Disable plugin

# Uninstall plugin
codebuddy plugin uninstall <plugin>            # Uninstall plugin
codebuddy plugin remove <plugin>               # Alias form

# Validate plugin or marketplace manifest
codebuddy plugin validate <path>               # Validate local plugin or marketplace
```

#### Marketplace Management

```bash
# Add marketplace
codebuddy plugin marketplace add <source>
codebuddy plugin marketplace add <source> -n <name>   # Specify marketplace name

# List marketplaces
codebuddy plugin marketplace list

# Update marketplace
codebuddy plugin marketplace update <name>

# Remove marketplace
codebuddy plugin marketplace remove <name>
codebuddy plugin marketplace rm <name>                # Alias form
```

## Plugin Management

### Adding a Plugin Marketplace

#### Using the Interactive Interface

1. Enter `/plugin`
2. Select "3. Add marketplace"
3. Enter the marketplace source address
4. Wait for automatic marketplace type recognition and plugin manifest loading

#### Using Subcommands

```bash
# Add GitHub repository marketplace
codebuddy plugin marketplace add https://github.com/username/plugin-repo

# Add marketplace and specify display name
codebuddy plugin marketplace add https://github.com/username/plugin-repo -n my-marketplace

# Add local directory marketplace
codebuddy plugin marketplace add /path/to/local/plugins

# Add HTTP marketplace
codebuddy plugin marketplace add https://example.com/plugins
```

**Parameter Explanation**:
- `<source>`: Marketplace source address (local path, GitHub URL, or HTTP(S) URL)
- `-n, --name <name>`: Optional, specify a display name for the marketplace

### Installing Plugins

#### Using the Interactive Interface

1. Enter `/plugin`
2. Select "1. Browse and install plugins"
3. Select the plugin marketplace
4. Browse available plugins and select to install

#### Using Subcommands

```bash
# Install from default marketplace
codebuddy plugin install my-plugin

# Install from specified marketplace
codebuddy plugin install my-plugin@marketplace-name

# Using alias
codebuddy plugin i my-plugin
```

### Enabling and Disabling Plugins

#### Using the Interactive Interface

1. Enter `/plugin`
2. Select "2. Manage plugins"
3. Select the plugin to enable or disable

#### Using Subcommands

```bash
# Enable plugin
codebuddy plugin enable my-plugin

# Disable plugin
codebuddy plugin disable my-plugin
```

**Note**: CodeBuddy must be restarted after enabling/disabling plugins for changes to take effect.

### Uninstalling Plugins

#### Using the Interactive Interface

1. Enter `/plugin`
2. Select "2. Manage plugins"
3. Select the plugin to uninstall and confirm uninstallation

#### Using Subcommands

```bash
# Uninstall plugin
codebuddy plugin uninstall my-plugin

# Using alias
codebuddy plugin remove my-plugin
```

### Managing Plugin Marketplaces

#### List Marketplaces

Using the interactive interface:
1. Enter `/plugin`
2. Select "4. Manage marketplaces"

Using subcommands:
```bash
codebuddy plugin marketplace list
```

#### Update Marketplace

Using the interactive interface:
1. Enter `/plugin`
2. Select "4. Manage marketplaces"
3. Select the marketplace to update

Using subcommands:
```bash
codebuddy plugin marketplace update my-marketplace
```

#### Remove Marketplace

Using the interactive interface:
1. Enter `/plugin`
2. Select "4. Manage marketplaces"
3. Select the marketplace to remove and confirm removal

Using subcommands:
```bash
codebuddy plugin marketplace remove my-marketplace
codebuddy plugin marketplace rm my-marketplace
```

### Validating Plugin or Marketplace Manifests

```bash
# Validate plugin manifest format
codebuddy plugin validate /path/to/plugin

# Validate marketplace manifest format
codebuddy plugin validate /path/to/marketplace

# Validate plugin manifest from GitHub
codebuddy plugin validate https://github.com/username/plugin-repo
```

The validate command checks the format and completeness of `plugin.json` or `marketplace.json`.

## Plugin Structure

### Standard Plugin Directory Structure

```
my-plugin/
├── .codebuddy-plugin/     # Metadata directory (required)
│   └── plugin.json        # Plugin manifest file
├── commands/              # Commands directory (optional)
│   └── example.md
├── agents/                # Agents directory (optional)
│   └── example.md
├── skills/                # Skills directory (optional)
│   └── example/
│       └── SKILL.md
├── hooks/                 # Hooks directory (optional)
│   └── hooks.json
├── .mcp.json              # MCP configuration file (optional)
└── .lsp.json              # LSP configuration file (optional)
```

### plugin.json Format

The plugin manifest file defines the plugin's metadata and included components, located at `.codebuddy-plugin/plugin.json`:

```json
{
  "name": "my-plugin",
  "version": "1.0.0",
  "description": "Plugin description",
  "author": {
    "name": "Author Name",
    "email": "author@example.com"
  },
  "homepage": "https://github.com/username/my-plugin",
  "repository": "https://github.com/username/my-plugin",
  "keywords": ["example"],
  "category": "Development Tools",
  "commands": [],
  "agents": [],
  "skills": [],
  "hooks": "./hooks/hooks.json"
}
```

### Commands

Plugins can provide custom slash commands that users can manually trigger. Commands are defined as Markdown files.

**Example**: `commands/example.md`

```markdown

This is an example command. It executes when the user enters /my-plugin:example.

Argument: $1
```

Commands are registered in the format `/plugin-name:command-name`.

For detailed information, refer to: [Slash Commands Documentation](slash-commands.md)

### Skills

Skills are specialized capability templates that the AI can automatically recognize and invoke.

**Example**: `skills/SKILL.md`

```markdown
---
description: "Skill description"
---

Detailed skill description and usage scenarios...
```

For detailed information, refer to: [Skills Documentation](skills.md)

### Hooks

Hooks allow automatic execution of operations when specific events occur.

**Example**: `hooks/hooks.json`

```json
{
  "hooks": {
    "user-prompt-submit-hook": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "echo 'User submitted: $INPUT'",
            "timeout": 5000
          }
        ]
      }
    ]
  }
}
```

For detailed information, refer to: [Hooks Documentation](hooks.md)

### LSP (Language Server Protocol)

LSP plugins provide real-time code intelligence for the AI, enabling it to understand code structure, type definitions, function signatures, and more.

#### Usage Recommendations

For common languages (such as TypeScript, Python, Rust, etc.), it's recommended to install pre-built LSP plugins directly from the official plugin marketplace. You only need to create custom LSP plugins when supporting languages not yet covered.

#### Configuring LSP Servers

Configure LSP servers by adding a `.lsp.json` file to the plugin root directory:

**Example**: `.lsp.json`

```json
{
  "go": {
    "command": "gopls",
    "args": ["serve"],
    "extensionToLanguage": {
      ".go": "go"
    }
  }
}
```

#### Configuration Field Descriptions

- **Language Identifier** (e.g., `"go"`): Defines the language supported by the LSP server
  - `command`: The command name of the LSP server executable
  - `args`: Array of arguments passed to the command
  - `extensionToLanguage`: Mapping of file extensions to language identifiers

#### Multi-Language Configuration Example

```json
{
  "python": {
    "command": "pylsp",
    "args": [],
    "extensionToLanguage": {
      ".py": "python"
    }
  },
  "rust": {
    "command": "rust-analyzer",
    "args": [],
    "extensionToLanguage": {
      ".rs": "rust"
    }
  }
}
```

#### Installation Requirements

When installing plugins that include LSP configurations, users must have the corresponding language server binaries pre-installed on their system. For example:

- **Go**: Requires `gopls` (`go install golang.org/x/tools/gopls@latest`)
- **Python**: Requires `python-lsp-server` (`pip install python-lsp-server`)
- **Rust**: Requires `rust-analyzer` (`rustup component add rust-analyzer`)

#### How It Works

1. CodeBuddy reads the `.lsp.json` configuration on startup
2. Automatically starts the corresponding LSP server based on file extensions
3. AI obtains code intelligence information via the LSP protocol
4. Provides more accurate code suggestions and modifications

#### Best Practices

1. **Provide Installation Instructions**: Clearly document the required language servers in the plugin's README
2. **Version Compatibility**: Document the supported language server version range
3. **Use Official Plugins**: Prefer officially maintained LSP plugins to avoid duplicate work
4. **Thorough Testing**: Ensure LSP configurations work correctly across different operating systems

## Plugin Marketplace Types

### GitHub Marketplace

Publish and fetch plugins from GitHub repositories.

**Repository Structure**:

```
plugin-repo/
├── .codebuddy-plugin/
│   └── marketplace.json       # Marketplace manifest
└── plugins/
    ├── plugin1/
    │   ├── .codebuddy-plugin/
    │   │   └── plugin.json
    │   └── ...
    └── plugin2/
        ├── .codebuddy-plugin/
        │   └── plugin.json
        └── ...
```

**marketplace.json** Format:

```json
{
  "name": "My Plugin Marketplace",
  "plugins": [
    {
      "name": "plugin1",
      "source": "plugins/plugin1",
      "description": "Plugin 1 description"
    },
    {
      "name": "plugin2",
      "source": "plugins/plugin2",
      "description": "Plugin 2 description"
    }
  ]
}
```

### HTTP Marketplace

Provide plugins through HTTP(S) servers.

**Server Requirements**:

- Provide `/marketplace.json` - Marketplace manifest
- Provide `/plugins/<plugin-name>/plugin.json` - Plugin manifest
- Provide plugin file downloads

### Local Directory Marketplace

Load plugins from the local filesystem, suitable for development and testing.

**Directory Structure**:

```
local-plugins/
├── .codebuddy-plugin/
│   └── marketplace.json
└── plugins/
    └── my-plugin/
        ├── .codebuddy-plugin/
        │   └── plugin.json
        └── ...
```

## Best Practices

### Plugin Development Recommendations

1. **Follow Naming Conventions**: Use clear, descriptive plugin names
2. **Provide Complete Metadata**: Provide detailed descriptions and author information in `plugin.json`
3. **Version Management**: Use semantic versioning (Semantic Versioning)
4. **Complete Documentation**: Provide clear descriptions for each command and skill
5. **Thorough Testing**: Test plugins in local marketplace before publishing

### Security Considerations

1. **Only Install Plugins from Trusted Sources**: Plugins can execute commands and access the filesystem
2. **Review Plugin Code**: Check plugin commands and hooks before installation
3. **Use Permission Controls**: Limit plugin access through CodeBuddy's permission system

### Plugin Publishing Workflow

1. Create plugin directory and files
2. Write `plugin.json`
3. Test plugin in local marketplace
4. Create GitHub repository or HTTP server
5. Add `marketplace.json`
6. Share marketplace address with users

## Troubleshooting

### Marketplace Not Loading

**Problem**: Unable to add marketplace or can't see plugins from it

**Solution**:

* Verify marketplace URL is accessible
* Check if `.codebuddy-plugin/marketplace.json` exists at the specified path
* Use `codebuddy plugin validate` to ensure JSON syntax is valid
* For private repositories, confirm you have access permissions

#### Plugin Installation Failed

**Problem**: Marketplace appears but plugin installation fails

**Solution**:

* Verify plugin source URL is accessible
* Check if plugin directory contains required files
* For GitHub sources, ensure repository is public or you have access permissions
* Test plugin source by manually cloning/downloading

### Plugin Not Loading

**Problem**: Plugin is installed but not working

**Solution**:

* Confirm plugin is enabled: `/plugin` → "3. Installed"
* Check that `plugin.json` format is correct
* Restart CodeBuddy to load new plugins
* Use `--debug` mode to view loading logs

### Command Not Available

**Problem**: Plugin is installed but commands are unavailable

**Solution**:

* Confirm command path is correctly configured in `plugin.json`
* Check that command file exists
* Verify command file format follows Markdown specifications

### Marketplace Connection Failed

**Problem**: Unable to connect to marketplace or fetch plugin list

**Solution**:

* **GitHub marketplace**: Check network connection and repository access permissions
* **HTTP marketplace**: Confirm server is accessible
* **Local marketplace**: Verify directory path and permissions

### Validation and Testing

Test your marketplace and plugins before sharing:

```bash
# Validate marketplace JSON syntax
codebuddy plugin validate .

# Validate specific plugin
codebuddy plugin validate /path/to/plugin

# Add local marketplace for testing
codebuddy plugin marketplace add ./path/to/marketplace

# Test plugin installation
codebuddy plugin install test-plugin@marketplace-name
```

## Related Documentation

- **[Plugin Reference Documentation](plugins-reference.md)** - Complete technical specification for plugin development
- **[Slash Commands](slash-commands.md)** - Learn about the command system
- **[Skills](skills.md)** - Learn about the skills system
- **[Hooks](hooks.md)** - Master the hooks mechanism

---

*Make CodeBuddy more powerful through the plugin system 🚀*
