Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(plugins): load scheduler runtime via platform loader (#336)

Mao Mrb035b64f85f1
diff --git a/packages/dsh-tauri-panel-scheduler/src/client/utils/schedule.ts b/packages/dsh-tauri-panel-scheduler/src/client/utils/schedule.ts
index 15cc8e51..af4974d6 100644
--- a/packages/dsh-tauri-panel-scheduler/src/client/utils/schedule.ts
+++ b/packages/dsh-tauri-panel-scheduler/src/client/utils/schedule.ts
@@ -2,8 +2,8 @@
* utils/schedule.ts — 计划描述与下次运行时间的展示格式化(纯函数)。
*
* 时间格式化委托 date-fns(format / differenceIn*),替换手写的 Intl 与差值算法;
- * 单位文案仍走 t() 以支持 zh/en 双语。date-fns 由 dsh-tauri/client 承载导出,
- * 本插件 client 不直接 import 外部依赖(见 AGENTS.plugins.md 客户端依赖约定)。
+ * 单位文案仍走 t() 以支持 zh/en 双语。date-fns 由 dsh-tauri/client 承载并在构建期
+ * 按使用导出 tree-shake 内联,本插件 client 不直接 import 外部依赖。
*/
import type { ScheduleForm, Translate, Weekday } from '../types'
diff --git a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.test.ts b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.test.ts
new file mode 100644
index 00000000..dd668fcf
--- /dev/null
+++ b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it, vi } from 'vitest'
+import { loadSchedulerRuntimeModules } from './executor.js'
+
+describe('loadSchedulerRuntimeModules', () => {
+ it('resolves DSH-owned modules through the platform loader', async () => {
+ const installModelSelection = vi.fn()
+ const createUserMessage = vi.fn()
+ const setApprovalPolicy = vi.fn()
+ const modules = new Map<string, unknown>([
+ ['@deepseek-ai/dsh-agent', { installModelSelection }],
+ ['@deepseek-ai/dsh-llm', { createUserMessage }],
+ ['@deepseek-ai/dsh-user-approval', { setApprovalPolicy }],
+ ])
+ const loader = {
+ import: vi.fn(async (name: string) => modules.get(name)),
+ unwrapExports: vi.fn((value: unknown) => value),
+ }
+
+ const runtime = await loadSchedulerRuntimeModules(loader)
+
+ expect(loader.import).toHaveBeenCalledTimes(3)
+ expect(loader.import).toHaveBeenNthCalledWith(1, '@deepseek-ai/dsh-agent')
+ expect(loader.import).toHaveBeenNthCalledWith(2, '@deepseek-ai/dsh-llm')
+ expect(loader.import).toHaveBeenNthCalledWith(3, '@deepseek-ai/dsh-user-approval')
+ expect(runtime).toEqual({ installModelSelection, createUserMessage, setApprovalPolicy })
+ })
+})
diff --git a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts
index e4289220..65629502 100644
--- a/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts
+++ b/packages/dsh-tauri-panel-scheduler/src/host/service/executor.ts
@@ -24,9 +24,6 @@ import { randomUUID } from 'node:crypto'
import { mkdir } from 'node:fs/promises'
import { homedir } from 'node:os'
import process from 'node:process'
-import { installModelSelection } from '@deepseek-ai/dsh-agent'
-import { createUserMessage } from '@deepseek-ai/dsh-llm'
-import { setApprovalPolicy } from '@deepseek-ai/dsh-user-approval'
import { join } from 'pathe'
import { RUNS_HISTORY_LIMIT } from '../constants/index.js'
import { loadState, saveRuns, withStateLock } from '../storage/index.js'
@@ -41,6 +38,24 @@ export interface ExecuteOutcome {
model?: string
}
+/** 宿主 loader 的最小接口:从 DSH 自身模块根解析核心包,而非插件资源目录。 */
+interface PlatformModuleLoader {
+ import: (name: string) => Promise<unknown>
+ unwrapExports: (exports: unknown) => unknown
+}
+
+interface SchedulerRuntimeModules {
+ installModelSelection: (agentCtx: unknown, selection: {
+ current: ModelSelection | undefined
+ assembled: ModelSelection | undefined
+ }) => () => void
+ createUserMessage: (value: {
+ content: readonly { type: 'text', text: string }[]
+ source: unknown
+ }) => unknown
+ setApprovalPolicy: (session: unknown, policy: 'ask' | 'never') => void
+}
+
interface SessionEventLike {
readonly seq: number
readonly type: string
@@ -71,6 +86,23 @@ const UNATTENDED_TOOL_ALLOWLIST = new Set([
const CANCEL_CONVERGENCE_TIMEOUT_MS = 10_000
+/**
+ * 从平台 loader 加载 DSH-owned 核心模块。内置插件位于独立 resources/node_modules,
+ * 原生 ESM 裸导入会错误地从该资源树查找这些包;loader 才持有 DSH 安装目录的解析基址。
+ */
+export async function loadSchedulerRuntimeModules(loader: PlatformModuleLoader): Promise<SchedulerRuntimeModules> {
+ const [agent, llm, approval] = await Promise.all([
+ loader.import('@deepseek-ai/dsh-agent'),
+ loader.import('@deepseek-ai/dsh-llm'),
+ loader.import('@deepseek-ai/dsh-user-approval'),
+ ])
+ return {
+ installModelSelection: (loader.unwrapExports(agent) as Pick<SchedulerRuntimeModules, 'installModelSelection'>).installModelSelection,
+ createUserMessage: (loader.unwrapExports(llm) as Pick<SchedulerRuntimeModules, 'createUserMessage'>).createUserMessage,
+ setApprovalPolicy: (loader.unwrapExports(approval) as Pick<SchedulerRuntimeModules, 'setApprovalPolicy'>).setApprovalPolicy,
+ }
+}
+
/** 对不保证及时响应 AbortSignal 的宿主任务设置第二道退出上限(对齐 MichengAI)。 */
export function settlesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {
let timer: ReturnType<typeof setTimeout> | undefined
@@ -105,6 +137,7 @@ export function applyUnattendedPermission(
presets: PermissionPresetService,
session: unknown,
permission: string | undefined,
+ setApprovalPolicy: SchedulerRuntimeModules['setApprovalPolicy'],
): void {
presets.set(session, permission ?? presets.defaultPreset)
setApprovalPolicy(session, 'never')
@@ -181,6 +214,10 @@ export async function executeTask(
})
try {
+ const runtime = await loadSchedulerRuntimeModules(
+ (ctx as HostContext & { loader: PlatformModuleLoader }).loader,
+ )
+
// 2. 解析工作区 CWD
let cwd: string
let workspace: { attachSession?: (id: unknown) => Promise<unknown> } | undefined
@@ -236,11 +273,16 @@ export async function executeTask(
agentOptions: selection ? { provider: selection.provider, model: selection.model } : {},
setup: async (agentCtx: any) => {
await (ctx.agentPresets as { mount?: (agentCtx: unknown, presetId: string) => Promise<unknown> } | undefined)?.mount?.(agentCtx, agentPreset)
- installModelSelection(agentCtx, { current: selection, assembled: undefined })
+ runtime.installModelSelection(agentCtx, { current: selection, assembled: undefined })
const agent = agentCtx.agent
if (!agent)
throw new Error('scheduler setup has no scoped Agent')
- applyUnattendedPermission(ctx.permissionPresets as PermissionPresetService, agent.session, task.permission)
+ applyUnattendedPermission(
+ ctx.permissionPresets as PermissionPresetService,
+ agent.session,
+ task.permission,
+ runtime.setApprovalPolicy,
+ )
agentCtx.tools?.guard?.((exec: ToolExecution) => unattendedToolGuardReason(exec.name, exec.arguments))
},
})
@@ -260,7 +302,7 @@ export async function executeTask(
}
const firstSeq = handle.agent.session.seq
- handle.agent.followup(createUserMessage({
+ handle.agent.followup(runtime.createUserMessage({
content: [{ type: 'text', text: task.prompt }],
source: { kind: 'scheduler', taskId: task.id, runId, scheduledFor },
}))
diff --git a/packages/dsh-tauri-tsdown/src/index.mjs b/packages/dsh-tauri-tsdown/src/index.mjs
index 9a09a79f..117879ad 100644
--- a/packages/dsh-tauri-tsdown/src/index.mjs
+++ b/packages/dsh-tauri-tsdown/src/index.mjs
@@ -45,7 +45,7 @@ export const dshExternal = [
* "missed the module table"(build-time externals drift)。
* 因此 client entry 必须把它们内联;host entry 保持 external(Node 运行时按
* 插件 dependencies 解析)。子路径(unstorage/drivers/*)一并覆盖。
- * date-fns 是 client 侧时间格式化依赖(dsh-tauri-panel-scheduler),同样内联。
+ * date-fns 仅作为构建期 devDependency,并按实际使用导出 tree-shake 后内联。
*/
const dshClientInline = [/^(unstorage|hookable|ofetch|pathe|date-fns)([/-].*)?$/]
diff --git a/packages/dsh-tauri/package.json b/packages/dsh-tauri/package.json
index 26d0965b..65f95d67 100644
--- a/packages/dsh-tauri/package.json
+++ b/packages/dsh-tauri/package.json
@@ -54,7 +54,6 @@
"typecheck": "tsc"
},
"dependencies": {
- "date-fns": "catalog:utils",
"hookable": "catalog:utils",
"ofetch": "catalog:utils",
"unstorage": "catalog:utils"
@@ -65,6 +64,7 @@
"@deepseek-ai/dsh-client-ui-renderer": "catalog:dsh",
"@deepseek-ai/dsh-client-ui-slots": "catalog:dsh",
"css-render": "catalog:ui",
+ "date-fns": "catalog:utils",
"dsh-tauri-tsdown": "workspace:*",
"tsdown": "catalog:cli"
}
diff --git a/packages/dsh-tauri/src/client/index.ts b/packages/dsh-tauri/src/client/index.ts
index e33de851..eab87cad 100644
--- a/packages/dsh-tauri/src/client/index.ts
+++ b/packages/dsh-tauri/src/client/index.ts
@@ -27,10 +27,7 @@ export type { ClientContext } from './types'
export { compat, resolveStartSession } from './utils/compat'
export { CssRender } from 'css-render'
-/**
- * date-fns(客户端时间格式化)由 dsh-tauri 承载并内联进其 client bundle;
- * 插件 client 禁止直接 import 'date-fns',一律从本 barrel(`dsh-tauri/client`)导入。
- */
+/** 仅构建期 tree-shake 内联所用导出;date-fns 不进入 release production 资源闭包。 */
export { differenceInDays, differenceInHours, differenceInMinutes, format } from 'date-fns'
export { createHooks } from 'hookable'
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 56d0753d..a4e297ed 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -465,9 +465,6 @@ importers:
packages/dsh-tauri:
dependencies:
- date-fns:
- specifier: catalog:utils
- version: 4.4.0
hookable:
specifier: catalog:utils
version: 6.1.1
@@ -493,6 +490,9 @@ importers:
css-render:
specifier: catalog:ui
version: 0.15.14
+ date-fns:
+ specifier: catalog:utils
+ version: 4.4.0
dsh-tauri-tsdown:
specifier: workspace:*
version: link:../dsh-tauri-tsdown
diff --git a/scripts/build-plugins.ts b/scripts/build-plugins.ts
index 7a7cb25b..f49b871b 100644
--- a/scripts/build-plugins.ts
+++ b/scripts/build-plugins.ts
@@ -9,6 +9,8 @@ const BUNDLE_PACKAGE = join(PACKAGES_ROOT, 'dsh-tauri-bundle', 'package.json')
const RESOURCE_ROOT = join(REPO_ROOT, 'src-tauri', 'resources')
/** 运行期实际依赖的部署产物:`resources/node_modules/<name>`(Tauri 只捆绑 `resources/**`) */
const DEPLOYED_NODE_MODULES = join(RESOURCE_ROOT, 'node_modules')
+const FORBIDDEN_PRODUCTION_PACKAGES = ['date-fns'] as const
+const DSH_STATIC_HOST_IMPORT = /\b(?:from|import)\s*['"](@deepseek-ai\/[^'"]+)['"]|\brequire\s*\(\s*['"](@deepseek-ai\/[^'"]+)['"]\s*\)/g
function run(args: readonly string[]): void {
console.log(`[build:plugins] $ pnpm ${args.join(' ')}`)
@@ -39,7 +41,23 @@ function bundledPackageNames(): string[] {
return names
}
+function verifyForbiddenProductionPackages(nodeModulesRoot: string): void {
+ const forbidden = new Set<string>(FORBIDDEN_PRODUCTION_PACKAGES)
+ for (const entry of readdirSync(nodeModulesRoot, { withFileTypes: true, recursive: true })) {
+ if (!entry.isFile() || entry.name !== 'package.json')
+ continue
+
+ const packageJson = join(entry.parentPath, entry.name)
+ const manifest = JSON.parse(readFileSync(packageJson, 'utf8')) as { name?: unknown }
+ if (typeof manifest.name === 'string' && forbidden.has(manifest.name)) {
+ throw new Error(`PLUGIN_DEPLOY_FORBIDDEN_PACKAGE: ${packageJson}`)
+ }
+ }
+}
+
function verifyDeployedPackages(names: readonly string[], nodeModulesRoot: string): void {
+ verifyForbiddenProductionPackages(nodeModulesRoot)
+
for (const name of names) {
const packageJson = join(nodeModulesRoot, name, 'package.json')
if (!existsSync(packageJson)) {
@@ -52,8 +70,20 @@ function verifyDeployedPackages(names: readonly string[], nodeModulesRoot: strin
if (typeof manifest.dsh !== 'object' || manifest.dsh === null || Array.isArray(manifest.dsh)) {
throw new Error(`PLUGIN_DEPLOY_INVALID_DSH: ${packageJson}`)
}
- if (typeof manifest.main === 'string' && !existsSync(join(nodeModulesRoot, name, manifest.main))) {
- throw new Error(`PLUGIN_DEPLOY_MISSING_ENTRY: ${join(nodeModulesRoot, name, manifest.main)}`)
+ if (typeof manifest.main !== 'string')
+ continue
+
+ const hostEntry = join(nodeModulesRoot, name, manifest.main)
+ if (!existsSync(hostEntry)) {
+ throw new Error(`PLUGIN_DEPLOY_MISSING_ENTRY: ${hostEntry}`)
+ }
+
+ // 内置插件与 DSH 安装目录分离,宿主模块必须经平台 loader 解析,不能依赖 Node 裸导入。
+ const source = readFileSync(hostEntry, 'utf8')
+ DSH_STATIC_HOST_IMPORT.lastIndex = 0
+ const match = DSH_STATIC_HOST_IMPORT.exec(source)
+ if (match !== null) {
+ throw new Error(`PLUGIN_DEPLOY_STATIC_DSH_IMPORT: ${hostEntry} -> ${match[1] ?? match[2]}`)
}
}
}