@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.
- package/LICENSE +661 -0
- package/README.md +24 -2
- package/package.json +34 -3
- package/src/__tests__/package.test.ts +58 -0
- package/src/assemble/__tests__/assemble.test.ts +656 -0
- package/src/assemble/assemble.ts +383 -0
- package/src/assemble/resolve.ts +59 -0
- package/src/compat/__tests__/context.test.ts +211 -0
- package/src/compat/__tests__/events.test.ts +135 -0
- package/src/compat/__tests__/tool-adapter.test.ts +157 -0
- package/src/compat/__tests__/view-bridge.test.ts +166 -0
- package/src/compat/context.ts +496 -0
- package/src/compat/events.ts +189 -0
- package/src/compat/tool-adapter.ts +115 -0
- package/src/compat/view-bridge.ts +160 -0
- package/src/guard/assert-fetchable-url.ts +239 -0
- package/src/index.ts +52 -0
- package/src/patch/__tests__/patch.test.ts +250 -0
- package/src/patch/eval.ts +343 -0
- package/src/patch/merge.ts +45 -0
- package/src/patch/types.ts +37 -0
- package/src/patch/yaml.ts +75 -0
- package/src/plugin-safety/__tests__/build-approval.test.ts +149 -0
- package/src/plugin-safety/__tests__/install-spec.test.ts +148 -0
- package/src/plugin-safety/build-approval.ts +134 -0
- package/src/plugin-safety/index.ts +31 -0
- package/src/plugin-safety/install-spec.ts +189 -0
- package/src/report.ts +47 -0
- package/src/surface.ts +92 -0
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// DSH Cordis 插件模块 → TanStack HarnessPlugin 翻译层(context 面)。
|
|
3
|
+
//
|
|
4
|
+
// 把 DSH 插件 `apply(ctx, config)` 翻译成官方 `definePlugin`。新版**零 kernel 依赖**
|
|
5
|
+
// (不用 ServiceRegistry / EffectScope / EventBus / CapabilityBus):
|
|
6
|
+
// - `effect` → 官方 `ctx.resources.acquire`(逆序清理)
|
|
7
|
+
// - `inject` → provided-services 静态表判定(表外键 ⇒ 插件不激活)
|
|
8
|
+
// - `on/emit` → events.ts(已知事件 → middleware contribution + 未知事件 → 包内总线)
|
|
9
|
+
//
|
|
10
|
+
// 三条硬前置(规格 §4.1.2,均有测试锁定):
|
|
11
|
+
// ① `apply(ctx, config)` 两参调用;② `inject` 含 provided-services 表外键 → 不激活
|
|
12
|
+
// (不调 apply,返回 missing);③ `apply` 100% try-catch → 异常返回 failed 形态,
|
|
13
|
+
// 单插件失败不拖垮其余(官方 mount 对 setup 抛错是「全部逆序回滚 + session open 失败」)。
|
|
14
|
+
import { definePlugin } from '@tanstack/ai-harness'
|
|
15
|
+
import type {
|
|
16
|
+
AnyChatMiddleware,
|
|
17
|
+
AnyTool,
|
|
18
|
+
} from '@tanstack/ai'
|
|
19
|
+
import type {
|
|
20
|
+
AnyCommand,
|
|
21
|
+
PluginContributions,
|
|
22
|
+
PluginSetupContext,
|
|
23
|
+
} from '@tanstack/ai-harness'
|
|
24
|
+
import { CordisEventBus, KNOWN_DSH_EVENTS } from './events'
|
|
25
|
+
|
|
26
|
+
/** DSH 工具 execute 收到的运行上下文(翻译层从官方 ToolExecutionContext 适配而来)。 */
|
|
27
|
+
export interface CordisToolRunContext {
|
|
28
|
+
/** 取消信号(← 官方 `context.abortSignal`)。 */
|
|
29
|
+
signal?: AbortSignal
|
|
30
|
+
/** 调用方标识(← 官方 `context.runId`)。 */
|
|
31
|
+
caller?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
// L1 服务 shim 类型面(规格 §4.5 / 计划 F6-6)
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
//
|
|
38
|
+
// DSH 插件可经 `ctx.fs` / `ctx.shell` / `ctx.sandbox` 触达文件 / 命令 / 沙箱能力。
|
|
39
|
+
// 翻译层只定义**类型面**(下述三个接口)——**实现由宿主注入**(apps/web server 侧把
|
|
40
|
+
// WorkspaceBinder / 执行面后端映射成本接口;包内**不 import** 任何 server 后端,包纯度)。
|
|
41
|
+
//
|
|
42
|
+
// ⚠ effect/session carry-forward(F2-2b 同款约束):DSH 插件主体 cordis 走
|
|
43
|
+
// assemble 期 apply-once(assemble.ts),故 `ctx.fs/shell/sandbox` 当前是
|
|
44
|
+
// **assemble-scoped 绑定**——随插件 apply 一次性注入,生命周期待 F3 定。本文件只在
|
|
45
|
+
// 注释钉住此约束,不改 apply 时机。
|
|
46
|
+
|
|
47
|
+
/** L1 文件服务(→ WorkspaceBinder:读放行 / 写审批语义,实现在 apps/web server 侧)。 */
|
|
48
|
+
export interface CordisFs {
|
|
49
|
+
/** 读文件文本(UTF-8);文件不存在 / 越出工作区 → 抛错。 */
|
|
50
|
+
read(path: string): Promise<string>
|
|
51
|
+
/** 写文件文本(UTF-8);缺父目录自动创建。写走 WorkspaceBinder 审批语义。 */
|
|
52
|
+
write(path: string, content: string): Promise<void>
|
|
53
|
+
/** 列目录条目名(非递归);缺省列工作区根。 */
|
|
54
|
+
list(path?: string): Promise<string[]>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** L1 shell 服务执行选项。 */
|
|
58
|
+
export interface CordisShellExecOptions {
|
|
59
|
+
/** 期望超时(毫秒);实现侧 clamp 到 [MIN,MAX](见 apps/web 工厂)。 */
|
|
60
|
+
timeoutMs?: number
|
|
61
|
+
/** 命令工作目录(相对工作区 root);缺省 = root。 */
|
|
62
|
+
cwd?: string
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** L1 shell 执行产出。 */
|
|
66
|
+
export interface CordisShellExecResult {
|
|
67
|
+
stdout: string
|
|
68
|
+
stderr: string
|
|
69
|
+
exitCode: number
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** L1 shell 服务(→ 执行面后端:桌面本机 hostBackend / 云端 Daytona)。 */
|
|
73
|
+
export interface CordisShell {
|
|
74
|
+
/**
|
|
75
|
+
* 跑一条 shell 命令并等其结束。实现侧施加**超时 clamp**(期望值限幅,防插件传
|
|
76
|
+
* 极端值)+ **输出保尾**(环形缓冲截断,只保留末尾 N 字节,防超长输出撑爆上下文)。
|
|
77
|
+
*/
|
|
78
|
+
exec(command: string, options?: CordisShellExecOptions): Promise<CordisShellExecResult>
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** L1 沙箱服务(DSH `ctx.sandbox.confine` 显式不可用——规格 §4.5)。 */
|
|
82
|
+
export interface CordisSandbox {
|
|
83
|
+
/** 恒 false:本兼容面不提供沙箱隔离(桌面 MVP 用 WorkspaceBinder 替代)。 */
|
|
84
|
+
readonly available: false
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 一组 L1 服务(宿主经 `CordisRunOptions.l1` 注入的单一载体)。 */
|
|
88
|
+
export interface CordisL1Services {
|
|
89
|
+
fs?: CordisFs
|
|
90
|
+
shell?: CordisShell
|
|
91
|
+
sandbox?: CordisSandbox
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* L1 服务工厂(per-session 惰性解析,规格 §4.5 / carry-forward F6-6)。
|
|
96
|
+
*
|
|
97
|
+
* 区别于静态 {@link CordisL1Services} 注入(assemble-scoped,一次构造终身复用):
|
|
98
|
+
* 工厂在插件 setup 重跑时按真实 session 身份惰性解析 L1 服务,故宿主可在工厂内
|
|
99
|
+
* `bind({run})` 得 BoundWorkspace + 叠加审批语义(fs.write 审批外围——apps/web server
|
|
100
|
+
* 侧 `createCordisL1ServicesWithApproval`)。
|
|
101
|
+
*
|
|
102
|
+
* **session 身份来源(H1 生产接线实证)**:session 插件 setup 期 `official.run` 为
|
|
103
|
+
* undefined(run 属 turn / 工具 execute 期),但 `official.session.threadId` 与
|
|
104
|
+
* `official.session.user`(host access 层从可信 session 解析,非客户端可传)已就绪。
|
|
105
|
+
* 故工厂收到的 sessionCtx 带这两项——宿主据此构造 bind 所需的最小 run 身份
|
|
106
|
+
* (binder 只读 `run.threadId` + `run.user.id`),无需等工具 execute 期的真实 run。
|
|
107
|
+
*
|
|
108
|
+
* 包纯度:本类型只是**函数面**,包内不 import WorkspaceBinder / 执行面后端 / 审批实现
|
|
109
|
+
* (那些在 apps/web server 侧)。`sessionCtx.run` 用 `unknown` 承载官方 RunContext、
|
|
110
|
+
* `user` 用结构化最小面(`{ id }`)承载官方 HarnessUser——包内不依赖 ai-harness 运行时
|
|
111
|
+
* 具体类型(避免拉入 ai-harness 运行时面到类型契约)。
|
|
112
|
+
*/
|
|
113
|
+
export type L1ServicesFactory = (sessionCtx: {
|
|
114
|
+
/** 官方 RunContext(工具 execute 期可得;session open setup 期为 undefined)。 */
|
|
115
|
+
run?: unknown
|
|
116
|
+
/** 当前 session 的线程 id(session open setup 期可得,宿主 bind 用)。 */
|
|
117
|
+
threadId?: string
|
|
118
|
+
/** 当前 session 的用户(host access 层可信解析;session open setup 期可得)。 */
|
|
119
|
+
user?: { id: string; name?: string; tenantId?: string }
|
|
120
|
+
}) => CordisL1Services | Promise<CordisL1Services>
|
|
121
|
+
|
|
122
|
+
/** DSH 工具定义(翻译层消费的最小面)。 */
|
|
123
|
+
export interface CordisToolDef {
|
|
124
|
+
name: string
|
|
125
|
+
description?: string
|
|
126
|
+
/** JSON Schema(直传官方 `inputSchema`)。 */
|
|
127
|
+
parameters?: unknown
|
|
128
|
+
/** 输出 schema(`{ schema }` 形态,→ 官方 `outputSchema`)。 */
|
|
129
|
+
output?: { schema?: unknown }
|
|
130
|
+
execute: (args: unknown, ctx: CordisToolRunContext) => unknown | Promise<unknown>
|
|
131
|
+
/** 工具级超时(毫秒),0/undefined = 不限时。 */
|
|
132
|
+
timeoutMs?: number
|
|
133
|
+
/** 延迟加载 → 官方 lazy 工具。 */
|
|
134
|
+
deferLoading?: boolean
|
|
135
|
+
/** 官方无对应,忽略并记入 report 备注字段。 */
|
|
136
|
+
isConcurrencySafe?: boolean
|
|
137
|
+
projectContent?: unknown
|
|
138
|
+
finalizeContent?: unknown
|
|
139
|
+
presentResult?: (args: unknown, result: unknown) => unknown
|
|
140
|
+
presentCall?: (args: unknown) => unknown
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** DSH 系统提示 section。 */
|
|
144
|
+
export interface CordisPromptSection {
|
|
145
|
+
text: string
|
|
146
|
+
/** 默认 system(随其它 plugin prompt 排序);context = 常变文本,单列不进缓存前缀。 */
|
|
147
|
+
placement?: 'system' | 'context'
|
|
148
|
+
id?: string
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** DSH 命令定义。 */
|
|
152
|
+
export interface CordisCommandDef {
|
|
153
|
+
name: string
|
|
154
|
+
description?: string
|
|
155
|
+
run: (args: unknown, ctx: unknown) => unknown | Promise<unknown>
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* 翻译层提供给 DSH `apply` 的 ctx。字段语义对齐 DSH CordisContext,
|
|
160
|
+
* 落点全部是官方 API / 包内模块。
|
|
161
|
+
*/
|
|
162
|
+
export interface CordisContext {
|
|
163
|
+
/** 行 config(patch 行传入的静态对象)。 */
|
|
164
|
+
readonly config: Record<string, unknown>
|
|
165
|
+
/** 读行 config 的某个键。 */
|
|
166
|
+
get(key: string): unknown
|
|
167
|
+
/** 注册工具 → 官方 `tools` contribution;返回注销函数。 */
|
|
168
|
+
tools: { register(def: CordisToolDef): () => void }
|
|
169
|
+
/** 系统提示 section / 常变 context 文本 → 官方 `prompts` contribution。 */
|
|
170
|
+
systemPrompt: {
|
|
171
|
+
section(textOrSection: string | CordisPromptSection): void
|
|
172
|
+
context(text: string): void
|
|
173
|
+
}
|
|
174
|
+
/** 注册命令 → 官方 `commands` contribution。 */
|
|
175
|
+
commands: { register(cmd: CordisCommandDef): () => void }
|
|
176
|
+
/**
|
|
177
|
+
* 打开一个随插件生命周期清理的资源 → 官方 `ctx.resources.acquire`(逆序清理)。
|
|
178
|
+
* `effect(dispose)` 的 open 是 no-op,dispose 由 DSH 提供。
|
|
179
|
+
*/
|
|
180
|
+
effect<T>(dispose: (resource: T) => unknown): (open: () => T | Promise<T>) => Promise<T>
|
|
181
|
+
/** 订阅事件(已知 → middleware,未知 → 包内总线);返回注销函数。 */
|
|
182
|
+
on(event: string, handler: (value: unknown) => void): () => void
|
|
183
|
+
/** 派发事件(已知 → 由 events.ts 映射的 middleware 在对应钩子触发;未知 → 包内总线)。 */
|
|
184
|
+
emit(event: string, ...args: unknown[]): void
|
|
185
|
+
/** 依次过一遍订阅者,每层返回值作为下一层入参(DSH waterfall 子集)。 */
|
|
186
|
+
waterfall(event: string, value: unknown): unknown
|
|
187
|
+
/**
|
|
188
|
+
* 解析 provided-services 注入。含表外键抛错(但激活判定在 apply 之前已做,
|
|
189
|
+
* 走不到这里——见 `runCordisPlugin` 的 inject 预检)。
|
|
190
|
+
*/
|
|
191
|
+
inject(keys: readonly string[]): Promise<Record<string, unknown>>
|
|
192
|
+
/**
|
|
193
|
+
* L1 文件服务(→ WorkspaceBinder)。宿主注入;未注入 = undefined(依赖型插件
|
|
194
|
+
* 声明 `inject: ['fs']` 时,`fs` 不在 provided-services 表 ⇒ 不激活)。
|
|
195
|
+
*/
|
|
196
|
+
readonly fs?: CordisFs
|
|
197
|
+
/** L1 shell 服务(→ 执行面后端,超时 clamp + 输出保尾)。未注入 = undefined。 */
|
|
198
|
+
readonly shell?: CordisShell
|
|
199
|
+
/** L1 沙箱服务(显式不可用,规格 §4.5)。未注入 = undefined。 */
|
|
200
|
+
readonly sandbox?: CordisSandbox
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* 一个 DSH Cordis 插件模块(翻译层消费的最小面)。
|
|
205
|
+
* `apply(ctx, config)` **两参**(硬前置①);`inject` 声明 provided-services 依赖;
|
|
206
|
+
* `Config` 可选自校验器(可调用值,不引入 schemastery 依赖)。
|
|
207
|
+
*/
|
|
208
|
+
export interface CordisPluginModule {
|
|
209
|
+
name: string
|
|
210
|
+
/** 依赖的 provided-services 键;含表外键 ⇒ 插件不激活(硬前置②)。 */
|
|
211
|
+
inject?: ReadonlyArray<string>
|
|
212
|
+
/** 可选 config 自校验器(调用 `Config(config)`,抛错 → warning 降级,不 fail 激活)。 */
|
|
213
|
+
Config?: unknown
|
|
214
|
+
/** 插件主体:注册 tools/prompts/commands、订阅事件、打开 effect 资源。 */
|
|
215
|
+
apply: (ctx: CordisContext, config: unknown) => void | Promise<void>
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 一次 runCordisPlugin 的产出:contributions + 激活状态 report。 */
|
|
219
|
+
export interface CordisRunResult {
|
|
220
|
+
/** apply 是否被调用(inject 不满足时为 false)。 */
|
|
221
|
+
activated: boolean
|
|
222
|
+
/** apply 抛错(→ failed 形态,不拖垮其余插件)。 */
|
|
223
|
+
failed: boolean
|
|
224
|
+
error?: unknown
|
|
225
|
+
/** inject 缺失的键(activated=false 时非空)。 */
|
|
226
|
+
missing?: ReadonlyArray<string>
|
|
227
|
+
/** 官方无对应而忽略的字段备注(F1-5 收集)。 */
|
|
228
|
+
notes?: ReadonlyArray<string>
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** 官方 setup 收集到的 contributions(apply 期累积)。 */
|
|
232
|
+
export interface CordisContributions {
|
|
233
|
+
tools: Array<AnyTool>
|
|
234
|
+
prompts: Array<string | CordisPromptSection>
|
|
235
|
+
commands: Record<string, AnyCommand>
|
|
236
|
+
middleware: Array<AnyChatMiddleware>
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** runCordisPlugin 的运行选项。 */
|
|
240
|
+
export interface CordisRunOptions {
|
|
241
|
+
/** provided-services 表(`inject` 判定与解析的单一来源)。 */
|
|
242
|
+
providedServices?: Readonly<Record<string, unknown>>
|
|
243
|
+
/** 行 config(patch 行)。 */
|
|
244
|
+
config?: Record<string, unknown>
|
|
245
|
+
/** 插件声明的依赖(= mod.inject),预检用。 */
|
|
246
|
+
inject?: ReadonlyArray<string>
|
|
247
|
+
/** 官方 session services(emit/on 桥接目标,可缺省 = 空实现)。 */
|
|
248
|
+
services?: {
|
|
249
|
+
emit: (plugin: string, name: string, value: unknown) => void
|
|
250
|
+
}
|
|
251
|
+
/** 工具适配器:把 CordisToolDef 翻译成官方 AnyTool(events/tool-adapter 解耦注入)。 */
|
|
252
|
+
adaptTool?: (def: CordisToolDef) => AnyTool
|
|
253
|
+
/** 命令适配器:CordisCommandDef → 官方 AnyCommand。 */
|
|
254
|
+
adaptCommand?: (cmd: CordisCommandDef) => AnyCommand
|
|
255
|
+
/**
|
|
256
|
+
* L1 服务 shim(fs/shell/sandbox,规格 §4.5)。宿主注入实现(apps/web server 侧把
|
|
257
|
+
* WorkspaceBinder / 执行面后端映射成 {@link CordisL1Services});缺省 = 三字段
|
|
258
|
+
* undefined(依赖型插件声明 `inject: ['fs']` 等 ⇒ 需 L1 键进 provided-services 表)。
|
|
259
|
+
*
|
|
260
|
+
* ⚠ assemble-scoped 绑定:随插件 apply-once 注入,生命周期待 F3 定(见文件头约束)。
|
|
261
|
+
*/
|
|
262
|
+
l1?: CordisL1Services
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* 判定 provided-services 表是否满足插件 `inject` 依赖。
|
|
267
|
+
* 返回缺失键列表(空 = 满足)。
|
|
268
|
+
*
|
|
269
|
+
* L1 服务键(`fs`/`shell`/`sandbox`,规格 §4.5)不在 provided-services 表里——它们经
|
|
270
|
+
* `opts.l1` 单独注入,是否「已提供」看对应服务是否定义。插件声明 `inject: ['fs']` 时,
|
|
271
|
+
* 宿主注入了 `l1.fs` ⇒ 满足;未注入 ⇒ 缺失(不激活)。L0 键仍只认表内键。
|
|
272
|
+
*/
|
|
273
|
+
function missingInjectKeys(
|
|
274
|
+
inject: ReadonlyArray<string> | undefined,
|
|
275
|
+
provided: Readonly<Record<string, unknown>>,
|
|
276
|
+
l1: CordisL1Services = {},
|
|
277
|
+
): Array<string> {
|
|
278
|
+
if (!inject || inject.length === 0) return []
|
|
279
|
+
return inject.filter((key) => {
|
|
280
|
+
if (key === 'fs') return !l1.fs
|
|
281
|
+
if (key === 'shell') return !l1.shell
|
|
282
|
+
if (key === 'sandbox') return !l1.sandbox
|
|
283
|
+
return !(key in provided)
|
|
284
|
+
})
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* 跑一个 DSH 插件模块:预检 inject → 自校验 config → try-catch 包住整个 apply +
|
|
289
|
+
* contribution 收集。任一异常 → 返回 failed 形态,绝不向上抛(单插件失败不拖垮其余)。
|
|
290
|
+
*/
|
|
291
|
+
export async function runCordisPlugin(
|
|
292
|
+
mod: CordisPluginModule,
|
|
293
|
+
official: PluginSetupContext,
|
|
294
|
+
opts: CordisRunOptions = {},
|
|
295
|
+
): Promise<{ contributions: CordisContributions; result: CordisRunResult }> {
|
|
296
|
+
const provided = opts.providedServices ?? {}
|
|
297
|
+
const l1 = opts.l1 ?? {}
|
|
298
|
+
const contributions: CordisContributions = {
|
|
299
|
+
tools: [],
|
|
300
|
+
prompts: [],
|
|
301
|
+
commands: {},
|
|
302
|
+
middleware: [],
|
|
303
|
+
}
|
|
304
|
+
const notes: Array<string> = []
|
|
305
|
+
|
|
306
|
+
// 硬前置②:inject 含 provided-services 表外键 → 不激活(不调 apply)。
|
|
307
|
+
// L1 键(fs/shell/sandbox)按 l1 注入判定,不走 provided-services 表(见 missingInjectKeys)。
|
|
308
|
+
const missing = missingInjectKeys(opts.inject ?? mod.inject, provided, l1)
|
|
309
|
+
if (missing.length > 0) {
|
|
310
|
+
return {
|
|
311
|
+
contributions,
|
|
312
|
+
result: { activated: false, failed: false, missing },
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const bus = new CordisEventBus()
|
|
317
|
+
|
|
318
|
+
const ctx: CordisContext = {
|
|
319
|
+
config: opts.config ?? {},
|
|
320
|
+
get: (key) => (opts.config ?? {})[key],
|
|
321
|
+
tools: {
|
|
322
|
+
register: (def) => {
|
|
323
|
+
const tool = opts.adaptTool
|
|
324
|
+
? opts.adaptTool(def)
|
|
325
|
+
: ({ name: def.name, description: def.description ?? '' } as AnyTool)
|
|
326
|
+
contributions.tools.push(tool)
|
|
327
|
+
return () => {
|
|
328
|
+
const at = contributions.tools.indexOf(tool)
|
|
329
|
+
if (at >= 0) contributions.tools.splice(at, 1)
|
|
330
|
+
}
|
|
331
|
+
},
|
|
332
|
+
},
|
|
333
|
+
systemPrompt: {
|
|
334
|
+
section: (textOrSection) => {
|
|
335
|
+
contributions.prompts.push(
|
|
336
|
+
typeof textOrSection === 'string'
|
|
337
|
+
? textOrSection
|
|
338
|
+
: textOrSection,
|
|
339
|
+
)
|
|
340
|
+
},
|
|
341
|
+
context: (text) => {
|
|
342
|
+
contributions.prompts.push({ text, placement: 'context' })
|
|
343
|
+
},
|
|
344
|
+
},
|
|
345
|
+
commands: {
|
|
346
|
+
register: (cmd) => {
|
|
347
|
+
const command: AnyCommand = opts.adaptCommand
|
|
348
|
+
? opts.adaptCommand(cmd)
|
|
349
|
+
: {
|
|
350
|
+
description: cmd.description ?? cmd.name,
|
|
351
|
+
run: (input: unknown, commandCtx: unknown) => cmd.run(input, commandCtx),
|
|
352
|
+
}
|
|
353
|
+
contributions.commands[cmd.name] = command
|
|
354
|
+
return () => {
|
|
355
|
+
if (contributions.commands[cmd.name] === command) {
|
|
356
|
+
delete contributions.commands[cmd.name]
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
},
|
|
360
|
+
},
|
|
361
|
+
// `effect` → 官方 resources.acquire:open 由 DSH 提供,close = DSH 的 dispose。
|
|
362
|
+
effect: <T,>(dispose: (resource: T) => unknown) =>
|
|
363
|
+
(open: () => T | Promise<T>) =>
|
|
364
|
+
official.resources.acquire(open, dispose as (resource: T) => unknown),
|
|
365
|
+
on: (event, handler) =>
|
|
366
|
+
bus.on(event, handler) as () => void,
|
|
367
|
+
emit: (event, ...args) => {
|
|
368
|
+
// 已知事件由 events.ts 映射成 middleware contribution,在对应钩子触发;
|
|
369
|
+
// 这里 emit 仅喂包内总线(插件自发自收 / 未知事件互通)。
|
|
370
|
+
bus.emit(event, args)
|
|
371
|
+
// 桥接到官方 session services(客户端可观察),emit 失败不影响 apply。
|
|
372
|
+
try {
|
|
373
|
+
opts.services?.emit(mod.name, event, args)
|
|
374
|
+
} catch {
|
|
375
|
+
/* 官方 emit 桥接尽力而为 */
|
|
376
|
+
}
|
|
377
|
+
},
|
|
378
|
+
waterfall: (event, value) => bus.waterfall(event, value),
|
|
379
|
+
inject: async (keys) => {
|
|
380
|
+
const stillMissing = missingInjectKeys(keys, provided, l1)
|
|
381
|
+
if (stillMissing.length > 0) {
|
|
382
|
+
throw new Error(
|
|
383
|
+
`Plugin ${mod.name} inject missing provided-services: ${stillMissing.join(', ')}`,
|
|
384
|
+
)
|
|
385
|
+
}
|
|
386
|
+
const out: Record<string, unknown> = {}
|
|
387
|
+
for (const key of keys) {
|
|
388
|
+
// L1 键从 l1 载体取(非 provided-services 表)。
|
|
389
|
+
if (key === 'fs' || key === 'shell' || key === 'sandbox') {
|
|
390
|
+
out[key] = l1[key]
|
|
391
|
+
} else {
|
|
392
|
+
out[key] = provided[key]
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
return out
|
|
396
|
+
},
|
|
397
|
+
// L1 服务 shim(规格 §4.5):实现由宿主经 opts.l1 注入,缺省 undefined。
|
|
398
|
+
...(l1.fs ? { fs: l1.fs } : {}),
|
|
399
|
+
...(l1.shell ? { shell: l1.shell } : {}),
|
|
400
|
+
...(l1.sandbox ? { sandbox: l1.sandbox } : {}),
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
// 硬前置①:两参 apply(ctx, config)。已知事件订阅 → middleware contribution。
|
|
404
|
+
try {
|
|
405
|
+
if (typeof mod.Config === 'function') {
|
|
406
|
+
// TODO: 真实 DSH schemastery 对象需 .parse() 校验,与纯可调用校验器区分——
|
|
407
|
+
// ConfigOption 转换是规格 §3 后续增项。
|
|
408
|
+
try {
|
|
409
|
+
mod.Config(ctx.config)
|
|
410
|
+
} catch (configError) {
|
|
411
|
+
// config 自校验抛错 → warning 降级(不 fail 激活),对齐 DSH 配置错误路径。
|
|
412
|
+
notes.push(
|
|
413
|
+
`config validation warning: ${String(
|
|
414
|
+
configError instanceof Error ? configError.message : configError,
|
|
415
|
+
)}`,
|
|
416
|
+
)
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
await mod.apply(ctx, ctx.config)
|
|
420
|
+
contributions.middleware.push(...bus.drainMiddleware())
|
|
421
|
+
} catch (error) {
|
|
422
|
+
// 硬前置③:apply 100% try-catch → failed 形态,单插件失败不拖垮其余。
|
|
423
|
+
return {
|
|
424
|
+
contributions,
|
|
425
|
+
result: { activated: true, failed: true, error },
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
return {
|
|
430
|
+
contributions,
|
|
431
|
+
result: {
|
|
432
|
+
activated: true,
|
|
433
|
+
failed: false,
|
|
434
|
+
notes: notes.length > 0 ? notes : undefined,
|
|
435
|
+
},
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* 把一个 DSH Cordis 插件模块翻译成官方 HarnessPlugin。
|
|
441
|
+
* `setup` 跑 `runCordisPlugin`,收集 tools/prompts/commands/middleware → PluginContributions。
|
|
442
|
+
* 已知事件订阅经 events.ts 注册成 middleware contribution(KNOWN_DSH_EVENTS 判定)。
|
|
443
|
+
*/
|
|
444
|
+
export function cordisPluginToHarness(
|
|
445
|
+
mod: CordisPluginModule,
|
|
446
|
+
opts: CordisRunOptions = {},
|
|
447
|
+
) {
|
|
448
|
+
return definePlugin({
|
|
449
|
+
name: mod.name,
|
|
450
|
+
lifetime: 'session',
|
|
451
|
+
setup: async (official: PluginSetupContext): Promise<PluginContributions> => {
|
|
452
|
+
const { contributions, result } = await runCordisPlugin(mod, official, {
|
|
453
|
+
...opts,
|
|
454
|
+
inject: opts.inject ?? mod.inject,
|
|
455
|
+
})
|
|
456
|
+
if (result.failed) {
|
|
457
|
+
// 官方 setup 抛错会拖垮整个 mount(全部逆序回滚)。这里降级为 log,并
|
|
458
|
+
// **丢弃全部部分 contributions**(failed → 空 contributions)——apply 中途抛错
|
|
459
|
+
// 说明插件状态不可信(部分工具闭包可能依赖未初始化状态),"failed" 语义 =
|
|
460
|
+
// 「该插件未贡献任何可靠内容」。给 F1-5 干净契约:failed 插件进
|
|
461
|
+
// report.failed,其部分工具不进 surface。单插件失败不拖垮其余。
|
|
462
|
+
try {
|
|
463
|
+
official.logger.error(
|
|
464
|
+
`cordis plugin ${mod.name} apply failed: ${String(
|
|
465
|
+
result.error instanceof Error ? result.error.message : result.error,
|
|
466
|
+
)}`,
|
|
467
|
+
)
|
|
468
|
+
} catch {
|
|
469
|
+
/* logger 失败不影响 */
|
|
470
|
+
}
|
|
471
|
+
return {}
|
|
472
|
+
}
|
|
473
|
+
const out: PluginContributions = {}
|
|
474
|
+
if (contributions.tools.length > 0) out.tools = contributions.tools
|
|
475
|
+
if (contributions.prompts.length > 0) {
|
|
476
|
+
out.prompts = contributions.prompts.map((prompt) =>
|
|
477
|
+
typeof prompt === 'string'
|
|
478
|
+
? prompt
|
|
479
|
+
: {
|
|
480
|
+
id: prompt.id ?? `${mod.name}#${prompt.placement ?? 'system'}`,
|
|
481
|
+
text: prompt.text,
|
|
482
|
+
...(prompt.placement ? { placement: prompt.placement } : {}),
|
|
483
|
+
},
|
|
484
|
+
)
|
|
485
|
+
}
|
|
486
|
+
if (Object.keys(contributions.commands).length > 0) {
|
|
487
|
+
out.commands = contributions.commands
|
|
488
|
+
}
|
|
489
|
+
if (contributions.middleware.length > 0) out.middleware = contributions.middleware
|
|
490
|
+
return out
|
|
491
|
+
},
|
|
492
|
+
})
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
/** 供 F1-5 assemble 判定:某事件名是否为已知事件(→ middleware)。 */
|
|
496
|
+
export { KNOWN_DSH_EVENTS }
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
2
|
+
// DSH 事件 ↔ 官方 chat middleware 映射 + 包内互通总线。
|
|
3
|
+
//
|
|
4
|
+
// 已知事件映射到官方 middleware 钩子(规格 §3 映射表):
|
|
5
|
+
// pre-execute → onBeforeToolCall { type:'skip', result } = 跳过执行且模型收到给定结果(DSH reject)
|
|
6
|
+
// post-execute → onAfterToolCall { type:'replaceResult', result } = 改写结果
|
|
7
|
+
// llm / stream → onChunk 每个 chunk 派发
|
|
8
|
+
// turn-stopping → onShouldContinue 返回 false(= stop)终止 agent loop
|
|
9
|
+
// 未知事件 → 包内互通总线(emit / on / waterfall,对齐旧 kernel EventBus 中 DSH 插件
|
|
10
|
+
// 实际用的 emit/waterfall 子集)。已知事件也可经包内总线在插件间互通(ctx.on 订阅)。
|
|
11
|
+
import type { AnyChatMiddleware, StreamChunk } from '@tanstack/ai'
|
|
12
|
+
import type {
|
|
13
|
+
AfterToolCallInfo,
|
|
14
|
+
BeforeToolCallDecision,
|
|
15
|
+
ToolCallHookContext,
|
|
16
|
+
} from '@tanstack/ai'
|
|
17
|
+
|
|
18
|
+
/** 已知 DSH 事件名 → 官方 middleware 钩子名。 */
|
|
19
|
+
export const DSH_EVENT_TO_HOOK: Readonly<Record<string, string>> = {
|
|
20
|
+
'pre-execute': 'onBeforeToolCall',
|
|
21
|
+
'post-execute': 'onAfterToolCall',
|
|
22
|
+
llm: 'onChunk',
|
|
23
|
+
stream: 'onChunk',
|
|
24
|
+
'turn-stopping': 'onShouldContinue',
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 已知事件名集合(context.ts 判定「走 middleware 还是包内总线」用)。 */
|
|
28
|
+
export const KNOWN_DSH_EVENTS: ReadonlySet<string> = new Set(
|
|
29
|
+
Object.keys(DSH_EVENT_TO_HOOK),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
/** DSH pre-execute 订阅者可返回的决策(reject 语义)。 */
|
|
33
|
+
export interface DshPreExecuteDecision {
|
|
34
|
+
type: 'skip' | 'abort'
|
|
35
|
+
result?: unknown
|
|
36
|
+
reason?: string
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 把 pre-execute 订阅者返回值翻译成官方 BeforeToolCallDecision。 */
|
|
40
|
+
function toBeforeToolCallDecision(value: unknown): BeforeToolCallDecision {
|
|
41
|
+
if (value === undefined || value === null) return undefined
|
|
42
|
+
if (typeof value === 'object') {
|
|
43
|
+
const decision = value as DshPreExecuteDecision
|
|
44
|
+
if (decision.type === 'skip') return { type: 'skip', result: decision.result }
|
|
45
|
+
if (decision.type === 'abort') {
|
|
46
|
+
return { type: 'abort', reason: decision.reason }
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return undefined
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 包内互通总线:已知 + 未知事件的插件间派发(ctx.on / ctx.emit / ctx.waterfall 的落点)。
|
|
54
|
+
* 已知事件除走总线外,还由 {@link middlewareForBus} 注册成官方 middleware contribution,
|
|
55
|
+
* 在对应钩子触发已注册的处理器。
|
|
56
|
+
*/
|
|
57
|
+
export class CordisEventBus {
|
|
58
|
+
private readonly handlers = new Map<string, Set<(value: unknown) => void>>()
|
|
59
|
+
/** 已注册的已知事件处理器(drainMiddleware 时翻译成 middleware)。 */
|
|
60
|
+
private readonly knownHandlers = new Map<
|
|
61
|
+
string,
|
|
62
|
+
Set<(value: unknown) => unknown>
|
|
63
|
+
>()
|
|
64
|
+
|
|
65
|
+
/** 订阅事件(已知 + 未知都走这里);返回注销函数。 */
|
|
66
|
+
on(event: string, handler: (value: unknown) => void): () => void {
|
|
67
|
+
let set = this.handlers.get(event)
|
|
68
|
+
if (!set) {
|
|
69
|
+
set = new Set()
|
|
70
|
+
this.handlers.set(event, set)
|
|
71
|
+
}
|
|
72
|
+
set.add(handler)
|
|
73
|
+
if (KNOWN_DSH_EVENTS.has(event)) {
|
|
74
|
+
let known = this.knownHandlers.get(event)
|
|
75
|
+
if (!known) {
|
|
76
|
+
known = new Set()
|
|
77
|
+
this.knownHandlers.set(event, known)
|
|
78
|
+
}
|
|
79
|
+
known.add(handler as (value: unknown) => unknown)
|
|
80
|
+
}
|
|
81
|
+
return () => {
|
|
82
|
+
set?.delete(handler)
|
|
83
|
+
this.knownHandlers.get(event)?.delete(handler as (value: unknown) => unknown)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 派发事件到所有订阅者(未知事件互通 + 已知事件的插件间直达)。 */
|
|
88
|
+
emit(event: string, value: unknown): void {
|
|
89
|
+
const set = this.handlers.get(event)
|
|
90
|
+
if (!set) return
|
|
91
|
+
for (const handler of [...set]) handler(value)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 依次过一遍订阅者,每层返回值作为下一层入参(DSH waterfall 子集)。 */
|
|
95
|
+
waterfall(event: string, value: unknown): unknown {
|
|
96
|
+
const set = this.handlers.get(event)
|
|
97
|
+
if (!set || set.size === 0) return value
|
|
98
|
+
let current = value
|
|
99
|
+
for (const handler of [...set]) {
|
|
100
|
+
const next = (handler as (v: unknown) => unknown)(current)
|
|
101
|
+
if (next !== undefined) current = next
|
|
102
|
+
}
|
|
103
|
+
return current
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* 把已注册的已知事件处理器翻译成官方 middleware contribution(每个已知事件一个
|
|
108
|
+
* middleware,仅当有处理器时)。调用一次(apply 之后),产出的 middleware 进
|
|
109
|
+
* PluginContributions.middleware。
|
|
110
|
+
*/
|
|
111
|
+
drainMiddleware(): Array<AnyChatMiddleware> {
|
|
112
|
+
const out: Array<AnyChatMiddleware> = []
|
|
113
|
+
for (const [event, handlers] of this.knownHandlers) {
|
|
114
|
+
const hook = DSH_EVENT_TO_HOOK[event]
|
|
115
|
+
if (handlers.size === 0 || !hook) continue
|
|
116
|
+
out.push(this.buildMiddleware(event, hook, [...handlers]))
|
|
117
|
+
}
|
|
118
|
+
return out
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private buildMiddleware(
|
|
122
|
+
event: string,
|
|
123
|
+
hook: string,
|
|
124
|
+
handlers: Array<(value: unknown) => unknown>,
|
|
125
|
+
): AnyChatMiddleware {
|
|
126
|
+
const runHandlers = (value: unknown): unknown => {
|
|
127
|
+
let current = value
|
|
128
|
+
for (const handler of handlers) {
|
|
129
|
+
const next = handler(current)
|
|
130
|
+
if (next !== undefined) current = next
|
|
131
|
+
}
|
|
132
|
+
return current
|
|
133
|
+
}
|
|
134
|
+
switch (hook) {
|
|
135
|
+
case 'onBeforeToolCall':
|
|
136
|
+
return {
|
|
137
|
+
name: `dsh-compat:event:${event}`,
|
|
138
|
+
onBeforeToolCall: (
|
|
139
|
+
_ctx,
|
|
140
|
+
hookCtx: ToolCallHookContext,
|
|
141
|
+
): BeforeToolCallDecision =>
|
|
142
|
+
toBeforeToolCallDecision(runHandlers(hookCtx)),
|
|
143
|
+
}
|
|
144
|
+
case 'onAfterToolCall':
|
|
145
|
+
return {
|
|
146
|
+
name: `dsh-compat:event:${event}`,
|
|
147
|
+
onAfterToolCall: (_ctx, info: AfterToolCallInfo) => {
|
|
148
|
+
const value = runHandlers(info)
|
|
149
|
+
if (
|
|
150
|
+
typeof value === 'object' &&
|
|
151
|
+
value !== null &&
|
|
152
|
+
'result' in (value as Record<string, unknown>) &&
|
|
153
|
+
(value as { type?: string }).type === 'replaceResult'
|
|
154
|
+
) {
|
|
155
|
+
return { type: 'replaceResult', result: (value as { result: unknown }).result }
|
|
156
|
+
}
|
|
157
|
+
return undefined
|
|
158
|
+
},
|
|
159
|
+
}
|
|
160
|
+
case 'onChunk':
|
|
161
|
+
return {
|
|
162
|
+
name: `dsh-compat:event:${event}`,
|
|
163
|
+
onChunk: (_ctx, chunk: StreamChunk) => {
|
|
164
|
+
runHandlers(chunk)
|
|
165
|
+
return undefined
|
|
166
|
+
},
|
|
167
|
+
}
|
|
168
|
+
case 'onShouldContinue':
|
|
169
|
+
return {
|
|
170
|
+
name: `dsh-compat:event:${event}`,
|
|
171
|
+
onShouldContinue: (_ctx, state) => {
|
|
172
|
+
const value = runHandlers(state)
|
|
173
|
+
// DSH turn-stopping 返回 stop / { stop:true } → 终止 agent loop。
|
|
174
|
+
if (value === 'stop') return false
|
|
175
|
+
if (
|
|
176
|
+
typeof value === 'object' &&
|
|
177
|
+
value !== null &&
|
|
178
|
+
(value as { stop?: unknown }).stop === true
|
|
179
|
+
) {
|
|
180
|
+
return false
|
|
181
|
+
}
|
|
182
|
+
return undefined
|
|
183
|
+
},
|
|
184
|
+
}
|
|
185
|
+
default:
|
|
186
|
+
return { name: `dsh-compat:event:${event}` }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|