dsh-swarm-console 0.2.1 → 0.2.2
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/README.md +109 -109
- package/docs/DETAIL.md +68 -62
- package/index.js +379 -379
- package/lib/core/verify.js +214 -177
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1,379 +1,379 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Swarm Console —— 可安装的 DSH Host 插件骨架(阶段3A)。
|
|
3
|
-
* 只做一件事:把一个任务交给一个外部 agent 执行一次,返回 stopReason / text / ms。
|
|
4
|
-
* 画布与交付门禁尚未实现(见 docs/DETAIL.md)。
|
|
5
|
-
*
|
|
6
|
-
* 复用 plugin/lib/adapter.js 的 callChat —— 唯一实现在包内,不复制第二份。
|
|
7
|
-
* src/external-agent-adapter.js 是反向 re-export 的兼容 shim。
|
|
8
|
-
*/
|
|
9
|
-
import { callChat } from './lib/adapter.js'
|
|
10
|
-
import { z } from './lib/core/mini-schema.js'
|
|
11
|
-
import { verifyContract, verifyRun, verifyStatus, guardCaller, gateApprove, gateRetry, gateStatus } from './lib/core/verify.js'
|
|
12
|
-
|
|
13
|
-
export const inject = ['tools']
|
|
14
|
-
|
|
15
|
-
/**
|
|
16
|
-
* 校验画像表。每个条目必须有 baseUrl / apiKeyEnv / models 三项,
|
|
17
|
-
* 缺一就 throw —— 激活即失败,不静默跳过。
|
|
18
|
-
*/
|
|
19
|
-
function validateAgents(agents) {
|
|
20
|
-
if (typeof agents !== 'object' || agents === null || Array.isArray(agents)) {
|
|
21
|
-
throw new Error('externalAgents 必须是对象')
|
|
22
|
-
}
|
|
23
|
-
for (const [name, p] of Object.entries(agents)) {
|
|
24
|
-
if (typeof p !== 'object' || p === null) {
|
|
25
|
-
throw new Error(`externalAgents.${name} 必须是对象`)
|
|
26
|
-
}
|
|
27
|
-
for (const key of ['baseUrl', 'apiKeyEnv', 'models']) {
|
|
28
|
-
const v = p[key]
|
|
29
|
-
const bad = key === 'models' ? !Array.isArray(v) || v.length === 0 : typeof v !== 'string' || v.trim() === ''
|
|
30
|
-
if (bad) throw new Error(`externalAgents.${name}.${key} 缺失或格式不对(必须是 ${key === 'models' ? '非空数组' : '非空字符串'})`)
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
/** 选一个画像:显式 agent → 唯一条目 → 报错。 */
|
|
36
|
-
function pickAgent(agents, requested) {
|
|
37
|
-
if (typeof requested === 'string' && requested !== '') {
|
|
38
|
-
if (agents[requested] === undefined) throw new Error(`未知的 agent "${requested}"`)
|
|
39
|
-
return { name: requested, profile: agents[requested] }
|
|
40
|
-
}
|
|
41
|
-
const names = Object.keys(agents)
|
|
42
|
-
if (names.length === 1) return { name: names[0], profile: agents[names[0]] }
|
|
43
|
-
if (names.length === 0) throw new Error('没有配置任何 externalAgents')
|
|
44
|
-
throw new Error('指定了多个 externalAgents,请用 agent 参数指明用哪一个')
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* 跑一次外部 agent。取消时返回 cancelled,不抛。
|
|
49
|
-
* signal 从 exec 透传给 callChat;callChat 内部会把 abort 转成异常,这里捕获后归一化。
|
|
50
|
-
*/
|
|
51
|
-
async function runExternal(agents, args, signal) {
|
|
52
|
-
const { profile } = pickAgent(agents, args.agent)
|
|
53
|
-
const prompt = typeof args.task === 'string' ? args.task : ''
|
|
54
|
-
if (prompt.trim() === '') throw new Error('task 不能为空')
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
const text = await callChat({
|
|
58
|
-
profile,
|
|
59
|
-
prompt,
|
|
60
|
-
model: typeof args.model === 'string' && args.model !== '' ? args.model : undefined,
|
|
61
|
-
signal,
|
|
62
|
-
})
|
|
63
|
-
return { stopReason: 'completed', text }
|
|
64
|
-
} catch (error) {
|
|
65
|
-
// 取消:exec.signal 触发,或底层 AbortError —— 不抛,归一化成 cancelled
|
|
66
|
-
const aborted = (signal && signal.aborted) || error?.name === 'AbortError' ||
|
|
67
|
-
/abort/i.test(String(error?.message ?? ''))
|
|
68
|
-
if (aborted) return { stopReason: 'cancelled', text: '' }
|
|
69
|
-
return { stopReason: 'error', text: String(error?.message ?? error) }
|
|
70
|
-
}
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
export function apply(ctx, config) {
|
|
74
|
-
const agents = config?.externalAgents ?? {}
|
|
75
|
-
validateAgents(agents)
|
|
76
|
-
|
|
77
|
-
ctx.effect(() => ctx.tools.register({
|
|
78
|
-
name: 'swarm_run',
|
|
79
|
-
description: '把一个任务交给一个外部 agent 执行一次,返回 stopReason 与文本结果。',
|
|
80
|
-
parameters: {
|
|
81
|
-
type: 'object',
|
|
82
|
-
properties: {
|
|
83
|
-
agent: { type: 'string', description: 'externalAgents 里的键;省略则用唯一的那个' },
|
|
84
|
-
task: { type: 'string' },
|
|
85
|
-
model: { type: 'string' },
|
|
86
|
-
},
|
|
87
|
-
required: ['task'],
|
|
88
|
-
additionalProperties: false,
|
|
89
|
-
},
|
|
90
|
-
output: {
|
|
91
|
-
schema: {
|
|
92
|
-
type: 'object',
|
|
93
|
-
properties: {
|
|
94
|
-
stopReason: { type: 'string' },
|
|
95
|
-
text: { type: 'string' },
|
|
96
|
-
ms: { type: 'number' },
|
|
97
|
-
},
|
|
98
|
-
required: ['stopReason', 'text', 'ms'],
|
|
99
|
-
},
|
|
100
|
-
render: (args, value) => [{ type: 'text', text: `[${value.stopReason}] ${value.text}` }],
|
|
101
|
-
},
|
|
102
|
-
async execute(args, exec) {
|
|
103
|
-
const t0 = Date.now()
|
|
104
|
-
const { stopReason, text } = await runExternal(agents, args, exec?.signal)
|
|
105
|
-
return { stopReason, text, ms: Date.now() - t0 }
|
|
106
|
-
},
|
|
107
|
-
}))
|
|
108
|
-
|
|
109
|
-
registerVerifyTools(ctx)
|
|
110
|
-
registerGateCommands(ctx)
|
|
111
|
-
// 卡片与 skill 是可选增强(仅在挂载 action-cards 的 profile 生效);v1 默认入口是斜杠命令。
|
|
112
|
-
// 两者都各自降级,任一失败都不阻塞 verify_* 三工具与斜杠命令。
|
|
113
|
-
registerGateSkill(ctx)
|
|
114
|
-
registerGateCard(ctx)
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* C1/C2 · 门禁放行斜杠命令(v1 默认入口,用户触发,不走模型工具)。
|
|
119
|
-
* commands 由 dsh base 自带;仍走 inject 保持挂载时机安全。
|
|
120
|
-
* 命令名 kebab-case、不带斜杠;handler 返回 {kind:'success'|'error', text}。
|
|
121
|
-
*/
|
|
122
|
-
/** P0-4 · 从工具/命令调用上下文取 sessionId,拿不到用 default。 */
|
|
123
|
-
function sessionOf(invocation) {
|
|
124
|
-
const id = invocation?.agent?.session?.id
|
|
125
|
-
return typeof id === 'string' && id !== '' ? id : 'default'
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
function registerGateCommands(ctx) {
|
|
129
|
-
if (typeof ctx.inject !== 'function') return
|
|
130
|
-
ctx.inject(['commands'], (ctx) => {
|
|
131
|
-
const commands = ctx.commands
|
|
132
|
-
if (!commands || typeof commands.register !== 'function') return
|
|
133
|
-
const defs = [
|
|
134
|
-
{
|
|
135
|
-
name: 'gate-approve',
|
|
136
|
-
description: '放行一个已 GREEN 的门禁契约(仅用户可触发)',
|
|
137
|
-
input: { hint: '<contractId> [evidenceHash]' },
|
|
138
|
-
// 可传第二参数 evidenceHash 做过期校验;不传时以 runs 里的为最新
|
|
139
|
-
handler: ({ agent, rawInput }) => {
|
|
140
|
-
const parts = String(rawInput ?? '').trim().split(/\s+/)
|
|
141
|
-
return gateApprove({
|
|
142
|
-
contractId: parts[0] ?? '',
|
|
143
|
-
sessionId: sessionOf({ agent }),
|
|
144
|
-
...(parts[1] ? { expectedHash: parts[1] } : {}),
|
|
145
|
-
})
|
|
146
|
-
},
|
|
147
|
-
},
|
|
148
|
-
{
|
|
149
|
-
name: 'gate-retry',
|
|
150
|
-
description: '重跑某契约的门禁校验并刷新决定',
|
|
151
|
-
input: { hint: '<contractId>' },
|
|
152
|
-
handler: ({ agent, rawInput }) => gateRetry({ contractId: String(rawInput ?? '').trim(), sessionId: sessionOf({ agent }) }),
|
|
153
|
-
},
|
|
154
|
-
{
|
|
155
|
-
name: 'gate-status',
|
|
156
|
-
description: '
|
|
157
|
-
input: { hint: '<contractId
|
|
158
|
-
handler: ({ agent, rawInput }) => gateStatus({ contractId: String(rawInput ?? '').trim(), sessionId: sessionOf({ agent }) }),
|
|
159
|
-
},
|
|
160
|
-
]
|
|
161
|
-
for (const def of defs) ctx.effect(() => commands.register(def))
|
|
162
|
-
})
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
/**
|
|
166
|
-
* 必改1 · 注册运行期 skill,让门禁卡的 propose_action 可用。
|
|
167
|
-
* DSH action-cards 的规则:根 Agent 必须先加载该种类声明的 Skill,propose_action 才会出现。
|
|
168
|
-
* 宿主无 skills 服务或注册失败时静默跳过(只影响卡片,不影响三工具)。
|
|
169
|
-
*/
|
|
170
|
-
const GATE_SKILL_NAME = 'dsh-swarm-console-verify'
|
|
171
|
-
const GATE_SKILL_CONTENT = [
|
|
172
|
-
'# Swarm Console 门禁',
|
|
173
|
-
'',
|
|
174
|
-
'当你需要把任务契约冻结、跑证据校验、或让用户对门禁结论做放行决定时使用本 skill。',
|
|
175
|
-
'流程:verify_contract → verify_run → verify_status;结论为 GREEN/YELLOW/RED。',
|
|
176
|
-
'',
|
|
177
|
-
'- 先调用 verify_contract 冻结目标与验收条件,拿到 contractId。',
|
|
178
|
-
'- 再调用 verify_run 得到判定。RED 的复现命令会随输出给出,可复制执行。',
|
|
179
|
-
'- 需要用户决定时,用 propose_action 提议门禁卡(action: dsh-swarm-console/gate)。',
|
|
180
|
-
'- approve = 用户放行,仅在 GREEN 时允许;非 GREEN 不得 approve,应 retry。',
|
|
181
|
-
'- retry = 重跑校验并刷新卡片;只有用户可以操作卡片,agent 代批会被拒绝。',
|
|
182
|
-
'',
|
|
183
|
-
'不要用本 skill 承诺画布或多阶段状态机(尚未实现)。',
|
|
184
|
-
].join('\n')
|
|
185
|
-
|
|
186
|
-
function registerGateSkill(ctx) {
|
|
187
|
-
// 可选服务走 inject:apply 阶段同步 get 时,晚挂载的服务还没就绪。
|
|
188
|
-
// 服务缺席时 inject 不触发回调,不抛错,verify_* 三工具照常注册。
|
|
189
|
-
try {
|
|
190
|
-
if (typeof ctx.inject !== 'function') return
|
|
191
|
-
ctx.inject(['skills'], (ctx) => {
|
|
192
|
-
try {
|
|
193
|
-
const skills = ctx.skills
|
|
194
|
-
if (!skills || typeof skills.register !== 'function') return
|
|
195
|
-
ctx.effect(() => skills.register({
|
|
196
|
-
name: GATE_SKILL_NAME,
|
|
197
|
-
description: 'Swarm Console 交付门禁:冻结契约、跑证据校验、由用户 approve/retry。',
|
|
198
|
-
content: GATE_SKILL_CONTENT,
|
|
199
|
-
source: 'runtime', // SkillRegistration 必填;缺它 skill 能注册但加载失败
|
|
200
|
-
invocation: { modelInvocable: true, userInvocable: true },
|
|
201
|
-
}))
|
|
202
|
-
} catch {
|
|
203
|
-
// 注册失败不阻塞三工具
|
|
204
|
-
}
|
|
205
|
-
})
|
|
206
|
-
} catch {
|
|
207
|
-
// inject 本身失败也不阻塞
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** D5 · 三个 verify 工具。核心逻辑在 lib/core/verify.js,这里只做薄封装。 */
|
|
212
|
-
function registerVerifyTools(ctx) {
|
|
213
|
-
const defs = [
|
|
214
|
-
{
|
|
215
|
-
name: 'verify_contract',
|
|
216
|
-
description: '冻结一个任务契约(目标/约束/验收条件),返回 contract.id。契约内容变化会换 id。',
|
|
217
|
-
parameters: {
|
|
218
|
-
type: 'object',
|
|
219
|
-
properties: {
|
|
220
|
-
objective: { type: 'string' },
|
|
221
|
-
constraints: { type: 'array', items: { type: 'string' } },
|
|
222
|
-
criteria: {
|
|
223
|
-
type: 'array',
|
|
224
|
-
items: {
|
|
225
|
-
type: 'object',
|
|
226
|
-
properties: {
|
|
227
|
-
id: { type: 'string' },
|
|
228
|
-
text: { type: 'string' },
|
|
229
|
-
checkIds: { type: 'array', items: { type: 'string' } },
|
|
230
|
-
},
|
|
231
|
-
required: ['id', 'text'],
|
|
232
|
-
},
|
|
233
|
-
},
|
|
234
|
-
},
|
|
235
|
-
required: ['objective'],
|
|
236
|
-
additionalProperties: false,
|
|
237
|
-
},
|
|
238
|
-
output: {
|
|
239
|
-
schema: { type: 'object', properties: { contractId: { type: 'string' } }, required: ['contractId'] },
|
|
240
|
-
render: (args, v) => [{ type: 'text', text: `contract ${v.contractId} 已冻结` }],
|
|
241
|
-
},
|
|
242
|
-
execute: async (args) => verifyContract(args),
|
|
243
|
-
},
|
|
244
|
-
{
|
|
245
|
-
name: 'verify_run',
|
|
246
|
-
description: '按策略跑一次证据校验,返回 GREEN/YELLOW/RED 三态与可复现命令。',
|
|
247
|
-
parameters: {
|
|
248
|
-
type: 'object',
|
|
249
|
-
properties: {
|
|
250
|
-
contractId: { type: 'string' },
|
|
251
|
-
checks: { type: 'array', items: { type: 'object' } },
|
|
252
|
-
},
|
|
253
|
-
required: ['contractId'],
|
|
254
|
-
additionalProperties: false,
|
|
255
|
-
},
|
|
256
|
-
output: {
|
|
257
|
-
schema: {
|
|
258
|
-
type: 'object',
|
|
259
|
-
properties: {
|
|
260
|
-
decision: { type: 'string' }, reasons: { type: 'array', items: { type: 'string' } },
|
|
261
|
-
evidenceHash: { type: 'string' }, reproCmd: { type: 'string' },
|
|
262
|
-
missing: { type: 'array', items: { type: 'string' } },
|
|
263
|
-
},
|
|
264
|
-
required: ['decision', 'reasons', 'evidenceHash'],
|
|
265
|
-
},
|
|
266
|
-
render: (args, v) => {
|
|
267
|
-
const lines = [`门禁 ${v.decision}:${v.reasons.join(';')}`]
|
|
268
|
-
// 必改2:RED 必带可复制复现命令;YELLOW 附缺失证据摘要
|
|
269
|
-
if (v.decision === 'RED') {
|
|
270
|
-
lines.push(v.reproCmd ? `复现:${v.reproCmd}` : '复现:未提供命令(异常)')
|
|
271
|
-
}
|
|
272
|
-
if (v.decision === 'YELLOW' && Array.isArray(v.missing) && v.missing.length > 0) {
|
|
273
|
-
lines.push(`缺失证据:${v.missing.join(';')}`)
|
|
274
|
-
}
|
|
275
|
-
return [{ type: 'text', text: lines.join('\n') }]
|
|
276
|
-
},
|
|
277
|
-
},
|
|
278
|
-
execute: async (args, exec) => {
|
|
279
|
-
// D4: diff 取宿主 workspaceChanges,不自建 diff
|
|
280
|
-
const wc = exec?.workspaceChanges ?? {}
|
|
281
|
-
const diffEvidence = typeof wc.summary === 'string' ? wc.summary : (typeof wc.diff === 'string' ? wc.diff : undefined)
|
|
282
|
-
const evidenceInput = args.checks ? { checks: args.checks, diff: diffEvidence } : undefined
|
|
283
|
-
// 0.2.0 P0-3:未显式给 checks 时按 code-change 策略生成检查请求
|
|
284
|
-
return verifyRun({ contractId: args.contractId, sessionId: sessionOf(exec), evidenceInput, usePolicy: !evidenceInput })
|
|
285
|
-
},
|
|
286
|
-
},
|
|
287
|
-
{
|
|
288
|
-
name: 'verify_status',
|
|
289
|
-
description: '查某个契约最近一次门禁决定与时间。',
|
|
290
|
-
parameters: {
|
|
291
|
-
type: 'object',
|
|
292
|
-
properties: { contractId: { type: 'string' } },
|
|
293
|
-
required: ['contractId'],
|
|
294
|
-
additionalProperties: false,
|
|
295
|
-
},
|
|
296
|
-
output: {
|
|
297
|
-
schema: {
|
|
298
|
-
type: 'object',
|
|
299
|
-
properties: {
|
|
300
|
-
known: { type: 'boolean' },
|
|
301
|
-
decision: { type: 'string' },
|
|
302
|
-
at: { type: 'string' },
|
|
303
|
-
reproCmd: { type: 'string' },
|
|
304
|
-
missing: { type: 'array', items: { type: 'string' } },
|
|
305
|
-
approved: { type: 'boolean' },
|
|
306
|
-
approvedAt: { type: 'string' },
|
|
307
|
-
},
|
|
308
|
-
required: ['known'],
|
|
309
|
-
},
|
|
310
|
-
render: (args, v) => {
|
|
311
|
-
if (!v.known) return [{ type: 'text', text: '未知 contractId,尚无门禁记录' }]
|
|
312
|
-
const lines = [`最近决定 ${v.decision}${v.at ? ' @ ' + v.at : ''}${v.approved ? `;已由用户放行 @ ${v.approvedAt}` : ';尚未放行'}`]
|
|
313
|
-
if (v.reproCmd) lines.push(`复现:${v.reproCmd}`)
|
|
314
|
-
if (Array.isArray(v.missing) && v.missing.length > 0) lines.push(`缺失证据:${v.missing.join(';')}`)
|
|
315
|
-
return [{ type: 'text', text: lines.join('\n') }]
|
|
316
|
-
},
|
|
317
|
-
},
|
|
318
|
-
execute: async (args, exec) => verifyStatus({ contractId: args.contractId, sessionId: sessionOf(exec) }),
|
|
319
|
-
},
|
|
320
|
-
]
|
|
321
|
-
for (const def of defs) ctx.effect(() => ctx.tools.register(def))
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
/**
|
|
325
|
-
* D5 · 门禁卡片种类。
|
|
326
|
-
* 用 ctx.get('actionCards') 可选获取 —— 宿主未装 action-cards 服务时跳过(不阻塞 swarm_run)。
|
|
327
|
-
* details 用零依赖 mini-schema 满足 safeParse 鸭子类型。
|
|
328
|
-
*/
|
|
329
|
-
function registerGateCard(ctx) {
|
|
330
|
-
// 仅在挂载 action-cards 的 profile 生效;v1 默认放行入口是斜杠命令(见 registerGateCommands)。
|
|
331
|
-
// 可选服务走 inject:actionCards 来自另一层 bundle,晚于本插件挂载,apply 时 get 取不到。
|
|
332
|
-
if (typeof ctx.inject !== 'function') return
|
|
333
|
-
ctx.inject(['actionCards'], (ctx) => {
|
|
334
|
-
const cards = ctx.actionCards
|
|
335
|
-
if (!cards || typeof cards.register !== 'function') return
|
|
336
|
-
|
|
337
|
-
const details = z.object({
|
|
338
|
-
decision: z.enum(['GREEN', 'YELLOW', 'RED']),
|
|
339
|
-
reasons: z.array(z.string()),
|
|
340
|
-
contractId: z.string({ nonempty: true }),
|
|
341
|
-
reproCmd: z.optional(z.string()),
|
|
342
|
-
})
|
|
343
|
-
|
|
344
|
-
ctx.effect(() => cards.register({
|
|
345
|
-
action: 'dsh-swarm-console/gate',
|
|
346
|
-
skill: GATE_SKILL_NAME,
|
|
347
|
-
invitation: '验收结论已出。请查看门禁卡片并选择 approve 放行或 retry 重跑。',
|
|
348
|
-
details,
|
|
349
|
-
verbs: { approve: { writes: true }, retry: { writes: true } },
|
|
350
|
-
openPhases: ['proposed', 'refused'],
|
|
351
|
-
async act(agent, proposal, verb, payload) {
|
|
352
|
-
// H3:放行只能由用户触发。非用户(subagent / 代码发起)拒绝并记事件。
|
|
353
|
-
const guard = guardCaller(agent, (a, decision) => cards.record(a, decision))
|
|
354
|
-
if (guard) return guard
|
|
355
|
-
|
|
356
|
-
const { contractId, decision } = proposal.details
|
|
357
|
-
if (verb === 'approve') {
|
|
358
|
-
if (decision !== 'GREEN') {
|
|
359
|
-
cards.record(agent, { callId: proposal.callId, action: proposal.action, phase: 'refused', data: { reason: '非 GREEN 不可放行' } })
|
|
360
|
-
return { status: 'refused', reason: '非 GREEN 不可放行' }
|
|
361
|
-
}
|
|
362
|
-
const d = { callId: proposal.callId, action: proposal.action, phase: 'approved', data: { contractId } }
|
|
363
|
-
cards.record(agent, d)
|
|
364
|
-
return { status: 'settled', decision: d }
|
|
365
|
-
}
|
|
366
|
-
if (verb === 'retry') {
|
|
367
|
-
const r = verifyRun({ contractId, evidenceInput: payload?.evidence })
|
|
368
|
-
const d = {
|
|
369
|
-
callId: proposal.callId, action: proposal.action, phase: 'proposed',
|
|
370
|
-
data: { contractId, decision: r.decision, reasons: r.reasons, ...(r.reproCmd ? { reproCmd: r.reproCmd } : {}) },
|
|
371
|
-
}
|
|
372
|
-
cards.record(agent, d)
|
|
373
|
-
return { status: 'settled', decision: d }
|
|
374
|
-
}
|
|
375
|
-
return { status: 'refused', reason: `未知操作 ${verb}` }
|
|
376
|
-
},
|
|
377
|
-
}))
|
|
378
|
-
})
|
|
379
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Swarm Console —— 可安装的 DSH Host 插件骨架(阶段3A)。
|
|
3
|
+
* 只做一件事:把一个任务交给一个外部 agent 执行一次,返回 stopReason / text / ms。
|
|
4
|
+
* 画布与交付门禁尚未实现(见 docs/DETAIL.md)。
|
|
5
|
+
*
|
|
6
|
+
* 复用 plugin/lib/adapter.js 的 callChat —— 唯一实现在包内,不复制第二份。
|
|
7
|
+
* src/external-agent-adapter.js 是反向 re-export 的兼容 shim。
|
|
8
|
+
*/
|
|
9
|
+
import { callChat } from './lib/adapter.js'
|
|
10
|
+
import { z } from './lib/core/mini-schema.js'
|
|
11
|
+
import { verifyContract, verifyRun, verifyStatus, guardCaller, gateApprove, gateRetry, gateStatus } from './lib/core/verify.js'
|
|
12
|
+
|
|
13
|
+
export const inject = ['tools']
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* 校验画像表。每个条目必须有 baseUrl / apiKeyEnv / models 三项,
|
|
17
|
+
* 缺一就 throw —— 激活即失败,不静默跳过。
|
|
18
|
+
*/
|
|
19
|
+
function validateAgents(agents) {
|
|
20
|
+
if (typeof agents !== 'object' || agents === null || Array.isArray(agents)) {
|
|
21
|
+
throw new Error('externalAgents 必须是对象')
|
|
22
|
+
}
|
|
23
|
+
for (const [name, p] of Object.entries(agents)) {
|
|
24
|
+
if (typeof p !== 'object' || p === null) {
|
|
25
|
+
throw new Error(`externalAgents.${name} 必须是对象`)
|
|
26
|
+
}
|
|
27
|
+
for (const key of ['baseUrl', 'apiKeyEnv', 'models']) {
|
|
28
|
+
const v = p[key]
|
|
29
|
+
const bad = key === 'models' ? !Array.isArray(v) || v.length === 0 : typeof v !== 'string' || v.trim() === ''
|
|
30
|
+
if (bad) throw new Error(`externalAgents.${name}.${key} 缺失或格式不对(必须是 ${key === 'models' ? '非空数组' : '非空字符串'})`)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 选一个画像:显式 agent → 唯一条目 → 报错。 */
|
|
36
|
+
function pickAgent(agents, requested) {
|
|
37
|
+
if (typeof requested === 'string' && requested !== '') {
|
|
38
|
+
if (agents[requested] === undefined) throw new Error(`未知的 agent "${requested}"`)
|
|
39
|
+
return { name: requested, profile: agents[requested] }
|
|
40
|
+
}
|
|
41
|
+
const names = Object.keys(agents)
|
|
42
|
+
if (names.length === 1) return { name: names[0], profile: agents[names[0]] }
|
|
43
|
+
if (names.length === 0) throw new Error('没有配置任何 externalAgents')
|
|
44
|
+
throw new Error('指定了多个 externalAgents,请用 agent 参数指明用哪一个')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* 跑一次外部 agent。取消时返回 cancelled,不抛。
|
|
49
|
+
* signal 从 exec 透传给 callChat;callChat 内部会把 abort 转成异常,这里捕获后归一化。
|
|
50
|
+
*/
|
|
51
|
+
async function runExternal(agents, args, signal) {
|
|
52
|
+
const { profile } = pickAgent(agents, args.agent)
|
|
53
|
+
const prompt = typeof args.task === 'string' ? args.task : ''
|
|
54
|
+
if (prompt.trim() === '') throw new Error('task 不能为空')
|
|
55
|
+
|
|
56
|
+
try {
|
|
57
|
+
const text = await callChat({
|
|
58
|
+
profile,
|
|
59
|
+
prompt,
|
|
60
|
+
model: typeof args.model === 'string' && args.model !== '' ? args.model : undefined,
|
|
61
|
+
signal,
|
|
62
|
+
})
|
|
63
|
+
return { stopReason: 'completed', text }
|
|
64
|
+
} catch (error) {
|
|
65
|
+
// 取消:exec.signal 触发,或底层 AbortError —— 不抛,归一化成 cancelled
|
|
66
|
+
const aborted = (signal && signal.aborted) || error?.name === 'AbortError' ||
|
|
67
|
+
/abort/i.test(String(error?.message ?? ''))
|
|
68
|
+
if (aborted) return { stopReason: 'cancelled', text: '' }
|
|
69
|
+
return { stopReason: 'error', text: String(error?.message ?? error) }
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function apply(ctx, config) {
|
|
74
|
+
const agents = config?.externalAgents ?? {}
|
|
75
|
+
validateAgents(agents)
|
|
76
|
+
|
|
77
|
+
ctx.effect(() => ctx.tools.register({
|
|
78
|
+
name: 'swarm_run',
|
|
79
|
+
description: '把一个任务交给一个外部 agent 执行一次,返回 stopReason 与文本结果。',
|
|
80
|
+
parameters: {
|
|
81
|
+
type: 'object',
|
|
82
|
+
properties: {
|
|
83
|
+
agent: { type: 'string', description: 'externalAgents 里的键;省略则用唯一的那个' },
|
|
84
|
+
task: { type: 'string' },
|
|
85
|
+
model: { type: 'string' },
|
|
86
|
+
},
|
|
87
|
+
required: ['task'],
|
|
88
|
+
additionalProperties: false,
|
|
89
|
+
},
|
|
90
|
+
output: {
|
|
91
|
+
schema: {
|
|
92
|
+
type: 'object',
|
|
93
|
+
properties: {
|
|
94
|
+
stopReason: { type: 'string' },
|
|
95
|
+
text: { type: 'string' },
|
|
96
|
+
ms: { type: 'number' },
|
|
97
|
+
},
|
|
98
|
+
required: ['stopReason', 'text', 'ms'],
|
|
99
|
+
},
|
|
100
|
+
render: (args, value) => [{ type: 'text', text: `[${value.stopReason}] ${value.text}` }],
|
|
101
|
+
},
|
|
102
|
+
async execute(args, exec) {
|
|
103
|
+
const t0 = Date.now()
|
|
104
|
+
const { stopReason, text } = await runExternal(agents, args, exec?.signal)
|
|
105
|
+
return { stopReason, text, ms: Date.now() - t0 }
|
|
106
|
+
},
|
|
107
|
+
}))
|
|
108
|
+
|
|
109
|
+
registerVerifyTools(ctx)
|
|
110
|
+
registerGateCommands(ctx)
|
|
111
|
+
// 卡片与 skill 是可选增强(仅在挂载 action-cards 的 profile 生效);v1 默认入口是斜杠命令。
|
|
112
|
+
// 两者都各自降级,任一失败都不阻塞 verify_* 三工具与斜杠命令。
|
|
113
|
+
registerGateSkill(ctx)
|
|
114
|
+
registerGateCard(ctx)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* C1/C2 · 门禁放行斜杠命令(v1 默认入口,用户触发,不走模型工具)。
|
|
119
|
+
* commands 由 dsh base 自带;仍走 inject 保持挂载时机安全。
|
|
120
|
+
* 命令名 kebab-case、不带斜杠;handler 返回 {kind:'success'|'error', text}。
|
|
121
|
+
*/
|
|
122
|
+
/** P0-4 · 从工具/命令调用上下文取 sessionId,拿不到用 default。 */
|
|
123
|
+
function sessionOf(invocation) {
|
|
124
|
+
const id = invocation?.agent?.session?.id
|
|
125
|
+
return typeof id === 'string' && id !== '' ? id : 'default'
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function registerGateCommands(ctx) {
|
|
129
|
+
if (typeof ctx.inject !== 'function') return
|
|
130
|
+
ctx.inject(['commands'], (ctx) => {
|
|
131
|
+
const commands = ctx.commands
|
|
132
|
+
if (!commands || typeof commands.register !== 'function') return
|
|
133
|
+
const defs = [
|
|
134
|
+
{
|
|
135
|
+
name: 'gate-approve',
|
|
136
|
+
description: '放行一个已 GREEN 的门禁契约(仅用户可触发)',
|
|
137
|
+
input: { hint: '<contractId> [evidenceHash]' },
|
|
138
|
+
// 可传第二参数 evidenceHash 做过期校验;不传时以 runs 里的为最新
|
|
139
|
+
handler: ({ agent, rawInput }) => {
|
|
140
|
+
const parts = String(rawInput ?? '').trim().split(/\s+/)
|
|
141
|
+
return gateApprove({
|
|
142
|
+
contractId: parts[0] ?? '',
|
|
143
|
+
sessionId: sessionOf({ agent }),
|
|
144
|
+
...(parts[1] ? { expectedHash: parts[1] } : {}),
|
|
145
|
+
})
|
|
146
|
+
},
|
|
147
|
+
},
|
|
148
|
+
{
|
|
149
|
+
name: 'gate-retry',
|
|
150
|
+
description: '重跑某契约的门禁校验并刷新决定',
|
|
151
|
+
input: { hint: '<contractId>' },
|
|
152
|
+
handler: ({ agent, rawInput }) => gateRetry({ contractId: String(rawInput ?? '').trim(), sessionId: sessionOf({ agent }) }),
|
|
153
|
+
},
|
|
154
|
+
{
|
|
155
|
+
name: 'gate-status',
|
|
156
|
+
description: '查看门禁状态:不带参数列出本会话所有契约,带参数看单条(支持 id 前缀)',
|
|
157
|
+
input: { hint: '[<contractId|前缀>]' },
|
|
158
|
+
handler: ({ agent, rawInput }) => gateStatus({ contractId: String(rawInput ?? '').trim(), sessionId: sessionOf({ agent }) }),
|
|
159
|
+
},
|
|
160
|
+
]
|
|
161
|
+
for (const def of defs) ctx.effect(() => commands.register(def))
|
|
162
|
+
})
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 必改1 · 注册运行期 skill,让门禁卡的 propose_action 可用。
|
|
167
|
+
* DSH action-cards 的规则:根 Agent 必须先加载该种类声明的 Skill,propose_action 才会出现。
|
|
168
|
+
* 宿主无 skills 服务或注册失败时静默跳过(只影响卡片,不影响三工具)。
|
|
169
|
+
*/
|
|
170
|
+
const GATE_SKILL_NAME = 'dsh-swarm-console-verify'
|
|
171
|
+
const GATE_SKILL_CONTENT = [
|
|
172
|
+
'# Swarm Console 门禁',
|
|
173
|
+
'',
|
|
174
|
+
'当你需要把任务契约冻结、跑证据校验、或让用户对门禁结论做放行决定时使用本 skill。',
|
|
175
|
+
'流程:verify_contract → verify_run → verify_status;结论为 GREEN/YELLOW/RED。',
|
|
176
|
+
'',
|
|
177
|
+
'- 先调用 verify_contract 冻结目标与验收条件,拿到 contractId。',
|
|
178
|
+
'- 再调用 verify_run 得到判定。RED 的复现命令会随输出给出,可复制执行。',
|
|
179
|
+
'- 需要用户决定时,用 propose_action 提议门禁卡(action: dsh-swarm-console/gate)。',
|
|
180
|
+
'- approve = 用户放行,仅在 GREEN 时允许;非 GREEN 不得 approve,应 retry。',
|
|
181
|
+
'- retry = 重跑校验并刷新卡片;只有用户可以操作卡片,agent 代批会被拒绝。',
|
|
182
|
+
'',
|
|
183
|
+
'不要用本 skill 承诺画布或多阶段状态机(尚未实现)。',
|
|
184
|
+
].join('\n')
|
|
185
|
+
|
|
186
|
+
function registerGateSkill(ctx) {
|
|
187
|
+
// 可选服务走 inject:apply 阶段同步 get 时,晚挂载的服务还没就绪。
|
|
188
|
+
// 服务缺席时 inject 不触发回调,不抛错,verify_* 三工具照常注册。
|
|
189
|
+
try {
|
|
190
|
+
if (typeof ctx.inject !== 'function') return
|
|
191
|
+
ctx.inject(['skills'], (ctx) => {
|
|
192
|
+
try {
|
|
193
|
+
const skills = ctx.skills
|
|
194
|
+
if (!skills || typeof skills.register !== 'function') return
|
|
195
|
+
ctx.effect(() => skills.register({
|
|
196
|
+
name: GATE_SKILL_NAME,
|
|
197
|
+
description: 'Swarm Console 交付门禁:冻结契约、跑证据校验、由用户 approve/retry。',
|
|
198
|
+
content: GATE_SKILL_CONTENT,
|
|
199
|
+
source: 'runtime', // SkillRegistration 必填;缺它 skill 能注册但加载失败
|
|
200
|
+
invocation: { modelInvocable: true, userInvocable: true },
|
|
201
|
+
}))
|
|
202
|
+
} catch {
|
|
203
|
+
// 注册失败不阻塞三工具
|
|
204
|
+
}
|
|
205
|
+
})
|
|
206
|
+
} catch {
|
|
207
|
+
// inject 本身失败也不阻塞
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** D5 · 三个 verify 工具。核心逻辑在 lib/core/verify.js,这里只做薄封装。 */
|
|
212
|
+
function registerVerifyTools(ctx) {
|
|
213
|
+
const defs = [
|
|
214
|
+
{
|
|
215
|
+
name: 'verify_contract',
|
|
216
|
+
description: '冻结一个任务契约(目标/约束/验收条件),返回 contract.id。契约内容变化会换 id。',
|
|
217
|
+
parameters: {
|
|
218
|
+
type: 'object',
|
|
219
|
+
properties: {
|
|
220
|
+
objective: { type: 'string' },
|
|
221
|
+
constraints: { type: 'array', items: { type: 'string' } },
|
|
222
|
+
criteria: {
|
|
223
|
+
type: 'array',
|
|
224
|
+
items: {
|
|
225
|
+
type: 'object',
|
|
226
|
+
properties: {
|
|
227
|
+
id: { type: 'string' },
|
|
228
|
+
text: { type: 'string' },
|
|
229
|
+
checkIds: { type: 'array', items: { type: 'string' } },
|
|
230
|
+
},
|
|
231
|
+
required: ['id', 'text'],
|
|
232
|
+
},
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
required: ['objective'],
|
|
236
|
+
additionalProperties: false,
|
|
237
|
+
},
|
|
238
|
+
output: {
|
|
239
|
+
schema: { type: 'object', properties: { contractId: { type: 'string' } }, required: ['contractId'] },
|
|
240
|
+
render: (args, v) => [{ type: 'text', text: `contract ${v.contractId} 已冻结` }],
|
|
241
|
+
},
|
|
242
|
+
execute: async (args) => verifyContract(args),
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
name: 'verify_run',
|
|
246
|
+
description: '按策略跑一次证据校验,返回 GREEN/YELLOW/RED 三态与可复现命令。',
|
|
247
|
+
parameters: {
|
|
248
|
+
type: 'object',
|
|
249
|
+
properties: {
|
|
250
|
+
contractId: { type: 'string' },
|
|
251
|
+
checks: { type: 'array', items: { type: 'object' } },
|
|
252
|
+
},
|
|
253
|
+
required: ['contractId'],
|
|
254
|
+
additionalProperties: false,
|
|
255
|
+
},
|
|
256
|
+
output: {
|
|
257
|
+
schema: {
|
|
258
|
+
type: 'object',
|
|
259
|
+
properties: {
|
|
260
|
+
decision: { type: 'string' }, reasons: { type: 'array', items: { type: 'string' } },
|
|
261
|
+
evidenceHash: { type: 'string' }, reproCmd: { type: 'string' },
|
|
262
|
+
missing: { type: 'array', items: { type: 'string' } },
|
|
263
|
+
},
|
|
264
|
+
required: ['decision', 'reasons', 'evidenceHash'],
|
|
265
|
+
},
|
|
266
|
+
render: (args, v) => {
|
|
267
|
+
const lines = [`门禁 ${v.decision}:${v.reasons.join(';')}`]
|
|
268
|
+
// 必改2:RED 必带可复制复现命令;YELLOW 附缺失证据摘要
|
|
269
|
+
if (v.decision === 'RED') {
|
|
270
|
+
lines.push(v.reproCmd ? `复现:${v.reproCmd}` : '复现:未提供命令(异常)')
|
|
271
|
+
}
|
|
272
|
+
if (v.decision === 'YELLOW' && Array.isArray(v.missing) && v.missing.length > 0) {
|
|
273
|
+
lines.push(`缺失证据:${v.missing.join(';')}`)
|
|
274
|
+
}
|
|
275
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
execute: async (args, exec) => {
|
|
279
|
+
// D4: diff 取宿主 workspaceChanges,不自建 diff
|
|
280
|
+
const wc = exec?.workspaceChanges ?? {}
|
|
281
|
+
const diffEvidence = typeof wc.summary === 'string' ? wc.summary : (typeof wc.diff === 'string' ? wc.diff : undefined)
|
|
282
|
+
const evidenceInput = args.checks ? { checks: args.checks, diff: diffEvidence } : undefined
|
|
283
|
+
// 0.2.0 P0-3:未显式给 checks 时按 code-change 策略生成检查请求
|
|
284
|
+
return verifyRun({ contractId: args.contractId, sessionId: sessionOf(exec), evidenceInput, usePolicy: !evidenceInput })
|
|
285
|
+
},
|
|
286
|
+
},
|
|
287
|
+
{
|
|
288
|
+
name: 'verify_status',
|
|
289
|
+
description: '查某个契约最近一次门禁决定与时间。',
|
|
290
|
+
parameters: {
|
|
291
|
+
type: 'object',
|
|
292
|
+
properties: { contractId: { type: 'string' } },
|
|
293
|
+
required: ['contractId'],
|
|
294
|
+
additionalProperties: false,
|
|
295
|
+
},
|
|
296
|
+
output: {
|
|
297
|
+
schema: {
|
|
298
|
+
type: 'object',
|
|
299
|
+
properties: {
|
|
300
|
+
known: { type: 'boolean' },
|
|
301
|
+
decision: { type: 'string' },
|
|
302
|
+
at: { type: 'string' },
|
|
303
|
+
reproCmd: { type: 'string' },
|
|
304
|
+
missing: { type: 'array', items: { type: 'string' } },
|
|
305
|
+
approved: { type: 'boolean' },
|
|
306
|
+
approvedAt: { type: 'string' },
|
|
307
|
+
},
|
|
308
|
+
required: ['known'],
|
|
309
|
+
},
|
|
310
|
+
render: (args, v) => {
|
|
311
|
+
if (!v.known) return [{ type: 'text', text: '未知 contractId,尚无门禁记录' }]
|
|
312
|
+
const lines = [`最近决定 ${v.decision}${v.at ? ' @ ' + v.at : ''}${v.approved ? `;已由用户放行 @ ${v.approvedAt}` : ';尚未放行'}`]
|
|
313
|
+
if (v.reproCmd) lines.push(`复现:${v.reproCmd}`)
|
|
314
|
+
if (Array.isArray(v.missing) && v.missing.length > 0) lines.push(`缺失证据:${v.missing.join(';')}`)
|
|
315
|
+
return [{ type: 'text', text: lines.join('\n') }]
|
|
316
|
+
},
|
|
317
|
+
},
|
|
318
|
+
execute: async (args, exec) => verifyStatus({ contractId: args.contractId, sessionId: sessionOf(exec) }),
|
|
319
|
+
},
|
|
320
|
+
]
|
|
321
|
+
for (const def of defs) ctx.effect(() => ctx.tools.register(def))
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* D5 · 门禁卡片种类。
|
|
326
|
+
* 用 ctx.get('actionCards') 可选获取 —— 宿主未装 action-cards 服务时跳过(不阻塞 swarm_run)。
|
|
327
|
+
* details 用零依赖 mini-schema 满足 safeParse 鸭子类型。
|
|
328
|
+
*/
|
|
329
|
+
function registerGateCard(ctx) {
|
|
330
|
+
// 仅在挂载 action-cards 的 profile 生效;v1 默认放行入口是斜杠命令(见 registerGateCommands)。
|
|
331
|
+
// 可选服务走 inject:actionCards 来自另一层 bundle,晚于本插件挂载,apply 时 get 取不到。
|
|
332
|
+
if (typeof ctx.inject !== 'function') return
|
|
333
|
+
ctx.inject(['actionCards'], (ctx) => {
|
|
334
|
+
const cards = ctx.actionCards
|
|
335
|
+
if (!cards || typeof cards.register !== 'function') return
|
|
336
|
+
|
|
337
|
+
const details = z.object({
|
|
338
|
+
decision: z.enum(['GREEN', 'YELLOW', 'RED']),
|
|
339
|
+
reasons: z.array(z.string()),
|
|
340
|
+
contractId: z.string({ nonempty: true }),
|
|
341
|
+
reproCmd: z.optional(z.string()),
|
|
342
|
+
})
|
|
343
|
+
|
|
344
|
+
ctx.effect(() => cards.register({
|
|
345
|
+
action: 'dsh-swarm-console/gate',
|
|
346
|
+
skill: GATE_SKILL_NAME,
|
|
347
|
+
invitation: '验收结论已出。请查看门禁卡片并选择 approve 放行或 retry 重跑。',
|
|
348
|
+
details,
|
|
349
|
+
verbs: { approve: { writes: true }, retry: { writes: true } },
|
|
350
|
+
openPhases: ['proposed', 'refused'],
|
|
351
|
+
async act(agent, proposal, verb, payload) {
|
|
352
|
+
// H3:放行只能由用户触发。非用户(subagent / 代码发起)拒绝并记事件。
|
|
353
|
+
const guard = guardCaller(agent, (a, decision) => cards.record(a, decision))
|
|
354
|
+
if (guard) return guard
|
|
355
|
+
|
|
356
|
+
const { contractId, decision } = proposal.details
|
|
357
|
+
if (verb === 'approve') {
|
|
358
|
+
if (decision !== 'GREEN') {
|
|
359
|
+
cards.record(agent, { callId: proposal.callId, action: proposal.action, phase: 'refused', data: { reason: '非 GREEN 不可放行' } })
|
|
360
|
+
return { status: 'refused', reason: '非 GREEN 不可放行' }
|
|
361
|
+
}
|
|
362
|
+
const d = { callId: proposal.callId, action: proposal.action, phase: 'approved', data: { contractId } }
|
|
363
|
+
cards.record(agent, d)
|
|
364
|
+
return { status: 'settled', decision: d }
|
|
365
|
+
}
|
|
366
|
+
if (verb === 'retry') {
|
|
367
|
+
const r = verifyRun({ contractId, evidenceInput: payload?.evidence })
|
|
368
|
+
const d = {
|
|
369
|
+
callId: proposal.callId, action: proposal.action, phase: 'proposed',
|
|
370
|
+
data: { contractId, decision: r.decision, reasons: r.reasons, ...(r.reproCmd ? { reproCmd: r.reproCmd } : {}) },
|
|
371
|
+
}
|
|
372
|
+
cards.record(agent, d)
|
|
373
|
+
return { status: 'settled', decision: d }
|
|
374
|
+
}
|
|
375
|
+
return { status: 'refused', reason: `未知操作 ${verb}` }
|
|
376
|
+
},
|
|
377
|
+
}))
|
|
378
|
+
})
|
|
379
|
+
}
|