一、先理解:Cordis Loader 到底是什么?
在 DeepSeek Harness(以下简称 DSH)中,Cordis Loader 是整个插件系统的加载器,也是插件运行时的组装器。
如果你已经理解了 Cordis 的 Context、Service、Plugin、Fiber,那么理解 Loader 就容易很多。
先记住一句话:
Cordis 负责管理插件的生命周期和服务依赖;Loader 负责根据配置文件找到插件、加载插件、解析配置,并把它们交给 Cordis 管理。
两者不是同一个东西。
举个例子,假设你要开发一个 Agent 系统,需要下面这些能力:
LLM:调用大模型。
Tools:管理工具。
Sessions:管理会话。
Bash:执行命令。
AgentLoop:驱动 Agent 执行循环。
WebServer:提供 Web 服务。
如果没有 Loader,你可能需要手动编写:
const ctx = new Context()
ctx.plugin(LLM)
ctx.plugin(Tools)
ctx.plugin(Sessions)
ctx.plugin(Bash)
ctx.plugin(AgentLoop)
ctx.plugin(WebServer)随着项目越来越大,你会遇到很多问题:
插件越来越多,手动维护加载代码很麻烦。
不同 Profile 需要加载不同的插件。
插件有依赖关系,不能随意启动。
插件需要配置参数。
有些插件需要根据环境变量决定是否启用。
插件可能需要运行时动态添加、删除或修改。
配置文件可能包含其他配置文件,需要递归加载。
Loader 就是为了解决这些问题而存在的。
例如,DSH 可以通过配置文件描述整个应用:
- name: '@deepseek-ai/dsh-llm'
config:
model: deepseek-chat
- name: '@deepseek-ai/dsh-tools'
- name: '@deepseek-ai/dsh-sessions'
- name: '@deepseek-ai/dsh-agent-loop'
- name: '@deepseek-ai/dsh-host-webserver'
config:
port: 3080Loader 读取这些配置,找到对应的插件模块,解析配置,然后让 Cordis 完成插件实例化、依赖注入和生命周期管理。
因此,你可以把它们理解成:
模块 | 主要职责 |
cordis | 插件运行时、Context、Service、依赖管理、生命周期 |
cordis-plugin-loader | 插件发现、模块加载、配置解析、插件树管理 |
cordis-plugin-include | 配置组合、嵌套配置、补丁处理 |
cordis-plugin-group | 插件分组、服务隔离 |
DSH app-boot | 将上述能力组织起来,启动 DSH Profile |
这里有一个非常重要的认识:
Loader 并不负责实现 LLM、Bash、AgentLoop 等业务能力,它只负责把这些能力按照配置组装起来。
官方源码中,Loader 来自:
vendor/loader/
核心文件是:
vendor/loader/src/index.tsvendor/loader/src/config/entry.tsvendor/loader/src/config/tree.tsvendor/loader/src/config/group.tsvendor/loader/src/config/isolate.tsvendor/loader/src/config/utils.tsvendor/loader/src/resolve.ts
此外,DSH 启动过程还会经过:
packages/boot/app-boot/src/index.ts
下面我们按照真实的执行过程,从配置文件开始,一步一步拆解。
二、先建立一个整体认识:Loader 在整个架构中的位置
先看一下整个关系。
cordis.yml / cordis.patch.yml
声明需要加载哪些插件,以及每个插件的配置
Loader
读取配置、构建插件树、解析插件模块、协调加载
Cordis Context
接收插件,管理插件实例和服务依赖
各个 Plugin / Service
LLM
Tools
Sessions
AgentLoop
Bash / WebServer / 其他插件
这里有一个容易产生的误解:
Loader 并不是一个简单的 import() 封装。
它还有配置树、插件条目、依赖等待、动态更新、分组隔离等机制。
要真正理解它,我们需要先认识三个核心对象:
Entry:一个插件配置项。
EntryTree:插件配置树。
Loader:负责驱动这棵树的加载器。
三、三个核心对象:Entry、EntryTree、Loader
这三个概念是理解 Loader 源码的关键。
3.1 Entry:一个插件配置项
先看一个配置:
- id: llm
name: '@deepseek-ai/dsh-llm'
config:
model: deepseek-chat
- id: tools
name: '@deepseek-ai/dsh-tools'Loader 并不会把 YAML 中的每一行直接当成 Cordis 插件。
它首先会将每一行转化成一个 Entry 对象。
你可以把 Entry 理解为:
一个插件在 Loader 中的登记信息,以及它在运行时对应的管理对象。
源码:
vendor/loader/src/config/entry.ts
主要结构可以简化成:
export class Entry {
public ctx: Context
public fiber?: Fiber
public moduleNamespace: unknown
public parent!: EntryGroup
public options = {} as EntryOptions
public subgroup?: EntryGroup
public subtree?: EntryTree
constructor(public loader: Loader) {
this.ctx = loader.ctx.extend({
[Entry.key]: this
})
}
}我们逐个理解。
① options:插件的配置
例如:
{
id: 'llm',
name: '@deepseek-ai/dsh-llm',
config: {
model: 'deepseek-chat'
}
}这里保存了插件的标识、模块名称、配置参数等。
EntryOptions 在源码中主要有以下字段:
字段 | 作用 |
id | 插件条目的唯一标识 |
name | 要加载的插件模块 |
config | 传递给插件的配置 |
group | 是否作为插件分组 |
disabled | 是否禁用 |
inject | 需要的服务依赖 |
注意:id 和 name 并不是一回事。
例如:
- id: llm-provider
name: '@deepseek-ai/dsh-llm'id是 Loader 用来管理这个条目的标识。name是 Loader 用来找到插件模块的名称。
你可以在一个应用中加载同一个插件的多个实例,只要它们的 Entry ID 不同,并且相应的服务隔离和依赖配置允许这样做。
② ctx:插件对应的 Context
这一句非常重要:
this.ctx = loader.ctx.extend({
[Entry.key]: this
})你之前研究过 Cordis 的 Context 和 Fiber。
这里可以理解为:
Loader 为每一个 Entry 创建一个扩展 Context。
为什么不直接使用全局 Context?
因为每个插件都需要有自己的运行上下文:
知道自己属于哪个 Entry。
可以获得父级 Context 提供的服务。
可以在自己的 Context 中注册服务。
可以管理自己的 Fiber 和生命周期。
注意,extend() 不等于创建了一个完全隔离的运行时。Context 之间仍然存在继承关系,是否隔离某个服务还要看 Cordis 的服务解析和 Group/Isolate 机制。
③ fiber:插件真正运行后的生命周期对象
这是最重要的字段:
public fiber?: Fiber为什么是可选的?
因为 Entry 可以先被创建,但插件还没有成功启动。
例如:
Entry 创建
|
| fiber = undefined
|
v
导入插件模块
|
v
Cordis 启动插件
|
v
Fiber 创建因此:
Entry 代表插件的配置和管理记录。
Fiber 代表插件在 Cordis 中实际运行的生命周期实例。
这两个东西一定要区分开。
举个例子:
const entry = new Entry(loader)
// 此时只是有了一个 Entry
console.log(entry.fiber) // undefined当 Loader 完成插件加载之后,才会有对应的 Fiber。
④ moduleNamespace:保存模块导入结果
例如:
const moduleNamespace = await import('./my-plugin.ts')得到的模块对象就是原始模块命名空间。
Loader 会保存它,以便在模块热更新等场景中管理模块状态。
3.2 EntryTree:为什么还需要一棵树?
如果只有 Entry,我们可以管理单个插件。
但是 DSH 的配置不是只有一层。
例如:
- id: base
name: 'some-base-plugin'
- id: group-a
name: 'cordis:group'
group: true
config:
- id: llm
name: '@deepseek-ai/dsh-llm'
- id: tools
name: '@deepseek-ai/dsh-tools'
- id: agent
name: '@deepseek-ai/dsh-agent-loop'这里出现了嵌套配置。
我们不能只用一个简单数组管理所有插件,因为它们之间存在父子关系。
因此,Loader 引入了 EntryTree。
源码:
vendor/loader/src/config/tree.ts
核心结构:
export abstract class EntryTree {
public ctx: Context
public root: EntryGroup
public store: Dict<Entry> = Object.create(null)
constructor(ctx: Context) {
this.ctx = ctx.extend({
baseUrl: ctx.baseUrl
})
this.root = new EntryGroup(this.ctx, this)
const entry = this.ctx.fiber.entry
if (entry) entry.subtree = this
}
}我们看三个属性。
① root:树的根节点
public root: EntryGroupEntryGroup 是 EntryTree 中的一组插件配置。
可以把它想象成一个文件夹。
例如:
EntryTree
│
└── root
│
├── Entry: base
│
├── Entry: group-a
│
└── Entry: agent这里 root 管理第一层的 Entry。
② store:保存 Entry 实例
public store: Dict<Entry> = Object.create(null)假设有三个 Entry:
store = {
'base': Entry实例,
'group-a': Entry实例,
'agent': Entry实例
}为什么还需要 store?
因为 Loader 后续需要根据 ID 查找、更新、删除插件。
例如:
const entry = loader.resolve('group-a:llm')这样就可以找到嵌套分组中的插件。
③ subtree:子树
if (entry) entry.subtree = this这句说明:
如果当前 EntryTree 是在某个 Entry 对应的上下文中创建的,那么它会成为这个 Entry 的子树。
例如:
根 EntryTree
│
├── Entry: base
│
├── Entry: group-a
│ │
│ └── 子 EntryTree
│ │
│ ├── Entry: llm
│ └── Entry: tools
│
└── Entry: agent这就是为什么它叫 EntryTree,而不是简单的 EntryList。
④ 为什么 EntryTree 还有 await()?
源码:
getTasks() {
return [...this.entries()]
.map(entry => entry._initTask || entry.fiber?.inertia)
.filter(isNonNullable)
}
async await() {
while (true) {
const tasks = this.getTasks()
if (!tasks.length) return
await Promise.allSettled(tasks)
}
}这段代码值得认真理解。
假设 Loader 同时启动了三个插件:
插件 A:正在导入模块
插件 B:正在执行初始化
插件 C:正在等待依赖服务这时如果只等待一次 Promise.allSettled(),可能还不够。
因为在等待期间,某个插件可能又创建了新的 Entry,进而产生新的初始化任务。
所以源码采用了循环:
收集当前所有任务。
等待这些任务完成。
再次收集任务。
如果没有任务了,才结束。
这保证了 Loader 等待的不只是最初那一批插件,还包括加载过程中产生的嵌套任务。
源码位置:vendor/loader/src/config/tree.ts,entries()、getTasks()、await()。
GitHub+1
3.3 Loader:真正负责调度的对象
现在再来看 Loader。
源码:
vendor/loader/src/index.ts
核心定义:
export class Loader extends EntryTree {
public name = 'loader'
public internal = ModuleLoader.fromInternal()
public builtins: Dict<any> = Object.create(null)
constructor(
ctx: Context,
public config: Loader.Config = {}
) {
super(ctx)
// ...
}
}这里有一个很值得注意的设计:
export class Loader extends EntryTreeLoader 本身继承 EntryTree。
也就是说:
Loader 自己就是一棵 EntryTree,同时它又负责管理这棵树中的 Entry。
为什么要这样设计?
因为根级插件和嵌套插件可以使用相同的管理模型。
根级插件:
Loader
└── Root EntryTree
├── Entry A
├── Entry B
└── Entry C嵌套插件:
Entry B
└── Subtree
├── Entry D
└── Entry E这样就不需要为根级插件和嵌套插件分别实现两套加载机制。
Loader 如何注册为 Cordis Service?
看构造函数中的这一句:
ctx.reflect.provide('loader', this, this[Service.check])这非常关键。
它的含义是:
Loader 将自身作为 loader 服务提供给 Cordis。
因此其他插件可以通过:
ctx.loader访问 Loader。
也可以通过:
ctx.get('loader')获取对应服务。
这里不要误解为 Loader 是通过 cordis.yml 中的某一行普通插件配置创建的。
在 DSH 的启动过程中,Loader 是启动基础设施的一部分,先于它所负责加载的插件树使用。
另外,Loader 构造函数还会安装一些 Cordis 事件监听器,例如:
ctx.on('internal/config', ...)
ctx.on('internal/commit', ...)
ctx.on('internal/update', ...)
ctx.on('internal/plugin', ...)这些监听器让 Loader 可以感知插件配置、插件更新和 Fiber 生命周期的变化。
例如 internal/plugin 监听器会将 Entry 关联到对应的 Fiber,并处理插件被销毁时的状态同步。
最后:
ctx.plugin(isolate)这里 Loader 自己也安装了一个子插件 isolate,用于配合服务隔离机制。
注意:这不代表所有业务插件都通过这个 ctx.plugin(isolate) 加载。业务插件仍然由 Entry 的加载流程管理。
源码:vendor/loader/src/index.ts,Loader 构造函数及其事件监听部分。
GitHub+1
四、最重要的部分:Loader 究竟如何加载一个插件?
前面认识了三个对象,现在开始看真正的执行过程。
我们用一个最简单的插件作为案例。
4.1 创建一个插件
假设我们编写:
hello.ts
import type { Context } from '@deepseek-ai/cordis'
export const name = 'hello'
export interface Config {
message: string
}
export function apply(
ctx: Context,
config: Config
) {
console.log('插件启动了:', config.message)
}这里定义了一个 Cordis 插件。
注意:
export function apply(ctx, config) {}apply 是插件的入口。
但我们并没有主动调用它。
接下来看看怎么让 Loader 加载它。
4.2 编写 cordis.yml
- id: hello
name: './hello.ts'
config:
message: 'Hello Cordis Loader!'这份 YAML 只是描述了:
加载哪个模块。
插件的 ID 是什么。
需要传递什么配置。
它本身不会执行 hello.ts。
执行工作由 Loader 完成。
4.3 Loader 创建 Entry
在源码中,创建 Entry 的入口之一是:
vendor/loader/src/config/tree.ts
async create(
options,
parent = null,
position = Infinity
) {
const group = this.resolveGroup(parent)
const id = group.tree.ensureId(options)
group.data.splice(position, 0, options)
group.tree.commit({
id,
group,
options
})
return group.create(options)
}这段代码可以拆成四个步骤。
第一步:确定父级分组
const group = this.resolveGroup(parent)如果没有指定 parent,就使用 root。
第二步:确定 ID
const id = group.tree.ensureId(options)如果没有 ID,就生成一个。
第三步:把配置放进分组数据
group.data.splice(position, 0, options)注意:这里放进去的还是配置对象,不是插件实例。
第四步:真正创建 Entry
return group.create(options)进入:
vendor/loader/src/config/group.ts
async create(options) {
const id = this.tree.ensureId(options)
const entry: Entry =
this.tree.store[id] ??= new Entry(this.ctx.loader)
entry.parent = this
await entry.update(options, true, true)
return entry.id
}这里发生了什么?
从 store 中查找 Entry。
如果没有,就创建一个新的 Entry。
设置 Entry 的父分组。
调用
entry.update()。
也就是说,Entry 创建之后,并不会直接执行插件,而是进入 update 生命周期。
GitHub+1
4.4 Entry.update():决定插件是否需要启动
源码:
vendor/loader/src/config/entry.ts
核心代码:
async update(
options: Partial<EntryOptions>,
create = false,
force = false
) {
const legacy = { ...this.options }
// 更新 Entry 配置
if (create) {
this.options = options as EntryOptions
} else {
// 合并更新
}
// 检查是否禁用
if (this.disabled) {
await this.fiber?.dispose()
return
}
// 检查是否已经运行
if (this.fiber?.uid) {
// 比较配置是否变化
// 必要时更新或重启
} else {
await this.init()
}
}你可以把它理解成一个状态判断器。
Entry.update() 的决策过程
Entry.update(options)
更新 Entry.options
disabled?
是
dispose 已有 Fiber
不再启动
否
检查 Fiber
是否已经运行
已运行
比较配置、必要时更新
未运行
调用 init()
这里有两个需要注意的地方。
第一,disabled 不只是一个静态布尔值,它还可能是 !!js 表达式。
第二,配置发生变化,不一定意味着整个插件必须重新启动。源码专门处理了 volatile 配置变化,后面会解释。
GitHub+1
4.5 Entry.init():真正加载插件的地方
这是整个 Loader 最值得研究的代码。
源码:
vendor/loader/src/config/entry.ts
async init() {
try {
await (this._initTask ??= this._init())
} finally {
this._initTask = undefined
}
this.fiber?.await()
.catch(() => {})
.finally(() => {
if (this.loader.getTasks().length) return
this.ctx.reflect.notify(['loader'])
})
}这里有两个重要的设计。
第一:避免同一个 Entry 重复初始化。
this._initTask ??= this._init()假设有两个地方同时要求启动同一个 Entry。
如果没有保护,就可能出现重复导入、重复创建插件实例的问题。
这里通过 _initTask 复用正在进行的初始化任务。
第二:等待 Fiber 生命周期稳定后通知依赖 Loader 的插件。
this.ctx.reflect.notify(['loader'])这和后面讨论的 Loader 依赖等待机制有关。
继续看真正执行的 _init():
private async _init() {
let moduleNamespace: unknown
try {
moduleNamespace =
await this.parent.tree.import(
this.options.name,
this.getOuterStack
)
} catch (error) {
this.ctx.logger.error(error)
return
}
const plugin =
this.loader.unwrapExports(moduleNamespace)
await this._patchContext([])
this.loader.showLog(this, 'apply')
this.fiber =
this.ctx.registry.plugin(
plugin,
this.options.config,
this.getOuterStack
)
this.moduleNamespace = moduleNamespace
}我们逐句分析。
第一步:导入插件模块
moduleNamespace =
await this.parent.tree.import(
this.options.name,
this.getOuterStack
)例如:
this.options.name = './hello.ts'Loader 根据插件名称和所属 EntryTree 的模块解析环境,找到对应文件并导入。
这里不是简单地把字符串作为文件路径处理。
因为还需要支持:
name: './hello.ts'以及:
name: '@deepseek-ai/dsh-llm'前者是相对路径,后者是包名。
Loader 还需要处理:
相对路径的基准目录。
Node 模块解析。
ESM/CJS 模块兼容。
内置插件。
错误堆栈。
相关模块:
vendor/loader/src/resolve.ts
vendor/loader/src/internal.ts
第二步:规范化模块导出
const plugin =
this.loader.unwrapExports(moduleNamespace)为什么需要这一步?
因为 JavaScript 模块可能有不同的导出形式。
例如:
export function apply(ctx) {}或者:
export default {
apply(ctx) {}
}还有编译器处理后的 ESM/CJS 互操作形式。
Loader 通过 unwrapExports() 尽量取得真正的插件对象。
它的实现:
unwrapExports(exports: any) {
if (isNullable(exports)) return exports
exports = exports.default ?? exports
if (!exports.__esModule) return exports
return exports.default ?? exports
}因此,Loader 并不是直接把 import() 返回的模块命名空间交给 Cordis,而是先规范化导出。
第三步:更新插件 Context
await this._patchContext([])这里涉及 Context 的父子关系。
Entry 创建时:
this.ctx = loader.ctx.extend({
[Entry.key]: this
})但在嵌套 Group、上下文变化、服务隔离等场景中,Entry 的 Context 还可能需要调整。
_patchContext() 会更新其 Context 原型关系,并在需要时重新检查依赖、更新 Fiber。
这就是 Loader 为什么还需要维护 loader/patch-context 事件的原因。
第四步:交给 Cordis 启动插件
最关键的一句:
this.fiber =
this.ctx.registry.plugin(
plugin,
this.options.config,
this.getOuterStack
)现在终于到了你之前经常问的:
ctx.plugin(SomePlugin)两者有什么区别?
在这个位置,Loader 没有直接写:
this.ctx.plugin(plugin)而是通过:
this.ctx.registry.plugin(...)使用 Cordis 的注册机制,并将返回的 Fiber 保存到 Entry。
这里传入三个参数:
参数 | 含义 |
plugin | 已导入并规范化的插件 |
options.config | 插件配置 |
getOuterStack | 外层加载路径,用于诊断 |
真正的插件生命周期由 Cordis 接管。
如果插件是:
export function apply(ctx, config) {
console.log(config.message)
}那么 Cordis 会在插件激活过程中调用它,而不是 Loader 自己直接调用 apply()。
这也是一个非常重要的架构边界:
Loader 决定加载什么插件,Cordis 决定如何激活这个插件。
GitHub+1
4.6 插件启动顺序:为什么不是按照 YAML 从上往下执行?
这是理解 Cordis Loader 时非常容易困惑的地方。
假设配置是:
- id: agent-loop
name: '@deepseek-ai/dsh-agent-loop'
- id: llm
name: '@deepseek-ai/dsh-llm'你可能会认为:
先启动 AgentLoop
再启动 LLM但实际上不是这样。
在 vendor/loader/src/config/group.ts 中,EntryGroup 的 update() 有这样一段代码:
async update(config: EntryOptions[]) {
const oldConfig = this.data as EntryOptions[]
this.data = config
const oldMap = Object.fromEntries(
oldConfig.map(options => [options.id, options])
)
const newMap = Object.fromEntries(
config.map(options => [options.id ?? Symbol('anonymous'), options])
)
const ids = Reflect.ownKeys({ ...oldMap, ...newMap })
await Promise.all(ids.map(async (id) => {
if (newMap[id]) {
await this.create(newMap[id]).catch(error => {
this.ctx.logger.error(error)
})
} else {
this.remove(id)
}
}))
}重点是:
await Promise.all(...)这说明同一个 EntryGroup 中的插件条目会并发处理。
因此,YAML 的排列顺序不代表插件启动顺序。
那么问题来了:
AgentLoop 依赖 LLM,如果 AgentLoop 先加载,怎么办?
这就涉及 Cordis 的 inject。
例如:
export const inject = [
'agents',
'sessions',
'llm',
'tools',
'systemPrompt'
]
export function apply(ctx) {
// 依赖都满足之后才会执行
}假设 AgentLoop 先开始加载,但 LLM 还没有注册。
那么:
AgentLoop 请求激活
|
v
检查 inject 依赖
|
v
发现 llm 不存在
|
v
等待 llm 服务出现
|
v
LLM 插件启动
|
v
llm 服务注册
|
v
AgentLoop 的依赖满足
|
v
AgentLoop 激活所以你应该记住:
Loader 负责并发发起插件加载,Cordis 根据 inject 依赖关系决定插件什么时候可以激活。
这也是为什么 DSH 不需要依赖 YAML 的排列顺序来维护插件启动顺序。
官方 Cordis Primer 也明确说明,插件通过 inject 声明依赖,依赖关系决定激活时机。
GitHub+2
五、配置是如何传递给插件的?!!js 又是什么?
这一部分与你之前研究的 SystemPrompt、web profile 配置有直接关系。
我们从最简单的情况开始。
5.1 普通配置
插件:
export interface Config {
model: string
temperature: number
}
export function apply(ctx, config: Config) {
console.log(config.model)
console.log(config.temperature)
}配置文件:
- id: llm
name: '@deepseek-ai/dsh-llm'
config:
model: deepseek-chat
temperature: 0.7在 Entry 初始化时:
this.ctx.registry.plugin(
plugin,
this.options.config,
this.getOuterStack
)配置就传递给 Cordis。
但你要注意:
Loader 传递的是原始配置,真正的配置校验和运行时配置管理由 Cordis 的插件/Fiber 机制配合完成。
如果插件定义了 Config Schema,那么 Cordis 可以在激活前对配置进行验证。
例如:
import Schema from '@deepseek-ai/schemastery'
export interface Config {
model: string
}
export const Config: Schema<Config> = Schema.object({
model: Schema.string().default('deepseek-chat')
})配置错误时,可以在插件正常启动前发现问题。
5.2 !!js:为什么配置文件里可以写 JavaScript?
你之前看过 DSH 的 Web Profile 配置:
- id: webserver
name: '@deepseek-ai/dsh-host-webserver'
inject: [webStartup]
config:
host: !!js ctx.webStartup.host ?? '127.0.0.1'
port: !!js ctx.webStartup.port ?? 3080你可能会问:
YAML 不是数据格式吗?
怎么能执行:
ctx.webStartup.host这是因为 DSH 扩展了 Loader 的配置解析机制。
先看源码:
vendor/loader/src/config/utils.ts
它提供了表达式识别和求值相关的能力。
核心思想是:
YAML 文件
|
v
解析 !!js
|
v
保存 JavaScript 表达式节点
|
v
等插件需要激活时
|
v
根据对应 Context 求值
|
v
将结果传给插件注意:不是整个 YAML 文件都可以随意执行 JavaScript。
官方的配置表达式主要用于 Entry 的 config 和 disabled 字段。
5.3 为什么要等 inject 依赖满足之后再计算?
这是一个非常重要的设计。
看这个例子:
- id: web-startup
name: '@deepseek-ai/dsh-web-startup'
- id: webserver
name: '@deepseek-ai/dsh-host-webserver'
inject: [webStartup]
config:
port: !!js ctx.webStartup.port ?? 3080假设 webStartup 服务是由 web-startup 插件提供的。
如果 Loader 在启动时立即执行:
ctx.webStartup.port可能会出现:
Cannot read properties of undefined因为 WebStartup 还没有启动。
所以正确的执行逻辑是:
Loader 导入 WebServer 插件。
Cordis 检查 WebServer 的
inject。发现它依赖
webStartup。等待 WebStartup 服务注册。
WebServer 获得依赖满足的运行环境。
Loader 监听的
internal/config机制解析配置表达式。Cordis 验证配置。
执行 WebServer 的插件逻辑。
Loader 构造函数中有这样一段:
ctx.on('internal/config', (fiber, next) => {
const config = next()
if (!fiber.entry ||
fiber.parent.fiber?.entry === fiber.entry) {
return config
}
if (fiber.runtime?.callback[EntryGroup.key]) {
return config
}
return interpolate(fiber.ctx, config)
})重点:
return interpolate(fiber.ctx, config)这里使用的是:
fiber.ctx也就是插件自己的 Context,而不是简单地使用全局 Context。
因此,配置表达式可以访问当前插件 Context 中已经可用的服务。
这里还需要注意 Group:Group 本身是承载子条目的容器,不能在父级配置解析时提前把子条目的表达式求值,否则子插件尚未获得自己的依赖环境。
这就是源码中为什么特别排除 EntryGroup 的原因。
GitHub+2
5.4 再看一个完整的 Web Profile 案例
- id: web-startup
name: '@deepseek-ai/dsh-web-startup'
- id: webserver
name: '@deepseek-ai/dsh-host-webserver'
inject: [webStartup]
config:
host: !!js ctx.webStartup.host ?? '127.0.0.1'
port: !!js ctx.webStartup.port ?? 3080
tls: !!js ctx.webStartup.tlsWebServer 插件:
export const inject = ['webStartup']
export function apply(ctx, config) {
console.log('Host:', config.host)
console.log('Port:', config.port)
}假设用户启动:
dsh --profile web --port 8080WebStartup 将命令行参数转换成服务:
ctx.webStartup.port = 8080那么 WebServer 的配置表达式最终得到:
{
host: '127.0.0.1',
port: 8080,
tls: undefined
}这里最重要的是:
Loader 不需要提前知道 WebServer 的端口是多少,它只需要保证配置表达式在正确的服务依赖环境下执行。
这是一种非常灵活的配置机制。
六、Include:为什么 DSH 的配置还要再套一层?
前面我们讲的是:
- id: llm
name: '@deepseek-ai/dsh-llm'但 DSH 实际启动 Profile 时,不是简单地把 cordis.yml 的每一行直接传给 Loader。
它还有一个非常重要的插件:
@deepseek-ai/cordis-plugin-include
它的作用是:
将外部配置文件作为插件树的一部分加载,并支持配置组合和补丁。
6.1 为什么需要 Include?
假设 DSH 有一个 base bundle。
它提供:
LLM
Tools
Sessions
AgentLoop
Bash
SystemPrompt然后 Web Profile 需要额外提供:
WebServer
Web UI
WebSocket
Browser Connection如果每个 Profile 都复制一份完整配置,会产生很多重复内容。
更好的方式是:
dsh-base
|
v
基础插件配置
dsh-web-app
|
v
Web 专属补丁
profile cordis.patch.yml
|
v
用户自定义补丁最终将这些配置组合成一棵插件树。
6.2 DSH 是如何创建根 Include 的?
这里直接看:
packages/boot/app-boot/src/index.ts
关键函数:
export async function mountRootInclude(
ctx: Context,
absoluteConfigPath: string,
patches = [],
bareModuleBaseUrl?,
binName = 'dsh'
) {
// ...
const includeConfig = {
path: pathToFileURL(absoluteConfigPath).href,
...(prepared.length > 0
? { patches: prepared }
: {})
}
const rootInclude = {
id: 'include',
name: 'cordis:include',
config: includeConfig
}
const includeId = await ctx.loader.create(rootInclude)
const entry = ctx.loader.resolve(includeId)
return entry
}这段代码非常值得理解。
DSH 创建了一个特殊的 Entry:
{
id: 'include',
name: 'cordis:include',
config: {
path: '.../cordis.yml'
}
}注意:
name: cordis:include它不是普通的 npm 包名称。
它是一个内置模块标识,由 Loader 的 builtins 机制处理。
源码中:
ctx.loader.builtins.include = Include因此,当 Loader 遇到:
name: 'cordis:include'就能取得对应的 Include 插件实现。
这说明一个很重要的事实:
Include 本身也是一个 Cordis 插件,只不过它承担的是配置树的加载工作。
源码:packages/boot/app-boot/src/index.ts 中的 mountRootInclude()。
GitHub+1
6.3 Include 加载之后会发生什么?
整体结构可以理解为:
Loader
│
└── Entry: include
│
└── Include Plugin
│
└── 读取 cordis.yml
│
├── Entry: system-prompt
├── Entry: llm
├── Entry: tools
├── Entry: sessions
├── Entry: agent-loop
└── Entry: bashInclude 读取配置文件后,使用自己的 EntryGroup 管理子插件。
所以你会看到:
根 Loader
└── Include
└── 一整套业务插件这不是重复创建了两个 Loader。
而是根 Loader 中存在一个 Include Entry,Include 负责管理自己的子插件组。
它们仍然属于 Loader 的插件树体系。
七、Group 和 Isolate:Loader 为什么还要管理插件分组?
这一部分和你之前研究的服务隔离问题密切相关。
我们先看一个例子:
- id: group-a
name: 'cordis:group'
group: true
config:
- id: llm
name: '@deepseek-ai/dsh-llm'
- id: agent
name: './agent.ts'这里的 group: true 表示这个 Entry 是一个分组。
它的作用是让子插件拥有自己的管理范围。
对应源码:
vendor/loader/src/config/group.ts
export class Group extends EntryGroup {
constructor(
public ctx: Context,
public config: EntryOptions[]
) {
super(
ctx,
ctx.fiber.entry!.parent.tree
)
ctx.on('internal/update', config => {
this.update(config)
})
}
async* [Service.init]() {
yield () => this.stop()
await this.update(this.config)
}
}这里有三个重要知识点。
① Group 本身也是一个插件
export class Group extends EntryGroup它继承 EntryGroup。
而:
async* [Service.init]()表明它遵循 Cordis Service 的初始化生命周期。
所以 Group 并不是 YAML 解析器里的一个简单数据结构。
它本身也参与插件生命周期管理。
② Group 负责启动子插件
await this.update(this.config)它把配置中的子插件交给 EntryGroup 管理。
比如:
config:
- id: llm
name: '@deepseek-ai/dsh-llm'
- id: agent
name: './agent.ts'就会创建两个子 Entry。
③ Group 销毁时会销毁子插件
yield () => this.stop()这句非常重要。
它相当于向 Cordis 注册一个清理函数。
当 Group 被卸载时,会执行:
stop() {
for (const options of this.data) {
this.remove(options.id, true)
}
}最终子插件也会被卸载。
所以 Group 的生命周期可以理解为:
Group 创建
|
v
创建子插件 Entry
|
v
启动子插件
|
v
Group 正常运行
|
v
Group 被卸载
|
v
执行 stop()
|
v
卸载所有子插件Isolate 又是什么?
Group 和 Isolate 不要混为一谈。
Group 负责管理一组插件。
Isolate 负责控制特定服务在不同上下文之间的可见性和实例解析。
例如:
- id: tenant-a
name: 'cordis:group'
group: true
isolate:
database: true
config:
- id: database
name: './database-a.ts'
- id: agent
name: './agent-a.ts'你可以把它理解成:
全局 Context
|
├── Tenant A Group
│ ├── Database A
│ └── Agent A
│
└── Tenant B Group
├── Database B
└── Agent B这里要注意:仅仅有 Group 并不会自动实现完整的多租户隔离。真正的服务实例隔离还需要 Isolate、Provider 的作用域以及其他资源权限控制配合。
源码:
vendor/loader/src/config/group.tsvendor/loader/src/config/isolate.tsvendor/loader/src/index.ts
GitHub+2
八、Loader 如何实现插件的动态更新、启用和卸载?
前面讲的是启动时加载插件。
但一个成熟的插件系统不能只支持启动,还应该支持:
禁用插件。
启用插件。
修改插件配置。
删除插件。
运行时增加插件。
配置变化后重新激活插件。
Loader 也负责协调这些事情。
8.1 禁用插件:disabled
例如:
- id: bash
name: '@deepseek-ai/dsh-bash-local'
disabled: trueEntry 中有一个 disabled getter:
get disabled() {
if (this.options.group) return false
let entry: Entry | undefined = this
do {
if (this._resolveDisabled(entry.options)) {
return true
}
entry = entry.parent.ctx.fiber.entry
} while (entry)
return false
}这里有一个很重要的细节:
它不仅检查自己是否禁用,还会沿着父级 Entry 向上检查。
例如:
Group A(disabled = true)
|
├── Plugin A
|
└── Plugin B即使 Plugin A 自己的 disabled 是 false,也会因为父级 Group 被禁用而无法运行。
不过 Group 自身始终被视为可用的分组容器,子插件的有效禁用状态会受到父级影响。
再看 Entry.update():
if (this.disabled) {
await this.fiber?.dispose()
return
}如果插件已经启动,那么禁用时就会销毁对应 Fiber。
如果还没有启动,就不会执行初始化。
这就是 Loader 管理插件启用状态的基本方式。
8.2 修改配置:update
假设原来:
- id: llm
name: '@deepseek-ai/dsh-llm'
config:
model: deepseek-chat现在改成:
- id: llm
name: '@deepseek-ai/dsh-llm'
config:
model: deepseek-reasonerLoader 会调用:
entry.update({
config: {
model: 'deepseek-reasoner'
}
})然后比较新旧配置:
const changes = Object.keys({
...this.options,
...legacy
}).filter(key =>
!deepEqual(
this.options[key],
legacy[key],
key === 'config'
)
)如果配置发生变化,就会进一步判断是否需要更新 Fiber。
这里有一个很有意思的优化:
不是所有配置变化都需要卸载插件并重新启动。
8.3 Volatile:有些配置可以原地更新
这是 Loader 比较精细的一项设计。
假设插件有这样的配置:
export interface Config {
model: string
temperature: number
}其中:
model变化可能需要重新初始化。temperature如果定义成 Volatile 配置,则可以在插件运行过程中更新。
源码中有这样的判断:
const volatileOnly =
changes.length === 1 &&
changes[0] === 'config' &&
this.fiber.state === FiberState.ACTIVE &&
Object.getPrototypeOf(this.ctx) === this.parent.ctx &&
equalExceptVolatile(
legacy.config,
this.options.config,
this.fiber.runtime?.Config
)它会检查:
是否只有 config 发生变化。
插件是否处于 ACTIVE 状态。
Context 是否没有发生需要重建的变化。
普通配置是否保持不变,变化的是否仅是 Volatile 字段。
满足条件后:
this._commitVolatile()会尝试更新运行中的配置引用,并发送:
fiber.ctx.emit(
self,
'loader/volatile-update',
paths
)这样就不必为了一个普通运行时参数而重启整个插件。
这对于模型参数、运行时策略等配置非常有用。
源码:vendor/loader/src/config/entry.ts,_commitVolatile()。
GitHub+1
8.4 删除插件:remove
假设我们要删除:
- id: bash
name: '@deepseek-ai/dsh-bash-local'EntryTree 提供:
remove(id: string) {
const entry = this.resolve(id)
const group = entry.parent
const legacy = entry.options
group.remove(legacy.id)
group.tree.commit({
id: legacy.id,
group,
legacy
})
}进入 EntryGroup:
remove(id: string, isDispose = false) {
const entry = this.tree.store[id]
if (!entry || entry.parent !== this) return
delete this.tree.store[id]
entry.fiber?.dispose()
if (!isDispose) {
this.unlink(entry.options)
}
this.context.emit(
'loader/partial-dispose',
entry,
entry.options,
false
)
}你可以看到:
从 store 中删除 Entry。
销毁插件对应的 Fiber。
从配置数组中移除条目。
发送卸载事件。
这里又涉及你之前学习过的 Cordis disposer 机制。
Fiber 被销毁时,插件注册的生命周期清理逻辑也会得到执行。
所以:
ctx.effect(() => {
const dispose = ctx.tools.register({
name: 'hello'
})
return dispose
})当插件卸载时,相关工具注册也会被清理。
这就是 Loader 和 Cordis 生命周期配合的地方。
GitHub+2
九、Loader 和 HMR 是什么关系?
HMR 是 Hot Module Replacement,也就是热模块替换。
假设你修改了:
hello.ts原来:
export function apply(ctx) {
console.log('hello')
}修改后:
export function apply(ctx) {
console.log('hello world')
}如果不重新加载模块,Node.js 可能仍然使用之前的模块缓存。
因此,Loader 需要配合 HMR 机制完成插件替换。
可以理解成:
监听文件变化
|
v
发现插件模块变化
|
v
重新导入模块
|
v
处理旧插件实例
|
v
使用新模块创建插件
|
v
建立新的 Fiber但需要注意:
HMR 不等于 Loader。
它们是不同的插件系统能力。
Loader 提供 Entry、模块导入和插件生命周期管理的基础;HMR 插件负责监听变化并协调重新加载。
DSH 中还会使用:
entry.moduleNamespace保存原始模块命名空间,以支持模块更新相关操作。
另外,Loader 本身也处理了插件自我销毁、HMR 卸载和 Loader 主动卸载之间的区别。
你可以在:
vendor/loader/src/index.ts
搜索:
internal/plugin其中有一段注释专门解释:
// self-dispose:
// ctx.fiber.dispose() -> fiber / runtime dispose -> delete(plugin)
// plugin hmr:
// delete(plugin) -> runtime dispose -> fiber dispose两种方向不同,Loader 需要区分它们,避免把正常的 HMR 卸载误认为插件主动禁用。
GitHub+1
十、实际运行时:dsh --profile web 到底是如何使用 Loader 的?
现在把前面的知识串起来。
这是最有价值的部分,因为你真正想理解的是 DSH,而不是单独研究一个 Loader 库。
我们以:
dsh --profile web为例。
先明确:这里讲的是 DSH 的应用启动层如何使用 Loader,而不是说 Loader 自己负责解析命令行参数、创建 HTTP 服务或启动前端。
10.1 启动阶段
DSH 的启动代码位于:
packages/boot/app-boot/src/index.ts
这个模块承担共享启动工作。
从源码注释和 mountRootInclude() 可以确认,启动过程会处理:
.env加载。Loader 启动保护。
Profile 配置路径解析。
用户补丁层。
配置表达式的环境。
根 Include 的挂载。
10.2 创建根配置树
应用准备好 Context 和 Loader 后,通过:
await mountRootInclude(
ctx,
absoluteConfigPath,
patches
)挂载配置文件。
这时创建的是:
{
id: 'include',
name: 'cordis:include',
config: {
path: absoluteConfigPath
}
}它成为整个插件树的入口。
10.3 Include 读取配置
假设配置文件中包含:
- id: system-prompt
name: '@deepseek-ai/dsh-system-prompt'
- id: llm
name: '@deepseek-ai/dsh-llm'
- id: tools
name: '@deepseek-ai/dsh-tools'
- id: sessions
name: '@deepseek-ai/dsh-sessions'
- id: agent-loop
name: '@deepseek-ai/dsh-agent-loop'Include 将这些条目交给对应的 EntryGroup。
10.4 Loader 创建 Entry
system-prompt -> Entry
llm -> Entry
tools -> Entry
sessions -> Entry
agent-loop -> Entry每个 Entry 都会有自己的 Context。
10.5 并发导入插件
EntryGroup 使用:
Promise.all(...)并发处理各个条目。
因此,不应该认为:
先导入 system-prompt
再导入 llm
再导入 tools就是它们的实际启动顺序。
10.6 Cordis 处理依赖
例如:
export const inject = [
'agents',
'sessions',
'llm',
'tools',
'systemPrompt'
]AgentLoop 声明依赖后,Cordis 会根据依赖是否满足决定什么时候激活。
10.7 插件激活
Loader 通过:
this.ctx.registry.plugin(
plugin,
this.options.config,
this.getOuterStack
)将插件交给 Cordis。
Cordis 建立 Fiber,管理插件生命周期。
最终:
SystemPrompt Service
LLM Service
Tools Service
Sessions Service
AgentLoop Service逐步进入可用状态。
10.8 等待整棵树稳定
最后,DSH 可以通过:
await ctx.loader.await()等待 Loader 当前管理的导入和生命周期任务完成。
但要注意:
这不是等待某个 Agent 完成一次对话,而是等待插件树的加载任务稳定。
在 Web Profile 中,后续还需要 WebServer、Web Runtime、前端静态资源等相关插件完成初始化,才真正具备对外提供服务的条件。
GitHub+4
十一、自己动手:实现一个简化版 Mini Loader
如果你仍然觉得源码比较抽象,我建议你自己实现一个极简版本。
不用一开始就实现 EntryTree、Group、Isolate、HMR。
先实现最基本的三个功能:
读取插件配置。
动态导入插件。
调用 Cordis 注册插件。
下面是一个教学用的简化版本。
mini-loader.ts
import { Context } from '@deepseek-ai/cordis'
interface PluginEntry {
id: string
name: string
config?: any
disabled?: boolean
}
class MiniLoader {
private ctx: Context
constructor(ctx: Context) {
this.ctx = ctx
}
async load(entries: PluginEntry[]) {
for (const entry of entries) {
await this.loadEntry(entry)
}
}
async loadEntry(entry: PluginEntry) {
if (entry.disabled) {
return
}
// 1. 导入模块
const module = await import(entry.name)
// 2. 取得插件对象
const plugin = module.default ?? module
// 3. 交给 Cordis
const fiber = this.ctx.registry.plugin(
plugin,
entry.config
)
console.log('插件已提交给 Cordis:', entry.id)
return fiber
}
}使用:
const ctx = new Context()
const loader = new MiniLoader(ctx)
await loader.load([
{
id: 'hello',
name: './hello.ts',
config: {
message: 'Hello'
}
}
])这个 Mini Loader 已经体现了最核心的思想:
配置
|
v
Entry
|
v
import()
|
v
plugin
|
v
ctx.registry.plugin()
|
v
Fiber但它与官方 Loader 还有很大的差距。
功能 | Mini Loader | DSH Loader |
动态导入 | 有 | 有 |
插件配置 | 有 | 有 |
Entry 管理 | 简单对象 | Entry 类 |
EntryTree | 无 | 有 |
依赖等待 | 无 | Cordis inject |
配置表达式 | 无 | !!js |
Group | 无 | 有 |
Isolate | 无 | 有 |
动态更新 | 无 | 有 |
禁用和卸载 | 简单判断 | 完整生命周期 |
HMR 配合 | 无 | 有 |
配置持久化 | 无 | 支持子树扩展 |
这个练习的意义在于:你会发现,Loader 最基础的工作并不复杂。
真正让它复杂的是如何把插件的加载、配置、依赖、生命周期、动态更新组织成一个稳定的系统。
十二、学习 Loader 时最容易产生的 8 个误解
十三、建议你按照这个顺序阅读源码
如果你准备真正掌握 Cordis Loader,不建议直接从 index.ts 的第一行开始读到最后一行。
应该按照实际执行关系阅读。
第一阶段:理解数据结构
vendor/loader/src/config/entry.ts重点:Entry、EntryOptions、update、init。
目标:理解一个插件如何从配置项变成 Fiber。
vendor/loader/src/config/tree.ts重点:EntryTree、store、create、remove、resolve、await。
目标:理解插件树如何管理所有 Entry。
vendor/loader/src/config/group.ts重点:EntryGroup、Group、update、stop。
目标:理解嵌套配置和分组。
第二阶段:理解加载机制
vendor/loader/src/index.ts重点:Loader 构造函数、internal/plugin、internal/config、unwrapExports。
vendor/loader/src/resolve.ts重点:模块路径解析、包名解析。
vendor/loader/src/internal.ts重点:Node 内部模块加载兼容。
vendor/loader/src/config/utils.ts重点:
!!js表达式。
第三阶段:理解 DSH 集成
packages/boot/app-boot/src/index.ts重点:
mountRootInclude()、启动配置准备。packages/bundle/base/cordis.patch.yml重点:基础插件组合。
packages/bundle/web-app/cordis.patch.yml重点:Web 专属插件和配置表达式。
源码入口:
注意:这里参考的是 GitHub 当前 master 分支。你本地如果使用的是之前的 v0.1.1-rc.2,部分实现可能存在版本差异,阅读时要以本地源码为最终依据。
十四、最后总结:Loader 在 DSH 中到底扮演什么角色?
我用一个比喻帮助你彻底记住。
假设你正在建造一座工厂。
cordis.yml:工厂建设图纸。
Entry:图纸上登记的设备。
EntryTree:整座工厂的设备组织结构。
Loader:负责按照图纸安排设备安装、更新和拆除的管理系统。
Cordis:设备安装完成后,负责管理设备运行、服务依赖和生命周期的运行环境。
Plugin:具体设备。
Service:设备向其他设备提供的能力。
Fiber:设备在运行环境中的生命周期管理单元。
inject:设备启动前必须具备的其他设备或服务。
因此,Loader 和 Cordis 的关系可以浓缩成:
Loader 解决的是:系统应该加载哪些插件,以及这些插件如何被组织和更新。
Cordis 解决的是:插件如何被激活、如何获得依赖、如何提供服务,以及如何管理生命周期。
二者配合,DSH 才能做到:
一份配置文件
|
v
构建一棵插件树
|
v
加载所有插件
|
v
解析插件配置
|
v
满足依赖关系
|
v
激活插件
|
v
运行 Agent
|
v
动态更新、卸载和替换插件我认为你接下来最值得深入研究的不是 Loader 的更多 API,而是一个具体问题:
为什么 Entry.init() 最终调用的是:
this.ctx.registry.plugin(
plugin,
this.options.config,
this.getOuterStack
)而不是直接调用:
plugin.apply(this.ctx, this.options.config)这背后涉及 Cordis 的 Registry、Fiber、Service.init、inject、FiberState 等核心机制。
如果把这部分彻底搞懂,你就能把 Loader 和 Cordis 两套源码真正串起来,而不再只是知道它们各自做什么。