返回知识库
0

第十七章:Self-Modification 扩展

本章目标:帮助你理解 Agent 如何检查/挂载自己的插件、运行时插件热重载、模型驱动的插件安装/卸载、以及安全边界与限制。阅读本章后,你应该能回答"Agent 如何动态扩展自己的能力"以及"Self-Modification 的安全边界在哪里"。


17.1 概述

17.1.1 什么是 Self-Modification

Self-Modification 是 dsh 的实验性功能,允许 Agent 在运行时检查和修改自己的插件配置。这使得 Agent 可以:

  1. 自省:查看当前加载了哪些插件

  2. 动态扩展:根据任务需要安装新插件

  3. 自适应:根据环境变化调整配置

预览
源码

Self-Modification

检查插件

安装插件

卸载插件

Agent

Cordis Inspector

Plugin Installer

Plugin Uninstaller

插件注册表

graph TB
    subgraph "Self-Modification"
        A[Agent] -->|"检查插件"| B[Cordis Inspector]
        A -->|"安装插件"| C[Plugin Installer]
        A -->|"卸载插件"| D[Plugin Uninstaller]
        B --> E[插件注册表]
        C --> E
        D --> E
    end

17.2 插件检查(Introspection)

17.2.1 CordisInspectRegistryService

// 来自 packages/extensions/cordis-host-runner/src/inspect-registry.ts
class CordisInspectRegistryService {
  /** 注册检查器 */
  register(inspector: CordisInspector): Disposable {
    this.inspectors.set(inspector.id, inspector)
    
    return () => {
      this.inspectors.delete(inspector.id)
    }
  }
  
  /** 查询插件信息 */
  query(pluginId: string): PluginInfo | undefined {
    return this.inspectors.get(pluginId)?.info()
  }
  
  /** 列出所有插件 */
  list(): PluginInfo[] {
    return Array.from(this.inspectors.values()).map(i => i.info())
  }
}

17.2.2 PluginInfo

interface PluginInfo {
  /** 插件 ID */
  id: string
  /** 插件名称 */
  name: string
  /** 插件版本 */
  version: string
  /** 插件状态 */
  status: 'active' | 'inactive' | 'error'
  /** 依赖的插件 */
  dependencies: string[]
  /** 提供的服务 */
  services: string[]
  /** 注册的事件监听器 */
  eventListeners: string[]
}

17.2.3 Agent 自省工具

// 概念性描述:Agent 可以使用的自省工具
ctx.tools.register({
  name: 'inspect_plugins',
  description: 'List all loaded plugins and their status',
  parameters: {
    type: 'object',
    properties: {
      filter: { type: 'string', description: 'Filter by plugin name' }
    }
  },
  async execute(input) {
    const plugins = ctx.cordisInspector.list()
    
    if (input.filter) {
      return plugins.filter(p => p.name.includes(input.filter))
    }
    
    return plugins
  }
})

17.3 插件安装

17.3.1 Plugin Installer

// 来自 packages/extensions/cordis-host-runner/src/index.ts(概念性)
class DynamicCordisRunnerService {
  /** 安装插件 */
  async installPlugin(plugin: PluginDefinition): Promise<void> {
    // 1. 验证插件
    await this.validatePlugin(plugin)
    
    // 2. 检查依赖
    await this.checkDependencies(plugin)
    
    // 3. 下载插件(如果是远程)
    if (plugin.remote) {
      await this.downloadPlugin(plugin)
    }
    
    // 4. 挂载插件
    await this.mountPlugin(plugin)
    
    // 5. 发送事件
    this.ctx.emit('plugin/installed', { pluginId: plugin.id })
  }
  
  /** 挂载插件 */
  private async mountPlugin(plugin: PluginDefinition): Promise<void> {
    // 动态加载插件模块
    const module = await import(plugin.entryPoint)
    
    // 注册到 Cordis
    this.ctx.plugin(module.default, plugin.config)
  }
}

17.3.2 PluginDefinition

interface PluginDefinition {
  /** 插件 ID */
  id: string
  /** 插件名称 */
  name: string
  /** 插件版本 */
  version: string
  /** 入口点 */
  entryPoint: string
  /** 配置 */
  config?: Record<string, unknown>
  /** 依赖 */
  dependencies?: string[]
  /** 是否为远程插件 */
  remote?: boolean
  /** 远程 URL */
  remoteUrl?: string
}

17.4 插件卸载

17.4.1 Plugin Uninstaller

// 来自 packages/extensions/cordis-host-runner/src/index.ts(概念性)
class DynamicCordisRunnerService {
  /** 卸载插件 */
  async uninstallPlugin(pluginId: string): Promise<void> {
    // 1. 检查是否有其他插件依赖
    const dependents = this.getDependents(pluginId)
    if (dependents.length > 0) {
      throw new Error(`Cannot uninstall plugin ${pluginId}: depended on by ${dependents.join(', ')}`)
    }
    
    // 2. 卸载插件
    await this.unmountPlugin(pluginId)
    
    // 3. 清理资源
    await this.cleanupPlugin(pluginId)
    
    // 4. 发送事件
    this.ctx.emit('plugin/uninstalled', { pluginId })
  }
  
  /** 卸载插件 */
  private async unmountPlugin(pluginId: string): Promise<void> {
    // 获取插件的 disposer
    const disposer = this.pluginDisposers.get(pluginId)
    if (disposer) {
      await disposer()
      this.pluginDisposers.delete(pluginId)
    }
  }
}

17.5 热重载

17.5.1 HMR(Hot Module Replacement)

// 来自 vendor/hmr/src/index.ts(概念性)
class HmrService {
  /** 监听文件变化 */
  watchFiles(directories: string[]): void {
    for (const dir of directories) {
      const watcher = chokidar.watch(dir, {
        ignoreInitial: true,
        ignored: /node_modules/
      })
      
      watcher.on('change', (path) => {
        this.handleFileChange(path)
      })
    }
  }
  
  /** 处理文件变化 */
  private async handleFileChange(path: string): Promise<void> {
    // 1. 找到对应的插件
    const plugin = this.findPluginByFile(path)
    if (!plugin) return
    
    // 2. 卸载旧插件
    await this.unmountPlugin(plugin.id)
    
    // 3. 重新加载插件
    const module = await import(path)
    
    // 4. 挂载新插件
    await this.mountPlugin({
      id: plugin.id,
      name: plugin.name,
      entryPoint: path,
      config: plugin.config
    })
    
    // 5. 发送事件
    this.ctx.emit('plugin/reloaded', { pluginId: plugin.id })
  }
}

17.5.2 配置热重载

// 来自 vendor/include/src/index.ts(概念性)
class IncludeService {
  /** 监听配置变化 */
  watchConfig(configPath: string): void {
    const watcher = chokidar.watch(configPath, {
      ignoreInitial: true
    })
    
    watcher.on('change', async () => {
      // 1. 重新加载配置
      const newConfig = await this.loadConfig(configPath)
      
      // 2. 应用配置变更
      await this.applyConfigChange(newConfig)
      
      // 3. 发送事件
      this.ctx.emit('config/reloaded', { path: configPath })
    })
  }
}

17.6 安全边界

17.6.1 限制

Self-Modification 功能有严格的安全限制:

  1. 权限控制:只有授权的 Agent 可以修改插件

  2. 沙箱隔离:插件在沙箱中运行

  3. 审计日志:所有修改操作被记录

  4. 回滚能力:支持插件修改的回滚

17.6.2 安全检查

// 概念性描述
class SecurityChecker {
  /** 检查插件安装权限 */
  checkInstallPermission(agent: Agent, plugin: PluginDefinition): boolean {
    // 1. 检查 Agent 权限
    if (!agent.hasPermission('plugin:install')) {
      return false
    }
    
    // 2. 检查插件来源
    if (plugin.remote && !this.isTrustedSource(plugin.remoteUrl)) {
      return false
    }
    
    // 3. 检查插件签名
    if (plugin.signature && !this.verifySignature(plugin)) {
      return false
    }
    
    return true
  }
  
  /** 检查插件卸载权限 */
  checkUninstallPermission(agent: Agent, pluginId: string): boolean {
    // 1. 检查 Agent 权限
    if (!agent.hasPermission('plugin:uninstall')) {
      return false
    }
    
    // 2. 检查是否有其他插件依赖
    const dependents = this.getDependents(pluginId)
    if (dependents.length > 0) {
      return false
    }
    
    return true
  }
}

17.7 配置

17.7.1 Self-Modification 配置

# cordis.patch.yml
- id: self-modification
  config:
    # 启用 Self-Modification
    enabled: true
    
    # 权限控制
    permissions:
      install: true
      uninstall: true
      reload: true
    
    # 安全限制
    security:
      requireSignature: true
      trustedSources:
        - 'https://github.com/deepseek-harness'
        - 'https://registry.npmjs.org/@deepseek-ai'
    
    # 审计日志
    audit:
      enabled: true
      logPath: '${DSH_HOME}/audit/self-modification.log'

17.8 使用场景

17.8.1 动态扩展能力

// Agent 根据任务需要动态安装插件
async function handleComplexTask(agent: Agent, task: string): Promise<void> {
  // 1. 分析任务
  const requirements = analyzeTaskRequirements(task)
  
  // 2. 检查当前能力
  const currentPlugins = await agent.inspectPlugins()
  
  // 3. 安装缺失的能力
  for (const requirement of requirements) {
    if (!currentPlugins.some(p => p.provides.includes(requirement))) {
      await agent.installPlugin({
        id: `plugin-${requirement}`,
        name: `Plugin for ${requirement}`,
        entryPoint: `./plugins/${requirement}.js`
      })
    }
  }
  
  // 4. 执行任务
  await agent.execute(task)
}

17.8.2 自适应配置

// Agent 根据环境调整配置
async function adaptToEnvironment(agent: Agent): Promise<void> {
  // 1. 检测环境
  const environment = await agent.detectEnvironment()
  
  // 2. 调整配置
  if (environment === 'production') {
    await agent.updatePluginConfig('logging', { level: 'warn' })
    await agent.updatePluginConfig('security', { strictMode: true })
  } else {
    await agent.updatePluginConfig('logging', { level: 'debug' })
    await agent.updatePluginConfig('security', { strictMode: false })
  }
}

17.9 小结

概念一句话解释
Self-ModificationAgent 动态修改自己的插件配置
Introspection检查当前加载的插件
Plugin Installer动态安装新插件
Plugin Uninstaller动态卸载插件
HMR热模块替换,运行时重载插件
Security Checker安全检查,防止恶意修改

17.10 完整教程总结

恭喜你完成了 DeepSeek Harness 补充教程的全部八章!加上之前的九章基础教程,你已经系统地学习了 dsh 的完整架构。

补充专题总结

  1. 安全沙箱与隔离:Landlock/Seatbelt/bwrap 沙箱、进程树隔离

  2. Session 日志深度:JSONL 格式、投影算法、日志重放

  3. Typert 类型系统:类型图生成、运行时注册、跨仓库发现

  4. Web Client 架构:React 组件、Slot 机制、WebSocket 通信

  5. API Gateway 与 SDK:BFF 架构、JSON-RPC 协议、TS/Python SDK

  6. 凭证与授权:凭证接缝、优先级链、OAuth 流程

  7. Webhook 与外部事件:签名验证、可信规则、CI/CD 集成

  8. Self-Modification:插件自省、动态安装/卸载、热重载

参考资源


本教程基于 DeepSeek Harness 源码编写,内容可能随项目更新而变化。

DeepSeek-Harness / 17-Self-Modification 扩展 0 0 iliuqi
2026-09-04T07:48:53.541148894Z 2026-09-04T07:58:44.597513063Z