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