All files / core base-plugin.ts

0% Statements 0/416
0% Branches 0/1
0% Functions 0/1
0% Lines 0/416

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
/**
 * Base Plugin Implementation
 *
 * Abstract base class that provides common plugin functionality.
 * Plugins should extend this class for easier implementation.
 */

import { EventEmitter } from 'events';
import type {
  PluginMetadata,
  PluginContext,
  PluginLifecycleState,
  PluginConfig,
  ILogger,
  IEventBus,
  ServiceContainer,
  AgentTypeDefinition,
  TaskTypeDefinition,
  MCPToolDefinition,
  CLICommandDefinition,
  MemoryBackendFactory,
  HookDefinition,
  WorkerDefinition,
  LLMProviderDefinition,
  HealthCheckResult,
} from '../types/index.js';
import type { IPlugin } from './plugin-interface.js';
import { PLUGIN_EVENTS } from './plugin-interface.js';

// ============================================================================
// Base Plugin
// ============================================================================

/**
 * Abstract base class for plugins.
 *
 * Provides:
 * - Lifecycle management
 * - Logging and event emission
 * - Configuration access
 * - Service container access
 * - Default implementations for optional methods
 *
 * @example
 * ```typescript
 * class MyPlugin extends BasePlugin {
 *   constructor() {
 *     super({
 *       name: 'my-plugin',
 *       version: '1.0.0',
 *       description: 'My custom plugin'
 *     });
 *   }
 *
 *   protected async onInitialize(): Promise<void> {
 *     this.logger.info('Plugin initialized');
 *   }
 *
 *   registerMCPTools(): MCPToolDefinition[] {
 *     return [{
 *       name: 'my-tool',
 *       description: 'My custom tool',
 *       inputSchema: { type: 'object', properties: {} },
 *       handler: async (input) => ({
 *         content: [{ type: 'text', text: 'Hello!' }]
 *       })
 *     }];
 *   }
 * }
 * ```
 */
export abstract class BasePlugin extends EventEmitter implements IPlugin {
  // =========================================================================
  // Properties
  // =========================================================================

  public readonly metadata: PluginMetadata;
  private _state: PluginLifecycleState = 'uninitialized';
  private _context: PluginContext | null = null;
  private _initTime: Date | null = null;

  // =========================================================================
  // Constructor
  // =========================================================================

  constructor(metadata: PluginMetadata) {
    super();
    this.metadata = Object.freeze(metadata);
  }

  // =========================================================================
  // State Management
  // =========================================================================

  get state(): PluginLifecycleState {
    return this._state;
  }

  protected setState(state: PluginLifecycleState): void {
    const previousState = this._state;
    this._state = state;
    this.emit('stateChange', { previousState, currentState: state });
  }

  // =========================================================================
  // Context Accessors
  // =========================================================================

  protected get context(): PluginContext {
    if (!this._context) {
      throw new Error(`Plugin ${this.metadata.name} not initialized`);
    }
    return this._context;
  }

  protected get config(): PluginConfig {
    return this.context.config;
  }

  protected get logger(): ILogger {
    return this.context.logger;
  }

  protected get eventBus(): IEventBus {
    return this.context.eventBus;
  }

  protected get services(): ServiceContainer {
    return this.context.services;
  }

  protected get settings(): Record<string, unknown> {
    return this.config.settings;
  }

  // =========================================================================
  // Lifecycle Implementation
  // =========================================================================

  /**
   * Initialize the plugin.
   * Subclasses should override onInitialize() instead of this method.
   */
  async initialize(context: PluginContext): Promise<void> {
    if (this._state !== 'uninitialized') {
      throw new Error(`Plugin ${this.metadata.name} already initialized`);
    }

    this.setState('initializing');
    this._context = context;
    this._initTime = new Date();

    try {
      // Validate dependencies
      await this.validateDependencies();

      // Validate configuration
      await this.validateConfig();

      // Call subclass initialization
      await this.onInitialize();

      this.setState('initialized');
      this.eventBus.emit(PLUGIN_EVENTS.INITIALIZED, { plugin: this.metadata.name });
    } catch (error) {
      this.setState('error');
      this.eventBus.emit(PLUGIN_EVENTS.ERROR, {
        plugin: this.metadata.name,
        error: error instanceof Error ? error.message : String(error),
      });
      throw error;
    }
  }

  /**
   * Shutdown the plugin.
   * Subclasses should override onShutdown() instead of this method.
   */
  async shutdown(): Promise<void> {
    if (this._state !== 'initialized' && this._state !== 'error') {
      return; // Already shutdown or never initialized
    }

    this.setState('shutting-down');

    try {
      await this.onShutdown();
      this.setState('shutdown');
      this.eventBus.emit(PLUGIN_EVENTS.SHUTDOWN, { plugin: this.metadata.name });
    } catch (error) {
      this.setState('error');
      throw error;
    } finally {
      this._context = null;
    }
  }

  /**
   * Health check implementation.
   * Subclasses can override onHealthCheck() for custom checks.
   */
  async healthCheck(): Promise<HealthCheckResult> {
    const checks: Record<string, { healthy: boolean; message?: string; latencyMs?: number }> = {};

    // Check state
    const stateHealthy = this._state === 'initialized';
    checks['state'] = {
      healthy: stateHealthy,
      message: stateHealthy ? 'Plugin initialized' : `State: ${this._state}`,
    };

    // Run custom health checks
    const startTime = Date.now();
    try {
      const customChecks = await this.onHealthCheck();
      Object.assign(checks, customChecks);
    } catch (error) {
      checks['custom'] = {
        healthy: false,
        message: error instanceof Error ? error.message : 'Health check failed',
        latencyMs: Date.now() - startTime,
      };
    }

    const allHealthy = Object.values(checks).every(c => c.healthy);

    return {
      healthy: allHealthy,
      status: allHealthy ? 'healthy' : 'unhealthy',
      checks,
      timestamp: new Date(),
    };
  }

  // =========================================================================
  // Lifecycle Hooks (Override in subclasses)
  // =========================================================================

  /**
   * Called during initialization.
   * Override this in subclasses to add initialization logic.
   */
  protected async onInitialize(): Promise<void> {
    // Default: no-op
  }

  /**
   * Called during shutdown.
   * Override this in subclasses to add cleanup logic.
   */
  protected async onShutdown(): Promise<void> {
    // Default: no-op
  }

  /**
   * Called during health check.
   * Override this in subclasses to add custom health checks.
   */
  protected async onHealthCheck(): Promise<Record<string, { healthy: boolean; message?: string }>> {
    return {};
  }

  // =========================================================================
  // Validation
  // =========================================================================

  /**
   * Validate plugin dependencies are available.
   */
  protected async validateDependencies(): Promise<void> {
    const deps = this.metadata.dependencies ?? [];
    for (const dep of deps) {
      // Dependencies are validated by the PluginManager
      // This hook allows plugins to do additional checks
      this.logger.debug(`Dependency validated: ${dep}`);
    }
  }

  /**
   * Validate plugin configuration.
   * Override this in subclasses to add config validation.
   */
  protected async validateConfig(): Promise<void> {
    // Default: no-op
  }

  // =========================================================================
  // Extension Points (Override in subclasses as needed)
  // =========================================================================

  registerAgentTypes?(): AgentTypeDefinition[];
  registerTaskTypes?(): TaskTypeDefinition[];
  registerMCPTools?(): MCPToolDefinition[];
  registerCLICommands?(): CLICommandDefinition[];
  registerMemoryBackends?(): MemoryBackendFactory[];
  registerHooks?(): HookDefinition[];
  registerWorkers?(): WorkerDefinition[];
  registerProviders?(): LLMProviderDefinition[];

  // =========================================================================
  // Utility Methods
  // =========================================================================

  /**
   * Get setting value with type safety.
   */
  protected getSetting<T>(key: string, defaultValue?: T): T | undefined {
    const value = this.settings[key];
    if (value === undefined) return defaultValue;
    return value as T;
  }

  /**
   * Get uptime in milliseconds.
   */
  protected getUptime(): number {
    if (!this._initTime) return 0;
    return Date.now() - this._initTime.getTime();
  }

  /**
   * Create a child logger with context.
   */
  protected createChildLogger(context: Record<string, unknown>): ILogger {
    return this.logger.child({ plugin: this.metadata.name, ...context });
  }
}

// ============================================================================
// Simple Plugin (for quick one-off plugins)
// ============================================================================

/**
 * Configuration for creating a simple plugin.
 */
export interface SimplePluginConfig {
  metadata: PluginMetadata;
  onInitialize?: (context: PluginContext) => Promise<void>;
  onShutdown?: () => Promise<void>;
  agentTypes?: AgentTypeDefinition[];
  taskTypes?: TaskTypeDefinition[];
  mcpTools?: MCPToolDefinition[];
  cliCommands?: CLICommandDefinition[];
  hooks?: HookDefinition[];
  workers?: WorkerDefinition[];
  providers?: LLMProviderDefinition[];
}

/**
 * Create a simple plugin from configuration.
 *
 * @example
 * ```typescript
 * const myPlugin = createSimplePlugin({
 *   metadata: { name: 'my-plugin', version: '1.0.0' },
 *   mcpTools: [{
 *     name: 'hello',
 *     description: 'Say hello',
 *     inputSchema: { type: 'object', properties: {} },
 *     handler: async () => ({ content: [{ type: 'text', text: 'Hello!' }] })
 *   }]
 * });
 * ```
 */
export function createSimplePlugin(config: SimplePluginConfig): IPlugin {
  return new SimplePlugin(config) as IPlugin;
}

class SimplePlugin extends BasePlugin {
  private readonly _config: SimplePluginConfig;

  constructor(config: SimplePluginConfig) {
    super(config.metadata);
    this._config = config;
  }

  protected async onInitialize(): Promise<void> {
    if (this._config.onInitialize) {
      await this._config.onInitialize(this.context);
    }
  }

  protected async onShutdown(): Promise<void> {
    if (this._config.onShutdown) {
      await this._config.onShutdown();
    }
  }

  override registerAgentTypes(): AgentTypeDefinition[] {
    return this._config.agentTypes ?? [];
  }

  override registerTaskTypes(): TaskTypeDefinition[] {
    return this._config.taskTypes ?? [];
  }

  override registerMCPTools(): MCPToolDefinition[] {
    return this._config.mcpTools ?? [];
  }

  override registerCLICommands(): CLICommandDefinition[] {
    return this._config.cliCommands ?? [];
  }

  override registerHooks(): HookDefinition[] {
    return this._config.hooks ?? [];
  }

  override registerWorkers(): WorkerDefinition[] {
    return this._config.workers ?? [];
  }

  override registerProviders(): LLMProviderDefinition[] {
    return this._config.providers ?? [];
  }
}