@allbluecn/dsh-compat 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,383 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // assembleProfile —— 包的唯一外部门面(规格 §4.1.1 / 计划 F1-5)。
6
+ //
7
+ // 多层 patch → 合并(F1-2 applyPatches 逐 key 覆盖)→ 激活判定 → resolver 解析 →
8
+ // cordis-compat 翻译(F1-4 runCordisPlugin / definePlugin)→ 工具名预去重 →
9
+ // 产出可挂 defineHarness `plugins:` 的 HarnessPlugin[] + 诊断 AssemblyReport。
10
+ //
11
+ // 每条 merged patch 行恰好落入一个状态桶:disabled → unresolved → deactivated →
12
+ // failed → activated(判定顺序即优先级)。
13
+
14
+ import { definePlugin } from '@tanstack/ai-harness'
15
+ import type {
16
+ PluginContributions,
17
+ PluginSetupContext,
18
+ } from '@tanstack/ai-harness'
19
+ import type { AnyTool } from '@tanstack/ai'
20
+ import type {
21
+ CordisContributions,
22
+ CordisL1Services,
23
+ CordisPluginModule,
24
+ CordisRunResult,
25
+ L1ServicesFactory,
26
+ } from '../compat/context'
27
+ import { runCordisPlugin } from '../compat/context'
28
+ import { dshToolToTanStack } from '../compat/tool-adapter'
29
+ import { applyPatches } from '../patch/merge'
30
+ import { evalDisabled } from '../patch/eval'
31
+ import type { PatchFile, PatchLine } from '../patch/types'
32
+ import type { AssemblyReport } from '../report'
33
+ import { DSH_COMPAT_SURFACE_VERSION } from '../surface'
34
+ import type {
35
+ BuiltinFactory,
36
+ CordisModuleResolver,
37
+ PluginResolverResult,
38
+ } from './resolve'
39
+
40
+ /** assembleProfile 的输入选项。 */
41
+ export interface AssembleProfileOptions {
42
+ /** 已解析的 patch 层(按应用顺序:base → 用户 → 插件追加)。yaml 解析在调用方。 */
43
+ layers: ReadonlyArray<PatchFile | PatchLine[]>
44
+ /** Cordis 模块解析器(缺省 = 全部有 name 的行 unresolved)。 */
45
+ resolver?: CordisModuleResolver
46
+ /** L0 平台服务表(inject 判定 + ctx.inject 解析的单一来源)。 */
47
+ providedServices?: Readonly<Record<string, unknown>>
48
+ /**
49
+ * L1 服务 shim(fs/shell/sandbox,规格 §4.5)。宿主注入实现(apps/web server 侧把
50
+ * WorkspaceBinder / 执行面后端映射成 {@link CordisL1Services});缺省 = 三字段
51
+ * undefined(依赖型插件 inject 含 L1 键时按 l1 是否注入判定,见 context.ts)。
52
+ *
53
+ * ⚠ 静态注入是 assemble-scoped 绑定:随插件预跑 apply-once 注入,全 session 复用同一
54
+ * 实例。**优先用 {@link AssembleProfileOptions.l1Factory} 做 per-session 惰性解析**
55
+ * (可叠加 fs.write 审批语义),本字段保留为向后兼容的静态注入。
56
+ * ⚠ fs/shell 的 `bind({run})` 需 RunContext——apps/web 侧在工具 execute 期经
57
+ * resolveToolIdentity/RunContext 取 run 后绑定 WorkspaceBinder(见 brief §1.2)。
58
+ */
59
+ l1?: CordisL1Services
60
+ /**
61
+ * L1 服务工厂(per-session 惰性解析,规格 §4.5 / carry-forward F6-6)。
62
+ *
63
+ * 插件 setup 在 session open 重跑 apply 时调用本工厂解析 L1 服务(`run` 由官方 setup
64
+ * ctx 提供)——宿主可在工厂内 `bind({run})` 得 BoundWorkspace 并叠加审批语义
65
+ * (fs.write 审批外围,apps/web server 侧 `createCordisL1ServicesWithApproval`)。
66
+ * 优先级高于静态 {@link AssembleProfileOptions.l1}:setup 重跑用 `l1Factory({run})`,
67
+ * 预跑(assemble 期,无真实 run)用静态 `l1`(工厂此刻无 run 可用)。
68
+ */
69
+ l1Factory?: L1ServicesFactory
70
+ /** patch ctx(!!js evalDisabled 用,经 `ctx.get(key)` 读取)。 */
71
+ config?: Record<string, unknown>
72
+ }
73
+
74
+ /** assembleProfile 的产出:可挂 harness 的插件数组 + 诊断报告。 */
75
+ export interface AssembleProfileResult {
76
+ plugins: HarnessPlugin[]
77
+ report: AssemblyReport
78
+ }
79
+
80
+ // HarnessPlugin(definePlugin 产出)的类型来源(默认类型参数 = 任意 plugin 定义)。
81
+ type HarnessPlugin = ReturnType<typeof definePlugin>
82
+
83
+ /** assemble 期给 runCordisPlugin 的最小官方 setup ctx(effect 资源在 assemble 期打开)。 */
84
+ function assembleOfficial(): PluginSetupContext {
85
+ return {
86
+ resources: {
87
+ acquire: async <T,>(
88
+ open: () => T | Promise<T>,
89
+ _close: (resource: T) => unknown,
90
+ ) => open(),
91
+ signal: new AbortController().signal,
92
+ },
93
+ logger: { error: () => {}, warn: () => {}, info: () => {}, debug: () => {} },
94
+ } as unknown as PluginSetupContext
95
+ }
96
+
97
+ /** 把未知错误转成可读字符串(report.failed.error)。 */
98
+ function errorToString(error: unknown): string {
99
+ return error instanceof Error ? error.message : String(error)
100
+ }
101
+
102
+ /**
103
+ * 判 resolver 结果是内置静态工厂(`kind: 'builtin'`)还是 cordis 模块。
104
+ *
105
+ * 向后兼容关键:既有 cordis mock resolver 返回裸 `CordisPluginModule`(无 `kind`
106
+ * 字段),`'kind' in result` 为 false → 当 cordis 处理,既有测试零改动仍绿。
107
+ */
108
+ function isBuiltinFactory(
109
+ resolved: PluginResolverResult,
110
+ ): resolved is BuiltinFactory {
111
+ return 'kind' in resolved && resolved.kind === 'builtin'
112
+ }
113
+
114
+ /** 一条已激活内置插件的中间态(create 产出的 lazy HarnessPlugin + 预去重工具名)。 */
115
+ interface BuiltinEntry {
116
+ plugin: HarnessPlugin
117
+ toolNames: readonly string[]
118
+ }
119
+
120
+ /** 把 cordis contributions 投影成官方 PluginContributions(空集合省略)。 */
121
+ function toPluginContributions(
122
+ mod: CordisPluginModule,
123
+ contributions: CordisContributions,
124
+ tools: ReadonlyArray<AnyTool>,
125
+ ): PluginContributions {
126
+ const out: PluginContributions = {}
127
+ if (tools.length > 0) out.tools = [...tools]
128
+ if (contributions.prompts.length > 0) {
129
+ // 对齐 cordisPluginToHarness:字符串直传;section 补 id(缺省 `${name}#${placement}`)。
130
+ out.prompts = contributions.prompts.map((prompt) =>
131
+ typeof prompt === 'string'
132
+ ? prompt
133
+ : {
134
+ id: prompt.id ?? `${mod.name}#${prompt.placement ?? 'system'}`,
135
+ text: prompt.text,
136
+ ...(prompt.placement ? { placement: prompt.placement } : {}),
137
+ },
138
+ )
139
+ }
140
+ if (Object.keys(contributions.commands).length > 0) {
141
+ out.commands = { ...contributions.commands }
142
+ }
143
+ if (contributions.middleware.length > 0) {
144
+ out.middleware = [...contributions.middleware]
145
+ }
146
+ return out
147
+ }
148
+
149
+ /**
150
+ * 组装门面:把多层 patch + resolver 翻译成可挂 harness 的插件数组 + 诊断报告。
151
+ *
152
+ * 管线:合并 → 逐行(disabled / unresolved / deactivated / failed / activated)→
153
+ * 工具名预去重(规格 §4.1.3 硬前置防御)→ 产出 HarnessPlugin[] + AssemblyReport。
154
+ *
155
+ * **工具名预去重**:官方对 PluginContributions.tools 同名是 throw + 全部插件逆序
156
+ * 回滚 + session open 失败,故 assemble 预去重——撞名时应用侧让位(先出现者 = 高
157
+ * 优先层保留,后到同名工具丢弃 + 记 report.toolConflicts),被让位插件照常激活
158
+ * (其余贡献保留)。最终 plugins 里任意两插件的工具名不重复。
159
+ *
160
+ * **两阶段 apply(预跑 + setup 重跑)**:assemble 先用 `runCordisPlugin` 预跑一遍(mock
161
+ * ctx)拿到 contributions + 激活状态,据此做工具名预去重;随后**最终 `definePlugin` 的
162
+ * setup 在真实 session open 期重跑 `runCordisPlugin`**(真实 official ctx),并按预跑的
163
+ * 去重结果过滤工具后返回。预跑只用于「解析 + 激活判定 + 工具名预去重」,**副作用落点在
164
+ * setup 重跑**:effect 资源经真实 `official.resources.acquire` 打开、session close 逆序
165
+ * dispose(修复 F2-2b / F6-6 carry-forward——旧实现 setup 只同步回放预跑 contributions,
166
+ * effect 资源落到 assemble 期 mock acquire、真实 session 不重新 acquire、close 不 dispose)。
167
+ * 预跑的二次 apply(相对 setup 重跑)是「一次解析、一次激活」的解析成本,工具注册 /
168
+ * effect acquire 的**持久副作用**只在 setup 重跑发生(预跑用 mock ctx,资源不进真实 session)。
169
+ */
170
+ export async function assembleProfile(
171
+ opts: AssembleProfileOptions,
172
+ ): Promise<AssembleProfileResult> {
173
+ const report: AssemblyReport = {
174
+ activated: [],
175
+ deactivated: [],
176
+ failed: [],
177
+ disabled: [],
178
+ toolConflicts: [],
179
+ surfaceVersion: DSH_COMPAT_SURFACE_VERSION,
180
+ }
181
+ const unresolved: Array<{ id: string; name?: string }> = []
182
+
183
+ const merged = applyPatches(...opts.layers)
184
+ const providedServices = opts.providedServices ?? {}
185
+ const official = assembleOfficial()
186
+
187
+ /** 一条已激活插件的中间态(工具去重在全部收集后统一做)。 */
188
+ interface ActivatedEntry {
189
+ mod: CordisPluginModule
190
+ contributions: CordisContributions
191
+ /** patch 行 config(setup 重跑 apply 时透传,与预跑一致)。 */
192
+ config: Record<string, unknown>
193
+ }
194
+ const activated: ActivatedEntry[] = []
195
+ /** 已激活内置插件(base 层,create 产出直挂 + toolNames 先入去重池)。 */
196
+ const builtinEntries: BuiltinEntry[] = []
197
+
198
+ for (const line of merged) {
199
+ const id = line.id
200
+
201
+ // ① disabled:evalDisabled 判定(boolean false / !!js 表达式 truthy)→ 停用。
202
+ if (evalDisabled(line, { get: (key) => opts.config?.[key] })) {
203
+ report.disabled.push({ id })
204
+ continue
205
+ }
206
+
207
+ // ② unresolved:未指定解析名(无从 resolver)。
208
+ if (!line.name) {
209
+ unresolved.push({ id })
210
+ continue
211
+ }
212
+
213
+ // ③ resolver 解析:抛错 → failed;未命中 → deactivated(name 已知、missing 空)。
214
+ let resolved: PluginResolverResult | undefined
215
+ try {
216
+ resolved = await opts.resolver?.(line.name)
217
+ } catch (error) {
218
+ report.failed.push({
219
+ id,
220
+ name: line.name,
221
+ error: `resolver threw: ${errorToString(error)}`,
222
+ })
223
+ continue
224
+ }
225
+ if (!resolved) {
226
+ report.deactivated.push({ id, name: line.name, missing: [] })
227
+ continue
228
+ }
229
+
230
+ // ④a 内置静态工厂(kind === 'builtin'):create(config) → lazy HarnessPlugin,
231
+ // 直接挂 plugins(不重建 contributions——内置工具唯一性由 base 哨兵保证)。
232
+ // toolNames 先入去重池(内置 = base 层,先于 user/DSH),后续撞名者让位。
233
+ if (isBuiltinFactory(resolved)) {
234
+ const plugin = resolved.create(line.config ?? {})
235
+ // 优先用 toolNamesFor(config)(尊重 disabledTools),缺省回落静态 toolNames
236
+ //(向后兼容:未覆写 toolNamesFor 的工厂行为不变)。
237
+ const toolNames = resolved.toolNamesFor
238
+ ? resolved.toolNamesFor(line.config ?? {})
239
+ : resolved.toolNames
240
+ builtinEntries.push({ plugin, toolNames })
241
+ report.activated.push({ id, name: plugin.name })
242
+ continue
243
+ }
244
+
245
+ // ④b cordis 模块:既有 runCordisPlugin 路径(eager contributions + 去重 + 重建)。
246
+ const mod = resolved
247
+ const lineConfig = (line.config ?? {}) as Record<string, unknown>
248
+ let result: CordisRunResult
249
+ let contributions: CordisContributions
250
+ try {
251
+ ;({ contributions, result } = await runCordisPlugin(mod, official, {
252
+ config: lineConfig,
253
+ providedServices,
254
+ // L1 服务 shim(规格 §4.5):预跑用静态 opts.l1(assemble 期无真实 run,工厂不可用)。
255
+ l1: opts.l1,
256
+ // 工具适配器(规格 §4.1.3):parameters(JSON Schema) 直传 inputSchema +
257
+ // execute 上下文适配 + presenter 捕获(渲染桥通道 A)。缺省时 ctx.tools.register
258
+ // 只存 {name, description} 桩,组装产物无法到达模型工具面——conformance 的
259
+ // 「工具 schema → 模型 round-trip」要求全工具面,故 assemble 统一挂适配器。
260
+ adaptTool: dshToolToTanStack,
261
+ }))
262
+ } catch (error) {
263
+ // 防御未来回归:runCordisPlugin 不应抛。
264
+ report.failed.push({ id, name: mod.name, error: errorToString(error) })
265
+ continue
266
+ }
267
+
268
+ if (!result.activated) {
269
+ // inject 含 provided-services 表外键 → 不激活(不调 apply)。
270
+ report.deactivated.push({
271
+ id,
272
+ name: mod.name,
273
+ missing: result.missing ?? [],
274
+ })
275
+ continue
276
+ }
277
+ if (result.failed) {
278
+ // apply 抛错 → failed(贡献空,见 F1-4 I-1;不拖垮其余插件)。
279
+ report.failed.push({ id, name: mod.name, error: errorToString(result.error) })
280
+ continue
281
+ }
282
+
283
+ // ⑤ 成功:暂存(含行 config,setup 重跑 apply 时透传),工具去重后统一构造 HarnessPlugin。
284
+ report.activated.push({ id, name: mod.name })
285
+ activated.push({ mod, contributions, config: lineConfig })
286
+ }
287
+
288
+ if (unresolved.length > 0) report.unresolved = unresolved
289
+
290
+ // ⑥ 工具名预去重(规格 §4.1.3):先出现者保留,后到同名丢弃 + 记冲突。
291
+ // 内置 = base 层,toolNames 先入池(先于 user/DSH cordis),撞名时后到者让位。
292
+ const toolOwner = new Map<string, string>()
293
+ for (const entry of builtinEntries) {
294
+ for (const tn of entry.toolNames) {
295
+ if (!toolOwner.has(tn)) toolOwner.set(tn, entry.plugin.name)
296
+ }
297
+ }
298
+ const pluginContributions = new Map<number, PluginContributions>()
299
+ activated.forEach((entry, index) => {
300
+ const kept: AnyTool[] = []
301
+ for (const tool of entry.contributions.tools) {
302
+ if (!toolOwner.has(tool.name)) {
303
+ toolOwner.set(tool.name, entry.mod.name)
304
+ kept.push(tool)
305
+ continue
306
+ }
307
+ // 后到同名工具 → 应用侧让位(丢弃),记冲突(owner=被让位,yieldedTo=保留)。
308
+ report.toolConflicts.push({
309
+ name: tool.name,
310
+ owner: entry.mod.name,
311
+ yieldedTo: toolOwner.get(tool.name) as string,
312
+ })
313
+ }
314
+ pluginContributions.set(
315
+ index,
316
+ toPluginContributions(entry.mod, entry.contributions, kept),
317
+ )
318
+ })
319
+
320
+ // ⑦ 构造 HarnessPlugin[]:内置插件直挂(create 产出,无 effect 问题)+ activated 重跑
321
+ // setup(真实 session open 期重新 apply,effect 资源经真实 official ctx.resources.acquire
322
+ // 打开、session close 逆序 dispose;工具按⑥预去重结果过滤,保持跨源去重语义)。
323
+ //
324
+ // ⚠ effect/session carry-forward 修复(F2-2b / F6-6):旧实现 setup 只同步回放预跑的
325
+ // contributions、不再调 apply——effect 资源在 assemble 期落到 mock acquire(assembleOfficial
326
+ // 的 no-op)、真实 session 期不重新 acquire、close 也不 dispose。现 setup 重跑
327
+ // runCordisPlugin,用真实 official ctx(resources.acquire 正常跟踪),再按预跑去重结果
328
+ // 过滤工具(避免重跑引入的重复工具触发官方同名 throw)。
329
+ const plugins: HarnessPlugin[] = [
330
+ ...builtinEntries.map((entry) => entry.plugin),
331
+ ...activated.map((entry, index) => {
332
+ const preRunContributions = pluginContributions.get(index) ?? {}
333
+ const preRunToolNames = new Set(
334
+ (preRunContributions.tools ?? []).map((t) => t.name),
335
+ )
336
+ return definePlugin({
337
+ name: entry.mod.name,
338
+ lifetime: 'session',
339
+ setup: async (
340
+ sessionOfficial: PluginSetupContext,
341
+ ): Promise<PluginContributions> => {
342
+ // per-session L1 解析(规格 §4.5 / carry-forward F6-6):优先用 l1Factory(宿主
343
+ // 可在工厂内 bind({run}) + 叠加 fs.write 审批语义),回落静态 opts.l1。
344
+ // session-open setup ctx 无顶层 run(run 属 turn/工具 execute 期),但
345
+ // session.threadId + session.user(host access 层可信解析)已就绪——透传给工厂,
346
+ // 宿主据此构造 bind 所需最小 run 身份(binder 只读 threadId + user.id)。
347
+ // ⚠ setup ctx 可能无 session(collectCommandNames 以空 ctx `{}` 回放 setup 聚合
348
+ // 命令名)——防御性可选链,无 session 时透传 undefined,工厂回落兜底 / fail-closed。
349
+ const session = (sessionOfficial as { session?: { threadId?: string; user?: { id: string } } })
350
+ .session
351
+ const l1 = opts.l1Factory
352
+ ? await opts.l1Factory({
353
+ run: (sessionOfficial as { run?: unknown }).run,
354
+ threadId: session?.threadId,
355
+ user: session?.user,
356
+ })
357
+ : opts.l1
358
+ // 重跑 runCordisPlugin:这次用真实 session official ctx(resources.acquire 正常
359
+ // 跟踪 effect 资源)。failed → 空 contributions(与预跑一致,单插件失败不拖垮其余)。
360
+ const { contributions, result } = await runCordisPlugin(
361
+ entry.mod,
362
+ sessionOfficial,
363
+ {
364
+ config: entry.config,
365
+ providedServices,
366
+ l1,
367
+ adaptTool: dshToolToTanStack,
368
+ },
369
+ )
370
+ if (result.failed) return {}
371
+ // 按预去重结果过滤工具(保持跨源去重语义——重跑会重新注册全部工具,撞名者
372
+ // 已在⑥让位,这里丢弃被让位者,避免官方对同名工具 throw + 逆序回滚)。
373
+ const keptTools = contributions.tools.filter((t) =>
374
+ preRunToolNames.has(t.name),
375
+ )
376
+ return toPluginContributions(entry.mod, contributions, keptTools)
377
+ },
378
+ })
379
+ }),
380
+ ]
381
+
382
+ return { plugins, report }
383
+ }
@@ -0,0 +1,59 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // AllBlue - 理想之海
3
+ // Copyright (C) 2026 AllBlue Contributors
4
+ //
5
+ // 插件解析器协议(规格 §4.1.1,计划 F1-5 / F2-2)。
6
+ //
7
+ // resolver 把 patch 行的 `name` 解析成一个可组装的插件源。解析失败(返回 undefined
8
+ // 或抛错)由 assembleProfile 归入 report.deactivated / report.failed。
9
+ //
10
+ // **返回 union(F2-2)**:resolver 结果是 `PluginResolverResult`——
11
+ // - **内置静态工厂**(`kind: 'builtin'`):`@allblue/*` 七域插件经静态 import 的
12
+ // config 工厂(`create(config) → HarnessPlugin`),`toolNames` 供跨源工具名预去重
13
+ // (内置 = base 层先入池,DSH/cordis 撞名让位)。assemble 走「create + 直挂」分支。
14
+ // - **cordis 模块**(裸对象,无 `kind`):profile node_modules 里的 `@deepseek-ai/*` /
15
+ // 社区包,经动态 import 取得。assemble 走既有 `runCordisPlugin` 分支。
16
+ //
17
+ // 具体 resolver 由 F3 安装流水 / F2-2b define.server 注入;测试用注入式 mock resolver。
18
+
19
+ import type { HarnessPlugin } from '@tanstack/ai-harness'
20
+ import type { CordisPluginModule } from '../compat/context'
21
+
22
+ /**
23
+ * 内置静态工厂解析结果(规格 §4.2.1:`'@allblue/story'` → 静态 import 工厂)。
24
+ *
25
+ * `create` 吃 patch 行 config 直接返回 lazy `HarnessPlugin`(`definePlugin` 产出,
26
+ * 暴露 `.name`);`toolNames` 是该内置插件的全部工具名,供 assemble 跨源工具名预去重。
27
+ */
28
+ export interface BuiltinFactory {
29
+ kind: 'builtin'
30
+ /** 吃 patch 行 config(base patch 默认 `{}`,用户 patch 可覆写 `disabledTools` 等)→ HarnessPlugin。 */
31
+ create: (config: unknown) => HarnessPlugin
32
+ /** 该内置插件的全部工具名(组装序 base 层先入池,DSH 撞名让位)。 */
33
+ toolNames: readonly string[]
34
+ /**
35
+ * 按 config 过滤后的工具名(规格 §4.1.3 工具名预去重用)。
36
+ *
37
+ * 缺省回落静态 {@link BuiltinFactory.toolNames}(不读 config);内置工厂可覆写以
38
+ * 尊重 `disabledTools`(用户 patch 覆写 config 后,被禁用的内置工具不该占据去重池,
39
+ * 否则 DSH 插件撞「已禁用的内置工具名」会被保守让位误丢)。assembleProfile 优先
40
+ * 消费本方法,缺省时回落 toolNames。
41
+ */
42
+ toolNamesFor?: (config: unknown) => readonly string[]
43
+ }
44
+
45
+ /** resolver 结果 union:内置静态工厂 | cordis 插件模块。 */
46
+ export type PluginResolverResult = CordisPluginModule | BuiltinFactory
47
+
48
+ /**
49
+ * 把 patch 行 `name` 解析成一个插件源(内置工厂 | cordis 模块)。
50
+ *
51
+ * @param name patch 行的解析名(内置 `@allblue/*` 标识 或 包子路径导出)
52
+ * @returns 插件源;未命中返回 undefined(assemble 归入 deactivated)
53
+ */
54
+ export type PluginResolver = (
55
+ name: string,
56
+ ) => Promise<PluginResolverResult | undefined>
57
+
58
+ /** 向后兼容别名:旧名保留(既有 assemble.test.ts 及 cordis-only 调用方用)。 */
59
+ export type CordisModuleResolver = PluginResolver
@@ -0,0 +1,211 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ import { describe, expect, it, vi } from 'vitest'
3
+ import type { PluginSetupContext } from '@tanstack/ai-harness'
4
+ import {
5
+ type CordisContext,
6
+ type CordisContributions,
7
+ runCordisPlugin,
8
+ } from '../context'
9
+
10
+ /** 造一个最小官方 setup ctx(runCordisPlugin 只用 resources / logger)。 */
11
+ function fakeOfficial(): PluginSetupContext {
12
+ return {
13
+ resources: {
14
+ acquire: async <T,>(
15
+ open: () => T | Promise<T>,
16
+ _close: (r: T) => unknown,
17
+ ) => open(),
18
+ signal: new AbortController().signal,
19
+ },
20
+ logger: { error: () => {}, warn: () => {}, info: () => {}, debug: () => {} },
21
+ } as unknown as PluginSetupContext
22
+ }
23
+
24
+ /** 造一个 DSH 插件模块,apply 里记录收到的 (ctx, config)。 */
25
+ function pluginRecordingApply(
26
+ body: (ctx: CordisContext, config: unknown) => void | Promise<void>,
27
+ extra: { inject?: ReadonlyArray<string>; Config?: unknown } = {},
28
+ ) {
29
+ return {
30
+ name: 'dsh/test',
31
+ ...extra,
32
+ apply: body,
33
+ }
34
+ }
35
+
36
+ describe('runCordisPlugin — 硬前置与 context 面', () => {
37
+ it('硬前置①:两参 apply(ctx, config)——config 是行 config,ctx 有完整面', async () => {
38
+ let seenCtx: CordisContext | undefined
39
+ let seenConfig: unknown
40
+ const mod = pluginRecordingApply((ctx, config) => {
41
+ seenCtx = ctx
42
+ seenConfig = config
43
+ })
44
+ const config = { region: 'cn-north-1' }
45
+ const { result } = await runCordisPlugin(mod, fakeOfficial(), { config })
46
+ expect(result.activated).toBe(true)
47
+ expect(result.failed).toBe(false)
48
+ expect(seenConfig).toBe(config)
49
+ expect(typeof seenCtx?.tools.register).toBe('function')
50
+ expect(typeof seenCtx?.systemPrompt.section).toBe('function')
51
+ expect(typeof seenCtx?.commands.register).toBe('function')
52
+ expect(typeof seenCtx?.effect).toBe('function')
53
+ expect(typeof seenCtx?.on).toBe('function')
54
+ expect(typeof seenCtx?.emit).toBe('function')
55
+ expect(typeof seenCtx?.inject).toBe('function')
56
+ })
57
+
58
+ it('硬前置②:inject 满足 → 激活,ctx.inject 解析出 provided-services', async () => {
59
+ let injected: Record<string, unknown> | undefined
60
+ const mod = pluginRecordingApply(async (ctx) => {
61
+ injected = await ctx.inject(['db', 'cache'])
62
+ }, { inject: ['db', 'cache'] })
63
+ const provided = { db: 'DB_HANDLE', cache: 'CACHE_HANDLE' }
64
+ const { result } = await runCordisPlugin(mod, fakeOfficial(), {
65
+ providedServices: provided,
66
+ inject: ['db', 'cache'],
67
+ })
68
+ expect(result.activated).toBe(true)
69
+ expect(injected).toEqual(provided)
70
+ })
71
+
72
+ it('硬前置②:inject 含表外键 → 不激活(不调 apply)+ 返回 missing', async () => {
73
+ let applyRan = false
74
+ const mod = pluginRecordingApply(() => {
75
+ applyRan = true
76
+ }, { inject: ['db', 'secret'] })
77
+ const { result } = await runCordisPlugin(mod, fakeOfficial(), {
78
+ providedServices: { db: 'DB_HANDLE' },
79
+ inject: ['db', 'secret'],
80
+ })
81
+ expect(result.activated).toBe(false)
82
+ expect(result.failed).toBe(false)
83
+ expect(result.missing).toEqual(['secret'])
84
+ expect(applyRan).toBe(false)
85
+ })
86
+
87
+ it('config 自校验三态:通过 / 抛错降级(不 fail 激活)/ 无 Config', async () => {
88
+ // 通过
89
+ const okMod = pluginRecordingApply(() => {}, {
90
+ Config: (config: unknown) => {
91
+ if ((config as { region?: string })?.region === undefined) {
92
+ throw new Error('region required')
93
+ }
94
+ },
95
+ })
96
+ const ok = await runCordisPlugin(okMod, fakeOfficial(), { config: { region: 'cn' } })
97
+ expect(ok.result.activated).toBe(true)
98
+ expect(ok.result.failed).toBe(false)
99
+ expect(ok.result.notes).toBeUndefined()
100
+
101
+ // 抛错降级:记入 notes,仍激活
102
+ const warn = await runCordisPlugin(okMod, fakeOfficial(), { config: {} })
103
+ expect(warn.result.activated).toBe(true)
104
+ expect(warn.result.failed).toBe(false)
105
+ expect(warn.result.notes?.[0]).toContain('config validation warning')
106
+
107
+ // 无 Config:正常激活,无 note
108
+ const noCfg = pluginRecordingApply(() => {})
109
+ const plain = await runCordisPlugin(noCfg, fakeOfficial(), { config: {} })
110
+ expect(plain.result.activated).toBe(true)
111
+ expect(plain.result.notes).toBeUndefined()
112
+ })
113
+
114
+ it('硬前置③:apply 抛错 → failed 形态(不向上抛,单插件不拖垮其余)', async () => {
115
+ const mod = pluginRecordingApply(() => {
116
+ throw new Error('apply exploded')
117
+ })
118
+ const { contributions, result } = await runCordisPlugin(mod, fakeOfficial(), {})
119
+ expect(result.activated).toBe(true)
120
+ expect(result.failed).toBe(true)
121
+ expect((result.error as Error).message).toBe('apply exploded')
122
+ expect(contributions.tools).toEqual([])
123
+ })
124
+
125
+ it('effect → 官方 resources.acquire(dispose 作为 close)', async () => {
126
+ const acquire = vi.fn(async <T,>(
127
+ open: () => T | Promise<T>,
128
+ _close: (r: T) => unknown,
129
+ ) => open())
130
+ const official = {
131
+ resources: { acquire, signal: new AbortController().signal },
132
+ logger: { error: () => {} },
133
+ } as unknown as PluginSetupContext
134
+ let disposed: string | undefined
135
+ const mod = pluginRecordingApply(async (ctx) => {
136
+ const open = ctx.effect<string>((resource) => {
137
+ disposed = resource
138
+ })
139
+ await open(() => 'RESOURCE')
140
+ })
141
+ const { result } = await runCordisPlugin(mod, official, {})
142
+ expect(result.activated).toBe(true)
143
+ expect(acquire).toHaveBeenCalledTimes(1)
144
+ expect(disposed).toBeUndefined() // close 只在清理期调用,run 期不触发
145
+ })
146
+
147
+ it('systemPrompt.section / .context / tools.register 收集进 contributions', async () => {
148
+ const mod = pluginRecordingApply((ctx) => {
149
+ ctx.systemPrompt.section('You are a deploy assistant.')
150
+ ctx.systemPrompt.context('Current region: cn-north-1')
151
+ ctx.tools.register({ name: 't1', description: 'tool one', execute: () => ({}) })
152
+ ctx.commands.register({ name: 'deploy', run: () => ({}) })
153
+ })
154
+ const { contributions } = await runCordisPlugin(mod, fakeOfficial(), {})
155
+ expect(contributions.prompts).toEqual([
156
+ 'You are a deploy assistant.',
157
+ { text: 'Current region: cn-north-1', placement: 'context' },
158
+ ])
159
+ expect(contributions.tools.map((t) => t.name)).toEqual(['t1'])
160
+ expect(Object.keys(contributions.commands)).toEqual(['deploy'])
161
+ })
162
+
163
+ it('known-events ctx.on → drainMiddleware 产出 middleware contribution(events 协同)', async () => {
164
+ const mod = pluginRecordingApply((ctx) => {
165
+ ctx.on('pre-execute', () => ({ type: 'skip', result: { blocked: true } }))
166
+ })
167
+ const { contributions } = await runCordisPlugin(mod, fakeOfficial(), {})
168
+ expect(contributions.middleware.length).toBe(1)
169
+ expect(contributions.middleware[0].onBeforeToolCall).toBeTypeOf('function')
170
+ })
171
+ })
172
+
173
+ describe('cordisPluginToHarness(definePlugin 翻译)', () => {
174
+ it('产出 HarnessPlugin,setup 返回 PluginContributions', async () => {
175
+ const { cordisPluginToHarness } = await import('../context')
176
+ const mod = pluginRecordingApply((ctx) => {
177
+ ctx.systemPrompt.section('hello')
178
+ ctx.tools.register({ name: 't', description: 'd', execute: () => ({}) })
179
+ })
180
+ const plugin = cordisPluginToHarness(mod)
181
+ expect(plugin.name).toBe('dsh/test')
182
+ const contributions = (await plugin.setup?.(fakeOfficial())) as Record<
183
+ string,
184
+ unknown
185
+ >
186
+ expect(Array.isArray(contributions.prompts)).toBe(true)
187
+ expect((contributions.tools as Array<{ name: string }>)[0].name).toBe('t')
188
+ })
189
+
190
+ it('failed 插件丢弃部分 contributions:apply 注册工具后抛错 → setup 返回空 contributions(非部分工具)', async () => {
191
+ const { cordisPluginToHarness, runCordisPlugin } = await import('../context')
192
+ const mod = pluginRecordingApply((ctx) => {
193
+ ctx.tools.register({ name: 'partial-tool', description: 'd', execute: () => ({}) })
194
+ throw new Error('boom after register')
195
+ })
196
+
197
+ // runCordisPlugin 层(原始收集面):部分工具被收集 + failed 标记。
198
+ const { contributions, result } = await runCordisPlugin(mod, fakeOfficial(), {})
199
+ expect(result.failed).toBe(true)
200
+ expect(contributions.tools.map((t) => t.name)).toEqual(['partial-tool'])
201
+
202
+ // harness 层(cordisPluginToHarness.setup):failed → 空 contributions,
203
+ // 部分工具被丢弃(不泄漏进 surface,给 F1-5 干净契约)。
204
+ const plugin = cordisPluginToHarness(mod)
205
+ const out = (await plugin.setup?.(fakeOfficial())) as Record<string, unknown>
206
+ expect(out.tools).toBeUndefined()
207
+ expect(out.prompts).toBeUndefined()
208
+ expect(out.commands).toBeUndefined()
209
+ expect(out.middleware).toBeUndefined()
210
+ })
211
+ })