nanocoder icon indicating copy to clipboard operation
nanocoder copied to clipboard

Feature Request: Plugin System & Marketplace for Extensible Capabilities

Open Avtrkrb opened this issue 1 year ago • 3 comments

Overview

Implement a comprehensive plugin system and marketplace similar to Claude Code that enables users to install, manage, and distribute extensions. Plugins would extend nanocoder through custom commands, agents, skills, MCP server configurations, and lifecycle hooks, creating a thriving ecosystem of community-built extensions.

Goals

  • Add robust plugin system for extending nanocoder capabilities
  • Implement marketplace functionality for plugin discovery and distribution
  • Support multiple plugin extension points (commands, agents, skills, hooks, MCP)
  • Provide secure plugin execution with sandboxing and permissions
  • Enable team-based plugin distribution and management
  • Create plugin development SDK and documentation

Current State Analysis

Existing Architecture Strengths:

  • Sophisticated CommandRegistry with fuzzy matching (source/commands.ts)
  • Extensible ToolManager and ToolRegistry system (source/tools/tool-manager.ts)
  • MCP integration for dynamic server loading (source/mcp/mcp-client.ts)
  • Directory trust system for security (source/hooks/useDirectoryTrust.tsx)
  • React-based UI with component architecture (source/components/)
  • Configuration system with environment variable support (source/config/)

Current Limitations:

  • No dynamic extension system beyond custom commands
  • No marketplace for discovering and sharing extensions
  • Limited plugin lifecycle management
  • No sandboxing or security model for third-party code
  • No dependency resolution or version management

Proposed Solution

Architecture

Plugin System Architecture:

┌─────────────────────────────────────────────────────────────┐
│                    Plugin Registry                           │
│  - Plugin Discovery & Installation                          │
│  - Dependency Resolution                                    │
│  - Version Management                                       │
│  - Security Validation                                      │
└──────────────────┬──────────────────────────────────────────┘
                   │
        ┌──────────▼───────────┐
        │   Plugin Manager     │
        ├──────────────────────┤
        │ • Lifecycle Hooks    │
        │ • Sandbox Manager    │
        │ • Permission System  │
        │ • Resource Loader    │
        └──────────────────────┘
                   │
        ┌──────────▼───────────┐
        │   Plugin Types       │
        ├──────────────────────┤
        │ • Commands           │
        │ • Agents             │
        │ • Skills             │
        │ • MCP Configs        │
        │ • Lifecycle Hooks    │
        └──────────────────────┘
                   │
        ┌──────────▼───────────┐
        │  Marketplace         │
        ├──────────────────────┤
        │ • Plugin Discovery   │
        │ • GitHub Integration │
        │ • Team Marketplaces  │
        │ • Update Management  │
        └──────────────────────┘

Implementation Tasks

Phase 1: Plugin Infrastructure

File: source/types/plugin.ts

Define plugin interfaces and types:

export interface Plugin {
    id: string;
    manifest: PluginManifest;
    location: string;
    status: PluginStatus;
    dependencies?: PluginDependency[];
    conflicts?: string[]; // Plugin IDs that conflict
    permissions: PluginPermission[];
    resources: PluginResource[];
    
    // Loaded components
    commands?: LoadedCommand[];
    agents?: LoadedAgent[];
    skills?: LoadedSkill[];
    mcpServers?: MCPServer[];
    hooks?: PluginHooks;
    
    // Runtime state
    enabled: boolean;
    loadedAt?: Date;
    lastUsed?: Date;
}

export interface PluginManifest {
    name: string;
    version: string;
    description: string;
    author: {
        name: string;
        email?: string;
        url?: string;
    };
    license: string;
    homepage?: string;
    repository?: {
        type: 'git';
        url: string;
    };
    keywords: string[];
    categories: string[];
    
    // Plugin requirements
    nanocoderVersion: string; // SemVer range
    engines?: Record<string, string>; // Node.js, etc.
    
    // Extension points
    commands?: PluginCommandManifest[];
    agents?: PluginAgentManifest[];
    skills?: PluginSkillManifest[];
    mcpServers?: MCPServer[];
    hooks?: PluginHookManifest;
    
    // Metadata
    icon?: string; // Base64 or URL
    screenshots?: string[];
    changelogUrl?: string;
    bugs?: {
        url: string;
        email?: string;
    };
    
    // Security
    permissions: PluginPermission[];
    signed?: boolean; // For plugin signing
}

export interface PluginCommandManifest {
    name: string;
    description: string;
    path: string; // Path to command file
    aliases?: string[];
    category?: string;
    hidden?: boolean;
    permissions?: PluginPermission[];
}

export interface PluginAgentManifest {
    name: string;
    description: string;
    path: string; // Path to agent file
    systemPrompt?: string;
    tools?: string[]; // Tool restrictions
    permissions?: PluginPermission[];
}

export interface PluginSkillManifest {
    name: string;
    path: string; // Path to skill directory
    enabled: boolean;
}

export interface PluginHookManifest {
    [hookType: string]: string[]; // Hook type -> array of script paths
}

export interface PluginPermission {
    type: 'filesystem' | 'network' | 'system' | 'tools' | 'process';
    scope: string; // Specific permission scope
    reason?: string; // Why this permission is needed
}

export interface PluginDependency {
    name: string;
    version: string; // SemVer range
    optional: boolean;
    reason?: string;
}

export interface PluginResource {
    name: string;
    path: string;
    type: 'script' | 'template' | 'static' | 'config';
    executable?: boolean;
    public?: boolean; // Whether accessible to other plugins
}

export enum PluginStatus {
    INSTALLED = 'installed',
    ENABLED = 'enabled',
    DISABLED = 'disabled',
    ERROR = 'error',
    LOADING = 'loading',
    UPDATING = 'updating',
}

export interface PluginSource {
    type: 'github' | 'git' | 'local' | 'npm' | 'marketplace';
    location: string;
    ref?: string; // Git ref, npm version, etc.
    trusted?: boolean;
}

export interface MarketplaceSource {
    name: string;
    url?: string;
    owner: {
        name: string;
        email?: string;
        url?: string;
    };
    plugins: MarketplacePlugin[];
}

export interface MarketplacePlugin {
    name: string;
    source: PluginSource;
    description: string;
    version: string;
    author: {
        name: string;
        email?: string;
    };
    tags?: string[];
    downloads?: number;
    rating?: number;
    verified?: boolean;
    lastUpdated?: string;
}

Phase 2: Plugin Manager

File: source/plugins/plugin-manager.ts

Core plugin management system:

export class PluginManager {
    private plugins: Map<string, Plugin> = new Map();
    private registry: Map<string, PluginSource> = new Map();
    private sandbox: PluginSandbox;
    private permissionManager: PluginPermissionManager;
    private dependencyResolver: PluginDependencyResolver;

    constructor(
        private toolManager: ToolManager,
        private commandRegistry: CommandRegistry,
        private skillManager: SkillManager
    ) {
        this.sandbox = new PluginSandbox();
        this.permissionManager = new PluginPermissionManager();
        this.dependencyResolver = new PluginDependencyResolver();
    }

    async initialize(): Promise<void> {
        await this.loadInstalledPlugins();
        await this.initializeDefaultMarketplaces();
    }

    async installPlugin(source: PluginSource, options?: InstallOptions): Promise<Plugin> {
        // Validate source and permissions
        await this.validatePluginSource(source);
        
        // Download plugin
        const pluginPath = await this.downloadPlugin(source, options);
        
        // Parse manifest
        const manifest = await this.parsePluginManifest(pluginPath);
        
        // Check dependencies
        await this.dependencyResolver.resolveDependencies(manifest);
        
        // Validate permissions
        await this.permissionManager.validatePermissions(manifest);
        
        // Install plugin
        const plugin = await this.installPluginFromPath(pluginPath, manifest, source);
        
        // Register plugin components
        await this.registerPluginComponents(plugin);
        
        this.plugins.set(plugin.id, plugin);
        
        return plugin;
    }

    async enablePlugin(pluginId: string): Promise<void> {
        const plugin = this.plugins.get(pluginId);
        if (!plugin) {
            throw new Error(`Plugin ${pluginId} not found`);
        }

        if (plugin.enabled) {
            return; // Already enabled
        }

        try {
            // Check dependencies
            await this.dependencyResolver.checkDependencies(plugin);
            
            // Enable in sandbox
            await this.sandbox.enablePlugin(plugin);
            
            // Register components
            await this.registerPluginComponents(plugin);
            
            // Enable hooks
            if (plugin.hooks) {
                await this.registerPluginHooks(plugin);
            }
            
            plugin.enabled = true;
            plugin.status = PluginStatus.ENABLED;
            
        } catch (error) {
            plugin.status = PluginStatus.ERROR;
            throw new Error(`Failed to enable plugin ${pluginId}: ${error.message}`);
        }
    }

    async disablePlugin(pluginId: string): Promise<void> {
        const plugin = this.plugins.get(pluginId);
        if (!plugin) {
            throw new Error(`Plugin ${pluginId} not found`);
        }

        if (!plugin.enabled) {
            return; // Already disabled
        }

        try {
            // Unregister hooks
            if (plugin.hooks) {
                await this.unregisterPluginHooks(plugin);
            }
            
            // Unregister components
            await this.unregisterPluginComponents(plugin);
            
            // Disable in sandbox
            await this.sandbox.disablePlugin(plugin);
            
            plugin.enabled = false;
            plugin.status = PluginStatus.DISABLED;
            
        } catch (error) {
            plugin.status = PluginStatus.ERROR;
            throw new Error(`Failed to disable plugin ${pluginId}: ${error.message}`);
        }
    }

    async uninstallPlugin(pluginId: string): Promise<void> {
        const plugin = this.plugins.get(pluginId);
        if (!plugin) {
            throw new Error(`Plugin ${pluginId} not found`);
        }

        // Disable first
        if (plugin.enabled) {
            await this.disablePlugin(pluginId);
        }

        // Check for dependents
        const dependents = this.findDependentPlugins(pluginId);
        if (dependents.length > 0) {
            throw new Error(`Cannot uninstall ${pluginId}: required by ${dependents.join(', ')}`);
        }

        try {
            // Remove files
            await fs.remove(plugin.location);
            
            // Remove from registry
            this.plugins.delete(pluginId);
            this.registry.delete(pluginId);
            
        } catch (error) {
            throw new Error(`Failed to uninstall plugin ${pluginId}: ${error.message}`);
        }
    }

    private async registerPluginComponents(plugin: Plugin): Promise<void> {
        // Register commands
        if (plugin.commands) {
            for (const command of plugin.commands) {
                await this.registerPluginCommand(plugin, command);
            }
        }

        // Register agents
        if (plugin.agents) {
            for (const agent of plugin.agents) {
                await this.registerPluginAgent(plugin, agent);
            }
        }

        // Register skills
        if (plugin.skills) {
            for (const skill of plugin.skills) {
                await this.registerPluginSkill(plugin, skill);
            }
        }

        // Register MCP servers
        if (plugin.mcpServers) {
            for (const mcpServer of plugin.mcpServers) {
                await this.registerPluginMCPServer(plugin, mcpServer);
            }
        }
    }

    private async registerPluginCommand(plugin: Plugin, command: PluginCommandManifest): Promise<void> {
        const commandPath = path.join(plugin.location, command.path);
        
        if (!await fs.pathExists(commandPath)) {
            throw new Error(`Command file not found: ${commandPath}`);
        }

        // Load command in sandbox
        const commandHandler = await this.sandbox.loadCommand(plugin, commandPath);
        
        // Register with command registry
        this.commandRegistry.register({
            name: command.name,
            description: command.description,
            aliases: command.aliases,
            category: command.category,
            pluginId: plugin.id,
            execute: commandHandler,
        });
    }

    private async registerPluginAgent(plugin: Plugin, agent: PluginAgentManifest): Promise<void> {
        const agentPath = path.join(plugin.location, agent.path);
        
        // Load agent in sandbox
        const agentConfig = await this.sandbox.loadAgent(plugin, agentPath);
        
        // Register with tool manager (would need extension)
        // this.toolManager.registerAgent(agent.name, agentConfig);
    }

    private async registerPluginSkill(plugin: Plugin, skill: PluginSkillManifest): Promise<void> {
        const skillPath = path.join(plugin.location, skill.path);
        
        // Register with skill manager
        await this.skillManager.registerSkillSource({
            type: 'plugin',
            location: skillPath,
            priority: 10,
            enabled: skill.enabled,
        });
    }

    private async registerPluginMCPServer(plugin: Plugin, mcpServer: MCPServer): Promise<void> {
        // Register MCP server with tool manager
        await this.toolManager.addMCPServer(mcpServer);
    }

    private async registerPluginHooks(plugin: Plugin): Promise<void> {
        if (!plugin.hooks) return;

        for (const [hookType, hookPaths] of Object.entries(plugin.hooks)) {
            for (const hookPath of hookPaths) {
                const fullPath = path.join(plugin.location, hookPath);
                const hookHandler = await this.sandbox.loadHook(plugin, fullPath);
                
                // Register hook with global hook system
                HookRegistry.register(hookType as HookType, hookHandler);
            }
        }
    }

    getInstalledPlugins(): Plugin[] {
        return Array.from(this.plugins.values());
    }

    getPlugin(pluginId: string): Plugin | undefined {
        return this.plugins.get(pluginId);
    }
}

Phase 3: Plugin Sandbox

File: source/plugins/plugin-sandbox.ts

Secure plugin execution environment:

export class PluginSandbox {
    private sandboxes: Map<string, PluginSandboxInstance> = new Map();
    private basePermissions: string[];

    constructor() {
        this.basePermissions = this.getBasePermissions();
    }

    async enablePlugin(plugin: Plugin): Promise<void> {
        const sandbox = new PluginSandboxInstance(plugin, this.basePermissions);
        await sandbox.initialize();
        
        this.sandboxes.set(plugin.id, sandbox);
    }

    async disablePlugin(plugin: Plugin): Promise<void> {
        const sandbox = this.sandboxes.get(plugin.id);
        if (sandbox) {
            await sandbox.cleanup();
            this.sandboxes.delete(plugin.id);
        }
    }

    async loadCommand(plugin: Plugin, commandPath: string): Promise<CommandHandler> {
        const sandbox = this.sandboxes.get(plugin.id);
        if (!sandbox) {
            throw new Error(`Plugin ${plugin.id} not enabled`);
        }

        return sandbox.loadCommand(commandPath);
    }

    async loadAgent(plugin: Plugin, agentPath: string): Promise<any> {
        const sandbox = this.sandboxes.get(plugin.id);
        if (!sandbox) {
            throw new Error(`Plugin ${plugin.id} not enabled`);
        }

        return sandbox.loadAgent(agentPath);
    }

    async loadHook(plugin: Plugin, hookPath: string): Promise<HookHandler> {
        const sandbox = this.sandboxes.get(plugin.id);
        if (!sandbox) {
            throw new Error(`Plugin ${plugin.id} not enabled`);
        }

        return sandbox.loadHook(hookPath);
    }

    private getBasePermissions(): string[] {
        return [
            'read_own_files',
            'write_own_files',
            'network_outbound',
            'execute_own_scripts',
        ];
    }
}

class PluginSandboxInstance {
    private vm?: NodeVM;
    private allowedPaths: string[] = [];
    private networkRules: NetworkRule[] = [];

    constructor(
        private plugin: Plugin,
        private basePermissions: string[]
    ) {
        this.configurePermissions();
    }

    async initialize(): Promise<void> {
        // Create isolated VM context
        this.vm = new NodeVM({
            console: 'inherit',
            sandbox: this.createSandboxContext(),
            require: {
                external: this.getAllowedModules(),
                builtin: this.getAllowedBuiltins(),
                root: this.plugin.location,
            },
        });

        // Set up file system restrictions
        await this.setupFilesystemRestrictions();
        
        // Set up network restrictions
        await this.setupNetworkRestrictions();
    }

    async loadCommand(commandPath: string): Promise<CommandHandler> {
        const commandCode = await fs.readFile(commandPath, 'utf-8');
        
        return async (context, args) => {
            try {
                const commandModule = this.vm!.run(commandCode, commandPath);
                
                if (typeof commandModule.execute === 'function') {
                    return await commandModule.execute(context, args);
                } else if (typeof commandModule === 'function') {
                    return await commandModule(context, args);
                } else {
                    throw new Error('Invalid command format');
                }
            } catch (error) {
                throw new Error(`Plugin command execution failed: ${error.message}`);
            }
        };
    }

    private createSandboxContext(): any {
        return {
            // Plugin API
            plugin: {
                id: this.plugin.id,
                version: this.plugin.manifest.version,
                location: this.plugin.location,
            },
            
            // Safe Node.js APIs
            console,
            setTimeout,
            clearTimeout,
            setInterval,
            clearInterval,
            
            // Nanocoder APIs (limited)
            nanocoder: {
                log: console.log,
                error: console.error,
                warn: console.warn,
            },
        };
    }

    private configurePermissions(): void {
        for (const permission of this.plugin.permissions) {
            switch (permission.type) {
                case 'filesystem':
                    this.allowedPaths.push(permission.scope);
                    break;
                case 'network':
                    this.networkRules.push({
                        type: 'allow',
                        pattern: permission.scope,
                    });
                    break;
            }
        }
    }

    private getAllowedModules(): string[] {
        // Whitelist of safe external modules
        return [
            'lodash',
            'moment',
            'axios',
            'chalk',
            'inquirer',
            'yaml',
            'semver',
        ];
    }

    private getAllowedBuiltins(): string[] {
        // Whitelist of safe Node.js builtins
        return [
            'fs',
            'path',
            'url',
            'querystring',
            'util',
            'events',
            'stream',
            'buffer',
            'crypto',
            'os',
        ];
    }
}

Phase 4: Marketplace Integration

File: source/plugins/marketplace/marketplace-client.ts

Plugin marketplace functionality:

export class MarketplaceClient {
    private marketplaces: Map<string, MarketplaceSource> = new Map();
    private cache: Map<string, MarketplacePlugin[]> = new Map();

    constructor(
        private pluginManager: PluginManager
    ) {
        this.initializeDefaultMarketplaces();
    }

    private async initializeDefaultMarketplaces(): Promise<void> {
        // Official nanocoder marketplace
        await this.addMarketplace({
            name: 'official',
            owner: {
                name: 'Nano Collective',
                url: 'https://github.com/nano-collective',
            },
            url: 'https://api.github.com/repos/nano-collective/nanocoder-marketplace/contents',
        });
    }

    async addMarketplace(source: MarketplaceSource): Promise<void> {
        try {
            const plugins = await this.fetchMarketplacePlugins(source);
            source.plugins = plugins;
            this.marketplaces.set(source.name, source);
        } catch (error) {
            throw new Error(`Failed to add marketplace ${source.name}: ${error.message}`);
        }
    }

    async searchPlugins(query: string, options?: SearchOptions): Promise<MarketplacePlugin[]> {
        const results: MarketplacePlugin[] = [];
        
        for (const [marketplaceName, marketplace] of this.marketplaces) {
            const marketResults = marketplace.plugins.filter(plugin => 
                this.matchesQuery(plugin, query)
            );
            results.push(...marketResults);
        }

        // Sort by relevance
        return results.sort((a, b) => {
            const scoreA = this.calculateRelevanceScore(a, query);
            const scoreB = this.calculateRelevanceScore(b, query);
            return scoreB - scoreA;
        });
    }

    async installFromMarketplace(pluginName: string, marketplaceName?: string): Promise<Plugin> {
        const plugin = await this.findMarketplacePlugin(pluginName, marketplaceName);
        
        if (!plugin) {
            throw new Error(`Plugin ${pluginName} not found in marketplace`);
        }

        // Convert marketplace plugin to plugin source
        const source: PluginSource = {
            type: plugin.source.type,
            location: plugin.source.location,
            ref: plugin.source.ref,
            trusted: plugin.verified || false,
        };

        return this.pluginManager.installPlugin(source);
    }

    async getPluginUpdates(installedPlugins: Plugin[]): Promise<PluginUpdate[]> {
        const updates: PluginUpdate[] = [];
        
        for (const plugin of installedPlugins) {
            try {
                const latestVersion = await this.getLatestVersion(plugin.id);
                
                if (latestVersion && semver.gt(latestVersion, plugin.manifest.version)) {
                    updates.push({
                        pluginId: plugin.id,
                        currentVersion: plugin.manifest.version,
                        latestVersion,
                        changelog: await this.getChangelog(plugin.id, plugin.manifest.version, latestVersion),
                    });
                }
            } catch (error) {
                console.warn(`Failed to check updates for ${plugin.id}:`, error);
            }
        }
        
        return updates;
    }

    async updatePlugin(pluginId: string): Promise<Plugin> {
        const plugin = this.pluginManager.getPlugin(pluginId);
        
        if (!plugin) {
            throw new Error(`Plugin ${pluginId} not installed`);
        }

        // Get source from registry
        const source = this.pluginManager.getPluginSource(pluginId);
        if (!source) {
            throw new Error(`No source found for plugin ${pluginId}`);
        }

        // Disable current version
        await this.pluginManager.disablePlugin(pluginId);
        
        try {
            // Install new version
            const newPlugin = await this.pluginManager.installPlugin(source, { force: true });
            
            // Remove old version
            await this.pluginManager.uninstallPlugin(pluginId);
            
            return newPlugin;
            
        } catch (error) {
            // Re-enable old version if update fails
            await this.pluginManager.enablePlugin(pluginId);
            throw error;
        }
    }

    private async fetchMarketplacePlugins(marketplace: MarketplaceSource): Promise<MarketplacePlugin[]> {
        if (!marketplace.url) {
            return [];
        }

        try {
            const response = await fetch(marketplace.url, {
                headers: {
                    'Accept': 'application/vnd.github.v3+json',
                    'User-Agent': 'nanocoder-marketplace-client',
                },
            });

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${response.statusText}`);
            }

            const data = await response.json();
            
            if (Array.isArray(data)) {
                return data.map(item => this.parseMarketplacePlugin(item));
            } else if (data.files) {
                // GitHub directory listing
                const pluginFiles = data.files.filter((file: any) => 
                    file.name.endsWith('.json') && file.type === 'file'
                );
                
                const plugins: MarketplacePlugin[] = [];
                
                for (const file of pluginFiles) {
                    const pluginData = await fetch(file.download_url);
                    const pluginJson = await pluginData.json();
                    plugins.push(this.parseMarketplacePlugin(pluginJson));
                }
                
                return plugins;
            }
            
            return [];
            
        } catch (error) {
            console.warn(`Failed to fetch marketplace plugins:`, error);
            return [];
        }
    }

    private parseMarketplacePlugin(data: any): MarketplacePlugin {
        return {
            name: data.name,
            source: data.source,
            description: data.description,
            version: data.version,
            author: data.author,
            tags: data.tags || [],
            downloads: data.downloads,
            rating: data.rating,
            verified: data.verified,
            lastUpdated: data.lastUpdated,
        };
    }

    private matchesQuery(plugin: MarketplacePlugin, query: string): boolean {
        const queryLower = query.toLowerCase();
        
        return (
            plugin.name.toLowerCase().includes(queryLower) ||
            plugin.description.toLowerCase().includes(queryLower) ||
            plugin.author.name.toLowerCase().includes(queryLower) ||
            plugin.tags?.some(tag => tag.toLowerCase().includes(queryLower))
        );
    }

    private calculateRelevanceScore(plugin: MarketplacePlugin, query: string): number {
        let score = 0;
        const queryLower = query.toLowerCase();

        // Exact name match
        if (plugin.name.toLowerCase() === queryLower) score += 100;
        // Name starts with query
        else if (plugin.name.toLowerCase().startsWith(queryLower)) score += 50;
        // Name contains query
        else if (plugin.name.toLowerCase().includes(queryLower)) score += 25;

        // Description match
        if (plugin.description.toLowerCase().includes(queryLower)) score += 10;

        // Tag matches
        if (plugin.tags) {
            for (const tag of plugin.tags) {
                if (tag.toLowerCase().includes(queryLower)) score += 15;
            }
        }

        // Verified plugins get bonus
        if (plugin.verified) score += 5;

        // Popular plugins get bonus
        if (plugin.downloads) {
            score += Math.min(Math.log10(plugin.downloads), 10);
        }

        return score;
    }
}

Phase 5: Plugin Commands

File: source/commands/plugins.tsx

Plugin management commands:

export const PluginsCommand: Command = {
    name: '/plugins',
    description: 'Manage nanocoder plugins and marketplace',
    execute: async (context, args) => {
        const pluginManager = context.toolManager.getPluginManager();
        const marketplaceClient = context.toolManager.getMarketplaceClient();
        
        if (args.length === 0) {
            return listInstalledPlugins(pluginManager);
        } else if (args[0] === 'list') {
            return listInstalledPlugins(pluginManager, args.slice(1));
        } else if (args[0] === 'search') {
            return searchMarketplacePlugins(marketplaceClient, args.slice(1));
        } else if (args[0] === 'install') {
            return installPlugin(pluginManager, marketplaceClient, args.slice(1));
        } else if (args[0] === 'uninstall') {
            return uninstallPlugin(pluginManager, args[1]);
        } else if (args[0] === 'enable') {
            return enablePlugin(pluginManager, args[1]);
        } else if (args[0] === 'disable') {
            return disablePlugin(pluginManager, args[1]);
        } else if (args[0] === 'update') {
            return updatePlugins(pluginManager, marketplaceClient, args.slice(1));
        } else if (args[0] === 'info') {
            return showPluginInfo(pluginManager, args[1]);
        } else if (args[0] === 'marketplace') {
            return manageMarketplaces(marketplaceClient, args.slice(1));
        } else {
            return showPluginUsage();
        }
    },
};

async function listInstalledPlugins(pluginManager: PluginManager, options?: string[]): Promise<CommandResult> {
    const plugins = pluginManager.getInstalledPlugins();
    const showAll = options?.includes('--all');
    
    if (plugins.length === 0) {
        return { text: 'No plugins installed. Use `/plugins search` to find plugins.' };
    }

    let output = `## Installed Plugins (${plugins.length})\n\n`;
    
    const enabledPlugins = plugins.filter(p => p.enabled);
    const disabledPlugins = plugins.filter(p => !p.enabled);
    
    if (enabledPlugins.length > 0) {
        output += `### ✅ Enabled (${enabledPlugins.length})\n\n`;
        for (const plugin of enabledPlugins) {
            output += formatPluginSummary(plugin);
        }
    }
    
    if (disabledPlugins.length > 0 && showAll) {
        output += `\n### ❌ Disabled (${disabledPlugins.length})\n\n`;
        for (const plugin of disabledPlugins) {
            output += formatPluginSummary(plugin);
        }
    }
    
    if (!showAll && disabledPlugins.length > 0) {
        output += `\n*${disabledPlugins.length} disabled plugins. Use \`--all\` to see all.*`;
    }

    return { text: output };
}

async function searchMarketplacePlugins(marketplaceClient: MarketplaceClient, args: string[]): Promise<CommandResult> {
    if (args.length === 0) {
        return { text: 'Usage: /plugins search <query>' };
    }

    const query = args.join(' ');
    
    try {
        const plugins = await marketplaceClient.searchPlugins(query);
        
        if (plugins.length === 0) {
            return { text: `No plugins found for "${query}"` };
        }

        let output = `## Search Results for "${query}" (${plugins.length})\n\n`;
        
        for (const plugin of plugins.slice(0, 20)) { // Limit results
            output += `### ${plugin.name}\n`;
            output += `**Description:** ${plugin.description}\n`;
            output += `**Author:** ${plugin.author.name}\n`;
            output += `**Version:** ${plugin.version}\n`;
            
            if (plugin.downloads) {
                output += `**Downloads:** ${plugin.downloads.toLocaleString()}\n`;
            }
            
            if (plugin.rating) {
                output += `**Rating:** ${'⭐'.repeat(Math.round(plugin.rating))}\n`;
            }
            
            if (plugin.tags && plugin.tags.length > 0) {
                output += `**Tags:** ${plugin.tags.map(tag => `\`${tag}\``).join(', ')}\n`;
            }
            
            if (plugin.verified) {
                output += `**✅ Verified**\n`;
            }
            
            output += `\n*Install with: \`/plugins install ${plugin.name}\`*\n\n`;
        }

        return { text: output };
        
    } catch (error) {
        return { text: `Error searching plugins: ${error.message}` };
    }
}

async function installPlugin(pluginManager: PluginManager, marketplaceClient: MarketplaceClient, args: string[]): Promise<CommandResult> {
    if (args.length === 0) {
        return { text: 'Usage: /plugins install <plugin-name> [from <marketplace>]' };
    }

    const pluginName = args[0];
    
    try {
        const plugin = await marketplaceClient.installFromMarketplace(pluginName);
        
        return { 
            text: `✅ Successfully installed **${plugin.manifest.name}** v${plugin.manifest.version}\n\n` +
                  `**Description:** ${plugin.manifest.description}\n` +
                  `**Author:** ${plugin.manifest.author.name}\n` +
                  `*Use \`/plugins enable ${plugin.id}\` to activate this plugin*`
        };
        
    } catch (error) {
        return { text: `❌ Failed to install plugin "${pluginName}": ${error.message}` };
    }
}

function formatPluginSummary(plugin: Plugin): string {
    let summary = `- **${plugin.manifest.name}** v${plugin.manifest.version}\n`;
    summary += `  ${plugin.manifest.description}\n`;
    summary += `  Author: ${plugin.manifest.author.name}\n`;
    
    if (plugin.commands && plugin.commands.length > 0) {
        summary += `  Commands: ${plugin.commands.map(c => `\`${c.name}\``).join(', ')}\n`;
    }
    
    if (plugin.skills && plugin.skills.length > 0) {
        summary += `  Skills: ${plugin.skills.length} available\n`;
    }
    
    if (plugin.mcpServers && plugin.mcpServers.length > 0) {
        summary += `  MCP Servers: ${plugin.mcpServers.length} configured\n`;
    }
    
    summary += `\n`;
    return summary;
}

async function showPluginUsage(): Promise<CommandResult> {
    return {
        text: `## Plugin Commands

### Management
- \`/plugins list [--all]\` - List installed plugins
- \`/plugins search <query>\` - Search marketplace
- \`/plugins install <plugin>\` - Install plugin
- \`/plugins uninstall <plugin>\` - Remove plugin
- \`/plugins enable <plugin>\` - Enable plugin
- \`/plugins disable <plugin>\` - Disable plugin
- \`/plugins update [plugin]\` - Update plugins
- \`/plugins info <plugin>\` - Show plugin details

### Marketplace
- \`/plugins marketplace list\` - List marketplaces
- \`/plugins marketplace add <url>\` - Add marketplace
- \`/plugins marketplace remove <name>\` - Remove marketplace

### Examples
\`\`\`bash
# Search for documentation plugins
/plugins search documentation

# Install a plugin
/plugins install doc-generator

# Enable a plugin
/plugins enable doc-generator

# List all plugins (including disabled)
/plugins list --all
\`\`\`
`
    };
}

Phase 6: Hook System

File: source/plugins/hooks/hook-system.ts

Plugin lifecycle hooks:

export enum HookType {
    PRE_TOOL_USE = 'preToolUse',
    POST_TOOL_USE = 'postToolUse',
    PERMISSION_REQUEST = 'permissionRequest',
    USER_PROMPT_SUBMIT = 'userPromptSubmit',
    SESSION_START = 'sessionStart',
    SESSION_END = 'sessionEnd',
    PLUGIN_ENABLE = 'pluginEnable',
    PLUGIN_DISABLE = 'pluginDisable',
    ERROR_OCCURRED = 'errorOccurred',
}

export interface HookContext {
    pluginId: string;
    timestamp: Date;
    data: any;
}

export type HookHandler = (context: HookContext) => Promise<void | any>;

export class HookRegistry {
    private static instance: HookRegistry;
    private hooks: Map<HookType, Array<{ pluginId: string; handler: HookHandler }>> = new Map();

    static getInstance(): HookRegistry {
        if (!HookRegistry.instance) {
            HookRegistry.instance = new HookRegistry();
        }
        return HookRegistry.instance;
    }

    register(hookType: HookType, handler: HookHandler, pluginId: string): void {
        if (!this.hooks.has(hookType)) {
            this.hooks.set(hookType, []);
        }
        
        this.hooks.get(hookType)!.push({ pluginId, handler });
    }

    unregister(hookType: HookType, pluginId: string): void {
        const hooks = this.hooks.get(hookType);
        if (hooks) {
            const filtered = hooks.filter(h => h.pluginId !== pluginId);
            this.hooks.set(hookType, filtered);
        }
    }

    async execute(hookType: HookType, data: any, pluginId?: string): Promise<any[]> {
        const hooks = this.hooks.get(hookType) || [];
        const results: any[] = [];

        for (const hook of hooks) {
            // Only execute hooks from specific plugin if provided
            if (pluginId && hook.pluginId !== pluginId) {
                continue;
            }

            try {
                const context: HookContext = {
                    pluginId: hook.pluginId,
                    timestamp: new Date(),
                    data,
                };

                const result = await hook.handler(context);
                results.push(result);
                
            } catch (error) {
                console.error(`Hook execution failed in ${hook.pluginId}:`, error);
                // Continue executing other hooks
            }
        }

        return results;
    }
}

// Global hook execution helpers
export async function executePreToolUse(toolName: string, args: any): Promise<any[]> {
    return HookRegistry.getInstance().execute(HookType.PRE_TOOL_USE, {
        toolName,
        args,
    });
}

export async function executePostToolUse(toolName: string, args: any, result: any): Promise<any[]> {
    return HookRegistry.getInstance().execute(HookType.POST_TOOL_USE, {
        toolName,
        args,
        result,
    });
}

export async function executeUserPromptSubmit(prompt: string): Promise<any[]> {
    return HookRegistry.getInstance().execute(HookType.USER_PROMPT_SUBMIT, {
        prompt,
    });
}

export async function executeErrorOccurred(error: Error, context?: any): Promise<any[]> {
    return HookRegistry.getInstance().execute(HookType.ERROR_OCCURRED, {
        error: error.message,
        stack: error.stack,
        context,
    });
}

Plugin Structure Examples

Basic Plugin Structure:

my-awesome-plugin/
├── .nanocoder-plugin/
│   └── plugin.json          # Plugin manifest
├── commands/
│   ├── hello.md            # Custom slash command
│   └── generate-docs.js    # JavaScript command
├── agents/
│   └── code-reviewer.md    # Custom agent
├── skills/
│   └── api-parser/         # Skill directory
│       └── SKILL.md
├── hooks/
│   └── hooks.json          # Hook definitions
├── resources/
│   ├── templates/          # File templates
│   └── scripts/            # Utility scripts
├── package.json            # Node dependencies
└── README.md              # Plugin documentation

Example plugin.json:

{
    "name": "awesome-docs",
    "version": "1.2.0",
    "description": "Automatic documentation generation for any codebase",
    "author": {
        "name": "DocGen Team",
        "email": "[email protected]",
        "url": "https://docgen.com"
    },
    "license": "MIT",
    "homepage": "https://github.com/docgen/nanocoder-plugin",
    "repository": {
        "type": "git",
        "url": "https://github.com/docgen/nanocoder-plugin.git"
    },
    "keywords": ["documentation", "generator", "api", "docs"],
    "categories": ["documentation", "productivity"],
    "nanocoderVersion": "^1.0.0",
    "permissions": [
        {
            "type": "filesystem",
            "scope": "read:project",
            "reason": "Read source files to analyze code structure"
        },
        {
            "type": "filesystem", 
            "scope": "write:docs",
            "reason": "Write generated documentation files"
        }
    ],
    "commands": [
        {
            "name": "docs-generate",
            "description": "Generate documentation for current project",
            "path": "commands/generate-docs.js",
            "aliases": ["gen-docs", "docs"],
            "category": "documentation"
        }
    ],
    "skills": [
        {
            "name": "api-parser",
            "path": "skills/api-parser",
            "enabled": true
        }
    ],
    "hooks": {
        "postToolUse": ["hooks/on-tool-use.js"],
        "sessionStart": ["hooks/on-session-start.js"]
    }
}

Security Considerations

  1. Sandboxing: All plugin code executes in isolated NodeVM environments
  2. Permission System: Granular permissions for filesystem, network, and system access
  3. Code Signing: Optional plugin signing and verification
  4. Dependency Validation: Automated security scanning of plugin dependencies
  5. Resource Limits: CPU, memory, and file access restrictions
  6. Network Filtering: Configurable network access rules
  7. Audit Logging: Comprehensive logging of plugin activities

Testing Strategy

  1. Unit Tests: Plugin loading, sandboxing, permission validation
  2. Integration Tests: Marketplace integration, plugin interactions
  3. Security Tests: Sandbox escape attempts, permission bypass testing
  4. Performance Tests: Plugin loading time, memory usage
  5. E2E Tests: Complete plugin lifecycle workflows

Success Metrics

  • Functionality: Plugins can be installed, enabled, and used correctly
  • Security: Sandbox prevents malicious plugin behavior
  • Performance: Plugin overhead is minimal (<5% performance impact)
  • Usability: Easy plugin discovery and installation
  • Ecosystem: Active marketplace with community contributions
  • Adoption: Users successfully create and share plugins

Future Enhancements

  1. Visual Plugin Editor: GUI for creating plugins without code
  2. Plugin Templates: Starter templates for common plugin types
  3. Advanced Security: Plugin signing and certificate authority
  4. Performance Profiling: Built-in profiling for plugin optimization
  5. Plugin Dependencies: Complex dependency resolution and management
  6. Team Features: Organization-level plugin management and approval workflows
  7. API Versioning: Stable API contracts for plugin compatibility
  8. Internationalization: Multi-language support for plugins

Avtrkrb avatar Nov 21 '25 07:11 Avtrkrb

Again, very much like this, however, probably a much longer horizon task as we building out the user base of Nanocoder as well as continuing work on the core mission is probably a priority. For example, making the tool better and better for smaller models :)

will-lamerton avatar Nov 23 '25 14:11 will-lamerton

Can also include the software that code with nanocoder on the marketplace? Perhaps include searching using local AI(I know it is far away from current state,but I think it helps to promote open source projects with nanocoder)

jason1015-coder avatar Jan 13 '26 20:01 jason1015-coder

As mentioned in a previous issue the groundworks for this is in play with custom tools, custom commands, custom subagents. How that then scopes into a bigger marketplace and extension support needs to be thought about organisation wide. Closing for now. I will open a new issue as and when we arrive on planning this :)

will-lamerton avatar May 18 '26 13:05 will-lamerton