[hong] Hong Blog
F2 纸面主题 ^K 快速搜索 搜索
guest@hong-blog:~/posts $ cat deepseek-harness-book-14-boot-launch.md

深入理解 DeepSeek Harness · 第 14 篇:启动链路——从命令行到插件挂载

2026-11-28 6 分钟 [AI 前沿]
从 dsh web 到插件挂载:runCli 分发、空 cordis.yml 与五层 patch、composeProfile 定序、代理与环境快照、信号所有权、required 审计,以及 --dump-config 为何能看见自己的树。

深入理解 DeepSeek Harness · 第 14 篇

启动链路:从命令行到插件挂载

前情回顾

第 13 篇讲完 Host 树如何被浏览器跨进程调用,并指出 plugin manager 自己是 Remote 服务。本篇从用户敲下 dsh web 开始,追到插件挂载与 required 审计完成,看这棵树如何真正跑起来。

本章要回答的问题

dsh web 里的 web 到底选了什么?启动顺序是硬编码还是可 patch?命令行参数怎么进插件树?--dump-config 为什么能看见自己的树?哪些失败会在启动期被拦下?

你会学到什么 / 先验知识

你会拿到完整调用链 runCli → runProfile → composeProfile → boot → mountRootInclude → applyEntryPatches → required 审计,看懂 launcher 在第一个插件挂载前提供的环境与代理快照、信号在整个启动窗口的所有权,以及参数如何以服务形式注入。先验是第 4 篇的 patch 栈、第 12 篇的 profile、第 13 篇的 Remote。

核心概念:启动即装配

[文档] docs/architecture.md:41-47 先立规矩(节选,省略 :43 关于 SDK 与 sdk-minimal 的句子):

Supported Node applications launch through named `dsh` profiles. The shipped profiles are `web`, `headless`, `sdk`, `sdk-minimal`, and `acp`, selected with `dsh --profile <name>` or `dsh <name>`. `plugin` names the management command; a profile with that name requires `--profile plugin`. The TypeScript SDK resolves its same-version `dsh` dependency and selects `sdk`; custom plugin composition remains a profile plus ordered patch files, not another executable or inline application tree.

Vendored CLIs, build-only and test-only executables, direct in-process plugin mounting, and the private browser WebWorker preview are not Harness application launchers. `verify-application-entrypoints` keeps every package bin, executable source, root demo, and the root `start:web` and `dev:web` scripts in an explicit class and rejects a Node application path that bypasses `dsh`.

没有「第二个可执行入口」:自定义组合仍然是 profile 加有序 patch 文件。这让第 4 篇的 patch 语义成为整个产品的唯一装配语。

graph TD
    A[dsh web] --> B[runCli<br/>parseDshArgs]
    B --> C{runCli mode}
    C -->|profile| D[runProfile]
    C -->|plugin| E[runPlugin]
    C -->|dump-config| F[runDumpConfig]
    D --> G[composeProfile<br/>empty root + 五层 patch]
    G --> RES[runtime resolution<br/>一次启动的不可变包解析表]
    RES --> PP[PluginPackages<br/>包查找 + 模块解析拦截<br/>非挂载服务]
    G --> H[boot<br/>mountRootInclude / applyEntryPatches]
    H --> I[required 审计<br/>auditStartupEntries]
    I --> J[ctx 稳定<br/>cmdlineArgs / profileContext / Proxy]

源码走读:五处证据

证据一:入口只做分发。 [源码] apps/cli/src/bin.ts:26-56:

export async function runCli(options: RunCliOptions = {}): Promise<void> {
  const version = getDshRuntimeVersion()
  const { manageDesktopProfile, ...profileOptions } = options
  const invocation = parseDshArgs(process.argv.slice(2), version, manageDesktopProfile)

  switch (invocation.mode) {
    case 'exit':
      process.exitCode = invocation.exitCode
      return
    case 'profile': {
      const { runProfile } = await import('./profile-boot.ts')
      try {
        await runProfile({
          environment: loadLayeredEnv('dsh'),
          profile: invocation.profile,
          fromDefaultProfile: invocation.fromDefaultProfile,
          patchFiles: invocation.patches,
          args: invocation.args,
          ...profileOptions,
        })
      } catch (error) {
        if (!(error instanceof StartupError)) throw error
        await reportStartupFailure(error, { home: resolveDshHome(), version, profile: invocation.profile })
        process.exit(1)
      }
      break
    }
    case 'plugin': {
      const { runPlugin } = await import('./plugin.ts')
      process.exitCode = await runPlugin(invocation.profile, invocation.args, options.packageManager)
      break
    }

runCli 本身不做装配:解析参数得到 invocation mode(exit / profile / plugin / dump-config 等),再按 mode 动态 import 对应分支。启动失败只在 StartupError 时走诊断报告(第 1 篇引过的 required 审计会抛这个类型),其余错误原样抛出。

证据二:从空列表开始。 [源码] apps/cli/src/profile-boot.ts:79-87:

/** The empty root entry list every profile tree patches over. */
const PROFILE_ROOT_CONFIG = `# dsh profile root — an empty entry list. The tree is composed as patches:
# each bundle in package.json's dsh.profile.bundles, then cordis.patch.yml, then any
# --patch overlays. Edit cordis.patch.yml, not this file.
[]
`

/** Root config filename inside a profile directory. */
export const PROFILE_ROOT_FILENAME = 'cordis.yml'

这就是第 4 篇「从空列表开始叠加」的物理文件:profile 目录里的 cordis.yml 内容是 [],真正的树来自 bundle 层与 patch。注释直接告诉用户「改 cordis.patch.yml,不是这个文件」。

证据三:composeProfile 定序。 [源码] apps/cli/src/profile-boot.ts:210-235:

/**
 * Load `name` and compose its effective patch stack: bundle layers in
 * `dsh.profile.bundles` order (a base-backed profile gets the base bundle's
 * platform-gated shell rows), the profile's user layer, the home-level user
 * layer (`$DSH_HOME/cordis.patch.yml` — machine-local preferences that apply
 * to every profile, so it outranks the per-profile layer), `--patch` overlays,
 * then the telemetry switch.
 ...
 */
async function composeProfile(
  name: string,
  patchFiles: readonly string[],
  fromDefaultProfile?: string,
  resolvedProfile?: ResolvedProfileRuntime,
): Promise<ComposedProfile> {
  const profile = resolvedProfile?.profile ?? prepareProfile(name, true, fromDefaultProfile)
  if (resolvedProfile !== undefined) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG)
  const resolutionOptions = { installAnchor: resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, profile }
  const resolution = await createRuntimeResolution(resolutionOptions)
  reportBundlePluginWarnings(NAME, resolution)
  return { profile, resolution, overlayPaths: patchFiles.map(file => resolve(file)) }
}

JSDoc 把五层顺序写全:bundle 层 → profile 用户层 → home 层($DSH_HOME/cordis.patch.yml,机器本地偏好,覆盖 per-profile)→ --patch → 遥测开关。注意 home 层高于 per-profile 层——这与第 4 篇引的 readProfilePatches() 实现一致。

这里出现两个术语:runtime resolution(运行时解析表)是 createRuntimeResolution() 算出的一次启动的不可变包解析表,包含安装范围里的 package name、目录、声明者与版本(packages/boot/app-boot/src/profile.ts:410-417),随后交给 PluginPackages 作为包查找与模块解析拦截服务(packages/boot/app-boot/src/profile-resolution/service.ts:59-76 的 class PluginPackages extends Service,构造器用 installRuntimeInterception(config.resolution) 安装拦截),它本身不挂载插件——真正挂载由 boot() 里的 Loader 与 mountRootInclude 完成(packages/boot/app-boot/src/index.ts:1295-1298);bundle plugin warnings 是解析时收集但只打印到 stderr、不抛错、不拦启动的告警——reportBundlePluginWarnings() 的实现只是逐条 process.stderr.write,且 launcher 每次启动只调用一次(profile.ts:121-130)。别把 warnings 误当成启动失败;真正拦启动的是 StartupError(证据一)。

证据四:runProfile 在第一个插件之前准备环境。 [源码] apps/cli/src/profile-boot.ts:281-349(节选关键段):

export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Context; shutdown: ProcessShutdown }> {
  // Model providers see which profile sent a request.
  process.env.DSH_USER_AGENT_SUFFIX = `dsh-profile/${userAgentProfile(options.profile)}`
  // Before the first plugin mounts and before anything can issue a request: Node's fetch ignores the
  // proxy environment on its own, so every profile would otherwise connect directly. Resolving from
  // the launcher's snapshot — not `process.env` — is what lets a proxy declared in a `.env` layer
  // work, which the NODE_USE_ENV_PROXY flag cannot do because Node samples the environment at start.
  const disposeProxy = await installProxyFromEnvironment(
    options.environment,
    (message) => { process.stderr.write(`${NAME}: ${message}\n`) },
  )
    // Signals own teardown throughout the startup window, not only after boot() settles:
    // an inserted provider can publish before sibling rows finish mounting.
    process.on('SIGTERM', () => { interrupt(0) })
    process.on('SIGINT', () => { interrupt(130) })
    const ctx = await boot(NAME, rootConfig, readProfilePatches(NAME, profileContext, composed.profile), async (hostCtx) => {
      app.current = hostCtx
      hostCtx.provide('profileContext', profileContext)
      // Before any config-tree entry mounts, so plugins resolve all launch-time
      // environment values from the same immutable launch snapshot.
      hostCtx.provide(DSH_LAUNCH_ENVIRONMENT_KEY, options.environment)
      await hostCtx.plugin(PluginPackages, { resolution: composed.resolution })
      // The command line and bounded exit request are launcher facts available
      // to every app plugin that injects the argument snapshot.
      provideCmdline(hostCtx, {
        args: options.args,
        exit: code => void shutdown.shutdown(code),
        ready: appReady.service,

appReady 是 launcher 自有的就绪信号:createAppReady() 返回一个 onReady(listener) 服务与 commit(),只有 boot() 与 host 设置都成功后才 commit() 并通知监听者(apps/cli/src/profile-boot.ts:42-63、:356)。它不是「插件挂完就 ready」,而是「host 可用才 ready」。

三个要点:代理必须在第一个插件挂载前从 launcher 的环境快照解析——Node 的 fetch 不自动读代理环境变量,NODE_USE_ENV_PROXY 在进程启动时就采样,救不了 .env 层声明的代理;信号在整个启动窗口拥有 teardown,因为插入的 provider 可能在兄弟行还没挂完时就发布;profileContext、启动环境快照与 cmdlineArgs 都在条目挂载前 provide 出去,让所有插件看到同一份不可变事实。

证据五:dump-config 把层摊开。 [源码] apps/cli/src/dump-config.ts:51-75:

export function collectConfigDumpLayers(
  loaded: Profile,
  defaultOnly: boolean,
  patches: readonly string[],
): ConfigDumpLayer[] {
  const layers: ConfigDumpLayer[] = loaded.layers.map(layer => ({
    label: layer.packageName,
    patches: layer.patches,
  }))
  if (!defaultOnly) {
    if (existsSync(loaded.patchPath)) {
      layers.push({ label: loaded.patchPath, patches: loaded.patches })
    }
    const homePatchFile = homePatchPath()
    const homePatches = loadOptionalPatches(NAME, homePatchFile)
    if (homePatches !== undefined) {
      layers.push({ label: homePatchFile, patches: homePatches })
    }
    for (const file of patches) {
      const absolute = resolve(file)
      layers.push({ label: absolute, patches: loadOverlayPatches(NAME, absolute) })
    }
  }
  return layers
}

--dump-config 按同样顺序把每一层连同来源标签输出:每个 bundle、profile patch、home patch、--patch 文件。第 1 篇的思考题 1 就是让读者用它找 agent-loop 行——这里给出了它的实现。boot() 内部的挂载与 required 审计已在第 1 篇引过(packages/boot/app-boot/src/index.ts:1288-1306),本篇不重复。

设计取舍

① 为什么 required 审计放在树 settle 之后? 第 1 篇已给出理由(patch 可来自四层、任意层都可能补齐服务)。本篇补一个 launcher 侧的证据:审计用的 ctx 必须是 boot() 返回的稳定根上下文,而 runProfile 在 boot 回调里还在 provide 服务——所以审计只能在回调结束、树 settle 之后做。

② 为什么代理要在第一个插件挂载前解析? 因为插件一挂载就可能发请求;Node 的 fetch 不自动读代理环境变量,NODE_USE_ENV_PROXY 在进程启动时采样,无法反映 .env 层声明的代理。代价是 launcher 必须在环境解析上做额外工作,而且要把快照 provide 给树(DSH_LAUNCH_ENVIRONMENT_KEY),不能让插件各自读 process.env。

③ 为什么信号在整个启动窗口拥有 teardown? 因为插入的 provider 可能在兄弟行还没挂完时就发布,此时 boot() 尚未返回;若只在 boot 之后注册信号处理器,这段窗口里的中断无人接管。代价是 launcher 要维护 dispose() 的幂等与聚合错误(profile-boot.ts:295-302)。

常见误解

「dsh web 是一个独立可执行文件。」 不是。web 是 profile 名,runCli 解析后走 profile 分支(bin.ts:31-51)。

「启动顺序写在启动脚本里。」 不是。空 cordis.yml 加五层 patch 决定顺序(profile-boot.ts:79-84、:210-216)。

「插件可以直接读 process.env 拿代理。」 不行。启动快照在条目挂载前 provide,插件应注入环境服务而不是各自读进程环境(profile-boot.ts:338-340)。

小结

dsh web 里的 web 选的是 profile 而非可执行文件(docs/architecture.md:43),启动顺序不是硬编码——根 cordis.yml 只有 [],五层 patch 决定树的形状(apps/cli/src/profile-boot.ts:79-84);命令行参数经 provideCmdline 以服务形式在条目挂载前注入(profile-boot.ts:346-349);--dump-config 之所以能看见自己的树,是因为它按与装配相同的顺序把每层摊开(apps/cli/src/dump-config.ts:51-75);启动期拦下的是 StartupError——必需条目启用却激活失败、或 bootstrap Include 未激活(packages/boot/app-boot/src/index.ts:1222-1237,第 1 篇),bundle warnings 只打日志不拦启动。完整链路是 runCli(apps/cli/src/bin.ts:26-56)→ runProfile(profile-boot.ts:281-349)→ composeProfile(:210-235)→ boot + mountRootInclude + required 审计;launcher 在第一个条目挂载前提供代理、profileContext 与 cmdlineArgs 快照,并在整个启动窗口接管信号。

代价落在三处:审计推迟到 settle 后、代理必须在启动前解析、信号处理器要覆盖启动窗口。第 15 篇讲配置体系与生成契约,看这些层的字段如何被机械校验。

思考题

  1. 在 apps/cli/src/profile-boot.ts:284-291 找到代理解析的注释。如果改成让插件自己从 process.env 读代理,为什么 .env 层声明的代理会失效?NODE_USE_ENV_PROXY 为什么救不了?
  2. 在 apps/cli/src/profile-boot.ts:79-84 看到根配置是 []。解释「从空列表叠加」为什么让第 4 篇的 patch 语义成为唯一装配语;如果你要加一个全局服务,该改哪个文件?
  3. 在 apps/cli/src/dump-config.ts:51-75 找到 home patch 被 push 的位置。它为什么排在 per-profile patch 之后?结合 composeProfile 的 JSDoc 说明这个优先级的实际用途。
# 评论区

发表评论

评论需审核后展示。

暂无评论