第 11 讲:System Prompt 组装

DeepSeek Harness 源码解析 · 第 11 讲

DeepSeek Harness 源码解析系列 第 11 讲:System Prompt 组装 基于 DeepSeek Harness 源码 · 2026-08-26 一、本节概述 前几讲我们拆解了 Agent Loop 的核心循环、工具注册表与执行管道。本节深入到 Harness 的 System Prompt 组装系统 —— SystemPrompt 服务。它负责把来自多个插件的 prompt section、动态上下文、工具 Schema 和模板变量合并成一个完整的模型请求,源码位于 packages/core/system-prompt/ 。这是模型"看到"什么内容的最终决定者: system-prompt 包文件结构 🔹 src/index.ts (545 行)— SystemPrompt 服务:注册、作用域链、组装流水线、变量插值 🔹 src/invariant.ts (61 行)— 运行时不变量:验证组装结果结构 🔹 tests/system-prompt.spec.ts (582 行)— 全面测试:内建 section、变量插值、作用域、水落流 二、System Prompt 组装的四个维度 SystemPrompt 服务管理四种独立注册的贡献: 四种 Prompt 贡献类型 🔹 PromptSection — 有序的 prompt 段落,按 order 升序排列,支持静态文本和动态函数 🔹 PromptContext — 动态运行时上下文快照,渲染为 user-role 消息注入会话历史 🔹 ToolProvider — 工具 Schema 提供者,全局和 scoped 提供者叠加 🔹 VariableProvider — 模板变量提供者,用于 {{variable}} 严格插值 三、SystemPrompt 服务:核心注册 API SystemPrompt 继承自 Cordis 的 Service 基类,通过 ScopedLayers 管理全局和 scoped 两层注册。先看服务定义与内建 section: 📄 packages/core/system-prompt/src/index.ts(第 338-371 行) /** Registry service for the prompt inputs assembled before each model step. */ export class SystemPrompt extends Service { static Config: z<Config> = z.object({ includeHarnessIdentity: z.boolean().default(true), // ↑ 是否包含 Harness 身份标识("You are an AI agent powered by DeepSeek Harness.") includeRuntimeContext: z.boolean().default(true), // ↑ 是否在模型历史中包含动态运行时上下文快照 persona: z.string().default(''), // ↑ 部署级 persona 模板文本,支持 {{variable}} 插值 // Preserve omission because an explicit empty order lacks the rest marker. toolOrder: z.array(z.string()).default(undefined as unknown as string[]), // ↑ 工具排序配置,省略时表示按字母序排列 }) private readonly layers = new ScopedLayers( scope => new PromptLayer(scope), // ↑ 为每个作用域创建独立的 PromptLayer,存储该 scope 的注册 () => { this.ctx.emit('system-prompt/change') }, // ↑ 任何注册/注销变化时触发 change 事件,通知所有监听者 ) private readonly toolOrder: string[] | unde…

阅读全文:DeepSeek Harness 源码解析 第 11 讲