dsh-dev-plan-presets 0.0.0-stage → 0.4.0

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/guard.js ADDED
@@ -0,0 +1,547 @@
1
+ /**
2
+ * 子代理模型守门(吸收 dsh-subagent-model-pin 的核心能力)。
3
+ *
4
+ * 语义:
5
+ * - 只管理子代理:有 parentSession 或 origin=subagent 的 Agent;主会话永不 select、永不 reject。
6
+ * - 创建时按 modelGuardMode 决定:pin=选中目标路由;audit=只记录 would-pin;off=什么都不做。
7
+ * - 每个被管理的子代理挂 agent/pre-step 守卫,逐步核对即将发请求的 modelSelection;
8
+ * pin + killOnViolation 时在发请求前 reject、cancel 子代理并通知父会话;audit 只记录。
9
+ * - honorExplicit=true 时,创建时检测到子代理被显式指定了非父级路由就不钉、也不挂守卫,
10
+ * 避免“说尊重却仍然打断”的自相矛盾。
11
+ * - 审计只记录路由、事件与 agent id,不记录任何凭据。
12
+ *
13
+ * 本文件不 import Node 内置模块,也不 import @deepseek-ai/*,便于单测。
14
+ */
15
+
16
+ import { DEFAULT_SETTINGS, routeMatches, routeOf } from './settings.js'
17
+ import { PRESET_ID } from './preset.js'
18
+
19
+ const MAX_TEXT = 240
20
+ const shortId = (value) => (typeof value === 'string' ? value.slice(0, 12) : '')
21
+
22
+ /**
23
+ * 判断一个 session header 是否代表子代理。
24
+ * @param {{ parentSession?: string, origin?: string } | undefined} header
25
+ */
26
+ export function isSubagentHeader(header) {
27
+ if (!header || typeof header !== 'object') return false
28
+ // fork 主对话也会带 parentSession(delegationDepth:0、无 origin),不能据此当子代理。
29
+ if (header.origin === 'subagent') return true
30
+ const depth = header.delegationDepth
31
+ return typeof depth === 'number' && Number.isFinite(depth) && depth > 0
32
+ }
33
+
34
+ /** 取父会话对象;拿不到就返回 undefined(调用方应跳过守门,避免误伤)。 */
35
+ const parentSessionOf = (ctx, agent) => {
36
+ try {
37
+ const parentId = agent?.session?.header?.parentSession
38
+ if (!parentId) return undefined
39
+ return ctx.get('agents')?.get?.(parentId)?.session
40
+ } catch {
41
+ return undefined
42
+ }
43
+ }
44
+
45
+ /**
46
+ * 读取会话当前 preset:优先 agentPresets.presetForSession(session)(含已不在 roster 的历史选择),
47
+ * 回退 session.header.agentPreset。拿不到时返回 undefined,调用方必须跳过守门。
48
+ */
49
+ export function presetOfSession(ctx, session) {
50
+ if (!session) return undefined
51
+ try {
52
+ const registry = ctx.get('agentPresets')
53
+ if (typeof registry?.presetForSession === 'function') {
54
+ const preset = registry.presetForSession(session)
55
+ if (typeof preset === 'string' && preset.length > 0) return preset
56
+ }
57
+ } catch {
58
+ /* 回退 header */
59
+ }
60
+ const fromHeader = session?.header?.agentPreset
61
+ return typeof fromHeader === 'string' && fromHeader.length > 0 ? fromHeader : undefined
62
+ }
63
+
64
+ /**
65
+ * 默认守门范围:只管理父会话 preset=dev-plan 的子代理;guardAllSubagents=true 时恢复全局。
66
+ * 父会话或 preset 无法可靠判断时返回 false(宁可跳过,也不误伤其他插件)。
67
+ */
68
+ export function shouldGuardAgent(ctx, agent, settings) {
69
+ if (settings?.guardAllSubagents === true) return true
70
+ const parent = parentSessionOf(ctx, agent)
71
+ if (!parent) return false
72
+ return presetOfSession(ctx, parent) === PRESET_ID
73
+ }
74
+
75
+ const parentRouteOf = (ctx, agent) => {
76
+ try {
77
+ const parentId = agent?.session?.header?.parentSession
78
+ if (!parentId) return undefined
79
+ const parent = ctx.get('agents')?.get?.(parentId)
80
+ const current = parent?.model?.current?.()
81
+ if (!current?.provider || !current?.model) return undefined
82
+ return { provider: current.provider, model: current.model }
83
+ } catch {
84
+ return undefined
85
+ }
86
+ }
87
+
88
+ const notifyParent = (ctx, agent, text) => {
89
+ try {
90
+ const parentId = agent?.session?.header?.parentSession
91
+ if (!parentId) return
92
+ const parent = ctx.get('agents')?.get?.(parentId)
93
+ if (typeof parent?.inject !== 'function') return
94
+ parent.inject({
95
+ content: [{ type: 'text', text }],
96
+ source: { kind: 'dev-plan-presets' },
97
+ })
98
+ } catch {
99
+ /* 通知失败不能反过来破坏守门 */
100
+ }
101
+ }
102
+
103
+ const describeRoute = (route) =>
104
+ route && route.provider && route.model ? `${route.provider}/${route.model}` : '(unknown)'
105
+
106
+ const stopChild = (ctx, agent, reason, hooks) => {
107
+ try {
108
+ if (typeof agent?.cancel === 'function') agent.cancel({ kind: 'user' })
109
+ } catch {
110
+ /* ignore */
111
+ }
112
+ notifyParent(
113
+ ctx,
114
+ agent,
115
+ `⚠️ [dev-plan-presets] 子代理 ${shortId(agent?.id)} ${reason},已中止。`,
116
+ )
117
+ hooks?.audit?.('stopped', { agent: shortId(agent?.id), reason })
118
+ }
119
+
120
+ const recordViolation = (hooks, agent, got, want, detail) => {
121
+ const entry = {
122
+ at: new Date().toISOString(),
123
+ agent: shortId(agent?.id),
124
+ session: shortId(agent?.session?.id),
125
+ from: describeRoute(got),
126
+ want: describeRoute(want),
127
+ text: String(detail).slice(0, MAX_TEXT),
128
+ }
129
+ try {
130
+ hooks?.recordViolation?.(entry)
131
+ } catch {
132
+ /* ignore */
133
+ }
134
+ }
135
+
136
+ const violationText = (got, want) =>
137
+ `越界使用模型 ${describeRoute(got)}(应为 ${describeRoute(want)})`
138
+
139
+ /**
140
+ * 给一个子代理装逐步守卫。
141
+ * 监听器注册在 agent.ctx 上,但**返回值必须由插件自己的生命周期持有**:
142
+ * agent 作用域销毁和插件卸载两边都会调用同一个幂等 disposer。
143
+ * @returns 幂等卸载函数;注册失败时返回 undefined。
144
+ */
145
+ const installStepGuard = (ctx, agent, settings, hooks, target, onDispose) => {
146
+ let stopped = false
147
+ let active = true
148
+ const handler = async (payload, next) => {
149
+ if (settings.modelGuardMode === 'off') return next()
150
+ if (stopped) return { kind: 'reject' }
151
+ const decision = await next()
152
+ try {
153
+ if (decision?.kind === 'reject') return decision
154
+ if (settings.modelGuardMode === 'off') return decision
155
+ if (stopped) return { kind: 'reject' }
156
+ const got = payload?.modelSelection
157
+ if (routeMatches(got, target)) return decision
158
+ const detail = violationText(got, target)
159
+ recordViolation(hooks, agent, got, target, detail)
160
+ hooks?.audit?.('violation', {
161
+ agent: shortId(agent?.id),
162
+ from: describeRoute(got),
163
+ want: describeRoute(target),
164
+ })
165
+ if (settings.modelGuardMode === 'pin' && settings.killOnViolation) {
166
+ stopped = true
167
+ stopChild(ctx, agent, detail, hooks)
168
+ return { kind: 'reject' }
169
+ }
170
+ return decision
171
+ } catch {
172
+ return decision
173
+ }
174
+ }
175
+ let off
176
+ try {
177
+ off = agent.ctx.on('agent/pre-step', handler)
178
+ } catch (error) {
179
+ hooks?.warn?.(`无法为子代理 ${shortId(agent?.id)} 安装模型守卫:${String(error?.message ?? error)}`)
180
+ return undefined
181
+ }
182
+ const dispose = () => {
183
+ if (!active) return
184
+ active = false
185
+ try {
186
+ if (typeof off === 'function') off()
187
+ } catch {
188
+ /* ignore */
189
+ }
190
+ try {
191
+ if (typeof onDispose === 'function') onDispose(agent)
192
+ } catch {
193
+ /* ignore */
194
+ }
195
+ }
196
+ // agent 作用域销毁时也释放;插件总 disposer 会先/后调用同一个 dispose,靠 active 幂等。
197
+ try {
198
+ if (typeof agent.ctx.effect === 'function') agent.ctx.effect(() => dispose)
199
+ } catch {
200
+ /* 没有 effect 时至少还有插件总 disposer */
201
+ }
202
+ return dispose
203
+ }
204
+
205
+ /**
206
+ * 处理一个 agent/created 事件。导出以便单测直接调用。
207
+ * @param {any} ctx
208
+ * @param {any} agent
209
+ * @param {import('./settings.js').DEFAULT_SETTINGS} settings
210
+ * @param {{ recordViolation?: Function, audit?: Function, warn?: Function }} hooks
211
+ * @param {{ provider: string, model: string, reasoningEffort?: string }} [target]
212
+ * @param {(agent: any) => void} [onDispose]
213
+ */
214
+ export function onAgentCreated(
215
+ ctx,
216
+ agent,
217
+ settings,
218
+ hooks = {},
219
+ target = routeOf(settings),
220
+ onDispose,
221
+ ) {
222
+ if (!agent || settings.modelGuardMode === 'off') return
223
+ const header = agent.session?.header
224
+ // 主会话在这里被挡掉:没有父会话,也不是 origin=subagent。
225
+ if (!isSubagentHeader(header)) return
226
+
227
+ // 默认只守 dev-plan 父会话派出的子代理;判断不了父会话 preset 时不守门。
228
+ if (settings.guardAllSubagents !== true) {
229
+ const parent = parentSessionOf(ctx, agent)
230
+ const preset = parent ? presetOfSession(ctx, parent) : undefined
231
+ if (preset !== PRESET_ID) {
232
+ if (preset === undefined) {
233
+ hooks?.audit?.('guard-skip-unknown-parent-preset', {
234
+ agent: shortId(agent?.id),
235
+ parentFound: Boolean(parent),
236
+ })
237
+ }
238
+ return
239
+ }
240
+ }
241
+
242
+ const mode = settings.modelGuardMode
243
+ const current = (() => {
244
+ try {
245
+ return agent.model?.current?.()
246
+ } catch {
247
+ return undefined
248
+ }
249
+ })()
250
+
251
+ if (mode === 'audit') {
252
+ const dispose = installStepGuard(ctx, agent, settings, hooks, target, onDispose)
253
+ hooks?.audit?.('would-pin', {
254
+ agent: shortId(agent?.id),
255
+ from: describeRoute(current),
256
+ want: describeRoute(target),
257
+ })
258
+ return dispose
259
+ }
260
+
261
+ const parentRoute = parentRouteOf(ctx, agent)
262
+ const explicit = Boolean(
263
+ current &&
264
+ parentRoute &&
265
+ (current.provider !== parentRoute.provider || current.model !== parentRoute.model),
266
+ )
267
+ if (explicit && settings.honorExplicit) {
268
+ hooks?.audit?.('skip-explicit', {
269
+ agent: shortId(agent?.id),
270
+ from: describeRoute(current),
271
+ want: describeRoute(target),
272
+ })
273
+ return
274
+ }
275
+
276
+ // pin:守卫必须在 select 尝试之前装好。这样即使 select 不存在/抛错且 kill=false,
277
+ // 后续 pre-step 仍能记录越界,而不是变成完全不设防。
278
+ const dispose = installStepGuard(ctx, agent, settings, hooks, target, onDispose)
279
+
280
+ // 已经在目标路由上:保留守卫防后续漂移即可。
281
+ if (routeMatches(current, target)) {
282
+ hooks?.audit?.('already', { agent: shortId(agent?.id), want: describeRoute(target) })
283
+ return dispose
284
+ }
285
+
286
+ const model = agent.model
287
+ if (typeof model?.select !== 'function') {
288
+ const detail = '当前 DSH 不支持 agent.model.select,无法钉住子代理路由'
289
+ recordViolation(hooks, agent, current, target, detail)
290
+ if (settings.killOnViolation) stopChild(ctx, agent, detail, hooks)
291
+ return dispose
292
+ }
293
+
294
+ try {
295
+ model.select({ ...target })
296
+ hooks?.audit?.('pinned', {
297
+ agent: shortId(agent?.id),
298
+ from: describeRoute(current),
299
+ want: describeRoute(target),
300
+ })
301
+ } catch (error) {
302
+ const detail = `钉住子代理路由失败:${String(error?.message ?? error)}`
303
+ recordViolation(hooks, agent, current, target, detail)
304
+ if (settings.killOnViolation) stopChild(ctx, agent, detail, hooks)
305
+ }
306
+ return dispose
307
+ }
308
+
309
+ /**
310
+ * 安装全局 agent/created 监听,并跟踪每个子代理的 step guard。
311
+ * 总 disposer 同时解绑事件监听和所有已装守卫:插件 HMR/卸载后旧设置不能继续拦截仍运行的 agent。
312
+ * @returns 幂等总卸载函数。
313
+ */
314
+ export function installModelGuard(ctx, settings, hooks = {}) {
315
+ if (settings.modelGuardMode === 'off') return () => {}
316
+ const target = routeOf(settings)
317
+ const steps = new Map()
318
+ let active = true
319
+
320
+ const release = (agent) => {
321
+ const dispose = steps.get(agent)
322
+ if (dispose === undefined) return
323
+ steps.delete(agent)
324
+ try {
325
+ dispose()
326
+ } catch {
327
+ /* ignore */
328
+ }
329
+ }
330
+
331
+ const listener = (payload) => {
332
+ const agent = payload?.agent
333
+ try {
334
+ const dispose = onAgentCreated(ctx, agent, settings, hooks, target, (targetAgent) => {
335
+ steps.delete(targetAgent)
336
+ })
337
+ if (typeof dispose === 'function' && agent && typeof agent === 'object') {
338
+ release(agent)
339
+ steps.set(agent, dispose)
340
+ }
341
+ } catch (error) {
342
+ hooks?.warn?.(`模型守门处理 agent 失败:${String(error?.message ?? error)}`)
343
+ }
344
+ }
345
+ const disposedListener = (payload) => {
346
+ try {
347
+ release(payload?.agent)
348
+ } catch {
349
+ /* ignore */
350
+ }
351
+ }
352
+
353
+ const offs = []
354
+ try {
355
+ offs.push(ctx.on('agent/created', listener))
356
+ offs.push(ctx.on('agent/disposed', disposedListener))
357
+ } catch (error) {
358
+ hooks?.warn?.(`无法注册模型守门:${String(error?.message ?? error)}`)
359
+ }
360
+
361
+ return () => {
362
+ if (!active) return
363
+ active = false
364
+ for (const off of offs) {
365
+ try {
366
+ if (typeof off === 'function') off()
367
+ } catch {
368
+ /* ignore */
369
+ }
370
+ }
371
+ const pending = [...steps.values()]
372
+ steps.clear()
373
+ for (const dispose of pending) {
374
+ try {
375
+ dispose()
376
+ } catch {
377
+ /* ignore */
378
+ }
379
+ }
380
+ }
381
+ }
382
+
383
+ const turnSignatureOf = (agent, payload) => {
384
+ if (payload && payload.turnId !== undefined) return `turn:${String(payload.turnId)}`
385
+ if (payload && payload.userMessageId !== undefined) {
386
+ return `userMsg:${String(payload.userMessageId)}`
387
+ }
388
+ const messages = agent?.session?.messages
389
+ if (!Array.isArray(messages)) return 'default'
390
+ let userCount = 0
391
+ let lastUserId = ''
392
+ for (const msg of messages) {
393
+ if (msg?.role === 'user' && msg?.source?.kind !== 'dev-plan-presets') {
394
+ userCount += 1
395
+ if (msg.id !== undefined) lastUserId = String(msg.id)
396
+ }
397
+ }
398
+ return `users:${userCount}:${lastUserId}`
399
+ }
400
+
401
+ /**
402
+ * 主会话步数预算软提醒(独立于 modelGuardMode)。
403
+ * 仅在 settings.mainToolMode !== 'none' 时激活;
404
+ * 仅监听非子代理且 preset=dev-plan 的主会话,在单轮连续步数超阈值时温和注入提示,
405
+ * 绝不调用 agent.model.select、绝不 cancel、绝不 reject。
406
+ *
407
+ * @returns 幂等总卸载函数。
408
+ */
409
+ export function installMainStepBudget(ctx, settings, hooks = {}) {
410
+ const mode = settings?.mainToolMode ?? DEFAULT_SETTINGS.mainToolMode
411
+ if (mode === 'none') return () => {}
412
+ const threshold =
413
+ Number.isInteger(settings?.mainStepWarnThreshold) && settings.mainStepWarnThreshold >= 2
414
+ ? settings.mainStepWarnThreshold
415
+ : 6
416
+
417
+ const tracked = new Map()
418
+ let active = true
419
+
420
+ const release = (agent) => {
421
+ const dispose = tracked.get(agent)
422
+ if (dispose === undefined) return
423
+ tracked.delete(agent)
424
+ try {
425
+ dispose()
426
+ } catch {
427
+ /* ignore */
428
+ }
429
+ }
430
+
431
+ const attach = (agent) => {
432
+ if (!agent || typeof agent.ctx?.on !== 'function') return
433
+ if (isSubagentHeader(agent.session?.header)) return
434
+ if (presetOfSession(ctx, agent.session) !== PRESET_ID) return
435
+
436
+ let stepCount = 0
437
+ let warned = false
438
+ let lastTurn = ''
439
+ let lastStepAt = 0
440
+ let stepActive = true
441
+
442
+ let off
443
+ try {
444
+ off = agent.ctx.on('agent/pre-step', async (payload, next) => {
445
+ const decision = await next()
446
+ try {
447
+ if (decision?.kind === 'reject') return decision
448
+ const now = Date.now()
449
+ const turn = turnSignatureOf(agent, payload)
450
+ if (turn !== lastTurn || (lastStepAt > 0 && now - lastStepAt > 60_000)) {
451
+ lastTurn = turn
452
+ stepCount = 0
453
+ warned = false
454
+ }
455
+ lastStepAt = now
456
+ stepCount += 1
457
+ if (stepCount > threshold && !warned) {
458
+ warned = true
459
+ const message =
460
+ `💡 [dev-plan-presets] 当前主模型在本轮已连续执行 ${stepCount} 步(提醒阈值 ${threshold}),` +
461
+ `建议将后续探索或修改转交 recon / develop 子代理以节省主模型额度。`
462
+ hooks?.audit?.('main-step-budget-warn', {
463
+ agent: shortId(agent?.id),
464
+ steps: stepCount,
465
+ threshold,
466
+ mode,
467
+ })
468
+ if (typeof agent?.inject === 'function') {
469
+ agent.inject({
470
+ content: [{ type: 'text', text: message }],
471
+ source: { kind: 'dev-plan-presets' },
472
+ })
473
+ }
474
+ }
475
+ } catch {
476
+ /* 软提醒绝不中断主会话 */
477
+ }
478
+ return decision
479
+ })
480
+ } catch {
481
+ return
482
+ }
483
+
484
+ const dispose = () => {
485
+ if (!stepActive) return
486
+ stepActive = false
487
+ tracked.delete(agent)
488
+ try {
489
+ if (typeof off === 'function') off()
490
+ } catch {
491
+ /* ignore */
492
+ }
493
+ }
494
+
495
+ release(agent)
496
+ tracked.set(agent, dispose)
497
+ try {
498
+ if (typeof agent.ctx.effect === 'function') agent.ctx.effect(() => dispose)
499
+ } catch {
500
+ /* ignore */
501
+ }
502
+ }
503
+
504
+ const createdListener = (payload) => {
505
+ try {
506
+ attach(payload?.agent)
507
+ } catch {
508
+ /* ignore */
509
+ }
510
+ }
511
+ const disposedListener = (payload) => {
512
+ try {
513
+ release(payload?.agent)
514
+ } catch {
515
+ /* ignore */
516
+ }
517
+ }
518
+
519
+ const offs = []
520
+ try {
521
+ offs.push(ctx.on('agent/created', createdListener))
522
+ offs.push(ctx.on('agent/disposed', disposedListener))
523
+ } catch (error) {
524
+ hooks?.warn?.(`无法注册主窗步数提醒:${String(error?.message ?? error)}`)
525
+ }
526
+
527
+ return () => {
528
+ if (!active) return
529
+ active = false
530
+ for (const off of offs) {
531
+ try {
532
+ if (typeof off === 'function') off()
533
+ } catch {
534
+ /* ignore */
535
+ }
536
+ }
537
+ const pending = [...tracked.values()]
538
+ tracked.clear()
539
+ for (const dispose of pending) {
540
+ try {
541
+ dispose()
542
+ } catch {
543
+ /* ignore */
544
+ }
545
+ }
546
+ }
547
+ }
package/icon.svg ADDED
@@ -0,0 +1,12 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Dev plan presets: a plan sheet with a read-only eye and a sealed pen">
2
+ <rect x="1" y="1" width="62" height="62" rx="14" fill="#101828"/>
3
+ <rect x="10" y="9" width="30" height="44" rx="4" fill="#1f2a3d" stroke="#3fbf9f" stroke-width="1.5"/>
4
+ <rect x="15" y="16" width="20" height="2.4" rx="1.2" fill="#3fbf9f"/>
5
+ <rect x="15" y="22" width="15" height="2.4" rx="1.2" fill="#3fbf9f" opacity="0.7"/>
6
+ <rect x="15" y="28" width="18" height="2.4" rx="1.2" fill="#3fbf9f" opacity="0.45"/>
7
+ <circle cx="45" cy="24" r="8.5" fill="#101828" stroke="#e6edf6" stroke-width="1.6"/>
8
+ <circle cx="45" cy="24" r="3" fill="#e6edf6"/>
9
+ <path d="M37.5 35.5 L50 48" stroke="#e0a43a" stroke-width="4" stroke-linecap="round"/>
10
+ <path d="M36.2 34.2 L38.8 36.8" stroke="#e0a43a" stroke-width="4" stroke-linecap="round"/>
11
+ <path d="M49 47 L52.5 50.5" stroke="#e0a43a" stroke-width="4" stroke-linecap="round"/>
12
+ </svg>