DeepSeek Harness 源码解析 · 第 7 讲
DeepSeek Harness 源码解析系列 第 7 讲:Session 管理与事件日志 基于 DeepSeek Harness 源码 · 2026-08-22 一、Session:事件溯源架构的基石 前几讲我们介绍了 Cordis 插件框架、事件系统和 Agent 生命周期。从本讲开始,我们进入第二阶段——核心运行时。Session 是 DeepSeek Harness 中最核心的数据模型之一:它不是一个简单的"对话记录",而是一个 事件溯源(Event Sourcing) 系统——所有状态变化都作为不可变事件追加到日志中,当前状态由日志推导而来。 Session 模块位于 packages/core/session/ ,包含五个源文件: 📁 Session 模块文件结构 packages/core/session/src/ ├── index.ts # Session 类 + SessionStore 服务 ├── types.ts # 事件类型定义(SessionEventMap 等) ├── surface.ts # 表面层(SurfaceManager, foldSurface) ├── json.ts # 无损 JSON 校验与快照 ├── request-header.ts # 请求头折叠 ├── preparation.ts # Session 准备/恢复 ├── repair.ts # 中断修复 ├── chunk-rows.ts # 流式分块压缩 └── known-event-types.ts # 44 种已知事件类型目录 二、Session 类的核心设计 Session 是一个普通类(不是 Cordis Service),它内部维护了一个追加-only 的事件日志。源码定义如下: 📄 packages/core/session/src/index.ts(第 425-433 行) /** * An event-sourced session: an append-only log of SessionEvents. * Plain class (not a Service) — create live instances via * ctx.sessions.create() and detached instances via create. */ export class Session { private log: SessionEvent[] = [] /** Single incremental owner of surface acceptance and projection. */ private readonly surfaceManager = new SurfaceManager(this.log) get surface(): SessionSurface { return this.surfaceManager } 注意两个关键设计决策: 🔹 log 是私有数组 ——外部无法直接修改,只能通过 append() 追加事件,保证了日志的追加-only 语义。 🔹 surfaceManager 与 log 共享引用 ——SurfaceManager 持有 log 的引用,当事件追加时,surfaceManager 能增量地更新"表面"(即模型可见的消息视图),而不需要重新遍历整个日志。 三、事件类型系统:SessionEventMap Session 的事件类型定义在 types.ts 中,使用 TypeScript 的 mapped type 构建了一个 可扩展的判别联合(discriminated union) 。这意味着插件可以通过类型声明合并(declaration merging)添加新的事件类型,而核心代码无需修改。 📄 packages/core/session/src/types.ts(第 162-220 行) /** * The merge-extensible, append-only source of truth for an agent * interaction. Message history is derived from this log. */ expo…