dsh-chief 1.2.1 → 1.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.
@@ -0,0 +1,869 @@
1
+ /**
2
+ * chief-network.js
3
+ *
4
+ * Cross-session messaging, subagent relay, peer directory, and pre-step delta delivery for DSH Chief.
5
+ */
6
+
7
+ import path from 'node:path'
8
+ import {
9
+ MAIL_CAP,
10
+ CHIEF_UPDATE_SOURCE,
11
+ CHIEF_RELAY_SOURCE,
12
+ CHIEF_INQUIRY_SOURCE,
13
+ CHIEF_EXEC_REQ_SOURCE,
14
+ persistChiefImagesToWorkspace,
15
+ admitChiefImages,
16
+ nextId,
17
+ clamp,
18
+ cleanMultiline,
19
+ normalizeMail,
20
+ loadChiefState,
21
+ mutateChiefState,
22
+ answerChiefInquiry,
23
+ getLinkedCluster,
24
+ ensureWorkspace,
25
+ clusterView,
26
+ stripCheckpointNoise,
27
+ isInternalCheckpointNoise,
28
+ } from './chief-state.js'
29
+ import { loadDshLlm } from './chief-models.js'
30
+
31
+ let chiefDirectRequestHook = null
32
+
33
+ export function registerChiefDirectRequestHook(fn) {
34
+ chiefDirectRequestHook = typeof fn === 'function' ? fn : null
35
+ }
36
+
37
+ export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE, extraSource = {}, imageBlocks = []) {
38
+ const dshLlm = await loadDshLlm()
39
+ const safeImages = Array.isArray(imageBlocks) ? imageBlocks : []
40
+ const content = [...safeImages, ...(text ? [{ type: 'text', text }] : [])]
41
+ if (!content.length) content.push({ type: 'text', text: '' })
42
+ const source = { kind: sourceKind, ...extraSource }
43
+ if (dshLlm && typeof dshLlm.createUserMessage === 'function') {
44
+ try {
45
+ return dshLlm.createUserMessage({ content, source })
46
+ } catch {}
47
+ }
48
+ return {
49
+ id: nextId('secmsg'),
50
+ role: 'user',
51
+ content,
52
+ source,
53
+ }
54
+ }
55
+
56
+ function summarizeBoardProgress(board) {
57
+ const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
58
+ const doneCount = tasks.filter(t => t && t.status === 'done').length
59
+ const doingCount = tasks.filter(t => t && t.status === 'doing').length
60
+ const blockedCount = tasks.filter(t => t && t.status === 'blocked').length
61
+ const todoCount = tasks.filter(t => t && t.status === 'todo').length
62
+ const plan = Array.isArray(board && board.plan) ? board.plan : []
63
+ const planDone = plan.filter(s => s && s.done).length
64
+ const cursorStep = clamp(board && board.cursor && board.cursor.step ? board.cursor.step : '', 48)
65
+ const parts = []
66
+ if (tasks.length > 0) parts.push(`任务 ${doneCount}完/${doingCount}做${blockedCount ? `/${blockedCount}阻` : ''}/${tasks.length}`)
67
+ else if (plan.length > 0) parts.push(`步骤 ${planDone}/${plan.length}`)
68
+ if (cursorStep) parts.push(`断点:${cursorStep}`)
69
+ return parts.join(' · ')
70
+ }
71
+
72
+ export function collectClusterPeerProgress(deps, cluster = [], selfRootId = '') {
73
+ const self = String(selfRootId || '').trim()
74
+ const members = Array.isArray(cluster) ? cluster.filter(sid => sid && sid !== self) : []
75
+ if (!members.length) return []
76
+ const runtime = deps && deps.runtime
77
+ const agentsSvc = runtime ? runtime.get('agents') : null
78
+ const out = []
79
+ for (const sid of members) {
80
+ let board = null
81
+ try {
82
+ board = deps.boardForSession ? deps.boardForSession(deps.boardFileFor(sid)) : null
83
+ } catch {}
84
+ if (!board) continue
85
+ let rootAgent = null
86
+ try {
87
+ rootAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(sid) : null
88
+ } catch {}
89
+ const name = (deps.sessionName && deps.sessionName(runtime, rootAgent || sid)) || ('会话 ' + sid.replace(/^session-/, '').slice(0, 8))
90
+ const tasks = Array.isArray(board.tasks) ? board.tasks : []
91
+ const doneCount = tasks.filter(t => t && t.status === 'done').length
92
+ const doingCount = tasks.filter(t => t && t.status === 'doing').length
93
+ const blockedCount = tasks.filter(t => t && t.status === 'blocked').length
94
+ const todoCount = tasks.filter(t => t && t.status === 'todo').length
95
+ const topTasks = tasks
96
+ .filter(t => t && t.status !== 'done')
97
+ .slice(0, 3)
98
+ .map(t => `[${t.status}] #${t.id} ${clamp(t.title, 44)}`)
99
+ const recentConclusions = (Array.isArray(board.memory) ? board.memory : [])
100
+ .filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
101
+ .slice(-2)
102
+ .map(m => clamp(stripCheckpointNoise(m.title || m.text), 72))
103
+ .filter(Boolean)
104
+ out.push({
105
+ rootId: sid,
106
+ name,
107
+ status: rootAgent && rootAgent.status === 'running' ? 'running' : 'idle',
108
+ objective: clamp(board.objective || '', 120),
109
+ cursorStep: clamp(board.cursor && board.cursor.step ? board.cursor.step : '', 90),
110
+ cursorNext: clamp(board.cursor && board.cursor.next ? board.cursor.next : '', 90),
111
+ cursorBlocked: clamp(board.cursor && board.cursor.blocked ? board.cursor.blocked : '', 90),
112
+ doingCount,
113
+ doneCount,
114
+ blockedCount,
115
+ todoCount,
116
+ topTasks,
117
+ recentConclusions,
118
+ progressSummary: summarizeBoardProgress(board),
119
+ })
120
+ }
121
+ return out
122
+ }
123
+
124
+ /** Build complete addressable peer directory across lead, subagents, and federated root sessions. */
125
+ export async function listPeerDirectory(deps, sessionId) {
126
+ const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || '')
127
+ const state = loadChiefState()
128
+ const cluster = getLinkedCluster(state, rootId)
129
+ const runtime = deps.runtime
130
+ const agentsSvc = runtime ? runtime.get('agents') : null
131
+ const liveAgents = agentsSvc && typeof agentsSvc.list === 'function' ? agentsSvc.list() : []
132
+ const archived = (() => {
133
+ try {
134
+ const list = runtime && runtime.get('workspaceRegistry')?.archivedSessionIds
135
+ return Array.isArray(list) ? new Set(list) : new Set()
136
+ } catch {
137
+ return new Set()
138
+ }
139
+ })()
140
+
141
+ const targets = []
142
+ const seenIds = new Set()
143
+
144
+ for (const memberRootId of cluster) {
145
+ const isCurrentRoot = memberRootId === rootId
146
+ const board = deps.boardForSession(deps.boardFileFor(memberRootId))
147
+ const roster = await deps.refreshSubagentTree(runtime, memberRootId, board)
148
+ const rootAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(memberRootId) : null
149
+ const rootTitle = deps.sessionName(runtime, rootAgent || memberRootId) || ('会话 ' + memberRootId.replace(/^session-/, '').slice(0, 8))
150
+ const memberProgressSummary = summarizeBoardProgress(board)
151
+
152
+ for (const entry of roster) {
153
+ if (!entry) continue
154
+ const isLead = entry.name === 'lead'
155
+ const key = isCurrentRoot
156
+ ? (isLead ? 'lead' : entry.name)
157
+ : (isLead ? memberRootId : `${memberRootId}:${entry.name}`)
158
+ if (seenIds.has(key)) continue
159
+ seenIds.add(key)
160
+ targets.push({
161
+ key,
162
+ id: entry.id || (isLead ? memberRootId : ''),
163
+ rootId: memberRootId,
164
+ name: isLead ? (isCurrentRoot ? '主对话' : rootTitle) : entry.name,
165
+ handle: isCurrentRoot ? (isLead ? 'lead' : entry.name) : (isLead ? rootTitle : `${rootTitle}/${entry.name}`),
166
+ kind: isLead ? (isCurrentRoot ? 'lead' : 'peer-session') : 'subagent',
167
+ isCurrentRoot,
168
+ status: entry.status === 'running' ? 'running' : 'idle',
169
+ taskTitle: entry.taskTitle || entry.description || (board && board.objective ? clamp(board.objective, 48) : ''),
170
+ ...(isLead ? { progressSummary: memberProgressSummary, objective: clamp(board && board.objective ? board.objective : '', 80) } : {}),
171
+ parentId: entry.parentId || memberRootId,
172
+ mode: entry.mode || 'continuable',
173
+ })
174
+ }
175
+ }
176
+
177
+ // Other top-level standalone sessions on this machine that can be linked into the federation
178
+ const otherSessions = []
179
+ for (const ag of liveAgents) {
180
+ const sid = String(ag && ag.id ? ag.id : '')
181
+ if (!sid || archived.has(sid)) continue
182
+ const agRoot = deps.resolveRootSessionId(sid, ag) || sid
183
+ if (agRoot !== sid) continue // skip child subagent sessions here
184
+ if (agRoot === rootId) continue
185
+ const isLinked = cluster.includes(agRoot)
186
+ const b = deps.loadBoard(deps.boardFileFor(agRoot))
187
+ otherSessions.push({
188
+ id: agRoot,
189
+ name: deps.sessionName(runtime, ag) || ('会话 ' + agRoot.replace(/^session-/, '').slice(0, 8)),
190
+ status: ag.status === 'running' ? 'running' : 'idle',
191
+ linked: isLinked,
192
+ objective: clamp(b && b.objective ? b.objective : '', 80),
193
+ openTasks: Array.isArray(b && b.tasks) ? b.tasks.filter(t => t.status !== 'done').length : 0,
194
+ progressSummary: summarizeBoardProgress(b),
195
+ })
196
+ }
197
+
198
+ return {
199
+ rootId,
200
+ cluster,
201
+ targets,
202
+ otherSessions,
203
+ }
204
+ }
205
+
206
+ function matchTargetPeer(targets, rawTarget) {
207
+ const q = String(rawTarget || '').trim().replace(/^@/, '')
208
+ if (!q) return null
209
+ const lower = q.toLowerCase()
210
+ if (lower === 'lead' || lower === 'main' || lower === '主对话' || lower === '主代理') {
211
+ return targets.find(t => t.kind === 'lead' && t.isCurrentRoot) || targets[0] || null
212
+ }
213
+ // Exact match by key, id, name, or handle
214
+ for (const t of targets) {
215
+ if (
216
+ t.key.toLowerCase() === lower
217
+ || (t.id && t.id.toLowerCase() === lower)
218
+ || t.name.toLowerCase() === lower
219
+ || t.handle.toLowerCase() === lower
220
+ || t.name.split('/').pop().toLowerCase() === lower
221
+ ) {
222
+ return t
223
+ }
224
+ }
225
+ // Partial substring match
226
+ return targets.find(t =>
227
+ t.name.toLowerCase().includes(lower) || t.handle.toLowerCase().includes(lower),
228
+ ) || null
229
+ }
230
+
231
+ /**
232
+ * Deliver a message across conversations (lead <-> subagent, subagent <-> subagent, session <-> session).
233
+ * Modes:
234
+ * - 'steer': cut into next step boundary immediately if running, or wake if idle.
235
+ * - 'followup': queue for next turn / wake idle session without cutting running step.
236
+ * - 'silent': record in chief mailbox so the recipient sees it cleanly at its next pre-step without waking an idle session.
237
+ */
238
+ function buildSavedImageNotice(savedImagePaths) {
239
+ const list = Array.isArray(savedImagePaths) ? savedImagePaths.filter(item => item && item.path) : []
240
+ if (!list.length) return ''
241
+ return [
242
+ '',
243
+ '🖼️ [用户原图已落盘至工作区路径]:',
244
+ ...list.map(item => `- ${item.path}${item.name ? ` (${item.name})` : ''}`),
245
+ '⚠️ 请直接查阅附带图片或使用读图/文件工具读取上述原始路径后再动手,严禁只凭参谋长转述文本猜测或编造未确认的图内信息!',
246
+ ].join('\n')
247
+ }
248
+
249
+ export async function deliverCrossMessage(deps, {
250
+ fromSession = '',
251
+ fromLabel = 'DSH 参谋长',
252
+ target = 'lead',
253
+ text = '',
254
+ subject = '',
255
+ mode = 'steer',
256
+ envelopeKind = 'relay',
257
+ taskId = '',
258
+ inquiryId = '',
259
+ images = [],
260
+ imageBlocks: preAdmittedBlocks = null,
261
+ savedImagePaths: preSavedPaths = null,
262
+ recordBoardLog = true,
263
+ }) {
264
+ const cleanBody = cleanMultiline(text, 2400)
265
+ const rawImages = Array.isArray(images) ? images : []
266
+ const hasPreAdmitted = Array.isArray(preAdmittedBlocks) && preAdmittedBlocks.length > 0
267
+ let savedPaths = Array.isArray(preSavedPaths) ? preSavedPaths : []
268
+ if (!savedPaths.length && rawImages.length > 0) {
269
+ try {
270
+ savedPaths = persistChiefImagesToWorkspace(deps, fromSession, rawImages)
271
+ } catch {}
272
+ }
273
+
274
+ if (!cleanBody && !rawImages.length && !hasPreAdmitted && !savedPaths.length) {
275
+ return { ok: false, error: '递话内容不能为空' }
276
+ }
277
+
278
+ let admittedBlocks = hasPreAdmitted ? preAdmittedBlocks : []
279
+ if (!hasPreAdmitted && rawImages.length > 0) {
280
+ try {
281
+ admittedBlocks = await admitChiefImages(deps, rawImages)
282
+ } catch (err) {
283
+ if (!savedPaths.length) {
284
+ return { ok: false, error: String(err && err.message ? err.message : err) }
285
+ }
286
+ // Degrade cleanly to path-based image delivery if host attachments service is unavailable
287
+ admittedBlocks = []
288
+ }
289
+ }
290
+ const effectiveText = cleanBody || (admittedBlocks.length || savedPaths.length ? '请查看随信附带的图片与落盘路径。' : '')
291
+ const totalImgCount = Math.max(admittedBlocks.length, savedPaths.length)
292
+ const imgTag = totalImgCount > 0 ? ` [附图 ×${totalImgCount}]` : ''
293
+
294
+ const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(fromSession)) || String(fromSession || directoryRootFallback(fromSession))
295
+ const rawTargetPre = String(target || 'lead').trim().replace(/^@/, '')
296
+ if (/^(?:chief|dsh-chief|参谋长|参谋)$/i.test(rawTargetPre)) {
297
+ const cleanChiefBody = cleanMultiline(text, 2400)
298
+ if (envelopeKind === 'inquiry_reply') {
299
+ if (!cleanChiefBody) return { ok: false, error: 'inquiry.reply 必须提供非空答复文本 (text)' }
300
+ const effInqId = String(inquiryId || taskId || '').trim()
301
+ const ansRes = answerChiefInquiry(rootId || 'global', {
302
+ inquiryId: effInqId,
303
+ answer: cleanChiefBody,
304
+ by: fromLabel,
305
+ })
306
+ if (recordBoardLog && rootId && typeof deps.appendBoardLog === 'function' && ansRes && ansRes.ok && ansRes.inquiry) {
307
+ deps.appendBoardLog(rootId, `⚡ ${fromLabel} 已原路回传问询 #${ansRes.inquiry.inquiryId}`, fromLabel)
308
+ }
309
+ return {
310
+ ok: Boolean(ansRes && ansRes.ok),
311
+ target: 'DSH 参谋长',
312
+ targetId: 'chief',
313
+ deliveryMode: 'inquiry-reply',
314
+ inquiryAnswered: ansRes && ansRes.inquiry ? ansRes.inquiry : null,
315
+ continueOwnWork: true,
316
+ ...(ansRes && !ansRes.ok ? { error: ansRes.error } : {}),
317
+ }
318
+ }
319
+ if (!cleanChiefBody) return { ok: false, error: '传话给参谋长的内容不能为空' }
320
+ const chiefMail = normalizeMail({
321
+ id: nextId('mail'),
322
+ from: fromLabel,
323
+ fromSession,
324
+ fromRootId: rootId,
325
+ to: 'chief',
326
+ toSession: 'chief',
327
+ toRootId: rootId,
328
+ participantRoots: rootId ? [rootId] : [],
329
+ channelType: 'internal',
330
+ subject: subject || '主对话求助与协同请求',
331
+ text: cleanChiefBody,
332
+ mode: mode || 'followup',
333
+ deliveredPhysical: true,
334
+ readBy: ['chief'],
335
+ at: Date.now(),
336
+ })
337
+ mutateChiefState((state) => {
338
+ const ws = ensureWorkspace(state, rootId || 'global')
339
+ if (chiefMail) {
340
+ ws.mailbox.push(chiefMail)
341
+ if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
342
+ }
343
+ })
344
+ if (recordBoardLog && rootId && typeof deps.appendBoardLog === 'function') {
345
+ deps.appendBoardLog(rootId, `📨 ${fromLabel} → @参谋长:${clamp(cleanChiefBody, 56)}`, fromLabel)
346
+ }
347
+ if (chiefDirectRequestHook) {
348
+ try {
349
+ const hookRes = await chiefDirectRequestHook(deps, {
350
+ fromSession: rootId || fromSession,
351
+ fromLabel,
352
+ subject,
353
+ text: cleanChiefBody,
354
+ mail: chiefMail,
355
+ })
356
+ if (hookRes && typeof hookRes === 'object') {
357
+ return {
358
+ ok: hookRes.ok !== false,
359
+ target: 'DSH 参谋长',
360
+ targetId: 'chief',
361
+ deliveryMode: 'chief-direct-request',
362
+ deliveredPhysical: true,
363
+ mail: chiefMail,
364
+ ...hookRes,
365
+ }
366
+ }
367
+ } catch (err) {
368
+ return {
369
+ ok: false,
370
+ target: 'DSH 参谋长',
371
+ mail: chiefMail,
372
+ error: String(err && err.message ? err.message : err),
373
+ }
374
+ }
375
+ }
376
+ return {
377
+ ok: true,
378
+ target: 'DSH 参谋长',
379
+ targetId: 'chief',
380
+ deliveryMode: 'chief-mailbox',
381
+ deliveredPhysical: true,
382
+ mail: chiefMail,
383
+ }
384
+ }
385
+
386
+ const directory = await listPeerDirectory(deps, rootId || fromSession)
387
+ const senderRootId = rootId || directory.rootId || ''
388
+ const rawTarget = rawTargetPre
389
+
390
+ // Broadcast support: 'all' / '全体' / 'team' (deduplicated single mailbox record for clean drawer UI)
391
+ if (['all', 'team', '全体', '所有人'].includes(rawTarget.toLowerCase())) {
392
+ const recipients = directory.targets.filter(t => t.id !== fromSession)
393
+ const deliveries = []
394
+ const deliveredReadMarks = []
395
+ for (const peer of recipients) {
396
+ const res = await deliverSinglePeer(deps, directory, peer, {
397
+ fromSession,
398
+ fromRootId: senderRootId,
399
+ fromLabel,
400
+ text: effectiveText,
401
+ subject,
402
+ mode,
403
+ imageBlocks: admittedBlocks,
404
+ savedImagePaths: savedPaths,
405
+ recordBoardLog: false,
406
+ recordMailbox: false,
407
+ })
408
+ deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
409
+ if (res.deliveredPhysical) {
410
+ if (peer.id) deliveredReadMarks.push(peer.id)
411
+ if (peer.key) deliveredReadMarks.push(peer.key)
412
+ if (peer.name) deliveredReadMarks.push(peer.name)
413
+ }
414
+ }
415
+ const participantRoots = [...new Set([senderRootId, ...(directory.cluster || [])].filter(Boolean))].sort()
416
+ const imgNoticeBlock = buildSavedImageNotice(savedPaths)
417
+ const textWithImagePaths = imgNoticeBlock ? `${effectiveText}\n${imgNoticeBlock}` : effectiveText
418
+ const broadcastId = nextId('bcast')
419
+ const mailItem = normalizeMail({
420
+ id: nextId('mail'),
421
+ from: fromLabel,
422
+ fromSession,
423
+ fromRootId: senderRootId,
424
+ to: 'all',
425
+ toSession: 'all',
426
+ toRootId: 'all',
427
+ participantRoots,
428
+ channelType: participantRoots.length > 1 ? 'broadcast' : 'internal',
429
+ broadcastId,
430
+ subject,
431
+ text: totalImgCount > 0 ? `${textWithImagePaths}${imgTag}` : textWithImagePaths,
432
+ imageCount: totalImgCount,
433
+ mode,
434
+ deliveredPhysical: deliveries.some(d => d.ok && d.mode !== 'mailbox-queued'),
435
+ readBy: [...new Set(deliveredReadMarks)],
436
+ at: Date.now(),
437
+ })
438
+ if (mailItem) {
439
+ mutateChiefState((state) => {
440
+ const ws = ensureWorkspace(state, senderRootId || directory.rootId)
441
+ ws.mailbox.push(mailItem)
442
+ if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
443
+ })
444
+ }
445
+ if (recordBoardLog && rootId) {
446
+ deps.appendBoardLog(rootId, `📡 ${fromLabel} 向全体成员广播递话(${deliveries.filter(d => d.ok).length} 个目标):${clamp(effectiveText, 56)}${imgTag}`, fromLabel)
447
+ }
448
+ return { ok: true, broadcast: true, target: 'all', mail: mailItem, deliveries, savedImagePaths: savedPaths }
449
+ }
450
+
451
+ // Multi-target comma-separated support (e.g. "sessionA,sessionB" or "worker1,worker2")
452
+ if (/[,,]/.test(rawTarget)) {
453
+ const parts = rawTarget.split(/[,,]/).map(s => s.trim().replace(/^@/, '')).filter(Boolean)
454
+ const matched = []
455
+ const seenKeys = new Set()
456
+ for (const part of parts) {
457
+ const hit = matchTargetPeer(directory.targets, part)
458
+ if (hit && !seenKeys.has(hit.key)) {
459
+ seenKeys.add(hit.key)
460
+ matched.push(hit)
461
+ }
462
+ }
463
+ if (matched.length >= 2) {
464
+ const deliveries = []
465
+ const readMarks = []
466
+ const roots = new Set([senderRootId].filter(Boolean))
467
+ for (const peer of matched) {
468
+ if (peer.rootId) roots.add(peer.rootId)
469
+ const res = await deliverSinglePeer(deps, directory, peer, {
470
+ fromSession,
471
+ fromRootId: senderRootId,
472
+ fromLabel,
473
+ text: effectiveText,
474
+ subject,
475
+ mode,
476
+ imageBlocks: admittedBlocks,
477
+ savedImagePaths: savedPaths,
478
+ recordBoardLog: false,
479
+ recordMailbox: false,
480
+ })
481
+ deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
482
+ if (res.deliveredPhysical) {
483
+ if (peer.id) readMarks.push(peer.id)
484
+ if (peer.key) readMarks.push(peer.key)
485
+ if (peer.name) readMarks.push(peer.name)
486
+ }
487
+ }
488
+ const participantRoots = [...roots].sort()
489
+ const imgNoticeBlock = buildSavedImageNotice(savedPaths)
490
+ const textWithImagePaths = imgNoticeBlock ? `${effectiveText}\n${imgNoticeBlock}` : effectiveText
491
+ const mailItem = normalizeMail({
492
+ id: nextId('mail'),
493
+ from: fromLabel,
494
+ fromSession,
495
+ fromRootId: senderRootId,
496
+ to: matched.map(m => m.handle).join('、'),
497
+ toSession: matched.map(m => m.id || m.key).join(','),
498
+ toRootId: participantRoots.length > 1 ? 'multi' : (participantRoots[0] || ''),
499
+ participantRoots,
500
+ channelType: participantRoots.length >= 3 ? 'multi' : (participantRoots.length === 2 ? 'pair' : 'internal'),
501
+ broadcastId: nextId('multi'),
502
+ subject,
503
+ text: totalImgCount > 0 ? `${textWithImagePaths}${imgTag}` : textWithImagePaths,
504
+ imageCount: totalImgCount,
505
+ mode,
506
+ deliveredPhysical: deliveries.some(d => d.ok && d.mode !== 'mailbox-queued'),
507
+ readBy: [...new Set(readMarks)],
508
+ at: Date.now(),
509
+ })
510
+ if (mailItem) {
511
+ mutateChiefState((state) => {
512
+ const ws = ensureWorkspace(state, senderRootId || directory.rootId)
513
+ ws.mailbox.push(mailItem)
514
+ if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
515
+ })
516
+ }
517
+ return { ok: true, multi: true, target: matched.map(m => m.handle).join('、'), mail: mailItem, deliveries, savedImagePaths: savedPaths }
518
+ }
519
+ }
520
+
521
+ const peer = matchTargetPeer(directory.targets, rawTarget)
522
+ if (!peer) {
523
+ return {
524
+ ok: false,
525
+ error: `未找到目标对话 "${rawTarget}"。当前可用目标:${directory.targets.map(t => t.handle).join('、') || '无'}`,
526
+ }
527
+ }
528
+
529
+ return deliverSinglePeer(deps, directory, peer, {
530
+ fromSession,
531
+ fromRootId: senderRootId,
532
+ fromLabel,
533
+ text: effectiveText,
534
+ subject,
535
+ mode,
536
+ envelopeKind,
537
+ taskId,
538
+ imageBlocks: admittedBlocks,
539
+ savedImagePaths: savedPaths,
540
+ recordBoardLog,
541
+ recordMailbox: true,
542
+ })
543
+ }
544
+
545
+ function directoryRootFallback(fromSession) {
546
+ return String(fromSession || 'global')
547
+ }
548
+
549
+ async function deliverSinglePeer(deps, directory, peer, {
550
+ fromSession,
551
+ fromRootId = '',
552
+ fromLabel,
553
+ text,
554
+ subject,
555
+ mode,
556
+ envelopeKind = 'relay',
557
+ taskId = '',
558
+ imageBlocks = [],
559
+ savedImagePaths = [],
560
+ recordBoardLog,
561
+ recordMailbox = true,
562
+ }) {
563
+ const runtime = deps.runtime
564
+ const agentsSvc = runtime ? runtime.get('agents') : null
565
+ const subagentsSvc = runtime ? runtime.get('subagents') : null
566
+ const safeBlocks = Array.isArray(imageBlocks) ? imageBlocks : []
567
+ const safePaths = Array.isArray(savedImagePaths) ? savedImagePaths : []
568
+ const imgCount = Math.max(safeBlocks.length, safePaths.length)
569
+ const imgSuffix = imgCount > 0 ? ` [附图 ×${imgCount}]` : ''
570
+ const imgNoticeBlock = buildSavedImageNotice(safePaths)
571
+ const textWithImagePaths = imgNoticeBlock ? `${text}\n${imgNoticeBlock}` : text
572
+ const headerTag = envelopeKind === 'execution_request'
573
+ ? `[EXECUTION_REQUEST${taskId ? ' #' + taskId : ''} · 来自 ${fromLabel}]`
574
+ : (envelopeKind === 'inquiry'
575
+ ? `[INQUIRY${taskId ? ' #' + taskId : ''} · DSH 参谋长优先问询]`
576
+ : (mode === 'steer'
577
+ ? `[DSH 参谋长插话 · 来自 ${fromLabel}]`
578
+ : `[DSH 参谋长递话 · 来自 ${fromLabel}]`))
579
+ const footerGuide = envelopeKind === 'inquiry'
580
+ ? '(请顺手调用 chief_board({ action: "inquiry.reply", text: "…" }) 原路作答,无需中断手头当前任务!)'
581
+ : `(如遇到需要参谋长协调、建议、或提权执行的需求,可调用 chief_board({ action: "chief.request", text: "…" }) 或 mail.send({ target: "chief", text: "…" }))`
582
+ const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${textWithImagePaths}\n\n${footerGuide}`
583
+
584
+ let deliveredPhysical = false
585
+ let deliveryMode = 'mailbox-queued'
586
+ let errorNote = ''
587
+
588
+ if (mode !== 'silent') {
589
+ // Path A: Subagent delivery via DSH native subagents service
590
+ if (peer.kind === 'subagent' && subagentsSvc) {
591
+ const caller = (agentsSvc && peer.rootId && agentsSvc.get(peer.rootId)) || deps.findLiveCallerAgent(runtime, peer.rootId, null)
592
+ if (caller) {
593
+ try {
594
+ let targetChildId = peer.id
595
+ if (!targetChildId && typeof subagentsSvc.resolveName === 'function') {
596
+ targetChildId = await subagentsSvc.resolveName(caller, peer.name, AbortSignal.timeout(5000))
597
+ }
598
+ if (targetChildId) {
599
+ await subagentsSvc.sendMessage(caller, targetChildId, [...safeBlocks, { type: 'text', text: formatted }], {
600
+ signal: AbortSignal.timeout(10_000),
601
+ })
602
+ deliveredPhysical = true
603
+ deliveryMode = 'subagent-send'
604
+ }
605
+ } catch (err) {
606
+ errorNote = String(err && err.message ? err.message : err)
607
+ }
608
+ }
609
+ }
610
+
611
+ // Path B: Direct Agent handle delivery (for root lead, peer standalone sessions, or fallback live child agent)
612
+ if (!deliveredPhysical && agentsSvc && peer.id) {
613
+ let targetAgent = typeof agentsSvc.get === 'function' ? agentsSvc.get(peer.id) : null
614
+ if (!targetAgent && runtime) {
615
+ try {
616
+ const controller = runtime.get('sessionController')
617
+ if (controller && typeof controller.resolveAgent === 'function') {
618
+ const resolved = await controller.resolveAgent(peer.id)
619
+ if (resolved && resolved.agent) targetAgent = resolved.agent
620
+ }
621
+ } catch {}
622
+ }
623
+ if (targetAgent) {
624
+ const envelopeSourceKind = envelopeKind === 'execution_request'
625
+ ? CHIEF_EXEC_REQ_SOURCE
626
+ : (envelopeKind === 'inquiry' ? CHIEF_INQUIRY_SOURCE : CHIEF_RELAY_SOURCE)
627
+ const envelope = await buildMessageEnvelope(formatted, envelopeSourceKind, {
628
+ senderName: fromLabel,
629
+ senderSessionId: fromSession || undefined,
630
+ role: envelopeKind === 'execution_request'
631
+ ? 'execution_request'
632
+ : (envelopeKind === 'inquiry' ? 'inquiry' : (mode === 'steer' ? 'steer' : 'relay')),
633
+ ...(taskId ? { taskId } : {}),
634
+ }, safeBlocks)
635
+ try {
636
+ if (mode === 'steer' && targetAgent.status === 'running' && typeof targetAgent.steer === 'function') {
637
+ const r = targetAgent.steer(envelope)
638
+ if (r && typeof r.then === 'function') await r
639
+ deliveredPhysical = true
640
+ deliveryMode = 'agent-steer'
641
+ } else if (targetAgent.status !== 'running' && typeof targetAgent.followup === 'function') {
642
+ const r = targetAgent.followup(envelope)
643
+ if (r && typeof r.then === 'function') await r
644
+ deliveredPhysical = true
645
+ deliveryMode = 'agent-followup'
646
+ } else if (typeof targetAgent.inject === 'function') {
647
+ const r = targetAgent.inject(envelope)
648
+ if (r && typeof r.then === 'function') await r
649
+ deliveredPhysical = true
650
+ deliveryMode = 'agent-inject'
651
+ } else if (typeof targetAgent.steer === 'function') {
652
+ targetAgent.steer(safeBlocks.length ? formatted + imgSuffix : formatted)
653
+ deliveredPhysical = true
654
+ deliveryMode = 'agent-steer-text'
655
+ }
656
+ } catch (err) {
657
+ errorNote = String(err && err.message ? err.message : err)
658
+ }
659
+ }
660
+ }
661
+ }
662
+
663
+ // Always record in the shared cluster mailbox; if physical delivery already carried it,
664
+ // mark the recipient in readBy so `agent/pre-step` will NOT double-deliver it!
665
+ const recipientMarks = deliveredPhysical
666
+ ? [peer.id, peer.key, peer.name].filter(Boolean)
667
+ : []
668
+
669
+ const senderRoot = String(fromRootId || (fromSession && deps.resolveRootSessionId && deps.resolveRootSessionId(fromSession)) || directory.rootId || '').trim()
670
+ const targetRoot = String(peer.rootId || directory.rootId || '').trim()
671
+ const participantRoots = [...new Set([senderRoot, targetRoot].filter(Boolean))].sort()
672
+ const channelType = participantRoots.length >= 2 ? 'pair' : 'internal'
673
+
674
+ const mailItem = normalizeMail({
675
+ id: nextId('mail'),
676
+ from: fromLabel,
677
+ fromSession,
678
+ fromRootId: senderRoot,
679
+ to: peer.handle,
680
+ toSession: peer.id || peer.key,
681
+ toRootId: targetRoot,
682
+ participantRoots,
683
+ channelType,
684
+ subject,
685
+ text: imgCount > 0 ? `${textWithImagePaths}${imgSuffix}` : textWithImagePaths,
686
+ imageCount: imgCount,
687
+ mode,
688
+ deliveredPhysical,
689
+ readBy: recipientMarks,
690
+ at: Date.now(),
691
+ })
692
+
693
+ if (recordMailbox && mailItem) {
694
+ mutateChiefState((state) => {
695
+ const ws = ensureWorkspace(state, peer.rootId || directory.rootId)
696
+ ws.mailbox.push(mailItem)
697
+ if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
698
+ })
699
+ }
700
+
701
+ if (recordBoardLog && (peer.rootId || directory.rootId)) {
702
+ const badge = mode === 'steer' ? '⚡ 插话' : mode === 'silent' ? '📌 备忘纸条' : '📨 递话'
703
+ deps.appendBoardLog(
704
+ peer.rootId || directory.rootId,
705
+ `${badge} ${fromLabel} → ${peer.handle}:${clamp(text, 56)}${imgSuffix}`,
706
+ fromLabel,
707
+ )
708
+ }
709
+
710
+ return {
711
+ ok: true,
712
+ mail: mailItem,
713
+ target: peer.handle,
714
+ targetId: peer.id,
715
+ deliveredPhysical,
716
+ deliveryMode,
717
+ savedImagePaths: safePaths,
718
+ ...(errorNote && !deliveredPhysical ? { note: '目标暂未在线运行,已存入参谋部协同信箱,将在其下一步自动送达(' + errorNote + ')' } : {}),
719
+ }
720
+ }
721
+
722
+ /* -------------------------------------------------------------------------- */
723
+ /* KV-Cache Friendly Pre-Step Delta Note (`agent/pre-step`) */
724
+ /* -------------------------------------------------------------------------- */
725
+
726
+ export async function consumePreStepDelta(deps, agent) {
727
+ const sessionId = String(agent && agent.id ? agent.id : '').trim()
728
+ if (!sessionId) return null
729
+ const rootId = deps.resolveRootSessionId(sessionId, agent) || sessionId
730
+ const identity = deps.resolveAgentIdentity(deps.runtime, sessionId, agent)
731
+ const myHandles = new Set(
732
+ [
733
+ sessionId,
734
+ identity && identity.self ? identity.self : '',
735
+ identity && !identity.isChild ? 'lead' : '',
736
+ identity && !identity.isChild ? '主对话' : '',
737
+ ].filter(Boolean).map(s => s.toLowerCase()),
738
+ )
739
+
740
+ const deltaLines = []
741
+ let hasPriorityInquiry = false
742
+ mutateChiefState((state) => {
743
+ const view = clusterView(state, rootId)
744
+ const ownWs = ensureWorkspace(state, rootId)
745
+
746
+ // 0. Highest priority: DSH Chief Inquiry Channel (answer without interrupting own task!)
747
+ if (Array.isArray(ownWs.inquiries)) {
748
+ const nowInq = Date.now()
749
+ for (const inq of ownWs.inquiries) {
750
+ if (!inq || inq.status !== 'pending') continue
751
+ if (inq.expiresAt && nowInq > inq.expiresAt) {
752
+ inq.status = 'expired'
753
+ continue
754
+ }
755
+ const tLower = String(inq.target || 'lead').toLowerCase()
756
+ const matchesMe = myHandles.has(tLower) || (!identity?.isChild && tLower === 'lead')
757
+ if (!matchesMe) continue
758
+ inq.status = 'delivered'
759
+ inq.deliveredAt = nowInq
760
+ hasPriorityInquiry = true
761
+ deltaLines.push(
762
+ `⚡ [INQUIRY #${inq.inquiryId}${inq.taskId ? ' / ' + inq.taskId : ''} · DSH 参谋长优先问询 · 答复后继续原动作勿中断]`
763
+ + `\n 问题:${inq.question}`
764
+ + (inq.context ? `\n 背景:${inq.context}` : '')
765
+ + `\n ↳ 请在当前回合顺手调用 chief_board({ action: "inquiry.reply", inquiryId: "${inq.inquiryId}", text: "基于真实代码与状态的准确答复" }) 原路回传,然后立即继续你刚才的工作,切勿打断当前计划!`,
766
+ )
767
+ }
768
+ }
769
+
770
+ // 1. Unread mailbox messages addressed to this session/handle (STRICT cluster isolation: ignore detached external peers!)
771
+ for (const mail of view.mailbox) {
772
+ if (mail.detachedFromCluster) continue
773
+ const mailFromRoot = mail.fromRootId || (mail.fromSession && deps.resolveRootSessionId ? deps.resolveRootSessionId(mail.fromSession) : '')
774
+ if (mailFromRoot && mailFromRoot !== rootId && !view.cluster.includes(mailFromRoot)) continue
775
+ const toLower = String(mail.toSession || mail.to || '').toLowerCase()
776
+ const toHandleLower = String(mail.to || '').toLowerCase()
777
+ const isMine = toLower === 'all'
778
+ || toHandleLower === 'all'
779
+ || myHandles.has(toLower)
780
+ || myHandles.has(toHandleLower)
781
+ || myHandles.has(toHandleLower.split('/').pop())
782
+ if (!isMine) continue
783
+ if (mail.fromSession && mail.fromSession === sessionId) continue
784
+ const alreadyRead = (mail.readBy || []).some(r => myHandles.has(String(r).toLowerCase()))
785
+ if (alreadyRead) continue
786
+
787
+ mail.readBy = [...new Set([...(mail.readBy || []), sessionId, ...(identity?.self ? [identity.self] : [])])]
788
+ deltaLines.push(`- 📨 来自 **${mail.from}** 的协同来信${mail.subject ? '(' + mail.subject + ')' : ''}:${mail.text}`)
789
+ }
790
+
791
+ // 2. Newly added/updated durable facts since this session last checked
792
+ const lastSeenFact = Number(ownWs.seenFactsAt[sessionId] || 0)
793
+ const now = Date.now()
794
+ if (lastSeenFact === 0) {
795
+ // First step: freeze baseline without injecting noise if already covered, unless facts exist
796
+ ownWs.seenFactsAt[sessionId] = now
797
+ if (view.facts.length > 0) {
798
+ const topFacts = view.facts.slice(-8)
799
+ for (const f of topFacts) {
800
+ deltaLines.push(`- 📌 团队记忆与纪律:${f.text}`)
801
+ }
802
+ }
803
+ } else {
804
+ const freshFacts = view.facts.filter(f => (f.updatedAt || f.addedAt || 0) > lastSeenFact)
805
+ if (freshFacts.length > 0) {
806
+ ownWs.seenFactsAt[sessionId] = Math.max(...freshFacts.map(f => f.updatedAt || f.addedAt || now))
807
+ for (const f of freshFacts.slice(-6)) {
808
+ deltaLines.push(`- 📌 最新记忆变更(${f.by || '参谋长'}):${f.text}`)
809
+ }
810
+ }
811
+ }
812
+ })
813
+
814
+ if (deltaLines.length === 0) return null
815
+
816
+ const text = [
817
+ '## DSH 参谋长 · 跨对话协同与记忆增量',
818
+ '以下是自你上一轮以来收到的跨对话来信或最新团队纪律变更(仅作上下文参考与协同配合):',
819
+ '',
820
+ ...deltaLines,
821
+ ].join('\n')
822
+
823
+ return buildMessageEnvelope(
824
+ text,
825
+ hasPriorityInquiry ? CHIEF_INQUIRY_SOURCE : CHIEF_UPDATE_SOURCE,
826
+ { form: hasPriorityInquiry ? 'priority_inquiry' : 'snapshot' },
827
+ )
828
+ }
829
+
830
+ /* -------------------------------------------------------------------------- */
831
+ /* Concise Structured Bullet Summary ("摘要" · 宰相简报) */
832
+ /* -------------------------------------------------------------------------- */
833
+
834
+ export function readMailboxForAgent(deps, { sessionId, callerAgent, unreadOnly = false }) {
835
+ const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
836
+ const rootId = deps.resolveRootSessionId(sid, callerAgent) || sid || 'global'
837
+ const identity = deps.resolveAgentIdentity(deps.runtime, sid, callerAgent)
838
+ const myHandles = new Set(
839
+ [
840
+ sid,
841
+ identity && identity.self ? identity.self : '',
842
+ identity && !identity.isChild ? 'lead' : '',
843
+ ].filter(Boolean).map(v => v.toLowerCase()),
844
+ )
845
+
846
+ const out = []
847
+ mutateChiefState((state) => {
848
+ const view = clusterView(state, rootId)
849
+ for (const m of view.mailbox) {
850
+ const toLower = String(m.toSession || m.to || '').toLowerCase()
851
+ const toHandleLower = String(m.to || '').toLowerCase()
852
+ const relevant = !sid
853
+ || toLower === 'all'
854
+ || toHandleLower === 'all'
855
+ || myHandles.has(toLower)
856
+ || myHandles.has(toHandleLower)
857
+ || myHandles.has(toHandleLower.split('/').pop())
858
+ || m.fromSession === sid
859
+ if (!relevant) continue
860
+ const isRead = (m.readBy || []).some(r => myHandles.has(String(r).toLowerCase()))
861
+ if (unreadOnly && isRead) continue
862
+ if (!isRead && sid && m.fromSession !== sid) {
863
+ m.readBy = [...new Set([...(m.readBy || []), sid, ...(identity?.self ? [identity.self] : [])])]
864
+ }
865
+ out.push({ ...m, unread: !isRead })
866
+ }
867
+ })
868
+ return out.slice(-25)
869
+ }