Desktop 与 npm CLI 共享什么、隔离什么?Electron Host 如何调用共享 CLI runner 并经 IPC 送 boot injections?Python SDK 为何只传 profile/patch 与显式 DSH_HOME。
深入理解 DeepSeek Harness · 第 16 篇
持久化与跨形态复用
前情回顾
第 15 篇讲完生成契约与验证闭环。本篇处理最后一层工程问题:同一套插件运行时如何在 Desktop 与 Python SDK 里复用,而不共享 activated plugins;会话格式结论只引用第 6 篇,不在这里重述迁移链。
本章要回答的问题
Desktop 与 npm CLI 到底共享什么、隔离什么?Electron 里谁启动 Host、谁拥有 RPC 和流?Python SDK 为什么不直接构造一棵 Cordis 树?显式 Harness home 为什么是硬性要求?
你会学到什么 / 先验知识
你会看懂 Desktop Host 如何调用共享的 runProfile、认证与 boot injections 如何经 IPC 送到页面、Python SDK 如何包装 CLI 并传 profile 与 patch,以及这种复用方式的代价。先验是第 12 篇的 profile、第 14 篇的启动链路、第 6 篇的格式结论。
核心概念:共享 CLI,隔离宿主
graph LR
C[同一 dsh CLI + profile runner] --> D[Electron Desktop Host<br/>签名资源 + profiles/desktop]
C --> P[Python SDK<br/>runtime wheel 包装 CLI]
C --> W[Web / npm CLI]
D --> L[本地页面<br/>Web owns RPC + streams]
P --> H[显式 DSH_HOME]
D -. 产品数据共享 .-> W
D -. packages / activation / lockfile 隔离 .-> W
[文档] docs/architecture.md:51-53 给出总览:
The Electron desktop application ships its exact dsh production runtime in signed resources and owns the reserved `$DSH_HOME/profiles/desktop`. Shared helpers initialize profile files, reconcile bundles, and resolve installation and bundle dependencies without replacing pnpm-owned packages. Desktop and npm CLI share product data but keep packages, activation, and lockfiles separate. Desktop’s bundled CLI manages its initialized plugins.
Electron starts the private Desktop Host in Electron Node mode. The Host invokes the shared CLI profile runner and complete Web application. The window immediately loads packaged Web assets and waits for boot injections before activating client plugins in the same document. Web owns RPC and streams; the desktop carrier connects the local page to the authenticated Host. Node IPC carries boot injections, readiness, fatal errors, and shutdown.
两条边界一句写清:共享的是产品数据与 CLI 装配逻辑,隔离的是 packages、activation 与 lockfile;Web 拥有 RPC 与流,Desktop 只是把本地页面接到已认证的 Host。
源码走读:四处证据
证据一:Desktop Host 直接调用共享 runner。 [源码] apps/desktop-host/src/index.ts:51-74:
// Set before the launch-environment snapshot and profile evaluation; empty means the payload sits beside the runtime directory. process.env.DSH_PRIMARY_RUNTIME = process.argv[4] || join(runtimeDir, '..', 'runtime', 'primary-runtime') const installAnchor = join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh', 'package.json') const profile = loadProfileDirectory('dsh', projectDir, installAnchor) reportSkippedBundles('dsh', profile) const application = runProfile({ environment: loadLayeredEnv('dsh'), profile: 'desktop', resolvedProfile: { profile, installAnchor }, patchFiles: [], args: ['--no-open', '--host', '127.0.0.1', '--port', '0'], ...(pnpm === undefined ? {} : { packageManager: { command: process.execPath, args: ['--expose-internals', pnpm], env: { ELECTRON_RUN_AS_NODE: '1', DSH_DESKTOP_NODE_EXECUTABLE: process.execPath, PATH: `${nodeBin ?? ''}${delimiter}${process.env.PATH ?? ''}`, }, }, }), })
这里没有另一套装配实现:Host 调用的就是第 14 篇那个 runProfile,只是 profile 换成保留名 desktop、install anchor 指向签名资源里的 dsh 包、端口传 0 让 OS 分配。包管理器命令走 Electron 的 Node 模式执行捆绑 pnpm——这意味着 plugin 交易用的是 normal user 与 profile 配置(docs/architecture.md:53),不是 Host 自己的特权。
证据二:认证、readiness 与 boot injections 走 IPC。 [源码] apps/desktop-host/src/index.ts:155-179:
const { ctx } = await application const canPublish = (): boolean => stopping === undefined && process.connected && !authentication.signal.aborted if (!canPublish()) return ctx.effect(() => () => { authentication.signal.removeEventListener('abort', onAuthenticationEnd) authentication.dispose() }, 'desktop-host: authentication channel') installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId) control.updateTasks = installDesktopUpdateTaskControl(ctx) control.quitInspection = installDesktopQuitInspection(ctx) if (receiverPath !== undefined) ctx.provide('desktopFrameReceiver', { path: receiverPath }) await ctx.plugin(sharedTexture) installPlatformSessionPublisher(ctx, (session) => { if (process.connected) process.send?.({ type: 'platform-session', session }) }) await ctx.plugin(DesktopAuthentication, { readSecret: () => secret }).await() if (!canPublish()) return const admission = ctx.connection.authentication.authenticate({ headers: { cookie: `dsh-desktop-session=${secret}` }, }) if ('rejection' in admission) throw new Error('Desktop authentication provider did not accept its startup credential') const url = `${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}/` const injections = ctx.webServer.collectIndexInjections(admission.peer) if (!canPublish()) return process.send?.({ type: 'ready', url, injections }, (error) => { if (error !== null) console.error(error) })
await application 等第 14 篇的稳定根上下文;然后挂 DesktopAuthentication、用 cookie 认证获得 Peer、collectIndexInjections(admission.peer) 收集 boot injections,最后通过 process.send({ type: 'ready', url, injections }) 发给页面。canPublish() 在每一步前复查:停止中、进程断连、认证取消就不再发布——页面要么拿到完整信息,要么什么都没拿到。这正是第 3 篇「状态在提交点发布」在跨进程场景的应用。
证据三:Python SDK 包装 CLI,不构造树。 [文档] docs/architecture.md:47 已说明 runtime wheel 把普通 dsh CLI 包装为 deepseek-harness-sdk-runtime-<platform>-<arch>,client 默认以显式 Harness home 启动 dsh --profile sdk;被删掉的私有 direct-config carrier 没有兼容 bin 或 fallback parser。[源码] python/sdk/src/deepseek_harness/client.py:610-638:
def _default_launch_args(self, env: dict[str, str]) -> tuple[str, ...]: if self.config.dsh_bin is None: try: from deepseek_harness_runtime import resolve_bundled_launch_args except ImportError as exc: raise FileNotFoundError( "Unable to locate the bundled DeepSeek Harness dsh runtime. " "Install deepseek-harness-runtime-bin." ) from exc base = resolve_bundled_launch_args() else: base = (str(Path(self.config.dsh_bin).expanduser().resolve()),) if self.config.dsh_home is not None: if not self.config.dsh_home.strip(): raise ValueError("HarnessConfig requires a non-empty dsh_home") env["DSH_HOME"] = str(Path(self.config.dsh_home).expanduser().resolve()) elif not env.get("DSH_HOME", "").strip(): raise ValueError( "HarnessConfig requires an explicit dsh_home or non-empty DSH_HOME; " "the Python SDK never uses ~/.dsh implicitly" ) patches = tuple( argument for patch in self.config.patches for argument in ("--patch", str(Path(patch).expanduser().resolve())) ) return (*base, "--profile", self.config.profile, *patches)
Python 暴露的东西只有三样:profile 选择、有序 patch 文件、显式 home;返回的 argv 形如 <dsh> --profile <name> --patch <file>...。:629-631 的报错逐字写着 the Python SDK never uses ~/.dsh implicitly——不猜用户目录,避免悄悄连到另一个实例。
证据四:runtime 入口同样拒绝隐式 home。 [源码] python/sdk-runtime/src/deepseek_harness_runtime/__init__.py:196-209:
def main() -> None: """Launch the CLI with explicit DSH_HOME; wait on Windows, replace the process on POSIX.""" if not os.environ.get("DSH_HOME", "").strip(): print( "dsh: the Python runtime command requires an explicit DSH_HOME; " "it never uses ~/.dsh implicitly", file=sys.stderr, ) raise SystemExit(2) argv = (*resolve_bundled_launch_args(), *sys.argv[1:]) if sys.platform == "win32": # Windows CRT exec does not replace the process; wait and preserve the runtime status. raise SystemExit(subprocess.run(argv, env=os.environ).returncode) os.execvpe(argv[0], argv, os.environ)
两层都做同一检查:client 侧与 runtime 入口侧都拒绝空 DSH_HOME。Windows 因 CRT exec 不替换进程而等待子进程并保留状态码;POSIX 用 os.execvpe 直接替换。
设计取舍
① 为什么跨形态复用 CLI 与 profile,而不是复用进程? 因为装配逻辑(patch 栈、required 审计、环境快照)只应存在一份;Electron 与 Python 各自替换宿主与认证载体即可。代价是每种宿主都要写一份适配层——Desktop 的 IPC/认证、Python 的 argv 与 home 检查。
② 为什么 Desktop 保留 $DSH_HOME/profiles/desktop? 因为 Desktop 与 npm CLI 可以共存于同一台机器,若共享 activated plugins 与 lockfile,一边的安装会改另一边的行为。代价是配置需要对账(docs/architecture.md:51 的 shared helpers 做 bundle 对账与依赖解析),收益是两边互不污染。
③ 为什么 Python 不提供 direct-config 兼容层? 因为那会让 Python 侧出现「另一棵 Cordis 树」的语义,与 CLI profile 分叉。代价是老调用方必须迁移到 profile + patch;收益是只有一种装配语义需要维护(docs/architecture.md:47)。
常见误解
「Desktop 与 npm CLI 共享 activated plugins。」 不共享。它们共享产品数据,但 packages、activation 与 lockfile 分离(docs/architecture.md:51)。
「Python SDK 直接构造 Cordis 树。」 不是。它只传 profile、patch 与显式 home,树由同一个 CLI runner 装配(client.py:633-638)。
「会话格式迁移由本篇负责。」 不是。格式 v0→v4 的四步链与迁移源码在第 6 篇;本篇只复用其结论:同一套持久化格式被各形态共用。
小结
Desktop 与 npm CLI 共享产品数据,但隔离 packages、activation 与 lockfile(docs/architecture.md:51),这样一边的安装不会改另一边的行为;Electron 在 Node 模式下启动私有 Desktop Host 并调用共享 CLI runner,而 RPC 与流归 Web,Desktop 只是把本地页面接到已认证的 Host(:53,apps/desktop-host/src/index.ts:51-74、:155-179);Python SDK 之所以不构造 Cordis 树,是因为那会让 Python 侧出现另一套装配语义,它只传 --profile、有序 --patch 与显式 DSH_HOME(python/sdk/src/deepseek_harness/client.py:610-638);显式 home 之所以是硬要求,是因为隐式 ~/.dsh 会悄悄连到另一个实例,client 与 runtime 两层都拒绝空 DSH_HOME(python/sdk-runtime/src/deepseek_harness_runtime/__init__.py:196-209)。四段走读分别给出:Host 以 profile: 'desktop' 调 runProfile、端口 0 由 OS 分配;ready、url 与 boot injections 经 IPC 送到页面;Python argv 形如 <dsh> --profile <name> --patch <file>...;Windows 等待子进程、POSIX 直接 exec。
代价落在三处:每种宿主要写适配层、配置需要对账、老 Python 调用方要迁移。第 17 篇是扩展实战,把前面所有机制变成「把新行为放到哪里」的操作清单。
思考题
- 在
apps/desktop-host/src/index.ts:176-179找到collectIndexInjections(admission.peer)与process.send({ type: 'ready', ... })。如果 Host 在认证完成前就发ready,页面会拿到什么?为什么canPublish()在每一步前都要复查? - 在
python/sdk/src/deepseek_harness/client.py:623-631找到显式 home 检查。如果 Python SDK 悄悄使用~/.dsh,在同一台机器上还会跑 npm CLI 的用户会遇到什么?为什么 runtime 入口(:196-204)还要再检查一次? - 在
docs/architecture.md:51找到「share product data but keep packages, activation, and lockfiles separate」。如果改成完全共享,Desktop 的 plugin 安装会怎样影响 npm CLI?shared helpers 的 bundle 对账在这里解决什么问题?