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