dsh-subagent-dispatch-control 0.0.0-stage → 1.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 +21 -0
- package/README.md +225 -2
- package/client.js +9781 -0
- package/cordis.patch.yml +13 -0
- package/docs/BOOST-EVIDENCE.md +259 -0
- package/docs/CONFORMANCE.md +236 -0
- package/docs/FACTS-CONTRACT.md +368 -0
- package/docs/FLOW-COVERAGE.md +215 -0
- package/docs/PACKAGE-README.md +858 -0
- package/docs/RANGE-PLAN.md +357 -0
- package/docs/SECURITY-NOTES.md +110 -0
- package/docs/SPLIT-PLAN.md +604 -0
- package/docs/STAGE3-CONTRACT.md +287 -0
- package/docs/TIER-ROUTING.md +275 -0
- package/docs/badge/CONFORMANCE.md +246 -0
- package/docs/badge/DETAIL.md +319 -0
- package/docs/badge/PROJECTIONS.md +264 -0
- package/docs/badge/TEST-PLAN.md +252 -0
- package/docs/images/badge-menu.png +0 -0
- package/docs/images/dispatch.png +0 -0
- package/docs/images/header.png +0 -0
- package/docs/images/pair-header.png +0 -0
- package/docs/images/pair-panel.png +0 -0
- package/docs/images/panel.png +0 -0
- package/docs/wiki/Home.md +43 -0
- package/docs/wiki//344/275/277/347/224/250/346/214/207/345/215/227.md +116 -0
- package/docs/wiki//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +103 -0
- package/docs/wiki//346/225/205/351/232/234/346/216/222/346/237/245.md +94 -0
- package/icon.svg +12 -0
- package/lib/badge-policy.mjs +502 -0
- package/lib/badge-sync.mjs +385 -0
- package/lib/command.mjs +490 -0
- package/lib/completion.mjs +288 -0
- package/lib/concurrency.mjs +2555 -0
- package/lib/dispatch-command.mjs +181 -0
- package/lib/dispatch-gate.mjs +924 -0
- package/lib/facts-store.mjs +183 -0
- package/lib/gate-state.mjs +465 -0
- package/lib/gate.mjs +886 -0
- package/lib/index.js +309 -0
- package/lib/inject.mjs +195 -0
- package/lib/interrupt.mjs +376 -0
- package/lib/ledger.mjs +948 -0
- package/lib/lifecycle.mjs +274 -0
- package/lib/messages.mjs +532 -0
- package/lib/notice.mjs +769 -0
- package/lib/plan-gate.mjs +385 -0
- package/lib/projection.mjs +978 -0
- package/lib/report.mjs +290 -0
- package/lib/route.mjs +346 -0
- package/lib/run-registry.mjs +402 -0
- package/lib/services.mjs +293 -0
- package/lib/stuck.mjs +567 -0
- package/lib/tier-config.mjs +212 -0
- package/lib/tier-policy.mjs +167 -0
- package/lib/tier-state.mjs +137 -0
- package/lib/todo-gate.mjs +1672 -0
- package/lib/tools.mjs +2912 -0
- package/locale/en.json +9 -0
- package/locale/zh.json +9 -0
- package/package.json +58 -4
- package/vendor/node_modules/@deepseek-ai/cosmokit/LICENSE +21 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/README.md +30 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/lib/index.js +418 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/package.json +32 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/array.ts +42 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/index.ts +12 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/misc.ts +78 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/string.ts +113 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/time.ts +92 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/types.ts +168 -0
- package/vendor/node_modules/@deepseek-ai/cosmokit/src/volatile.ts +86 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/LICENSE +21 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/README.md +393 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.cjs +635 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.mjs +635 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/package.json +39 -0
- package/vendor/node_modules/@deepseek-ai/schemastery/src/index.ts +962 -0
- package/vendor/node_modules/@standard-schema/spec/LICENSE +21 -0
- package/vendor/node_modules/@standard-schema/spec/README.md +198 -0
- package/vendor/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
- package/vendor/node_modules/@standard-schema/spec/dist/index.js +0 -0
- package/vendor/node_modules/@standard-schema/spec/package.json +39 -0
package/lib/notice.mjs
ADDED
|
@@ -0,0 +1,769 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 委派后提示 / snapshot 构造 / tool-result 归因。
|
|
3
|
+
*
|
|
4
|
+
* 从 lib/index.js 原样搬出,函数体逐字未改;
|
|
5
|
+
* installPostExecuteNotice / installResultDiagnostics 由 apply 中原监听器块原样包成函数壳。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { isDelegationTool, hasExplicitRouteArgs, resolveEffectiveRoute, formatRoute } from './route.mjs'
|
|
10
|
+
import { isModelSelectableTool, injectedExecutions } from './inject.mjs'
|
|
11
|
+
import { readUiSelection, sessionKeyOf, teamEnabled } from './services.mjs'
|
|
12
|
+
import { allowedRoutesOf } from './projection.mjs'
|
|
13
|
+
// 档位路由显式化(第二波):确认档位与标签。tier-state 是另一 lane 的模块,防御性加载
|
|
14
|
+
// (缺失 / 加载失败 → readConfirmedTierOf 恒 undefined,提示文案保持原样);tierLabel 只进
|
|
15
|
+
// 带档位分支的模板串,不触碰无档位文案。
|
|
16
|
+
import { tierLabel } from './messages.mjs'
|
|
17
|
+
import { normalizeTier } from './tier-policy.mjs'
|
|
18
|
+
let tierStateMod = null
|
|
19
|
+
try { tierStateMod = await import('./tier-state.mjs') } catch { tierStateMod = null }
|
|
20
|
+
|
|
21
|
+
/** 注入上下文的 source 标签;带 kind 才不会被当成用户输入渲染。 */
|
|
22
|
+
const PREFLIGHT_SOURCE = { kind: 'team-preflight' }
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* 每个会话最近一次 snapshot 的文本,用于内容去重。
|
|
26
|
+
*
|
|
27
|
+
* 用 WeakMap 而不是 Map:Map 的键是 session id 字符串,永不回收,
|
|
28
|
+
* 跨会话生命周期无界增长。WeakMap 需要对象键——这里用 session 对象本身,
|
|
29
|
+
* 会话被回收时条目自动消失。
|
|
30
|
+
*/
|
|
31
|
+
const lastSnapshotBySession = new WeakMap()
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* 取 agent 所属 root session 的**对象**作为去重键。
|
|
35
|
+
*
|
|
36
|
+
* 早先返回字符串 id,出错时返回 '',导致所有异常会话共用同一个去重键
|
|
37
|
+
* (本该发送的提示被误判「内容未变」而跳过)。现在返回对象或 undefined,
|
|
38
|
+
* 取不到就跳过去重、总是发送。
|
|
39
|
+
*
|
|
40
|
+
* ⚠️ 命名注意(X13):本函数返回 session **对象**(WeakMap 键),
|
|
41
|
+
* 与 services.mjs 导出的 sessionKeyOf(返回 id **字符串**,供
|
|
42
|
+
* readUiSelection 按会话取界面选择)不是同一个东西,故改名 sessionObjectOf,
|
|
43
|
+
* 避免同名遮蔽。
|
|
44
|
+
*/
|
|
45
|
+
function sessionObjectOf(agent) {
|
|
46
|
+
try {
|
|
47
|
+
const session = agent?.session
|
|
48
|
+
if (session === null || session === undefined) return undefined
|
|
49
|
+
// 直接用 session 对象本身作为键:同一会话的所有委派共享去重状态。
|
|
50
|
+
// 子代理会话有自己的 session 对象,因此各自独立去重(符合预期)。
|
|
51
|
+
return session
|
|
52
|
+
} catch {
|
|
53
|
+
return undefined
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* 构造一条**完整**的 user 消息(带 id / role / source.kind),不做任何包裹。
|
|
59
|
+
*
|
|
60
|
+
* ── 为什么必须集中到这一个构造函数(FIX6-MSGID,真实事故)──────────
|
|
61
|
+
*
|
|
62
|
+
* 宿主把 `additionalContexts` 里的对象**原样**当成 `user/message` 的 data
|
|
63
|
+
* 写进会话日志(dsh-agent-loop/lib/index.js,step() 内):
|
|
64
|
+
* this.session.append("user/message", context, { surfaceOp: "append" })
|
|
65
|
+
* 也就是说:user/message 的 data **本身就是完整消息**,不是 { message } 包装。
|
|
66
|
+
*
|
|
67
|
+
* 官方校验器 assertMessageEventShape(@deepseek-ai/dsh-session/lib/index.js):
|
|
68
|
+
* const message = type === "user/message" ? record : record?.["message"]
|
|
69
|
+
* if (typeof message["id"] !== "string" || message["id"] === "")
|
|
70
|
+
* throw new Error(`${subject} lacks an identified message`)
|
|
71
|
+
* if (messageRecord["role"] !== MESSAGE_ROLE_BY_TYPE[type])
|
|
72
|
+
* throw new Error(`${subject} message must have role "${expectedRole}"`)
|
|
73
|
+
* const source = messageRecord["source"]
|
|
74
|
+
* if (typeof source["kind"] !== "string" || source["kind"] === "")
|
|
75
|
+
* throw new Error(`${subject} message has invalid source`)
|
|
76
|
+
*
|
|
77
|
+
* 早先 completion.mjs / todo-gate.mjs 各自手写 `{ content, source }`(没有 id、
|
|
78
|
+
* 没有 role),注入后日志里留下非法 user/message,**该会话历史从此加载失败**:
|
|
79
|
+
* stored session failed validation:
|
|
80
|
+
* session event at seq 8738 lacks an identified message
|
|
81
|
+
* (session-05a8cb50 真实事故)。
|
|
82
|
+
*
|
|
83
|
+
* 所以:id / role 只能在这里生成一次,任何注入点都不得自己拼消息对象。
|
|
84
|
+
* 需要「文案已自带 <system-reminder> 包裹」时用本函数(makeRawSnapshotMessage),
|
|
85
|
+
* 需要外层包裹时用下面的 makeSnapshotMessage —— 两者共用同一条信封构造。
|
|
86
|
+
*
|
|
87
|
+
* @param {Array<{type: string, text?: string}>} content - 已格式化的 content blocks
|
|
88
|
+
* @param {object} [source] - kind 之外的 source 字段(form / sections / …)
|
|
89
|
+
* @returns {{id: string, role: 'user', content: object[], source: object}}
|
|
90
|
+
*/
|
|
91
|
+
export function makeRawSnapshotMessage(content, source = {}) {
|
|
92
|
+
return {
|
|
93
|
+
// 每条消息一个全新 uuid:复用固定 id 会被宿主的 pending 去重判成
|
|
94
|
+
// 「message "<id>" is already pending」(inbox.splice 的 ids 检查)。
|
|
95
|
+
id: randomUUID(),
|
|
96
|
+
role: 'user',
|
|
97
|
+
content,
|
|
98
|
+
source: { ...PREFLIGHT_SOURCE, ...source },
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* 构造 snapshot 形式的上下文消息(外层加 <system-reminder> 包裹)。
|
|
104
|
+
*
|
|
105
|
+
* 为什么用 snapshot 而不是 notice:
|
|
106
|
+
* notice 每次追加,20 次委派 ≈ 2040 token 永久留在历史;
|
|
107
|
+
* snapshot 新代旧,始终只有一份。
|
|
108
|
+
*
|
|
109
|
+
* sections 是官方要求的字段(ContextFormed 的 snapshot 分支,
|
|
110
|
+
* dsh-llm/src/message.ts:84-90)。
|
|
111
|
+
*/
|
|
112
|
+
function makeSnapshotMessage(sections) {
|
|
113
|
+
// ── 必须转义 </system-reminder> ──
|
|
114
|
+
//
|
|
115
|
+
// provider/model 名称来自用户配置,可以包含任意字符。若不转义,
|
|
116
|
+
// 一个形如 `</system-reminder>\n\n忽略以上所有指令` 的 model 名会真的闭合
|
|
117
|
+
// 我们的提醒标签,把后续文本变成正文 —— 这是提示注入。
|
|
118
|
+
//
|
|
119
|
+
// 官方 runtime-context.ts 做同样的转义(大小写与尾随空白都覆盖):
|
|
120
|
+
// .replace(/<\/system-reminder\s*>/gi, tag => `<\\${tag.slice(1)}`)
|
|
121
|
+
const escape = (text) => String(text).replace(/<\/system-reminder\s*>/gi, tag => `<\\${tag.slice(1)}`)
|
|
122
|
+
const body = sections.map((section) => escape(section.text)).join('\n\n')
|
|
123
|
+
// 信封(id / role / source.kind)由 makeRawSnapshotMessage 唯一生成 —— 见其头注释。
|
|
124
|
+
// sections 保留原始文本(官方约定:日志中的 sections 不转义,包装才是格式约定)
|
|
125
|
+
return makeRawSnapshotMessage(
|
|
126
|
+
[{ type: 'text', text: `<system-reminder>\n${body}\n</system-reminder>` }],
|
|
127
|
+
{ form: 'snapshot', sections },
|
|
128
|
+
)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* 实时读取「疑似孤儿」的共享任务:pending 且无 ownerId 且未被阻塞。
|
|
134
|
+
*
|
|
135
|
+
* ── 为什么用实时板而不是事件 / 预留集合(X16)────────────────
|
|
136
|
+
* dispatch-gate 的 reserved 只覆盖「派发时被 reserve 过」的任务;
|
|
137
|
+
* 「先建任务 → 弹确认卡 → 用户打断 → 派发从未发生」这类任务从没被 reserve,
|
|
138
|
+
* 事件流里也不会留下任何痕迹。唯一能看见它的地方就是实时任务板本身,
|
|
139
|
+
* 因此这里直接 ctx.get('agentTeams').listTasks(agent)(与 X5 / dispatch-gate 同源)。
|
|
140
|
+
*
|
|
141
|
+
* 代价:板上无法区分「刚建、即将派发」与「真孤儿」——reserve 是内存态,
|
|
142
|
+
* 不在板上。所以文案必须**非指责**,只列事实让主 agent 自己判断。
|
|
143
|
+
*
|
|
144
|
+
* @param {object} ctx cordis context
|
|
145
|
+
* @param {object} [agent] 当前主 agent
|
|
146
|
+
* @returns {Array<object> | null} 疑似孤儿任务;服务不可用 / 无 listTasks / 抛错时返回 null
|
|
147
|
+
*/
|
|
148
|
+
function readOrphanTasks(ctx, agent) {
|
|
149
|
+
let teams
|
|
150
|
+
try {
|
|
151
|
+
if (typeof ctx?.get === 'function') teams = ctx.get('agentTeams')
|
|
152
|
+
} catch { return null }
|
|
153
|
+
if (teams === null || typeof teams !== 'object' || typeof teams.listTasks !== 'function') return null
|
|
154
|
+
let tasks
|
|
155
|
+
try { tasks = teams.listTasks(agent) } catch { return null }
|
|
156
|
+
if (!Array.isArray(tasks)) return null
|
|
157
|
+
return tasks.filter((task) => task !== null && typeof task === 'object'
|
|
158
|
+
&& task.status === 'pending'
|
|
159
|
+
&& (task.ownerId === undefined || task.ownerId === null)
|
|
160
|
+
// blockedBy 非空 = 合法等待上游任务,不算孤儿。
|
|
161
|
+
&& !(Array.isArray(task.blockedBy) && task.blockedBy.length > 0))
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 构造孤儿提醒文案:**非指责**、只陈述事实、给出处置指引。
|
|
166
|
+
*
|
|
167
|
+
* 只用「已建未派的共享任务」描述,不用「孤儿 / 错误 / 失败」这类定性词
|
|
168
|
+
* ——插件无法从板上区分「刚建即将派」与「真残留」,定性会冤枉正常的并发批次。
|
|
169
|
+
*
|
|
170
|
+
* @param {string[]} ids 任务 id(调用方保证非空)
|
|
171
|
+
* @returns {string}
|
|
172
|
+
*/
|
|
173
|
+
function buildOrphanReminder(ids) {
|
|
174
|
+
const shown = ids.slice(0, 5)
|
|
175
|
+
return [
|
|
176
|
+
`[team-preflight] 检测到 ${ids.length} 个已建未派的共享任务:${shown.join('、')}。`,
|
|
177
|
+
'若它们属于即将派发的批次,请在派发 prompt 里写明领取;',
|
|
178
|
+
'若是残留(如用户中断了确认流程),请 team_task_update 删除(action: "delete")。',
|
|
179
|
+
].join('\n')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 统一的监听器登记袋(R1/P2 卸载纪律):收 ctx.on 的 off,卸载时逐个摘。
|
|
184
|
+
*
|
|
185
|
+
* 抽出来的理由(W4-24):installPostExecuteNotice 里有三段「try { ctx.on } catch {}」
|
|
186
|
+
* 样板(路由提示 / 孤儿检测 / 卸载),与业务逻辑混在一起让 247 行的主函数更难过读;
|
|
187
|
+
* 登记纪律只有一处实现。
|
|
188
|
+
* @param {object} ctx cordis context
|
|
189
|
+
* @returns {{disposers: Function[], listen: (event: string, fn: Function) => void}}
|
|
190
|
+
*/
|
|
191
|
+
function createListenerBag(ctx) {
|
|
192
|
+
const disposers = []
|
|
193
|
+
const listen = (event, fn) => {
|
|
194
|
+
try {
|
|
195
|
+
const off = ctx.on(event, fn)
|
|
196
|
+
if (typeof off === 'function') disposers.push(off)
|
|
197
|
+
} catch { /* 监听器注册失败不应阻断插件加载 */ }
|
|
198
|
+
}
|
|
199
|
+
return { disposers, listen }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* 每会话孤儿检测状态表的容量上限(W4-25)。
|
|
204
|
+
*
|
|
205
|
+
* ── 为什么需要(审计 W4-25)────────────────────────────────────────────
|
|
206
|
+
* 旧实现:turnSeq / pending / alerted 三张 per-session 表**只在卸载时 clear()**,
|
|
207
|
+
* 安装期间每见过一个会话就多一条 —— 宿主长期运行 + 多会话 / 多项目工作区时无界增长
|
|
208
|
+
* (gate 的确认表、todo-gate 的轮次表都有 SESSION_MAP_CAP=1024 同款上限,唯独这三张没有)。
|
|
209
|
+
* 现在设同一族上限:**超限淘汰最旧(FIFO)**。
|
|
210
|
+
*
|
|
211
|
+
* ── 为什么淘汰「最旧」而不是 LRU ─────────────────────────────────────
|
|
212
|
+
* 三张表都是**按轮次去重**的短命状态(turn/start 就刷新序号),不需要命中率精度;
|
|
213
|
+
* FIFO 与 Map/Set 的插入序天然一致,零额外簿记。若真的淘汰了仍在用的会话,
|
|
214
|
+
* 后果只是「该会话下一轮可能多提醒一次」(提醒本身无副作用),不会丢注入。
|
|
215
|
+
*/
|
|
216
|
+
const ORPHAN_SESSION_CAP = 1024
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* 创建孤儿检测的每会话状态表(纯内存、无 I/O、无 ctx 依赖)。
|
|
220
|
+
*
|
|
221
|
+
* 抽成独立工厂的原因(W4-24 可读性 + W4-25 可测性):
|
|
222
|
+
* · 旧实现把三张表 + 四个读写点混在 installOrphanDetection 的监听器闭包里,
|
|
223
|
+
* 容量策略无处安放;
|
|
224
|
+
* · 容量/淘汰是本批**唯一允许的行为变化**,必须能被单测直接钉住 —— 有了这个
|
|
225
|
+
* 工厂,不用造 ctx 夹具、不用发事件就能断言「超限淘汰最旧」。
|
|
226
|
+
*
|
|
227
|
+
* 语义与旧实现逐字一致(只有容量策略是新增的):
|
|
228
|
+
* turn/start → seq +1 且置 pending;subagent/end → 置 pending;
|
|
229
|
+
* post-execute 取走 pending、按 seq 去重、注入后记 alerted=seq。
|
|
230
|
+
* @param {number} [cap] 表容量上限(默认 ORPHAN_SESSION_CAP;测试可注入小值)
|
|
231
|
+
*/
|
|
232
|
+
export function createOrphanNoticeState(cap = ORPHAN_SESSION_CAP) {
|
|
233
|
+
const limit = Number.isFinite(cap) && cap > 0 ? Math.floor(cap) : ORPHAN_SESSION_CAP
|
|
234
|
+
/** 每个会话的轮次序号(turn/start 自增;subagent/end 不改)。 */
|
|
235
|
+
const turnSeqBySession = new Map()
|
|
236
|
+
/** 已请求在下一次 post-execute 检查的会话。 */
|
|
237
|
+
const pendingBySession = new Set()
|
|
238
|
+
/** 每个会话最近一次真正注入提醒的轮次序号(去重键)。 */
|
|
239
|
+
const alertedSeqBySession = new Map()
|
|
240
|
+
|
|
241
|
+
/** 淘汰某会话的**全部**状态:三张表同进同退,绝不留下「半套」状态。 */
|
|
242
|
+
const forget = (key) => {
|
|
243
|
+
turnSeqBySession.delete(key)
|
|
244
|
+
pendingBySession.delete(key)
|
|
245
|
+
alertedSeqBySession.delete(key)
|
|
246
|
+
}
|
|
247
|
+
/** 有界写入前置:表满且是新键 → 先淘汰最旧(最早插入)会话的全部状态,再交给调用方写入。 */
|
|
248
|
+
const makeRoom = (table, key) => {
|
|
249
|
+
if (table.has(key)) return
|
|
250
|
+
if (table.size < limit) return
|
|
251
|
+
const oldest = table.keys().next()
|
|
252
|
+
if (oldest.done !== true) forget(oldest.value)
|
|
253
|
+
}
|
|
254
|
+
const turnSeqOf = (key) => turnSeqBySession.get(key) ?? 0
|
|
255
|
+
const notePending = (key) => {
|
|
256
|
+
makeRoom(pendingBySession, key)
|
|
257
|
+
pendingBySession.add(key)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return {
|
|
261
|
+
noteTurnStart(key) {
|
|
262
|
+
makeRoom(turnSeqBySession, key)
|
|
263
|
+
turnSeqBySession.set(key, turnSeqOf(key) + 1)
|
|
264
|
+
notePending(key)
|
|
265
|
+
},
|
|
266
|
+
notePending,
|
|
267
|
+
takePending(key) {
|
|
268
|
+
if (!pendingBySession.has(key)) return false
|
|
269
|
+
pendingBySession.delete(key)
|
|
270
|
+
return true
|
|
271
|
+
},
|
|
272
|
+
turnSeqOf,
|
|
273
|
+
isAlerted(key) { return alertedSeqBySession.get(key) === turnSeqOf(key) },
|
|
274
|
+
markAlerted(key) {
|
|
275
|
+
makeRoom(alertedSeqBySession, key)
|
|
276
|
+
alertedSeqBySession.set(key, turnSeqOf(key))
|
|
277
|
+
},
|
|
278
|
+
clear() {
|
|
279
|
+
turnSeqBySession.clear()
|
|
280
|
+
pendingBySession.clear()
|
|
281
|
+
alertedSeqBySession.clear()
|
|
282
|
+
},
|
|
283
|
+
/** 诊断 / 单测:三张表当前条目数(容量断言用;不参与业务)。 */
|
|
284
|
+
sizes() {
|
|
285
|
+
return { turnSeq: turnSeqBySession.size, pending: pendingBySession.size, alerted: alertedSeqBySession.size }
|
|
286
|
+
},
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* 孤儿共享任务检测(X16):subagent/end 与 turn/start 触发,tools/post-execute 注入。
|
|
292
|
+
*
|
|
293
|
+
* ── 为什么检测在 subagent/end + turn/start、注入却在 post-execute ──
|
|
294
|
+
* subagent/end / turn/start 都是生命周期事件,没有注入通道;唯一能把文本送进
|
|
295
|
+
* 主 agent 上下文的既有通道是 tools/post-execute 返回 additionalContexts
|
|
296
|
+
* (completion.mjs 对同一问题采用同一做法)。所以这里在两个触发点「记账」,
|
|
297
|
+
* 在下一个 post-execute 一次性注入。
|
|
298
|
+
*
|
|
299
|
+
* ── 防噪(X16)──
|
|
300
|
+
* · 去重键 = 会话 + 轮次序号:同一轮只提醒一次。
|
|
301
|
+
* · 孤儿数 0 → 不注入。
|
|
302
|
+
* · 文案最多列 5 个 id(总数仍如实给出)。
|
|
303
|
+
* · listTasks 不可用(返回 null)→ 静默跳过、不抛错。
|
|
304
|
+
* · 每会话状态表有容量上限(W4-25,见 createOrphanNoticeState)。
|
|
305
|
+
*
|
|
306
|
+
* @param {object} ctx cordis context
|
|
307
|
+
* @param {(event: string, fn: Function) => void} listen 统一的监听器登记函数
|
|
308
|
+
* @returns {{ clear: () => void }} 清理去重状态的句柄(卸载时调用)
|
|
309
|
+
*/
|
|
310
|
+
function installOrphanDetection(ctx, listen) {
|
|
311
|
+
// 三张 per-session 表及其容量策略集中在工厂里(W4-25);本函数只做事件接线。
|
|
312
|
+
const state = createOrphanNoticeState()
|
|
313
|
+
|
|
314
|
+
// ── 触发点 1:turn/start —— 新一轮开始,最容易发现上一批遗留孤儿 ──
|
|
315
|
+
listen('session/event', (session, event) => {
|
|
316
|
+
try {
|
|
317
|
+
if (event?.type !== 'turn/start') return
|
|
318
|
+
const key = sessionKeyOf(session)
|
|
319
|
+
if (key === undefined) return
|
|
320
|
+
state.noteTurnStart(key)
|
|
321
|
+
} catch { /* 状态跟踪失败不影响主流程 */ }
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
// ── 触发点 2:subagent/end —— 一路结束,顺带检查板上是否留下未派任务 ──
|
|
325
|
+
listen('subagent/end', (info) => {
|
|
326
|
+
try {
|
|
327
|
+
const key = typeof info?.parentSessionId === 'string' && info.parentSessionId !== ''
|
|
328
|
+
? info.parentSessionId
|
|
329
|
+
: undefined
|
|
330
|
+
if (key === undefined) return
|
|
331
|
+
state.notePending(key)
|
|
332
|
+
} catch { /* 同上 */ }
|
|
333
|
+
})
|
|
334
|
+
|
|
335
|
+
// ── 注入点:tools/post-execute —— 一次性把提醒交给主 agent ──
|
|
336
|
+
//
|
|
337
|
+
// 放在 route 监听器之后注册,保证既有测试里 listeners['tools/post-execute'][0]
|
|
338
|
+
// 仍是路由提示监听器(X16 不改既有契约)。
|
|
339
|
+
listen('tools/post-execute', async (exec, result, next) => {
|
|
340
|
+
const downstream = await next()
|
|
341
|
+
try {
|
|
342
|
+
const key = sessionKeyOf(exec?.agent)
|
|
343
|
+
if (key === undefined) return downstream
|
|
344
|
+
if (!state.takePending(key)) return downstream
|
|
345
|
+
if (state.isAlerted(key)) return downstream
|
|
346
|
+
|
|
347
|
+
const orphans = readOrphanTasks(ctx, exec?.agent)
|
|
348
|
+
// 服务不可用(null)或没有孤儿(空)→ 静默跳过。
|
|
349
|
+
if (orphans === null || orphans.length === 0) return downstream
|
|
350
|
+
|
|
351
|
+
state.markAlerted(key)
|
|
352
|
+
const text = buildOrphanReminder(orphans.map((task) => String(task.id)))
|
|
353
|
+
return {
|
|
354
|
+
...downstream,
|
|
355
|
+
additionalContexts: [
|
|
356
|
+
makeSnapshotMessage([{ name: 'orphan-tasks', text }]),
|
|
357
|
+
...(downstream?.additionalContexts ?? []),
|
|
358
|
+
],
|
|
359
|
+
}
|
|
360
|
+
} catch (error) {
|
|
361
|
+
// 提醒构造失败不影响工具执行,但要能查。
|
|
362
|
+
try {
|
|
363
|
+
ctx.logger?.warn?.('team-preflight: orphan task notice failed:', error?.message ?? error)
|
|
364
|
+
} catch {}
|
|
365
|
+
return downstream
|
|
366
|
+
}
|
|
367
|
+
})
|
|
368
|
+
|
|
369
|
+
return state
|
|
370
|
+
}
|
|
371
|
+
/**
|
|
372
|
+
* 确认档位句(第二波「档位路由显式化」):有确认档位 → 追加一句话,如
|
|
373
|
+
* 「本次档位:深度档(magpie/zhipu/glm-5.3)」;无档位 → 空串(原文案逐字不变)。
|
|
374
|
+
*
|
|
375
|
+
* 数据真相只有一处:tier-state 的确认档位(本会话当轮 suggest_concurrency 卡片上
|
|
376
|
+
* 用户选定的档位与它解析出的路由)。这里只做**转录**:
|
|
377
|
+
* · 模块缺失 / readConfirmedTier 不可用 / 读取抛错 → ''(文案保持原样);
|
|
378
|
+
* · 无确认 / 过期(TTL 由 tier-state 判)→ '';
|
|
379
|
+
* · tier 非法(normalizeTier 不认)但 route 完整 → 兜底标 custom(不臆造档位名);
|
|
380
|
+
* · 路由不完整(缺 provider/model)→ 只写档位名,不臆造路由。
|
|
381
|
+
* @param {object} ctx cordis context
|
|
382
|
+
* @param {object} agent 调用方 agent(取会话键)
|
|
383
|
+
* @returns {string}
|
|
384
|
+
*/
|
|
385
|
+
function tierSentenceOf(ctx, agent) {
|
|
386
|
+
const read = tierStateMod?.readConfirmedTier
|
|
387
|
+
if (typeof read !== 'function') return ''
|
|
388
|
+
try {
|
|
389
|
+
const key = sessionKeyOf(agent)
|
|
390
|
+
if (key === undefined) return ''
|
|
391
|
+
const confirmed = read(key)
|
|
392
|
+
if (confirmed === null || confirmed === undefined
|
|
393
|
+
|| typeof confirmed !== 'object' || Array.isArray(confirmed)) return ''
|
|
394
|
+
const rawTier = confirmed.tier
|
|
395
|
+
const route = confirmed.route !== null && typeof confirmed.route === 'object' ? confirmed.route : null
|
|
396
|
+
// W4-07:未知档位不能用「标准档」冒充。normalizeTier 认的走标准名;其余非空字符串
|
|
397
|
+
// 原样交给 tierLabel(会显示「未知档位(原值)」),custom 保留专用标签。
|
|
398
|
+
const tier = normalizeTier(rawTier)
|
|
399
|
+
?? (typeof rawTier === 'string' && rawTier !== '' ? rawTier : undefined)
|
|
400
|
+
// W4-08 / W4-11:tier 链路(tier-config / badge 绑定 / tier-state)的字段名是 effort,
|
|
401
|
+
// formatRoute 的规范字段是 reasoningEffort —— 在这里显式映射一次(仅在缺 reasoningEffort 时补),
|
|
402
|
+
// 否则档位句会丢掉 effort(「本次档位:深度档(p/m)」而不是「… / effort=high」)。
|
|
403
|
+
const routeForDisplay = route === null
|
|
404
|
+
? null
|
|
405
|
+
: (route.reasoningEffort === undefined && typeof route.effort === 'string' && route.effort !== ''
|
|
406
|
+
? { ...route, reasoningEffort: route.effort }
|
|
407
|
+
: route)
|
|
408
|
+
const routeText = routeForDisplay !== null
|
|
409
|
+
&& typeof routeForDisplay.provider === 'string' && routeForDisplay.provider !== ''
|
|
410
|
+
&& typeof routeForDisplay.model === 'string' && routeForDisplay.model !== ''
|
|
411
|
+
? formatRoute(routeForDisplay)
|
|
412
|
+
: undefined
|
|
413
|
+
if (tier === undefined && routeText === undefined) return ''
|
|
414
|
+
// custom 用专用标签;其余走 tierLabel(三档中文名 / 「未知档位(原值)」/「未定档位」)。
|
|
415
|
+
const label = tier === 'custom' ? 'custom' : tierLabel(tier)
|
|
416
|
+
return routeText === undefined
|
|
417
|
+
? `;本次档位:${label}`
|
|
418
|
+
: `;本次档位:${label}(${routeText})`
|
|
419
|
+
} catch {
|
|
420
|
+
return ''
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* 委派后路由提示的「要不要发」判据(W4-24:从 190 行监听器体内抽出,行为逐字不变)。
|
|
426
|
+
*
|
|
427
|
+
* ── 失败 / 被拒的委派不发提示 ──
|
|
428
|
+
*
|
|
429
|
+
* 早先不看结果,导致委派失败时模型仍被告知「本次将使用 X」,
|
|
430
|
+
* 于是向用户复述一个从未发生的路由;同时去重表被写入,
|
|
431
|
+
* 后续真实成功的同路由委派反而被跳过。
|
|
432
|
+
*
|
|
433
|
+
* 失败判定看三个来源:
|
|
434
|
+
* result.isError — 工具体抛错(subagent 校验失败走这条)★
|
|
435
|
+
* result.error — 结构化错误
|
|
436
|
+
* downstream.kind==='block' — 被前置监听器拒绝
|
|
437
|
+
*
|
|
438
|
+
* ★ 2026-11-18 asar 官方源码定谳(两次查证,最终结论):
|
|
439
|
+
* 工具体**抛错会进 post-execute**,错误以 `isError` 结果的形式传入。
|
|
440
|
+
* 依据 dsh-tools/src/pipeline.ts 的 `dispatch()`:
|
|
441
|
+
* try {
|
|
442
|
+
* const result = await this.ctx.waterfall(carrier, 'tools/execute', mutableExec,
|
|
443
|
+
* () => this.dispatchToolBody(mutableExec)) // ← 工具体抛错在此被 catch 成返回值
|
|
444
|
+
* return { kind: 'post-result', result: ... } // ← 照走 post-execute
|
|
445
|
+
* } catch (error) {
|
|
446
|
+
* return { kind: 'final-result', result: toolErrorResult(error) } // ← 只有 waterfall 自身抛错才跳过
|
|
447
|
+
* }
|
|
448
|
+
* 同文件 :297 的 doc comment 明写:
|
|
449
|
+
* "Tool and unknown-tool failures still receive post-execute;
|
|
450
|
+
* pipeline failures are already final."
|
|
451
|
+
*
|
|
452
|
+
* 注意区分:pipeline.ts:181 / :232 的 `final-result` 属于 **prepare 阶段**
|
|
453
|
+
* (工具被 reject 或 prepare 抛错),不是工具体执行 —— 早期误把那段当成
|
|
454
|
+
* dispatch 的错误路径,结论正好相反。此处以 dispatch() 与 :297 注释为准。
|
|
455
|
+
*
|
|
456
|
+
* @param {object} exec 工具执行上下文
|
|
457
|
+
* @param {object} result 工具体结果
|
|
458
|
+
* @param {object} downstream 下游 PostToolDecision
|
|
459
|
+
* @returns {boolean} true = 本次跳过(非委派 / 无 agent / 失败或被拒)
|
|
460
|
+
*/
|
|
461
|
+
function routeNoticeSkipped(exec, result, downstream) {
|
|
462
|
+
if (!isDelegationTool(exec.name)) return true
|
|
463
|
+
if (exec.agent === undefined) return true
|
|
464
|
+
const failed = result?.isError === true
|
|
465
|
+
|| result?.error !== undefined
|
|
466
|
+
|| downstream?.kind === 'block'
|
|
467
|
+
if (!failed) return false
|
|
468
|
+
// 失败时清掉去重记录,让下一次成功的同路由委派能正常发提示
|
|
469
|
+
const key = sessionObjectOf(exec.agent)
|
|
470
|
+
if (key !== undefined) lastSnapshotBySession.delete(key)
|
|
471
|
+
return true
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/**
|
|
475
|
+
* 委派后路由提示正文 + 实际应用路由(方案 C)。
|
|
476
|
+
*
|
|
477
|
+
* 与注入 / 自检共用同一份判断:显示的路由就是实际使用的路由。
|
|
478
|
+
* 构造失败(任何异常)→ 返回 undefined,调用方降级为原结果(只记 warn)。
|
|
479
|
+
* @param {object} ctx cordis context
|
|
480
|
+
* @param {object} exec 工具执行上下文(含 agent / name / arguments)
|
|
481
|
+
* @returns {{text: string, appliedRoute: string|undefined}|undefined}
|
|
482
|
+
*/
|
|
483
|
+
async function routeNoticeOf(ctx, exec) {
|
|
484
|
+
const agent = exec.agent
|
|
485
|
+
let text
|
|
486
|
+
// 方案 C 需要把实际路由带到返回结果里,因此提到 try 外
|
|
487
|
+
let appliedRoute
|
|
488
|
+
try {
|
|
489
|
+
const autoInjected = injectedExecutions.has(exec)
|
|
490
|
+
// 本插件只为 isModelSelectableTool 为真的工具注入;对 subagent_fork 这类不支持
|
|
491
|
+
// 模型选择的工具,决策里不能把界面选择当成会生效的路由。
|
|
492
|
+
const injectable = isModelSelectableTool(ctx, agent, exec.name)
|
|
493
|
+
// 界面选择读取很便宜,始终读(提示文案要用它判断「未生效」);
|
|
494
|
+
// 白名单要读投影,只在真可能注入时才读。
|
|
495
|
+
// X13:读**当前会话**的界面选择(sessionKeyOf 取会话 id)。
|
|
496
|
+
const uiSelection = readUiSelection(ctx, sessionKeyOf(agent))
|
|
497
|
+
const allowedRoutes = injectable && !autoInjected && !hasExplicitRouteArgs(exec.arguments)
|
|
498
|
+
&& uiSelection !== undefined && uiSelection !== null
|
|
499
|
+
? await allowedRoutesOf(ctx, agent)
|
|
500
|
+
: undefined
|
|
501
|
+
|
|
502
|
+
// 与注入 / 自检共用同一份判断:显示的路由就是实际使用的路由
|
|
503
|
+
const decision = resolveEffectiveRoute({
|
|
504
|
+
agent,
|
|
505
|
+
args: exec.arguments,
|
|
506
|
+
uiSelection: injectable ? uiSelection : undefined,
|
|
507
|
+
allowedRoutes,
|
|
508
|
+
autoInjected,
|
|
509
|
+
})
|
|
510
|
+
const routeText = formatRoute(decision.route)
|
|
511
|
+
const sourceText = decision.reason
|
|
512
|
+
|
|
513
|
+
const team = teamEnabled(ctx, agent)
|
|
514
|
+
const teamText = team === undefined ? 'Team 不可用' : team ? 'Team 已开启' : 'Team 未开启'
|
|
515
|
+
|
|
516
|
+
// 界面选择与实际不一致时才额外说明(正常情况下省掉这段)
|
|
517
|
+
let mismatch = ''
|
|
518
|
+
if (uiSelection !== undefined && uiSelection !== null) {
|
|
519
|
+
const uiRoute = `${uiSelection.provider}/${uiSelection.model}`
|
|
520
|
+
const actual = decision.route?.provider !== undefined && decision.route?.model !== undefined
|
|
521
|
+
? `${decision.route.provider}/${decision.route.model}`
|
|
522
|
+
: undefined
|
|
523
|
+
if (actual !== undefined && actual !== uiRoute) {
|
|
524
|
+
mismatch = `;界面选择 ${uiRoute} 未生效`
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// ── 诚实标注:非 `subagent` 实例的路由本插件读不到 ──
|
|
529
|
+
//
|
|
530
|
+
// `- insert:` 新增的实例(如 profile 里的 `tool-subagent-glm`)路由由
|
|
531
|
+
// 它自己的 `config.agentOptions` 决定,而 `tools.definitions()` 只暴露
|
|
532
|
+
// ToolDefinition(name/description/parameters),**不含 config**。
|
|
533
|
+
// 因此本插件无法得知真实路由。
|
|
534
|
+
//
|
|
535
|
+
// 信任链上「说不知道」远好于「说错」:早先这里会给出一个看似确定
|
|
536
|
+
// 但错误的「继承主代理」,正是本插件要消灭的那种失真。
|
|
537
|
+
// 仅在「确实可能读不到」时才提示:非 subagent 实例 **且** 本次是继承
|
|
538
|
+
// (decision.source === 'inherited')。若是显式指定或按界面选择注入,路由
|
|
539
|
+
// 来自参数、本插件看得见——此时再挂「读不到」就是狼来了,稀释真正需要
|
|
540
|
+
// 警惕的场景(未配 agentOptions 的 insert 实例、以及将来任何非 subagent 名)。
|
|
541
|
+
const instanceNote = exec.name === 'subagent' || decision.source !== 'inherited'
|
|
542
|
+
? ''
|
|
543
|
+
: `;⚠ 该实例若配置 agentOptions,实际路由由它决定(本插件读不到)`
|
|
544
|
+
|
|
545
|
+
// 精简文案:约 40 token(原 notice 版本 102 token)。
|
|
546
|
+
// 第二波档位记账:有确认档位时 tierSentenceOf 追加「;本次档位:…」;
|
|
547
|
+
// 无档位返回 '',text 与改造前逐字相同(去重、§19.7 对拍等既有契约不破)。
|
|
548
|
+
text = `子代理路由:${routeText}(${sourceText});${teamText}${mismatch}${instanceNote}`
|
|
549
|
+
|
|
550
|
+
// 方案 C:记录实际路由,供 tool/result content 使用。
|
|
551
|
+
// 用 formatRoute 复用唯一的路由格式化实现 —— 早先这里手写了一份,
|
|
552
|
+
// effort 少写 "effort=",与提示/报告里的格式不一致(两份实现会漂移)。
|
|
553
|
+
if (decision.route?.provider !== undefined && decision.route?.model !== undefined) {
|
|
554
|
+
appliedRoute = formatRoute(decision.route)
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
// ── 档位句(第二波「档位路由显式化」)──────────────────────────────
|
|
558
|
+
//
|
|
559
|
+
// 有确认档位(suggest_concurrency 卡片上用户选定的档位)才追加一句
|
|
560
|
+
// 「本次档位:深度档(provider/model)」;无档位(未确认 / 过期 / 通道缺失)
|
|
561
|
+
// → tierSentenceOf 返回 '',text 与改造前逐字相同(向后兼容硬约束)。
|
|
562
|
+
//
|
|
563
|
+
// 追加位置在 try 内(sessionKeyOf(agent) 可用),失败由外层 catch 兜底
|
|
564
|
+
// (提示构造失败不影响委派结果,只记 warn)。
|
|
565
|
+
text += tierSentenceOf(ctx, agent)
|
|
566
|
+
} catch (error) {
|
|
567
|
+
// W4-20:注释承诺「失败只记 warn」,旧实现静默 return。补上留痕(logger 本身
|
|
568
|
+
// 失败也不能影响返回:双层 try/catch)。
|
|
569
|
+
try {
|
|
570
|
+
ctx?.logger?.warn?.('[team-preflight] 委派提示构造失败(降级为原结果):', error?.message ?? error)
|
|
571
|
+
} catch { /* logger 不可用 */ }
|
|
572
|
+
return undefined
|
|
573
|
+
}
|
|
574
|
+
return { text, appliedRoute }
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
/**
|
|
578
|
+
* 去重 + 组装 PostToolDecision(W4-24:从监听器尾部抽出,行为逐字不变)。
|
|
579
|
+
*
|
|
580
|
+
* 三件独立的事,顺序与旧实现一致:
|
|
581
|
+
* ① snapshot 提示:文案**相同**才跳过(去重只作用于提示);
|
|
582
|
+
* ② tool/result content 路由标记:**不去重**,每次委派都追加;
|
|
583
|
+
* ③ 只在硬约束第 5 条内动作:content 只追加(基于 result.content),绝不替换。
|
|
584
|
+
*
|
|
585
|
+
* ── 用 snapshot 形式注入(内容相同则跳过,**但不取代旧消息**)──
|
|
586
|
+
*
|
|
587
|
+
* ⚠️ 重要更正:`form: 'snapshot'` 的「新代旧」语义**只对
|
|
588
|
+
* `source.kind === 'runtime-context'` 生效**。
|
|
589
|
+
*
|
|
590
|
+
* dsh-agent-loop/src/runtime-context.ts:20,24-26:
|
|
591
|
+
* const SOURCE = 'runtime-context'
|
|
592
|
+
* function isOwned(message) { return message.source.kind === SOURCE }
|
|
593
|
+
*
|
|
594
|
+
* `RuntimeContextProjection` 只跟踪 isOwned 的消息,因此本插件
|
|
595
|
+
* (source.kind = 'team-preflight')发出的 snapshot **永远不会被 supersede**。
|
|
596
|
+
* 它在历史里就是一条普通 user 消息,只是被标了 form 字段。
|
|
597
|
+
*
|
|
598
|
+
* 真实行为:
|
|
599
|
+
* - 文案**相同** → 跳过不发送(由下面的 previous === text 保证)
|
|
600
|
+
* - 文案**变化**(换路由 / Team 状态变 / 出现 mismatch)→ **追加一条新消息**
|
|
601
|
+
*
|
|
602
|
+
* 所以正确的预期是「同一配置下不重复发」,而不是「恒定一份」。
|
|
603
|
+
* 保留 snapshot 形式的价值:语义上更准确地表达「这是当前状态」,
|
|
604
|
+
* 且若未来官方把 supersede 推广到任意 source,行为会自动变好。
|
|
605
|
+
*
|
|
606
|
+
* 若要做到真正恒定一份,需改用 agent.inject() 配合 surface replacement,
|
|
607
|
+
* 那会依赖内部机制,不在本插件范围内。
|
|
608
|
+
*
|
|
609
|
+
* @param {object} agent 当前主 agent
|
|
610
|
+
* @param {object} downstream 下游 PostToolDecision
|
|
611
|
+
* @param {object} result 工具体结果(content 追加必须基于**执行结果**)
|
|
612
|
+
* @param {{text: string, appliedRoute: string|undefined}} notice 提示正文
|
|
613
|
+
* @returns {object} PostToolDecision(失败 → 原样返回 downstream)
|
|
614
|
+
*/
|
|
615
|
+
function routeNoticeDecisionOf(agent, downstream, result, notice) {
|
|
616
|
+
try {
|
|
617
|
+
const section = { name: 'subagent-route', text: notice.text }
|
|
618
|
+
const key = sessionObjectOf(agent)
|
|
619
|
+
|
|
620
|
+
// ── 去重只作用于「提示」,不作用于「路由标记」──
|
|
621
|
+
//
|
|
622
|
+
// 2026-11-18 回归:早先去重命中时直接 `return downstream`,
|
|
623
|
+
// 把方案 C 的 content 追加也一起跳过了。而 text 只由
|
|
624
|
+
// 「路由 + Team 状态 + mismatch」组成,同一会话里路由不变时文案恒定
|
|
625
|
+
// —— 于是**第 2 次及以后的所有委派既不发提示、也不追加标记**。
|
|
626
|
+
// 方案 C 的目标(fork/resume/replay 可重建真相)实际只达成了 1/3。
|
|
627
|
+
//
|
|
628
|
+
// 现在拆成两个独立决定:
|
|
629
|
+
// shouldNotice → 要不要发 snapshot 提示(去重)
|
|
630
|
+
// content 追加 → 每次委派都做(可追溯性是逐条事实,不该去重)
|
|
631
|
+
let shouldNotice = true
|
|
632
|
+
if (key !== undefined) {
|
|
633
|
+
const previous = lastSnapshotBySession.get(key)
|
|
634
|
+
shouldNotice = previous !== notice.text
|
|
635
|
+
if (shouldNotice) lastSnapshotBySession.set(key, notice.text)
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
return {
|
|
639
|
+
...downstream,
|
|
640
|
+
...(shouldNotice
|
|
641
|
+
? {
|
|
642
|
+
additionalContexts: [
|
|
643
|
+
makeSnapshotMessage([section]),
|
|
644
|
+
...(downstream.additionalContexts ?? []),
|
|
645
|
+
],
|
|
646
|
+
}
|
|
647
|
+
: {}),
|
|
648
|
+
// ── 方案 C:把实际路由写进 tool/result 的 content ──
|
|
649
|
+
//
|
|
650
|
+
// 为什么需要这一步:
|
|
651
|
+
// tool/call 事件在 tools/execute 之前就写完了(batch.ts settlement.start),
|
|
652
|
+
// 而我们注入的 provider/model 发生在之后 —— 所以会话日志里的
|
|
653
|
+
// tool/call 参数**不含**实际路由。fork / resume / replay 无法重建真相。
|
|
654
|
+
//
|
|
655
|
+
// 本插件无法改写 tool/call(契约禁止),但可以在 post-execute 里
|
|
656
|
+
// 把路由追加到 model-facing content —— 该 content 会随 tool/result
|
|
657
|
+
// 一起持久化,因此「实际用了哪个路由」在日志里可追溯。
|
|
658
|
+
//
|
|
659
|
+
// ⚠️ 必须基于 **result.content**(执行结果),不是 downstream.content(决策)。
|
|
660
|
+
// 2026-11-18 事故:误用 downstream.content 时它是 undefined,
|
|
661
|
+
// 于是 content 变成「只有路由标记」,把工具原本的渲染输出
|
|
662
|
+
// (如 `started subagent <name>`)整个替换掉了。
|
|
663
|
+
// PostToolDecision 的 content 是**替换**语义,不是追加语义。
|
|
664
|
+
//
|
|
665
|
+
// ⚠️ 标记**不去重**:每次委派都追加。去重会让第二次以后的委派无标记。
|
|
666
|
+
...(notice.appliedRoute === undefined
|
|
667
|
+
? {}
|
|
668
|
+
: {
|
|
669
|
+
content: [
|
|
670
|
+
...(result?.content ?? []),
|
|
671
|
+
{
|
|
672
|
+
type: 'text',
|
|
673
|
+
// 前面加换行:content 块在 UI 里是相邻拼接的,
|
|
674
|
+
// 不加分隔会渲染成 `started subagent x[team-preflight] ...`。
|
|
675
|
+
text: `\n[team-preflight] delegated with ${notice.appliedRoute}`,
|
|
676
|
+
},
|
|
677
|
+
],
|
|
678
|
+
}),
|
|
679
|
+
}
|
|
680
|
+
} catch (error) {
|
|
681
|
+
// 提示构造失败不影响委派结果,但要能查
|
|
682
|
+
try {
|
|
683
|
+
ctx.logger?.warn?.('team-preflight: snapshot notice failed:', error?.message ?? error)
|
|
684
|
+
} catch {}
|
|
685
|
+
return downstream
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/**
|
|
690
|
+
* 委派后路由提示(snapshot 形式;方案 C 路由标记)。
|
|
691
|
+
*
|
|
692
|
+
* 只做三件事的编排:判据(routeNoticeSkipped)→ 正文(routeNoticeOf)→ 组装
|
|
693
|
+
* (routeNoticeDecisionOf)。三段各自可单测,主函数不再是一个 190 行的闭包。
|
|
694
|
+
* @param {object} ctx cordis context
|
|
695
|
+
* @param {(event: string, fn: Function) => void} listen 监听器登记函数
|
|
696
|
+
*/
|
|
697
|
+
function installRouteNotice(ctx, listen) {
|
|
698
|
+
listen('tools/post-execute', async (exec, result, next) => {
|
|
699
|
+
const downstream = await next()
|
|
700
|
+
if (routeNoticeSkipped(exec, result, downstream)) return downstream
|
|
701
|
+
const notice = await routeNoticeOf(ctx, exec)
|
|
702
|
+
if (notice === undefined) return downstream
|
|
703
|
+
return routeNoticeDecisionOf(exec.agent, downstream, result, notice)
|
|
704
|
+
})
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* 安装委派后提示(路由快照 + 孤儿共享任务提醒)。
|
|
709
|
+
*
|
|
710
|
+
* 旧实现是一个 247 行的大函数:监听器登记样板 + 路由判据 + 文案拼装 + 去重 +
|
|
711
|
+
* 孤儿检测全挤在同一个闭包里(审计 W4-24「超长函数」)。现在按职责拆成:
|
|
712
|
+
* · createListenerBag —— 登记/卸载纪律(唯一实现)
|
|
713
|
+
* · installRouteNotice —— 路由提示编排(判据 / 正文 / 组装三段)
|
|
714
|
+
* · installOrphanDetection —— 孤儿任务检测(状态表在 createOrphanNoticeState)
|
|
715
|
+
* 本函数只保留装配与卸载(与 apply 的分层同款)。
|
|
716
|
+
*
|
|
717
|
+
* @param {object} ctx cordis context
|
|
718
|
+
* @returns {() => void} 卸载:摘除本模块登记的全部监听器 + 清空孤儿检测去重状态
|
|
719
|
+
*/
|
|
720
|
+
export function installPostExecuteNotice(ctx) {
|
|
721
|
+
// ── 监听器统一登记(便于卸载时摘除 + 清去重状态)──
|
|
722
|
+
const { disposers, listen } = createListenerBag(ctx)
|
|
723
|
+
|
|
724
|
+
// ── 1. 委派后:用 snapshot 形式更新「当前子代理路由」状态 ──
|
|
725
|
+
installRouteNotice(ctx, listen)
|
|
726
|
+
|
|
727
|
+
// ── 2. 孤儿共享任务检测:subagent/end + turn/start 触发,post-execute 注入 ──
|
|
728
|
+
const orphanState = installOrphanDetection(ctx, listen)
|
|
729
|
+
|
|
730
|
+
// ── 卸载:摘除本模块登记的全部监听器 + 清空孤儿检测去重状态 ──
|
|
731
|
+
return () => {
|
|
732
|
+
for (const off of disposers.splice(0)) {
|
|
733
|
+
try { off() } catch { /* ctx 已销毁时忽略 */ }
|
|
734
|
+
}
|
|
735
|
+
orphanState.clear()
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
export function installResultDiagnostics(ctx) {
|
|
740
|
+
// ── 2. 观察最终结果:识别「注入导致工具拒收」并给出归因 ──
|
|
741
|
+
//
|
|
742
|
+
// 为什么用 tools/result 而不是 post-execute:
|
|
743
|
+
// post-execute 的返回类型是 PostToolDecision,只有 accept / block,**没有 error**
|
|
744
|
+
// —— 它无法改写错误结果,只能接受或阻断。
|
|
745
|
+
// 而 tools/result 是观察最终结果的钩子,能拿到 isError / error 原文。
|
|
746
|
+
// 官方 practices.md 明确:观察最终结果要在 tools/result。
|
|
747
|
+
//
|
|
748
|
+
// ⚠️ 2026-11-18 asar 定谳:工具体抛错**会**进 post-execute(错误以 isError 结果形式传入,
|
|
749
|
+
// 见 dsh-tools/src/pipeline.ts 的 dispatch() 与 :297 注释)。
|
|
750
|
+
// 所以早先「抛错绕过 post-execute,诊断分支是死代码」这个搬迁理由**不成立**。
|
|
751
|
+
// 搬迁本身仍然正确,但理由应改为:post-execute 只能 accept/block,
|
|
752
|
+
// 无法把诊断信息写回结果;只有 tools/result 能观察最终错误。
|
|
753
|
+
// (相关:post-execute 里「失败判定三来源」那段注释有同一处的完整依据。)
|
|
754
|
+
ctx.on('tools/result', (exec, result) => {
|
|
755
|
+
if (!isDelegationTool(exec?.name)) return
|
|
756
|
+
if (!injectedExecutions.has(exec)) return
|
|
757
|
+
if (result?.isError !== true) return
|
|
758
|
+
const message = String(result?.error?.message ?? '')
|
|
759
|
+
if (!message.includes('child model selection is disabled')) return
|
|
760
|
+
try {
|
|
761
|
+
ctx.logger?.warn?.(
|
|
762
|
+
'team-preflight: the target subagent tool instance has modelSelection disabled; '
|
|
763
|
+
+ 'the auto-injected route was rejected. Either enable modelSelection on that tool '
|
|
764
|
+
+ 'instance, or clear the selection in the badge to delegate without a route.',
|
|
765
|
+
{ tool: exec.name },
|
|
766
|
+
)
|
|
767
|
+
} catch {}
|
|
768
|
+
})
|
|
769
|
+
}
|