dsh-chief 0.0.0-stage → 1.0.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/CHANGELOG.md +34 -0
- package/LICENSE +661 -0
- package/README.en.md +161 -0
- package/README.md +213 -2
- package/archives.js +1157 -0
- package/chief.js +3216 -0
- package/client.js +11079 -0
- package/cordis.patch.yml +3 -0
- package/digest.js +509 -0
- package/handoff.js +481 -0
- package/icon.svg +52 -0
- package/idle-guard.js +536 -0
- package/index.js +4453 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/memory.js +515 -0
- package/package.json +77 -3
- package/screenshots.json +9 -0
package/chief.js
ADDED
|
@@ -0,0 +1,3216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DSH Chief Engine (DSH 参谋长核心引擎)
|
|
3
|
+
*
|
|
4
|
+
* Bridges human natural-language intent, DS-Bot style narrative memory digests,
|
|
5
|
+
* and cross-session / subagent SuperAgent communication on top of the shared chief.
|
|
6
|
+
*
|
|
7
|
+
* Key capabilities:
|
|
8
|
+
* 1. Independent Chief Model selector (`ctx.llm`) with lowest-reasoning fast routing & fallback.
|
|
9
|
+
* 2. Two-tier memory inspired by DS-Bot: atomic durable facts + prose narrative digest ("摘要").
|
|
10
|
+
* 3. Natural-language command decomposition -> targeted relay / interjection (`steer` / `followup` / `silent`).
|
|
11
|
+
* 4. Cross-session & subagent communication bus (`mail.send` / `mail.inbox` / `mail.ack` + linked peer windows).
|
|
12
|
+
* 5. Post-turn background review & proactive Suggestion Pills (with toggleable Auto-Pilot mode).
|
|
13
|
+
* 6. KV-Cache friendly delta updates via `agent/pre-step` (never mutating historical messages).
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs'
|
|
17
|
+
import path from 'node:path'
|
|
18
|
+
import os from 'node:os'
|
|
19
|
+
import crypto from 'node:crypto'
|
|
20
|
+
import {
|
|
21
|
+
DEFAULT_ARCHIVE_FOLDERS,
|
|
22
|
+
loadArchiveStore,
|
|
23
|
+
listArchiveHeaders,
|
|
24
|
+
getArchiveDetail,
|
|
25
|
+
searchArchives,
|
|
26
|
+
smartParseNoteToDossier,
|
|
27
|
+
applyChiefArchiveCurations,
|
|
28
|
+
} from './archives.js'
|
|
29
|
+
|
|
30
|
+
const STATE_VERSION = 1
|
|
31
|
+
const FACTS_CAP = 120
|
|
32
|
+
const FACT_TEXT_MAX = 260
|
|
33
|
+
const CHAT_CAP = 36
|
|
34
|
+
const MAIL_CAP = 80
|
|
35
|
+
const SUGGESTIONS_CAP = 6
|
|
36
|
+
const MODEL_TIMEOUT_MS = 90_000
|
|
37
|
+
const CATALOG_TTL_MS = 10_000
|
|
38
|
+
const REVIEW_DELAY_MS = 2_800
|
|
39
|
+
const AUTO_SUMMARY_COOLDOWN_MS = 5 * 60_000
|
|
40
|
+
const SMART_REVIEW_COOLDOWN_MS = 3 * 60_000
|
|
41
|
+
const AUTO_REVIEW_COOLDOWN_MS = 90_000
|
|
42
|
+
// Thinking models spend several thousand output tokens on internal reasoning before emitting text;
|
|
43
|
+
// small caps (e.g. 2k-4k) starve the visible answer to empty string.
|
|
44
|
+
const SUMMARY_MAX_TOKENS = 16_384
|
|
45
|
+
const SUMMARY_RETRY_MAX_TOKENS = 32_768
|
|
46
|
+
|
|
47
|
+
export const CHIEF_UPDATE_SOURCE = 'dsh-chief-update'
|
|
48
|
+
export const CHIEF_RELAY_SOURCE = 'dsh-chief-relay'
|
|
49
|
+
|
|
50
|
+
const SECRET_PATTERN = /(?:sk-[a-zA-Z0-9_-]{16,}|ghp_[a-zA-Z0-9]{20,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{30,}|Bearer\s+[A-Za-z0-9._~+/=-]{20,}|-----BEGIN [A-Z ]*PRIVATE KEY-----)/
|
|
51
|
+
|
|
52
|
+
let dshLlmModulePromise = null
|
|
53
|
+
async function loadDshLlm() {
|
|
54
|
+
if (!dshLlmModulePromise) {
|
|
55
|
+
dshLlmModulePromise = import('@deepseek-ai/dsh-llm').catch(() => null)
|
|
56
|
+
}
|
|
57
|
+
return dshLlmModulePromise
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
let idSeq = 0
|
|
61
|
+
function nextId(prefix) {
|
|
62
|
+
idSeq = (idSeq + 1) % 1000000
|
|
63
|
+
return prefix + '-' + Date.now().toString(36) + '-' + idSeq.toString(36)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function clamp(value, max) {
|
|
67
|
+
const text = String(value == null ? '' : value).replace(/\s+/g, ' ').trim()
|
|
68
|
+
if (text.length <= max) return text
|
|
69
|
+
return text.slice(0, Math.max(0, max - 1)) + '…'
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function cleanMultiline(value, max) {
|
|
73
|
+
const text = String(value == null ? '' : value).replace(/\r/g, '').trim()
|
|
74
|
+
if (text.length <= max) return text
|
|
75
|
+
return text.slice(0, Math.max(0, max - 1)) + '…'
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function secretLike(text) {
|
|
79
|
+
return SECRET_PATTERN.test(String(text || ''))
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function chiefDir() {
|
|
83
|
+
const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
84
|
+
return path.join(home, 'chief')
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function stateFilePath() {
|
|
88
|
+
return path.join(chiefDir(), 'chief-state.json')
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function emptyWorkspace() {
|
|
92
|
+
return {
|
|
93
|
+
facts: [],
|
|
94
|
+
narrative: { hash: '', text: '', at: 0, byModel: '' },
|
|
95
|
+
suggestions: [],
|
|
96
|
+
chat: [],
|
|
97
|
+
mailbox: [],
|
|
98
|
+
seenMailAt: {},
|
|
99
|
+
seenFactsAt: {},
|
|
100
|
+
reviewCursors: {},
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function normalizeFact(raw) {
|
|
105
|
+
if (!raw || typeof raw !== 'object') return null
|
|
106
|
+
const text = clamp(raw.text, FACT_TEXT_MAX)
|
|
107
|
+
if (!text || secretLike(text)) return null
|
|
108
|
+
const validCategories = ['discipline', 'architecture', 'progress', 'preference', 'team']
|
|
109
|
+
const category = validCategories.includes(raw.category) ? raw.category : 'discipline'
|
|
110
|
+
return {
|
|
111
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('fact'),
|
|
112
|
+
text,
|
|
113
|
+
category,
|
|
114
|
+
by: clamp(raw.by || 'chief', 36),
|
|
115
|
+
source: clamp(raw.source || '', 60),
|
|
116
|
+
pinned: Boolean(raw.pinned),
|
|
117
|
+
addedAt: Number(raw.addedAt) || Date.now(),
|
|
118
|
+
updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || Date.now(),
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function normalizeSuggestion(raw) {
|
|
123
|
+
if (!raw || typeof raw !== 'object') return null
|
|
124
|
+
const title = clamp(raw.title, 90)
|
|
125
|
+
if (!title) return null
|
|
126
|
+
const kind = raw.kind === 'bound' ? 'bound' : raw.kind === 'board' ? 'board' : 'relay'
|
|
127
|
+
const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
|
|
128
|
+
const replaces = Array.isArray(raw.replaces)
|
|
129
|
+
? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
|
|
130
|
+
: []
|
|
131
|
+
return {
|
|
132
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('sug'),
|
|
133
|
+
kind,
|
|
134
|
+
boundField,
|
|
135
|
+
replaces,
|
|
136
|
+
pinGlobal: Boolean(raw.pinGlobal),
|
|
137
|
+
fromAgent: clamp(raw.fromAgent || '', 48),
|
|
138
|
+
title,
|
|
139
|
+
reason: clamp(raw.reason || '', 220),
|
|
140
|
+
target: clamp(raw.target || (kind === 'bound' ? 'bounds' : 'lead'), 64),
|
|
141
|
+
targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : '主对话'), 40),
|
|
142
|
+
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
|
|
143
|
+
draftText: cleanMultiline(raw.draftText || '', 600),
|
|
144
|
+
boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
|
|
145
|
+
status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
|
|
146
|
+
createdAt: Number(raw.createdAt) || Date.now(),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function normalizeMail(raw) {
|
|
151
|
+
if (!raw || typeof raw !== 'object') return null
|
|
152
|
+
const text = cleanMultiline(raw.text, 1500)
|
|
153
|
+
if (!text) return null
|
|
154
|
+
return {
|
|
155
|
+
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
|
|
156
|
+
from: clamp(raw.from || 'agent', 48),
|
|
157
|
+
fromSession: String(raw.fromSession || ''),
|
|
158
|
+
to: clamp(raw.to || 'lead', 64),
|
|
159
|
+
toSession: String(raw.toSession || ''),
|
|
160
|
+
subject: clamp(raw.subject || '', 80),
|
|
161
|
+
text,
|
|
162
|
+
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
|
|
163
|
+
deliveredPhysical: Boolean(raw.deliveredPhysical),
|
|
164
|
+
readBy: Array.isArray(raw.readBy) ? raw.readBy.map(String).slice(0, 32) : [],
|
|
165
|
+
at: Number(raw.at) || Date.now(),
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function normalizeWorkspace(raw) {
|
|
170
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
171
|
+
const base = emptyWorkspace()
|
|
172
|
+
base.facts = (Array.isArray(src.facts) ? src.facts : []).map(normalizeFact).filter(Boolean).slice(-FACTS_CAP)
|
|
173
|
+
if (src.narrative && typeof src.narrative === 'object') {
|
|
174
|
+
base.narrative = {
|
|
175
|
+
hash: String(src.narrative.hash || ''),
|
|
176
|
+
text: String(src.narrative.text || ''),
|
|
177
|
+
at: Number(src.narrative.at) || 0,
|
|
178
|
+
byModel: String(src.narrative.byModel || ''),
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
base.suggestions = (Array.isArray(src.suggestions) ? src.suggestions : [])
|
|
182
|
+
.map(normalizeSuggestion)
|
|
183
|
+
.filter(Boolean)
|
|
184
|
+
.slice(-SUGGESTIONS_CAP * 2)
|
|
185
|
+
base.chat = (Array.isArray(src.chat) ? src.chat : [])
|
|
186
|
+
.filter(item => item && typeof item === 'object' && typeof item.text === 'string')
|
|
187
|
+
.slice(-CHAT_CAP)
|
|
188
|
+
.map(item => ({
|
|
189
|
+
id: String(item.id || nextId('chat')),
|
|
190
|
+
role: item.role === 'user' ? 'user' : 'chief',
|
|
191
|
+
text: cleanMultiline(item.text, 2000),
|
|
192
|
+
target: item.target ? String(item.target) : '',
|
|
193
|
+
actions: Array.isArray(item.actions) ? item.actions.slice(0, 8) : [],
|
|
194
|
+
at: Number(item.at) || Date.now(),
|
|
195
|
+
}))
|
|
196
|
+
base.mailbox = (Array.isArray(src.mailbox) ? src.mailbox : []).map(normalizeMail).filter(Boolean).slice(-MAIL_CAP)
|
|
197
|
+
base.seenMailAt = src.seenMailAt && typeof src.seenMailAt === 'object' ? { ...src.seenMailAt } : {}
|
|
198
|
+
base.seenFactsAt = src.seenFactsAt && typeof src.seenFactsAt === 'object' ? { ...src.seenFactsAt } : {}
|
|
199
|
+
base.reviewCursors = src.reviewCursors && typeof src.reviewCursors === 'object' ? { ...src.reviewCursors } : {}
|
|
200
|
+
return base
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function normalizeState(raw) {
|
|
204
|
+
const src = raw && typeof raw === 'object' ? raw : {}
|
|
205
|
+
const cfg = src.config && typeof src.config === 'object' ? src.config : {}
|
|
206
|
+
const links = {}
|
|
207
|
+
if (src.links && typeof src.links === 'object') {
|
|
208
|
+
for (const [k, list] of Object.entries(src.links)) {
|
|
209
|
+
if (!k || !Array.isArray(list)) continue
|
|
210
|
+
const clean = [...new Set(list.map(v => String(v || '').trim()).filter(v => v && v !== k))]
|
|
211
|
+
if (clean.length) links[k] = clean
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const workspaces = {}
|
|
215
|
+
if (src.workspaces && typeof src.workspaces === 'object') {
|
|
216
|
+
for (const [k, ws] of Object.entries(src.workspaces)) {
|
|
217
|
+
if (!k) continue
|
|
218
|
+
workspaces[k] = normalizeWorkspace(ws)
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
const validPaces = ['manual', 'smart', 'auto']
|
|
222
|
+
// Default to 'manual' (human-paced, zero background token burn) unless explicitly set to smart/auto
|
|
223
|
+
const paceMode = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
|
|
224
|
+
return {
|
|
225
|
+
version: STATE_VERSION,
|
|
226
|
+
config: {
|
|
227
|
+
modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
|
|
228
|
+
paceMode,
|
|
229
|
+
autoPilot: paceMode === 'auto',
|
|
230
|
+
autoReview: paceMode !== 'manual',
|
|
231
|
+
},
|
|
232
|
+
links,
|
|
233
|
+
workspaces,
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
let cachedState = null
|
|
238
|
+
let cachedMtime = 0
|
|
239
|
+
|
|
240
|
+
export function loadChiefState() {
|
|
241
|
+
const file = stateFilePath()
|
|
242
|
+
try {
|
|
243
|
+
const stat = fs.statSync(file)
|
|
244
|
+
if (cachedState && stat.mtimeMs === cachedMtime) return cachedState
|
|
245
|
+
const parsed = JSON.parse(fs.readFileSync(file, 'utf8'))
|
|
246
|
+
cachedState = normalizeState(parsed)
|
|
247
|
+
cachedMtime = stat.mtimeMs
|
|
248
|
+
return cachedState
|
|
249
|
+
} catch {
|
|
250
|
+
if (!cachedState) cachedState = normalizeState({})
|
|
251
|
+
return cachedState
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export function saveChiefState(state) {
|
|
256
|
+
const normalized = normalizeState(state)
|
|
257
|
+
const file = stateFilePath()
|
|
258
|
+
try {
|
|
259
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
260
|
+
const tmp = file + '.' + process.pid + '.' + Date.now().toString(36) + '.tmp'
|
|
261
|
+
fs.writeFileSync(tmp, JSON.stringify(normalized, null, 2), 'utf8')
|
|
262
|
+
fs.renameSync(tmp, file)
|
|
263
|
+
try {
|
|
264
|
+
cachedMtime = fs.statSync(file).mtimeMs
|
|
265
|
+
} catch {
|
|
266
|
+
cachedMtime = Date.now()
|
|
267
|
+
}
|
|
268
|
+
} catch {}
|
|
269
|
+
cachedState = normalized
|
|
270
|
+
return normalized
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
export function mutateChiefState(mutator) {
|
|
274
|
+
const state = loadChiefState()
|
|
275
|
+
const result = mutator(state)
|
|
276
|
+
saveChiefState(state)
|
|
277
|
+
return result
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Find connected component of linked root sessions (undirected graph). */
|
|
281
|
+
export function getLinkedCluster(state, rootSessionId) {
|
|
282
|
+
const seed = String(rootSessionId || '').trim()
|
|
283
|
+
if (!seed) return ['global']
|
|
284
|
+
const visited = new Set([seed])
|
|
285
|
+
const queue = [seed]
|
|
286
|
+
const links = (state && state.links) || {}
|
|
287
|
+
while (queue.length > 0) {
|
|
288
|
+
const cur = queue.shift()
|
|
289
|
+
const direct = Array.isArray(links[cur]) ? links[cur] : []
|
|
290
|
+
for (const peer of direct) {
|
|
291
|
+
if (peer && !visited.has(peer)) {
|
|
292
|
+
visited.add(peer)
|
|
293
|
+
queue.push(peer)
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
for (const [other, list] of Object.entries(links)) {
|
|
297
|
+
if (Array.isArray(list) && list.includes(cur) && !visited.has(other)) {
|
|
298
|
+
visited.add(other)
|
|
299
|
+
queue.push(other)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
return [...visited].sort()
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function setPeerLink(rootA, rootB, linked) {
|
|
307
|
+
const a = String(rootA || '').trim()
|
|
308
|
+
const b = String(rootB || '').trim()
|
|
309
|
+
if (!a || !b || a === b) return { ok: false, error: '需要两个不同的主会话才能建立协同连接' }
|
|
310
|
+
return mutateChiefState((state) => {
|
|
311
|
+
const setA = new Set(state.links[a] || [])
|
|
312
|
+
const setB = new Set(state.links[b] || [])
|
|
313
|
+
if (linked) {
|
|
314
|
+
setA.add(b)
|
|
315
|
+
setB.add(a)
|
|
316
|
+
} else {
|
|
317
|
+
setA.delete(b)
|
|
318
|
+
setB.delete(a)
|
|
319
|
+
}
|
|
320
|
+
if (setA.size) state.links[a] = [...setA]
|
|
321
|
+
else delete state.links[a]
|
|
322
|
+
if (setB.size) state.links[b] = [...setB]
|
|
323
|
+
else delete state.links[b]
|
|
324
|
+
return { ok: true, cluster: getLinkedCluster(state, a) }
|
|
325
|
+
})
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
function ensureWorkspace(state, rootId) {
|
|
329
|
+
const key = String(rootId || 'global').trim() || 'global'
|
|
330
|
+
if (!state.workspaces[key]) state.workspaces[key] = emptyWorkspace()
|
|
331
|
+
return state.workspaces[key]
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Merge facts & mailbox across all linked peer sessions in the federation cluster. */
|
|
335
|
+
function clusterView(state, rootId) {
|
|
336
|
+
const cluster = getLinkedCluster(state, rootId)
|
|
337
|
+
const primary = ensureWorkspace(state, rootId)
|
|
338
|
+
if (cluster.length <= 1) {
|
|
339
|
+
return {
|
|
340
|
+
cluster,
|
|
341
|
+
primary,
|
|
342
|
+
facts: primary.facts,
|
|
343
|
+
mailbox: primary.mailbox,
|
|
344
|
+
suggestions: primary.suggestions.filter(s => s.status === 'pending'),
|
|
345
|
+
chat: primary.chat,
|
|
346
|
+
narrative: primary.narrative,
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const factMap = new Map()
|
|
350
|
+
const mailMap = new Map()
|
|
351
|
+
for (const sid of cluster) {
|
|
352
|
+
const ws = ensureWorkspace(state, sid)
|
|
353
|
+
for (const f of ws.facts) factMap.set(f.id, f)
|
|
354
|
+
for (const m of ws.mailbox) mailMap.set(m.id, m)
|
|
355
|
+
}
|
|
356
|
+
const facts = [...factMap.values()].sort((a, b) => (a.addedAt || 0) - (b.addedAt || 0)).slice(-FACTS_CAP)
|
|
357
|
+
const mailbox = [...mailMap.values()].sort((a, b) => (a.at || 0) - (b.at || 0)).slice(-MAIL_CAP)
|
|
358
|
+
return {
|
|
359
|
+
cluster,
|
|
360
|
+
primary,
|
|
361
|
+
facts,
|
|
362
|
+
mailbox,
|
|
363
|
+
suggestions: primary.suggestions.filter(s => s.status === 'pending'),
|
|
364
|
+
chat: primary.chat,
|
|
365
|
+
narrative: primary.narrative,
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/* -------------------------------------------------------------------------- */
|
|
370
|
+
/* Model Catalog & Auxiliary LLM Caller */
|
|
371
|
+
/* -------------------------------------------------------------------------- */
|
|
372
|
+
|
|
373
|
+
let modelCatalogCache = { at: 0, items: [] }
|
|
374
|
+
|
|
375
|
+
export function invalidateChiefModelCatalog() {
|
|
376
|
+
modelCatalogCache = { at: 0, items: [] }
|
|
377
|
+
unusableRouteUntil.clear()
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
function splitModelRef(ref) {
|
|
381
|
+
const clean = String(ref || '').trim()
|
|
382
|
+
const idx = clean.indexOf('/')
|
|
383
|
+
if (idx <= 0 || idx >= clean.length - 1) return null
|
|
384
|
+
return { provider: clean.slice(0, idx), model: clean.slice(idx + 1), ref: clean }
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function stripVendorPrefixFromModelId(modelId) {
|
|
388
|
+
const raw = String(modelId || '').trim()
|
|
389
|
+
if (!raw.includes('/')) return raw
|
|
390
|
+
const parts = raw.split('/').filter(Boolean)
|
|
391
|
+
return parts.length > 1 ? parts.slice(1).join('/') : raw
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function shortProviderTag(providerId, providerName) {
|
|
395
|
+
const pid = String(providerId || '').toLowerCase()
|
|
396
|
+
const pname = String(providerName || '').trim()
|
|
397
|
+
if (pid === 'commandcode' || /command\s*code/i.test(pname)) return 'Command Code'
|
|
398
|
+
if (pid.includes('account') || /account/i.test(pname)) return pname || 'DeepSeek Account'
|
|
399
|
+
if (pid === 'our-free-model') return 'Free Model'
|
|
400
|
+
return pname || providerId || ''
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function formatChiefModelLabel(ref, items = [], providers = [], compact = false) {
|
|
404
|
+
const parsed = splitModelRef(ref)
|
|
405
|
+
if (!parsed) return compact ? '自动跟随' : ''
|
|
406
|
+
const hit = Array.isArray(items) ? items.find(it => it && it.ref === parsed.ref) : null
|
|
407
|
+
const provObj = Array.isArray(providers) ? providers.find(p => p && p.id === parsed.provider) : null
|
|
408
|
+
const provLabel = shortProviderTag(parsed.provider, (hit && hit.providerName) || (provObj && (provObj.name || provObj.label)) || parsed.provider)
|
|
409
|
+
const rawModelName = (hit && hit.name) ? String(hit.name).trim() : stripVendorPrefixFromModelId(parsed.model)
|
|
410
|
+
|
|
411
|
+
if (compact) {
|
|
412
|
+
// Keep channel crystal-clear so Command Code DS is never confused with official DeepSeek API
|
|
413
|
+
const shortProv = parsed.provider === 'commandcode' ? 'CC' : provLabel
|
|
414
|
+
const alreadyTagged = /\(CC\)/i.test(rawModelName) && shortProv === 'CC'
|
|
415
|
+
const base = alreadyTagged ? rawModelName : (shortProv ? `${shortProv} · ${rawModelName}` : rawModelName)
|
|
416
|
+
return clamp(base, 24)
|
|
417
|
+
}
|
|
418
|
+
const alreadyHasProv = provLabel && rawModelName.toLowerCase().includes(provLabel.toLowerCase())
|
|
419
|
+
return alreadyHasProv || !provLabel ? rawModelName : `${provLabel} · ${rawModelName}`
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
function detectUnkeyedProviders(runtime, llm) {
|
|
423
|
+
const missing = new Set()
|
|
424
|
+
if (!runtime || !llm || typeof llm.listConfigurableProviders !== 'function') return missing
|
|
425
|
+
try {
|
|
426
|
+
const settings = runtime.get('settings')
|
|
427
|
+
const credentials = runtime.get('credentials')
|
|
428
|
+
if (!settings || !credentials || typeof settings.describe !== 'function') return missing
|
|
429
|
+
const sections = new Map((settings.describe({ redactSecrets: true }) || []).map(s => [s.ns, s]))
|
|
430
|
+
for (const entry of (llm.listConfigurableProviders() || [])) {
|
|
431
|
+
if (!entry || !entry.provider || !Array.isArray(entry.settingsPath)) continue
|
|
432
|
+
const sec = sections.get(entry.settingsNs)
|
|
433
|
+
const profile = entry.settingsPath.reduce((v, k) => v?.[k], sec?.value)
|
|
434
|
+
const keyEnv = typeof profile?.apiKeyEnv === 'string' && profile.apiKeyEnv ? profile.apiKeyEnv : ''
|
|
435
|
+
if (keyEnv && process.env[keyEnv] === '') {
|
|
436
|
+
// Explicit empty env hint; async describe handled below when needed
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
} catch {}
|
|
440
|
+
return missing
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
async function detectMissingProviderKeysAsync(runtime, llm, providerIds) {
|
|
444
|
+
const missing = detectUnkeyedProviders(runtime, llm)
|
|
445
|
+
if (!runtime || !llm || typeof llm.listConfigurableProviders !== 'function') return missing
|
|
446
|
+
try {
|
|
447
|
+
const settings = runtime.get('settings')
|
|
448
|
+
const credentials = runtime.get('credentials')
|
|
449
|
+
if (!settings || !credentials || typeof settings.describe !== 'function' || typeof credentials.describe !== 'function') {
|
|
450
|
+
return missing
|
|
451
|
+
}
|
|
452
|
+
const sections = new Map((settings.describe({ redactSecrets: true }) || []).map(s => [s.ns, s]))
|
|
453
|
+
const keyRefs = new Map()
|
|
454
|
+
for (const entry of (llm.listConfigurableProviders() || [])) {
|
|
455
|
+
if (!entry || !entry.provider || !Array.isArray(entry.settingsPath)) continue
|
|
456
|
+
const sec = sections.get(entry.settingsNs)
|
|
457
|
+
const profile = entry.settingsPath.reduce((v, k) => v?.[k], sec?.value)
|
|
458
|
+
if (typeof profile?.apiKeyEnv === 'string' && profile.apiKeyEnv) {
|
|
459
|
+
keyRefs.set(entry.provider, profile.apiKeyEnv)
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
await Promise.all(
|
|
463
|
+
providerIds
|
|
464
|
+
.filter(id => keyRefs.has(id))
|
|
465
|
+
.map(async (id) => {
|
|
466
|
+
const info = await Promise.resolve(credentials.describe(keyRefs.get(id))).catch(() => undefined)
|
|
467
|
+
if (info && info.configured === false) missing.add(id)
|
|
468
|
+
}),
|
|
469
|
+
)
|
|
470
|
+
} catch {}
|
|
471
|
+
return missing
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function extractAgentModelRef(agent) {
|
|
475
|
+
if (!agent) return ''
|
|
476
|
+
try {
|
|
477
|
+
const sess = agent.session
|
|
478
|
+
const header = sess && typeof sess.requestHeader === 'function'
|
|
479
|
+
? sess.requestHeader()
|
|
480
|
+
: (sess && sess.header ? sess.header : null)
|
|
481
|
+
const candidates = [
|
|
482
|
+
header && header.config,
|
|
483
|
+
header,
|
|
484
|
+
sess && sess.config,
|
|
485
|
+
sess && sess.modelSelection,
|
|
486
|
+
agent.modelSelection,
|
|
487
|
+
agent.config,
|
|
488
|
+
]
|
|
489
|
+
for (const cfg of candidates) {
|
|
490
|
+
if (cfg && typeof cfg.provider === 'string' && cfg.provider && typeof cfg.model === 'string' && cfg.model) {
|
|
491
|
+
if (!cfg.provider.startsWith('local-agent')) {
|
|
492
|
+
return `${cfg.provider}/${cfg.model}`
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
} catch {}
|
|
497
|
+
return ''
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
function sessionModelRef(deps, sessionId) {
|
|
501
|
+
if (!deps || !deps.runtime) return ''
|
|
502
|
+
try {
|
|
503
|
+
const agents = deps.runtime.get('agents')
|
|
504
|
+
if (!agents || typeof agents.get !== 'function') return ''
|
|
505
|
+
if (sessionId) {
|
|
506
|
+
const direct = extractAgentModelRef(agents.get(sessionId))
|
|
507
|
+
if (direct) return direct
|
|
508
|
+
const rootId = deps.resolveRootSessionId ? deps.resolveRootSessionId(sessionId) : ''
|
|
509
|
+
if (rootId && rootId !== sessionId) {
|
|
510
|
+
const rootRef = extractAgentModelRef(agents.get(rootId))
|
|
511
|
+
if (rootRef) return rootRef
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
} catch {}
|
|
515
|
+
return ''
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
function profileDefaultModelRef(runtime) {
|
|
519
|
+
if (!runtime) return ''
|
|
520
|
+
try {
|
|
521
|
+
const sel = runtime.get('agentDefaultModel')?.currentSelection?.()
|
|
522
|
+
if (sel && sel.provider && sel.model && !String(sel.provider).startsWith('local-agent')) {
|
|
523
|
+
return `${sel.provider}/${sel.model}`
|
|
524
|
+
}
|
|
525
|
+
} catch {}
|
|
526
|
+
return ''
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
export async function listChiefModels(deps, fresh = false, sessionId = '') {
|
|
530
|
+
const llm = deps.getLlm ? deps.getLlm() : null
|
|
531
|
+
const runtime = deps.runtime
|
|
532
|
+
const state = loadChiefState()
|
|
533
|
+
let selectedRef = state.config.modelRef || ''
|
|
534
|
+
|
|
535
|
+
const leadRef = sessionModelRef(deps, sessionId)
|
|
536
|
+
const profileDefaultRef = profileDefaultModelRef(runtime)
|
|
537
|
+
const followRef = leadRef || profileDefaultRef || ''
|
|
538
|
+
|
|
539
|
+
if (!llm || typeof llm.listProviders !== 'function' || typeof llm.listModels !== 'function') {
|
|
540
|
+
const resolvedRef = selectedRef || followRef || ''
|
|
541
|
+
return {
|
|
542
|
+
available: false,
|
|
543
|
+
selectedRef,
|
|
544
|
+
followRef,
|
|
545
|
+
followLabel: formatChiefModelLabel(followRef, [], [], false),
|
|
546
|
+
defaultRef: followRef,
|
|
547
|
+
resolvedRef,
|
|
548
|
+
resolvedLabel: formatChiefModelLabel(resolvedRef, [], [], true),
|
|
549
|
+
models: [],
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
const rawProviders = (llm.listProviders() || []).filter(p => p && p.id && !String(p.id).startsWith('local-agent'))
|
|
554
|
+
const registeredProviderIds = new Set(rawProviders.map(p => String(p.id)))
|
|
555
|
+
|
|
556
|
+
// Auto-heal stale selectedRef if its provider was uninstalled/removed (e.g. legacy `opendesign/...`)
|
|
557
|
+
if (selectedRef) {
|
|
558
|
+
const parsedSel = splitModelRef(selectedRef)
|
|
559
|
+
if (!parsedSel || (registeredProviderIds.size > 0 && !registeredProviderIds.has(parsedSel.provider))) {
|
|
560
|
+
selectedRef = ''
|
|
561
|
+
mutateChiefState((s) => {
|
|
562
|
+
s.config.modelRef = ''
|
|
563
|
+
})
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
let items = []
|
|
568
|
+
if (!fresh && modelCatalogCache.items.length > 0 && Date.now() - modelCatalogCache.at < CATALOG_TTL_MS) {
|
|
569
|
+
items = modelCatalogCache.items.slice()
|
|
570
|
+
} else {
|
|
571
|
+
try {
|
|
572
|
+
const missingKeys = await detectMissingProviderKeysAsync(runtime, llm, [...registeredProviderIds])
|
|
573
|
+
for (const provider of rawProviders) {
|
|
574
|
+
const pid = String(provider.id)
|
|
575
|
+
const pname = String(provider.name || provider.label || pid)
|
|
576
|
+
const needsKey = missingKeys.has(pid)
|
|
577
|
+
let models = []
|
|
578
|
+
try {
|
|
579
|
+
models = (await llm.listModels(pid)) || []
|
|
580
|
+
} catch {
|
|
581
|
+
continue
|
|
582
|
+
}
|
|
583
|
+
for (const m of models) {
|
|
584
|
+
if (!m || !m.id) continue
|
|
585
|
+
items.push({
|
|
586
|
+
ref: `${pid}/${m.id}`,
|
|
587
|
+
provider: pid,
|
|
588
|
+
providerName: pname,
|
|
589
|
+
id: String(m.id),
|
|
590
|
+
name: String(m.name || m.label || m.id),
|
|
591
|
+
...(needsKey ? { needsKey: true } : {}),
|
|
592
|
+
})
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
} catch {}
|
|
596
|
+
modelCatalogCache = { at: Date.now(), items: items.slice() }
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
// Ensure the active main-conversation model (`followRef`) & `profileDefaultRef` appear in the catalog
|
|
600
|
+
// even when a dynamic provider (e.g. Command Code) only returned a subset in `listModels()`!
|
|
601
|
+
const ensureListed = async (refToEnsure, markCurrent = false) => {
|
|
602
|
+
const parsed = splitModelRef(refToEnsure)
|
|
603
|
+
if (!parsed || !registeredProviderIds.has(parsed.provider)) return
|
|
604
|
+
const existing = items.find(it => it.ref === parsed.ref)
|
|
605
|
+
if (existing) {
|
|
606
|
+
if (markCurrent) existing.isCurrentLead = true
|
|
607
|
+
return
|
|
608
|
+
}
|
|
609
|
+
const provObj = rawProviders.find(p => String(p.id) === parsed.provider)
|
|
610
|
+
const pname = String((provObj && (provObj.name || provObj.label)) || parsed.provider)
|
|
611
|
+
let displayName = stripVendorPrefixFromModelId(parsed.model)
|
|
612
|
+
try {
|
|
613
|
+
if (typeof llm.resolveModelInfo === 'function') {
|
|
614
|
+
const info = await llm.resolveModelInfo(parsed.provider, parsed.model)
|
|
615
|
+
if (info && typeof info.name === 'string' && info.name.trim()) {
|
|
616
|
+
displayName = info.name.trim()
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
} catch {}
|
|
620
|
+
const entry = {
|
|
621
|
+
ref: parsed.ref,
|
|
622
|
+
provider: parsed.provider,
|
|
623
|
+
providerName: pname,
|
|
624
|
+
id: parsed.model,
|
|
625
|
+
name: displayName,
|
|
626
|
+
...(markCurrent ? { isCurrentLead: true } : {}),
|
|
627
|
+
}
|
|
628
|
+
// Insert at the top of its provider group so it is immediately visible without scrolling
|
|
629
|
+
const firstProvIdx = items.findIndex(it => it.provider === parsed.provider)
|
|
630
|
+
if (firstProvIdx >= 0) items.splice(firstProvIdx, 0, entry)
|
|
631
|
+
else items.unshift(entry)
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
await ensureListed(followRef, true)
|
|
635
|
+
if (profileDefaultRef && profileDefaultRef !== followRef) {
|
|
636
|
+
await ensureListed(profileDefaultRef, false)
|
|
637
|
+
}
|
|
638
|
+
if (selectedRef && selectedRef !== followRef && selectedRef !== profileDefaultRef) {
|
|
639
|
+
await ensureListed(selectedRef, false)
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
const picked = pickRouteFromItems(items, selectedRef, followRef, deps, sessionId, registeredProviderIds)
|
|
643
|
+
const resolvedRef = (picked && picked.ref) || selectedRef || followRef || ''
|
|
644
|
+
return {
|
|
645
|
+
available: items.length > 0 || Boolean(resolvedRef),
|
|
646
|
+
selectedRef,
|
|
647
|
+
followRef,
|
|
648
|
+
followLabel: formatChiefModelLabel(followRef, items, rawProviders, false),
|
|
649
|
+
defaultRef: followRef,
|
|
650
|
+
resolvedRef,
|
|
651
|
+
resolvedLabel: formatChiefModelLabel(resolvedRef, items, rawProviders, true),
|
|
652
|
+
models: items,
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const unusableRouteUntil = new Map()
|
|
657
|
+
|
|
658
|
+
function isRouteCoolingDown(ref, provider) {
|
|
659
|
+
const now = Date.now()
|
|
660
|
+
if (ref && (unusableRouteUntil.get(ref) || 0) > now) return true
|
|
661
|
+
if (provider && (unusableRouteUntil.get('prov:' + provider) || 0) > now) return true
|
|
662
|
+
return false
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
function markRouteFailure(route, err) {
|
|
666
|
+
if (!route) return
|
|
667
|
+
const msg = String(err && err.message ? err.message : err || '')
|
|
668
|
+
const code = String(err && (err.code || err.failure?.code) ? (err.code || err.failure?.code) : '')
|
|
669
|
+
// Missing API key / auth error / hosted loop engine cannot serve auxiliary completions
|
|
670
|
+
if (/api[_ -]?key|unauthorized|authentication|401|403|not configured|missing key|no key|credentials/i.test(msg) || /AUTH|KEY/i.test(code)) {
|
|
671
|
+
unusableRouteUntil.set('prov:' + route.provider, Date.now() + 90_000)
|
|
672
|
+
} else if (/HOSTED_ENGINE_ROUTE|not a model endpoint|no adapter/i.test(msg) || code === 'HOSTED_ENGINE_ROUTE') {
|
|
673
|
+
unusableRouteUntil.set(route.ref, Date.now() + 300_000)
|
|
674
|
+
} else {
|
|
675
|
+
unusableRouteUntil.set(route.ref, Date.now() + 20_000)
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function buildRouteQueue(items, selectedRef, followRef, deps, sessionId, registeredProviderIds = null) {
|
|
680
|
+
const seen = new Set()
|
|
681
|
+
const out = []
|
|
682
|
+
const isProviderRegistered = (prov) => {
|
|
683
|
+
if (!prov || String(prov).startsWith('local-agent')) return false
|
|
684
|
+
if (registeredProviderIds && registeredProviderIds.size > 0) return registeredProviderIds.has(prov)
|
|
685
|
+
return true
|
|
686
|
+
}
|
|
687
|
+
const pushCand = (cand, allowUnlisted = false) => {
|
|
688
|
+
const parsed = splitModelRef(cand)
|
|
689
|
+
if (!parsed || !isProviderRegistered(parsed.provider)) return
|
|
690
|
+
if (seen.has(parsed.ref)) return
|
|
691
|
+
if (!allowUnlisted && items.length > 0 && !items.some(it => it.ref === parsed.ref && !it.needsKey)) return
|
|
692
|
+
seen.add(parsed.ref)
|
|
693
|
+
out.push(parsed)
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
const liveLeadRef = sessionModelRef(deps, sessionId)
|
|
697
|
+
const primaryFollow = liveLeadRef || followRef || profileDefaultModelRef(deps && deps.runtime)
|
|
698
|
+
|
|
699
|
+
if (selectedRef) {
|
|
700
|
+
// Explicit user-pinned Chief model: try it first, then same-provider models, then main session model
|
|
701
|
+
pushCand(selectedRef, true)
|
|
702
|
+
const selParsed = splitModelRef(selectedRef)
|
|
703
|
+
if (selParsed) {
|
|
704
|
+
for (const it of items) {
|
|
705
|
+
if (it && it.provider === selParsed.provider && !it.needsKey) pushCand(it.ref, false)
|
|
706
|
+
if (out.length >= 3) break
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
if (primaryFollow) pushCand(primaryFollow, true)
|
|
710
|
+
} else if (primaryFollow) {
|
|
711
|
+
// Auto-follow main conversation mode:
|
|
712
|
+
// MUST use the exact provider/model of the main conversation (e.g. `commandcode/deepseek/deepseek-v4.1-flash`)
|
|
713
|
+
// and NEVER silently jump across to a paid official API provider (like `deepseek/...`)!
|
|
714
|
+
pushCand(primaryFollow, true)
|
|
715
|
+
if (followRef && followRef !== primaryFollow) pushCand(followRef, true)
|
|
716
|
+
const followParsed = splitModelRef(primaryFollow)
|
|
717
|
+
if (followParsed) {
|
|
718
|
+
for (const it of items) {
|
|
719
|
+
if (it && it.provider === followParsed.provider && !it.needsKey) pushCand(it.ref, false)
|
|
720
|
+
if (out.length >= 4) break
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
} else {
|
|
724
|
+
// Only when neither a pinned model nor any main/default model exists at all: pick keyed catalog models
|
|
725
|
+
const seenProviders = new Set()
|
|
726
|
+
for (const it of items) {
|
|
727
|
+
if (!it || !it.ref || it.needsKey || seenProviders.has(it.provider)) continue
|
|
728
|
+
seenProviders.add(it.provider)
|
|
729
|
+
pushCand(it.ref, false)
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
// Prefer routes not currently cooling down, keeping cooled ones only as last-resort tail
|
|
734
|
+
const healthy = out.filter(r => !isRouteCoolingDown(r.ref, r.provider))
|
|
735
|
+
const cooled = out.filter(r => isRouteCoolingDown(r.ref, r.provider))
|
|
736
|
+
return [...healthy, ...cooled]
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function pickRouteFromItems(items, selectedRef, followRef, deps, sessionId, registeredProviderIds = null) {
|
|
740
|
+
const queue = buildRouteQueue(items, selectedRef, followRef, deps, sessionId, registeredProviderIds)
|
|
741
|
+
return queue[0] || null
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
async function callOneRoute(llm, route, system, userText, maxTokens = SUMMARY_MAX_TOKENS, sessionId = '') {
|
|
745
|
+
let effort
|
|
746
|
+
let modelDefaultMaxTokens
|
|
747
|
+
try {
|
|
748
|
+
if (typeof llm.resolveModelInfo === 'function') {
|
|
749
|
+
const info = await llm.resolveModelInfo(route.provider, route.model)
|
|
750
|
+
if (typeof info?.defaultMaxTokens === 'number' && info.defaultMaxTokens > 0) {
|
|
751
|
+
modelDefaultMaxTokens = info.defaultMaxTokens
|
|
752
|
+
}
|
|
753
|
+
const efforts = info?.reasoning?.efforts
|
|
754
|
+
if (Array.isArray(efforts) && efforts.length > 0) {
|
|
755
|
+
effort = efforts.some(e => e.id === 'off') ? 'off' : efforts[0]?.id
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
} catch {}
|
|
759
|
+
|
|
760
|
+
const targetBudget = Math.max(Number(maxTokens) || 0, SUMMARY_MAX_TOKENS)
|
|
761
|
+
const firstBudget = modelDefaultMaxTokens ? Math.min(modelDefaultMaxTokens, targetBudget) : targetBudget
|
|
762
|
+
const retryBudget = firstBudget < targetBudget ? targetBudget : SUMMARY_RETRY_MAX_TOKENS
|
|
763
|
+
const budgets = retryBudget > firstBudget ? [firstBudget, retryBudget] : [firstBudget]
|
|
764
|
+
|
|
765
|
+
const runOnce = async (budget) => {
|
|
766
|
+
const request = {
|
|
767
|
+
provider: route.provider,
|
|
768
|
+
model: route.model,
|
|
769
|
+
...(sessionId ? { sessionId } : {}),
|
|
770
|
+
...(effort !== undefined ? { reasoningEffort: effort } : {}),
|
|
771
|
+
system,
|
|
772
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: userText }] }],
|
|
773
|
+
maxTokens: budget,
|
|
774
|
+
signal: AbortSignal.timeout(MODEL_TIMEOUT_MS),
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const dshLlm = await loadDshLlm()
|
|
778
|
+
if (dshLlm && typeof dshLlm.BlockAssembler === 'function') {
|
|
779
|
+
const assembler = new dshLlm.BlockAssembler()
|
|
780
|
+
for await (const chunk of llm.stream(request)) {
|
|
781
|
+
assembler.push(chunk)
|
|
782
|
+
}
|
|
783
|
+
const finish = assembler.finish
|
|
784
|
+
if (finish && (finish.kind === 'error' || finish.kind === 'aborted')) {
|
|
785
|
+
const err = new Error(finish.failure?.message || finish.failure?.code || finish.kind || 'LLM request error')
|
|
786
|
+
err.failure = finish.failure
|
|
787
|
+
throw err
|
|
788
|
+
}
|
|
789
|
+
const text = assembler
|
|
790
|
+
.blocks()
|
|
791
|
+
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
792
|
+
.map(b => b.text)
|
|
793
|
+
.join('\n')
|
|
794
|
+
.trim()
|
|
795
|
+
return { text, finishKind: finish?.kind || '', modelRef: route.ref }
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// Pure standalone fallback stream reader (for unit tests / lightweight hosts)
|
|
799
|
+
const parts = []
|
|
800
|
+
let finishKind = ''
|
|
801
|
+
for await (const chunk of llm.stream(request)) {
|
|
802
|
+
if (!chunk || typeof chunk !== 'object') continue
|
|
803
|
+
if (chunk.type === 'text-delta' || chunk.type === 'text_delta') {
|
|
804
|
+
if (typeof chunk.text === 'string') parts.push(chunk.text)
|
|
805
|
+
else if (typeof chunk.delta === 'string') parts.push(chunk.delta)
|
|
806
|
+
} else if (chunk.type === 'text' && typeof chunk.text === 'string') parts.push(chunk.text)
|
|
807
|
+
else if (typeof chunk.content === 'string') parts.push(chunk.content)
|
|
808
|
+
else if (chunk.type === 'finish') {
|
|
809
|
+
finishKind = chunk.reason?.kind || chunk.finishReason || ''
|
|
810
|
+
if (finishKind === 'error') {
|
|
811
|
+
const err = new Error(chunk.reason?.failure?.message || 'LLM stream error')
|
|
812
|
+
err.failure = chunk.reason?.failure
|
|
813
|
+
throw err
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
return { text: parts.join('').trim(), finishKind, modelRef: route.ref }
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
let lastRes = { text: '', finishKind: '', modelRef: route.ref }
|
|
821
|
+
for (let i = 0; i < budgets.length; i += 1) {
|
|
822
|
+
const res = await runOnce(budgets[i])
|
|
823
|
+
lastRes = res
|
|
824
|
+
if (res.text && res.finishKind !== 'max-tokens') {
|
|
825
|
+
return { text: res.text, modelRef: res.modelRef }
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
return { text: lastRes.text, modelRef: lastRes.modelRef }
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
export async function callChiefLlm(deps, { sessionId = '', system, prompt, maxTokens = SUMMARY_MAX_TOKENS }) {
|
|
832
|
+
if (deps && typeof deps.callLlmOverride === 'function') {
|
|
833
|
+
return deps.callLlmOverride({ sessionId, system, prompt, maxTokens })
|
|
834
|
+
}
|
|
835
|
+
const llm = deps.getLlm ? deps.getLlm() : null
|
|
836
|
+
if (!llm || typeof llm.stream !== 'function') {
|
|
837
|
+
return { ok: false, error: '当前环境未挂载 LLM 服务' }
|
|
838
|
+
}
|
|
839
|
+
const catalog = await listChiefModels(deps, false, sessionId)
|
|
840
|
+
const regSet = typeof llm.listProviders === 'function'
|
|
841
|
+
? new Set((llm.listProviders() || []).filter(p => p && p.id && !String(p.id).startsWith('local-agent')).map(p => String(p.id)))
|
|
842
|
+
: null
|
|
843
|
+
const queue = buildRouteQueue(catalog.models, catalog.selectedRef, catalog.followRef || catalog.defaultRef, deps, sessionId, regSet)
|
|
844
|
+
if (!queue.length) {
|
|
845
|
+
return { ok: false, error: '未找到可用的参谋长模型,请在 DSH 设置中配置模型供应商' }
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
let lastError = '模型返回内容为空'
|
|
849
|
+
for (const route of queue.slice(0, 4)) {
|
|
850
|
+
try {
|
|
851
|
+
const res = await callOneRoute(llm, route, system, prompt, maxTokens, sessionId)
|
|
852
|
+
if (res.text) return { ok: true, text: res.text, modelRef: res.modelRef }
|
|
853
|
+
lastError = `${route.ref} 返回内容为空`
|
|
854
|
+
markRouteFailure(route, new Error(lastError))
|
|
855
|
+
} catch (err) {
|
|
856
|
+
lastError = String(err && err.message ? err.message : err)
|
|
857
|
+
markRouteFailure(route, err)
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
return { ok: false, error: lastError }
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
/* -------------------------------------------------------------------------- */
|
|
864
|
+
/* Peer Discovery & Cross-Conversation Delivery ("递话 / 插话") */
|
|
865
|
+
/* -------------------------------------------------------------------------- */
|
|
866
|
+
|
|
867
|
+
export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE, extraSource = {}) {
|
|
868
|
+
const dshLlm = await loadDshLlm()
|
|
869
|
+
const content = [{ type: 'text', text }]
|
|
870
|
+
const source = { kind: sourceKind, ...extraSource }
|
|
871
|
+
if (dshLlm && typeof dshLlm.createUserMessage === 'function') {
|
|
872
|
+
try {
|
|
873
|
+
return dshLlm.createUserMessage({ content, source })
|
|
874
|
+
} catch {}
|
|
875
|
+
}
|
|
876
|
+
return {
|
|
877
|
+
id: nextId('secmsg'),
|
|
878
|
+
role: 'user',
|
|
879
|
+
content,
|
|
880
|
+
source,
|
|
881
|
+
}
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
/** Build complete addressable peer directory across lead, subagents, and federated root sessions. */
|
|
885
|
+
export async function listPeerDirectory(deps, sessionId) {
|
|
886
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || '')
|
|
887
|
+
const state = loadChiefState()
|
|
888
|
+
const cluster = getLinkedCluster(state, rootId)
|
|
889
|
+
const runtime = deps.runtime
|
|
890
|
+
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
891
|
+
const liveAgents = agentsSvc && typeof agentsSvc.list === 'function' ? agentsSvc.list() : []
|
|
892
|
+
const archived = (() => {
|
|
893
|
+
try {
|
|
894
|
+
const list = runtime && runtime.get('workspaceRegistry')?.archivedSessionIds
|
|
895
|
+
return Array.isArray(list) ? new Set(list) : new Set()
|
|
896
|
+
} catch {
|
|
897
|
+
return new Set()
|
|
898
|
+
}
|
|
899
|
+
})()
|
|
900
|
+
|
|
901
|
+
const targets = []
|
|
902
|
+
const seenIds = new Set()
|
|
903
|
+
|
|
904
|
+
for (const memberRootId of cluster) {
|
|
905
|
+
const isCurrentRoot = memberRootId === rootId
|
|
906
|
+
const board = deps.boardForSession(deps.boardFileFor(memberRootId))
|
|
907
|
+
const roster = await deps.refreshSubagentTree(runtime, memberRootId, board)
|
|
908
|
+
const rootAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(memberRootId) : null
|
|
909
|
+
const rootTitle = deps.sessionName(runtime, rootAgent || memberRootId) || ('会话 ' + memberRootId.replace(/^session-/, '').slice(0, 8))
|
|
910
|
+
|
|
911
|
+
for (const entry of roster) {
|
|
912
|
+
if (!entry) continue
|
|
913
|
+
const isLead = entry.name === 'lead'
|
|
914
|
+
const key = isCurrentRoot
|
|
915
|
+
? (isLead ? 'lead' : entry.name)
|
|
916
|
+
: (isLead ? memberRootId : `${memberRootId}:${entry.name}`)
|
|
917
|
+
if (seenIds.has(key)) continue
|
|
918
|
+
seenIds.add(key)
|
|
919
|
+
targets.push({
|
|
920
|
+
key,
|
|
921
|
+
id: entry.id || (isLead ? memberRootId : ''),
|
|
922
|
+
rootId: memberRootId,
|
|
923
|
+
name: isLead ? (isCurrentRoot ? '主对话' : rootTitle) : entry.name,
|
|
924
|
+
handle: isCurrentRoot ? (isLead ? 'lead' : entry.name) : (isLead ? rootTitle : `${rootTitle}/${entry.name}`),
|
|
925
|
+
kind: isLead ? (isCurrentRoot ? 'lead' : 'peer-session') : 'subagent',
|
|
926
|
+
isCurrentRoot,
|
|
927
|
+
status: entry.status === 'running' ? 'running' : 'idle',
|
|
928
|
+
taskTitle: entry.taskTitle || entry.description || (board && board.objective ? clamp(board.objective, 48) : ''),
|
|
929
|
+
parentId: entry.parentId || memberRootId,
|
|
930
|
+
mode: entry.mode || 'continuable',
|
|
931
|
+
})
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
|
|
935
|
+
// Other top-level standalone sessions on this machine that can be linked into the federation
|
|
936
|
+
const otherSessions = []
|
|
937
|
+
for (const ag of liveAgents) {
|
|
938
|
+
const sid = String(ag && ag.id ? ag.id : '')
|
|
939
|
+
if (!sid || archived.has(sid)) continue
|
|
940
|
+
const agRoot = deps.resolveRootSessionId(sid, ag) || sid
|
|
941
|
+
if (agRoot !== sid) continue // skip child subagent sessions here
|
|
942
|
+
if (agRoot === rootId) continue
|
|
943
|
+
const isLinked = cluster.includes(agRoot)
|
|
944
|
+
const b = deps.loadBoard(deps.boardFileFor(agRoot))
|
|
945
|
+
otherSessions.push({
|
|
946
|
+
id: agRoot,
|
|
947
|
+
name: deps.sessionName(runtime, ag) || ('会话 ' + agRoot.replace(/^session-/, '').slice(0, 8)),
|
|
948
|
+
status: ag.status === 'running' ? 'running' : 'idle',
|
|
949
|
+
linked: isLinked,
|
|
950
|
+
objective: clamp(b && b.objective ? b.objective : '', 80),
|
|
951
|
+
openTasks: Array.isArray(b && b.tasks) ? b.tasks.filter(t => t.status !== 'done').length : 0,
|
|
952
|
+
})
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
return {
|
|
956
|
+
rootId,
|
|
957
|
+
cluster,
|
|
958
|
+
targets,
|
|
959
|
+
otherSessions,
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
function matchTargetPeer(targets, rawTarget) {
|
|
964
|
+
const q = String(rawTarget || '').trim().replace(/^@/, '')
|
|
965
|
+
if (!q) return null
|
|
966
|
+
const lower = q.toLowerCase()
|
|
967
|
+
if (lower === 'lead' || lower === 'main' || lower === '主对话' || lower === '主代理') {
|
|
968
|
+
return targets.find(t => t.kind === 'lead' && t.isCurrentRoot) || targets[0] || null
|
|
969
|
+
}
|
|
970
|
+
// Exact match by key, id, name, or handle
|
|
971
|
+
for (const t of targets) {
|
|
972
|
+
if (
|
|
973
|
+
t.key.toLowerCase() === lower
|
|
974
|
+
|| (t.id && t.id.toLowerCase() === lower)
|
|
975
|
+
|| t.name.toLowerCase() === lower
|
|
976
|
+
|| t.handle.toLowerCase() === lower
|
|
977
|
+
|| t.name.split('/').pop().toLowerCase() === lower
|
|
978
|
+
) {
|
|
979
|
+
return t
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
// Partial substring match
|
|
983
|
+
return targets.find(t =>
|
|
984
|
+
t.name.toLowerCase().includes(lower) || t.handle.toLowerCase().includes(lower),
|
|
985
|
+
) || null
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/**
|
|
989
|
+
* Deliver a message across conversations (lead <-> subagent, subagent <-> subagent, session <-> session).
|
|
990
|
+
* Modes:
|
|
991
|
+
* - 'steer': cut into next step boundary immediately if running, or wake if idle.
|
|
992
|
+
* - 'followup': queue for next turn / wake idle session without cutting running step.
|
|
993
|
+
* - 'silent': record in chief mailbox so the recipient sees it cleanly at its next pre-step without waking an idle session.
|
|
994
|
+
*/
|
|
995
|
+
export async function deliverCrossMessage(deps, {
|
|
996
|
+
fromSession = '',
|
|
997
|
+
fromLabel = 'DSH 参谋长',
|
|
998
|
+
target = 'lead',
|
|
999
|
+
text = '',
|
|
1000
|
+
subject = '',
|
|
1001
|
+
mode = 'steer',
|
|
1002
|
+
recordBoardLog = true,
|
|
1003
|
+
}) {
|
|
1004
|
+
const cleanBody = cleanMultiline(text, 2400)
|
|
1005
|
+
if (!cleanBody) return { ok: false, error: '递话内容不能为空' }
|
|
1006
|
+
|
|
1007
|
+
const rootId = deps.resolveRootSessionId(fromSession) || String(fromSession || '')
|
|
1008
|
+
const directory = await listPeerDirectory(deps, rootId || fromSession)
|
|
1009
|
+
const rawTarget = String(target || 'lead').trim().replace(/^@/, '')
|
|
1010
|
+
|
|
1011
|
+
// Broadcast support: 'all' / '全体' / 'team'
|
|
1012
|
+
if (['all', 'team', '全体', '所有人'].includes(rawTarget.toLowerCase())) {
|
|
1013
|
+
const recipients = directory.targets.filter(t => t.id !== fromSession)
|
|
1014
|
+
const deliveries = []
|
|
1015
|
+
for (const peer of recipients) {
|
|
1016
|
+
const res = await deliverSinglePeer(deps, directory, peer, {
|
|
1017
|
+
fromSession,
|
|
1018
|
+
fromLabel,
|
|
1019
|
+
text: cleanBody,
|
|
1020
|
+
subject,
|
|
1021
|
+
mode,
|
|
1022
|
+
recordBoardLog: false,
|
|
1023
|
+
})
|
|
1024
|
+
deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
|
|
1025
|
+
}
|
|
1026
|
+
if (recordBoardLog && rootId) {
|
|
1027
|
+
deps.appendBoardLog(rootId, `📡 ${fromLabel} 向全体成员广播递话(${deliveries.filter(d => d.ok).length} 个目标):${clamp(cleanBody, 56)}`, fromLabel)
|
|
1028
|
+
}
|
|
1029
|
+
return { ok: true, broadcast: true, deliveries }
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
const peer = matchTargetPeer(directory.targets, rawTarget)
|
|
1033
|
+
if (!peer) {
|
|
1034
|
+
return {
|
|
1035
|
+
ok: false,
|
|
1036
|
+
error: `未找到目标对话 "${rawTarget}"。当前可用目标:${directory.targets.map(t => t.handle).join('、') || '无'}`,
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
return deliverSinglePeer(deps, directory, peer, {
|
|
1041
|
+
fromSession,
|
|
1042
|
+
fromLabel,
|
|
1043
|
+
text: cleanBody,
|
|
1044
|
+
subject,
|
|
1045
|
+
mode,
|
|
1046
|
+
recordBoardLog,
|
|
1047
|
+
})
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
async function deliverSinglePeer(deps, directory, peer, { fromSession, fromLabel, text, subject, mode, recordBoardLog }) {
|
|
1051
|
+
const runtime = deps.runtime
|
|
1052
|
+
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
1053
|
+
const subagentsSvc = runtime ? runtime.get('subagents') : null
|
|
1054
|
+
const headerTag = mode === 'steer'
|
|
1055
|
+
? `[DSH 参谋长插话 · 来自 ${fromLabel}]`
|
|
1056
|
+
: `[DSH 参谋长递话 · 来自 ${fromLabel}]`
|
|
1057
|
+
const formatted = `${headerTag}${subject ? ' ' + subject : ''}\n${text}\n\n(如需回信或同步进展,可调用参谋看板 chief_board({ action: "mail.send", target: "${fromLabel === 'DSH 参谋长' ? 'lead' : fromLabel}", text: "…" }))`
|
|
1058
|
+
|
|
1059
|
+
let deliveredPhysical = false
|
|
1060
|
+
let deliveryMode = 'mailbox-queued'
|
|
1061
|
+
let errorNote = ''
|
|
1062
|
+
|
|
1063
|
+
if (mode !== 'silent') {
|
|
1064
|
+
// Path A: Subagent delivery via DSH native subagents service
|
|
1065
|
+
if (peer.kind === 'subagent' && subagentsSvc) {
|
|
1066
|
+
const caller = (agentsSvc && peer.rootId && agentsSvc.get(peer.rootId)) || deps.findLiveCallerAgent(runtime, peer.rootId, null)
|
|
1067
|
+
if (caller) {
|
|
1068
|
+
try {
|
|
1069
|
+
let targetChildId = peer.id
|
|
1070
|
+
if (!targetChildId && typeof subagentsSvc.resolveName === 'function') {
|
|
1071
|
+
targetChildId = await subagentsSvc.resolveName(caller, peer.name, AbortSignal.timeout(5000))
|
|
1072
|
+
}
|
|
1073
|
+
if (targetChildId) {
|
|
1074
|
+
await subagentsSvc.sendMessage(caller, targetChildId, [{ type: 'text', text: formatted }], {
|
|
1075
|
+
signal: AbortSignal.timeout(10_000),
|
|
1076
|
+
})
|
|
1077
|
+
deliveredPhysical = true
|
|
1078
|
+
deliveryMode = 'subagent-send'
|
|
1079
|
+
}
|
|
1080
|
+
} catch (err) {
|
|
1081
|
+
errorNote = String(err && err.message ? err.message : err)
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
// Path B: Direct Agent handle delivery (for root lead, peer standalone sessions, or fallback live child agent)
|
|
1087
|
+
if (!deliveredPhysical && agentsSvc && peer.id) {
|
|
1088
|
+
let targetAgent = typeof agentsSvc.get === 'function' ? agentsSvc.get(peer.id) : null
|
|
1089
|
+
if (!targetAgent && runtime) {
|
|
1090
|
+
try {
|
|
1091
|
+
const controller = runtime.get('sessionController')
|
|
1092
|
+
if (controller && typeof controller.resolveAgent === 'function') {
|
|
1093
|
+
const resolved = await controller.resolveAgent(peer.id)
|
|
1094
|
+
if (resolved && resolved.agent) targetAgent = resolved.agent
|
|
1095
|
+
}
|
|
1096
|
+
} catch {}
|
|
1097
|
+
}
|
|
1098
|
+
if (targetAgent) {
|
|
1099
|
+
const envelope = await buildMessageEnvelope(formatted, CHIEF_RELAY_SOURCE, {
|
|
1100
|
+
senderName: fromLabel,
|
|
1101
|
+
senderSessionId: fromSession || undefined,
|
|
1102
|
+
role: mode === 'steer' ? 'steer' : 'relay',
|
|
1103
|
+
})
|
|
1104
|
+
try {
|
|
1105
|
+
if (mode === 'steer' && targetAgent.status === 'running' && typeof targetAgent.steer === 'function') {
|
|
1106
|
+
const r = targetAgent.steer(envelope)
|
|
1107
|
+
if (r && typeof r.then === 'function') await r
|
|
1108
|
+
deliveredPhysical = true
|
|
1109
|
+
deliveryMode = 'agent-steer'
|
|
1110
|
+
} else if (targetAgent.status !== 'running' && typeof targetAgent.followup === 'function') {
|
|
1111
|
+
const r = targetAgent.followup(envelope)
|
|
1112
|
+
if (r && typeof r.then === 'function') await r
|
|
1113
|
+
deliveredPhysical = true
|
|
1114
|
+
deliveryMode = 'agent-followup'
|
|
1115
|
+
} else if (typeof targetAgent.inject === 'function') {
|
|
1116
|
+
const r = targetAgent.inject(envelope)
|
|
1117
|
+
if (r && typeof r.then === 'function') await r
|
|
1118
|
+
deliveredPhysical = true
|
|
1119
|
+
deliveryMode = 'agent-inject'
|
|
1120
|
+
} else if (typeof targetAgent.steer === 'function') {
|
|
1121
|
+
targetAgent.steer(formatted)
|
|
1122
|
+
deliveredPhysical = true
|
|
1123
|
+
deliveryMode = 'agent-steer-text'
|
|
1124
|
+
}
|
|
1125
|
+
} catch (err) {
|
|
1126
|
+
errorNote = String(err && err.message ? err.message : err)
|
|
1127
|
+
}
|
|
1128
|
+
}
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// Always record in the shared cluster mailbox; if physical delivery already carried it,
|
|
1133
|
+
// mark the recipient in readBy so `agent/pre-step` will NOT double-deliver it!
|
|
1134
|
+
const recipientMarks = deliveredPhysical
|
|
1135
|
+
? [peer.id, peer.key, peer.name].filter(Boolean)
|
|
1136
|
+
: []
|
|
1137
|
+
|
|
1138
|
+
const mailItem = normalizeMail({
|
|
1139
|
+
id: nextId('mail'),
|
|
1140
|
+
from: fromLabel,
|
|
1141
|
+
fromSession,
|
|
1142
|
+
to: peer.handle,
|
|
1143
|
+
toSession: peer.id || peer.key,
|
|
1144
|
+
subject,
|
|
1145
|
+
text,
|
|
1146
|
+
mode,
|
|
1147
|
+
deliveredPhysical,
|
|
1148
|
+
readBy: recipientMarks,
|
|
1149
|
+
at: Date.now(),
|
|
1150
|
+
})
|
|
1151
|
+
|
|
1152
|
+
mutateChiefState((state) => {
|
|
1153
|
+
const ws = ensureWorkspace(state, peer.rootId || directory.rootId)
|
|
1154
|
+
ws.mailbox.push(mailItem)
|
|
1155
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
1156
|
+
})
|
|
1157
|
+
|
|
1158
|
+
if (recordBoardLog && (peer.rootId || directory.rootId)) {
|
|
1159
|
+
const badge = mode === 'steer' ? '⚡ 插话' : mode === 'silent' ? '📌 备忘纸条' : '📨 递话'
|
|
1160
|
+
deps.appendBoardLog(
|
|
1161
|
+
peer.rootId || directory.rootId,
|
|
1162
|
+
`${badge} ${fromLabel} → ${peer.handle}:${clamp(text, 56)}`,
|
|
1163
|
+
fromLabel,
|
|
1164
|
+
)
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
return {
|
|
1168
|
+
ok: true,
|
|
1169
|
+
mail: mailItem,
|
|
1170
|
+
target: peer.handle,
|
|
1171
|
+
targetId: peer.id,
|
|
1172
|
+
deliveredPhysical,
|
|
1173
|
+
deliveryMode,
|
|
1174
|
+
...(errorNote && !deliveredPhysical ? { note: '目标暂未在线运行,已存入参谋部协同信箱,将在其下一步自动送达(' + errorNote + ')' } : {}),
|
|
1175
|
+
}
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
/* -------------------------------------------------------------------------- */
|
|
1179
|
+
/* KV-Cache Friendly Pre-Step Delta Note (`agent/pre-step`) */
|
|
1180
|
+
/* -------------------------------------------------------------------------- */
|
|
1181
|
+
|
|
1182
|
+
export async function consumePreStepDelta(deps, agent) {
|
|
1183
|
+
const sessionId = String(agent && agent.id ? agent.id : '').trim()
|
|
1184
|
+
if (!sessionId) return null
|
|
1185
|
+
const rootId = deps.resolveRootSessionId(sessionId, agent) || sessionId
|
|
1186
|
+
const identity = deps.resolveAgentIdentity(deps.runtime, sessionId, agent)
|
|
1187
|
+
const myHandles = new Set(
|
|
1188
|
+
[
|
|
1189
|
+
sessionId,
|
|
1190
|
+
identity && identity.self ? identity.self : '',
|
|
1191
|
+
identity && !identity.isChild ? 'lead' : '',
|
|
1192
|
+
identity && !identity.isChild ? '主对话' : '',
|
|
1193
|
+
].filter(Boolean).map(s => s.toLowerCase()),
|
|
1194
|
+
)
|
|
1195
|
+
|
|
1196
|
+
const deltaLines = []
|
|
1197
|
+
mutateChiefState((state) => {
|
|
1198
|
+
const view = clusterView(state, rootId)
|
|
1199
|
+
const ownWs = ensureWorkspace(state, rootId)
|
|
1200
|
+
|
|
1201
|
+
// 1. Unread mailbox messages addressed to this session/handle
|
|
1202
|
+
for (const mail of view.mailbox) {
|
|
1203
|
+
const toLower = String(mail.toSession || mail.to || '').toLowerCase()
|
|
1204
|
+
const toHandleLower = String(mail.to || '').toLowerCase()
|
|
1205
|
+
const isMine = toLower === 'all'
|
|
1206
|
+
|| toHandleLower === 'all'
|
|
1207
|
+
|| myHandles.has(toLower)
|
|
1208
|
+
|| myHandles.has(toHandleLower)
|
|
1209
|
+
|| myHandles.has(toHandleLower.split('/').pop())
|
|
1210
|
+
if (!isMine) continue
|
|
1211
|
+
if (mail.fromSession && mail.fromSession === sessionId) continue
|
|
1212
|
+
const alreadyRead = (mail.readBy || []).some(r => myHandles.has(String(r).toLowerCase()))
|
|
1213
|
+
if (alreadyRead) continue
|
|
1214
|
+
|
|
1215
|
+
mail.readBy = [...new Set([...(mail.readBy || []), sessionId, ...(identity?.self ? [identity.self] : [])])]
|
|
1216
|
+
deltaLines.push(`- 📨 来自 **${mail.from}** 的协同来信${mail.subject ? '(' + mail.subject + ')' : ''}:${mail.text}`)
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// 2. Newly added/updated durable facts since this session last checked
|
|
1220
|
+
const lastSeenFact = Number(ownWs.seenFactsAt[sessionId] || 0)
|
|
1221
|
+
const now = Date.now()
|
|
1222
|
+
if (lastSeenFact === 0) {
|
|
1223
|
+
// First step: freeze baseline without injecting noise if already covered, unless facts exist
|
|
1224
|
+
ownWs.seenFactsAt[sessionId] = now
|
|
1225
|
+
if (view.facts.length > 0) {
|
|
1226
|
+
const topFacts = view.facts.slice(-8)
|
|
1227
|
+
for (const f of topFacts) {
|
|
1228
|
+
deltaLines.push(`- 📌 团队记忆与纪律:${f.text}`)
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
} else {
|
|
1232
|
+
const freshFacts = view.facts.filter(f => (f.updatedAt || f.addedAt || 0) > lastSeenFact)
|
|
1233
|
+
if (freshFacts.length > 0) {
|
|
1234
|
+
ownWs.seenFactsAt[sessionId] = Math.max(...freshFacts.map(f => f.updatedAt || f.addedAt || now))
|
|
1235
|
+
for (const f of freshFacts.slice(-6)) {
|
|
1236
|
+
deltaLines.push(`- 📌 最新记忆变更(${f.by || '参谋长'}):${f.text}`)
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
})
|
|
1241
|
+
|
|
1242
|
+
if (deltaLines.length === 0) return null
|
|
1243
|
+
|
|
1244
|
+
const text = [
|
|
1245
|
+
'## DSH 参谋长 · 跨对话协同与记忆增量',
|
|
1246
|
+
'以下是自你上一轮以来收到的跨对话来信或最新团队纪律变更(仅作上下文参考与协同配合):',
|
|
1247
|
+
'',
|
|
1248
|
+
...deltaLines,
|
|
1249
|
+
].join('\n')
|
|
1250
|
+
|
|
1251
|
+
return buildMessageEnvelope(text, CHIEF_UPDATE_SOURCE, { form: 'snapshot' })
|
|
1252
|
+
}
|
|
1253
|
+
|
|
1254
|
+
/* -------------------------------------------------------------------------- */
|
|
1255
|
+
/* Concise Structured Bullet Summary ("摘要" · 宰相简报) */
|
|
1256
|
+
/* -------------------------------------------------------------------------- */
|
|
1257
|
+
|
|
1258
|
+
const SUMMARY_FORMAT_REV = 'v2.1-structured-bullets'
|
|
1259
|
+
|
|
1260
|
+
const NARRATIVE_SYSTEM = [
|
|
1261
|
+
'你是「DSH 参谋长」(如同统揽全局的宰相),负责把当前工作区和协同团队的目标、进展、纪律与红线边界,提炼成用户一眼扫完就能掌握全局的「摘要」。',
|
|
1262
|
+
'严格遵守以下【简明结构化 · 分点作答】规范:',
|
|
1263
|
+
'1. 使用简体中文,语气精炼干脆、直击要害,严禁寒暄套话与冗长铺垫。',
|
|
1264
|
+
'2. 全文分为 2 到 4 个模块,每个模块以一行 `## 模块短标题` 开头(如 `## 核心目标与态势`、`## 关键结论与进展`、`## 协作纪律与边界`)。',
|
|
1265
|
+
'3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【推进中】…`、`- 【受阻】…`、`- 【结论】…`、`- 【禁止红线】…`、`- 【允许范围】…`。',
|
|
1266
|
+
'4. **去噪与聚合铁律**:遇到大量同前缀或已结束的后台巡检子代理(如 `mnemon-review-*`),**严禁逐一报菜名罗列**,必须合并成一句话统计(如 `- 【团队】1 名子代理运行中,其余 12 名历史巡检已结束`);自动忽略 `[dsh-mnemon:...]` 等系统内部检查点噪音。',
|
|
1267
|
+
'5. 具体路径、端口、版本号、命令原样保留,同一事实绝不重复,只陈述真实输入,第一个 `## ` 之前不要输出任何多余字符。',
|
|
1268
|
+
].join('\n')
|
|
1269
|
+
|
|
1270
|
+
function shortAgentBriefName(name) {
|
|
1271
|
+
const raw = String(name || '').trim()
|
|
1272
|
+
if (!raw) return ''
|
|
1273
|
+
return raw
|
|
1274
|
+
.split('/')
|
|
1275
|
+
.map(seg => seg.replace(/[-_]([0-9a-f]{8,40})$/i, (_, hex) => '·' + hex.slice(0, 4)))
|
|
1276
|
+
.join('/')
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
function stripCheckpointNoise(text) {
|
|
1280
|
+
return String(text || '')
|
|
1281
|
+
.replace(/\[dsh-mnemon:[^\]]*\][\s\S]*/gi, '')
|
|
1282
|
+
.replace(/Bounded completed checkpoint[\s\S]*/gi, '')
|
|
1283
|
+
.replace(/\s+/g, ' ')
|
|
1284
|
+
.trim()
|
|
1285
|
+
}
|
|
1286
|
+
|
|
1287
|
+
function isInternalCheckpointNoise(text) {
|
|
1288
|
+
const s = stripCheckpointNoise(text)
|
|
1289
|
+
if (!s) return true
|
|
1290
|
+
if (/^Mnemon idle checkpoint review\b/i.test(s)) return true
|
|
1291
|
+
return false
|
|
1292
|
+
}
|
|
1293
|
+
|
|
1294
|
+
function summarizeSubagentsCompact(workers) {
|
|
1295
|
+
if (!Array.isArray(workers) || workers.length === 0) return ''
|
|
1296
|
+
const running = workers.filter(w => w.status === 'running')
|
|
1297
|
+
const idle = workers.filter(w => w.status !== 'running')
|
|
1298
|
+
const parts = []
|
|
1299
|
+
if (running.length > 0) {
|
|
1300
|
+
const detail = running.slice(0, 4).map(w => {
|
|
1301
|
+
const cleanTask = w.taskTitle && !isInternalCheckpointNoise(w.taskTitle) ? `(推进:${clamp(w.taskTitle, 28)})` : ''
|
|
1302
|
+
return `@${shortAgentBriefName(w.name)}${cleanTask}`
|
|
1303
|
+
}).join('、')
|
|
1304
|
+
parts.push(`${running.length} 运行中:${detail}${running.length > 4 ? ' 等' : ''}`)
|
|
1305
|
+
}
|
|
1306
|
+
if (idle.length > 0) {
|
|
1307
|
+
if (running.length === 0 && idle.length <= 3) {
|
|
1308
|
+
parts.push(`待命:${idle.map(w => '@' + shortAgentBriefName(w.name)).join('、')}`)
|
|
1309
|
+
} else {
|
|
1310
|
+
parts.push(`${idle.length} 已结束/待命`)
|
|
1311
|
+
}
|
|
1312
|
+
}
|
|
1313
|
+
return `共 ${workers.length} 名子代理(${parts.join(';')})`
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
function buildNarrativeInput({ board, facts, cluster, targets }) {
|
|
1317
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1318
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1319
|
+
const memory = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
1320
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
1321
|
+
const anchors = (Array.isArray(board && board.notes) ? board.notes : []).filter(n => (n.tags || []).includes('anchor'))
|
|
1322
|
+
|
|
1323
|
+
const lines = []
|
|
1324
|
+
if (board && board.objective) lines.push(`当前总目标:${board.objective}`)
|
|
1325
|
+
if ((bounds.forbidden || []).length) lines.push(`禁止红线:${bounds.forbidden.join(';')}`)
|
|
1326
|
+
if ((bounds.allowed || []).length) lines.push(`允许范围:${bounds.allowed.join(';')}`)
|
|
1327
|
+
if ((bounds.notes || []).length) lines.push(`边界注意:${bounds.notes.join(';')}`)
|
|
1328
|
+
|
|
1329
|
+
if (cluster.length > 1) {
|
|
1330
|
+
lines.push(`跨窗口协同频道:当前已串联 ${cluster.length} 个主对话窗口协同作业。`)
|
|
1331
|
+
}
|
|
1332
|
+
const activeWorkers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
|
|
1333
|
+
if (activeWorkers.length > 0) {
|
|
1334
|
+
lines.push(`子代理态势:${summarizeSubagentsCompact(activeWorkers)}`)
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
if (facts.length > 0) {
|
|
1338
|
+
lines.push('', '【持久记忆与纪律条目】')
|
|
1339
|
+
for (const f of facts) {
|
|
1340
|
+
lines.push(`- [${f.category}] ${f.text}`)
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
|
|
1344
|
+
if (anchors.length > 0) {
|
|
1345
|
+
lines.push('', '【关键锚点笔记】')
|
|
1346
|
+
for (const a of anchors.slice(0, 8)) {
|
|
1347
|
+
lines.push(`- ${a.title}:${clamp(a.body, 220)}`)
|
|
1348
|
+
}
|
|
1349
|
+
}
|
|
1350
|
+
|
|
1351
|
+
if (tasks.length > 0) {
|
|
1352
|
+
const done = tasks.filter(t => t.status === 'done')
|
|
1353
|
+
const open = tasks.filter(t => t.status !== 'done')
|
|
1354
|
+
lines.push('', '【任务图态势】')
|
|
1355
|
+
for (const t of open.slice(0, 10)) {
|
|
1356
|
+
lines.push(`- 未完 [${t.status}] #${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ':' + clamp(t.note, 120) : ''}`)
|
|
1357
|
+
}
|
|
1358
|
+
for (const t of done.slice(-8)) {
|
|
1359
|
+
lines.push(`- 已完 #${t.id} ${t.title}${t.evidence ? '(证据:' + clamp(t.evidence, 140) + ')' : ''}`)
|
|
1360
|
+
}
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
if (memory.length > 0) {
|
|
1364
|
+
lines.push('', '【近期回合关键结论】')
|
|
1365
|
+
for (const m of memory.slice(-10)) {
|
|
1366
|
+
const cleaned = stripCheckpointNoise(m.title || m.text)
|
|
1367
|
+
if (cleaned) lines.push(`- [${m.section}] ${clamp(cleaned, 180)}`)
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
return lines.join('\n').trim()
|
|
1372
|
+
}
|
|
1373
|
+
|
|
1374
|
+
/** Deterministic structured bullet summary when no LLM key is configured or while first summary is warming up. */
|
|
1375
|
+
function buildFallbackNarrative({ board, facts, targets }) {
|
|
1376
|
+
const sections = []
|
|
1377
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1378
|
+
const blocked = tasks.filter(t => t.status === 'blocked')
|
|
1379
|
+
const doing = tasks.filter(t => t.status === 'doing')
|
|
1380
|
+
const todo = tasks.filter(t => t.status === 'todo')
|
|
1381
|
+
const done = tasks.filter(t => t.status === 'done')
|
|
1382
|
+
const workers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
|
|
1383
|
+
|
|
1384
|
+
const statusBullets = []
|
|
1385
|
+
if (board && board.objective) {
|
|
1386
|
+
statusBullets.push(`- 【总目标】${clamp(board.objective, 150)}`)
|
|
1387
|
+
}
|
|
1388
|
+
for (const b of blocked.slice(0, 4)) {
|
|
1389
|
+
statusBullets.push(`- 【受阻】${clamp(b.title, 70)}${b.note ? ' — ' + clamp(b.note, 70) : ''}`)
|
|
1390
|
+
}
|
|
1391
|
+
for (const d of doing.slice(0, 4)) {
|
|
1392
|
+
const who = d.subagent || d.owner ? `(@${shortAgentBriefName(d.subagent || d.owner)})` : ''
|
|
1393
|
+
statusBullets.push(`- 【推进中】${clamp(d.title, 72)}${who}`)
|
|
1394
|
+
}
|
|
1395
|
+
if (tasks.length > 0) {
|
|
1396
|
+
statusBullets.push(`- 【任务进度】已完成 ${done.length} 项 / 推进中 ${doing.length} 项 / 受阻 ${blocked.length} 项 / 待推进 ${todo.length} 项`)
|
|
1397
|
+
}
|
|
1398
|
+
if (workers.length > 0) {
|
|
1399
|
+
statusBullets.push(`- 【子代理团队】${summarizeSubagentsCompact(workers)}`)
|
|
1400
|
+
}
|
|
1401
|
+
if (statusBullets.length > 0) {
|
|
1402
|
+
sections.push('## 核心目标与态势\n' + statusBullets.join('\n'))
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
const otherFacts = facts.filter(f => f.category !== 'discipline' && f.category !== 'preference')
|
|
1406
|
+
const mem = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
1407
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
1408
|
+
.slice(-5)
|
|
1409
|
+
const progressBullets = [
|
|
1410
|
+
...otherFacts.slice(-5).map(f => `- 【结论】${clamp(stripCheckpointNoise(f.text), 130)}`),
|
|
1411
|
+
...mem.map(m => `- 【进展】${clamp(stripCheckpointNoise(m.title || m.text), 120)}`),
|
|
1412
|
+
]
|
|
1413
|
+
if (progressBullets.length > 0) {
|
|
1414
|
+
sections.push('## 关键结论与进展\n' + progressBullets.join('\n'))
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1418
|
+
const disciplines = facts.filter(f => f.category === 'discipline' || f.category === 'preference')
|
|
1419
|
+
const ruleBullets = []
|
|
1420
|
+
for (const f of (bounds.forbidden || []).slice(0, 6)) ruleBullets.push(`- 【禁止红线】${clamp(f, 110)}`)
|
|
1421
|
+
for (const a of (bounds.allowed || []).slice(0, 4)) ruleBullets.push(`- 【允许范围】${clamp(a, 110)}`)
|
|
1422
|
+
for (const n of (bounds.notes || []).slice(0, 3)) ruleBullets.push(`- 【注意事项】${clamp(n, 110)}`)
|
|
1423
|
+
for (const d of disciplines.slice(-5)) ruleBullets.push(`- 【协作纪律】${clamp(d.text, 120)}`)
|
|
1424
|
+
if (ruleBullets.length > 0) {
|
|
1425
|
+
sections.push('## 协作纪律与边界\n' + ruleBullets.join('\n'))
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
if (sections.length === 0) {
|
|
1429
|
+
return '## 尚无沉淀摘要\n- 【状态】当前会话刚启动,暂未沉淀阶段结论或红线纪律\n- 【用法】可在下方参谋栏直接立规矩、查进展,或用一句话拆话调度主对话与各子代理'
|
|
1430
|
+
}
|
|
1431
|
+
return sections.join('\n\n')
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
const summarizingLocks = new Map()
|
|
1435
|
+
|
|
1436
|
+
export async function getChiefView(deps, sessionId, { regenerate = false, autoSummarize = false } = {}) {
|
|
1437
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
1438
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
1439
|
+
const board = deps.boardForSession(deps.boardFileFor(rootId))
|
|
1440
|
+
const state = loadChiefState()
|
|
1441
|
+
const view = clusterView(state, rootId)
|
|
1442
|
+
const modelsInfo = await listChiefModels(deps, false, rootId)
|
|
1443
|
+
const paceMode = (state.config && state.config.paceMode) || 'manual'
|
|
1444
|
+
|
|
1445
|
+
const rawInput = buildNarrativeInput({
|
|
1446
|
+
board,
|
|
1447
|
+
facts: view.facts,
|
|
1448
|
+
cluster: directory.cluster,
|
|
1449
|
+
targets: directory.targets,
|
|
1450
|
+
})
|
|
1451
|
+
const inputHash = rawInput
|
|
1452
|
+
? crypto.createHash('sha256').update(SUMMARY_FORMAT_REV + '\n' + rawInput).digest('hex').slice(0, 24)
|
|
1453
|
+
: 'empty'
|
|
1454
|
+
|
|
1455
|
+
const hasSaved = Boolean(view.narrative && view.narrative.text)
|
|
1456
|
+
const lastSummaryAt = Number((view.narrative && view.narrative.at) || 0)
|
|
1457
|
+
const isFresh = !rawInput || (hasSaved && view.narrative.hash === inputHash)
|
|
1458
|
+
const cooledForAuto = Date.now() - lastSummaryAt >= AUTO_SUMMARY_COOLDOWN_MS
|
|
1459
|
+
const allowBackgroundSummary = paceMode === 'auto' && autoSummarize && !isFresh && cooledForAuto
|
|
1460
|
+
|
|
1461
|
+
// Human-paced rule: ONLY call LLM when operator explicitly clicked Regenerate (`regenerate: true`),
|
|
1462
|
+
// OR when operator explicitly chose `paceMode === 'auto'` AND the 5-minute cooldown has elapsed!
|
|
1463
|
+
if (rawInput && (regenerate || allowBackgroundSummary) && modelsInfo.available && !summarizingLocks.has(rootId)) {
|
|
1464
|
+
const job = (async () => {
|
|
1465
|
+
const res = await callChiefLlm(deps, {
|
|
1466
|
+
sessionId: rootId,
|
|
1467
|
+
system: NARRATIVE_SYSTEM,
|
|
1468
|
+
prompt: rawInput + '\n\n请按上述规范输出简体中文摘要:',
|
|
1469
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
1470
|
+
})
|
|
1471
|
+
if (res.ok && res.text) {
|
|
1472
|
+
mutateChiefState((s) => {
|
|
1473
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1474
|
+
ws.narrative = {
|
|
1475
|
+
hash: inputHash,
|
|
1476
|
+
text: res.text,
|
|
1477
|
+
at: Date.now(),
|
|
1478
|
+
byModel: res.modelRef || '',
|
|
1479
|
+
}
|
|
1480
|
+
})
|
|
1481
|
+
}
|
|
1482
|
+
})().finally(() => {
|
|
1483
|
+
summarizingLocks.delete(rootId)
|
|
1484
|
+
})
|
|
1485
|
+
summarizingLocks.set(rootId, job)
|
|
1486
|
+
if (regenerate) {
|
|
1487
|
+
await job.catch(() => {})
|
|
1488
|
+
}
|
|
1489
|
+
}
|
|
1490
|
+
|
|
1491
|
+
const latestState = loadChiefState()
|
|
1492
|
+
const latestView = clusterView(latestState, rootId)
|
|
1493
|
+
const hasLatestSaved = Boolean(latestView.narrative && latestView.narrative.text)
|
|
1494
|
+
const latestFresh = !rawInput || (hasLatestSaved && latestView.narrative.hash === inputHash)
|
|
1495
|
+
const narrativeText = hasLatestSaved
|
|
1496
|
+
? latestView.narrative.text
|
|
1497
|
+
: buildFallbackNarrative({ board, facts: latestView.facts, targets: directory.targets })
|
|
1498
|
+
|
|
1499
|
+
return {
|
|
1500
|
+
ok: true,
|
|
1501
|
+
rootId,
|
|
1502
|
+
config: latestState.config,
|
|
1503
|
+
models: modelsInfo,
|
|
1504
|
+
narrative: {
|
|
1505
|
+
text: narrativeText,
|
|
1506
|
+
at: hasLatestSaved ? (latestView.narrative.at || 0) : (board.updatedAt || 0),
|
|
1507
|
+
byModel: hasLatestSaved ? (latestView.narrative.byModel || '') : '',
|
|
1508
|
+
isLiveZeroToken: !hasLatestSaved,
|
|
1509
|
+
hasUnsummarizedChanges: Boolean(rawInput && !latestFresh),
|
|
1510
|
+
summarizing: summarizingLocks.has(rootId),
|
|
1511
|
+
fresh: latestFresh,
|
|
1512
|
+
},
|
|
1513
|
+
facts: latestView.facts.slice().reverse(),
|
|
1514
|
+
suggestions: latestView.suggestions.slice().reverse(),
|
|
1515
|
+
chat: latestView.chat.slice(-20),
|
|
1516
|
+
mailbox: latestView.mailbox.slice(-30).reverse(),
|
|
1517
|
+
peers: directory.targets,
|
|
1518
|
+
otherSessions: directory.otherSessions,
|
|
1519
|
+
cluster: directory.cluster,
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
/* -------------------------------------------------------------------------- */
|
|
1524
|
+
/* Chief Command Bar: All-Seeing Strategist + Relay + Bounds + Board Ops */
|
|
1525
|
+
/* -------------------------------------------------------------------------- */
|
|
1526
|
+
|
|
1527
|
+
const ASK_CHIEF_SYSTEM = [
|
|
1528
|
+
'你是「DSH 参谋长」(DSH Chief)——统揽主对话、子代理团队与跨窗口协同的全能参谋宰相。',
|
|
1529
|
+
'你**绝不只是**被动的记忆检索器或传话筒!你实时掌握:',
|
|
1530
|
+
'1) 主代理(@lead)与各子代理的**实时对话流快照**(刚刚说了什么、正在调什么工具、卡在哪里);',
|
|
1531
|
+
'2) 参谋看板总目标、实时断点游标(cursor)、计划(plan)与任务拓扑(推进中 / 受阻 / 待办 / 已完成证据);',
|
|
1532
|
+
'3) 双层工作边界(📌 定住全局跨任务共享边界 vs 仅当前任务边界)与持久记忆、便签、协同信箱。',
|
|
1533
|
+
'',
|
|
1534
|
+
'请精准洞悉用户意图(态势汇报、卡点诊断、战术参谋、拆话传话、代维护看板、记忆管理、提炼或浓缩零散边界),并**只输出一个合法 JSON 对象**:',
|
|
1535
|
+
'{',
|
|
1536
|
+
' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论` 列出(如【当前进展】【活跃现场】【受阻卡点】【下一步建议】),直给干货,绝不说『记忆里没有这条』,绝不堆砌废话或暴露内部 sessionId",',
|
|
1537
|
+
' "relays": [',
|
|
1538
|
+
' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行指令" }',
|
|
1539
|
+
' ],',
|
|
1540
|
+
' "memoryChanges": [',
|
|
1541
|
+
' { "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "一句独立完整的持久事实或规矩(不超过200字,绝不存密钥密码)" },',
|
|
1542
|
+
' { "op": "edit", "index": 2, "text": "替换第2条的新内容" },',
|
|
1543
|
+
' { "op": "remove", "index": 3 }',
|
|
1544
|
+
' ],',
|
|
1545
|
+
' "boundProposals": [',
|
|
1546
|
+
' {',
|
|
1547
|
+
' "field": "forbidden|allowed|notes",',
|
|
1548
|
+
' "item": "拟请示用户注入的一句话高密度边界条文",',
|
|
1549
|
+
' "reason": "撞墙教训、提炼依据或浓缩说明",',
|
|
1550
|
+
' "replaces": ["可选:当把多条零散边界浓缩合并成一条时,逐字列出被合并替代的原边界条文"],',
|
|
1551
|
+
' "pinGlobal": false',
|
|
1552
|
+
' }',
|
|
1553
|
+
' ],',
|
|
1554
|
+
' "boardOps": [',
|
|
1555
|
+
' { "op": "objective.set", "objective": "新总目标" },',
|
|
1556
|
+
' { "op": "task.add", "title": "任务名", "owner": "可选负责人", "priority": "high|normal|low" },',
|
|
1557
|
+
' { "op": "task.update", "id": "已有任务ID", "status": "todo|doing|blocked|done", "note": "可选进展或阻塞说明", "evidence": "可选完成证据", "owner": "可选负责人" },',
|
|
1558
|
+
' { "op": "cursor.set", "step": "当前步骤", "next": "下一步具体动作", "blocked": "阻塞点(无则空串)" },',
|
|
1559
|
+
' { "op": "bounds.forbid", "item": "用户明确下令立即写入的禁止红线", "pinGlobal": false },',
|
|
1560
|
+
' { "op": "bounds.allow", "item": "用户明确下令立即写入的允许范围", "pinGlobal": false }',
|
|
1561
|
+
' ]',
|
|
1562
|
+
'}',
|
|
1563
|
+
'',
|
|
1564
|
+
'宰相参谋与行事准则:',
|
|
1565
|
+
'- 【问进展 / 问卡点 / 求建议】:结合「实时对话流快照」+「任务图」+「断点游标」综合研判!就算模型还没把最新动作写进参谋看板,你也要从实时对话流里看出主代理和子代理正在干什么、刚跑了什么命令、取得了什么结论或卡在什么报错上,并主动给出 1~2 条切中要害的下一步建议。',
|
|
1566
|
+
'- 【代维护看板】:当用户让你「把某任务标为完成/受阻」「记一下下一步干啥」「改总目标」时,直接通过 `boardOps`(`task.update` / `cursor.set` / `objective.set` / `task.add`)落实。',
|
|
1567
|
+
'- 【该传必传、该记必记】:用户要求转告/催促/纠偏某代理时生成精准 `relays`(急切纠偏用 `steer`,派下一步用 `followup`,同步背景用 `silent`);用户立长期规矩或交代关键事实时写入 `memoryChanges`。',
|
|
1568
|
+
'- 【边界奏请与零散浓缩】:',
|
|
1569
|
+
' 1) 总结踩坑红线时,生成 `boundProposals` 呈交用户拍板(若用户提到「全局定住/以后所有任务都生效」则设 `"pinGlobal": true`);只有用户明确下令「直接写进禁止/允许边界」时才用 `boardOps`。',
|
|
1570
|
+
' 2) 当用户要求「把重要的零散边界总结成一条 / 合并重复边界」时,仔细阅读现有边界,保留关键命令名/路径/硬红线,浓缩为 1 条精炼总则放入 `boundProposals[0].item`,并把被它吸收替代的旧条文原样放进 `replaces` 数组(若被合并旧规中含 📌 全局定住项,则 `"pinGlobal": true`)。',
|
|
1571
|
+
].join('\n')
|
|
1572
|
+
|
|
1573
|
+
const CONSOLIDATE_BOUNDS_SYSTEM = [
|
|
1574
|
+
'你是「DSH 参谋长」(宰相级边界治理中枢)。用户的边界列表中积累了多条零散、重复或同一主题的规则。',
|
|
1575
|
+
'请将给定的多条零散边界**浓缩合并成唯一 1 条**高信息密度、表述清晰、可直接执行的精炼总则(不超过 180 字)。',
|
|
1576
|
+
'硬性要求:',
|
|
1577
|
+
'- 必须完整保留关键具象锚点(如禁止的具体命令 `git push` / `install_bundle`、具体目录路径、权限红线),绝不能浓缩成空洞套话!',
|
|
1578
|
+
'- 用紧凑的分号或并列短句收纳核心约束,去除重复啰嗦的铺垫词。',
|
|
1579
|
+
'- **只输出一个合法 JSON 对象**:',
|
|
1580
|
+
'{',
|
|
1581
|
+
' "item": "浓缩合并后的单条精炼边界总则(≤180字)",',
|
|
1582
|
+
' "reason": "简述合并了哪几类零散约束(≤70字)"',
|
|
1583
|
+
'}',
|
|
1584
|
+
].join('\n')
|
|
1585
|
+
|
|
1586
|
+
/**
|
|
1587
|
+
* Inspect live in-memory conversation streams (`agent.session.deriveMessages()`)
|
|
1588
|
+
* across `@lead` and active/recent `@subagents` so DSH Chief has real-time
|
|
1589
|
+
* situational awareness even before a turn settles into `board.tasks` or `board.memory`.
|
|
1590
|
+
*/
|
|
1591
|
+
function collectLiveConversationsDigest(deps, rootId, directory) {
|
|
1592
|
+
const entries = []
|
|
1593
|
+
const runtime = deps && deps.runtime
|
|
1594
|
+
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
1595
|
+
if (!agentsSvc || typeof agentsSvc.get !== 'function') {
|
|
1596
|
+
return { entries, summaryLines: [] }
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
const allTargets = Array.isArray(directory && directory.targets) ? directory.targets : []
|
|
1600
|
+
// Filter out idle internal checkpoint probes (`mnemon-review-*`) so real workers stand out
|
|
1601
|
+
const meaningfulTargets = allTargets.filter(t => {
|
|
1602
|
+
if (!t || !t.id) return false
|
|
1603
|
+
if (t.kind === 'lead') return true
|
|
1604
|
+
if (t.status === 'running') return true
|
|
1605
|
+
return !/^mnemon-review/i.test(String(t.name || t.handle || ''))
|
|
1606
|
+
})
|
|
1607
|
+
|
|
1608
|
+
// Prioritize: lead first, then running subagents/peers, then up to 4 recent workers
|
|
1609
|
+
const ordered = [
|
|
1610
|
+
...meaningfulTargets.filter(t => t.kind === 'lead'),
|
|
1611
|
+
...meaningfulTargets.filter(t => t.kind !== 'lead' && t.status === 'running'),
|
|
1612
|
+
...meaningfulTargets.filter(t => t.kind !== 'lead' && t.status !== 'running'),
|
|
1613
|
+
].slice(0, 6)
|
|
1614
|
+
|
|
1615
|
+
if (!ordered.length && rootId) {
|
|
1616
|
+
ordered.push({ key: 'lead', id: rootId, handle: 'lead', name: '主对话', kind: 'lead', status: 'idle', taskTitle: '' })
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
for (const peer of ordered) {
|
|
1620
|
+
let agent = null
|
|
1621
|
+
try {
|
|
1622
|
+
agent = agentsSvc.get(peer.id)
|
|
1623
|
+
} catch {}
|
|
1624
|
+
if (!agent || !agent.session || typeof agent.session.deriveMessages !== 'function') continue
|
|
1625
|
+
|
|
1626
|
+
let msgs = []
|
|
1627
|
+
try {
|
|
1628
|
+
msgs = agent.session.deriveMessages() || []
|
|
1629
|
+
} catch {
|
|
1630
|
+
continue
|
|
1631
|
+
}
|
|
1632
|
+
if (!Array.isArray(msgs) || !msgs.length) continue
|
|
1633
|
+
|
|
1634
|
+
const liveStatus = agent.status === 'running' ? 'running' : (peer.status || 'idle')
|
|
1635
|
+
let lastUser = ''
|
|
1636
|
+
const recentAssistant = []
|
|
1637
|
+
const recentTools = []
|
|
1638
|
+
|
|
1639
|
+
const tail = msgs.slice(-8)
|
|
1640
|
+
for (const m of tail) {
|
|
1641
|
+
if (!m || !m.role) continue
|
|
1642
|
+
const isInjected = m.source && m.source.kind && m.source.kind !== 'user'
|
|
1643
|
+
const blocks = Array.isArray(m.content)
|
|
1644
|
+
? m.content
|
|
1645
|
+
: (typeof m.content === 'string' ? [{ type: 'text', text: m.content }] : [])
|
|
1646
|
+
|
|
1647
|
+
const textParts = []
|
|
1648
|
+
for (const b of blocks) {
|
|
1649
|
+
if (!b || typeof b !== 'object') continue
|
|
1650
|
+
if (b.type === 'text' && typeof b.text === 'string') {
|
|
1651
|
+
textParts.push(b.text)
|
|
1652
|
+
} else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
|
|
1653
|
+
const tName = String(b.name || b.toolName)
|
|
1654
|
+
let argHint = ''
|
|
1655
|
+
try {
|
|
1656
|
+
const rawArgs = b.input || b.arguments || b.args
|
|
1657
|
+
const obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs
|
|
1658
|
+
if (obj && typeof obj === 'object') {
|
|
1659
|
+
const keyVal = obj.command || obj.cmd || obj.action || obj.path || obj.file_path || obj.query || obj.url || obj.agent || obj.title || ''
|
|
1660
|
+
if (keyVal && !secretLike(String(keyVal))) argHint = clamp(String(keyVal), 48)
|
|
1661
|
+
}
|
|
1662
|
+
} catch {}
|
|
1663
|
+
recentTools.push(argHint ? `${tName}(${argHint})` : tName)
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
|
|
1667
|
+
const txt = stripCheckpointNoise(textParts.join('\n').trim())
|
|
1668
|
+
if (!txt || isInternalCheckpointNoise(txt) || secretLike(txt)) continue
|
|
1669
|
+
|
|
1670
|
+
if (m.role === 'user' && !isInjected) {
|
|
1671
|
+
lastUser = clamp(txt, 260)
|
|
1672
|
+
} else if (m.role === 'assistant') {
|
|
1673
|
+
recentAssistant.push(clamp(txt, 380))
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
|
|
1677
|
+
if (!lastUser && !recentAssistant.length && !recentTools.length) continue
|
|
1678
|
+
entries.push({
|
|
1679
|
+
key: peer.key,
|
|
1680
|
+
handle: peer.handle || peer.name || peer.key,
|
|
1681
|
+
kind: peer.kind,
|
|
1682
|
+
status: liveStatus,
|
|
1683
|
+
taskTitle: peer.taskTitle || '',
|
|
1684
|
+
lastUser,
|
|
1685
|
+
lastAssistant: recentAssistant.length ? recentAssistant[recentAssistant.length - 1] : '',
|
|
1686
|
+
recentTools: recentTools.slice(-4),
|
|
1687
|
+
})
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
const summaryLines = entries.map((e) => {
|
|
1691
|
+
const parts = [`- **@${e.handle}** [${e.status === 'running' ? '🟢运行中' : '⚪空闲'}]${e.taskTitle ? '(负责:' + clamp(e.taskTitle, 48) + ')' : ''}`]
|
|
1692
|
+
if (e.lastUser) parts.push(` · 最近用户指令:${e.lastUser}`)
|
|
1693
|
+
if (e.recentTools.length) parts.push(` · 近期工具动作:${e.recentTools.join(' → ')}`)
|
|
1694
|
+
if (e.lastAssistant) parts.push(` · 最新回复/进展:${e.lastAssistant}`)
|
|
1695
|
+
return parts.join('\n')
|
|
1696
|
+
})
|
|
1697
|
+
|
|
1698
|
+
return { entries, summaryLines }
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function extractJsonObject(raw) {
|
|
1702
|
+
const text = String(raw || '').trim()
|
|
1703
|
+
if (!text) return null
|
|
1704
|
+
const stripped = text.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim()
|
|
1705
|
+
try {
|
|
1706
|
+
const direct = JSON.parse(stripped)
|
|
1707
|
+
if (direct && typeof direct === 'object') return direct
|
|
1708
|
+
} catch {}
|
|
1709
|
+
const first = text.indexOf('{')
|
|
1710
|
+
const last = text.lastIndexOf('}')
|
|
1711
|
+
if (first !== -1 && last > first) {
|
|
1712
|
+
try {
|
|
1713
|
+
const sliced = JSON.parse(text.slice(first, last + 1))
|
|
1714
|
+
if (sliced && typeof sliced === 'object') return sliced
|
|
1715
|
+
} catch {}
|
|
1716
|
+
}
|
|
1717
|
+
return null
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
function applyFactChanges(ws, numberedFacts, changes, actor = 'user') {
|
|
1721
|
+
const applied = []
|
|
1722
|
+
if (!Array.isArray(changes) || !changes.length) return applied
|
|
1723
|
+
|
|
1724
|
+
for (const ch of changes.slice(0, 12)) {
|
|
1725
|
+
if (!ch || typeof ch !== 'object') continue
|
|
1726
|
+
const op = String(ch.op || '').trim()
|
|
1727
|
+
if (op === 'add') {
|
|
1728
|
+
const fact = normalizeFact({
|
|
1729
|
+
text: ch.text,
|
|
1730
|
+
category: ch.category || 'discipline',
|
|
1731
|
+
by: actor,
|
|
1732
|
+
source: 'chief',
|
|
1733
|
+
})
|
|
1734
|
+
if (!fact) continue
|
|
1735
|
+
const dup = ws.facts.find(f => f.text === fact.text)
|
|
1736
|
+
if (dup) {
|
|
1737
|
+
dup.updatedAt = Date.now()
|
|
1738
|
+
continue
|
|
1739
|
+
}
|
|
1740
|
+
ws.facts.push(fact)
|
|
1741
|
+
if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
|
|
1742
|
+
applied.push({ op: 'add', text: fact.text })
|
|
1743
|
+
} else if (op === 'edit') {
|
|
1744
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
1745
|
+
const nextText = clamp(ch.text, FACT_TEXT_MAX)
|
|
1746
|
+
if (!target || !nextText || secretLike(nextText)) continue
|
|
1747
|
+
const found = ws.facts.find(f => f.id === target.id)
|
|
1748
|
+
if (found && !found.pinned) {
|
|
1749
|
+
found.text = nextText
|
|
1750
|
+
found.updatedAt = Date.now()
|
|
1751
|
+
applied.push({ op: 'edit', text: nextText })
|
|
1752
|
+
}
|
|
1753
|
+
} else if (op === 'remove') {
|
|
1754
|
+
const target = numberedFacts[Number(ch.index) - 1]
|
|
1755
|
+
if (!target) continue
|
|
1756
|
+
const idx = ws.facts.findIndex(f => f.id === target.id)
|
|
1757
|
+
if (idx !== -1 && !ws.facts[idx].pinned) {
|
|
1758
|
+
const [removed] = ws.facts.splice(idx, 1)
|
|
1759
|
+
applied.push({ op: 'remove', text: removed.text })
|
|
1760
|
+
}
|
|
1761
|
+
}
|
|
1762
|
+
}
|
|
1763
|
+
return applied
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1766
|
+
function applyBoardOps(deps, rootId, boardOps) {
|
|
1767
|
+
const executed = []
|
|
1768
|
+
if (!Array.isArray(boardOps) || !boardOps.length) return executed
|
|
1769
|
+
|
|
1770
|
+
for (const opItem of boardOps.slice(0, 10)) {
|
|
1771
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
1772
|
+
const op = String(opItem.op || '').trim()
|
|
1773
|
+
if (op === 'objective.set' && opItem.objective) {
|
|
1774
|
+
deps.runAction({ action: 'objective.set', objective: String(opItem.objective), session: rootId, by: 'chief' })
|
|
1775
|
+
executed.push('更新目标:' + clamp(opItem.objective, 40))
|
|
1776
|
+
} else if (op === 'task.add' && opItem.title) {
|
|
1777
|
+
deps.runAction({
|
|
1778
|
+
action: 'task.add',
|
|
1779
|
+
title: String(opItem.title),
|
|
1780
|
+
owner: opItem.owner ? String(opItem.owner) : '',
|
|
1781
|
+
subagent: opItem.owner ? String(opItem.owner) : '',
|
|
1782
|
+
priority: opItem.priority || 'normal',
|
|
1783
|
+
session: rootId,
|
|
1784
|
+
by: 'chief',
|
|
1785
|
+
})
|
|
1786
|
+
executed.push('新增任务:' + clamp(opItem.title, 40))
|
|
1787
|
+
} else if (op === 'task.update' && (opItem.id || opItem.taskId)) {
|
|
1788
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
1789
|
+
const res = deps.runAction({
|
|
1790
|
+
action: 'task.update',
|
|
1791
|
+
id: tid,
|
|
1792
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
1793
|
+
...(typeof opItem.note === 'string' ? { note: opItem.note } : {}),
|
|
1794
|
+
...(typeof opItem.evidence === 'string' ? { evidence: opItem.evidence } : {}),
|
|
1795
|
+
...(typeof opItem.owner === 'string' ? { owner: opItem.owner } : {}),
|
|
1796
|
+
session: rootId,
|
|
1797
|
+
by: 'chief',
|
|
1798
|
+
})
|
|
1799
|
+
if (res && res.ok) executed.push(`更新任务 #${tid}${opItem.status ? ' → ' + opItem.status : ''}`)
|
|
1800
|
+
} else if (op === 'cursor.set') {
|
|
1801
|
+
const res = deps.runAction({
|
|
1802
|
+
action: 'cursor.set',
|
|
1803
|
+
...(typeof opItem.step === 'string' ? { step: opItem.step } : {}),
|
|
1804
|
+
...(typeof opItem.next === 'string' ? { next: opItem.next } : {}),
|
|
1805
|
+
...(typeof opItem.blocked === 'string' ? { blocked: opItem.blocked } : {}),
|
|
1806
|
+
session: rootId,
|
|
1807
|
+
by: 'chief',
|
|
1808
|
+
})
|
|
1809
|
+
if (res && res.ok) executed.push('更新推进断点')
|
|
1810
|
+
} else if ((op === 'bounds.forbid' || op === 'bounds.allow') && opItem.item) {
|
|
1811
|
+
const field = op === 'bounds.forbid' ? 'forbidden' : 'allowed'
|
|
1812
|
+
const val = clamp(opItem.item, 220)
|
|
1813
|
+
const pinned = Boolean(opItem.pinGlobal)
|
|
1814
|
+
if (val) {
|
|
1815
|
+
const res = deps.runAction({
|
|
1816
|
+
action: 'bounds.add',
|
|
1817
|
+
field,
|
|
1818
|
+
item: val,
|
|
1819
|
+
pinned,
|
|
1820
|
+
session: rootId,
|
|
1821
|
+
by: 'chief',
|
|
1822
|
+
})
|
|
1823
|
+
if (res && res.ok) {
|
|
1824
|
+
executed.push(`${pinned ? '📌全局' : '本任务'}${field === 'forbidden' ? '红线' : '允许'}:${clamp(val, 30)}`)
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
}
|
|
1829
|
+
return executed
|
|
1830
|
+
}
|
|
1831
|
+
|
|
1832
|
+
/**
|
|
1833
|
+
* Holistic offline/fallback intelligence synthesizer so DSH Chief NEVER
|
|
1834
|
+
* utters "记忆里没有这条" even if every configured LLM provider is unreachable.
|
|
1835
|
+
*/
|
|
1836
|
+
function buildSmartFallbackReply({ input, board, liveDigest, directory, facts = [], mailbox = [] }) {
|
|
1837
|
+
const q = String(input || '').trim()
|
|
1838
|
+
const qLower = q.toLowerCase()
|
|
1839
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1840
|
+
const doing = tasks.filter(t => t.status === 'doing')
|
|
1841
|
+
const blocked = tasks.filter(t => t.status === 'blocked')
|
|
1842
|
+
const todo = tasks.filter(t => t.status === 'todo')
|
|
1843
|
+
const done = tasks.filter(t => t.status === 'done')
|
|
1844
|
+
const cursor = (board && board.cursor) || {}
|
|
1845
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1846
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1847
|
+
const workers = ((directory && directory.targets) || []).filter(t => t.kind === 'subagent')
|
|
1848
|
+
const runningWorkers = workers.filter(w => w.status === 'running')
|
|
1849
|
+
const liveEntries = (liveDigest && liveDigest.entries) || []
|
|
1850
|
+
const leadLive = liveEntries.find(e => e.kind === 'lead') || liveEntries[0] || null
|
|
1851
|
+
const cleanMem = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
1852
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
1853
|
+
|
|
1854
|
+
const asksBounds = /边界|红线|禁止|允许|规矩|约束/.test(q)
|
|
1855
|
+
const asksTeam = /子代理|团队|谁在|分工|成员|subagent|worker/i.test(qLower)
|
|
1856
|
+
const asksBlocked = /卡在哪|受阻|阻塞|报错|问题|风险|撞墙|block/i.test(qLower)
|
|
1857
|
+
const asksProgress = /进展|进度|怎么样|到哪|在干嘛|干什么|情况|状态|汇报|总结|下一步|status|progress/i.test(qLower)
|
|
1858
|
+
|
|
1859
|
+
const bullets = []
|
|
1860
|
+
|
|
1861
|
+
if (asksBounds) {
|
|
1862
|
+
const fList = bounds.forbidden || []
|
|
1863
|
+
const aList = bounds.allowed || []
|
|
1864
|
+
const nList = bounds.notes || []
|
|
1865
|
+
const pinCount = (pinnedBounds.forbidden?.length || 0) + (pinnedBounds.allowed?.length || 0) + (pinnedBounds.notes?.length || 0)
|
|
1866
|
+
bullets.push(`- 【生效边界概览】共 ${fList.length + aList.length + nList.length} 条生效(其中 📌 定住全局共享 ${pinCount} 条)。`)
|
|
1867
|
+
if (fList.length) bullets.push(`- 【禁止红线】${fList.slice(0, 5).map(x => (pinnedBounds.forbidden?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
1868
|
+
if (aList.length) bullets.push(`- 【允许范围】${aList.slice(0, 4).map(x => (pinnedBounds.allowed?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
1869
|
+
if (nList.length) bullets.push(`- 【注意事项】${nList.slice(0, 3).map(x => (pinnedBounds.notes?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
1870
|
+
if (!fList.length && !aList.length && !nList.length) {
|
|
1871
|
+
bullets.push('- 【提示】当前尚未配置边界规则,可在「边界」页添加并点击 📌 定住为跨任务共享,或点「✦ 提炼新边界」。')
|
|
1872
|
+
}
|
|
1873
|
+
return bullets.join('\n')
|
|
1874
|
+
}
|
|
1875
|
+
|
|
1876
|
+
if (asksTeam && !asksProgress) {
|
|
1877
|
+
bullets.push(`- 【团队编制】${workers.length ? summarizeSubagentsCompact(workers) : '当前仅主代理(@lead)单线作业,尚未派生子代理。'}`)
|
|
1878
|
+
for (const w of runningWorkers.slice(0, 5)) {
|
|
1879
|
+
bullets.push(`- 【运行中 · @${shortAgentBriefName(w.handle)}】${w.taskTitle ? clamp(w.taskTitle, 80) : '正在执行委派任务'}`)
|
|
1880
|
+
}
|
|
1881
|
+
for (const e of liveEntries.filter(x => x.kind !== 'lead').slice(0, 3)) {
|
|
1882
|
+
if (e.lastAssistant || e.recentTools.length) {
|
|
1883
|
+
bullets.push(`- 【@${shortAgentBriefName(e.handle)} 现场】${e.recentTools.length ? '调用 ' + e.recentTools.join(' → ') + ';' : ''}${clamp(e.lastAssistant, 100)}`)
|
|
1884
|
+
}
|
|
1885
|
+
}
|
|
1886
|
+
return bullets.join('\n')
|
|
1887
|
+
}
|
|
1888
|
+
|
|
1889
|
+
// Keyword match across tasks, facts, notes, live stream, and memory if user asked a specific domain question
|
|
1890
|
+
if (!asksProgress && !asksBlocked) {
|
|
1891
|
+
const tokens = qLower
|
|
1892
|
+
.replace(/[??!!。,,、::“”"'()()[\]【】]/g, ' ')
|
|
1893
|
+
.split(/\s+/)
|
|
1894
|
+
.filter(t => t.length >= 2 && !/^(现在|目前|什么|怎么|请问|帮我|一下|看看|告诉)$/.test(t))
|
|
1895
|
+
|
|
1896
|
+
const hits = []
|
|
1897
|
+
for (const t of tasks) {
|
|
1898
|
+
const hay = `${t.title} ${t.note || ''} ${t.evidence || ''}`.toLowerCase()
|
|
1899
|
+
if (tokens.some(tk => hay.includes(tk))) {
|
|
1900
|
+
hits.push(`- 【任务 #${t.id} · ${t.status}】${clamp(t.title, 65)}${t.evidence ? '(证据:' + clamp(t.evidence, 70) + ')' : t.note ? '(' + clamp(t.note, 70) + ')' : ''}`)
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
for (const f of facts) {
|
|
1904
|
+
if (tokens.some(tk => String(f.text || '').toLowerCase().includes(tk))) {
|
|
1905
|
+
hits.push(`- 【持久记录】${clamp(f.text, 120)}`)
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
for (const m of cleanMem.slice(-15)) {
|
|
1909
|
+
const txt = stripCheckpointNoise(m.title || m.text)
|
|
1910
|
+
if (tokens.some(tk => txt.toLowerCase().includes(tk))) {
|
|
1911
|
+
hits.push(`- 【近期回合】${clamp(txt, 120)}`)
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
if (hits.length > 0) {
|
|
1915
|
+
return hits.slice(0, 6).join('\n')
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
// Comprehensive Live Situation & Progress Briefing (default + asksProgress + asksBlocked)
|
|
1920
|
+
if (board && board.objective) {
|
|
1921
|
+
bullets.push(`- 【核心目标】${clamp(board.objective, 130)}`)
|
|
1922
|
+
}
|
|
1923
|
+
if (cursor.step || cursor.next || cursor.blocked) {
|
|
1924
|
+
const curParts = []
|
|
1925
|
+
if (cursor.step) curParts.push(`正在推进「${clamp(cursor.step, 70)}」`)
|
|
1926
|
+
if (cursor.blocked) curParts.push(`卡点:${clamp(cursor.blocked, 80)}`)
|
|
1927
|
+
if (cursor.next) curParts.push(`下一步:${clamp(cursor.next, 80)}`)
|
|
1928
|
+
bullets.push(`- 【实时断点】${curParts.join(';')}`)
|
|
1929
|
+
}
|
|
1930
|
+
if (tasks.length > 0) {
|
|
1931
|
+
bullets.push(`- 【任务盘点】共 ${tasks.length} 项:🟢推进中 ${doing.length} · 🔴受阻 ${blocked.length} · ⏳待办 ${todo.length} · ✅已完成 ${done.length}`)
|
|
1932
|
+
for (const b of blocked.slice(0, 3)) {
|
|
1933
|
+
bullets.push(`- 【🔴 受阻卡点】#${b.id} ${clamp(b.title, 64)}${b.note ? ' — ' + clamp(b.note, 85) : ''}`)
|
|
1934
|
+
}
|
|
1935
|
+
for (const d of doing.slice(0, 3)) {
|
|
1936
|
+
const ownerTag = d.subagent || d.owner ? `(@${shortAgentBriefName(d.subagent || d.owner)})` : ''
|
|
1937
|
+
bullets.push(`- 【🟢 正在推进】#${d.id} ${clamp(d.title, 68)}${ownerTag}${d.note ? ':' + clamp(d.note, 65) : ''}`)
|
|
1938
|
+
}
|
|
1939
|
+
if (!doing.length && !blocked.length && done.length > 0) {
|
|
1940
|
+
const lastDone = done[done.length - 1]
|
|
1941
|
+
bullets.push(`- 【最近完工】#${lastDone.id} ${clamp(lastDone.title, 68)}${lastDone.evidence ? '(' + clamp(lastDone.evidence, 80) + ')' : ''}`)
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
if (runningWorkers.length > 0) {
|
|
1945
|
+
bullets.push(`- 【活跃子代理】${runningWorkers.length} 名正在运行:${runningWorkers.slice(0, 4).map(w => '@' + shortAgentBriefName(w.handle) + (w.taskTitle ? '(' + clamp(w.taskTitle, 32) + ')' : '')).join('、')}`)
|
|
1946
|
+
}
|
|
1947
|
+
if (leadLive && (leadLive.lastAssistant || leadLive.recentTools.length || leadLive.lastUser)) {
|
|
1948
|
+
const toolStr = leadLive.recentTools.length ? `刚执行 ${leadLive.recentTools.slice(-3).join(' → ')};` : ''
|
|
1949
|
+
const msgStr = leadLive.lastAssistant
|
|
1950
|
+
? clamp(leadLive.lastAssistant, 140)
|
|
1951
|
+
: (leadLive.lastUser ? `收到指令「${clamp(leadLive.lastUser, 90)}」` : '')
|
|
1952
|
+
bullets.push(`- 【主对话现场 (${leadLive.status === 'running' ? '运行中' : '就绪'})】${toolStr}${msgStr}`)
|
|
1953
|
+
} else if (cleanMem.length > 0) {
|
|
1954
|
+
const latest = stripCheckpointNoise(cleanMem[cleanMem.length - 1].title || cleanMem[cleanMem.length - 1].text)
|
|
1955
|
+
if (latest) bullets.push(`- 【最新回合结论】${clamp(latest, 140)}`)
|
|
1956
|
+
}
|
|
1957
|
+
if (mailbox.length > 0) {
|
|
1958
|
+
const lastMail = mailbox[mailbox.length - 1]
|
|
1959
|
+
if (lastMail && lastMail.text) {
|
|
1960
|
+
bullets.push(`- 【最新协同通信】${lastMail.from || '成员'} → @${lastMail.to || 'lead'}:${clamp(lastMail.text, 90)}`)
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
|
|
1964
|
+
// Tactical next-step suggestion
|
|
1965
|
+
if (blocked.length > 0) {
|
|
1966
|
+
bullets.push(`- 【参谋建议】当前有 ${blocked.length} 项任务受阻,建议优先排障 #${blocked[0].id},或让我直接向主代理/对应子代理插话调整方案。`)
|
|
1967
|
+
} else if (doing.length > 0 || runningWorkers.length > 0) {
|
|
1968
|
+
bullets.push('- 【参谋建议】主线正在推进中;如需纠偏方向或补充约束,可直接告诉我「让 @某成员 注意……」,我立即替你插话传达。')
|
|
1969
|
+
} else if (todo.length > 0) {
|
|
1970
|
+
bullets.push(`- 【参谋建议】当前无运行中代理,尚有 ${todo.length} 项待办(首项:#${todo[0].id} ${clamp(todo[0].title, 40)}),可吩咐主对话继续推进。`)
|
|
1971
|
+
} else if (!bullets.length) {
|
|
1972
|
+
bullets.push('- 【当前态势】本会话尚未开始任务或记录目标;你可以直接在主对话下达任务,或在下方让我替你立目标、定边界、派分工。')
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
return bullets.join('\n')
|
|
1976
|
+
}
|
|
1977
|
+
|
|
1978
|
+
function deterministicConsolidateClauses(items) {
|
|
1979
|
+
const seen = new Set()
|
|
1980
|
+
const clauses = []
|
|
1981
|
+
for (const raw of items) {
|
|
1982
|
+
const parts = String(raw || '')
|
|
1983
|
+
.split(/[;;。\n]+/)
|
|
1984
|
+
.map(s => s.replace(/^[•·\-*\d.)\s📌]+/, '').trim())
|
|
1985
|
+
.filter(Boolean)
|
|
1986
|
+
for (const p of parts) {
|
|
1987
|
+
const norm = p.toLowerCase().replace(/\s+/g, '')
|
|
1988
|
+
if (!norm || seen.has(norm)) continue
|
|
1989
|
+
if ([...seen].some(existing => existing.includes(norm) || (norm.length > 6 && norm.includes(existing)))) {
|
|
1990
|
+
if (norm.length > 6) {
|
|
1991
|
+
for (const ex of [...seen]) {
|
|
1992
|
+
if (norm.includes(ex) && norm !== ex) {
|
|
1993
|
+
const idx = clauses.findIndex(c => c.toLowerCase().replace(/\s+/g, '') === ex)
|
|
1994
|
+
if (idx !== -1) {
|
|
1995
|
+
clauses[idx] = p
|
|
1996
|
+
seen.delete(ex)
|
|
1997
|
+
seen.add(norm)
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
}
|
|
2001
|
+
}
|
|
2002
|
+
continue
|
|
2003
|
+
}
|
|
2004
|
+
seen.add(norm)
|
|
2005
|
+
clauses.push(p)
|
|
2006
|
+
}
|
|
2007
|
+
}
|
|
2008
|
+
return clamp(clauses.join(';'), 220)
|
|
2009
|
+
}
|
|
2010
|
+
|
|
2011
|
+
/**
|
|
2012
|
+
* Consolidate multiple scattered/overlapping boundary rules into ONE concise master rule,
|
|
2013
|
+
* creating a pending Prime Minister approval card (`replaces: sourceItems`) so the user
|
|
2014
|
+
* can approve & optionally pin it globally (`📌 定住全局`).
|
|
2015
|
+
*/
|
|
2016
|
+
export async function consolidateBoundsWithChief(deps, {
|
|
2017
|
+
sessionId = '',
|
|
2018
|
+
field = '',
|
|
2019
|
+
items = [],
|
|
2020
|
+
instruction = '',
|
|
2021
|
+
} = {}) {
|
|
2022
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
2023
|
+
const board = deps.boardForSession && deps.boardFileFor
|
|
2024
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2025
|
+
: { bounds: { allowed: [], forbidden: [], notes: [] }, pinnedBounds: { allowed: [], forbidden: [], notes: [] } }
|
|
2026
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2027
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2028
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '允许范围', notes: '注意事项' }
|
|
2029
|
+
|
|
2030
|
+
// Determine which column(s) to consolidate
|
|
2031
|
+
const targetCols = []
|
|
2032
|
+
const explicitItems = Array.isArray(items)
|
|
2033
|
+
? items.map(x => String(x || '').trim()).filter(Boolean)
|
|
2034
|
+
: []
|
|
2035
|
+
|
|
2036
|
+
if (['forbidden', 'allowed', 'notes'].includes(field)) {
|
|
2037
|
+
const colList = Array.isArray(bounds[field]) ? bounds[field] : []
|
|
2038
|
+
const chosen = explicitItems.length >= 2
|
|
2039
|
+
? colList.filter(x => explicitItems.includes(x))
|
|
2040
|
+
: colList
|
|
2041
|
+
if (chosen.length < 2) {
|
|
2042
|
+
return { ok: false, error: `【${BOUND_COL_LABEL[field]}】当前不足 2 条规则,无需浓缩合并。` }
|
|
2043
|
+
}
|
|
2044
|
+
targetCols.push({ col: field, sourceItems: chosen })
|
|
2045
|
+
} else if (explicitItems.length >= 2) {
|
|
2046
|
+
// Infer column with most matches, default forbidden
|
|
2047
|
+
let bestCol = 'forbidden'
|
|
2048
|
+
let bestHits = -1
|
|
2049
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
2050
|
+
const hits = (bounds[c] || []).filter(x => explicitItems.includes(x)).length
|
|
2051
|
+
if (hits > bestHits) {
|
|
2052
|
+
bestHits = hits
|
|
2053
|
+
bestCol = c
|
|
2054
|
+
}
|
|
2055
|
+
}
|
|
2056
|
+
targetCols.push({ col: bestCol, sourceItems: explicitItems })
|
|
2057
|
+
} else {
|
|
2058
|
+
for (const c of ['forbidden', 'allowed', 'notes']) {
|
|
2059
|
+
const colList = Array.isArray(bounds[c]) ? bounds[c] : []
|
|
2060
|
+
if (colList.length >= 2) {
|
|
2061
|
+
targetCols.push({ col: c, sourceItems: colList })
|
|
2062
|
+
}
|
|
2063
|
+
}
|
|
2064
|
+
if (!targetCols.length) {
|
|
2065
|
+
return { ok: false, error: '当前各边界分栏均不足 2 条零散规则,暂时无需合并。' }
|
|
2066
|
+
}
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
const createdProposals = []
|
|
2070
|
+
for (const { col, sourceItems } of targetCols) {
|
|
2071
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
2072
|
+
const hadPinned = sourceItems.some(x => (pinnedBounds[col] || []).includes(x))
|
|
2073
|
+
const prompt = [
|
|
2074
|
+
`目标边界分栏:【${colLabel}】(${col})`,
|
|
2075
|
+
instruction ? `用户额外要求:${clamp(instruction, 200)}` : '',
|
|
2076
|
+
`待浓缩合并的 ${sourceItems.length} 条零散边界:`,
|
|
2077
|
+
...sourceItems.map((it, idx) => `${idx + 1}. ${(pinnedBounds[col] || []).includes(it) ? '[📌全局定住] ' : ''}${it}`),
|
|
2078
|
+
'',
|
|
2079
|
+
'请将以上零散规则浓缩合并为唯一 1 条高密度总则(保留具体命令、路径与硬红线),只输出 JSON:',
|
|
2080
|
+
].filter(Boolean).join('\n')
|
|
2081
|
+
|
|
2082
|
+
const llmRes = await callChiefLlm(deps, {
|
|
2083
|
+
sessionId: rootId,
|
|
2084
|
+
system: CONSOLIDATE_BOUNDS_SYSTEM,
|
|
2085
|
+
prompt,
|
|
2086
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
2087
|
+
})
|
|
2088
|
+
|
|
2089
|
+
const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
2090
|
+
const mergedText = clamp(
|
|
2091
|
+
(parsed && (parsed.item || parsed.draftText || parsed.text)) || deterministicConsolidateClauses(sourceItems),
|
|
2092
|
+
220,
|
|
2093
|
+
)
|
|
2094
|
+
const mergedReason = clamp(
|
|
2095
|
+
(parsed && parsed.reason) || `已将【${colLabel}】下 ${sourceItems.length} 条零散边界浓缩合成为 1 条总则,批准后自动替换原零散条目。`,
|
|
2096
|
+
180,
|
|
2097
|
+
)
|
|
2098
|
+
|
|
2099
|
+
if (!mergedText || secretLike(mergedText)) continue
|
|
2100
|
+
|
|
2101
|
+
mutateChiefState((s) => {
|
|
2102
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2103
|
+
// Dismiss older pending consolidation proposals for the exact same column to avoid clutter
|
|
2104
|
+
for (const existing of ws.suggestions) {
|
|
2105
|
+
if (existing.status === 'pending' && existing.kind === 'bound' && existing.boundField === col && Array.isArray(existing.replaces) && existing.replaces.length > 0) {
|
|
2106
|
+
existing.status = 'dismissed'
|
|
2107
|
+
}
|
|
2108
|
+
}
|
|
2109
|
+
const sug = normalizeSuggestion({
|
|
2110
|
+
kind: 'bound',
|
|
2111
|
+
boundField: col,
|
|
2112
|
+
fromAgent: '✦ 参谋长浓缩',
|
|
2113
|
+
title: `${colLabel} ${sourceItems.length} 合 1:${clamp(mergedText, 26)}`,
|
|
2114
|
+
reason: mergedReason,
|
|
2115
|
+
target: 'bounds',
|
|
2116
|
+
targetLabel: colLabel,
|
|
2117
|
+
mode: 'silent',
|
|
2118
|
+
draftText: mergedText,
|
|
2119
|
+
replaces: sourceItems,
|
|
2120
|
+
pinGlobal: hadPinned,
|
|
2121
|
+
})
|
|
2122
|
+
if (sug) {
|
|
2123
|
+
ws.suggestions.push(sug)
|
|
2124
|
+
createdProposals.push(sug)
|
|
2125
|
+
}
|
|
2126
|
+
})
|
|
2127
|
+
}
|
|
2128
|
+
|
|
2129
|
+
if (!createdProposals.length) {
|
|
2130
|
+
return { ok: false, error: '未能生成浓缩边界,请稍后重试。' }
|
|
2131
|
+
}
|
|
2132
|
+
|
|
2133
|
+
const replyLines = createdProposals.map(p =>
|
|
2134
|
+
`- 【${p.targetLabel} · ${p.replaces.length} 合 1】${p.draftText}(可在上方请示卡片选「📌 定住全局」或「仅本任务」一键替换)`,
|
|
2135
|
+
)
|
|
2136
|
+
|
|
2137
|
+
return {
|
|
2138
|
+
ok: true,
|
|
2139
|
+
proposals: createdProposals,
|
|
2140
|
+
reply: replyLines.join('\n'),
|
|
2141
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
const ORGANIZE_ARCHIVES_SYSTEM = [
|
|
2146
|
+
'你是「DSH 参谋长」的工程档案馆馆长。请把杂乱的工程笔记按「档案柜文件夹抽屉 → 曲别针卷宗 → 分条记忆点 → 小点记忆」结构化整理收纳。',
|
|
2147
|
+
'',
|
|
2148
|
+
'【核心铁律】',
|
|
2149
|
+
'1. 默认标准抽屉 ID(优先归入这 5 个抽屉;仅当用户指令明确要求新建分类时才在 newFolders 中定义新抽屉):',
|
|
2150
|
+
' - "coords" : 工程坐标与部署锚点(源码路径、端口、热更口令、验证脚本命令)',
|
|
2151
|
+
' - "incidents" : 排障实录与硬事实(症状→根因→修复、踩坑实录、线上/本地故障)',
|
|
2152
|
+
' - "contracts" : 架构契约与方法论(写入/截断/类型宽容契约、自检断言、设计规范)',
|
|
2153
|
+
' - "ops" : 运维链路与机器环境(本机环境硬事实、服务器/代理/容器链路、运维手册)',
|
|
2154
|
+
' - "plans" : 阶段蓝图与归档计划(能力对照表、历史阶段计划存档、交接里程碑)',
|
|
2155
|
+
'2. 曲别针等级 (`paperclip`):',
|
|
2156
|
+
' - "gold" : 跨会话最核心必查锚点(如工程坐标、核心红线实录)',
|
|
2157
|
+
' - "silver" : 标准已验证工程经验/契约/排障记录',
|
|
2158
|
+
' - "copper" : 阶段性历史存档/旧计划备查',
|
|
2159
|
+
'3. 分条分块记忆点 (`points`):',
|
|
2160
|
+
' - 每份卷宗提炼 2~6 个结构清晰的「记忆点」,禁止把整篇堆成 1 大坨!',
|
|
2161
|
+
' - 每个记忆点必须包含:',
|
|
2162
|
+
' * `title` : 记忆点短标题(≤24字,点明这一条讲什么,如「症状表现」「根因与服务注入契约」「部署态验证命令」)',
|
|
2163
|
+
' * `cue` : 一句话速览钩子(≤48字,未展开时就能扫一眼看懂结论)',
|
|
2164
|
+
' * `detail`: 点击展开的「小点记忆」(**必须无损保留**原文中的具体命令、文件路径、行号、参数名、错误码与核心判据,严禁编造原文没有的事实!)',
|
|
2165
|
+
'4. **只输出一个合法 JSON 对象**,格式如下:',
|
|
2166
|
+
'{',
|
|
2167
|
+
' "newFolders": [',
|
|
2168
|
+
' { "id": "custom-key", "label": "新抽屉名称", "hint": "简短说明" }',
|
|
2169
|
+
' ],',
|
|
2170
|
+
' "items": [',
|
|
2171
|
+
' {',
|
|
2172
|
+
' "id": "原样回填输入的档案 id",',
|
|
2173
|
+
' "folder": "coords|incidents|contracts|ops|plans 或自定义 id",',
|
|
2174
|
+
' "paperclip": "gold|silver|copper",',
|
|
2175
|
+
' "summary": "一句话卷宗总提要(≤52字)",',
|
|
2176
|
+
' "tags": ["精炼标签1", "精炼标签2"],',
|
|
2177
|
+
' "points": [',
|
|
2178
|
+
' { "title": "记忆点标题", "cue": "速览钩子", "detail": "展开后的详细小点记忆(保留命令与路径)" }',
|
|
2179
|
+
' ]',
|
|
2180
|
+
' }',
|
|
2181
|
+
' ]',
|
|
2182
|
+
'}',
|
|
2183
|
+
].join('\n')
|
|
2184
|
+
|
|
2185
|
+
/**
|
|
2186
|
+
* Organize & structure engineering archives via DSH Chief LLM (`请参谋长整理收纳`).
|
|
2187
|
+
* Classifies dossiers into filing-cabinet folders, assigns gold/silver/copper paperclips,
|
|
2188
|
+
* and breaks walls of text into crisp `points: [{ title, cue, detail }]` while 100% preserving raw `body`!
|
|
2189
|
+
*/
|
|
2190
|
+
export async function organizeArchivesWithChief(deps, {
|
|
2191
|
+
sessionId = '',
|
|
2192
|
+
ids = [],
|
|
2193
|
+
folder = '',
|
|
2194
|
+
scope = 'unorganized',
|
|
2195
|
+
instruction = '',
|
|
2196
|
+
} = {}) {
|
|
2197
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
2198
|
+
const sharedFile = typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile
|
|
2199
|
+
const store = loadArchiveStore(sharedFile)
|
|
2200
|
+
|
|
2201
|
+
if (!store.items.length) {
|
|
2202
|
+
return {
|
|
2203
|
+
ok: false,
|
|
2204
|
+
error: '当前「档案」柜中暂无可整理的工程卷宗,可先新建卷宗或将便签沉淀入柜。',
|
|
2205
|
+
}
|
|
2206
|
+
}
|
|
2207
|
+
|
|
2208
|
+
const explicitIds = Array.isArray(ids) ? ids.map(x => String(x || '').trim()).filter(Boolean) : []
|
|
2209
|
+
let candidates = []
|
|
2210
|
+
if (explicitIds.length > 0) {
|
|
2211
|
+
const idSet = new Set(explicitIds)
|
|
2212
|
+
candidates = store.items.filter(it => idSet.has(it.id))
|
|
2213
|
+
} else if (folder) {
|
|
2214
|
+
candidates = store.items.filter(it => it.folder === folder)
|
|
2215
|
+
} else if (scope === 'all') {
|
|
2216
|
+
candidates = store.items.slice()
|
|
2217
|
+
} else {
|
|
2218
|
+
// Prefer unorganized / inbox / single-point items first; if all were already organized, take newest batch
|
|
2219
|
+
const unorg = store.items.filter(it => it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
|
|
2220
|
+
candidates = unorg.length > 0 ? unorg : store.items.slice(0, 8)
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
if (!candidates.length) {
|
|
2224
|
+
return { ok: false, error: '未找到符合筛选范围的工程档案。' }
|
|
2225
|
+
}
|
|
2226
|
+
|
|
2227
|
+
const BATCH_SIZE = 5
|
|
2228
|
+
const MAX_ITEMS_PER_RUN = explicitIds.length > 0 ? Math.min(explicitIds.length, 15) : 10
|
|
2229
|
+
const selected = candidates.slice(0, MAX_ITEMS_PER_RUN)
|
|
2230
|
+
const remainingCount = Math.max(0, candidates.length - selected.length)
|
|
2231
|
+
|
|
2232
|
+
const folderLines = store.folders.map(f => `- "${f.id}": ${f.label}(${f.hint || ''})`)
|
|
2233
|
+
const allCurations = []
|
|
2234
|
+
const allNewFolders = []
|
|
2235
|
+
let usedLlm = false
|
|
2236
|
+
|
|
2237
|
+
for (let offset = 0; offset < selected.length; offset += BATCH_SIZE) {
|
|
2238
|
+
const batch = selected.slice(offset, offset + BATCH_SIZE)
|
|
2239
|
+
const promptParts = [
|
|
2240
|
+
'现有档案柜文件夹抽屉:',
|
|
2241
|
+
...folderLines,
|
|
2242
|
+
instruction ? `\n用户收纳叮嘱:${clamp(instruction, 240)}` : '',
|
|
2243
|
+
`\n待整理收纳的 ${batch.length} 份工程卷宗:`,
|
|
2244
|
+
]
|
|
2245
|
+
batch.forEach((item, idx) => {
|
|
2246
|
+
promptParts.push(
|
|
2247
|
+
`\n--- 卷宗 #${idx + 1} ---`,
|
|
2248
|
+
`id: ${item.id}`,
|
|
2249
|
+
`标题: ${item.title}`,
|
|
2250
|
+
`当前抽屉: ${item.folder} | 当前曲别针: ${item.paperclip} | 原标签: ${(item.tags || []).join(', ') || '无'}`,
|
|
2251
|
+
`原始正文:\n${cleanMultiline(item.body || item.summary || item.title, 2600)}`,
|
|
2252
|
+
)
|
|
2253
|
+
})
|
|
2254
|
+
|
|
2255
|
+
const llmRes = await callChiefLlm(deps, {
|
|
2256
|
+
sessionId: rootId,
|
|
2257
|
+
system: ORGANIZE_ARCHIVES_SYSTEM,
|
|
2258
|
+
prompt: promptParts.filter(Boolean).join('\n'),
|
|
2259
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
2260
|
+
})
|
|
2261
|
+
|
|
2262
|
+
const parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
2263
|
+
if (parsed && Array.isArray(parsed.items) && parsed.items.length > 0) {
|
|
2264
|
+
usedLlm = true
|
|
2265
|
+
if (Array.isArray(parsed.newFolders)) {
|
|
2266
|
+
for (const nf of parsed.newFolders) allNewFolders.push(nf)
|
|
2267
|
+
}
|
|
2268
|
+
const byId = new Map(parsed.items.filter(x => x && x.id).map(x => [String(x.id).trim(), x]))
|
|
2269
|
+
for (const orig of batch) {
|
|
2270
|
+
const cur = byId.get(orig.id)
|
|
2271
|
+
if (cur) {
|
|
2272
|
+
allCurations.push(cur)
|
|
2273
|
+
} else {
|
|
2274
|
+
const fb = smartParseNoteToDossier(orig)
|
|
2275
|
+
allCurations.push({
|
|
2276
|
+
id: orig.id,
|
|
2277
|
+
folder: fb.folder,
|
|
2278
|
+
paperclip: fb.paperclip,
|
|
2279
|
+
summary: fb.summary,
|
|
2280
|
+
tags: orig.tags,
|
|
2281
|
+
points: fb.points,
|
|
2282
|
+
})
|
|
2283
|
+
}
|
|
2284
|
+
}
|
|
2285
|
+
} else {
|
|
2286
|
+
// Deterministic high-precision fallback when LLM is offline or returned non-JSON
|
|
2287
|
+
for (const orig of batch) {
|
|
2288
|
+
const fb = smartParseNoteToDossier(orig)
|
|
2289
|
+
allCurations.push({
|
|
2290
|
+
id: orig.id,
|
|
2291
|
+
folder: orig.folder === 'inbox' ? fb.folder : (orig.folder || fb.folder),
|
|
2292
|
+
paperclip: fb.paperclip,
|
|
2293
|
+
summary: fb.summary,
|
|
2294
|
+
tags: orig.tags,
|
|
2295
|
+
points: fb.points,
|
|
2296
|
+
})
|
|
2297
|
+
}
|
|
2298
|
+
}
|
|
2299
|
+
}
|
|
2300
|
+
|
|
2301
|
+
const applied = applyChiefArchiveCurations(allCurations, allNewFolders, sharedFile)
|
|
2302
|
+
const refreshedList = listArchiveHeaders(rootId, {}, sharedFile)
|
|
2303
|
+
const folderNameMap = new Map(refreshedList.folders.map(f => [f.id, f.label]))
|
|
2304
|
+
|
|
2305
|
+
const folderStats = new Map()
|
|
2306
|
+
for (const c of allCurations) {
|
|
2307
|
+
const fName = folderNameMap.get(c.folder) || c.folder
|
|
2308
|
+
folderStats.set(fName, (folderStats.get(fName) || 0) + 1)
|
|
2309
|
+
}
|
|
2310
|
+
const statSummary = [...folderStats.entries()].map(([k, n]) => `「${k}」${n} 卷`).join('、')
|
|
2311
|
+
const reply = `- 【档案收纳完成】已${usedLlm ? '由参谋长模型深度提炼' : '按结构规则分拣'} **${applied.updatedCount} 份**工程卷宗(归入 ${statSummary}),每份均已拆解「记忆点 → 小点记忆」,原文 100% 无损封存。`
|
|
2312
|
+
+ (remainingCount > 0 ? `\n- 【分批提示】柜内另有 ${remainingCount} 份卷宗待精修,可再点一次「请参谋长整理收纳」继续完成剩余部分。` : '')
|
|
2313
|
+
|
|
2314
|
+
mutateChiefState((s) => {
|
|
2315
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2316
|
+
ws.chat.push(
|
|
2317
|
+
{
|
|
2318
|
+
id: nextId('chat'),
|
|
2319
|
+
role: 'user',
|
|
2320
|
+
text: instruction ? `整理工程档案:${instruction}` : `请参谋长整理收纳工程档案(${applied.updatedCount} 卷)`,
|
|
2321
|
+
actions: [],
|
|
2322
|
+
at: Date.now(),
|
|
2323
|
+
},
|
|
2324
|
+
{
|
|
2325
|
+
id: nextId('chat'),
|
|
2326
|
+
role: 'chief',
|
|
2327
|
+
text: reply,
|
|
2328
|
+
actions: [`已收纳 ${applied.updatedCount} 卷档案`],
|
|
2329
|
+
at: Date.now(),
|
|
2330
|
+
},
|
|
2331
|
+
)
|
|
2332
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2333
|
+
})
|
|
2334
|
+
|
|
2335
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
2336
|
+
deps.appendBoardLog(rootId, `🗄️ 参谋长完成工程档案收纳:共精修 ${applied.updatedCount} 卷(${statSummary})`, 'chief')
|
|
2337
|
+
}
|
|
2338
|
+
|
|
2339
|
+
return {
|
|
2340
|
+
ok: true,
|
|
2341
|
+
updatedCount: applied.updatedCount,
|
|
2342
|
+
remainingCount,
|
|
2343
|
+
usedLlm,
|
|
2344
|
+
reply,
|
|
2345
|
+
archives: refreshedList,
|
|
2346
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
2349
|
+
|
|
2350
|
+
export async function askOrCommandChief(deps, {
|
|
2351
|
+
sessionId = '',
|
|
2352
|
+
text = '',
|
|
2353
|
+
forcedTarget = '',
|
|
2354
|
+
forcedMode = 'steer',
|
|
2355
|
+
}) {
|
|
2356
|
+
const input = cleanMultiline(text, 2000)
|
|
2357
|
+
if (!input) return { ok: false, error: '请输入要询问或吩咐参谋长的内容' }
|
|
2358
|
+
|
|
2359
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
2360
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
2361
|
+
const board = deps.boardForSession(deps.boardFileFor(rootId))
|
|
2362
|
+
const state = loadChiefState()
|
|
2363
|
+
const view = clusterView(state, rootId)
|
|
2364
|
+
|
|
2365
|
+
// Fast path: if user explicitly picked a concrete target pill AND used direct relay mode without asking chief to decompose
|
|
2366
|
+
if (forcedTarget && forcedTarget !== 'auto') {
|
|
2367
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
2368
|
+
fromSession: rootId,
|
|
2369
|
+
fromLabel: '用户 (经 DSH 参谋长)',
|
|
2370
|
+
target: forcedTarget,
|
|
2371
|
+
text: input,
|
|
2372
|
+
mode: ['steer', 'followup', 'silent'].includes(forcedMode) ? forcedMode : 'steer',
|
|
2373
|
+
})
|
|
2374
|
+
const reply = delivery.ok
|
|
2375
|
+
? `已按你的指定向 ${delivery.target || forcedTarget} ${forcedMode === 'steer' ? '插话' : forcedMode === 'silent' ? '投递备忘纸条' : '递话'}${delivery.note ? '(' + delivery.note + ')' : '。'}`
|
|
2376
|
+
: `投递失败:${delivery.error}`
|
|
2377
|
+
|
|
2378
|
+
mutateChiefState((s) => {
|
|
2379
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2380
|
+
ws.chat.push(
|
|
2381
|
+
{ id: nextId('chat'), role: 'user', text: input, target: forcedTarget, actions: [], at: Date.now() },
|
|
2382
|
+
{ id: nextId('chat'), role: 'chief', text: reply, actions: [delivery.ok ? `→ ${delivery.target || forcedTarget}` : '投递失败'], at: Date.now() },
|
|
2383
|
+
)
|
|
2384
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2385
|
+
})
|
|
2386
|
+
|
|
2387
|
+
return {
|
|
2388
|
+
ok: delivery.ok,
|
|
2389
|
+
reply,
|
|
2390
|
+
relays: [delivery],
|
|
2391
|
+
memoryChanges: [],
|
|
2392
|
+
boardOps: [],
|
|
2393
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2396
|
+
|
|
2397
|
+
// Direct natural-language command to organize/curate the Engineering Archive Cabinet (`整理档案` / `收纳档案`)
|
|
2398
|
+
if (!forcedTarget || forcedTarget === 'auto') {
|
|
2399
|
+
if (/(?:档案|卷宗|老笔记)/.test(input) && /(?:整理|收纳|归类|分拣|拆解)/.test(input)) {
|
|
2400
|
+
const orgRes = await organizeArchivesWithChief(deps, {
|
|
2401
|
+
sessionId: rootId,
|
|
2402
|
+
scope: /全部|所有|全柜/.test(input) ? 'all' : 'unorganized',
|
|
2403
|
+
instruction: input,
|
|
2404
|
+
})
|
|
2405
|
+
if (orgRes.ok) {
|
|
2406
|
+
return {
|
|
2407
|
+
ok: true,
|
|
2408
|
+
reply: orgRes.reply,
|
|
2409
|
+
relays: [],
|
|
2410
|
+
memoryChanges: [],
|
|
2411
|
+
boardOps: [`收纳档案 ${orgRes.updatedCount} 卷`],
|
|
2412
|
+
archives: orgRes.archives,
|
|
2413
|
+
view: orgRes.view,
|
|
2414
|
+
}
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
|
|
2419
|
+
// On-demand lazy archive lookup ONLY when the user explicitly asks about archives / historical engineering records
|
|
2420
|
+
const asksArchiveExplicitly = /(?:档案|卷宗|归档|以前|历史记录|工程坐标|老笔记|查一下.*(?:怎么|路径|命令|配置))/.test(input)
|
|
2421
|
+
const onDemandArchiveLines = []
|
|
2422
|
+
if (asksArchiveExplicitly) {
|
|
2423
|
+
const sharedFile = typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile
|
|
2424
|
+
const found = searchArchives(input, { limit: 4 }, sharedFile)
|
|
2425
|
+
if (found.ok && found.hits.length > 0) {
|
|
2426
|
+
onDemandArchiveLines.push('', '## 7. 按需调取的沉淀工程档案(仅因用户本次提问涉及历史档案而临时检索)')
|
|
2427
|
+
for (let i = 0; i < found.hits.length; i += 1) {
|
|
2428
|
+
const hit = found.hits[i]
|
|
2429
|
+
onDemandArchiveLines.push(`- 📎 [${hit.folderLabel}] 《${hit.title}》:${hit.summary}`)
|
|
2430
|
+
if (i < 2) {
|
|
2431
|
+
const det = getArchiveDetail(hit.id, rootId, sharedFile)
|
|
2432
|
+
if (det.ok && det.item && Array.isArray(det.item.points)) {
|
|
2433
|
+
for (const pt of det.item.points.slice(0, 4)) {
|
|
2434
|
+
onDemandArchiveLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 180)}`)
|
|
2435
|
+
}
|
|
2436
|
+
}
|
|
2437
|
+
}
|
|
2438
|
+
}
|
|
2439
|
+
}
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2442
|
+
// Gather real-time conversation stream + cursor + dual-tier bounds + task breakdown
|
|
2443
|
+
const liveDigest = collectLiveConversationsDigest(deps, rootId, directory)
|
|
2444
|
+
const numberedFacts = view.facts.slice()
|
|
2445
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
2446
|
+
const doingTasks = tasks.filter(t => t.status === 'doing')
|
|
2447
|
+
const blockedTasks = tasks.filter(t => t.status === 'blocked')
|
|
2448
|
+
const todoTasks = tasks.filter(t => t.status === 'todo')
|
|
2449
|
+
const doneTasks = tasks.filter(t => t.status === 'done')
|
|
2450
|
+
const cursor = (board && board.cursor) || {}
|
|
2451
|
+
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2452
|
+
const allBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2453
|
+
const fmtBoundCol = (col) => {
|
|
2454
|
+
const list = allBounds[col] || []
|
|
2455
|
+
if (!list.length) return '(无)'
|
|
2456
|
+
const pinSet = new Set(pinnedBounds[col] || [])
|
|
2457
|
+
return list.map(x => `${pinSet.has(x) ? '📌[全局定住] ' : '[本任务] '}${x}`).join(';')
|
|
2458
|
+
}
|
|
2459
|
+
|
|
2460
|
+
const meaningfulPeers = directory.targets.filter(
|
|
2461
|
+
t => t.kind === 'lead' || t.status === 'running' || !/^mnemon-review/i.test(String(t.name || t.handle || '')),
|
|
2462
|
+
)
|
|
2463
|
+
const hiddenIdleProbes = Math.max(0, directory.targets.length - meaningfulPeers.length)
|
|
2464
|
+
|
|
2465
|
+
const promptLines = [
|
|
2466
|
+
'## 1. 当前可通信成员名录 (Peers)',
|
|
2467
|
+
...(meaningfulPeers.length
|
|
2468
|
+
? meaningfulPeers.slice(0, 16).map(t => `- key="${t.key}" | 名称="${t.handle}" | 类型=${t.kind} | 状态=${t.status}${t.taskTitle ? ' | 当前负责: ' + t.taskTitle : ''}`)
|
|
2469
|
+
: ['- key="lead" | 名称="主对话" | 类型=lead']),
|
|
2470
|
+
...(hiddenIdleProbes > 0 ? [`(另有 ${hiddenIdleProbes} 个已空闲后台检查点探针已折叠)`] : []),
|
|
2471
|
+
'',
|
|
2472
|
+
'## 2. 主对话与子代理【实时对话流现场快照】(Live Transcripts)',
|
|
2473
|
+
...(liveDigest.summaryLines.length
|
|
2474
|
+
? liveDigest.summaryLines
|
|
2475
|
+
: ['(当前暂无活跃对话流消息)']),
|
|
2476
|
+
'',
|
|
2477
|
+
'## 3. 参谋看板目标、断点游标与任务图态势',
|
|
2478
|
+
`- 总目标: ${board.objective || '(未设)'}`,
|
|
2479
|
+
`- 实时断点游标 (Cursor): 当前步骤="${cursor.step || '无'}" | 下一步="${cursor.next || '无'}" | 阻塞点="${cursor.blocked || '无'}"`,
|
|
2480
|
+
`- 计划步骤 (Plan): ${((board.plan || []).slice(0, 8).map(s => `${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';')) || '(无)'}`,
|
|
2481
|
+
`- 🔴 受阻任务 (${blockedTasks.length} 项): ${blockedTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [原因:' + clamp(t.note, 80) + ']' : ''}`).join(';') || '(无)'}`,
|
|
2482
|
+
`- 🟢 推进中任务 (${doingTasks.length} 项): ${doingTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}${t.note ? ' [' + clamp(t.note, 60) + ']' : ''}`).join(';') || '(无)'}`,
|
|
2483
|
+
`- ⏳ 待办任务 (${todoTasks.length} 项): ${todoTasks.slice(0, 6).map(t => `#${t.id} ${t.title}${t.owner ? '(@' + shortAgentBriefName(t.owner) + ')' : ''}`).join(';') || '(无)'}`,
|
|
2484
|
+
`- ✅ 最近完成 (${doneTasks.length} 项): ${doneTasks.slice(-5).map(t => `#${t.id} ${t.title}${t.evidence ? ' [证据:' + clamp(t.evidence, 60) + ']' : ''}`).join(';') || '(无)'}`,
|
|
2485
|
+
'',
|
|
2486
|
+
'## 4. 当前生效边界(📌全局定住 vs 本任务)',
|
|
2487
|
+
`- 禁止红线 (forbidden): ${fmtBoundCol('forbidden')}`,
|
|
2488
|
+
`- 允许范围 (allowed): ${fmtBoundCol('allowed')}`,
|
|
2489
|
+
`- 注意事项 (notes): ${fmtBoundCol('notes')}`,
|
|
2490
|
+
'',
|
|
2491
|
+
'## 5. 编号持久记忆条目 (Facts)',
|
|
2492
|
+
...(numberedFacts.length
|
|
2493
|
+
? numberedFacts.map((f, idx) => `[${idx + 1}] (${f.category}) ${f.text}`)
|
|
2494
|
+
: ['(暂无条目)']),
|
|
2495
|
+
'',
|
|
2496
|
+
'## 6. 近期回合摘要与协同信箱参考',
|
|
2497
|
+
...((board.memory || [])
|
|
2498
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
2499
|
+
.slice(-6)
|
|
2500
|
+
.map(m => `- [回合/${m.section}] ${clamp(stripCheckpointNoise(m.title || m.text), 150)}`)),
|
|
2501
|
+
...(view.mailbox.slice(-4).map(m => `- [信箱 ${m.from} → @${m.to}] ${clamp(m.text, 120)}`)),
|
|
2502
|
+
...onDemandArchiveLines,
|
|
2503
|
+
'',
|
|
2504
|
+
'## 用户刚刚对你说的话:',
|
|
2505
|
+
input,
|
|
2506
|
+
]
|
|
2507
|
+
|
|
2508
|
+
const llmRes = await callChiefLlm(deps, {
|
|
2509
|
+
sessionId: rootId,
|
|
2510
|
+
system: ASK_CHIEF_SYSTEM,
|
|
2511
|
+
prompt: promptLines.join('\n'),
|
|
2512
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
2513
|
+
})
|
|
2514
|
+
|
|
2515
|
+
let parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
2516
|
+
|
|
2517
|
+
// Graceful intelligent fallback if LLM is offline / unconfigured / returned non-JSON
|
|
2518
|
+
if (!parsed) {
|
|
2519
|
+
// 1) Explicit @peer relay syntax
|
|
2520
|
+
const mentionMatch = input.match(/^@([^\s::,,]+)[::,,\s]+([\s\S]+)$/)
|
|
2521
|
+
if (mentionMatch) {
|
|
2522
|
+
const targetName = mentionMatch[1]
|
|
2523
|
+
const msgBody = mentionMatch[2].trim()
|
|
2524
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
2525
|
+
fromSession: rootId,
|
|
2526
|
+
fromLabel: '用户 (经 DSH 参谋长)',
|
|
2527
|
+
target: targetName,
|
|
2528
|
+
text: msgBody,
|
|
2529
|
+
mode: 'steer',
|
|
2530
|
+
})
|
|
2531
|
+
const fallbackReply = delivery.ok
|
|
2532
|
+
? `- 【已递话】已向 @${delivery.target} 插话传达指令。`
|
|
2533
|
+
: `- 【投递失败】未找到目标 ${targetName}(${delivery.error})`
|
|
2534
|
+
mutateChiefState((s) => {
|
|
2535
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2536
|
+
ws.chat.push(
|
|
2537
|
+
{ id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
|
|
2538
|
+
{ id: nextId('chat'), role: 'chief', text: fallbackReply, actions: [], at: Date.now() },
|
|
2539
|
+
)
|
|
2540
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2541
|
+
})
|
|
2542
|
+
return {
|
|
2543
|
+
ok: delivery.ok,
|
|
2544
|
+
reply: fallbackReply,
|
|
2545
|
+
relays: [delivery],
|
|
2546
|
+
memoryChanges: [],
|
|
2547
|
+
boardOps: [],
|
|
2548
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
2549
|
+
}
|
|
2550
|
+
}
|
|
2551
|
+
|
|
2552
|
+
// 2) Natural-language request to consolidate scattered boundaries into one
|
|
2553
|
+
if (/边界|红线/.test(input) && /总结成一条|合并成一条|浓缩|合一|整合/.test(input)) {
|
|
2554
|
+
const targetCol = /允许/.test(input) ? 'allowed' : /注意/.test(input) ? 'notes' : ''
|
|
2555
|
+
const consRes = await consolidateBoundsWithChief(deps, {
|
|
2556
|
+
sessionId: rootId,
|
|
2557
|
+
field: targetCol,
|
|
2558
|
+
instruction: input,
|
|
2559
|
+
})
|
|
2560
|
+
if (consRes.ok) {
|
|
2561
|
+
mutateChiefState((s) => {
|
|
2562
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2563
|
+
ws.chat.push(
|
|
2564
|
+
{ id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
|
|
2565
|
+
{ id: nextId('chat'), role: 'chief', text: consRes.reply, actions: ['呈批浓缩边界'], at: Date.now() },
|
|
2566
|
+
)
|
|
2567
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2568
|
+
})
|
|
2569
|
+
return {
|
|
2570
|
+
ok: true,
|
|
2571
|
+
reply: consRes.reply,
|
|
2572
|
+
relays: [],
|
|
2573
|
+
memoryChanges: [],
|
|
2574
|
+
boardOps: [],
|
|
2575
|
+
boundProposals: consRes.proposals,
|
|
2576
|
+
view: consRes.view,
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
// 3) If LLM actually returned readable prose (just not wrapped in JSON), use it; otherwise synthesize smart live briefing
|
|
2582
|
+
const usablePlainLlm = llmRes.ok && llmRes.text && !llmRes.text.trim().startsWith('{')
|
|
2583
|
+
? cleanMultiline(llmRes.text, 900)
|
|
2584
|
+
: ''
|
|
2585
|
+
const archiveFallback = onDemandArchiveLines.length > 1
|
|
2586
|
+
? ['- 【已从沉淀档案柜按需检索到以下卷宗】', ...onDemandArchiveLines.slice(2)].join('\n')
|
|
2587
|
+
: ''
|
|
2588
|
+
const replyText = usablePlainLlm || archiveFallback || buildSmartFallbackReply({
|
|
2589
|
+
input,
|
|
2590
|
+
board,
|
|
2591
|
+
liveDigest,
|
|
2592
|
+
directory,
|
|
2593
|
+
facts: numberedFacts,
|
|
2594
|
+
mailbox: view.mailbox,
|
|
2595
|
+
})
|
|
2596
|
+
|
|
2597
|
+
mutateChiefState((s) => {
|
|
2598
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2599
|
+
ws.chat.push(
|
|
2600
|
+
{ id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
|
|
2601
|
+
{ id: nextId('chat'), role: 'chief', text: replyText, actions: [], at: Date.now() },
|
|
2602
|
+
)
|
|
2603
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2604
|
+
})
|
|
2605
|
+
return {
|
|
2606
|
+
ok: true,
|
|
2607
|
+
reply: replyText,
|
|
2608
|
+
relays: [],
|
|
2609
|
+
memoryChanges: [],
|
|
2610
|
+
boardOps: [],
|
|
2611
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
// Execute decomposed relays
|
|
2616
|
+
const relayResults = []
|
|
2617
|
+
const actionBadges = []
|
|
2618
|
+
for (const r of (Array.isArray(parsed.relays) ? parsed.relays : []).slice(0, 8)) {
|
|
2619
|
+
if (!r || !r.text) continue
|
|
2620
|
+
const deliv = await deliverCrossMessage(deps, {
|
|
2621
|
+
fromSession: rootId,
|
|
2622
|
+
fromLabel: 'DSH 参谋长 (代用户传达)',
|
|
2623
|
+
target: r.target || 'lead',
|
|
2624
|
+
subject: r.subject || '',
|
|
2625
|
+
text: r.text,
|
|
2626
|
+
mode: ['steer', 'followup', 'silent'].includes(r.mode) ? r.mode : 'steer',
|
|
2627
|
+
})
|
|
2628
|
+
relayResults.push(deliv)
|
|
2629
|
+
if (deliv.ok) actionBadges.push(`${r.mode === 'steer' ? '插话' : '递话'} → ${deliv.target}`)
|
|
2630
|
+
}
|
|
2631
|
+
|
|
2632
|
+
// Execute board ops
|
|
2633
|
+
const executedBoardOps = applyBoardOps(deps, rootId, parsed.boardOps)
|
|
2634
|
+
for (const b of executedBoardOps) actionBadges.push(b)
|
|
2635
|
+
|
|
2636
|
+
// Execute durable memory changes & Prime Minister bound proposals (including N-in-1 consolidation)
|
|
2637
|
+
let appliedFacts = []
|
|
2638
|
+
const proposedBounds = []
|
|
2639
|
+
const existingBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2640
|
+
const rawBoundProposals = Array.isArray(parsed.boundProposals) ? parsed.boundProposals.slice(0, 4) : []
|
|
2641
|
+
const replyText = cleanMultiline(parsed.reply || '- 【已执行】已按你的吩咐安排妥当。', 1000)
|
|
2642
|
+
|
|
2643
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '允许范围', notes: '注意事项' }
|
|
2644
|
+
|
|
2645
|
+
mutateChiefState((s) => {
|
|
2646
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2647
|
+
appliedFacts = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, 'user')
|
|
2648
|
+
for (const f of appliedFacts) {
|
|
2649
|
+
actionBadges.push((f.op === 'add' ? '记入:' : f.op === 'edit' ? '修订:' : '移除:') + clamp(f.text, 24))
|
|
2650
|
+
}
|
|
2651
|
+
|
|
2652
|
+
for (const bp of rawBoundProposals) {
|
|
2653
|
+
if (!bp || typeof bp !== 'object') continue
|
|
2654
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(bp.field) ? bp.field : 'forbidden'
|
|
2655
|
+
const itemText = clamp(bp.item || bp.draftText || bp.text || '', 220)
|
|
2656
|
+
if (!itemText || secretLike(itemText)) continue
|
|
2657
|
+
const replaces = Array.isArray(bp.replaces)
|
|
2658
|
+
? bp.replaces.filter(x => typeof x === 'string' && x.trim()).map(x => x.trim().slice(0, 240)).slice(0, 20)
|
|
2659
|
+
: []
|
|
2660
|
+
const colExisting = Array.isArray(existingBounds[col]) ? existingBounds[col] : []
|
|
2661
|
+
if (!replaces.length && colExisting.some(x => String(x).trim() === itemText)) continue
|
|
2662
|
+
const dupPending = ws.suggestions.some(
|
|
2663
|
+
existing => existing.status === 'pending' && existing.kind === 'bound' && existing.draftText === itemText,
|
|
2664
|
+
)
|
|
2665
|
+
if (dupPending) continue
|
|
2666
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
2667
|
+
const hadPinnedInReplaces = replaces.some(r => ((board.pinnedBounds && board.pinnedBounds[col]) || []).includes(r))
|
|
2668
|
+
const sug = normalizeSuggestion({
|
|
2669
|
+
kind: 'bound',
|
|
2670
|
+
boundField: col,
|
|
2671
|
+
fromAgent: replaces.length ? '✦ 参谋长浓缩' : '✦ 参谋长提炼',
|
|
2672
|
+
title: replaces.length
|
|
2673
|
+
? `${colLabel} ${replaces.length} 合 1:${clamp(itemText, 26)}`
|
|
2674
|
+
: `拟入${colLabel}:${clamp(itemText, 30)}`,
|
|
2675
|
+
reason: clamp(
|
|
2676
|
+
bp.reason || (replaces.length
|
|
2677
|
+
? `将 ${replaces.length} 条零散边界浓缩合成为 1 条,请拍板替换。`
|
|
2678
|
+
: '根据会话上下文总结的工作边界,请拍板注入。'),
|
|
2679
|
+
180,
|
|
2680
|
+
),
|
|
2681
|
+
target: 'bounds',
|
|
2682
|
+
targetLabel: colLabel,
|
|
2683
|
+
mode: 'silent',
|
|
2684
|
+
draftText: itemText,
|
|
2685
|
+
replaces,
|
|
2686
|
+
pinGlobal: Boolean(bp.pinGlobal) || hadPinnedInReplaces,
|
|
2687
|
+
})
|
|
2688
|
+
if (sug) {
|
|
2689
|
+
ws.suggestions.push(sug)
|
|
2690
|
+
proposedBounds.push(sug)
|
|
2691
|
+
actionBadges.push(`${replaces.length ? '浓缩' : '呈批'}${colLabel}:${clamp(itemText, 18)}`)
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
|
|
2695
|
+
ws.chat.push(
|
|
2696
|
+
{ id: nextId('chat'), role: 'user', text: input, actions: [], at: Date.now() },
|
|
2697
|
+
{ id: nextId('chat'), role: 'chief', text: replyText, actions: actionBadges, at: Date.now() },
|
|
2698
|
+
)
|
|
2699
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
2700
|
+
})
|
|
2701
|
+
|
|
2702
|
+
// Refresh narrative summary in background if facts or board changed
|
|
2703
|
+
const shouldRefreshNarrative = appliedFacts.length > 0 || executedBoardOps.length > 0
|
|
2704
|
+
const freshView = await getChiefView(deps, rootId, { autoSummarize: shouldRefreshNarrative })
|
|
2705
|
+
|
|
2706
|
+
return {
|
|
2707
|
+
ok: true,
|
|
2708
|
+
reply: replyText,
|
|
2709
|
+
relays: relayResults,
|
|
2710
|
+
memoryChanges: appliedFacts,
|
|
2711
|
+
boardOps: executedBoardOps,
|
|
2712
|
+
boundProposals: proposedBounds,
|
|
2713
|
+
view: freshView,
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
/**
|
|
2718
|
+
* Prime Minister Boundary Proposal API (`chief_board` action `"bounds.propose"`).
|
|
2719
|
+
* Lead or subagents submit wall-hits / boundary lessons here instead of silently mutating global bounds;
|
|
2720
|
+
* DSH Chief curates them and prompts the user for approval before injecting into `board.bounds`.
|
|
2721
|
+
*/
|
|
2722
|
+
export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, item, items, reason }) {
|
|
2723
|
+
const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
|
|
2724
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, callerAgent)) || sid || 'global'
|
|
2725
|
+
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, callerAgent) : null
|
|
2726
|
+
const speaker = identity && identity.isChild
|
|
2727
|
+
? `@${identity.self}`
|
|
2728
|
+
: (by && by !== 'agent' ? String(by) : '@lead')
|
|
2729
|
+
|
|
2730
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(field) ? field : 'forbidden'
|
|
2731
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '允许范围', notes: '注意事项' }
|
|
2732
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
2733
|
+
|
|
2734
|
+
const rawItems = []
|
|
2735
|
+
if (typeof item === 'string' && item.trim()) rawItems.push(item.trim())
|
|
2736
|
+
if (Array.isArray(items)) {
|
|
2737
|
+
for (const entry of items) {
|
|
2738
|
+
if (typeof entry === 'string' && entry.trim()) rawItems.push(entry.trim())
|
|
2739
|
+
}
|
|
2740
|
+
}
|
|
2741
|
+
if (!rawItems.length) {
|
|
2742
|
+
return { ok: false, error: 'bounds.propose requires item (string) or items (string[])' }
|
|
2743
|
+
}
|
|
2744
|
+
|
|
2745
|
+
const board = deps.boardForSession && deps.boardFileFor && rootId !== 'global'
|
|
2746
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2747
|
+
: null
|
|
2748
|
+
const existingCol = Array.isArray(board?.bounds?.[col]) ? board.bounds[col] : []
|
|
2749
|
+
|
|
2750
|
+
const proposed = []
|
|
2751
|
+
const skippedDuplicates = []
|
|
2752
|
+
|
|
2753
|
+
mutateChiefState((state) => {
|
|
2754
|
+
const ws = ensureWorkspace(state, rootId)
|
|
2755
|
+
for (const rawRule of rawItems.slice(0, 6)) {
|
|
2756
|
+
const ruleText = clamp(rawRule, 220)
|
|
2757
|
+
if (!ruleText || secretLike(ruleText)) continue
|
|
2758
|
+
if (existingCol.some(x => String(x).trim() === ruleText)) {
|
|
2759
|
+
skippedDuplicates.push(ruleText)
|
|
2760
|
+
continue
|
|
2761
|
+
}
|
|
2762
|
+
const dupPending = ws.suggestions.some(
|
|
2763
|
+
s => s.status === 'pending' && s.kind === 'bound' && s.draftText === ruleText,
|
|
2764
|
+
)
|
|
2765
|
+
if (dupPending) {
|
|
2766
|
+
skippedDuplicates.push(ruleText)
|
|
2767
|
+
continue
|
|
2768
|
+
}
|
|
2769
|
+
const sug = normalizeSuggestion({
|
|
2770
|
+
kind: 'bound',
|
|
2771
|
+
boundField: col,
|
|
2772
|
+
fromAgent: speaker,
|
|
2773
|
+
title: `拟入${colLabel}:${clamp(ruleText, 30)}`,
|
|
2774
|
+
reason: clamp(reason || `${speaker} 在执行中上报的边界约束,请批准后注入全局边界。`, 180),
|
|
2775
|
+
target: 'bounds',
|
|
2776
|
+
targetLabel: colLabel,
|
|
2777
|
+
mode: 'silent',
|
|
2778
|
+
draftText: ruleText,
|
|
2779
|
+
})
|
|
2780
|
+
if (sug) {
|
|
2781
|
+
const pendingNonBound = ws.suggestions.filter(s => s.status === 'pending' && s.kind !== 'bound')
|
|
2782
|
+
const pendingAll = ws.suggestions.filter(s => s.status === 'pending')
|
|
2783
|
+
if (pendingAll.length >= SUGGESTIONS_CAP && pendingNonBound.length > 0) {
|
|
2784
|
+
pendingNonBound[0].status = 'dismissed'
|
|
2785
|
+
}
|
|
2786
|
+
ws.suggestions.push(sug)
|
|
2787
|
+
proposed.push(sug)
|
|
2788
|
+
}
|
|
2789
|
+
}
|
|
2790
|
+
})
|
|
2791
|
+
|
|
2792
|
+
if (proposed.length && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
2793
|
+
deps.appendBoardLog(
|
|
2794
|
+
rootId,
|
|
2795
|
+
`🏛 收到边界奏请 (${colLabel}):${proposed.map(p => clamp(p.draftText, 40)).join(';')}`,
|
|
2796
|
+
speaker,
|
|
2797
|
+
)
|
|
2798
|
+
}
|
|
2799
|
+
|
|
2800
|
+
return {
|
|
2801
|
+
ok: true,
|
|
2802
|
+
proposed: proposed.map(p => ({ id: p.id, field: p.boundField, item: p.draftText, from: p.fromAgent })),
|
|
2803
|
+
skippedDuplicates,
|
|
2804
|
+
message: proposed.length
|
|
2805
|
+
? `已呈交 DSH 参谋长(共 ${proposed.length} 条),参谋长正请示用户批准后注入全局【${colLabel}】。`
|
|
2806
|
+
: '该边界已在全局边界或待批请示列表中,无需重复上报。',
|
|
2807
|
+
}
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
/* -------------------------------------------------------------------------- */
|
|
2811
|
+
/* Post-Turn Silent Review & Proactive Suggestion Pills */
|
|
2812
|
+
/* -------------------------------------------------------------------------- */
|
|
2813
|
+
|
|
2814
|
+
const TURN_REVIEW_SYSTEM = [
|
|
2815
|
+
'你是「DSH 参谋长」(宰相级协同中枢)的后台复盘与参谋模块。某个对话刚结束一轮输出。',
|
|
2816
|
+
'请阅读最新对话片段、团队状态、当前边界与持久记忆,完成两件事并**只输出一个 JSON 对象**:',
|
|
2817
|
+
'1. `memoryChanges`:仅当出现跨轮次持久有效的规矩、分工、关键架构结论或踩坑教训时才新增/修订/删除(精炼一句话);普通干活过程返回 `[]`。严禁保存密码或密钥。',
|
|
2818
|
+
'2. `suggestions`(最多 1 条,宁缺毋滥,没有高价值事项必须返回 `[]`):',
|
|
2819
|
+
' - **类型 A · 宰相边界请示 (`"kind": "bound"`)**:若主代理或子代理在本轮**明显撞墙**(如权限拒绝、沙箱越界、目录不可写、某工具/命令严禁调用、环境硬限制),或用户明确提出了某条应长期遵守的工作红线/允许范围,且尚不在「已有全局边界」中 → 生成一条 `bound` 请示,由用户一键批准后正式注入全局边界!',
|
|
2820
|
+
' - **类型 B · 跨对话递话建议 (`"kind": "relay"`)**:若发现明确的跨对话信息差(如子代理刚查清下游急需的关键结论、或某代理偏离目标需纠偏) → 生成一条简明分点的 `relay` 递话建议。',
|
|
2821
|
+
'',
|
|
2822
|
+
'输出格式:',
|
|
2823
|
+
'{',
|
|
2824
|
+
' "memoryChanges": [',
|
|
2825
|
+
' { "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "…" }',
|
|
2826
|
+
' ],',
|
|
2827
|
+
' "suggestions": [',
|
|
2828
|
+
' {',
|
|
2829
|
+
' "kind": "bound 或 relay",',
|
|
2830
|
+
' "boundField": "当 kind=bound 时必填: forbidden|allowed|notes",',
|
|
2831
|
+
' "title": "一句话简明标题(≤26字)",',
|
|
2832
|
+
' "reason": "简要说明撞墙背景或递话原因(≤65字)",',
|
|
2833
|
+
' "target": "当 kind=relay 时填目标 key(如 lead 或子代理名);kind=bound 时填 bounds",',
|
|
2834
|
+
' "targetLabel": "目标显示名(如 主对话 / 禁止红线)",',
|
|
2835
|
+
' "mode": "steer|followup|silent",',
|
|
2836
|
+
' "draftText": "kind=bound 时填精炼的一句话边界条文;kind=relay 时填简明分点的递话内容"',
|
|
2837
|
+
' }',
|
|
2838
|
+
' ]',
|
|
2839
|
+
'}',
|
|
2840
|
+
].join('\n')
|
|
2841
|
+
|
|
2842
|
+
const reviewTimers = new Map()
|
|
2843
|
+
|
|
2844
|
+
function extractLatestTurnDigest(agent, turn) {
|
|
2845
|
+
if (!agent || !agent.session) return null
|
|
2846
|
+
try {
|
|
2847
|
+
if (typeof agent.session.deriveMessages === 'function') {
|
|
2848
|
+
const msgs = agent.session.deriveMessages() || []
|
|
2849
|
+
const tail = msgs.slice(-6)
|
|
2850
|
+
const lines = []
|
|
2851
|
+
let hasUser = false
|
|
2852
|
+
for (const m of tail) {
|
|
2853
|
+
if (!m || !m.role) continue
|
|
2854
|
+
if (m.source && m.source.kind && m.source.kind !== 'user' && m.role === 'user') continue
|
|
2855
|
+
const blocks = Array.isArray(m.content) ? m.content : []
|
|
2856
|
+
const txt = blocks
|
|
2857
|
+
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
2858
|
+
.map(b => b.text)
|
|
2859
|
+
.join('\n')
|
|
2860
|
+
.trim()
|
|
2861
|
+
if (!txt || isInternalCheckpointNoise(txt)) continue
|
|
2862
|
+
if (m.role === 'user') {
|
|
2863
|
+
hasUser = true
|
|
2864
|
+
lines.push('User: ' + clamp(txt, 1200))
|
|
2865
|
+
} else if (m.role === 'assistant') {
|
|
2866
|
+
lines.push('Assistant: ' + clamp(txt, 900))
|
|
2867
|
+
}
|
|
2868
|
+
}
|
|
2869
|
+
if (lines.length > 0) return { text: lines.join('\n'), hasUser, stamp: msgs.length }
|
|
2870
|
+
}
|
|
2871
|
+
} catch {}
|
|
2872
|
+
return null
|
|
2873
|
+
}
|
|
2874
|
+
|
|
2875
|
+
const lastReviewAtByRoot = new Map()
|
|
2876
|
+
|
|
2877
|
+
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
2878
|
+
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
2879
|
+
if (!sid) return
|
|
2880
|
+
// Never waste tokens reviewing internal mnemon checkpoint / probe subagents
|
|
2881
|
+
if (/^mnemon-(?:review|run)/i.test(sid) || /^mnemon-(?:review|run)/i.test(String((agent && agent.name) || ''))) {
|
|
2882
|
+
return
|
|
2883
|
+
}
|
|
2884
|
+
const state = loadChiefState()
|
|
2885
|
+
const paceMode = (state.config && state.config.paceMode) || 'manual'
|
|
2886
|
+
// Default 'manual' mode: ZERO automatic background LLM calls! Human controls the rhythm.
|
|
2887
|
+
if (paceMode === 'manual' || state.config.autoReview === false) return
|
|
2888
|
+
|
|
2889
|
+
const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
2890
|
+
clearTimeout(reviewTimers.get(rootKey))
|
|
2891
|
+
const timer = setTimeout(() => {
|
|
2892
|
+
reviewTimers.delete(rootKey)
|
|
2893
|
+
runTurnReview(deps, { agent, sessionId: sid, turn }).catch(() => {})
|
|
2894
|
+
}, REVIEW_DELAY_MS)
|
|
2895
|
+
timer.unref?.()
|
|
2896
|
+
reviewTimers.set(rootKey, timer)
|
|
2897
|
+
}
|
|
2898
|
+
|
|
2899
|
+
async function runTurnReview(deps, { agent, sessionId, turn }) {
|
|
2900
|
+
const rootId = deps.resolveRootSessionId(sessionId, agent) || sessionId
|
|
2901
|
+
const stateBefore = loadChiefState()
|
|
2902
|
+
const paceMode = (stateBefore.config && stateBefore.config.paceMode) || 'manual'
|
|
2903
|
+
if (paceMode === 'manual') return
|
|
2904
|
+
|
|
2905
|
+
const digest = extractLatestTurnDigest(agent, turn)
|
|
2906
|
+
if (!digest || !digest.text) return
|
|
2907
|
+
|
|
2908
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
2909
|
+
const cursorKey = `${sessionId}`
|
|
2910
|
+
if (wsBefore.reviewCursors[cursorKey] === digest.stamp) return
|
|
2911
|
+
|
|
2912
|
+
const identity = deps.resolveAgentIdentity(deps.runtime, sessionId, agent)
|
|
2913
|
+
if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return
|
|
2914
|
+
|
|
2915
|
+
const hasWallCue = /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
2916
|
+
const now = Date.now()
|
|
2917
|
+
const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
|
|
2918
|
+
const cooldownMs = paceMode === 'smart'
|
|
2919
|
+
? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS)
|
|
2920
|
+
: AUTO_REVIEW_COOLDOWN_MS
|
|
2921
|
+
if (now - lastAt < cooldownMs) return
|
|
2922
|
+
|
|
2923
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
2924
|
+
const realPeers = directory.targets.filter(t => !/^mnemon-(?:review|run)/i.test(String(t.name || t.handle || '')))
|
|
2925
|
+
|
|
2926
|
+
// In 'smart' mode, ONLY review when a hard wall/error cue occurred OR multi-agent milestone with human turn
|
|
2927
|
+
if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
|
|
2928
|
+
return
|
|
2929
|
+
}
|
|
2930
|
+
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return
|
|
2931
|
+
|
|
2932
|
+
const modelsInfo = await listChiefModels(deps, false, rootId)
|
|
2933
|
+
if (!modelsInfo.available) return
|
|
2934
|
+
|
|
2935
|
+
lastReviewAtByRoot.set(rootId, now)
|
|
2936
|
+
const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
|
|
2937
|
+
const view = clusterView(stateBefore, rootId)
|
|
2938
|
+
const numberedFacts = view.facts.slice()
|
|
2939
|
+
const board = deps.boardForSession && deps.boardFileFor
|
|
2940
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
2941
|
+
: null
|
|
2942
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2943
|
+
|
|
2944
|
+
const activeTargets = realPeers.filter(t => t.key === 'lead' || t.status === 'running').slice(0, 10)
|
|
2945
|
+
const idleCount = Math.max(0, realPeers.length - activeTargets.length)
|
|
2946
|
+
|
|
2947
|
+
const prompt = [
|
|
2948
|
+
`刚刚结束回合的对话身份:${speaker}(sessionId=${sessionId})`,
|
|
2949
|
+
`活跃团队成员:${activeTargets.map(t => `${t.handle}[key=${t.key}, ${t.status}${t.taskTitle ? ', 任务:' + t.taskTitle : ''}]`).join(';')}${idleCount > 0 ? `(另有 ${idleCount} 名空闲子代理已折叠)` : ''}`,
|
|
2950
|
+
'',
|
|
2951
|
+
'已有全局边界(请勿重复提议已有项):',
|
|
2952
|
+
`- 禁止:${(bounds.forbidden || []).join(';') || '(暂无)'}`,
|
|
2953
|
+
`- 允许:${(bounds.allowed || []).join(';') || '(暂无)'}`,
|
|
2954
|
+
`- 注意:${(bounds.notes || []).join(';') || '(暂无)'}`,
|
|
2955
|
+
'',
|
|
2956
|
+
'已有持久记忆条目:',
|
|
2957
|
+
...(numberedFacts.length ? numberedFacts.map((f, i) => `[${i + 1}] (${f.category}) ${f.text}`) : ['(暂无)']),
|
|
2958
|
+
'',
|
|
2959
|
+
'本轮最新对话片段:',
|
|
2960
|
+
digest.text,
|
|
2961
|
+
].join('\n')
|
|
2962
|
+
|
|
2963
|
+
const res = await callChiefLlm(deps, {
|
|
2964
|
+
sessionId: rootId,
|
|
2965
|
+
system: TURN_REVIEW_SYSTEM,
|
|
2966
|
+
prompt,
|
|
2967
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
2968
|
+
})
|
|
2969
|
+
if (!res.ok) return
|
|
2970
|
+
|
|
2971
|
+
const parsed = extractJsonObject(res.text)
|
|
2972
|
+
if (!parsed) return
|
|
2973
|
+
|
|
2974
|
+
const autoPilot = Boolean(loadChiefState().config.autoPilot)
|
|
2975
|
+
const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
|
|
2976
|
+
.map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
|
|
2977
|
+
.filter(Boolean)
|
|
2978
|
+
.slice(0, 1)
|
|
2979
|
+
|
|
2980
|
+
let factsChanged = false
|
|
2981
|
+
const autoRelays = []
|
|
2982
|
+
|
|
2983
|
+
mutateChiefState((s) => {
|
|
2984
|
+
const ws = ensureWorkspace(s, rootId)
|
|
2985
|
+
ws.reviewCursors[cursorKey] = digest.stamp
|
|
2986
|
+
const applied = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, speaker)
|
|
2987
|
+
if (applied.length > 0) factsChanged = true
|
|
2988
|
+
|
|
2989
|
+
for (const sug of rawSuggestions) {
|
|
2990
|
+
if (sug.kind === 'bound') {
|
|
2991
|
+
const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
|
|
2992
|
+
if (colList.some(x => String(x).trim() === sug.draftText)) continue
|
|
2993
|
+
}
|
|
2994
|
+
// Prime Minister Rule: Boundary changes NEVER auto-execute without explicit user approval!
|
|
2995
|
+
if (autoPilot && sug.kind === 'relay' && sug.draftText) {
|
|
2996
|
+
sug.status = 'applied'
|
|
2997
|
+
autoRelays.push(sug)
|
|
2998
|
+
} else {
|
|
2999
|
+
const dup = ws.suggestions.some(
|
|
3000
|
+
existing => existing.status === 'pending'
|
|
3001
|
+
&& existing.kind === sug.kind
|
|
3002
|
+
&& (sug.kind === 'bound' ? existing.draftText === sug.draftText : (existing.target === sug.target && existing.title === sug.title)),
|
|
3003
|
+
)
|
|
3004
|
+
if (!dup) {
|
|
3005
|
+
const pending = ws.suggestions.filter(item => item.status === 'pending')
|
|
3006
|
+
if (pending.length >= 5) {
|
|
3007
|
+
const victim = pending.find(item => item.kind !== 'bound') || pending[0]
|
|
3008
|
+
victim.status = 'dismissed'
|
|
3009
|
+
}
|
|
3010
|
+
ws.suggestions.push(sug)
|
|
3011
|
+
}
|
|
3012
|
+
}
|
|
3013
|
+
}
|
|
3014
|
+
})
|
|
3015
|
+
|
|
3016
|
+
for (const sug of autoRelays) {
|
|
3017
|
+
await deliverCrossMessage(deps, {
|
|
3018
|
+
fromSession: rootId,
|
|
3019
|
+
fromLabel: 'DSH 参谋长 (自动托管)',
|
|
3020
|
+
target: sug.target,
|
|
3021
|
+
subject: sug.title,
|
|
3022
|
+
text: sug.draftText,
|
|
3023
|
+
mode: sug.mode || 'silent',
|
|
3024
|
+
})
|
|
3025
|
+
}
|
|
3026
|
+
// Never chain an automatic LLM summary right after turn review — human controls summary rhythm!
|
|
3027
|
+
}
|
|
3028
|
+
|
|
3029
|
+
export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal }) {
|
|
3030
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
3031
|
+
let found = null
|
|
3032
|
+
mutateChiefState((state) => {
|
|
3033
|
+
const ws = ensureWorkspace(state, rootId)
|
|
3034
|
+
const item = ws.suggestions.find(s => s.id === suggestionId)
|
|
3035
|
+
if (!item) return
|
|
3036
|
+
item.status = decision === 'approve' ? 'applied' : 'dismissed'
|
|
3037
|
+
found = { ...item }
|
|
3038
|
+
})
|
|
3039
|
+
if (!found) return { ok: false, error: '未找到该请示或建议卡片' }
|
|
3040
|
+
|
|
3041
|
+
if (decision === 'approve' && found.kind === 'bound') {
|
|
3042
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(boundField)
|
|
3043
|
+
? boundField
|
|
3044
|
+
: (['forbidden', 'allowed', 'notes'].includes(found.boundField) ? found.boundField : 'forbidden')
|
|
3045
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '允许范围', notes: '注意事项' }
|
|
3046
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
3047
|
+
const ruleText = clamp(editedText || found.draftText || found.title, 220)
|
|
3048
|
+
if (!ruleText) return { ok: false, error: '边界条文不能为空' }
|
|
3049
|
+
|
|
3050
|
+
const shouldPin = typeof pinGlobal === 'boolean' ? pinGlobal : Boolean(found.pinGlobal)
|
|
3051
|
+
const replaces = Array.isArray(found.replaces) ? found.replaces.filter(Boolean) : []
|
|
3052
|
+
|
|
3053
|
+
const writeRes = deps.runAction
|
|
3054
|
+
? (replaces.length > 0
|
|
3055
|
+
? deps.runAction({
|
|
3056
|
+
action: 'bounds.consolidate',
|
|
3057
|
+
field: col,
|
|
3058
|
+
removeItems: replaces,
|
|
3059
|
+
item: ruleText,
|
|
3060
|
+
pinned: shouldPin,
|
|
3061
|
+
session: rootId === 'global' ? '' : rootId,
|
|
3062
|
+
by: 'DSH 参谋长',
|
|
3063
|
+
})
|
|
3064
|
+
: deps.runAction({
|
|
3065
|
+
action: 'bounds.add',
|
|
3066
|
+
field: col,
|
|
3067
|
+
item: ruleText,
|
|
3068
|
+
pinned: shouldPin,
|
|
3069
|
+
session: rootId === 'global' ? '' : rootId,
|
|
3070
|
+
by: 'DSH 参谋长',
|
|
3071
|
+
}))
|
|
3072
|
+
: { ok: false, error: 'runAction unavailable' }
|
|
3073
|
+
if (!writeRes || !writeRes.ok) {
|
|
3074
|
+
return { ok: false, error: (writeRes && writeRes.error) || '写入边界失败' }
|
|
3075
|
+
}
|
|
3076
|
+
|
|
3077
|
+
const scopeTag = shouldPin ? '📌 全局共享边界(跨任务生效)' : '本任务边界(仅当前会话树生效)'
|
|
3078
|
+
// Broadcast a silent boundary decree so running lead/subagents immediately see the new rule on next pre-step
|
|
3079
|
+
mutateChiefState((state) => {
|
|
3080
|
+
const ws = ensureWorkspace(state, rootId)
|
|
3081
|
+
const decree = normalizeMail({
|
|
3082
|
+
from: 'DSH 参谋长 (边界颁布)',
|
|
3083
|
+
fromSession: '',
|
|
3084
|
+
to: 'all',
|
|
3085
|
+
toSession: 'all',
|
|
3086
|
+
subject: `用户已批准${replaces.length ? `浓缩${colLabel}(${replaces.length} 合 1)` : `新${colLabel}`}`,
|
|
3087
|
+
text: `- 【${colLabel} · ${scopeTag}】${shouldPin ? '📌 ' : ''}${ruleText}${replaces.length ? `\n- 【已整合替代】原 ${replaces.length} 条零散边界已合并为此条总则` : ''}${found.reason ? `\n- 【缘由】${found.reason}` : ''}\n请主代理与全体子代理自即刻起严格遵守!`,
|
|
3088
|
+
mode: 'silent',
|
|
3089
|
+
deliveredPhysical: false,
|
|
3090
|
+
})
|
|
3091
|
+
if (decree) {
|
|
3092
|
+
ws.mailbox.push(decree)
|
|
3093
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
3094
|
+
}
|
|
3095
|
+
})
|
|
3096
|
+
|
|
3097
|
+
return {
|
|
3098
|
+
ok: true,
|
|
3099
|
+
boundApplied: { field: col, label: colLabel, item: ruleText, pinned: shouldPin, replacedCount: replaces.length },
|
|
3100
|
+
view: await getChiefView(deps, rootId, { autoSummarize: true }),
|
|
3101
|
+
}
|
|
3102
|
+
}
|
|
3103
|
+
|
|
3104
|
+
if (decision === 'approve' && found.kind === 'relay') {
|
|
3105
|
+
const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
|
|
3106
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
3107
|
+
fromSession: rootId,
|
|
3108
|
+
fromLabel: 'DSH 参谋长 (获批建议)',
|
|
3109
|
+
target: found.target,
|
|
3110
|
+
subject: found.title,
|
|
3111
|
+
text: body,
|
|
3112
|
+
mode: found.mode || 'steer',
|
|
3113
|
+
})
|
|
3114
|
+
return {
|
|
3115
|
+
ok: delivery.ok,
|
|
3116
|
+
delivery,
|
|
3117
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
3118
|
+
}
|
|
3119
|
+
}
|
|
3120
|
+
|
|
3121
|
+
return {
|
|
3122
|
+
ok: true,
|
|
3123
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
3124
|
+
}
|
|
3125
|
+
}
|
|
3126
|
+
|
|
3127
|
+
export function updateChiefConfig(patch) {
|
|
3128
|
+
return mutateChiefState((state) => {
|
|
3129
|
+
if (typeof patch.modelRef === 'string') state.config.modelRef = patch.modelRef.trim()
|
|
3130
|
+
if (typeof patch.paceMode === 'string' && ['manual', 'smart', 'auto'].includes(patch.paceMode)) {
|
|
3131
|
+
state.config.paceMode = patch.paceMode
|
|
3132
|
+
state.config.autoPilot = patch.paceMode === 'auto'
|
|
3133
|
+
state.config.autoReview = patch.paceMode !== 'manual'
|
|
3134
|
+
} else if (typeof patch.autoPilot === 'boolean') {
|
|
3135
|
+
state.config.paceMode = patch.autoPilot ? 'auto' : 'manual'
|
|
3136
|
+
state.config.autoPilot = patch.autoPilot
|
|
3137
|
+
state.config.autoReview = patch.autoPilot
|
|
3138
|
+
}
|
|
3139
|
+
if (typeof patch.autoReview === 'boolean' && typeof patch.paceMode !== 'string') {
|
|
3140
|
+
state.config.autoReview = patch.autoReview
|
|
3141
|
+
if (!patch.autoReview) state.config.paceMode = 'manual'
|
|
3142
|
+
}
|
|
3143
|
+
return { ok: true, config: { ...state.config } }
|
|
3144
|
+
})
|
|
3145
|
+
}
|
|
3146
|
+
|
|
3147
|
+
export function mutateChiefFact(deps, { sessionId, op, id, text, category, pinned }) {
|
|
3148
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
3149
|
+
return mutateChiefState((state) => {
|
|
3150
|
+
const ws = ensureWorkspace(state, rootId)
|
|
3151
|
+
if (op === 'add') {
|
|
3152
|
+
const fact = normalizeFact({ text, category: category || 'discipline', by: 'user', pinned: Boolean(pinned) })
|
|
3153
|
+
if (!fact) return { ok: false, error: '条目无效或包含敏感凭据' }
|
|
3154
|
+
ws.facts.push(fact)
|
|
3155
|
+
if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
|
|
3156
|
+
return { ok: true, fact }
|
|
3157
|
+
}
|
|
3158
|
+
const target = ws.facts.find(f => f.id === id)
|
|
3159
|
+
if (!target) return { ok: false, error: '未找到该记忆条目' }
|
|
3160
|
+
if (op === 'remove') {
|
|
3161
|
+
ws.facts = ws.facts.filter(f => f.id !== id)
|
|
3162
|
+
return { ok: true }
|
|
3163
|
+
}
|
|
3164
|
+
if (op === 'pin') {
|
|
3165
|
+
target.pinned = Boolean(pinned)
|
|
3166
|
+
target.updatedAt = Date.now()
|
|
3167
|
+
return { ok: true, fact: target }
|
|
3168
|
+
}
|
|
3169
|
+
if (op === 'edit') {
|
|
3170
|
+
const clean = clamp(text, FACT_TEXT_MAX)
|
|
3171
|
+
if (!clean || secretLike(clean)) return { ok: false, error: '内容无效或包含敏感凭据' }
|
|
3172
|
+
target.text = clean
|
|
3173
|
+
if (category) target.category = category
|
|
3174
|
+
target.updatedAt = Date.now()
|
|
3175
|
+
return { ok: true, fact: target }
|
|
3176
|
+
}
|
|
3177
|
+
return { ok: false, error: '未知操作: ' + op }
|
|
3178
|
+
})
|
|
3179
|
+
}
|
|
3180
|
+
|
|
3181
|
+
export function readMailboxForAgent(deps, { sessionId, callerAgent, unreadOnly = false }) {
|
|
3182
|
+
const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
|
|
3183
|
+
const rootId = deps.resolveRootSessionId(sid, callerAgent) || sid || 'global'
|
|
3184
|
+
const identity = deps.resolveAgentIdentity(deps.runtime, sid, callerAgent)
|
|
3185
|
+
const myHandles = new Set(
|
|
3186
|
+
[
|
|
3187
|
+
sid,
|
|
3188
|
+
identity && identity.self ? identity.self : '',
|
|
3189
|
+
identity && !identity.isChild ? 'lead' : '',
|
|
3190
|
+
].filter(Boolean).map(v => v.toLowerCase()),
|
|
3191
|
+
)
|
|
3192
|
+
|
|
3193
|
+
const out = []
|
|
3194
|
+
mutateChiefState((state) => {
|
|
3195
|
+
const view = clusterView(state, rootId)
|
|
3196
|
+
for (const m of view.mailbox) {
|
|
3197
|
+
const toLower = String(m.toSession || m.to || '').toLowerCase()
|
|
3198
|
+
const toHandleLower = String(m.to || '').toLowerCase()
|
|
3199
|
+
const relevant = !sid
|
|
3200
|
+
|| toLower === 'all'
|
|
3201
|
+
|| toHandleLower === 'all'
|
|
3202
|
+
|| myHandles.has(toLower)
|
|
3203
|
+
|| myHandles.has(toHandleLower)
|
|
3204
|
+
|| myHandles.has(toHandleLower.split('/').pop())
|
|
3205
|
+
|| m.fromSession === sid
|
|
3206
|
+
if (!relevant) continue
|
|
3207
|
+
const isRead = (m.readBy || []).some(r => myHandles.has(String(r).toLowerCase()))
|
|
3208
|
+
if (unreadOnly && isRead) continue
|
|
3209
|
+
if (!isRead && sid && m.fromSession !== sid) {
|
|
3210
|
+
m.readBy = [...new Set([...(m.readBy || []), sid, ...(identity?.self ? [identity.self] : [])])]
|
|
3211
|
+
}
|
|
3212
|
+
out.push({ ...m, unread: !isRead })
|
|
3213
|
+
}
|
|
3214
|
+
})
|
|
3215
|
+
return out.slice(-25)
|
|
3216
|
+
}
|