编程 DeepSeek Harness 深度解析:一切皆插件的 AI Agent 运行时架构——从 Cordis 底层到插件生态全景拆解

2026-08-15 15:21:35 +0800 CST views 13

DeepSeek Harness 深度解析:一切皆插件的 AI Agent 运行时架构——从 Cordis 底层到插件生态全景拆解

背景介绍:从"嘴炮 Agent"到"手脚健全的 Agent"

过去两年,AI Agent 概念火遍整个技术圈,几乎每家大厂都在发布自己的 Agent 框架。Claude Code、Codex、Copilot Workspace……一个比一个响亮。但仔细看这些产品,你会发现一个共同的尴尬:大多数 Agent 其实只是"嘴炮 Agent"——它们能说会道,能生成漂亮的计划,但真让它们去改一个真实项目的代码、跑测试、排查问题,十有八九会在某个环节卡住:要么没有文件系统的真实访问权限,要么终端命令执行不到预期,要么上下文窗口不够用需要人工"喂"信息。

问题的根源在于:模型是模型,环境是环境,两者之间缺乏一个真正可靠的"连接层"。

2026年8月13日晚,DeepSeek 正式开源了 DeepSeek Harness(简称 DSH),直击这个痛点。发布仅 1.5 小时,GitHub Star 突破 2.2 万,成为 GitHub 史上最快涨星的项目。此前的纪录保持者是 xAI 的 Grok-1,也用了约 1.2 天才突破 2 万星。

DSH 想要解决的核心问题是:把大模型从"只会输出文字"的状态,升级成"真正能在数字世界里动手做事"的状态。

本文将从架构设计、核心原理、插件生态、代码实战四个维度,全面拆解这个框架。适合对 AI Agent 有一定了解、想深入理解其工程实现的开发者阅读。


一、架构概览:Everything is a Plugin

1.1 设计哲学

DSH 的官方 slogan 是 "Everything is a Plugin"(一切皆插件)。这句话不是营销话术,而是一个字面意义上的工程宣言。

在传统 Agent 框架中,核心组件通常是"硬编码"的:

  • 模型调用逻辑写死在代码里
  • 文件系统访问是内置的、不可替换的
  • Agent 的决策循环(Agent Loop)是框架的"灵魂",改不了

这带来了一个根本问题:如果我想把 DeepSeek 的模型换成别家?如果我想让 Agent 通过不同的协议访问文件系统?如果我想自定义 Agent 的决策策略?——不好意思,改不了,或者需要 fork 整个仓库自己维护。

DSH 的回答是:把这些全部做成插件,可插拔、可替换。

具体来说,以下这些组件在 DSH 中都是插件:

组件类别具体内容可替换性
模型适配器DeepSeek 模型、OpenAI 兼容模型、本地模型完全可替换
工具层文件系统、Shell、网页访问、代码工具、子 Agent完全可替换
存储层Session Log、上下文管理、长期记忆完全可替换
安全策略权限控制、危险操作拦截、审计日志完全可替换
Agent Loop决策循环本身完全可替换
交互界面Web UI、TUI、Headless、API Server完全可替换

也就是说:你拿到的是一个框架的"空壳",里面填什么插件由你决定。 这和传统框架"给你一个完整的产品,然后让你在里面修修补补"的思路完全相反。

1.2 底层引擎:Cordis

DSH 的底层依赖一个名为 Cordis 的基础设施。关于 Cordis 的公开资料目前主要来自一篇 88 页的范式论文(发布在 DSH 同期),但根据 GitHub 仓库结构和官方文档的蛛丝马迹,可以推断 Cordis 提供以下核心能力:

消息总线与事件系统:Cordis 作为所有插件之间的通信中枢。任何插件发出的消息(工具调用结果、状态变更、错误通知等)都通过 Cordis 的消息总线进行路由。这类似于操作系统内核的 IPC 机制,但针对 AI Agent 的工作流做了专门优化。

生命周期管理:插件的加载、初始化、运行、销毁由 Cordis 统一管理。它维护一个插件依赖图,确保加载顺序正确,销毁时反向进行。

上下文注入:Cordis 负责将全局上下文(当前项目结构、用户偏好、运行状态等)注入到 Agent 的每次决策过程中。这解决了传统框架中"上下文丢失"的经典问题。

安全沙箱:Cordis 提供插件级别的安全隔离。危险的工具调用(如删除系统文件、执行未经审核的 Shell 命令)会被安全策略插件拦截并记录。

Cordis 的设计哲学借鉴了微内核操作系统的思想:只保留最核心的通信和调度能力,其他一切功能都放到插件层。 这样做的好处是框架本身足够稳定,而插件的迭代不会影响核心系统的稳定性。

1.3 整体架构图

用一个简化的视角看,DSH 的架构分为三层:

交互层 (Interface Layer)
    Web UI | TUI | Headless | API Server
─────────────────────────────────────────────
          插件层 (Plugin Layer)
  模型插件 | 工具插件 | 存储插件 | 安全插件
─────────────────────────────────────────────
         核心层 (Cordis Kernel)
  消息总线 | 生命周期管理 | 上下文注入 | 沙箱

二、核心概念深度解析

2.1 插件系统(Plugin System)

什么是插件?

在 DSH 的语境下,一个插件(Plugin)是一个具有标准接口的代码单元。每个插件需要实现一组预定义的接口(interface),但具体的实现完全自由。

DSH 的插件接口设计遵循一个重要的原则:最小接口,最大自由。 Cordis 只规定插件必须实现哪些方法,不规定插件内部怎么实现。

一个典型的 DSH 插件结构如下:

// 插件接口定义(伪代码,基于 DSH 源码结构推断)
interface DSHPlugin {
  // 插件元信息
  name: string;           // 插件唯一标识名
  version: string;        // 版本号
  dependencies?: string[]; // 依赖的其他插件名
  
  // 生命周期钩子
  onLoad?(ctx: PluginContext): Promise<void>;   // 加载时调用
  onUnload?(): Promise<void>;                    // 卸载时调用
  
  // 核心功能
  execute(input: PluginInput): Promise<PluginOutput>; // 执行业务逻辑
}

// 插件上下文:Cordis 注入给每个插件的运行环境
interface PluginContext {
  cordis: CordisInstance;     // 指向 Cordis 内核实例
  config: PluginConfig;       // 插件的配置参数
  bus: MessageBus;            // 消息总线引用
  storage: StorageAdapter;    // 存储适配器
  security: SecurityPolicy;   // 安全策略引用
}

插件的注册与加载

DSH 通过一个配置文件来声明要加载哪些插件:

// dsh.config.ts
import { defineConfig } from '@deepseek-ai/dsh';

export default defineConfig({
  // 指定使用的模型插件
  model: {
    adapter: 'deepseek-chat',
    apiKey: process.env.DEEPSEEK_API_KEY,
    baseUrl: 'https://api.deepseek.com',
    model: 'deepseek-chat-v3',
    parameters: {
      temperature: 0.7,
      maxTokens: 8192,
    },
  },

  // 注册工具插件
  tools: [
    {
      name: 'filesystem',
      adapter: '@dsh/plugin-filesystem',
      config: {
        rootPath: process.cwd(),
        allowedExtensions: ['.ts', '.js', '.json', '.md', '.py', '.go', '.rs'],
        maxFileSize: 10 * 1024 * 1024,
      },
    },
    {
      name: 'shell',
      adapter: '@dsh/plugin-shell',
      config: {
        workingDirectory: process.cwd(),
        timeout: 30000,
        allowedCommands: ['git', 'npm', 'node', 'python', 'cargo', 'go'],
        dangerousCommands: ['rm -rf /', 'dd if=', ':(){:|:&};:'],
      },
    },
    {
      name: 'web',
      adapter: '@dsh/plugin-web',
      config: {
        userAgent: 'DeepSeek-Harness/1.0',
        timeout: 15000,
        followRedirects: true,
        maxContentLength: 1024 * 1024,
      },
    },
    {
      name: 'code',
      adapter: '@dsh/plugin-code-tools',
      config: {
        linters: ['eslint', 'ruff', 'gofmt'],
        formatters: ['prettier', 'rustfmt'],
      },
    },
  ],

  storage: {
    adapter: '@dsh/plugin-storage-filesystem',
    config: { sessionDir: './.dsh/sessions' },
  },

  security: {
    adapter: '@dsh/plugin-security-default',
    config: {
      allowNetwork: true,
      allowFileWrite: true,
      allowCommandExecution: true,
      maxConcurrentTools: 5,
      auditLog: true,
    },
  },
});

这个配置文件就是 DSH 的"入口"——用户通过它来定义自己的 Agent 是什么样子的。同一个框架,换一套配置文件,就变成了完全不同的 Agent。

插件之间的通信

插件之间通过 Cordis 的消息总线进行通信。消息总线采用发布-订阅(Pub/Sub)模式:

// 示例:文件系统插件发布文件变更事件
await cordis.bus.publish('file:changed', {
  path: '/src/main.ts',
  changeType: 'modified',
  timestamp: Date.now(),
});

// 示例:安全插件订阅文件变更事件
cordis.bus.subscribe('file:changed', async (event) => {
  if (isSensitivePath(event.path)) {
    await security.logSuspiciousActivity(event);
    throw new SecurityError(`Access denied to sensitive path: ${event.path}`);
  }
});

// 示例:Agent Loop 订阅工具执行结果
cordis.bus.subscribe('tool:executed', (result) => {
  agentLoop.recordToolResult(result);
});

2.2 工具系统(Tool System)

工具的定义

在 DSH 中,"工具"(Tool)是 Agent 与外部世界交互的桥梁。每个工具本质上是一个函数:

interface Tool {
  name: string;
  description: string;
  parameters: ToolParameterSchema;
  execute(params: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
  metadata: {
    category: 'filesystem' | 'shell' | 'web' | 'code' | 'agent' | 'storage';
    requiresApproval?: boolean;
    canBeParallel?: boolean;
    estimatedDuration?: number;
  };
}

文件系统工具详解

文件系统工具是 DSH 中最核心的工具之一,让 Agent 能够真正"看到"和"修改"项目文件。

核心能力

// 文件系统工具提供的核心方法

// 1. 读取文件
async readFile(path: string, options?: {
  encoding?: 'utf-8' | 'base64';
  lines?: number;
  fromLine?: number;
}): Promise<FileContent>;

// 2. 写入文件
async writeFile(path: string, content: string, options?: {
  createDirs?: boolean;
  overwrite?: boolean;
}): Promise<WriteResult>;

// 3. 列出目录
async listDir(path: string, options?: {
  recursive?: boolean;
  includeHidden?: boolean;
  filter?: (filename: string) => boolean;
}): Promise<FileEntry[]>;

// 4. 搜索文件内容
async grep(pattern: string, options?: {
  path?: string;
  regex?: boolean;
  caseSensitive?: boolean;
  maxResults?: number;
}): Promise<GrepResult[]>;

// 5. 获取项目结构
async getTree(path?: string, options?: {
  maxDepth?: number;
  excludeDirs?: string[];
}): Promise<TreeNode>;

上下文感知能力:文件系统工具不仅仅是"读写文件",它还理解项目的上下文。

// 文件系统工具的上下文增强逻辑
async readFile(path: string) {
  const content = await this.doReadFile(path);
  
  // 自动提取 import 语句
  const imports = this.extractImports(content, path);
  
  // 为每个 import 补全相对路径
  const resolvedImports = imports.map(imp => ({
    ...imp,
    resolvedPath: this.resolveImport(imp.source, path),
  }));
  
  // 读取被引用的文件(只读前几行,用于理解上下文)
  const contextFiles = await Promise.all(
    resolvedImports
      .filter(imp => !imp.node_modules)
      .map(imp => this.doReadFile(imp.resolvedPath, { lines: 30 }))
  );
  
  return {
    content,
    imports: resolvedImports,
    context: contextFiles,
    projectRoot: this.findProjectRoot(path),
  };
}

Shell 工具详解

Shell 工具让 Agent 能够在真实的终端环境中执行命令。这是 AI 编程辅助工具的"最后一公里"——代码写得再好,如果不能实际运行和测试,就永远不知道对不对。

interface ShellTool {
  execute(command: string, options?: {
    cwd?: string;
    timeout?: number;
    env?: Record<string, string>;
  }): Promise<ShellResult>;
  
  pipeline(commands: string[], options?: ShellOptions): Promise<ShellResult[]>;
  getStatus(): Promise<ShellStatus>;
  kill(processId: number): Promise<void>;
}

安全策略:Shell 工具是 DSH 中最需要安全策略的工具,通过多层防护来确保安全性:

// 第一层:命令白名单
const ALLOWED_COMMANDS = new Set([
  'git', 'npm', 'npx', 'pnpm', 'yarn', 'bun',
  'node', 'python', 'python3', 'cargo', 'go', 'rustc',
  'docker', 'docker-compose', 'kubectl',
  'eslint', 'ruff', 'mypy', 'gofmt', 'rustfmt',
  'make', 'cmake', 'gcc', 'g++',
]);

// 第二层:危险模式匹配
const DANGEROUS_PATTERNS = [
  /^rm\s+-rf\s+\//,
  /^rm\s+-rf\s+\*\s*$/,
  /;\s*rm\s+/,
  /\|\s*rm\s+/,
  /^dd\s+/,
  /:\(\)\{:\|:&\};:/,
  /^curl\s+.*\|\s*sh$/,
  /wget.*\|\s*sh$/,
  /eval\s+\$/,
  /exec\s+/,
];

// 第三层:执行前检查
async function preExecuteCheck(command: string): Promise<boolean> {
  const cmdName = command.trim().split(/\s+/)[0];
  
  if (!ALLOWED_COMMANDS.has(cmdName)) {
    throw new SecurityError(`Command not in whitelist: ${cmdName}`);
  }
  
  for (const pattern of DANGEROUS_PATTERNS) {
    if (pattern.test(command)) {
      throw new SecurityError(`Dangerous pattern detected: ${command}`);
    }
  }
  
  return true;
}

2.3 Agent Loop(智能体决策循环)

什么是 Agent Loop?

在传统 Agent 框架中,Agent Loop 通常是一个"硬编码的黑箱":用户给一个任务,模型生成一系列工具调用,系统执行工具调用,结果返回给模型,模型再生成下一轮调用……直到任务完成或者达到某个终止条件。

DSH 的 Agent Loop 本身也是一个插件,这意味着:你可以完全自定义 Agent 的决策策略。

默认的 Agent Loop 实现了一个标准的 ReAct(Reasoning + Acting)模式:

class DefaultAgentLoop implements AgentLoopPlugin {
  private maxIterations = 50;
  
  async run(task: Task, ctx: AgentContext): Promise<AgentResult> {
    const history: ConversationTurn[] = [];
    let iteration = 0;
    let context = await this.buildInitialContext(task, ctx);
    
    while (iteration < this.maxIterations) {
      iteration++;
      
      // 阶段一:推理
      const reasoning = await this.reason(context, history);
      
      // 阶段二:决定行动
      const action = await this.decideAction(reasoning, context);
      
      if (action.type === 'final_answer') {
        return { success: true, result: action.content };
      }
      
      // 阶段三:执行工具
      const toolResult = await this.executeTool(action, ctx);
      
      // 阶段四:记录历史
      history.push({ iteration, reasoning, action, result: toolResult });
      
      // 阶段五:更新上下文
      context = await this.updateContext(context, toolResult);
      
      // 阶段六:检查终止条件
      if (this.shouldTerminate(reasoning, toolResult)) break;
    }
    
    return { success: false, reason: 'max_iterations_reached', history };
  }
  
  private async reason(context: Context, history: ConversationTurn[]) {
    const prompt = buildReasoningPrompt(context, history);
    return this.parseReasoning(await this.model.generate(prompt));
  }
  
  private async decideAction(reasoning: Reasoning, context: Context) {
    const prompt = buildActionPrompt(reasoning, context);
    return this.parseAction(await this.model.generate(prompt));
  }
  
  private async executeTool(action: Action, ctx: AgentContext) {
    const tool = ctx.tools.get(action.toolName);
    if (!tool) return { error: `Tool not found: ${action.toolName}` };
    try {
      return { success: true, data: await tool.execute(action.parameters, ctx) };
    } catch (err) {
      return { success: false, error: err.message };
    }
  }
}

可定制化的决策策略

// 保守型 Agent Loop(每次执行前都需要确认)
class ConservativeAgentLoop implements AgentLoopPlugin {
  name = 'conservative-agent-loop';
  async run(task: Task, ctx: AgentContext) {
    ctx.security.setApprovalMode('always');
    return new DefaultAgentLoop().run(task, ctx);
  }
}

// 批量执行型 Agent Loop
class BatchAgentLoop implements AgentLoopPlugin {
  name = 'batch-agent-loop';
  private batchSize = 5;
  async run(task: Task, ctx: AgentContext) {
    // 积累 batchSize 条调用后一起执行,减少往返次数
  }
}

2.4 上下文管理(Context Management)

DSH 的上下文管理采用了分层架构,将上下文分为四个层级:

interface LayeredContext {
  // L0: 原始日志层
  rawLog: ToolCallRecord[];
  
  // L1: 结构化摘要层
  structuredSummary: {
    filesModified: string[];
    commandsExecuted: string[];
    errorsEncountered: ErrorRecord[];
    decisionsMade: Decision[];
  };
  
  // L2: 语义记忆层
  semanticMemory: {
    embeddings: VectorEmbedding[];
    retrieval: (query: string, topK: number) => Promise<MemoryEntry[]>;
  };
  
  // L3: 用户画像层
  userProfile: {
    preferences: UserPreference[];
    projectContext: ProjectContext;
    codingStyle: CodingStyle;
  };
}

这个分层设计的核心思想是:不同层级的信息有不同的用途,也需要不同的管理策略。 L0 层保留所有原始信息(最全但最占空间),L3 层只保留最精炼的摘要(最节省空间但可能丢失细节)。


三、插件生态与实战

3.1 内置插件一览

插件功能状态
@dsh/plugin-filesystem文件系统读写、搜索、Tree内置
@dsh/plugin-shell终端命令执行内置
@dsh/plugin-web网页抓取、联网搜索内置
@dsh/plugin-code-toolsESLint、Ruff、Formatter内置
@dsh/plugin-sub-agent子 Agent 协作内置
@dsh/plugin-storage-filesystem本地文件系统存储内置
@dsh/plugin-security-default默认安全策略内置

3.2 实战:构建一个代码审查 Agent

场景:构建一个代码审查 Agent,能够:

  1. 理解项目结构和代码风格
  2. 读取 pull request 中变更的文件
  3. 运行 linter 检查代码质量
  4. 针对每个问题给出具体的修改建议
// review-agent.ts - 代码审查 Agent 配置
import { defineConfig } from '@deepseek-ai/dsh';
import { FileSystemTool } from '@dsh/plugin-filesystem';
import { ShellTool } from '@dsh/plugin-shell';
import { WebTool } from '@dsh/plugin-web';
import { CodeToolsPlugin } from '@dsh/plugin-code-tools';

export default defineConfig({
  model: {
    adapter: 'deepseek-chat',
    apiKey: process.env.DEEPSEEK_API_KEY,
    model: 'deepseek-chat-v3',
    parameters: {
      temperature: 0.3,
      maxTokens: 16384,
    },
  },

  tools: [
    {
      name: 'filesystem',
      adapter: FileSystemTool,
      config: {
        rootPath: process.env.REPO_PATH || process.cwd(),
        allowedExtensions: ['.ts', '.js', '.tsx', '.jsx', '.py', '.go', '.rs'],
        maxFileSize: 5 * 1024 * 1024,
      },
    },
    {
      name: 'shell',
      adapter: ShellTool,
      config: {
        workingDirectory: process.env.REPO_PATH || process.cwd(),
        timeout: 60000,
        allowedCommands: ['git', 'npm', 'pnpm', 'yarn', 'eslint', 'ruff', 'mypy', 'go vet', 'cargo clippy'],
      },
    },
    {
      name: 'web',
      adapter: WebTool,
      config: { timeout: 10000, maxContentLength: 512 * 1024 },
    },
    {
      name: 'code-analysis',
      adapter: CodeToolsPlugin,
      config: { linters: ['eslint', 'ruff'], autoFix: false },
    },
  ],

  security: {
    adapter: 'default',
    config: {
      allowNetwork: true,
      allowFileWrite: false,
      allowCommandExecution: true,
      auditLog: true,
    },
  },
});

自定义代码审查逻辑

// 自定义代码审查 Agent Loop
import { AgentLoopPlugin } from '@deepseek-ai/dsh';

class CodeReviewAgentLoop extends AgentLoopPlugin {
  name = 'code-review-loop';
  
  async run(task: Task, ctx: AgentContext) {
    const results: ReviewResult[] = [];
    
    // 1. 获取 PR 变更的文件列表
    const changedFiles = await this.getChangedFiles(ctx);
    console.log(`Reviewing ${changedFiles.length} files...`);
    
    for (const file of changedFiles) {
      const diff = await this.getFileDiff(file, ctx);
      const linterResults = await this.runLinter(file, ctx);
      const analysis = await this.analyzeCode(file, diff, linterResults, ctx);
      results.push(analysis);
    }
    
    return { success: true, result: this.generateReport(results) };
  }
  
  private async getChangedFiles(ctx: AgentContext) {
    const shell = ctx.tools.get('shell');
    const result = await shell.execute(`git diff --name-only origin/main...HEAD`);
    return result.stdout.split('\n').filter(f => f.trim() && /\.(ts|js|tsx|jsx|py|go|rs)$/.test(f));
  }
  
  private async getFileDiff(file: string, ctx: AgentContext) {
    const shell = ctx.tools.get('shell');
    return (await shell.execute(`git diff origin/main...HEAD -- "${file}"`)).stdout;
  }
  
  private async analyzeCode(file: string, diff: string, linterResults: any[], ctx: AgentContext) {
    const prompt = `
## 文件:${file}

## 代码变更:
\`\`\`diff
${diff}
\`\`\`

## Linter 检测结果:
${linterResults.map(r => `- ${r.rule}: ${r.message} (line ${r.line})`).join('\n')}

## 审查要求:
请从以下几个维度对该代码变更进行深度审查:
1. **正确性**:逻辑是否正确?边界条件是否处理?
2. **安全性**:是否有潜在的安全漏洞(如 SQL 注入、XSS、敏感信息泄露)?
3. **性能**:是否有明显的性能问题?
4. **可维护性**:代码是否清晰易读?命名是否规范?
5. **测试覆盖**:新增逻辑是否有对应的测试?

请为每个发现的问题提供:问题描述、严重程度、具体代码位置、修改建议。
`;

    const response = await ctx.model.generate(prompt);
    return { file, analysis: response, issues: this.parseIssues(response) };
  }
  
  private generateReport(results: ReviewResult[]) {
    const critical = results.flatMap(r => r.issues.filter(i => i.severity === 'Critical'));
    const major = results.flatMap(r => r.issues.filter(i => i.severity === 'Major'));
    
    return `# 代码审查报告

## 概览
- 审查文件数:${results.length}
- Critical 问题:${critical.length}
- Major 问题:${major.length}

## Critical 问题(必须修复)
${critical.map(i => `- [${i.file}:${i.line}] ${i.description}`).join('\n')}

## Major 问题(强烈建议修复)
${major.map(i => `- [${i.file}:${i.line}] ${i.description}`).join('\n')}

## 详细分析
${results.map(r => `### ${r.file}\n\n${r.analysis}`).join('\n\n')}
    `.trim();
  }
}

3.3 实战:多 Agent 协作

DSH 支持多 Agent 协作,不同的 Agent 可以扮演不同的角色:

// 多 Agent 协作示例:构建一个 AI 编程团队
const architectAgent = new SubAgent({
  name: 'architect',
  role: '系统架构师',
  prompt: `你是一位资深系统架构师,擅长设计可扩展、高性能的分布式系统。
当用户描述需求时,你需要:分析可行性、设计架构、识别风险、输出架构文档。`,
});

const coderAgent = new SubAgent({
  name: 'coder',
  role: '后端开发工程师',
  prompt: `你是一位经验丰富的后端开发工程师,精通 Go、Python、TypeScript。
你需要根据架构设计文档实现代码,确保正确性、错误处理、测试覆盖、编码规范。`,
});

const reviewerAgent = new SubAgent({
  name: 'reviewer',
  role: '代码审查员',
  prompt: `你是一位严格的代码审查员。
你会检查:正确性、安全性、性能、可维护性、测试覆盖率。`,
});

export default defineConfig({
  model: { adapter: 'deepseek-chat', apiKey: process.env.DEEPSEEK_API_KEY },
  tools: [
    { name: 'filesystem', adapter: FileSystemTool, config: { rootPath: process.cwd() } },
    { name: 'shell', adapter: ShellTool, config: { timeout: 60000 } },
  ],
  agentTeam: {
    agents: [architectAgent, coderAgent, reviewerAgent],
    workflow: `
      1. [User] 描述需求
      2. [Architect] 分析需求,输出架构设计
      3. [Coder] 根据架构设计实现代码
      4. [Reviewer] 审查代码,输出审查报告
      5. [Coder] 根据审查意见修复问题
      6. [Reviewer] 复审,通过则结束
    `,
    strategy: 'sequential',
  },
});

四、性能优化与生产部署

4.1 上下文窗口优化

技巧一:智能文件采样

// 智能文件采样策略
async function smartRead(file: string, task: string) {
  const grepResult = await grep(task, { path: file });
  
  if (grepResult.matches.length === 0) {
    return {
      header: await readLines(file, { from: 1, count: 30 }),
      footer: await readLines(file, { from: -30, count: 30 }),
      sampling: 'header_footer_only',
    };
  }
  
  const relevantRanges = grepResult.matches.map(m => ({
    start: Math.max(1, m.line - 10),
    end: m.line + 10,
  }));
  
  const mergedRanges = mergeRanges(relevantRanges);
  const relevantContent = await Promise.all(
    mergedRanges.map(range => readLines(file, range))
  );
  
  return {
    content: relevantContent.join('\n...\n'),
    sampling: 'relevant_ranges_only',
    totalLines: await countLines(file),
    readLines: mergedRanges.reduce((sum, r) => sum + r.end - r.start + 1, 0),
  };
}

技巧二:增量上下文更新

class IncrementalContextManager {
  private previousContext: Context | null = null;
  private previousHash: string = '';
  
  async buildContext(task: Task, tools: Tool[]): Promise<Context> {
    const currentStateHash = await this.computeStateHash(tools);
    
    if (currentStateHash === this.previousHash && this.previousContext) {
      return this.previousContext;
    }
    
    const baseContext = this.previousContext || await this.buildBaseContext(task);
    const delta = await this.computeDelta(tools, baseContext);
    const newContext = this.mergeContext(baseContext, delta);
    
    this.previousContext = newContext;
    this.previousHash = currentStateHash;
    
    return newContext;
  }
}

4.2 工具调用效率优化

并行工具调用

// 并行执行多个独立的文件读取
const independentReads = [
  { tool: 'filesystem', method: 'readFile', params: { path: 'src/a.ts' } },
  { tool: 'filesystem', method: 'readFile', params: { path: 'src/b.ts' } },
  { tool: 'filesystem', method: 'readFile', params: { path: 'src/c.ts' } },
];
const results = await ctx.tools.executeParallel(independentReads);

智能重试机制

const toolConfig = {
  name: 'web',
  adapter: WebTool,
  config: {
    timeout: 10000,
    retries: 3,
    retryDelay: 1000,
    retryBackoff: 'exponential',
  },
};

4.3 生产部署建议

# Dockerfile
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY dsh.config.ts ./
COPY plugins/ ./plugins/
CMD ["npx", "@deepseek-ai/dsh", "start", "--config", "dsh.config.ts"]
// 资源限制配置
export default defineConfig({
  resourceLimits: {
    maxMemoryMB: 512,
    maxCPUPercent: 80,
    maxConcurrentTools: 3,
    maxShellTimeout: 120000,
    maxFileSize: 50 * 1024 * 1024,
  },
  audit: {
    enabled: true,
    outputDir: './logs/audit',
    retentionDays: 30,
    logLevel: 'info',
  },
});

五、DSH vs. 竞品对比

维度DeepSeek HarnessClaude CodeCodexLangChain Agents
架构哲学插件化,一切皆可替换整体式,内置工作流API 服务化模块化但耦合度较高
底层引擎Cordis(自研微内核)专用 Agent RuntimeOpenAI 平台集成LangChain 核心库
插件生态官方 + 社区(早期)官方插件为主MCP 协议扩展丰富的第三方集成
上下文管理四层渐进式滚动上下文窗口Token 预算管理多种 Memory 实现
安全策略插件化安全策略内置安全过滤OpenAI 安全策略可配置但非核心
多 Agent 协作原生支持有限的 Sub-agents不支持支持但实现复杂
开源程度完整开源(MIT)闭源闭源Apache 2.0
模型兼容性全模型(以 DeepSeek 为主)仅 Claude仅 OpenAI 模型全模型
学习曲线中等(需要理解插件概念)低(开箱即用)低(API 调用)较高(概念较多)

DSH 的核心差异化优势

  1. 插件化架构最彻底:Claude Code 和 Codex 的插件系统相对封闭,而 DSH 的插件系统是真正开放的可插拔架构。

  2. 上下文管理最精细:四层渐进式上下文管理是 DSH 的独门绝技,在处理大型代码库时能显著提升上下文效率。

  3. Cordis 微内核设计:借鉴操作系统领域的微内核思想,将核心功能压缩到最小,其余全部外置。

DSH 的短板

  1. 生态早期:发布仅几天,插件生态还不够丰富。
  2. 文档不完善:官方文档还在快速迭代中。
  3. Cordis 论文尚未完全公开:88 页的 Cordis 范式论文虽然发布了,但要完全理解需要深入阅读。

六、总结与展望

6.1 DSH 的意义

DeepSeek Harness 的发布,不仅仅是"又多了一个 Agent 框架"这么简单。它代表了一种新的 Agent 架构思路:从"框架提供能力"到"用户按需组装能力"。

过去两年,我们见过太多 Agent 框架——它们功能强大、界面漂亮,但当你想要做一点"框架没有预设"的事情时,就会发现处处受限。DSH 用"一切皆插件"的哲学,从根本上解决了这个问题。

6.2 未来展望

  1. 更丰富的官方插件:预计官方会陆续发布更多工具插件(数据库操作、云服务集成等)。

  2. Cordis 论文的完整公开:会有更多基于 Cordis 的衍生项目出现。

  3. 插件市场:参考 VS Code 的插件生态,预计会有官方插件市场。

  4. 企业级功能:审计、权限管理、多租户等功能正在规划中。

  5. 性能优化:Cordis 消息总线在高并发场景下还有优化空间。

6.3 给开发者的建议

对于普通开发者:先用 DSH 官方提供的开箱即用配置体验一下,感受"真正的 Agent 能做什么"。

对于深度定制开发者:认真读一下 Cordis 的论文,理解微内核设计的思路。

对于框架开发者:DSH 的插件系统设计非常值得借鉴。"一切皆可替换"的设计哲学在很多场景下都是好的架构选择。

AI Agent 的发展才刚刚开始。DeepSeek Harness 的出现,让我们看到了一个可能的方向:不是给开发者一个"更智能的模型",而是给开发者一个"更开放的舞台"。 当框架足够灵活,当插件生态足够丰富,每个开发者都可以构建出符合自己需求的 Agent——这才是 AI Agent 的正确打开方式。


参考资料

  • DeepSeek Harness GitHub:https://github.com/deepseek-ai/deepseek-harness
  • Cordis 范式论文(同期发布)
  • DeepSeek 官方文档:https://huggingface.co/deepseek-ai/DeepSeek-Harness

推荐文章

Rust 并发执行异步操作
2024-11-19 08:16:42 +0800 CST
Java环境中使用Elasticsearch
2024-11-18 22:46:32 +0800 CST
SQL常用优化的技巧
2024-11-18 15:56:06 +0800 CST
Linux 网站访问日志分析脚本
2024-11-18 19:58:45 +0800 CST
Go 协程上下文切换的代价
2024-11-19 09:32:28 +0800 CST
Nginx 反向代理 Redis 服务
2024-11-19 09:41:21 +0800 CST
前端代码规范 - Commit 提交规范
2024-11-18 10:18:08 +0800 CST
`Blob` 与 `File` 的关系
2025-05-11 23:45:58 +0800 CST
git使用笔记
2024-11-18 18:17:44 +0800 CST
程序员茄子在线接单