Skip to content

插件类型定义

本文档定义了XAI-SDK插件系统中使用的类型和接口。

基础插件接口

Plugin

插件基础接口:

typescript
interface Plugin {
  /** 插件名称 */
  name: string
  
  /** 插件版本 */
  version: string
  
  /** 插件描述 */
  description: string
  
  /** 插件作者 */
  author?: string
  
  /** 插件主页 */
  homepage?: string
  
  /** 插件依赖 */
  dependencies?: string[]
  
  /** 插件配置 */
  config?: PluginConfig
  
  /** 初始化方法 */
  initialize?: (sdk: XAI_SDK, config?: any) => Promise<void> | void
  
  /** 销毁方法 */
  destroy?: () => Promise<void> | void
  
  /** 插件钩子 */
  hooks?: PluginHooks
  
  /** 插件工具 */
  tools?: Tool[]
  
  /** 插件中间件 */
  middleware?: PluginMiddleware[]
  
  /** 插件元数据 */
  metadata?: Record<string, any>
}

BasePlugin

插件基类:

typescript
abstract class BasePlugin implements Plugin {
  abstract name: string
  abstract version: string
  abstract description: string
  
  author?: string
  homepage?: string
  dependencies?: string[]
  config?: PluginConfig
  metadata?: Record<string, any>
  
  protected sdk?: XAI_SDK
  protected logger?: Logger
  
  /** 初始化插件 */
  async initialize(sdk: XAI_SDK, config?: any): Promise<void> {
    this.sdk = sdk
    this.logger = sdk.getLogger(`plugin:${this.name}`)
    await this.onInitialize(config)
  }
  
  /** 销毁插件 */
  async destroy(): Promise<void> {
    await this.onDestroy()
    this.sdk = undefined
    this.logger = undefined
  }
  
  /** 子类实现的初始化方法 */
  protected async onInitialize(config?: any): Promise<void> {
    // 子类可重写
  }
  
  /** 子类实现的销毁方法 */
  protected async onDestroy(): Promise<void> {
    // 子类可重写
  }
  
  /** 获取插件状态 */
  getStatus(): PluginStatus {
    return {
      name: this.name,
      version: this.version,
      enabled: !!this.sdk,
      initialized: !!this.sdk,
      lastActivity: new Date()
    }
  }
}

插件配置

PluginConfig

插件配置接口:

typescript
interface PluginConfig {
  /** 是否启用插件 */
  enabled?: boolean
  
  /** 插件优先级 */
  priority?: number
  
  /** 插件配置选项 */
  options?: Record<string, any>
  
  /** 环境限制 */
  environments?: ('development' | 'production' | 'test')[]
  
  /** 条件加载 */
  condition?: (sdk: XAI_SDK) => boolean
  
  /** 延迟加载 */
  lazy?: boolean
  
  /** 超时时间(毫秒) */
  timeout?: number
  
  /** 重试次数 */
  retries?: number
}

PluginOptions

插件选项:

typescript
interface PluginOptions {
  /** 插件实例或构造函数 */
  plugin: Plugin | PluginConstructor
  
  /** 插件配置 */
  config?: PluginConfig
  
  /** 插件别名 */
  alias?: string
  
  /** 是否立即初始化 */
  immediate?: boolean
}

PluginConstructor

插件构造函数类型:

typescript
type PluginConstructor = new (...args: any[]) => Plugin

插件钩子

PluginHooks

插件钩子接口:

typescript
interface PluginHooks {
  /** SDK初始化前 */
  beforeInitialize?: HookFunction<BeforeInitializeContext>
  
  /** SDK初始化后 */
  afterInitialize?: HookFunction<AfterInitializeContext>
  
  /** 请求前 */
  beforeRequest?: HookFunction<BeforeRequestContext>
  
  /** 请求后 */
  afterRequest?: HookFunction<AfterRequestContext>
  
  /** 响应前 */
  beforeResponse?: HookFunction<BeforeResponseContext>
  
  /** 响应后 */
  afterResponse?: HookFunction<AfterResponseContext>
  
  /** 错误处理 */
  onError?: HookFunction<ErrorContext>
  
  /** 工具执行前 */
  beforeToolExecution?: HookFunction<BeforeToolExecutionContext>
  
  /** 工具执行后 */
  afterToolExecution?: HookFunction<AfterToolExecutionContext>
  
  /** 插件卸载前 */
  beforeDestroy?: HookFunction<BeforeDestroyContext>
}

HookFunction

钩子函数类型:

typescript
type HookFunction<T = any> = (
  context: T,
  next?: () => Promise<void>
) => Promise<void> | void

钩子上下文类型

BeforeInitializeContext

初始化前上下文:

typescript
interface BeforeInitializeContext {
  /** SDK实例 */
  sdk: XAI_SDK
  
  /** 配置对象 */
  config: XAIConfig
  
  /** 插件列表 */
  plugins: Plugin[]
}

AfterInitializeContext

初始化后上下文:

typescript
interface AfterInitializeContext {
  /** SDK实例 */
  sdk: XAI_SDK
  
  /** 初始化结果 */
  result: InitializationResult
  
  /** 初始化时间(毫秒) */
  initTime: number
}

BeforeRequestContext

请求前上下文:

typescript
interface BeforeRequestContext {
  /** 消息列表 */
  messages: Message[]
  
  /** 请求选项 */
  options: ChatOptions
  
  /** 请求ID */
  requestId: string
  
  /** 适配器名称 */
  adapter: string
  
  /** 请求时间戳 */
  timestamp: Date
}

AfterRequestContext

请求后上下文:

typescript
interface AfterRequestContext {
  /** 请求上下文 */
  request: BeforeRequestContext
  
  /** 响应结果 */
  response: ChatResponse
  
  /** 请求时间(毫秒) */
  duration: number
  
  /** 是否成功 */
  success: boolean
}

BeforeResponseContext

响应前上下文:

typescript
interface BeforeResponseContext {
  /** 原始响应 */
  rawResponse: any
  
  /** 处理后的响应 */
  response: ChatResponse
  
  /** 请求上下文 */
  request: BeforeRequestContext
}

AfterResponseContext

响应后上下文:

typescript
interface AfterResponseContext {
  /** 最终响应 */
  response: ChatResponse
  
  /** 请求上下文 */
  request: BeforeRequestContext
  
  /** 处理时间(毫秒) */
  processingTime: number
}

ErrorContext

错误上下文:

typescript
interface ErrorContext {
  /** 错误对象 */
  error: Error
  
  /** 错误类型 */
  errorType: 'request' | 'response' | 'tool' | 'plugin' | 'system'
  
  /** 相关上下文 */
  context?: any
  
  /** 是否可恢复 */
  recoverable: boolean
  
  /** 重试次数 */
  retryCount: number
}

BeforeToolExecutionContext

工具执行前上下文:

typescript
interface BeforeToolExecutionContext {
  /** 工具名称 */
  toolName: string
  
  /** 工具参数 */
  parameters: Record<string, any>
  
  /** 执行ID */
  executionId: string
  
  /** 调用上下文 */
  callContext?: any
}

AfterToolExecutionContext

工具执行后上下文:

typescript
interface AfterToolExecutionContext {
  /** 执行前上下文 */
  beforeContext: BeforeToolExecutionContext
  
  /** 执行结果 */
  result: ToolResult
  
  /** 执行时间(毫秒) */
  executionTime: number
  
  /** 是否成功 */
  success: boolean
}

BeforeDestroyContext

销毁前上下文:

typescript
interface BeforeDestroyContext {
  /** 插件名称 */
  pluginName: string
  
  /** 插件实例 */
  plugin: Plugin
  
  /** 销毁原因 */
  reason: 'shutdown' | 'reload' | 'error' | 'manual'
}

插件中间件

PluginMiddleware

插件中间件接口:

typescript
interface PluginMiddleware {
  /** 中间件名称 */
  name: string
  
  /** 中间件优先级 */
  priority?: number
  
  /** 中间件处理函数 */
  handler: MiddlewareHandler
  
  /** 中间件配置 */
  config?: Record<string, any>
  
  /** 适用的钩子 */
  hooks?: (keyof PluginHooks)[]
}

MiddlewareHandler

中间件处理函数:

typescript
type MiddlewareHandler = (
  context: any,
  next: () => Promise<void>
) => Promise<void>

插件状态

PluginStatus

插件状态接口:

typescript
interface PluginStatus {
  /** 插件名称 */
  name: string
  
  /** 插件版本 */
  version: string
  
  /** 是否启用 */
  enabled: boolean
  
  /** 是否已初始化 */
  initialized: boolean
  
  /** 健康状态 */
  health?: 'healthy' | 'degraded' | 'unhealthy'
  
  /** 最后活动时间 */
  lastActivity: Date
  
  /** 错误信息 */
  error?: string
  
  /** 统计信息 */
  stats?: PluginStats
}

PluginStats

插件统计信息:

typescript
interface PluginStats {
  /** 钩子调用次数 */
  hookCalls: Record<string, number>
  
  /** 工具执行次数 */
  toolExecutions: number
  
  /** 错误次数 */
  errors: number
  
  /** 平均执行时间(毫秒) */
  averageExecutionTime: number
  
  /** 最后执行时间 */
  lastExecution: Date
  
  /** 内存使用量 */
  memoryUsage?: number
}

插件管理

PluginManager

插件管理器接口:

typescript
interface PluginManager {
  /** 注册插件 */
  register(plugin: Plugin | PluginOptions): Promise<void>
  
  /** 卸载插件 */
  unregister(name: string): Promise<void>
  
  /** 启用插件 */
  enable(name: string): Promise<void>
  
  /** 禁用插件 */
  disable(name: string): Promise<void>
  
  /** 获取插件 */
  get(name: string): Plugin | undefined
  
  /** 获取所有插件 */
  getAll(): Plugin[]
  
  /** 获取插件状态 */
  getStatus(name: string): PluginStatus | undefined
  
  /** 获取所有插件状态 */
  getAllStatus(): Record<string, PluginStatus>
  
  /** 重新加载插件 */
  reload(name: string): Promise<void>
  
  /** 执行钩子 */
  executeHook<T>(hookName: keyof PluginHooks, context: T): Promise<void>
  
  /** 清理所有插件 */
  cleanup(): Promise<void>
}

PluginRegistry

插件注册表:

typescript
interface PluginRegistry {
  /** 注册插件 */
  register(plugin: Plugin, config?: PluginConfig): void
  
  /** 获取插件 */
  get(name: string): RegisteredPlugin | undefined
  
  /** 获取所有插件 */
  getAll(): RegisteredPlugin[]
  
  /** 检查插件是否存在 */
  has(name: string): boolean
  
  /** 移除插件 */
  remove(name: string): boolean
  
  /** 清空注册表 */
  clear(): void
  
  /** 获取插件数量 */
  size(): number
}

RegisteredPlugin

已注册的插件:

typescript
interface RegisteredPlugin {
  /** 插件实例 */
  plugin: Plugin
  
  /** 插件配置 */
  config: PluginConfig
  
  /** 注册时间 */
  registeredAt: Date
  
  /** 是否已初始化 */
  initialized: boolean
  
  /** 初始化时间 */
  initializedAt?: Date
  
  /** 插件状态 */
  status: PluginStatus
}

插件事件

PluginEvent

插件事件接口:

typescript
interface PluginEvent {
  /** 事件类型 */
  type: PluginEventType
  
  /** 插件名称 */
  pluginName: string
  
  /** 事件数据 */
  data?: any
  
  /** 事件时间戳 */
  timestamp: Date
  
  /** 事件ID */
  id: string
}

PluginEventType

插件事件类型:

typescript
type PluginEventType =
  | 'plugin:registered'
  | 'plugin:unregistered'
  | 'plugin:enabled'
  | 'plugin:disabled'
  | 'plugin:initialized'
  | 'plugin:destroyed'
  | 'plugin:error'
  | 'plugin:hook:executed'
  | 'plugin:tool:executed'
  | 'plugin:middleware:executed'

PluginEventListener

插件事件监听器:

typescript
type PluginEventListener = (event: PluginEvent) => void | Promise<void>

插件开发辅助类型

PluginContext

插件上下文:

typescript
interface PluginContext {
  /** SDK实例 */
  sdk: XAI_SDK
  
  /** 插件配置 */
  config: any
  
  /** 日志记录器 */
  logger: Logger
  
  /** 事件发射器 */
  emitter: EventEmitter
  
  /** 插件存储 */
  storage: PluginStorage
  
  /** 工具管理器 */
  toolManager: ToolManager
}

PluginStorage

插件存储接口:

typescript
interface PluginStorage {
  /** 设置值 */
  set(key: string, value: any): Promise<void>
  
  /** 获取值 */
  get<T = any>(key: string): Promise<T | undefined>
  
  /** 删除值 */
  delete(key: string): Promise<boolean>
  
  /** 检查键是否存在 */
  has(key: string): Promise<boolean>
  
  /** 清空存储 */
  clear(): Promise<void>
  
  /** 获取所有键 */
  keys(): Promise<string[]>
}

PluginLogger

插件日志记录器:

typescript
interface PluginLogger {
  /** 调试日志 */
  debug(message: string, ...args: any[]): void
  
  /** 信息日志 */
  info(message: string, ...args: any[]): void
  
  /** 警告日志 */
  warn(message: string, ...args: any[]): void
  
  /** 错误日志 */
  error(message: string, ...args: any[]): void
  
  /** 创建子日志记录器 */
  child(namespace: string): PluginLogger
}

插件验证

PluginValidator

插件验证器:

typescript
interface PluginValidator {
  /** 验证插件 */
  validate(plugin: Plugin): ValidationResult
  
  /** 验证插件配置 */
  validateConfig(config: PluginConfig): ValidationResult
  
  /** 验证插件依赖 */
  validateDependencies(plugin: Plugin, availablePlugins: Plugin[]): ValidationResult
}

ValidationResult

验证结果:

typescript
interface ValidationResult {
  /** 是否有效 */
  valid: boolean
  
  /** 错误信息 */
  errors: ValidationError[]
  
  /** 警告信息 */
  warnings: ValidationWarning[]
}

ValidationError

验证错误:

typescript
interface ValidationError {
  /** 错误代码 */
  code: string
  
  /** 错误消息 */
  message: string
  
  /** 错误路径 */
  path?: string
  
  /** 错误详情 */
  details?: any
}

ValidationWarning

验证警告:

typescript
interface ValidationWarning {
  /** 警告代码 */
  code: string
  
  /** 警告消息 */
  message: string
  
  /** 警告路径 */
  path?: string
  
  /** 建议 */
  suggestion?: string
}

插件生命周期

PluginLifecycle

插件生命周期状态:

typescript
type PluginLifecycle =
  | 'unregistered'
  | 'registered'
  | 'initializing'
  | 'initialized'
  | 'running'
  | 'paused'
  | 'stopping'
  | 'stopped'
  | 'error'
  | 'destroyed'

LifecycleTransition

生命周期转换:

typescript
interface LifecycleTransition {
  /** 源状态 */
  from: PluginLifecycle
  
  /** 目标状态 */
  to: PluginLifecycle
  
  /** 转换时间 */
  timestamp: Date
  
  /** 转换原因 */
  reason?: string
  
  /** 转换数据 */
  data?: any
}

这些类型定义为XAI-SDK的插件系统提供了完整的类型支持,确保插件开发的类型安全和一致性。

Released under the MIT License.