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.
Files changed (83) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +225 -2
  3. package/client.js +9781 -0
  4. package/cordis.patch.yml +13 -0
  5. package/docs/BOOST-EVIDENCE.md +259 -0
  6. package/docs/CONFORMANCE.md +236 -0
  7. package/docs/FACTS-CONTRACT.md +368 -0
  8. package/docs/FLOW-COVERAGE.md +215 -0
  9. package/docs/PACKAGE-README.md +858 -0
  10. package/docs/RANGE-PLAN.md +357 -0
  11. package/docs/SECURITY-NOTES.md +110 -0
  12. package/docs/SPLIT-PLAN.md +604 -0
  13. package/docs/STAGE3-CONTRACT.md +287 -0
  14. package/docs/TIER-ROUTING.md +275 -0
  15. package/docs/badge/CONFORMANCE.md +246 -0
  16. package/docs/badge/DETAIL.md +319 -0
  17. package/docs/badge/PROJECTIONS.md +264 -0
  18. package/docs/badge/TEST-PLAN.md +252 -0
  19. package/docs/images/badge-menu.png +0 -0
  20. package/docs/images/dispatch.png +0 -0
  21. package/docs/images/header.png +0 -0
  22. package/docs/images/pair-header.png +0 -0
  23. package/docs/images/pair-panel.png +0 -0
  24. package/docs/images/panel.png +0 -0
  25. package/docs/wiki/Home.md +43 -0
  26. package/docs/wiki//344/275/277/347/224/250/346/214/207/345/215/227.md +116 -0
  27. package/docs/wiki//345/256/211/350/243/205/344/270/216/345/215/207/347/272/247.md +103 -0
  28. package/docs/wiki//346/225/205/351/232/234/346/216/222/346/237/245.md +94 -0
  29. package/icon.svg +12 -0
  30. package/lib/badge-policy.mjs +502 -0
  31. package/lib/badge-sync.mjs +385 -0
  32. package/lib/command.mjs +490 -0
  33. package/lib/completion.mjs +288 -0
  34. package/lib/concurrency.mjs +2555 -0
  35. package/lib/dispatch-command.mjs +181 -0
  36. package/lib/dispatch-gate.mjs +924 -0
  37. package/lib/facts-store.mjs +183 -0
  38. package/lib/gate-state.mjs +465 -0
  39. package/lib/gate.mjs +886 -0
  40. package/lib/index.js +309 -0
  41. package/lib/inject.mjs +195 -0
  42. package/lib/interrupt.mjs +376 -0
  43. package/lib/ledger.mjs +948 -0
  44. package/lib/lifecycle.mjs +274 -0
  45. package/lib/messages.mjs +532 -0
  46. package/lib/notice.mjs +769 -0
  47. package/lib/plan-gate.mjs +385 -0
  48. package/lib/projection.mjs +978 -0
  49. package/lib/report.mjs +290 -0
  50. package/lib/route.mjs +346 -0
  51. package/lib/run-registry.mjs +402 -0
  52. package/lib/services.mjs +293 -0
  53. package/lib/stuck.mjs +567 -0
  54. package/lib/tier-config.mjs +212 -0
  55. package/lib/tier-policy.mjs +167 -0
  56. package/lib/tier-state.mjs +137 -0
  57. package/lib/todo-gate.mjs +1672 -0
  58. package/lib/tools.mjs +2912 -0
  59. package/locale/en.json +9 -0
  60. package/locale/zh.json +9 -0
  61. package/package.json +58 -4
  62. package/vendor/node_modules/@deepseek-ai/cosmokit/LICENSE +21 -0
  63. package/vendor/node_modules/@deepseek-ai/cosmokit/README.md +30 -0
  64. package/vendor/node_modules/@deepseek-ai/cosmokit/lib/index.js +418 -0
  65. package/vendor/node_modules/@deepseek-ai/cosmokit/package.json +32 -0
  66. package/vendor/node_modules/@deepseek-ai/cosmokit/src/array.ts +42 -0
  67. package/vendor/node_modules/@deepseek-ai/cosmokit/src/index.ts +12 -0
  68. package/vendor/node_modules/@deepseek-ai/cosmokit/src/misc.ts +78 -0
  69. package/vendor/node_modules/@deepseek-ai/cosmokit/src/string.ts +113 -0
  70. package/vendor/node_modules/@deepseek-ai/cosmokit/src/time.ts +92 -0
  71. package/vendor/node_modules/@deepseek-ai/cosmokit/src/types.ts +168 -0
  72. package/vendor/node_modules/@deepseek-ai/cosmokit/src/volatile.ts +86 -0
  73. package/vendor/node_modules/@deepseek-ai/schemastery/LICENSE +21 -0
  74. package/vendor/node_modules/@deepseek-ai/schemastery/README.md +393 -0
  75. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.cjs +635 -0
  76. package/vendor/node_modules/@deepseek-ai/schemastery/lib/index.mjs +635 -0
  77. package/vendor/node_modules/@deepseek-ai/schemastery/package.json +39 -0
  78. package/vendor/node_modules/@deepseek-ai/schemastery/src/index.ts +962 -0
  79. package/vendor/node_modules/@standard-schema/spec/LICENSE +21 -0
  80. package/vendor/node_modules/@standard-schema/spec/README.md +198 -0
  81. package/vendor/node_modules/@standard-schema/spec/dist/index.cjs +18 -0
  82. package/vendor/node_modules/@standard-schema/spec/dist/index.js +0 -0
  83. package/vendor/node_modules/@standard-schema/spec/package.json +39 -0
@@ -0,0 +1,288 @@
1
+ /**
2
+ * 完成即记录:子代理结束后提醒主 agent 更新 todo(round-10)。
3
+ *
4
+ * ── 为什么需要这个模块 ─────────────────────────────
5
+ *
6
+ * 用户实测发现:主 agent 派了 5 路并发,共享任务板全部 completed,
7
+ * 但 todo 面板还停在 in_progress —— 因为**没有任何机制提醒主 agent 去更新**。
8
+ *
9
+ * 官方 `todo_write` 的实际情况(从 app.asar 全文确认):
10
+ * - 工具描述里写了一句 "Mark each todo completed as soon as it is done."
11
+ * - 但这只是**给模型看的描述文字**,零运行时强制
12
+ * - 投影 apply 只认两种事件:`todo/write` 与 `turn/start`
13
+ * - 整个 todo 插件里 `subagent` 出现 **0 次** → 子代理完成不会触发任何自动更新
14
+ *
15
+ * 所以「完成自动写回去」在官方层面**不存在**,只能由主 agent 主动调。
16
+ *
17
+ * ── 本模块的做法 ────────────────────────────────
18
+ *
19
+ * 订阅宿主 `subagent/end`(载荷含 runId / parentSessionId / stopReason /
20
+ * lastAssistantMessage),在子代理**真正结束**时注入一条 snapshot notice,
21
+ * 提醒主 agent:某个子代理完成了,请更新对应 todo 条目。
22
+ *
23
+ * ── 为什么不直接替主 agent 写 todo ────────────────
24
+ *
25
+ * 技术上做不到,也不该做:
26
+ * 1. `todo_write` 的 execute 用的是 `exec.agent.session.append`,
27
+ * 写入的是**调用者自己的 session**。插件没有主 agent 的 exec 上下文。
28
+ * 2. 即便能写,插件也不知道哪个 todo 条目对应哪个子代理
29
+ * (todo 只有 content + status,没有 id/owner 字段)。
30
+ * 3. 用户明确要求「让主 agent 去记录」——主 agent 知道自己在做什么,
31
+ * 插件猜不准。记录事实的权力留给主 agent,插件只负责**提醒**。
32
+ *
33
+ * ── 为什么这样不产生幻觉 ──────────────────────────
34
+ *
35
+ * 提醒文案只陈述**可验证的事实**:子代理名字、stopReason、最后一条回复的摘要。
36
+ * 不替主 agent 判断"这个任务算不算完成",也不编造 todo 内容。
37
+ * 主 agent 拿到事实后自己决定怎么写。
38
+ */
39
+
40
+ import { makeRawSnapshotMessage } from './notice.mjs'
41
+
42
+ /**
43
+ * snapshot 信封的唯一构造点(notice.mjs 的 makeRawSnapshotMessage)。
44
+ *
45
+ * ── FIX6-MSGID:这里曾经手写裸对象,导致真实会话历史加载失败 ──
46
+ *
47
+ * 旧代码(错):
48
+ * additionalContexts: [{
49
+ * content: [{ type: 'text', text }],
50
+ * source: { ...COMPLETION_SOURCE, sections: [text] },
51
+ * }]
52
+ *
53
+ * 缺 id、缺 role。宿主把该对象**原样**当 user/message 的 data 写进日志
54
+ * (dsh-agent-loop:session.append("user/message", context, …)),
55
+ * 官方 assertMessageEventShape 于是拒绝整份会话:
56
+ * stored session failed validation:
57
+ * session event at seq 8738 lacks an identified message
58
+ * (session-05a8cb50 真实事故;role 缺失还会触发 message must have role "user")。
59
+ *
60
+ * 注意:completion 的文案**已自带** <system-reminder> 包裹(buildCompletionReminder
61
+ * 的首尾行就是它),所以这里用 makeRawSnapshotMessage(不二次包裹),
62
+ * 而不是 makeSnapshotMessage(会再包一层,产生嵌套 <system-reminder>)。
63
+ *
64
+ * 为什么不改文案去适配 makeSnapshotMessage:那样要拆掉 buildCompletionReminder
65
+ * 的包裹并改动 39.1「包在 system-reminder 里」等既有契约,风险大于收益。
66
+ */
67
+ const completionContextOf = (text) => makeRawSnapshotMessage(
68
+ [{ type: 'text', text }],
69
+ { form: 'snapshot', sections: [text] },
70
+ )
71
+
72
+ /** 摘要最大长度(码点)。太长会挤占上下文。 */
73
+ const MAX_SUMMARY_CHARS = 160
74
+
75
+ /**
76
+ * W3-F-15:按 Unicode 码点截断(超长补「…」),绝不劈开 UTF-16 代理对。
77
+ * 与 report.mjs / concurrency.mjs / tools.mjs 的 truncateSafe 同语义(各留一份
78
+ * 是既有「零依赖叶子」结构;本模块只加这一份纯函数,不 import 业务模块)。
79
+ * @param {string} value
80
+ * @param {number} max 码点上限
81
+ * @returns {string}
82
+ */
83
+ function truncateByCodePoint(value, max) {
84
+ const chars = Array.from(String(value ?? ''))
85
+ return chars.length > max ? chars.slice(0, max).join('') + '…' : chars.join('')
86
+ }
87
+
88
+ /**
89
+ * 转义 `</system-reminder>`(大小写不敏感、容忍尾随空白)。
90
+ *
91
+ * ── 为什么必须有(F3 / B1-P1-1)─────────────────
92
+ *
93
+ * buildCompletionReminder 的 name / stopReason / summary 全部来自子代理:
94
+ * - name ← subagent/end 的 name 或 id
95
+ * - stopReason ← subagent/end 的 stopReason
96
+ * - summary ← 子代理最后一条回复的原文
97
+ * 若原样拼进 `<system-reminder>`,子代理只要输出 `</system-reminder>`
98
+ * 就能提前闭合提醒块,把后续文本变成主 agent 上下文里的普通用户消息
99
+ * —— 跨信任边界的提示注入。
100
+ *
101
+ * 语义与 notice.mjs 的 escape 实现(escapeSystemReminder,位于文件后段)逐字一致
102
+ * (官方 runtime-context.ts 同款):
103
+ * .replace(/<\/system-reminder\s*>/gi, tag => `<\\${tag.slice(1)}`)
104
+ * 两处实现必须保持一致;test-integration §19 会用 notice 的真实行为对拍。
105
+ *
106
+ * @param {unknown} text
107
+ * @returns {string}
108
+ */
109
+ export function escapeSystemReminder(text) {
110
+ return String(text).replace(/<\/system-reminder\s*>/gi, (tag) => `<\\${tag.slice(1)}`)
111
+ }
112
+
113
+ /**
114
+ * 从子代理最后一条回复里提取一段摘要。
115
+ *
116
+ * 载荷里的 `lastAssistantMessage` 是 content block 数组(可能含 text/image 等),
117
+ * 只取 text block 并拼接。取不到就返回空串(调用方据此降级)。
118
+ *
119
+ * @param {unknown} message - subagent/end 的 lastAssistantMessage
120
+ * @returns {string}
121
+ */
122
+ function summarizeLastMessage(message) {
123
+ if (!Array.isArray(message)) return ''
124
+ const parts = []
125
+ for (const block of message) {
126
+ if (block === null || typeof block !== 'object') continue
127
+ if (block.type !== 'text' || typeof block.text !== 'string') continue
128
+ const text = block.text.trim()
129
+ if (text !== '') parts.push(text)
130
+ }
131
+ const joined = parts.join(' ').replace(/\s+/g, ' ').trim()
132
+ // W3-F-15:按**码点**截断(Array.from),不按 UTF-16 码元 —— 否则 160 边界
133
+ // 遇到 emoji / 星体字符会把代理对劈成孤立字符(项目 F14 同一纪律)。
134
+ return truncateByCodePoint(joined, MAX_SUMMARY_CHARS)
135
+ }
136
+
137
+ /**
138
+ * 构造提醒文案。
139
+ *
140
+ * 只陈述事实,不替主 agent 下判断。三种情况分开写:
141
+ * 1. 正常完成(stopReason === 'completed')→ 提示更新为 completed
142
+ * 2. 非正常结束(error / aborted 等)→ 提示如实记录,不要谎报完成
143
+ * 3. 拿不到 stopReason → 只报"已结束",不猜
144
+ *
145
+ * @param {{ name?: string, stopReason?: string, summary?: string }} facts
146
+ * @returns {string}
147
+ */
148
+ export function buildCompletionReminder(facts) {
149
+ // raw* 用于逻辑判断;展示值统一走 escapeSystemReminder —— 判断不能看转义后的字符串。
150
+ const rawName = typeof facts?.name === 'string' && facts.name !== '' ? facts.name : '(未命名)'
151
+ const rawStopReason = typeof facts?.stopReason === 'string' ? facts.stopReason : ''
152
+ // 截断放在这里而不是只放在 summarizeLastMessage:
153
+ // 调用方可能直接传 summary(测试、未来别的入口),不能指望上游一定截过。
154
+ const rawSummary = typeof facts?.summary === 'string' ? facts.summary : ''
155
+ const truncatedSummary = truncateByCodePoint(rawSummary, MAX_SUMMARY_CHARS)
156
+
157
+ // 所有来自子代理的字符串(name / stopReason / summary)都必须转义后才能拼接。
158
+ const name = escapeSystemReminder(rawName)
159
+ const stopReason = escapeSystemReminder(rawStopReason)
160
+ const summary = escapeSystemReminder(truncatedSummary)
161
+
162
+ const lines = ['<system-reminder>']
163
+ lines.push('子代理「' + name + '」已结束' + (stopReason === '' ? '。' : '(stopReason: ' + stopReason + ')。'))
164
+ if (summary !== '') lines.push('它的最后一条回复:' + summary)
165
+
166
+ if (rawStopReason === 'completed') {
167
+ lines.push('如果它负责的子任务已经完成,请立刻调用 todo_write 把对应条目改为 completed。')
168
+ lines.push('注意:todo_write 是整体替换(每次传完整列表),不是追加日志。')
169
+ lines.push('若它的产出还需要你复核才能算完成,就先把该条改为 in_progress 并说明在等什么。')
170
+ } else if (stopReason !== '') {
171
+ lines.push('它**没有正常完成**(' + stopReason + ')。请如实记录该条目的状态,'
172
+ + '不要为了"看起来完成"而改成 completed;需要时改为 pending 并注明失败原因。')
173
+ } else {
174
+ lines.push('无法确定它的结束原因。请根据实际产出判断该条目状态,不要臆断。')
175
+ }
176
+ lines.push('</system-reminder>')
177
+ return lines.join('\n')
178
+ }
179
+
180
+ /**
181
+ * 安装「完成即记录」提醒。
182
+ *
183
+ * @param ctx cordis context
184
+ * @param {{ enabled?: boolean }} [options]
185
+ * @returns {() => void} 卸载函数(调用方必须接线到 ctx.effect)
186
+ */
187
+ export function installCompletionReminder(ctx, options = {}) {
188
+ const enabled = options?.enabled !== false
189
+
190
+ /** 每个 session 待提醒的完成事件:Map<sessionKey, Array<facts>>。 */
191
+ let pending = new Map()
192
+
193
+ // ── 监听器统一登记(P2-2 / L1-B)──
194
+ //
195
+ // 早先直接 ctx.on 并丢弃返回值,卸载函数只做 pending = new Map():
196
+ // - 卸载后「记录」与「注入」两个监听器仍挂在事件上(探针实证:
197
+ // dispose 后 completion 仍会注入);
198
+ // - 与同目录 todo-gate.mjs / stuck.mjs 的既有约定不一致
199
+ // (它们都收集 off 并在卸载时逐个调用)。
200
+ // 现在照 todo-gate 的 listen 写法统一登记,卸载时逐个摘除。
201
+ // try/catch 兜住:ctx 已销毁时 off 本身可能抛,且不能因此中断其余清理。
202
+ const disposers = []
203
+ const listen = (event, listener) => {
204
+ const off = ctx.on(event, listener)
205
+ if (typeof off === 'function') disposers.push(off)
206
+ }
207
+
208
+ const keyOf = (parentSessionId) => (typeof parentSessionId === 'string' && parentSessionId !== '' ? parentSessionId : undefined)
209
+
210
+ listen('subagent/end', (info) => {
211
+ if (!enabled) return
212
+ try {
213
+ const key = keyOf(info?.parentSessionId)
214
+ if (key === undefined) return
215
+ const facts = {
216
+ name: typeof info?.name === 'string' ? info.name : (typeof info?.id === 'string' ? info.id : ''),
217
+ stopReason: typeof info?.stopReason === 'string' ? info.stopReason : '',
218
+ summary: summarizeLastMessage(info?.lastAssistantMessage),
219
+ }
220
+ const list = pending.get(key) ?? []
221
+ list.push(facts)
222
+ pending.set(key, list)
223
+ } catch { /* 记账失败不影响主流程 */ }
224
+ })
225
+
226
+ // 在委派工具的 post-execute 里把待提醒的完成事件注入给主 agent。
227
+ //
228
+ // 为什么挂在 post-execute 而不是直接在有 end 事件时注入:
229
+ // tools/post-execute 是唯一能返回 additionalContexts 的钩子。
230
+ // subagent/end 只是生命周期事件,没有注入通道。
231
+ listen('tools/post-execute', async (exec, result, next) => {
232
+ const downstream = await next()
233
+ if (!enabled) return downstream
234
+
235
+ try {
236
+ const agent = exec?.agent
237
+ const key = keyOf(agent?.session?.id ?? agent?.session?.sessionId)
238
+ if (key === undefined) return downstream
239
+
240
+ const list = pending.get(key)
241
+ if (list === undefined || list.length === 0) return downstream
242
+ pending.delete(key)
243
+
244
+ const text = list.length === 1
245
+ ? buildCompletionReminder(list[0])
246
+ : [
247
+ '<system-reminder>',
248
+ '以下 ' + list.length + ' 个子代理已结束:',
249
+ // 多路合并文案同样来自子代理输出:name / stopReason / summary 全部转义。
250
+ ...list.map((facts, index) => (index + 1) + '. 「'
251
+ + escapeSystemReminder(typeof facts.name === 'string' && facts.name !== '' ? facts.name : '未命名') + '」'
252
+ + (facts.stopReason === '' ? '' : '(' + escapeSystemReminder(facts.stopReason) + ')')
253
+ + (facts.summary === '' ? '' : ':' + escapeSystemReminder(facts.summary))),
254
+ '',
255
+ '请立刻调用 todo_write,按实际产出更新这些子任务对应的条目状态。',
256
+ '注意:todo_write 是整体替换(每次传完整列表),不是追加日志。',
257
+ '没有正常完成的不要谎报为 completed。',
258
+ '</system-reminder>',
259
+ ].join('\n')
260
+
261
+ return {
262
+ ...downstream,
263
+ additionalContexts: [
264
+ // 完整 user 消息(id / role / source.kind 齐备)—— 裸对象会让宿主
265
+ // 写出非法 user/message,整份会话历史从此加载失败(FIX6-MSGID)。
266
+ completionContextOf(text),
267
+ ...(downstream.additionalContexts ?? []),
268
+ ],
269
+ }
270
+ } catch (error) {
271
+ try {
272
+ ctx.logger?.warn?.('[team-preflight] completion reminder failed:', error?.message ?? error)
273
+ } catch { /* ignore */ }
274
+ return downstream
275
+ }
276
+ })
277
+
278
+ // ── 卸载清理(P2-2):摘监听器 + 清待发队列 ──
279
+ //
280
+ // 顺序:先摘监听器(不再产生新账),再清队列(丢掉已记但未发的账)。
281
+ // 与同目录 todo-gate.mjs 的卸载(disposers.splice 逐个 off)同一写法。
282
+ return () => {
283
+ for (const off of disposers.splice(0)) {
284
+ try { off() } catch { /* 监听器已随 ctx 销毁时忽略 */ }
285
+ }
286
+ pending = new Map()
287
+ }
288
+ }