dsh-chief 1.1.0 → 1.2.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 +51 -0
- package/README.en.md +104 -74
- package/README.md +112 -96
- package/archives.js +1200 -199
- package/auto-continue.js +627 -0
- package/chief-executor.js +861 -0
- package/chief.js +3221 -279
- package/client.js +4668 -1093
- package/digest.js +67 -21
- package/handoff.js +3 -3
- package/index.js +1163 -172
- package/package.json +6 -2
package/chief.js
CHANGED
|
@@ -21,17 +21,33 @@ import {
|
|
|
21
21
|
DEFAULT_ARCHIVE_FOLDERS,
|
|
22
22
|
resolveProjectKey,
|
|
23
23
|
loadArchiveStore,
|
|
24
|
+
getChiefMountedGlobalForSession,
|
|
25
|
+
getTakenOutGlobalForSession,
|
|
26
|
+
collectSealedWatchSummary,
|
|
24
27
|
listArchiveHeaders,
|
|
25
28
|
getArchiveDetail,
|
|
26
29
|
searchArchives,
|
|
30
|
+
searchGlobalVaultForChief,
|
|
27
31
|
smartParseNoteToDossier,
|
|
28
32
|
mutateArchive,
|
|
29
33
|
applyChiefArchiveCurations,
|
|
34
|
+
copyPrecipitatedToVault,
|
|
30
35
|
getFlippedOutPrecipitatedForSession,
|
|
31
36
|
listPrecipitatedHeaders,
|
|
37
|
+
getPrecipitatedDetail,
|
|
32
38
|
savePrecipitatedEntry,
|
|
33
39
|
mutatePrecipitated,
|
|
34
40
|
} from './archives.js'
|
|
41
|
+
import {
|
|
42
|
+
CHIEF_PERMISSION_MODES,
|
|
43
|
+
DEFAULT_CHIEF_PERMISSION_MODE,
|
|
44
|
+
normalizePermissionMode,
|
|
45
|
+
CHIEF_TOOLS_PROMPT_GUIDE,
|
|
46
|
+
runChiefAgenticLoop,
|
|
47
|
+
stripToolCallMarkup,
|
|
48
|
+
} from './chief-executor.js'
|
|
49
|
+
|
|
50
|
+
export { CHIEF_PERMISSION_MODES, DEFAULT_CHIEF_PERMISSION_MODE, normalizePermissionMode }
|
|
35
51
|
|
|
36
52
|
const STATE_VERSION = 1
|
|
37
53
|
const FACTS_CAP = 120
|
|
@@ -109,13 +125,81 @@ function resolveSessionWorkspaceCwd(deps, sessionId) {
|
|
|
109
125
|
return process.cwd()
|
|
110
126
|
}
|
|
111
127
|
|
|
112
|
-
function archiveTargetForRoot(deps, rootId,
|
|
128
|
+
function archiveTargetForRoot(deps, rootId, extra = '') {
|
|
129
|
+
const opts = extra && typeof extra === 'object' ? extra : { cabinetId: String(extra || '') }
|
|
130
|
+
const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
|
|
113
131
|
const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
|
|
114
132
|
const cwd = resolveSessionWorkspaceCwd(deps, rootId)
|
|
133
|
+
let cab = opts.cabinetId ? String(opts.cabinetId).trim() : ''
|
|
134
|
+
if (vaultScope !== 'global' && !cab && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function' && rootId && rootId !== 'global') {
|
|
135
|
+
try {
|
|
136
|
+
const b = deps.boardForSession(deps.boardFileFor(rootId))
|
|
137
|
+
if (b && typeof b.activeCabinetId === 'string') cab = b.activeCabinetId.trim()
|
|
138
|
+
} catch {}
|
|
139
|
+
}
|
|
115
140
|
return {
|
|
116
141
|
customSharedBoardFile: sharedFile || '',
|
|
117
142
|
cwd,
|
|
118
|
-
|
|
143
|
+
vaultScope,
|
|
144
|
+
...(vaultScope !== 'global' && rootId && rootId !== 'global' ? { rootSessionId: String(rootId).trim() } : {}),
|
|
145
|
+
...(cab ? { cabinetId: cab } : {}),
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Chief-of-Staff visibility matrix (0-Token Global Cold Vault):
|
|
151
|
+
* - Sees current session's Working Cabinet (`session`), if bound to a concrete rootSessionId
|
|
152
|
+
* - Sees ONLY System Global Cold Vault entries explicitly mounted for Chief in THIS session (`chiefMountedSessions`) — 0 Token by default!
|
|
153
|
+
* - Sees Precipitated Vault entries ONLY when explicitly `flippedOut` (`ws.flippedPrecipitatedIds`) for this session!
|
|
154
|
+
*/
|
|
155
|
+
function collectChiefVisibleArchives(deps, rootId, stateSnapshot = null) {
|
|
156
|
+
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
157
|
+
const sessionTarget = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
|
|
158
|
+
const globalTarget = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
|
|
159
|
+
const baseOpt = sessionTarget || globalTarget
|
|
160
|
+
const projectKey = resolveProjectKey(baseOpt.cwd)
|
|
161
|
+
|
|
162
|
+
let deskSessionItems = []
|
|
163
|
+
let deskGlobalItems = []
|
|
164
|
+
let deskFlippedItems = []
|
|
165
|
+
let mountedGlobalItems = []
|
|
166
|
+
let sealedWatch = { sessionSealed: [], globalSealed: [], precipSealed: [] }
|
|
167
|
+
|
|
168
|
+
try {
|
|
169
|
+
if (sessionTarget) {
|
|
170
|
+
const stSess = loadArchiveStore(sessionTarget)
|
|
171
|
+
const allSess = Array.isArray(stSess.items) ? stSess.items : []
|
|
172
|
+
deskSessionItems = allSess.filter(it => Array.isArray(it.takenOutSessions) && it.takenOutSessions.includes(sid)).slice(0, 6)
|
|
173
|
+
}
|
|
174
|
+
} catch {}
|
|
175
|
+
try {
|
|
176
|
+
if (sid) {
|
|
177
|
+
deskGlobalItems = getTakenOutGlobalForSession(sid, globalTarget).slice(0, 6)
|
|
178
|
+
mountedGlobalItems = getChiefMountedGlobalForSession(sid, globalTarget).slice(0, 6)
|
|
179
|
+
}
|
|
180
|
+
} catch {}
|
|
181
|
+
try {
|
|
182
|
+
if (sid) {
|
|
183
|
+
const st = stateSnapshot || loadChiefState()
|
|
184
|
+
const ws = st && st.workspaces && st.workspaces[sid]
|
|
185
|
+
const flippedIds = ws && Array.isArray(ws.flippedPrecipitatedIds) ? ws.flippedPrecipitatedIds : []
|
|
186
|
+
if (flippedIds.length > 0) {
|
|
187
|
+
deskFlippedItems = getFlippedOutPrecipitatedForSession(projectKey, sid, true, baseOpt).slice(0, 6)
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
} catch {}
|
|
191
|
+
try {
|
|
192
|
+
sealedWatch = collectSealedWatchSummary(sid, projectKey, baseOpt, { limitPerVault: 8 })
|
|
193
|
+
} catch {}
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
deskSessionItems,
|
|
197
|
+
deskGlobalItems,
|
|
198
|
+
deskFlippedItems,
|
|
199
|
+
mountedGlobalItems,
|
|
200
|
+
sealedWatch,
|
|
201
|
+
sessionTarget,
|
|
202
|
+
globalTarget,
|
|
119
203
|
}
|
|
120
204
|
}
|
|
121
205
|
|
|
@@ -236,7 +320,7 @@ function emptyWorkspace() {
|
|
|
236
320
|
return {
|
|
237
321
|
config: null,
|
|
238
322
|
facts: [],
|
|
239
|
-
narrative: { hash: '', text: '', at: 0, byModel: '' },
|
|
323
|
+
narrative: { hash: '', text: '', at: 0, byModel: '', clusterSig: '' },
|
|
240
324
|
suggestions: [],
|
|
241
325
|
chat: [],
|
|
242
326
|
mailbox: [],
|
|
@@ -252,6 +336,11 @@ function emptyWorkspace() {
|
|
|
252
336
|
cooldownUntil: 0,
|
|
253
337
|
circuitBroken: false,
|
|
254
338
|
circuitReason: '',
|
|
339
|
+
hazardAlert: null,
|
|
340
|
+
lastGoalAchievedSig: '',
|
|
341
|
+
autoPilotStartedAt: 0,
|
|
342
|
+
autoPilotHadTurn: false,
|
|
343
|
+
lastAutoArchiveOrgAt: 0,
|
|
255
344
|
},
|
|
256
345
|
flippedPrecipitatedIds: [],
|
|
257
346
|
}
|
|
@@ -263,12 +352,17 @@ function normalizeFact(raw) {
|
|
|
263
352
|
if (!text || secretLike(text)) return null
|
|
264
353
|
const validCategories = ['discipline', 'architecture', 'progress', 'preference', 'team']
|
|
265
354
|
const category = validCategories.includes(raw.category) ? raw.category : 'discipline'
|
|
355
|
+
const peerRootIds = Array.isArray(raw.peerRootIds)
|
|
356
|
+
? [...new Set(raw.peerRootIds.map(x => String(x || '').trim()).filter(Boolean))].slice(0, 16)
|
|
357
|
+
: []
|
|
266
358
|
return {
|
|
267
359
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('fact'),
|
|
268
360
|
text,
|
|
269
361
|
category,
|
|
270
362
|
by: clamp(raw.by || 'chief', 36),
|
|
271
363
|
source: clamp(raw.source || '', 60),
|
|
364
|
+
originRootId: typeof raw.originRootId === 'string' ? raw.originRootId.trim() : '',
|
|
365
|
+
...(peerRootIds.length ? { peerRootIds } : {}),
|
|
272
366
|
pinned: Boolean(raw.pinned),
|
|
273
367
|
addedAt: Number(raw.addedAt) || Date.now(),
|
|
274
368
|
updatedAt: Number(raw.updatedAt) || Number(raw.addedAt) || Date.now(),
|
|
@@ -279,7 +373,7 @@ function normalizeSuggestion(raw) {
|
|
|
279
373
|
if (!raw || typeof raw !== 'object') return null
|
|
280
374
|
const title = clamp(raw.title, 90)
|
|
281
375
|
if (!title) return null
|
|
282
|
-
const kind = ['bound', 'board', 'goal_approval', 'relay'].includes(raw.kind) ? raw.kind : 'relay'
|
|
376
|
+
const kind = ['bound', 'board', 'goal_approval', 'relay', 'advice'].includes(raw.kind) ? raw.kind : 'relay'
|
|
283
377
|
const boundField = ['forbidden', 'allowed', 'notes'].includes(raw.boundField) ? raw.boundField : 'forbidden'
|
|
284
378
|
const replaces = Array.isArray(raw.replaces)
|
|
285
379
|
? raw.replaces.map(x => String(x || '').trim()).filter(Boolean).slice(0, 20)
|
|
@@ -294,12 +388,14 @@ function normalizeSuggestion(raw) {
|
|
|
294
388
|
title,
|
|
295
389
|
reason: clamp(raw.reason || '', 220),
|
|
296
390
|
target: clamp(raw.target || (kind === 'bound' ? 'bounds' : kind === 'goal_approval' ? 'board' : 'lead'), 64),
|
|
297
|
-
targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'goal_approval' ? '目标结项批示' : '主对话'), 40),
|
|
298
|
-
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : 'steer',
|
|
391
|
+
targetLabel: clamp(raw.targetLabel || raw.target || (kind === 'bound' ? '工作边界' : kind === 'goal_approval' ? '目标结项批示' : kind === 'advice' ? '参谋进言' : '主对话'), 40),
|
|
392
|
+
mode: ['steer', 'followup', 'silent'].includes(raw.mode) ? raw.mode : (kind === 'advice' ? 'followup' : 'steer'),
|
|
299
393
|
draftText: cleanMultiline(raw.draftText || '', 600),
|
|
300
394
|
evidence: cleanMultiline(raw.evidence || '', 600),
|
|
301
395
|
missing: clamp(raw.missing || '', 300),
|
|
302
396
|
boardOp: raw.boardOp && typeof raw.boardOp === 'object' ? raw.boardOp : null,
|
|
397
|
+
popup: Boolean(raw.popup || kind === 'advice'),
|
|
398
|
+
urgency: ['normal', 'high'].includes(raw.urgency) ? raw.urgency : 'normal',
|
|
303
399
|
status: ['pending', 'applied', 'dismissed'].includes(raw.status) ? raw.status : 'pending',
|
|
304
400
|
createdAt: Number(raw.createdAt) || Date.now(),
|
|
305
401
|
}
|
|
@@ -310,12 +406,22 @@ function normalizeMail(raw) {
|
|
|
310
406
|
const imageCount = Math.max(0, Math.round(Number(raw.imageCount) || 0))
|
|
311
407
|
const text = cleanMultiline(raw.text, 1500) || (imageCount > 0 ? `[附图 ×${imageCount}]` : '')
|
|
312
408
|
if (!text) return null
|
|
409
|
+
const participantRoots = Array.isArray(raw.participantRoots)
|
|
410
|
+
? [...new Set(raw.participantRoots.map(x => String(x || '').trim()).filter(Boolean))].sort().slice(0, 24)
|
|
411
|
+
: []
|
|
412
|
+
const validChannels = ['internal', 'pair', 'multi', 'broadcast']
|
|
413
|
+
const channelType = validChannels.includes(raw.channelType) ? raw.channelType : ''
|
|
313
414
|
return {
|
|
314
415
|
id: typeof raw.id === 'string' && raw.id ? raw.id : nextId('mail'),
|
|
315
416
|
from: clamp(raw.from || 'agent', 48),
|
|
316
417
|
fromSession: String(raw.fromSession || ''),
|
|
418
|
+
fromRootId: String(raw.fromRootId || ''),
|
|
317
419
|
to: clamp(raw.to || 'lead', 64),
|
|
318
420
|
toSession: String(raw.toSession || ''),
|
|
421
|
+
toRootId: String(raw.toRootId || ''),
|
|
422
|
+
...(participantRoots.length ? { participantRoots } : {}),
|
|
423
|
+
...(channelType ? { channelType } : {}),
|
|
424
|
+
...(raw.broadcastId ? { broadcastId: String(raw.broadcastId) } : {}),
|
|
319
425
|
subject: clamp(raw.subject || '', 80),
|
|
320
426
|
text,
|
|
321
427
|
...(imageCount > 0 ? { imageCount } : {}),
|
|
@@ -336,6 +442,7 @@ function normalizeWorkspace(raw) {
|
|
|
336
442
|
text: String(src.narrative.text || ''),
|
|
337
443
|
at: Number(src.narrative.at) || 0,
|
|
338
444
|
byModel: String(src.narrative.byModel || ''),
|
|
445
|
+
clusterSig: String(src.narrative.clusterSig || ''),
|
|
339
446
|
}
|
|
340
447
|
}
|
|
341
448
|
base.suggestions = (Array.isArray(src.suggestions) ? src.suggestions : [])
|
|
@@ -365,19 +472,45 @@ function normalizeWorkspace(raw) {
|
|
|
365
472
|
base.runtimeGuard = {
|
|
366
473
|
lastCompactedSeq: Math.max(0, Math.round(Number(rg.lastCompactedSeq) || 0)),
|
|
367
474
|
lastCompactedAt: Math.max(0, Number(rg.lastCompactedAt) || 0),
|
|
475
|
+
autoCompactCount: Math.max(0, Math.round(Number(rg.autoCompactCount) || 0)),
|
|
476
|
+
pendingSmartCompact: rg.pendingSmartCompact && typeof rg.pendingSmartCompact === 'object'
|
|
477
|
+
? {
|
|
478
|
+
at: Number(rg.pendingSmartCompact.at) || Date.now(),
|
|
479
|
+
reason: clamp(rg.pendingSmartCompact.reason || '', 240),
|
|
480
|
+
by: clamp(rg.pendingSmartCompact.by || 'lead', 40),
|
|
481
|
+
}
|
|
482
|
+
: null,
|
|
368
483
|
interventionTurns: Math.max(0, Math.round(Number(rg.interventionTurns) || 0)),
|
|
369
484
|
lastDigestHash: String(rg.lastDigestHash || ''),
|
|
370
485
|
unchangedCount: Math.max(0, Math.round(Number(rg.unchangedCount) || 0)),
|
|
371
486
|
cooldownUntil: Math.max(0, Number(rg.cooldownUntil) || 0),
|
|
372
487
|
circuitBroken: Boolean(rg.circuitBroken),
|
|
373
488
|
circuitReason: String(rg.circuitReason || ''),
|
|
489
|
+
hazardAlert: rg.hazardAlert && typeof rg.hazardAlert === 'object' && (rg.hazardAlert.reason || rg.hazardAlert.title)
|
|
490
|
+
? {
|
|
491
|
+
id: String(rg.hazardAlert.id || ''),
|
|
492
|
+
category: clamp(rg.hazardAlert.category || 'irreversible_risk', 40),
|
|
493
|
+
title: clamp(rg.hazardAlert.title || '强介入安全煞停', 120),
|
|
494
|
+
reason: cleanMultiline(rg.hazardAlert.reason || '', 600),
|
|
495
|
+
objective: clamp(rg.hazardAlert.objective || '', 300),
|
|
496
|
+
at: Math.max(0, Number(rg.hazardAlert.at) || 0),
|
|
497
|
+
}
|
|
498
|
+
: null,
|
|
499
|
+
lastGoalAchievedSig: String(rg.lastGoalAchievedSig || ''),
|
|
500
|
+
autoPilotStartedAt: Math.max(0, Number(rg.autoPilotStartedAt) || 0),
|
|
501
|
+
autoPilotHadTurn: Boolean(rg.autoPilotHadTurn),
|
|
502
|
+
lastAutoArchiveOrgAt: Math.max(0, Number(rg.lastAutoArchiveOrgAt) || 0),
|
|
374
503
|
}
|
|
375
504
|
if (src.config && typeof src.config === 'object') {
|
|
376
|
-
const validPaces = ['manual', 'smart', 'auto']
|
|
505
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
377
506
|
const pm = validPaces.includes(src.config.paceMode) ? src.config.paceMode : undefined
|
|
507
|
+
const rawStopped = typeof src.config.stopped === 'boolean' ? src.config.stopped : (pm === 'stopped')
|
|
508
|
+
const rawPerm = typeof src.config.permissionMode === 'string' ? normalizePermissionMode(src.config.permissionMode) : undefined
|
|
378
509
|
base.config = {
|
|
379
510
|
...(typeof src.config.modelRef === 'string' ? { modelRef: src.config.modelRef.trim() } : {}),
|
|
380
|
-
...(
|
|
511
|
+
...(rawPerm ? { permissionMode: rawPerm } : {}),
|
|
512
|
+
...(typeof src.config.stopped === 'boolean' || pm === 'stopped' ? { stopped: rawStopped } : {}),
|
|
513
|
+
...(pm ? { paceMode: pm, autoPilot: !rawStopped && pm === 'auto', autoReview: !rawStopped && pm !== 'manual' } : {}),
|
|
381
514
|
...(src.config.tacticalModes && typeof src.config.tacticalModes === 'object'
|
|
382
515
|
? { tacticalModes: normalizeTacticalModes(src.config.tacticalModes) }
|
|
383
516
|
: {}),
|
|
@@ -389,6 +522,57 @@ function normalizeWorkspace(raw) {
|
|
|
389
522
|
return base
|
|
390
523
|
}
|
|
391
524
|
|
|
525
|
+
export const COMPACT_THRESHOLD_MIN_PCT = 10
|
|
526
|
+
export const COMPACT_THRESHOLD_MAX_PCT = 95
|
|
527
|
+
export const COMPACT_PCT_WARN_FLOOR = 25
|
|
528
|
+
export const COMPACT_TOKEN_HARD_MIN = 8_000
|
|
529
|
+
export const COMPACT_TOKEN_WARN_FLOOR = 32_000
|
|
530
|
+
|
|
531
|
+
/** Format a token threshold cleanly into compact K/M display notation (e.g. `64K`, `1M`). */
|
|
532
|
+
export function formatCompactTokenShort(tokens) {
|
|
533
|
+
const n = Math.max(0, Math.round(Number(tokens) || 0))
|
|
534
|
+
if (n >= 1_000_000 && n % 100_000 === 0) {
|
|
535
|
+
const m = n / 1_000_000
|
|
536
|
+
return (Number.isInteger(m) ? String(m) : m.toFixed(1).replace(/\.0$/, '')) + 'M'
|
|
537
|
+
}
|
|
538
|
+
if (n >= 1_000) {
|
|
539
|
+
const k = n / 1_000
|
|
540
|
+
return (k >= 100 ? String(Math.round(k)) : k.toFixed(1).replace(/\.0$/, '')) + 'K'
|
|
541
|
+
}
|
|
542
|
+
return String(n)
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/**
|
|
546
|
+
* Parse custom context size threshold input (`'1M'` -> 1,000,000; `'64K'` -> 64,000; bare `'64'` -> `64K`).
|
|
547
|
+
* Bare numbers without a unit default to K, and values below `32K` attach a low-threshold warning.
|
|
548
|
+
*/
|
|
549
|
+
export function parseCompactTokensInput(rawInput) {
|
|
550
|
+
const s = String(rawInput ?? '').trim()
|
|
551
|
+
if (!s) return { ok: false, error: '请输入上下文阈值,例如 64K、1M 或纯数字(无单位默认为 K)' }
|
|
552
|
+
const m = s.match(/^(\d+(?:\.\d+)?)\s*(k|m|t|tokens?)?$/i)
|
|
553
|
+
if (!m) return { ok: false, error: '格式无效:支持如 64K、1M 或纯数字(无单位默认为 K)' }
|
|
554
|
+
const num = Number(m[1])
|
|
555
|
+
if (!Number.isFinite(num) || num <= 0) return { ok: false, error: '上下文阈值必须大于 0' }
|
|
556
|
+
const unit = (m[2] || 'k').toLowerCase()
|
|
557
|
+
let rawTokens = 0
|
|
558
|
+
if (unit === 'm') rawTokens = Math.round(num * 1_000_000)
|
|
559
|
+
else if (unit === 'k') rawTokens = Math.round(num * 1_000)
|
|
560
|
+
else rawTokens = Math.round(num)
|
|
561
|
+
const tokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
|
|
562
|
+
const displayInput = formatCompactTokenShort(tokens)
|
|
563
|
+
const lowWarning = tokens < COMPACT_TOKEN_WARN_FLOOR
|
|
564
|
+
? `当前阈值(${displayInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
|
|
565
|
+
: ''
|
|
566
|
+
return {
|
|
567
|
+
ok: true,
|
|
568
|
+
tokens,
|
|
569
|
+
rawTokens,
|
|
570
|
+
clampedToMin: rawTokens < COMPACT_TOKEN_HARD_MIN,
|
|
571
|
+
displayInput,
|
|
572
|
+
lowWarning,
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
|
|
392
576
|
/** Resolve effective Chief config for a specific root session (isolates `intervention` per session). */
|
|
393
577
|
export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
394
578
|
const safeState = state && typeof state === 'object' ? state : {}
|
|
@@ -397,21 +581,34 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
|
397
581
|
const sid = String(sessionId || '').trim()
|
|
398
582
|
const ws = sid && safeState.workspaces && safeState.workspaces[sid] ? safeState.workspaces[sid] : null
|
|
399
583
|
const wsCfg = ws && ws.config && typeof ws.config === 'object' ? ws.config : null
|
|
400
|
-
const validPaces = ['manual', 'smart', 'auto']
|
|
401
|
-
const
|
|
584
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
585
|
+
const basePaceSafe = validPaces.includes(base.paceMode) && !(sid && base.paceMode === 'auto')
|
|
586
|
+
? base.paceMode
|
|
587
|
+
: 'manual'
|
|
588
|
+
const rawPaceMode = wsCfg && validPaces.includes(wsCfg.paceMode)
|
|
402
589
|
? wsCfg.paceMode
|
|
403
|
-
:
|
|
590
|
+
: basePaceSafe
|
|
591
|
+
const explicitStopped = wsCfg && typeof wsCfg.stopped === 'boolean'
|
|
592
|
+
? wsCfg.stopped
|
|
593
|
+
: (typeof base.stopped === 'boolean' ? base.stopped : false)
|
|
594
|
+
const stopped = rawPaceMode === 'stopped' || explicitStopped
|
|
595
|
+
const paceMode = stopped ? 'stopped' : rawPaceMode
|
|
404
596
|
const modelRef = wsCfg && typeof wsCfg.modelRef === 'string'
|
|
405
597
|
? wsCfg.modelRef.trim()
|
|
406
598
|
: (typeof base.modelRef === 'string' ? base.modelRef.trim() : '')
|
|
407
599
|
const mergedTactical = wsCfg && wsCfg.tacticalModes
|
|
408
600
|
? normalizeTacticalModes({ ...baseTactical, ...wsCfg.tacticalModes })
|
|
409
601
|
: { ...baseTactical, ...(sid ? { intervention: false } : {}) }
|
|
602
|
+
const permissionMode = normalizePermissionMode(
|
|
603
|
+
(wsCfg && wsCfg.permissionMode) || base.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE
|
|
604
|
+
)
|
|
410
605
|
return {
|
|
411
606
|
modelRef,
|
|
412
607
|
paceMode,
|
|
413
|
-
|
|
414
|
-
|
|
608
|
+
stopped,
|
|
609
|
+
permissionMode,
|
|
610
|
+
autoPilot: !stopped && paceMode === 'auto',
|
|
611
|
+
autoReview: !stopped && paceMode !== 'manual',
|
|
415
612
|
tacticalModes: mergedTactical,
|
|
416
613
|
}
|
|
417
614
|
}
|
|
@@ -419,7 +616,11 @@ export function resolveWorkspaceConfig(state, sessionId = '') {
|
|
|
419
616
|
const DEFAULT_TACTICAL_MODES = {
|
|
420
617
|
intervention: false,
|
|
421
618
|
autoCompact: false,
|
|
619
|
+
smartCompact: false,
|
|
620
|
+
compactThresholdMode: 'pct',
|
|
422
621
|
compactThresholdPct: 80,
|
|
622
|
+
compactThresholdTokens: 64_000,
|
|
623
|
+
compactThresholdInput: '64K',
|
|
423
624
|
strictVerify: false,
|
|
424
625
|
redlineSentinel: false,
|
|
425
626
|
conciseBrief: false,
|
|
@@ -429,15 +630,29 @@ const DEFAULT_TACTICAL_MODES = {
|
|
|
429
630
|
function normalizeTacticalModes(raw) {
|
|
430
631
|
const src = raw && typeof raw === 'object' ? raw : {}
|
|
431
632
|
const pct = Math.round(Number(src.compactThresholdPct) || DEFAULT_TACTICAL_MODES.compactThresholdPct)
|
|
432
|
-
const
|
|
633
|
+
const mode = src.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
|
|
634
|
+
const rawTokens = Math.round(Number(src.compactThresholdTokens) || DEFAULT_TACTICAL_MODES.compactThresholdTokens)
|
|
635
|
+
const compactThresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, rawTokens)
|
|
636
|
+
const compactThresholdInput = typeof src.compactThresholdInput === 'string' && src.compactThresholdInput.trim()
|
|
637
|
+
? src.compactThresholdInput.trim()
|
|
638
|
+
: formatCompactTokenShort(compactThresholdTokens)
|
|
639
|
+
const rawTurns = src.maxInterventionTurns
|
|
640
|
+
const isZeroTurns = rawTurns === 0 || rawTurns === '0'
|
|
641
|
+
const parsedTurns = isZeroTurns
|
|
642
|
+
? 0
|
|
643
|
+
: Math.min(30, Math.max(1, Math.round(Number(rawTurns) || DEFAULT_TACTICAL_MODES.maxInterventionTurns)))
|
|
433
644
|
return {
|
|
434
645
|
intervention: Boolean(src.intervention),
|
|
435
646
|
autoCompact: Boolean(src.autoCompact),
|
|
436
|
-
|
|
647
|
+
smartCompact: Boolean(src.smartCompact),
|
|
648
|
+
compactThresholdMode: mode,
|
|
649
|
+
compactThresholdPct: Math.min(COMPACT_THRESHOLD_MAX_PCT, Math.max(COMPACT_THRESHOLD_MIN_PCT, pct)),
|
|
650
|
+
compactThresholdTokens,
|
|
651
|
+
compactThresholdInput,
|
|
437
652
|
strictVerify: Boolean(src.strictVerify),
|
|
438
653
|
redlineSentinel: Boolean(src.redlineSentinel),
|
|
439
654
|
conciseBrief: Boolean(src.conciseBrief),
|
|
440
|
-
maxInterventionTurns:
|
|
655
|
+
maxInterventionTurns: parsedTurns,
|
|
441
656
|
}
|
|
442
657
|
}
|
|
443
658
|
|
|
@@ -459,16 +674,20 @@ function normalizeState(raw) {
|
|
|
459
674
|
workspaces[k] = normalizeWorkspace(ws)
|
|
460
675
|
}
|
|
461
676
|
}
|
|
462
|
-
const validPaces = ['manual', 'smart', 'auto']
|
|
677
|
+
const validPaces = ['manual', 'smart', 'auto', 'stopped']
|
|
463
678
|
// Default to 'manual' (human-paced, zero background token burn) unless explicitly set to smart/auto
|
|
464
|
-
const
|
|
679
|
+
const rawPace = validPaces.includes(cfg.paceMode) ? cfg.paceMode : 'manual'
|
|
680
|
+
const stopped = rawPace === 'stopped' || Boolean(cfg.stopped)
|
|
681
|
+
const paceMode = stopped ? 'stopped' : rawPace
|
|
465
682
|
return {
|
|
466
683
|
version: STATE_VERSION,
|
|
467
684
|
config: {
|
|
468
685
|
modelRef: typeof cfg.modelRef === 'string' ? cfg.modelRef.trim() : '',
|
|
469
686
|
paceMode,
|
|
470
|
-
|
|
471
|
-
|
|
687
|
+
stopped,
|
|
688
|
+
permissionMode: normalizePermissionMode(cfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE),
|
|
689
|
+
autoPilot: !stopped && paceMode === 'auto',
|
|
690
|
+
autoReview: !stopped && paceMode !== 'manual',
|
|
472
691
|
tacticalModes: normalizeTacticalModes(cfg.tacticalModes),
|
|
473
692
|
},
|
|
474
693
|
links,
|
|
@@ -545,11 +764,19 @@ export function getLinkedCluster(state, rootSessionId) {
|
|
|
545
764
|
return [...visited].sort()
|
|
546
765
|
}
|
|
547
766
|
|
|
767
|
+
export function computeClusterSig(cluster = []) {
|
|
768
|
+
return [...new Set((Array.isArray(cluster) ? cluster : []).map(x => String(x || '').trim()).filter(Boolean))].sort().join('|')
|
|
769
|
+
}
|
|
770
|
+
|
|
548
771
|
export function setPeerLink(rootA, rootB, linked) {
|
|
549
772
|
const a = String(rootA || '').trim()
|
|
550
773
|
const b = String(rootB || '').trim()
|
|
551
774
|
if (!a || !b || a === b) return { ok: false, error: '需要两个不同的主会话才能建立协同连接' }
|
|
552
775
|
return mutateChiefState((state) => {
|
|
776
|
+
const affected = new Set([
|
|
777
|
+
...getLinkedCluster(state, a),
|
|
778
|
+
...getLinkedCluster(state, b),
|
|
779
|
+
])
|
|
553
780
|
const setA = new Set(state.links[a] || [])
|
|
554
781
|
const setB = new Set(state.links[b] || [])
|
|
555
782
|
if (linked) {
|
|
@@ -563,6 +790,23 @@ export function setPeerLink(rootA, rootB, linked) {
|
|
|
563
790
|
else delete state.links[a]
|
|
564
791
|
if (setB.size) state.links[b] = [...setB]
|
|
565
792
|
else delete state.links[b]
|
|
793
|
+
|
|
794
|
+
// Topology isolation guard: purge stale narrative caches on EVERY affected session whose cluster changed
|
|
795
|
+
// so detaching from a peer cluster NEVER leaves residual peer context inside Chief's narrative digest!
|
|
796
|
+
const now = Date.now()
|
|
797
|
+
for (const sid of affected) {
|
|
798
|
+
const ws = ensureWorkspace(state, sid)
|
|
799
|
+
const nextCluster = getLinkedCluster(state, sid)
|
|
800
|
+
const nextSig = computeClusterSig(nextCluster)
|
|
801
|
+
if (!ws.narrative || ws.narrative.clusterSig !== nextSig) {
|
|
802
|
+
ws.narrative = { hash: '', text: '', at: 0, byModel: '', clusterSig: nextSig }
|
|
803
|
+
}
|
|
804
|
+
if (!linked) {
|
|
805
|
+
ws.seenFactsAt = { [sid]: now }
|
|
806
|
+
} else {
|
|
807
|
+
ws.seenFactsAt = {}
|
|
808
|
+
}
|
|
809
|
+
}
|
|
566
810
|
return { ok: true, cluster: getLinkedCluster(state, a) }
|
|
567
811
|
})
|
|
568
812
|
}
|
|
@@ -573,16 +817,41 @@ function ensureWorkspace(state, rootId) {
|
|
|
573
817
|
return state.workspaces[key]
|
|
574
818
|
}
|
|
575
819
|
|
|
576
|
-
|
|
820
|
+
function filterFactsForCluster(rawFacts, clusterSet, rootId) {
|
|
821
|
+
return (Array.isArray(rawFacts) ? rawFacts : []).filter((f) => {
|
|
822
|
+
if (!f || !f.text) return false
|
|
823
|
+
if (f.originRootId && !clusterSet.has(f.originRootId)) return false
|
|
824
|
+
if (f.category === 'team' && Array.isArray(f.peerRootIds) && f.peerRootIds.length > 0) {
|
|
825
|
+
// A team fact created during multi-session collaboration stays ONLY if another participant besides rootId remains linked
|
|
826
|
+
const participants = f.originRootId ? [f.originRootId, ...f.peerRootIds] : f.peerRootIds
|
|
827
|
+
const peerStillLinked = participants.some(pid => pid && pid !== rootId && clusterSet.has(pid))
|
|
828
|
+
if (!peerStillLinked) return false
|
|
829
|
+
}
|
|
830
|
+
return true
|
|
831
|
+
})
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function annotateMailClusterState(mail, clusterSet) {
|
|
835
|
+
if (!mail || typeof mail !== 'object') return mail
|
|
836
|
+
const fromOut = Boolean(mail.fromRootId && !clusterSet.has(mail.fromRootId))
|
|
837
|
+
const toOut = Boolean(mail.toRootId && mail.toRootId !== 'all' && !clusterSet.has(mail.toRootId))
|
|
838
|
+
const detachedFromCluster = fromOut || toOut
|
|
839
|
+
return detachedFromCluster ? { ...mail, detachedFromCluster: true } : mail
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
/** Merge facts & mailbox across all linked peer sessions in the federation cluster, isolating detached artifacts. */
|
|
577
843
|
function clusterView(state, rootId) {
|
|
578
844
|
const cluster = getLinkedCluster(state, rootId)
|
|
845
|
+
const clusterSig = computeClusterSig(cluster)
|
|
846
|
+
const clusterSet = new Set(cluster)
|
|
579
847
|
const primary = ensureWorkspace(state, rootId)
|
|
580
848
|
if (cluster.length <= 1) {
|
|
581
849
|
return {
|
|
582
850
|
cluster,
|
|
851
|
+
clusterSig,
|
|
583
852
|
primary,
|
|
584
|
-
facts: primary.facts,
|
|
585
|
-
mailbox: primary.mailbox,
|
|
853
|
+
facts: filterFactsForCluster(primary.facts, clusterSet, rootId),
|
|
854
|
+
mailbox: (primary.mailbox || []).map(m => annotateMailClusterState(m, clusterSet)),
|
|
586
855
|
suggestions: primary.suggestions.filter(s => s.status === 'pending'),
|
|
587
856
|
chat: primary.chat,
|
|
588
857
|
narrative: primary.narrative,
|
|
@@ -592,13 +861,20 @@ function clusterView(state, rootId) {
|
|
|
592
861
|
const mailMap = new Map()
|
|
593
862
|
for (const sid of cluster) {
|
|
594
863
|
const ws = ensureWorkspace(state, sid)
|
|
595
|
-
for (const f of ws.facts) factMap.set(f.id, f)
|
|
596
|
-
for (const m of ws.mailbox)
|
|
864
|
+
for (const f of filterFactsForCluster(ws.facts, clusterSet, rootId)) factMap.set(f.id, f)
|
|
865
|
+
for (const m of ws.mailbox) {
|
|
866
|
+
if (m && m.broadcastId && m.channelType === 'broadcast') {
|
|
867
|
+
mailMap.set('bcast:' + m.broadcastId, annotateMailClusterState(m, clusterSet))
|
|
868
|
+
} else {
|
|
869
|
+
mailMap.set(m.id, annotateMailClusterState(m, clusterSet))
|
|
870
|
+
}
|
|
871
|
+
}
|
|
597
872
|
}
|
|
598
873
|
const facts = [...factMap.values()].sort((a, b) => (a.addedAt || 0) - (b.addedAt || 0)).slice(-FACTS_CAP)
|
|
599
874
|
const mailbox = [...mailMap.values()].sort((a, b) => (a.at || 0) - (b.at || 0)).slice(-MAIL_CAP)
|
|
600
875
|
return {
|
|
601
876
|
cluster,
|
|
877
|
+
clusterSig,
|
|
602
878
|
primary,
|
|
603
879
|
facts,
|
|
604
880
|
mailbox,
|
|
@@ -1184,6 +1460,74 @@ export async function buildMessageEnvelope(text, sourceKind = CHIEF_RELAY_SOURCE
|
|
|
1184
1460
|
}
|
|
1185
1461
|
}
|
|
1186
1462
|
|
|
1463
|
+
function summarizeBoardProgress(board) {
|
|
1464
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1465
|
+
const doneCount = tasks.filter(t => t && t.status === 'done').length
|
|
1466
|
+
const doingCount = tasks.filter(t => t && t.status === 'doing').length
|
|
1467
|
+
const blockedCount = tasks.filter(t => t && t.status === 'blocked').length
|
|
1468
|
+
const todoCount = tasks.filter(t => t && t.status === 'todo').length
|
|
1469
|
+
const plan = Array.isArray(board && board.plan) ? board.plan : []
|
|
1470
|
+
const planDone = plan.filter(s => s && s.done).length
|
|
1471
|
+
const cursorStep = clamp(board && board.cursor && board.cursor.step ? board.cursor.step : '', 48)
|
|
1472
|
+
const parts = []
|
|
1473
|
+
if (tasks.length > 0) parts.push(`任务 ${doneCount}完/${doingCount}做${blockedCount ? `/${blockedCount}阻` : ''}/${tasks.length}`)
|
|
1474
|
+
else if (plan.length > 0) parts.push(`步骤 ${planDone}/${plan.length}`)
|
|
1475
|
+
if (cursorStep) parts.push(`断点:${cursorStep}`)
|
|
1476
|
+
return parts.join(' · ')
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
export function collectClusterPeerProgress(deps, cluster = [], selfRootId = '') {
|
|
1480
|
+
const self = String(selfRootId || '').trim()
|
|
1481
|
+
const members = Array.isArray(cluster) ? cluster.filter(sid => sid && sid !== self) : []
|
|
1482
|
+
if (!members.length) return []
|
|
1483
|
+
const runtime = deps && deps.runtime
|
|
1484
|
+
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
1485
|
+
const out = []
|
|
1486
|
+
for (const sid of members) {
|
|
1487
|
+
let board = null
|
|
1488
|
+
try {
|
|
1489
|
+
board = deps.boardForSession ? deps.boardForSession(deps.boardFileFor(sid)) : null
|
|
1490
|
+
} catch {}
|
|
1491
|
+
if (!board) continue
|
|
1492
|
+
let rootAgent = null
|
|
1493
|
+
try {
|
|
1494
|
+
rootAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(sid) : null
|
|
1495
|
+
} catch {}
|
|
1496
|
+
const name = (deps.sessionName && deps.sessionName(runtime, rootAgent || sid)) || ('会话 ' + sid.replace(/^session-/, '').slice(0, 8))
|
|
1497
|
+
const tasks = Array.isArray(board.tasks) ? board.tasks : []
|
|
1498
|
+
const doneCount = tasks.filter(t => t && t.status === 'done').length
|
|
1499
|
+
const doingCount = tasks.filter(t => t && t.status === 'doing').length
|
|
1500
|
+
const blockedCount = tasks.filter(t => t && t.status === 'blocked').length
|
|
1501
|
+
const todoCount = tasks.filter(t => t && t.status === 'todo').length
|
|
1502
|
+
const topTasks = tasks
|
|
1503
|
+
.filter(t => t && t.status !== 'done')
|
|
1504
|
+
.slice(0, 3)
|
|
1505
|
+
.map(t => `[${t.status}] #${t.id} ${clamp(t.title, 44)}`)
|
|
1506
|
+
const recentConclusions = (Array.isArray(board.memory) ? board.memory : [])
|
|
1507
|
+
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
1508
|
+
.slice(-2)
|
|
1509
|
+
.map(m => clamp(stripCheckpointNoise(m.title || m.text), 72))
|
|
1510
|
+
.filter(Boolean)
|
|
1511
|
+
out.push({
|
|
1512
|
+
rootId: sid,
|
|
1513
|
+
name,
|
|
1514
|
+
status: rootAgent && rootAgent.status === 'running' ? 'running' : 'idle',
|
|
1515
|
+
objective: clamp(board.objective || '', 120),
|
|
1516
|
+
cursorStep: clamp(board.cursor && board.cursor.step ? board.cursor.step : '', 90),
|
|
1517
|
+
cursorNext: clamp(board.cursor && board.cursor.next ? board.cursor.next : '', 90),
|
|
1518
|
+
cursorBlocked: clamp(board.cursor && board.cursor.blocked ? board.cursor.blocked : '', 90),
|
|
1519
|
+
doingCount,
|
|
1520
|
+
doneCount,
|
|
1521
|
+
blockedCount,
|
|
1522
|
+
todoCount,
|
|
1523
|
+
topTasks,
|
|
1524
|
+
recentConclusions,
|
|
1525
|
+
progressSummary: summarizeBoardProgress(board),
|
|
1526
|
+
})
|
|
1527
|
+
}
|
|
1528
|
+
return out
|
|
1529
|
+
}
|
|
1530
|
+
|
|
1187
1531
|
/** Build complete addressable peer directory across lead, subagents, and federated root sessions. */
|
|
1188
1532
|
export async function listPeerDirectory(deps, sessionId) {
|
|
1189
1533
|
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || '')
|
|
@@ -1210,6 +1554,7 @@ export async function listPeerDirectory(deps, sessionId) {
|
|
|
1210
1554
|
const roster = await deps.refreshSubagentTree(runtime, memberRootId, board)
|
|
1211
1555
|
const rootAgent = agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(memberRootId) : null
|
|
1212
1556
|
const rootTitle = deps.sessionName(runtime, rootAgent || memberRootId) || ('会话 ' + memberRootId.replace(/^session-/, '').slice(0, 8))
|
|
1557
|
+
const memberProgressSummary = summarizeBoardProgress(board)
|
|
1213
1558
|
|
|
1214
1559
|
for (const entry of roster) {
|
|
1215
1560
|
if (!entry) continue
|
|
@@ -1229,6 +1574,7 @@ export async function listPeerDirectory(deps, sessionId) {
|
|
|
1229
1574
|
isCurrentRoot,
|
|
1230
1575
|
status: entry.status === 'running' ? 'running' : 'idle',
|
|
1231
1576
|
taskTitle: entry.taskTitle || entry.description || (board && board.objective ? clamp(board.objective, 48) : ''),
|
|
1577
|
+
...(isLead ? { progressSummary: memberProgressSummary, objective: clamp(board && board.objective ? board.objective : '', 80) } : {}),
|
|
1232
1578
|
parentId: entry.parentId || memberRootId,
|
|
1233
1579
|
mode: entry.mode || 'continuable',
|
|
1234
1580
|
})
|
|
@@ -1252,6 +1598,7 @@ export async function listPeerDirectory(deps, sessionId) {
|
|
|
1252
1598
|
linked: isLinked,
|
|
1253
1599
|
objective: clamp(b && b.objective ? b.objective : '', 80),
|
|
1254
1600
|
openTasks: Array.isArray(b && b.tasks) ? b.tasks.filter(t => t.status !== 'done').length : 0,
|
|
1601
|
+
progressSummary: summarizeBoardProgress(b),
|
|
1255
1602
|
})
|
|
1256
1603
|
}
|
|
1257
1604
|
|
|
@@ -1348,17 +1695,20 @@ export async function deliverCrossMessage(deps, {
|
|
|
1348
1695
|
const totalImgCount = Math.max(admittedBlocks.length, savedPaths.length)
|
|
1349
1696
|
const imgTag = totalImgCount > 0 ? ` [附图 ×${totalImgCount}]` : ''
|
|
1350
1697
|
|
|
1351
|
-
const rootId = deps.resolveRootSessionId(fromSession) || String(fromSession ||
|
|
1698
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(fromSession)) || String(fromSession || directoryRootFallback(fromSession))
|
|
1352
1699
|
const directory = await listPeerDirectory(deps, rootId || fromSession)
|
|
1700
|
+
const senderRootId = rootId || directory.rootId || ''
|
|
1353
1701
|
const rawTarget = String(target || 'lead').trim().replace(/^@/, '')
|
|
1354
1702
|
|
|
1355
|
-
// Broadcast support: 'all' / '全体' / 'team'
|
|
1703
|
+
// Broadcast support: 'all' / '全体' / 'team' (deduplicated single mailbox record for clean drawer UI)
|
|
1356
1704
|
if (['all', 'team', '全体', '所有人'].includes(rawTarget.toLowerCase())) {
|
|
1357
1705
|
const recipients = directory.targets.filter(t => t.id !== fromSession)
|
|
1358
1706
|
const deliveries = []
|
|
1707
|
+
const deliveredReadMarks = []
|
|
1359
1708
|
for (const peer of recipients) {
|
|
1360
1709
|
const res = await deliverSinglePeer(deps, directory, peer, {
|
|
1361
1710
|
fromSession,
|
|
1711
|
+
fromRootId: senderRootId,
|
|
1362
1712
|
fromLabel,
|
|
1363
1713
|
text: effectiveText,
|
|
1364
1714
|
subject,
|
|
@@ -1366,13 +1716,119 @@ export async function deliverCrossMessage(deps, {
|
|
|
1366
1716
|
imageBlocks: admittedBlocks,
|
|
1367
1717
|
savedImagePaths: savedPaths,
|
|
1368
1718
|
recordBoardLog: false,
|
|
1719
|
+
recordMailbox: false,
|
|
1369
1720
|
})
|
|
1370
1721
|
deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
|
|
1722
|
+
if (res.deliveredPhysical) {
|
|
1723
|
+
if (peer.id) deliveredReadMarks.push(peer.id)
|
|
1724
|
+
if (peer.key) deliveredReadMarks.push(peer.key)
|
|
1725
|
+
if (peer.name) deliveredReadMarks.push(peer.name)
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
const participantRoots = [...new Set([senderRootId, ...(directory.cluster || [])].filter(Boolean))].sort()
|
|
1729
|
+
const imgNoticeBlock = buildSavedImageNotice(savedPaths)
|
|
1730
|
+
const textWithImagePaths = imgNoticeBlock ? `${effectiveText}\n${imgNoticeBlock}` : effectiveText
|
|
1731
|
+
const broadcastId = nextId('bcast')
|
|
1732
|
+
const mailItem = normalizeMail({
|
|
1733
|
+
id: nextId('mail'),
|
|
1734
|
+
from: fromLabel,
|
|
1735
|
+
fromSession,
|
|
1736
|
+
fromRootId: senderRootId,
|
|
1737
|
+
to: 'all',
|
|
1738
|
+
toSession: 'all',
|
|
1739
|
+
toRootId: 'all',
|
|
1740
|
+
participantRoots,
|
|
1741
|
+
channelType: participantRoots.length > 1 ? 'broadcast' : 'internal',
|
|
1742
|
+
broadcastId,
|
|
1743
|
+
subject,
|
|
1744
|
+
text: totalImgCount > 0 ? `${textWithImagePaths}${imgTag}` : textWithImagePaths,
|
|
1745
|
+
imageCount: totalImgCount,
|
|
1746
|
+
mode,
|
|
1747
|
+
deliveredPhysical: deliveries.some(d => d.ok && d.mode !== 'mailbox-queued'),
|
|
1748
|
+
readBy: [...new Set(deliveredReadMarks)],
|
|
1749
|
+
at: Date.now(),
|
|
1750
|
+
})
|
|
1751
|
+
if (mailItem) {
|
|
1752
|
+
mutateChiefState((state) => {
|
|
1753
|
+
const ws = ensureWorkspace(state, senderRootId || directory.rootId)
|
|
1754
|
+
ws.mailbox.push(mailItem)
|
|
1755
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
1756
|
+
})
|
|
1371
1757
|
}
|
|
1372
1758
|
if (recordBoardLog && rootId) {
|
|
1373
1759
|
deps.appendBoardLog(rootId, `📡 ${fromLabel} 向全体成员广播递话(${deliveries.filter(d => d.ok).length} 个目标):${clamp(effectiveText, 56)}${imgTag}`, fromLabel)
|
|
1374
1760
|
}
|
|
1375
|
-
return { ok: true, broadcast: true, deliveries, savedImagePaths: savedPaths }
|
|
1761
|
+
return { ok: true, broadcast: true, target: 'all', mail: mailItem, deliveries, savedImagePaths: savedPaths }
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
// Multi-target comma-separated support (e.g. "sessionA,sessionB" or "worker1,worker2")
|
|
1765
|
+
if (/[,,]/.test(rawTarget)) {
|
|
1766
|
+
const parts = rawTarget.split(/[,,]/).map(s => s.trim().replace(/^@/, '')).filter(Boolean)
|
|
1767
|
+
const matched = []
|
|
1768
|
+
const seenKeys = new Set()
|
|
1769
|
+
for (const part of parts) {
|
|
1770
|
+
const hit = matchTargetPeer(directory.targets, part)
|
|
1771
|
+
if (hit && !seenKeys.has(hit.key)) {
|
|
1772
|
+
seenKeys.add(hit.key)
|
|
1773
|
+
matched.push(hit)
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
if (matched.length >= 2) {
|
|
1777
|
+
const deliveries = []
|
|
1778
|
+
const readMarks = []
|
|
1779
|
+
const roots = new Set([senderRootId].filter(Boolean))
|
|
1780
|
+
for (const peer of matched) {
|
|
1781
|
+
if (peer.rootId) roots.add(peer.rootId)
|
|
1782
|
+
const res = await deliverSinglePeer(deps, directory, peer, {
|
|
1783
|
+
fromSession,
|
|
1784
|
+
fromRootId: senderRootId,
|
|
1785
|
+
fromLabel,
|
|
1786
|
+
text: effectiveText,
|
|
1787
|
+
subject,
|
|
1788
|
+
mode,
|
|
1789
|
+
imageBlocks: admittedBlocks,
|
|
1790
|
+
savedImagePaths: savedPaths,
|
|
1791
|
+
recordBoardLog: false,
|
|
1792
|
+
recordMailbox: false,
|
|
1793
|
+
})
|
|
1794
|
+
deliveries.push({ target: peer.handle, ok: res.ok, mode: res.deliveryMode })
|
|
1795
|
+
if (res.deliveredPhysical) {
|
|
1796
|
+
if (peer.id) readMarks.push(peer.id)
|
|
1797
|
+
if (peer.key) readMarks.push(peer.key)
|
|
1798
|
+
if (peer.name) readMarks.push(peer.name)
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
const participantRoots = [...roots].sort()
|
|
1802
|
+
const imgNoticeBlock = buildSavedImageNotice(savedPaths)
|
|
1803
|
+
const textWithImagePaths = imgNoticeBlock ? `${effectiveText}\n${imgNoticeBlock}` : effectiveText
|
|
1804
|
+
const mailItem = normalizeMail({
|
|
1805
|
+
id: nextId('mail'),
|
|
1806
|
+
from: fromLabel,
|
|
1807
|
+
fromSession,
|
|
1808
|
+
fromRootId: senderRootId,
|
|
1809
|
+
to: matched.map(m => m.handle).join('、'),
|
|
1810
|
+
toSession: matched.map(m => m.id || m.key).join(','),
|
|
1811
|
+
toRootId: participantRoots.length > 1 ? 'multi' : (participantRoots[0] || ''),
|
|
1812
|
+
participantRoots,
|
|
1813
|
+
channelType: participantRoots.length >= 3 ? 'multi' : (participantRoots.length === 2 ? 'pair' : 'internal'),
|
|
1814
|
+
broadcastId: nextId('multi'),
|
|
1815
|
+
subject,
|
|
1816
|
+
text: totalImgCount > 0 ? `${textWithImagePaths}${imgTag}` : textWithImagePaths,
|
|
1817
|
+
imageCount: totalImgCount,
|
|
1818
|
+
mode,
|
|
1819
|
+
deliveredPhysical: deliveries.some(d => d.ok && d.mode !== 'mailbox-queued'),
|
|
1820
|
+
readBy: [...new Set(readMarks)],
|
|
1821
|
+
at: Date.now(),
|
|
1822
|
+
})
|
|
1823
|
+
if (mailItem) {
|
|
1824
|
+
mutateChiefState((state) => {
|
|
1825
|
+
const ws = ensureWorkspace(state, senderRootId || directory.rootId)
|
|
1826
|
+
ws.mailbox.push(mailItem)
|
|
1827
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
1828
|
+
})
|
|
1829
|
+
}
|
|
1830
|
+
return { ok: true, multi: true, target: matched.map(m => m.handle).join('、'), mail: mailItem, deliveries, savedImagePaths: savedPaths }
|
|
1831
|
+
}
|
|
1376
1832
|
}
|
|
1377
1833
|
|
|
1378
1834
|
const peer = matchTargetPeer(directory.targets, rawTarget)
|
|
@@ -1385,6 +1841,7 @@ export async function deliverCrossMessage(deps, {
|
|
|
1385
1841
|
|
|
1386
1842
|
return deliverSinglePeer(deps, directory, peer, {
|
|
1387
1843
|
fromSession,
|
|
1844
|
+
fromRootId: senderRootId,
|
|
1388
1845
|
fromLabel,
|
|
1389
1846
|
text: effectiveText,
|
|
1390
1847
|
subject,
|
|
@@ -1392,11 +1849,17 @@ export async function deliverCrossMessage(deps, {
|
|
|
1392
1849
|
imageBlocks: admittedBlocks,
|
|
1393
1850
|
savedImagePaths: savedPaths,
|
|
1394
1851
|
recordBoardLog,
|
|
1852
|
+
recordMailbox: true,
|
|
1395
1853
|
})
|
|
1396
1854
|
}
|
|
1397
1855
|
|
|
1856
|
+
function directoryRootFallback(fromSession) {
|
|
1857
|
+
return String(fromSession || 'global')
|
|
1858
|
+
}
|
|
1859
|
+
|
|
1398
1860
|
async function deliverSinglePeer(deps, directory, peer, {
|
|
1399
1861
|
fromSession,
|
|
1862
|
+
fromRootId = '',
|
|
1400
1863
|
fromLabel,
|
|
1401
1864
|
text,
|
|
1402
1865
|
subject,
|
|
@@ -1404,6 +1867,7 @@ async function deliverSinglePeer(deps, directory, peer, {
|
|
|
1404
1867
|
imageBlocks = [],
|
|
1405
1868
|
savedImagePaths = [],
|
|
1406
1869
|
recordBoardLog,
|
|
1870
|
+
recordMailbox = true,
|
|
1407
1871
|
}) {
|
|
1408
1872
|
const runtime = deps.runtime
|
|
1409
1873
|
const agentsSvc = runtime ? runtime.get('agents') : null
|
|
@@ -1498,12 +1962,21 @@ async function deliverSinglePeer(deps, directory, peer, {
|
|
|
1498
1962
|
? [peer.id, peer.key, peer.name].filter(Boolean)
|
|
1499
1963
|
: []
|
|
1500
1964
|
|
|
1965
|
+
const senderRoot = String(fromRootId || (fromSession && deps.resolveRootSessionId && deps.resolveRootSessionId(fromSession)) || directory.rootId || '').trim()
|
|
1966
|
+
const targetRoot = String(peer.rootId || directory.rootId || '').trim()
|
|
1967
|
+
const participantRoots = [...new Set([senderRoot, targetRoot].filter(Boolean))].sort()
|
|
1968
|
+
const channelType = participantRoots.length >= 2 ? 'pair' : 'internal'
|
|
1969
|
+
|
|
1501
1970
|
const mailItem = normalizeMail({
|
|
1502
1971
|
id: nextId('mail'),
|
|
1503
1972
|
from: fromLabel,
|
|
1504
1973
|
fromSession,
|
|
1974
|
+
fromRootId: senderRoot,
|
|
1505
1975
|
to: peer.handle,
|
|
1506
1976
|
toSession: peer.id || peer.key,
|
|
1977
|
+
toRootId: targetRoot,
|
|
1978
|
+
participantRoots,
|
|
1979
|
+
channelType,
|
|
1507
1980
|
subject,
|
|
1508
1981
|
text: imgCount > 0 ? `${textWithImagePaths}${imgSuffix}` : textWithImagePaths,
|
|
1509
1982
|
imageCount: imgCount,
|
|
@@ -1513,11 +1986,13 @@ async function deliverSinglePeer(deps, directory, peer, {
|
|
|
1513
1986
|
at: Date.now(),
|
|
1514
1987
|
})
|
|
1515
1988
|
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1989
|
+
if (recordMailbox && mailItem) {
|
|
1990
|
+
mutateChiefState((state) => {
|
|
1991
|
+
const ws = ensureWorkspace(state, peer.rootId || directory.rootId)
|
|
1992
|
+
ws.mailbox.push(mailItem)
|
|
1993
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
1994
|
+
})
|
|
1995
|
+
}
|
|
1521
1996
|
|
|
1522
1997
|
if (recordBoardLog && (peer.rootId || directory.rootId)) {
|
|
1523
1998
|
const badge = mode === 'steer' ? '⚡ 插话' : mode === 'silent' ? '📌 备忘纸条' : '📨 递话'
|
|
@@ -1563,8 +2038,11 @@ export async function consumePreStepDelta(deps, agent) {
|
|
|
1563
2038
|
const view = clusterView(state, rootId)
|
|
1564
2039
|
const ownWs = ensureWorkspace(state, rootId)
|
|
1565
2040
|
|
|
1566
|
-
// 1. Unread mailbox messages addressed to this session/handle
|
|
2041
|
+
// 1. Unread mailbox messages addressed to this session/handle (STRICT cluster isolation: ignore detached external peers!)
|
|
1567
2042
|
for (const mail of view.mailbox) {
|
|
2043
|
+
if (mail.detachedFromCluster) continue
|
|
2044
|
+
const mailFromRoot = mail.fromRootId || (mail.fromSession && deps.resolveRootSessionId ? deps.resolveRootSessionId(mail.fromSession) : '')
|
|
2045
|
+
if (mailFromRoot && mailFromRoot !== rootId && !view.cluster.includes(mailFromRoot)) continue
|
|
1568
2046
|
const toLower = String(mail.toSession || mail.to || '').toLowerCase()
|
|
1569
2047
|
const toHandleLower = String(mail.to || '').toLowerCase()
|
|
1570
2048
|
const isMine = toLower === 'all'
|
|
@@ -1620,18 +2098,140 @@ export async function consumePreStepDelta(deps, agent) {
|
|
|
1620
2098
|
/* Concise Structured Bullet Summary ("摘要" · 宰相简报) */
|
|
1621
2099
|
/* -------------------------------------------------------------------------- */
|
|
1622
2100
|
|
|
1623
|
-
const SUMMARY_FORMAT_REV = '
|
|
2101
|
+
const SUMMARY_FORMAT_REV = 'v5-six-goal-lines'
|
|
1624
2102
|
|
|
1625
2103
|
const NARRATIVE_SYSTEM = [
|
|
1626
2104
|
'你是「DSH 参谋长」(如同统揽全局的宰相),负责把当前工作区和协同团队的目标、进展、纪律与红线边界,提炼成用户一眼扫完就能掌握全局的「摘要」。',
|
|
1627
2105
|
'严格遵守以下【简明结构化 · 分点作答】规范:',
|
|
1628
2106
|
'1. 使用简体中文,语气精炼干脆、直击要害,严禁寒暄套话与冗长铺垫。',
|
|
1629
2107
|
'2. 全文分为 2 到 4 个模块,每个模块以一行 `## 模块短标题` 开头(如 `## 核心目标与态势`、`## 关键结论与进展`、`## 协作纪律与红线`、`## 协作纪律与边界`)。',
|
|
1630
|
-
'3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【总目标】…`、`- 【推进中】…`、`- 【已完】…`、`- 【已验证】…`、`- 【结论】…`、`- 【待办】…`、`- 【待收尾】…`、`- 【注意】…`、`- 【归因纪律】…`、`- 【收尾纪律】…`、`- 【并列直接原因】…`、`- 【受阻】…`、`- 【禁止红线】…`、`-
|
|
1631
|
-
'4. **去噪与聚合铁律**:遇到大量同前缀或已结束的后台巡检子代理(如 `mnemon-review
|
|
2108
|
+
'3. **每个模块下方必须全部使用 `- ` 分点列表作答(严禁写成挤在一起的长段落散文!)**。每一点控制在 1 行(最多不超过 2 行),推荐在要点开头用方括号短标签提亮,如 `- 【总目标】…`、`- 【推进中】…`、`- 【已完】…`、`- 【已验证】…`、`- 【结论】…`、`- 【待办】…`、`- 【待收尾】…`、`- 【注意】…`、`- 【归因纪律】…`、`- 【收尾纪律】…`、`- 【并列直接原因】…`、`- 【受阻】…`、`- 【禁止红线】…`、`- 【必做事项】…`。',
|
|
2109
|
+
'4. **去噪与聚合铁律**:遇到大量同前缀或已结束的后台巡检子代理(如 `mnemon-review-*`),**严禁逐一报菜名罗列**,必须合并成一句话统计;自动忽略 `[dsh-mnemon:...]` 等系统内部检查点噪音。',
|
|
1632
2110
|
'5. 具体路径、端口、版本号、命令原样保留,同一事实绝不重复,只陈述真实输入,第一个 `## ` 之前不要输出任何多余字符。',
|
|
1633
2111
|
].join('\n')
|
|
1634
2112
|
|
|
2113
|
+
const CONCISE_BRIEF_NARRATIVE_EXTRA = [
|
|
2114
|
+
'',
|
|
2115
|
+
'⚡ 【当前已开启极简战报模式 — 六句话目标边界系列(最高优先级覆盖一切细节规则!)】:',
|
|
2116
|
+
'- **一切以目标为导向,说人话,拒绝任何事务细节**:严禁出现任何文件路径、文件名、代码符号/函数名、行号、端口号、Token/字节数、耗时、版本号、终端命令或具体计数统计!',
|
|
2117
|
+
'- **严格只输出如下 1 个标题 + 刚好 6 行单句列表(不要多也不要少)**:',
|
|
2118
|
+
' ## 极简目标战报',
|
|
2119
|
+
' - 【🎯 总目标】用一句人话说清最终要达成的目标。',
|
|
2120
|
+
' - 【🚀 当前推进目标】用一句人话说清现在正聚焦推进的阶段目标。',
|
|
2121
|
+
' - 【⛔ 受阻目标】若无受阻写“当前暂无受阻目标”;若有受阻,用一句人话点明卡住的目标与原因。',
|
|
2122
|
+
' - 【🧰 需要什么】用一句人话说明达成目标还缺的前提、验证或支撑条件(无则写“条件已齐备,可顺畅推进”)。',
|
|
2123
|
+
' - 【🙋 用户需要提供什么】若需要您拍板、授权、提供账号/素材或重启确认写一句人话;无需操作写“暂无需您额外提供,可继续推进”。',
|
|
2124
|
+
' - 【💡 参谋长建议】用一句人话给出最清晰可执行的建议或建议弹窗拍板方向。',
|
|
2125
|
+
'- 每条控制在 1 句精炼大白话(20~55 字),切忌写成事务流水账或代码改动清单!',
|
|
2126
|
+
].join('\n')
|
|
2127
|
+
|
|
2128
|
+
/** Remove or qualitatively normalize raw numeric parameters, file paths & technical trivia when Concise Brief Mode (`极简战报模式`) is enabled. */
|
|
2129
|
+
export function sanitizeConciseBriefText(text) {
|
|
2130
|
+
const src = String(text || '')
|
|
2131
|
+
if (!src.trim()) return ''
|
|
2132
|
+
return src
|
|
2133
|
+
.replace(/[A-Za-z]:\\[^\s"'`))】]+/g, '本地相关目录')
|
|
2134
|
+
.replace(/(?:^|\s)\/(?:[\w.-]+\/)+[\w.-]*/g, ' 相关路径')
|
|
2135
|
+
.replace(/\b[\w.-]+\.(?:m?[jt]sx?|py|json|ya?ml|md|css|html|sh|ps1)\b/gi, '相关模块')
|
|
2136
|
+
.replace(/`[^`]{2,64}`/g, '对应能力')
|
|
2137
|
+
.replace(/\bv?\d+\.\d+\.\d+(?:-[a-z0-9.]+)?\b/gi, '当前版本')
|
|
2138
|
+
.replace(/\bL\d+(?:\s*[-~–]\s*L?\d+)?\b/g, '相关位置')
|
|
2139
|
+
.replace(/:\d{2,5}\b/g, '')
|
|
2140
|
+
.replace(/(?:端口|port)\s*\d{2,5}/gi, '对应端口')
|
|
2141
|
+
.replace(/(?:第)\s*\d+(?:\.\d+)?\s*(?:行|页|步|轮|阶段)/gi, '当前阶段')
|
|
2142
|
+
.replace(/(?:耗时|用时|约|共|已有|剩余|累计|包含|存在|触发|达到|占比)\s*\d+(?:\.\d+)?\s*(?:ms|s|毫秒|秒|分钟|小时|天|字节|bytes?|KB|MB|GB|K|M|%|%|项|个|条|卷|次|步|轮|行|页|张|名|家|处)/gi, (m) => {
|
|
2143
|
+
if (/(?:%|%)/.test(m)) return '相应比例'
|
|
2144
|
+
if (/(?:ms|s|毫秒|秒|分钟|小时)/.test(m)) return '短暂耗时'
|
|
2145
|
+
if (/(?:KB|MB|GB|K|M|字节|bytes?)/i.test(m)) return '一定体量'
|
|
2146
|
+
return '若干进展'
|
|
2147
|
+
})
|
|
2148
|
+
.replace(/\b\d+(?:\.\d+)?\s*(?:%|%)/g, '相应比例')
|
|
2149
|
+
.replace(/\b\d+(?:\.\d+)?\s*(?:ms|毫秒|KB|MB|GB)(?![a-z0-9_])/gi, '相应规模')
|
|
2150
|
+
.replace(/(^|\s)#\d+\b/g, '$1该目标')
|
|
2151
|
+
.replace(/\b\d{3,}\b/g, '若干')
|
|
2152
|
+
.replace(/(?<=[\u4e00-\u9fa5\s])\d+(?=[\s]*(?:项|个|条|卷|次|步|轮|名|处|份|行))/g, '若干')
|
|
2153
|
+
.replace(/[ \t]{2,}/g, ' ')
|
|
2154
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
2155
|
+
.trim()
|
|
2156
|
+
}
|
|
2157
|
+
|
|
2158
|
+
/** Synthesize the 6-line goal-only human report (`六句话目标边界系列`) shared by Narrative fallback & AskChief fallback. */
|
|
2159
|
+
function buildConciseSixLineReport({ board, blocked = [], doing = [], todo = [], done = [], workers = [], suggestions = [], needFromUserHint = '' }) {
|
|
2160
|
+
const clean = (s, max = 54) => sanitizeConciseBriefText(clamp(String(s || '').replace(/\s+/g, ' ').trim(), max))
|
|
2161
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
2162
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
2163
|
+
const donePlan = planSteps.filter(s => s.done)
|
|
2164
|
+
const objText = (board && board.objective) ? clean(board.objective, 56) : '按您当前的指令完成本阶段目标'
|
|
2165
|
+
let curText = '等待您确认方向后启动推进'
|
|
2166
|
+
if (doing.length > 0) {
|
|
2167
|
+
curText = clean(doing[0].title, 54)
|
|
2168
|
+
} else if (blocked.length > 0) {
|
|
2169
|
+
curText = '正聚焦排查并疏通受阻目标:' + clean(blocked[0].title, 44)
|
|
2170
|
+
} else if (todo.length > 0) {
|
|
2171
|
+
curText = '准备推进下一项目标:' + clean(todo[0].title, 46)
|
|
2172
|
+
} else if (openPlan.length > 0) {
|
|
2173
|
+
curText = clean(openPlan[0].text, 54)
|
|
2174
|
+
} else if (done.length > 0 || (donePlan.length > 0 && !openPlan.length)) {
|
|
2175
|
+
curText = '本阶段核心事项已基本收尾,待核对确认后交卷'
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
let blockedText = '当前暂无受阻目标,推进链路顺畅'
|
|
2179
|
+
if (blocked.length > 0) {
|
|
2180
|
+
const b0 = blocked[0]
|
|
2181
|
+
blockedText = clean(b0.title, 40) + (b0.note ? '(症结:' + clean(b0.note, 34) + ')' : '(需排查卡点条件)')
|
|
2182
|
+
}
|
|
2183
|
+
|
|
2184
|
+
let needWhatText = '前提条件与执行环境基本齐备,可按既定节奏完成验证与收尾'
|
|
2185
|
+
if (blocked.length > 0) {
|
|
2186
|
+
needWhatText = '需要先解除受阻卡点并补齐相关前置验证条件'
|
|
2187
|
+
} else if (todo.length > 0 && workers.some(w => w.status === 'running')) {
|
|
2188
|
+
needWhatText = '需要等当前并行协作收口并完成关键结果核验'
|
|
2189
|
+
} else if (todo.length > 0) {
|
|
2190
|
+
needWhatText = '需要按序完成剩余收尾环节与最终效果检验'
|
|
2191
|
+
} else if (openPlan.length > 0) {
|
|
2192
|
+
needWhatText = '需要推进或确认当前待完成环节:' + clean(openPlan[0].text, 40)
|
|
2193
|
+
} else if (!board || !board.objective) {
|
|
2194
|
+
needWhatText = '需要明确具体的最终验收标准或本轮预期效果'
|
|
2195
|
+
}
|
|
2196
|
+
|
|
2197
|
+
const pendingBoundOrApproval = (Array.isArray(suggestions) ? suggestions : []).find(
|
|
2198
|
+
s => s && s.status === 'pending' && (s.kind === 'goal_approval' || s.kind === 'bound' || s.kind === 'advice'),
|
|
2199
|
+
)
|
|
2200
|
+
let userNeedText = '暂无需您额外提供,参谋长与主对话可继续自动推进'
|
|
2201
|
+
if (needFromUserHint) {
|
|
2202
|
+
userNeedText = clean(needFromUserHint, 54)
|
|
2203
|
+
} else if (pendingBoundOrApproval) {
|
|
2204
|
+
userNeedText = '请您查看并拍板确认「' + clean(pendingBoundOrApproval.title, 38) + '」'
|
|
2205
|
+
} else if (blocked.length > 0 && /权限|登录|账号|密钥|token|重启|确认|决定|选择/i.test(String(blocked[0].note || blocked[0].title || ''))) {
|
|
2206
|
+
userNeedText = '需要您协助授权、提供凭据或拍板选定解决路线'
|
|
2207
|
+
} else if (openPlan.length > 0 && /用户|确认|拍板|点头|决定|选择/.test(String(openPlan[0].text || ''))) {
|
|
2208
|
+
userNeedText = '需要您拍板选定下一步路线:' + clean(openPlan[0].text, 38)
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
let adviceText = '建议保持当前推进节奏,收口前做一轮完整实测核对即可交卷'
|
|
2212
|
+
if (pendingBoundOrApproval && pendingBoundOrApproval.kind === 'advice') {
|
|
2213
|
+
adviceText = clean(pendingBoundOrApproval.reason || pendingBoundOrApproval.draftText || pendingBoundOrApproval.title, 54)
|
|
2214
|
+
} else if (blocked.length > 0) {
|
|
2215
|
+
adviceText = '建议先集中解决首要受阻目标,必要时由参谋长向主对话插话纠偏'
|
|
2216
|
+
} else if (openPlan.length > 0 && doing.length === 0 && todo.length === 0) {
|
|
2217
|
+
adviceText = '建议按当前待定环节及时确认方向,确认后即可顺畅续跑'
|
|
2218
|
+
} else if (todo.length > 0) {
|
|
2219
|
+
adviceText = '建议优先收拢在手推进项,顺势拿下紧接的待办目标'
|
|
2220
|
+
} else if ((done.length > 0 || (donePlan.length > 0 && !openPlan.length)) && !doing.length && !todo.length) {
|
|
2221
|
+
adviceText = '建议您核对整体表现,满意后即可批准结项或开启下一目标'
|
|
2222
|
+
}
|
|
2223
|
+
|
|
2224
|
+
return [
|
|
2225
|
+
'## 极简目标战报',
|
|
2226
|
+
`- 【🎯 总目标】${objText}`,
|
|
2227
|
+
`- 【🚀 当前推进目标】${curText}`,
|
|
2228
|
+
`- 【⛔ 受阻目标】${blockedText}`,
|
|
2229
|
+
`- 【🧰 需要什么】${needWhatText}`,
|
|
2230
|
+
`- 【🙋 用户需要提供什么】${userNeedText}`,
|
|
2231
|
+
`- 【💡 参谋长建议】${adviceText}`,
|
|
2232
|
+
].join('\n')
|
|
2233
|
+
}
|
|
2234
|
+
|
|
1635
2235
|
function shortAgentBriefName(name) {
|
|
1636
2236
|
const raw = String(name || '').trim()
|
|
1637
2237
|
if (!raw) return ''
|
|
@@ -1678,7 +2278,7 @@ function summarizeSubagentsCompact(workers) {
|
|
|
1678
2278
|
return `共 ${workers.length} 名子代理(${parts.join(';')})`
|
|
1679
2279
|
}
|
|
1680
2280
|
|
|
1681
|
-
function buildNarrativeInput({ board, facts, cluster, targets }) {
|
|
2281
|
+
function buildNarrativeInput({ board, facts, cluster, targets, peerProgress = [], archiveDigest = null }) {
|
|
1682
2282
|
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
1683
2283
|
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1684
2284
|
const memory = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
@@ -1688,11 +2288,23 @@ function buildNarrativeInput({ board, facts, cluster, targets }) {
|
|
|
1688
2288
|
const lines = []
|
|
1689
2289
|
if (board && board.objective) lines.push(`当前总目标:${board.objective}`)
|
|
1690
2290
|
if ((bounds.forbidden || []).length) lines.push(`禁止红线:${bounds.forbidden.join(';')}`)
|
|
1691
|
-
if ((bounds.allowed || []).length) lines.push(
|
|
2291
|
+
if ((bounds.allowed || []).length) lines.push(`必做事项:${bounds.allowed.join(';')}`)
|
|
1692
2292
|
if ((bounds.notes || []).length) lines.push(`边界注意:${bounds.notes.join(';')}`)
|
|
1693
2293
|
|
|
1694
2294
|
if (cluster.length > 1) {
|
|
1695
|
-
lines.push(`跨窗口协同频道:当前已串联 ${cluster.length}
|
|
2295
|
+
lines.push(`跨窗口协同频道:当前已串联 ${cluster.length} 个主对话窗口协同作业(网络内自动共享进度)。`)
|
|
2296
|
+
}
|
|
2297
|
+
if (Array.isArray(peerProgress) && peerProgress.length > 0) {
|
|
2298
|
+
lines.push('', '【协同对话网络共享进度】')
|
|
2299
|
+
for (const p of peerProgress) {
|
|
2300
|
+
lines.push(`- 联动对话「${p.name}」[${p.status === 'running' ? '🟢运行中' : '⚪空闲'}]:目标="${p.objective || '未设'}" | 任务=${p.doneCount}完/${p.doingCount}做/${p.blockedCount}阻/${p.todoCount}待${p.cursorStep ? ` | 断点=${p.cursorStep}` : ''}`)
|
|
2301
|
+
if (Array.isArray(p.topTasks) && p.topTasks.length) {
|
|
2302
|
+
lines.push(` · 在手任务:${p.topTasks.join(';')}`)
|
|
2303
|
+
}
|
|
2304
|
+
if (Array.isArray(p.recentConclusions) && p.recentConclusions.length) {
|
|
2305
|
+
lines.push(` · 近期结论:${p.recentConclusions.join(';')}`)
|
|
2306
|
+
}
|
|
2307
|
+
}
|
|
1696
2308
|
}
|
|
1697
2309
|
const activeWorkers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
|
|
1698
2310
|
if (activeWorkers.length > 0) {
|
|
@@ -1733,11 +2345,41 @@ function buildNarrativeInput({ board, facts, cluster, targets }) {
|
|
|
1733
2345
|
}
|
|
1734
2346
|
}
|
|
1735
2347
|
|
|
2348
|
+
if (archiveDigest) {
|
|
2349
|
+
const dSess = Array.isArray(archiveDigest.deskSessionItems) ? archiveDigest.deskSessionItems : []
|
|
2350
|
+
const dGlob = Array.isArray(archiveDigest.deskGlobalItems) ? archiveDigest.deskGlobalItems : []
|
|
2351
|
+
const dFlip = Array.isArray(archiveDigest.deskFlippedItems) ? archiveDigest.deskFlippedItems : []
|
|
2352
|
+
const mGlob = Array.isArray(archiveDigest.mountedGlobalItems) ? archiveDigest.mountedGlobalItems : []
|
|
2353
|
+
const sw = archiveDigest.sealedWatch || {}
|
|
2354
|
+
const deskAll = [
|
|
2355
|
+
...dSess.map(it => `[桌面·本局(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 140)}`),
|
|
2356
|
+
...dGlob.map(it => `[桌面·全局(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 140)}`),
|
|
2357
|
+
...dFlip.map(it => `[桌面·沉淀(主可见)] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.rawBody, 140)}`),
|
|
2358
|
+
]
|
|
2359
|
+
if (deskAll.length > 0) {
|
|
2360
|
+
lines.push('', '【当前摆上桌面备选(重点强调,主对话与参谋长共同可见)】', ...deskAll.slice(0, 8).map(x => '- ' + x))
|
|
2361
|
+
}
|
|
2362
|
+
if (mGlob.length > 0) {
|
|
2363
|
+
lines.push('', '【参谋长单独参阅中的全局档案(主对话不可见)】')
|
|
2364
|
+
for (const it of mGlob.slice(0, 5)) {
|
|
2365
|
+
lines.push(`- [全局参阅] 《${clamp(it.title, 40)}》:${clamp(it.summary || it.body, 120)}`)
|
|
2366
|
+
}
|
|
2367
|
+
}
|
|
2368
|
+
const sealedLines = [
|
|
2369
|
+
...((sw.sessionSealed || []).slice(0, 4).map(it => `- [本局封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
|
|
2370
|
+
...((sw.globalSealed || []).slice(0, 4).map(it => `- [全局封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
|
|
2371
|
+
...((sw.precipSealed || []).slice(0, 3).map(it => `- [沉淀封存·仅参谋关注] 《${clamp(it.title, 36)}》:${clamp(it.summary, 90)}`)),
|
|
2372
|
+
]
|
|
2373
|
+
if (sealedLines.length > 0) {
|
|
2374
|
+
lines.push('', '【参谋长后台守望的三库封存索引(主对话上下文零注入)】', ...sealedLines)
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
|
|
1736
2378
|
return lines.join('\n').trim()
|
|
1737
2379
|
}
|
|
1738
2380
|
|
|
1739
2381
|
/** Deterministic structured bullet summary when no LLM key is configured or while first summary is warming up. */
|
|
1740
|
-
function buildFallbackNarrative({ board, facts, targets }) {
|
|
2382
|
+
function buildFallbackNarrative({ board, facts, targets, peerProgress = [], conciseBrief = false, suggestions = [] }) {
|
|
1741
2383
|
const sections = []
|
|
1742
2384
|
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
1743
2385
|
const blocked = tasks.filter(t => t.status === 'blocked')
|
|
@@ -1746,6 +2388,10 @@ function buildFallbackNarrative({ board, facts, targets }) {
|
|
|
1746
2388
|
const done = tasks.filter(t => t.status === 'done')
|
|
1747
2389
|
const workers = targets.filter(t => t.kind === 'subagent' && !/^mnemon-(?:review|run)/i.test(String(t.name || t.key || '')))
|
|
1748
2390
|
|
|
2391
|
+
if (conciseBrief) {
|
|
2392
|
+
return buildConciseSixLineReport({ board, blocked, doing, todo, done, workers, suggestions })
|
|
2393
|
+
}
|
|
2394
|
+
|
|
1749
2395
|
const statusBullets = []
|
|
1750
2396
|
if (board && board.objective) {
|
|
1751
2397
|
statusBullets.push(`- 【总目标】${clamp(board.objective, 150)}`)
|
|
@@ -1763,6 +2409,11 @@ function buildFallbackNarrative({ board, facts, targets }) {
|
|
|
1763
2409
|
if (workers.length > 0) {
|
|
1764
2410
|
statusBullets.push(`- 【子代理团队】${summarizeSubagentsCompact(workers)}`)
|
|
1765
2411
|
}
|
|
2412
|
+
if (Array.isArray(peerProgress) && peerProgress.length > 0) {
|
|
2413
|
+
for (const p of peerProgress.slice(0, 4)) {
|
|
2414
|
+
statusBullets.push(`- 【协同进度·${clamp(p.name, 22)}】${p.objective ? clamp(p.objective, 70) + ' · ' : ''}任务 ${p.doneCount}完/${p.doingCount}做${p.blockedCount ? `/${p.blockedCount}阻` : ''}${p.cursorStep ? '(断点:' + clamp(p.cursorStep, 32) + ')' : ''}`)
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
1766
2417
|
if (statusBullets.length > 0) {
|
|
1767
2418
|
sections.push('## 核心目标与态势\n' + statusBullets.join('\n'))
|
|
1768
2419
|
}
|
|
@@ -1783,7 +2434,7 @@ function buildFallbackNarrative({ board, facts, targets }) {
|
|
|
1783
2434
|
const disciplines = facts.filter(f => f.category === 'discipline' || f.category === 'preference')
|
|
1784
2435
|
const ruleBullets = []
|
|
1785
2436
|
for (const f of (bounds.forbidden || []).slice(0, 6)) ruleBullets.push(`- 【禁止红线】${clamp(f, 110)}`)
|
|
1786
|
-
for (const a of (bounds.allowed || []).slice(0, 4)) ruleBullets.push(`-
|
|
2437
|
+
for (const a of (bounds.allowed || []).slice(0, 4)) ruleBullets.push(`- 【必做事项】${clamp(a, 110)}`)
|
|
1787
2438
|
for (const n of (bounds.notes || []).slice(0, 3)) ruleBullets.push(`- 【注意事项】${clamp(n, 110)}`)
|
|
1788
2439
|
for (const d of disciplines.slice(-5)) ruleBullets.push(`- 【协作纪律】${clamp(d.text, 120)}`)
|
|
1789
2440
|
if (ruleBullets.length > 0) {
|
|
@@ -1798,7 +2449,7 @@ function buildFallbackNarrative({ board, facts, targets }) {
|
|
|
1798
2449
|
|
|
1799
2450
|
const summarizingLocks = new Map()
|
|
1800
2451
|
|
|
1801
|
-
export async function getChiefView(deps, sessionId, { regenerate = false, autoSummarize = false } = {}) {
|
|
2452
|
+
export async function getChiefView(deps, sessionId, { regenerate = false, autoSummarize = false, syncHandoff = undefined, _skipAutoPilotCheck = false } = {}) {
|
|
1802
2453
|
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
1803
2454
|
const directory = await listPeerDirectory(deps, rootId)
|
|
1804
2455
|
const board = deps.boardForSession(deps.boardFileFor(rootId))
|
|
@@ -1807,18 +2458,33 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
|
|
|
1807
2458
|
const modelsInfo = await listChiefModels(deps, false, rootId)
|
|
1808
2459
|
const effCfgBefore = resolveWorkspaceConfig(state, rootId)
|
|
1809
2460
|
const paceMode = effCfgBefore.paceMode || 'manual'
|
|
2461
|
+
const isConciseBrief = Boolean(effCfgBefore.tacticalModes && effCfgBefore.tacticalModes.conciseBrief)
|
|
2462
|
+
const currentSig = view.clusterSig || computeClusterSig(directory.cluster)
|
|
2463
|
+
const peerProgress = directory.cluster.length > 1
|
|
2464
|
+
? collectClusterPeerProgress(deps, directory.cluster, rootId)
|
|
2465
|
+
: []
|
|
2466
|
+
const archiveDigest = collectChiefVisibleArchives(deps, rootId, state)
|
|
1810
2467
|
|
|
1811
2468
|
const rawInput = buildNarrativeInput({
|
|
1812
2469
|
board,
|
|
1813
2470
|
facts: view.facts,
|
|
1814
2471
|
cluster: directory.cluster,
|
|
1815
2472
|
targets: directory.targets,
|
|
2473
|
+
peerProgress,
|
|
2474
|
+
archiveDigest,
|
|
1816
2475
|
})
|
|
1817
2476
|
const inputHash = rawInput
|
|
1818
|
-
? crypto.createHash('sha256').update(SUMMARY_FORMAT_REV + '\n' + rawInput).digest('hex').slice(0, 24)
|
|
2477
|
+
? crypto.createHash('sha256').update(SUMMARY_FORMAT_REV + '\n' + (isConciseBrief ? 'concise:1' : 'concise:0') + '\n' + currentSig + '\n' + rawInput).digest('hex').slice(0, 24)
|
|
1819
2478
|
: 'empty'
|
|
1820
2479
|
|
|
1821
|
-
const
|
|
2480
|
+
const isClusterSigValid = (nar) => {
|
|
2481
|
+
if (!nar || !nar.text) return false
|
|
2482
|
+
if (nar.clusterSig && nar.clusterSig !== currentSig) return false
|
|
2483
|
+
if (!nar.clusterSig && directory.cluster.length > 1) return false
|
|
2484
|
+
return true
|
|
2485
|
+
}
|
|
2486
|
+
|
|
2487
|
+
const hasSaved = isClusterSigValid(view.narrative)
|
|
1822
2488
|
const lastSummaryAt = Number((view.narrative && view.narrative.at) || 0)
|
|
1823
2489
|
const isFresh = !rawInput || (hasSaved && view.narrative.hash === inputHash)
|
|
1824
2490
|
const cooledForAuto = Date.now() - lastSummaryAt >= AUTO_SUMMARY_COOLDOWN_MS
|
|
@@ -1828,20 +2494,27 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
|
|
|
1828
2494
|
// OR when operator explicitly chose `paceMode === 'auto'` AND the 5-minute cooldown has elapsed!
|
|
1829
2495
|
if (rawInput && (regenerate || allowBackgroundSummary) && modelsInfo.available && !summarizingLocks.has(rootId)) {
|
|
1830
2496
|
const job = (async () => {
|
|
2497
|
+
const sysPrompt = isConciseBrief
|
|
2498
|
+
? (NARRATIVE_SYSTEM + CONCISE_BRIEF_NARRATIVE_EXTRA)
|
|
2499
|
+
: NARRATIVE_SYSTEM
|
|
1831
2500
|
const res = await callChiefLlm(deps, {
|
|
1832
2501
|
sessionId: rootId,
|
|
1833
|
-
system:
|
|
1834
|
-
prompt: rawInput +
|
|
2502
|
+
system: sysPrompt,
|
|
2503
|
+
prompt: rawInput + (isConciseBrief
|
|
2504
|
+
? '\n\n请开启【极简战报模式】:分结构列出多个简明短句,不写具体数字参数,精确概括现状:'
|
|
2505
|
+
: '\n\n请按上述规范输出简体中文摘要:'),
|
|
1835
2506
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
1836
2507
|
})
|
|
1837
2508
|
if (res.ok && res.text) {
|
|
2509
|
+
const finalNarText = isConciseBrief ? sanitizeConciseBriefText(res.text) : res.text
|
|
1838
2510
|
mutateChiefState((s) => {
|
|
1839
2511
|
const ws = ensureWorkspace(s, rootId)
|
|
1840
2512
|
ws.narrative = {
|
|
1841
2513
|
hash: inputHash,
|
|
1842
|
-
text:
|
|
2514
|
+
text: finalNarText,
|
|
1843
2515
|
at: Date.now(),
|
|
1844
2516
|
byModel: res.modelRef || '',
|
|
2517
|
+
clusterSig: currentSig,
|
|
1845
2518
|
}
|
|
1846
2519
|
})
|
|
1847
2520
|
}
|
|
@@ -1856,35 +2529,110 @@ export async function getChiefView(deps, sessionId, { regenerate = false, autoSu
|
|
|
1856
2529
|
|
|
1857
2530
|
const latestState = loadChiefState()
|
|
1858
2531
|
const latestView = clusterView(latestState, rootId)
|
|
1859
|
-
const hasLatestSaved =
|
|
2532
|
+
const hasLatestSaved = isClusterSigValid(latestView.narrative)
|
|
1860
2533
|
const latestFresh = !rawInput || (hasLatestSaved && latestView.narrative.hash === inputHash)
|
|
1861
|
-
const narrativeText = hasLatestSaved
|
|
1862
|
-
? latestView.narrative.text
|
|
1863
|
-
: buildFallbackNarrative({ board, facts: latestView.facts, targets: directory.targets })
|
|
2534
|
+
const narrativeText = (hasLatestSaved && (!isConciseBrief || latestFresh))
|
|
2535
|
+
? (isConciseBrief ? sanitizeConciseBriefText(latestView.narrative.text) : latestView.narrative.text)
|
|
2536
|
+
: buildFallbackNarrative({ board, facts: latestView.facts, targets: directory.targets, peerProgress, conciseBrief: isConciseBrief, suggestions: latestView.suggestions })
|
|
2537
|
+
|
|
2538
|
+
// Optional 1-click Handoff Packet Sync on Digest regeneration or explicit sync request (strictly blocked if pinned by human!)
|
|
2539
|
+
let handoffSyncResult = null
|
|
2540
|
+
const latestBoardBeforeSync = deps.boardForSession(deps.boardFileFor(rootId))
|
|
2541
|
+
const shouldSyncHandoff = syncHandoff !== undefined
|
|
2542
|
+
? Boolean(syncHandoff)
|
|
2543
|
+
: Boolean(regenerate && latestBoardBeforeSync && latestBoardBeforeSync.handoff && latestBoardBeforeSync.handoff.syncOnDigest)
|
|
2544
|
+
if (shouldSyncHandoff && typeof deps.runAction === 'function') {
|
|
2545
|
+
const isPinned = Boolean(latestBoardBeforeSync && latestBoardBeforeSync.handoff && latestBoardBeforeSync.handoff.pinned)
|
|
2546
|
+
if (isPinned) {
|
|
2547
|
+
handoffSyncResult = {
|
|
2548
|
+
synced: false,
|
|
2549
|
+
skipped: 'pinned-by-human',
|
|
2550
|
+
reason: 'pinned',
|
|
2551
|
+
message: '交接单已被人工定住,参谋长跳过自动覆写',
|
|
2552
|
+
}
|
|
2553
|
+
} else {
|
|
2554
|
+
const composed = typeof deps.composeHandoffFromNarrative === 'function'
|
|
2555
|
+
? deps.composeHandoffFromNarrative(rootId, narrativeText)
|
|
2556
|
+
: ''
|
|
2557
|
+
if (composed && composed.trim()) {
|
|
2558
|
+
const saveRes = deps.runAction({
|
|
2559
|
+
action: 'handoff.save',
|
|
2560
|
+
session: rootId === 'global' ? '' : rootId,
|
|
2561
|
+
by: 'chief',
|
|
2562
|
+
source: 'chief',
|
|
2563
|
+
text: composed,
|
|
2564
|
+
})
|
|
2565
|
+
const isLocked = Boolean(saveRes && (saveRes.pinned || saveRes.locked))
|
|
2566
|
+
handoffSyncResult = saveRes && saveRes.ok
|
|
2567
|
+
? { synced: true, at: Date.now() }
|
|
2568
|
+
: {
|
|
2569
|
+
synced: false,
|
|
2570
|
+
...(isLocked ? { skipped: 'pinned-by-human' } : {}),
|
|
2571
|
+
reason: isLocked ? 'pinned' : 'error',
|
|
2572
|
+
message: (saveRes && saveRes.error) || '同步失败',
|
|
2573
|
+
}
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
}
|
|
1864
2577
|
|
|
1865
|
-
const
|
|
1866
|
-
const
|
|
2578
|
+
const ownWsBeforeStop = ensureWorkspace(latestState, rootId)
|
|
2579
|
+
const effectiveConfigBeforeStop = resolveWorkspaceConfig(latestState, rootId)
|
|
2580
|
+
if (
|
|
2581
|
+
!_skipAutoPilotCheck
|
|
2582
|
+
&& rootId
|
|
2583
|
+
&& rootId !== 'global'
|
|
2584
|
+
&& effectiveConfigBeforeStop.autoPilot
|
|
2585
|
+
&& effectiveConfigBeforeStop.paceMode === 'auto'
|
|
2586
|
+
&& !effectiveConfigBeforeStop.stopped
|
|
2587
|
+
) {
|
|
2588
|
+
await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
2589
|
+
allowStartupGrace: true,
|
|
2590
|
+
directory,
|
|
2591
|
+
currentFresh: latestFresh,
|
|
2592
|
+
fromViewCheck: true,
|
|
2593
|
+
}).catch(() => null)
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2596
|
+
const finalState = loadChiefState()
|
|
2597
|
+
const finalView = clusterView(finalState, rootId)
|
|
2598
|
+
const ownWs = ensureWorkspace(finalState, rootId)
|
|
2599
|
+
const effectiveConfig = resolveWorkspaceConfig(finalState, rootId)
|
|
2600
|
+
const narrativeAt = hasLatestSaved
|
|
2601
|
+
? (latestView.narrative.at || 0)
|
|
2602
|
+
: (ownWs.narrative && ownWs.narrative.at ? ownWs.narrative.at : (board.updatedAt || 0))
|
|
2603
|
+
const finalNarrativeText = ownWs.narrative && ownWs.narrative.text && (!isConciseBrief || latestFresh)
|
|
2604
|
+
? (isConciseBrief ? sanitizeConciseBriefText(ownWs.narrative.text) : ownWs.narrative.text)
|
|
2605
|
+
: narrativeText
|
|
1867
2606
|
return {
|
|
1868
2607
|
ok: true,
|
|
1869
2608
|
rootId,
|
|
1870
2609
|
config: effectiveConfig,
|
|
1871
2610
|
models: modelsInfo,
|
|
1872
2611
|
narrative: {
|
|
1873
|
-
text:
|
|
1874
|
-
at:
|
|
1875
|
-
byModel: hasLatestSaved ? (latestView.narrative.byModel || '') : '',
|
|
1876
|
-
|
|
1877
|
-
|
|
2612
|
+
text: finalNarrativeText,
|
|
2613
|
+
at: narrativeAt,
|
|
2614
|
+
byModel: hasLatestSaved ? (latestView.narrative.byModel || '') : ((ownWs.narrative && ownWs.narrative.byModel) || ''),
|
|
2615
|
+
clusterSig: currentSig,
|
|
2616
|
+
isLiveZeroToken: !hasLatestSaved && !(ownWs.narrative && ownWs.narrative.text),
|
|
2617
|
+
hasUnsummarizedChanges: Boolean(rawInput && !latestFresh && !(ownWs.narrative && ownWs.narrative.hash === inputHash)),
|
|
1878
2618
|
summarizing: summarizingLocks.has(rootId),
|
|
1879
|
-
fresh: latestFresh,
|
|
2619
|
+
fresh: latestFresh || Boolean(ownWs.narrative && ownWs.narrative.hash === inputHash),
|
|
1880
2620
|
},
|
|
1881
|
-
|
|
1882
|
-
|
|
1883
|
-
|
|
1884
|
-
|
|
2621
|
+
...(handoffSyncResult ? { handoffSyncResult } : {}),
|
|
2622
|
+
facts: finalView.facts.slice().reverse(),
|
|
2623
|
+
suggestions: finalView.suggestions.slice().reverse(),
|
|
2624
|
+
chat: finalView.chat.slice(-40).map((c) => {
|
|
2625
|
+
if (!c || typeof c !== 'object') return c
|
|
2626
|
+
const cleaned = stripToolCallMarkup(c.text || '')
|
|
2627
|
+
return cleaned !== c.text
|
|
2628
|
+
? { ...c, text: cleaned || '(该条历史响应仅包含内部工具调用标记,已自动净化)' }
|
|
2629
|
+
: c
|
|
2630
|
+
}),
|
|
2631
|
+
mailbox: finalView.mailbox.slice(-30).reverse(),
|
|
1885
2632
|
peers: directory.targets,
|
|
1886
2633
|
otherSessions: directory.otherSessions,
|
|
1887
2634
|
cluster: directory.cluster,
|
|
2635
|
+
peerProgress,
|
|
1888
2636
|
flippedPrecipitatedIds: (ownWs.flippedPrecipitatedIds || []).slice(),
|
|
1889
2637
|
runtimeGuard: { ...ownWs.runtimeGuard },
|
|
1890
2638
|
}
|
|
@@ -1933,6 +2681,8 @@ export function deployChiefWorkspaceState(deps, {
|
|
|
1933
2681
|
toWs.facts.push({
|
|
1934
2682
|
...f,
|
|
1935
2683
|
id: nextId('fact'),
|
|
2684
|
+
originRootId: toKey === 'global' ? (f.originRootId || '') : toKey,
|
|
2685
|
+
peerRootIds: [],
|
|
1936
2686
|
source: f.source || `移交自 ${fromTitle || fromKey}`,
|
|
1937
2687
|
updatedAt: Date.now(),
|
|
1938
2688
|
})
|
|
@@ -1948,6 +2698,7 @@ export function deployChiefWorkspaceState(deps, {
|
|
|
1948
2698
|
toWs.narrative = {
|
|
1949
2699
|
...fromWs.narrative,
|
|
1950
2700
|
hash: fromWs.narrative.hash || '',
|
|
2701
|
+
clusterSig: toKey,
|
|
1951
2702
|
at: Date.now(),
|
|
1952
2703
|
}
|
|
1953
2704
|
}
|
|
@@ -2020,15 +2771,18 @@ export function deployChiefWorkspaceState(deps, {
|
|
|
2020
2771
|
/* -------------------------------------------------------------------------- */
|
|
2021
2772
|
|
|
2022
2773
|
const ASK_CHIEF_SYSTEM = [
|
|
2023
|
-
'你是「DSH 参谋长」(DSH Chief
|
|
2024
|
-
'
|
|
2774
|
+
'你是「DSH 参谋长」(DSH Chief)——统揽主对话、子代理团队与跨窗口协同的全能参谋宰相,默认拥有最高「完全权限(danger-full-access)」。',
|
|
2775
|
+
'你**绝不只是**被动的记忆检索器或传话筒!你既可以动用实权工具直接读写核验,也实时掌握:',
|
|
2025
2776
|
'1) 主代理(@lead)与各子代理的**实时对话流快照**(刚刚说了什么、正在调什么工具、卡在哪里);',
|
|
2026
2777
|
'2) 参谋看板总目标、实时断点游标(cursor)、计划(plan)与任务拓扑(推进中 / 受阻 / 待办 / 已完成证据);',
|
|
2027
2778
|
'3) 双层工作边界(📌 定住全局跨任务共享边界 vs 仅当前任务边界)与持久记忆、便签、协同信箱。',
|
|
2028
2779
|
'',
|
|
2029
|
-
'
|
|
2780
|
+
'请精准洞悉用户意图——你的输入框就是用户的【全能许愿框】(亲自查证修复/跑命令、派发调度子代理、态势汇报、卡点诊断、拆话传话、代维护或重设任务计划、设定/重设/浓缩边界、整理/提炼入全局/上下桌面档案、连接或断开跨窗口协同网络),并**只输出一个合法 JSON 对象**:',
|
|
2030
2781
|
'{',
|
|
2031
|
-
' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论`
|
|
2782
|
+
' "reply": "必须【简明、结构化、分点作答】!用换行 `- 【标签】结论` 列出(优先使用语义清晰标签:如【总目标】【实测执行】【推进中】【已完】【已验证】【结论】【待办】【受阻】【禁止红线】【下一步建议】),直给干货,绝不说『记忆里没有这条』,绝不堆砌废话或暴露内部 sessionId",',
|
|
2783
|
+
' "toolCalls": [',
|
|
2784
|
+
' { "tool": "read_file|list_dir|search_files|write_file|edit_file|run_command|subagent_dispatch|subagent_steer|subagent_interrupt|archive_write|session_compact", "args": {} }',
|
|
2785
|
+
' ],',
|
|
2032
2786
|
' "relays": [',
|
|
2033
2787
|
' { "target": "成员 key 或名字(如 lead / 子代理名 / session-xxx / all)", "mode": "steer|followup|silent", "subject": "简短事由", "text": "替用户转化好的清晰可执行指令" }',
|
|
2034
2788
|
' ],',
|
|
@@ -2050,22 +2804,53 @@ const ASK_CHIEF_SYSTEM = [
|
|
|
2050
2804
|
' { "op": "objective.set", "objective": "新总目标" },',
|
|
2051
2805
|
' { "op": "task.add", "title": "任务名", "owner": "可选负责人", "priority": "high|normal|low" },',
|
|
2052
2806
|
' { "op": "task.update", "id": "已有任务ID", "status": "todo|doing|blocked|done", "note": "可选进展或阻塞说明", "evidence": "可选完成证据", "owner": "可选负责人" },',
|
|
2807
|
+
' { "op": "task.remove", "id": "要删除的任务ID" },',
|
|
2808
|
+
' { "op": "task.reset", "status": "可选(all|open|done),清空/重设任务列表", "resetPlan": false },',
|
|
2809
|
+
' { "op": "graph.plan", "replace": false, "objective": "可选新目标", "tasks": [{ "id": "step1", "title": "重编任务", "owner": "", "priority": "high|normal|low", "blockedBy": [] }] },',
|
|
2053
2810
|
' { "op": "cursor.set", "step": "当前步骤", "next": "下一步具体动作", "blocked": "阻塞点(无则空串)" },',
|
|
2811
|
+
' { "op": "bounds.set", "field": "forbidden|allowed|notes", "items": ["整列覆盖的新边界条文列表"] },',
|
|
2054
2812
|
' { "op": "bounds.forbid", "item": "用户明确下令立即写入的禁止红线", "pinGlobal": false },',
|
|
2055
|
-
' { "op": "bounds.allow", "item": "
|
|
2813
|
+
' { "op": "bounds.allow", "item": "用户明确下令立即写入的必做事项", "pinGlobal": false },',
|
|
2814
|
+
' { "op": "bounds.note", "item": "用户明确下令立即写入的注意事项", "pinGlobal": false },',
|
|
2815
|
+
' { "op": "bounds.remove", "field": "forbidden|allowed|notes", "item": "要移除的旧边界条文", "pinGlobal": false }',
|
|
2816
|
+
' ],',
|
|
2817
|
+
' "archiveOps": [',
|
|
2818
|
+
' { "op": "organize", "vaultScope": "session|global", "scope": "unorganized|all", "instruction": "整理分类要求" },',
|
|
2819
|
+
' { "op": "distill_to_global", "ids": ["可选:指定本局档案ID,留空自动筛选可复用本局经验"], "instruction": "提炼入全局要求" },',
|
|
2820
|
+
' { "op": "take_out|put_back|mount_chief|unmount_chief|copy_to_global|copy_to_session|pull_precipitated|delete", "vaultScope": "session|global|precipitated", "id": "目标档案ID", "title": "或标题关键词", "targetScope": "session|global" },',
|
|
2821
|
+
' { "op": "save", "vaultScope": "session|global", "title": "档案标题", "folder": "inbox|architecture|contracts|pitfalls|ops", "summary": "摘要", "body": "正文", "takeOut": false }',
|
|
2822
|
+
' ],',
|
|
2823
|
+
' "networkOps": [',
|
|
2824
|
+
' { "op": "link|unlink", "targetSessionId": "目标独立会话ID或名称关键词" }',
|
|
2056
2825
|
' ]',
|
|
2057
2826
|
'}',
|
|
2058
2827
|
'',
|
|
2059
2828
|
'宰相参谋与行事准则:',
|
|
2060
|
-
'-
|
|
2061
|
-
'-
|
|
2062
|
-
'-
|
|
2829
|
+
'- 【实权执行优先(禁止退化为纯传话筒)】:当用户要求你直接查文件、检查代码、修改补丁、跑测试/命令、直接派发/纠偏/中断子代理、记入档案或立即压缩时,务必先用 `toolCalls` 亲自执行并拿回真实结果后再汇报!只有用户明确要求转告 `@lead` / 其他窗口,或明确属主对话长程编码任务时,才使用 `relays` 递话。',
|
|
2830
|
+
'- 【许愿框全权自治】:无论整理/分类/提炼档案入全局、上下桌面、设定/覆盖/清空边界、重设/重编任务(`task.reset`/`graph.plan`),还是连接/断开独立窗口协同网络(`networkOps`),只要用户开口许愿且符合当前权限,直接输出对应 JSON ops 执行到位(严禁越级让本局档案直接跳级沉淀,必须遵循 `本局 -> 全局 -> 沉淀` 梯度),绝不推辞让用户自己去点按钮!',
|
|
2831
|
+
'- 【严守当前权限与禁止红线】:绝不越过当前权限等级上限,也绝不执行触发 `禁止红线 (forbidden)` 的写操作或高危命令。',
|
|
2832
|
+
'- 【问进展 / 问步骤 / 问卡点 / 求建议】:当用户询问“现在在做什么 / 处于什么步骤 / 目前进度如何 / 卡在哪里”等态势问题时,你面前的上下文已经完整包含「实时对话流快照」+「小任务板 (Plan)」+「任务图」+「断点游标」!直接用简明人话分点作答并放进 JSON 的 `reply` 字段,**严禁退化成纯工具 XML/DSML 标签输出,更严禁盲目运行 `run_command` / `list_dir` 扫盘**!只有用户明确要求去核查具体源码文件/跑命令实测时,才在 JSON `toolCalls` 里调工具。',
|
|
2833
|
+
'- 【代维护看板】:当用户让你「把某任务标为完成/受阻」「记一下下一步干啥」「改总目标」时,直接通过 `boardOps`(`task.update` / `cursor.set` / `objective.set` / `task.add`)落实(若强介入已锁定核心目标,则提示先解锁或关闭强介入)。',
|
|
2063
2834
|
'- 【边界奏请与零散浓缩】:',
|
|
2064
|
-
' 1)
|
|
2835
|
+
' 1) 总结踩坑红线或必做要求时,生成 `boundProposals` 呈交用户拍板(若用户提到「全局定住/以后所有任务都生效」则设 `"pinGlobal": true`);只有用户明确下令「直接写进禁止/必做边界」时才用 `boardOps`。',
|
|
2065
2836
|
' 2) 当用户要求「把重要的零散边界总结成一条 / 合并重复边界」时,仔细阅读现有边界,保留关键命令名/路径/硬红线,浓缩为 1 条精炼总则放入 `boundProposals[0].item`,并把被它吸收替代的旧条文原样放进 `replaces` 数组(若被合并旧规中含 📌 全局定住项,则 `"pinGlobal": true`)。',
|
|
2066
2837
|
'- 【看图与带图拆话】:当用户附带上传图片时,请直接结合图片画面诊断 UI 样式、报错截图或架构图;若你在 relays 中向代理拆话派活,系统会自动把用户附带的图片一并转送给目标代理。',
|
|
2067
2838
|
].join('\n')
|
|
2068
2839
|
|
|
2840
|
+
const CONCISE_BRIEF_ASK_EXTRA = [
|
|
2841
|
+
'',
|
|
2842
|
+
'⚡ 【极简战报模式已开启 — reply 字段强约束(六句话目标边界系列)】:',
|
|
2843
|
+
'- 一切以目标为导向,说人话,拒绝任何文件/代码/命令/端口/数字/计数等事务细节!',
|
|
2844
|
+
'- 总结现状或汇报进度时,优先按如下 6 条一句话边界结构输出:',
|
|
2845
|
+
' ## 极简目标战报',
|
|
2846
|
+
' - 【🎯 总目标】一句话说清最终目标',
|
|
2847
|
+
' - 【🚀 当前推进目标】一句话说清正在推进的目标',
|
|
2848
|
+
' - 【⛔ 受阻目标】一句话点明受阻处或“当前暂无受阻目标”',
|
|
2849
|
+
' - 【🧰 需要什么】一句话说明还需什么条件或验证',
|
|
2850
|
+
' - 【🙋 用户需要提供什么】一句话说明需用户提供/拍板的内容(或“暂无需您额外提供”)',
|
|
2851
|
+
' - 【💡 参谋长建议】一句话给出明确建议',
|
|
2852
|
+
].join('\n')
|
|
2853
|
+
|
|
2069
2854
|
const CONSOLIDATE_BOUNDS_SYSTEM = [
|
|
2070
2855
|
'你是「DSH 参谋长」(宰相级边界治理中枢)。用户的边界列表中积累了多条零散、重复或同一主题的规则。',
|
|
2071
2856
|
'请将给定的多条零散边界**浓缩合并成唯一 1 条**高信息密度、表述清晰、可直接执行的精炼总则(不超过 180 字)。',
|
|
@@ -2213,19 +2998,24 @@ function extractJsonObject(raw) {
|
|
|
2213
2998
|
return null
|
|
2214
2999
|
}
|
|
2215
3000
|
|
|
2216
|
-
function applyFactChanges(ws, numberedFacts, changes, actor = 'user') {
|
|
3001
|
+
function applyFactChanges(ws, numberedFacts, changes, actor = 'user', meta = {}) {
|
|
2217
3002
|
const applied = []
|
|
2218
3003
|
if (!Array.isArray(changes) || !changes.length) return applied
|
|
3004
|
+
const originRootId = typeof meta.originRootId === 'string' ? meta.originRootId : ''
|
|
3005
|
+
const clusterRoots = Array.isArray(meta.peerRootIds) ? meta.peerRootIds : []
|
|
2219
3006
|
|
|
2220
3007
|
for (const ch of changes.slice(0, 12)) {
|
|
2221
3008
|
if (!ch || typeof ch !== 'object') continue
|
|
2222
3009
|
const op = String(ch.op || '').trim()
|
|
2223
3010
|
if (op === 'add') {
|
|
3011
|
+
const category = ch.category || 'discipline'
|
|
2224
3012
|
const fact = normalizeFact({
|
|
2225
3013
|
text: ch.text,
|
|
2226
|
-
category
|
|
3014
|
+
category,
|
|
2227
3015
|
by: actor,
|
|
2228
3016
|
source: 'chief',
|
|
3017
|
+
originRootId: originRootId && originRootId !== 'global' ? originRootId : '',
|
|
3018
|
+
peerRootIds: category === 'team' ? clusterRoots : [],
|
|
2229
3019
|
})
|
|
2230
3020
|
if (!fact) continue
|
|
2231
3021
|
const dup = ws.facts.find(f => f.text === fact.text)
|
|
@@ -2259,14 +3049,22 @@ function applyFactChanges(ws, numberedFacts, changes, actor = 'user') {
|
|
|
2259
3049
|
return applied
|
|
2260
3050
|
}
|
|
2261
3051
|
|
|
2262
|
-
function applyBoardOps(deps, rootId, boardOps) {
|
|
3052
|
+
function applyBoardOps(deps, rootId, boardOps, opts = {}) {
|
|
2263
3053
|
const executed = []
|
|
2264
|
-
if (!Array.isArray(boardOps) || !boardOps.length) return executed
|
|
3054
|
+
if (!Array.isArray(boardOps) || !boardOps.length || !deps || typeof deps.runAction !== 'function') return executed
|
|
3055
|
+
const forceSessionOnly = Boolean(opts && opts.forceSessionOnly)
|
|
3056
|
+
const allowLockedObjectiveWrite = Boolean(opts && opts.allowLockedObjectiveWrite)
|
|
3057
|
+
const effCfg = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
3058
|
+
const objectiveLocked = Boolean(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.intervention) && !allowLockedObjectiveWrite
|
|
2265
3059
|
|
|
2266
3060
|
for (const opItem of boardOps.slice(0, 10)) {
|
|
2267
3061
|
if (!opItem || typeof opItem !== 'object') continue
|
|
2268
3062
|
const op = String(opItem.op || '').trim()
|
|
2269
3063
|
if (op === 'objective.set' && opItem.objective) {
|
|
3064
|
+
if (objectiveLocked) {
|
|
3065
|
+
executed.push('核心目标已锁定(强介入进行中,跳过改写)')
|
|
3066
|
+
continue
|
|
3067
|
+
}
|
|
2270
3068
|
deps.runAction({ action: 'objective.set', objective: String(opItem.objective), session: rootId, by: 'chief' })
|
|
2271
3069
|
executed.push('更新目标:' + clamp(opItem.objective, 40))
|
|
2272
3070
|
} else if (op === 'task.add' && opItem.title) {
|
|
@@ -2293,6 +3091,30 @@ function applyBoardOps(deps, rootId, boardOps) {
|
|
|
2293
3091
|
by: 'chief',
|
|
2294
3092
|
})
|
|
2295
3093
|
if (res && res.ok) executed.push(`更新任务 #${tid}${opItem.status ? ' → ' + opItem.status : ''}`)
|
|
3094
|
+
} else if (op === 'task.remove' && (opItem.id || opItem.taskId)) {
|
|
3095
|
+
const tid = String(opItem.id || opItem.taskId).trim()
|
|
3096
|
+
const res = deps.runAction({ action: 'task.remove', id: tid, session: rootId, by: 'chief' })
|
|
3097
|
+
if (res && res.ok) executed.push(`移除任务 #${tid}`)
|
|
3098
|
+
} else if (op === 'task.reset') {
|
|
3099
|
+
const res = deps.runAction({
|
|
3100
|
+
action: 'task.reset',
|
|
3101
|
+
...(typeof opItem.status === 'string' ? { status: opItem.status } : {}),
|
|
3102
|
+
...(opItem.resetPlan !== undefined ? { resetPlan: Boolean(opItem.resetPlan) } : {}),
|
|
3103
|
+
session: rootId,
|
|
3104
|
+
by: 'chief',
|
|
3105
|
+
})
|
|
3106
|
+
if (res && res.ok) executed.push(`重设任务看板(${res.removedCount ?? 0}项)`)
|
|
3107
|
+
} else if ((op === 'graph.plan' || op === 'task.batch') && Array.isArray(opItem.tasks) && opItem.tasks.length > 0) {
|
|
3108
|
+
const canSetObj = !objectiveLocked && typeof opItem.objective === 'string' && opItem.objective.trim()
|
|
3109
|
+
const res = deps.runAction({
|
|
3110
|
+
action: 'graph.plan',
|
|
3111
|
+
tasks: opItem.tasks,
|
|
3112
|
+
...(canSetObj ? { objective: opItem.objective } : {}),
|
|
3113
|
+
...(opItem.replace !== undefined ? { replace: Boolean(opItem.replace) } : {}),
|
|
3114
|
+
session: rootId,
|
|
3115
|
+
by: 'chief',
|
|
3116
|
+
})
|
|
3117
|
+
if (res && res.ok) executed.push(`重编任务拓扑(${(res.tasks || opItem.tasks).length}项)`)
|
|
2296
3118
|
} else if (op === 'cursor.set') {
|
|
2297
3119
|
const res = deps.runAction({
|
|
2298
3120
|
action: 'cursor.set',
|
|
@@ -2322,10 +3144,31 @@ function applyBoardOps(deps, rootId, boardOps) {
|
|
|
2322
3144
|
by: 'chief',
|
|
2323
3145
|
})
|
|
2324
3146
|
if (res && res.ok) executed.push('呈批目标结项')
|
|
2325
|
-
} else if (
|
|
2326
|
-
const
|
|
3147
|
+
} else if (op === 'bounds.set') {
|
|
3148
|
+
const rawField = String(opItem.field || '').trim().toLowerCase()
|
|
3149
|
+
const normField = rawField === 'must' ? 'allowed' : rawField
|
|
3150
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normField) ? normField : ''
|
|
3151
|
+
if (col && Array.isArray(opItem.items)) {
|
|
3152
|
+
const items = opItem.items.map(x => clamp(x, 220)).filter(Boolean)
|
|
3153
|
+
const res = deps.runAction({ action: 'bounds.set', field: col, items, session: rootId, by: 'chief' })
|
|
3154
|
+
if (res && res.ok) executed.push(`覆写边界(${col})共 ${items.length} 条`)
|
|
3155
|
+
} else if (Array.isArray(opItem.allowed) || Array.isArray(opItem.must) || Array.isArray(opItem.forbidden) || Array.isArray(opItem.notes)) {
|
|
3156
|
+
const allowList = Array.isArray(opItem.allowed) ? opItem.allowed : opItem.must
|
|
3157
|
+
const res = deps.runAction({
|
|
3158
|
+
action: 'bounds.set',
|
|
3159
|
+
...(Array.isArray(allowList) ? { allowed: allowList.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
3160
|
+
...(Array.isArray(opItem.forbidden) ? { forbidden: opItem.forbidden.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
3161
|
+
...(Array.isArray(opItem.notes) ? { notes: opItem.notes.map(x => clamp(x, 220)).filter(Boolean) } : {}),
|
|
3162
|
+
session: rootId,
|
|
3163
|
+
by: 'chief',
|
|
3164
|
+
})
|
|
3165
|
+
if (res && res.ok) executed.push('重置边界列表')
|
|
3166
|
+
}
|
|
3167
|
+
} else if ((op === 'bounds.forbid' || op === 'bounds.allow' || op === 'bounds.must' || op === 'bounds.note') && opItem.item) {
|
|
3168
|
+
const field = op === 'bounds.forbid' ? 'forbidden' : (op === 'bounds.note' ? 'notes' : 'allowed')
|
|
3169
|
+
const label = field === 'forbidden' ? '红线' : (field === 'notes' ? '注意' : '必做')
|
|
2327
3170
|
const val = clamp(opItem.item, 220)
|
|
2328
|
-
const pinned = Boolean(opItem.pinGlobal)
|
|
3171
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
2329
3172
|
if (val) {
|
|
2330
3173
|
const res = deps.runAction({
|
|
2331
3174
|
action: 'bounds.add',
|
|
@@ -2336,22 +3179,291 @@ function applyBoardOps(deps, rootId, boardOps) {
|
|
|
2336
3179
|
by: 'chief',
|
|
2337
3180
|
})
|
|
2338
3181
|
if (res && res.ok) {
|
|
2339
|
-
executed.push(`${pinned ? '📌全局' : '本任务'}${
|
|
3182
|
+
executed.push(`${pinned ? '📌全局' : '本任务'}${label}:${clamp(val, 30)}`)
|
|
3183
|
+
}
|
|
3184
|
+
}
|
|
3185
|
+
} else if (op === 'bounds.remove' && opItem.item) {
|
|
3186
|
+
const field = ['forbidden', 'allowed', 'notes'].includes(opItem.field) ? opItem.field : 'forbidden'
|
|
3187
|
+
const val = clamp(opItem.item, 220)
|
|
3188
|
+
const pinned = forceSessionOnly ? false : Boolean(opItem.pinGlobal)
|
|
3189
|
+
if (val) {
|
|
3190
|
+
const res = deps.runAction({
|
|
3191
|
+
action: 'bounds.remove',
|
|
3192
|
+
field,
|
|
3193
|
+
item: val,
|
|
3194
|
+
pinned,
|
|
3195
|
+
session: rootId,
|
|
3196
|
+
by: 'chief',
|
|
3197
|
+
})
|
|
3198
|
+
if (res && res.ok) {
|
|
3199
|
+
executed.push(`移除边界:${clamp(val, 30)}`)
|
|
3200
|
+
}
|
|
3201
|
+
}
|
|
3202
|
+
}
|
|
3203
|
+
}
|
|
3204
|
+
return executed
|
|
3205
|
+
}
|
|
3206
|
+
|
|
3207
|
+
/**
|
|
3208
|
+
* Execute Wishing-Box `archiveOps` across Session / Global / Precipitated vaults
|
|
3209
|
+
* while strictly preserving the upward gradient (`session -> global -> precipitated`;
|
|
3210
|
+
* direct session -> precipitated jump is forbidden).
|
|
3211
|
+
*/
|
|
3212
|
+
async function applyArchiveOps(deps, rootId, archiveOps, ctx = {}) {
|
|
3213
|
+
const executed = []
|
|
3214
|
+
if (!Array.isArray(archiveOps) || !archiveOps.length) return { executed, changed: false }
|
|
3215
|
+
const sid = rootId && rootId !== 'global' ? String(rootId).trim() : ''
|
|
3216
|
+
const globalOpt = archiveTargetForRoot(deps, sid || 'global', { vaultScope: 'global' })
|
|
3217
|
+
const sessionOpt = sid ? archiveTargetForRoot(deps, sid, { vaultScope: 'session' }) : null
|
|
3218
|
+
const projectKey = resolveProjectKey(globalOpt.cwd)
|
|
3219
|
+
let changed = false
|
|
3220
|
+
|
|
3221
|
+
const resolveItemInScope = (scope, rawId, rawTitle) => {
|
|
3222
|
+
const idQ = String(rawId || '').trim()
|
|
3223
|
+
const titleQ = String(rawTitle || '').trim().toLowerCase()
|
|
3224
|
+
if (scope === 'precipitated') {
|
|
3225
|
+
const items = listPrecipitatedHeaders(projectKey, sid, globalOpt) || []
|
|
3226
|
+
if (idQ) {
|
|
3227
|
+
const exact = items.find(it => it.id === idQ)
|
|
3228
|
+
if (exact) return exact.id
|
|
3229
|
+
}
|
|
3230
|
+
if (titleQ) {
|
|
3231
|
+
const byTitle = items.find(it => String(it.title || '').toLowerCase().includes(titleQ))
|
|
3232
|
+
if (byTitle) return byTitle.id
|
|
3233
|
+
}
|
|
3234
|
+
return idQ
|
|
3235
|
+
}
|
|
3236
|
+
const opt = scope === 'global' ? globalOpt : sessionOpt
|
|
3237
|
+
if (!opt) return idQ
|
|
3238
|
+
const store = loadArchiveStore(opt)
|
|
3239
|
+
const items = Array.isArray(store.items) ? store.items : []
|
|
3240
|
+
if (idQ) {
|
|
3241
|
+
const exact = items.find(it => it.id === idQ)
|
|
3242
|
+
if (exact) return exact.id
|
|
3243
|
+
}
|
|
3244
|
+
if (titleQ) {
|
|
3245
|
+
const byTitle = items.find(it => String(it.title || '').toLowerCase().includes(titleQ))
|
|
3246
|
+
if (byTitle) return byTitle.id
|
|
3247
|
+
}
|
|
3248
|
+
return idQ
|
|
3249
|
+
}
|
|
3250
|
+
|
|
3251
|
+
for (const opItem of archiveOps.slice(0, 8)) {
|
|
3252
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
3253
|
+
const op = String(opItem.op || '').trim()
|
|
3254
|
+
const scope = opItem.vaultScope === 'precipitated'
|
|
3255
|
+
? 'precipitated'
|
|
3256
|
+
: (opItem.vaultScope === 'global' ? 'global' : 'session')
|
|
3257
|
+
|
|
3258
|
+
if (op === 'organize') {
|
|
3259
|
+
const orgScope = opItem.vaultScope === 'global' ? 'global' : 'session'
|
|
3260
|
+
if (orgScope === 'session' && !sid) continue
|
|
3261
|
+
const r = await organizeArchivesWithChief(deps, {
|
|
3262
|
+
sessionId: sid || 'global',
|
|
3263
|
+
vaultScope: orgScope,
|
|
3264
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : [],
|
|
3265
|
+
scope: opItem.scope === 'all' ? 'all' : 'unorganized',
|
|
3266
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
3267
|
+
}).catch(() => null)
|
|
3268
|
+
if (r && r.ok) {
|
|
3269
|
+
changed = true
|
|
3270
|
+
executed.push(`整理${orgScope === 'global' ? '全局' : '本局'}档案 ×${r.updatedCount ?? 0}`)
|
|
3271
|
+
}
|
|
3272
|
+
} else if (op === 'distill_to_global' || op === 'distill') {
|
|
3273
|
+
if (!sid) continue
|
|
3274
|
+
const r = await distillSessionArchivesToGlobal(deps, {
|
|
3275
|
+
sessionId: sid,
|
|
3276
|
+
ids: Array.isArray(opItem.ids) ? opItem.ids : (opItem.id ? [opItem.id] : []),
|
|
3277
|
+
instruction: String(opItem.instruction || ctx.input || ''),
|
|
3278
|
+
}).catch(() => null)
|
|
3279
|
+
if (r && r.ok) {
|
|
3280
|
+
changed = true
|
|
3281
|
+
executed.push(`提炼入全局 ×${r.createdCount ?? 0}`)
|
|
3282
|
+
}
|
|
3283
|
+
} else if (op === 'save' || op === 'create') {
|
|
3284
|
+
if (scope === 'precipitated') continue // strict gradient: cannot write directly into precipitated
|
|
3285
|
+
if (scope === 'session' && !sid) continue
|
|
3286
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
3287
|
+
const r = mutateArchive({
|
|
3288
|
+
op: 'save',
|
|
3289
|
+
vaultScope: scope,
|
|
3290
|
+
rootSessionId: sid,
|
|
3291
|
+
folder: opItem.folder || 'inbox',
|
|
3292
|
+
paperclip: ['gold', 'silver', 'copper'].includes(opItem.paperclip) ? opItem.paperclip : 'silver',
|
|
3293
|
+
title: clamp(opItem.title || '参谋长工作归档', 160),
|
|
3294
|
+
summary: clamp(opItem.summary || '', 400),
|
|
3295
|
+
body: cleanMultiline(opItem.body || opItem.summary || opItem.title || '', 12000),
|
|
3296
|
+
takeOutNow: Boolean(opItem.takeOut),
|
|
3297
|
+
by: 'chief',
|
|
3298
|
+
}, targetOpt)
|
|
3299
|
+
if (r && r.ok) {
|
|
3300
|
+
changed = true
|
|
3301
|
+
executed.push(`存档(${scope === 'global' ? '全局' : '本局'}):《${clamp(opItem.title || '', 24)}》`)
|
|
3302
|
+
}
|
|
3303
|
+
} else if (op === 'take_out' || op === 'put_back') {
|
|
3304
|
+
if (!sid) continue
|
|
3305
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
3306
|
+
if (!hitId) continue
|
|
3307
|
+
if (scope === 'precipitated') {
|
|
3308
|
+
const pOp = op === 'take_out' ? 'flipOut' : 'sealBack'
|
|
3309
|
+
const r = mutatePrecipitated(projectKey, { op: pOp, id: hitId, rootSessionId: sid }, { ...globalOpt, rootSessionId: sid })
|
|
3310
|
+
if (r && r.ok) {
|
|
3311
|
+
updateWorkspaceFlippedIds(sid, pOp === 'flipOut' ? { flippedId: hitId } : { sealId: hitId })
|
|
3312
|
+
changed = true
|
|
3313
|
+
executed.push(`${op === 'take_out' ? '摆上桌面(沉淀)' : '放回封存(沉淀)'} #${hitId}`)
|
|
3314
|
+
}
|
|
3315
|
+
} else {
|
|
3316
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
3317
|
+
const r = mutateArchive({
|
|
3318
|
+
op: op === 'take_out' ? 'takeOut' : 'putBack',
|
|
3319
|
+
vaultScope: scope,
|
|
3320
|
+
rootSessionId: sid,
|
|
3321
|
+
id: hitId,
|
|
3322
|
+
}, targetOpt)
|
|
3323
|
+
if (r && r.ok) {
|
|
3324
|
+
changed = true
|
|
3325
|
+
executed.push(`${op === 'take_out' ? '摆上桌面' : '放回封存'} #${hitId}`)
|
|
2340
3326
|
}
|
|
2341
3327
|
}
|
|
3328
|
+
} else if (op === 'mount_chief' || op === 'unmount_chief') {
|
|
3329
|
+
if (!sid) continue
|
|
3330
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
3331
|
+
if (!hitId) continue
|
|
3332
|
+
const r = mutateArchive({
|
|
3333
|
+
op: op === 'mount_chief' ? 'mountChief' : 'unmountChief',
|
|
3334
|
+
vaultScope: 'global',
|
|
3335
|
+
rootSessionId: sid,
|
|
3336
|
+
id: hitId,
|
|
3337
|
+
}, globalOpt)
|
|
3338
|
+
if (r && r.ok) {
|
|
3339
|
+
changed = true
|
|
3340
|
+
executed.push(`${op === 'mount_chief' ? '参阅全局档案' : '取消全局参阅'} #${hitId}`)
|
|
3341
|
+
}
|
|
3342
|
+
} else if (op === 'copy_to_global') {
|
|
3343
|
+
if (!sid) continue
|
|
3344
|
+
const hitId = resolveItemInScope('session', opItem.id || opItem.archiveId, opItem.title)
|
|
3345
|
+
if (!hitId) continue
|
|
3346
|
+
const r = mutateArchive({ op: 'copyToGlobal', vaultScope: 'session', rootSessionId: sid, id: hitId }, sessionOpt)
|
|
3347
|
+
if (r && r.ok) {
|
|
3348
|
+
changed = true
|
|
3349
|
+
executed.push(`升入全局档案 #${hitId}`)
|
|
3350
|
+
}
|
|
3351
|
+
} else if (op === 'copy_to_session') {
|
|
3352
|
+
if (!sid) continue
|
|
3353
|
+
const hitId = resolveItemInScope('global', opItem.id || opItem.archiveId, opItem.title)
|
|
3354
|
+
if (!hitId) continue
|
|
3355
|
+
const r = mutateArchive({ op: 'copyToSession', vaultScope: 'global', rootSessionId: sid, id: hitId }, globalOpt)
|
|
3356
|
+
if (r && r.ok) {
|
|
3357
|
+
changed = true
|
|
3358
|
+
executed.push(`全局调入本局 #${hitId}`)
|
|
3359
|
+
}
|
|
3360
|
+
} else if (op === 'pull_precipitated') {
|
|
3361
|
+
const targetScope = opItem.targetScope === 'global' ? 'global' : 'session'
|
|
3362
|
+
if (targetScope === 'session' && !sid) continue
|
|
3363
|
+
const hitId = resolveItemInScope('precipitated', opItem.id || opItem.archiveId, opItem.title)
|
|
3364
|
+
if (!hitId) continue
|
|
3365
|
+
const r = copyPrecipitatedToVault(projectKey, {
|
|
3366
|
+
id: hitId,
|
|
3367
|
+
targetScope,
|
|
3368
|
+
rootSessionId: sid,
|
|
3369
|
+
takeOutNow: Boolean(opItem.takeOut),
|
|
3370
|
+
}, { ...globalOpt, rootSessionId: sid })
|
|
3371
|
+
if (r && r.ok) {
|
|
3372
|
+
changed = true
|
|
3373
|
+
executed.push(`沉淀无损调入${targetScope === 'global' ? '全局' : '本局'} #${hitId}`)
|
|
3374
|
+
}
|
|
3375
|
+
} else if (op === 'move_folder' && opItem.folder) {
|
|
3376
|
+
if (scope === 'precipitated') continue
|
|
3377
|
+
if (scope === 'session' && !sid) continue
|
|
3378
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
3379
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
3380
|
+
if (!hitId) continue
|
|
3381
|
+
const r = mutateArchive({ op: 'moveFolder', vaultScope: scope, rootSessionId: sid, id: hitId, folder: opItem.folder }, targetOpt)
|
|
3382
|
+
if (r && r.ok) {
|
|
3383
|
+
changed = true
|
|
3384
|
+
executed.push(`移动档案分类 → ${opItem.folder}`)
|
|
3385
|
+
}
|
|
3386
|
+
} else if (op === 'delete' || op === 'remove') {
|
|
3387
|
+
if (scope === 'precipitated') continue
|
|
3388
|
+
if (scope === 'session' && !sid) continue
|
|
3389
|
+
const targetOpt = scope === 'global' ? globalOpt : sessionOpt
|
|
3390
|
+
const hitId = resolveItemInScope(scope, opItem.id || opItem.archiveId, opItem.title)
|
|
3391
|
+
if (!hitId) continue
|
|
3392
|
+
const r = mutateArchive({ op: 'delete', vaultScope: scope, rootSessionId: sid, id: hitId }, targetOpt)
|
|
3393
|
+
if (r && r.ok) {
|
|
3394
|
+
changed = true
|
|
3395
|
+
executed.push(`移除${scope === 'global' ? '全局' : '本局'}档案 #${hitId}`)
|
|
3396
|
+
}
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
3399
|
+
|
|
3400
|
+
return { executed, changed }
|
|
3401
|
+
}
|
|
3402
|
+
|
|
3403
|
+
/** Execute Wishing-Box `networkOps` to link or unlink standalone DSH sessions. */
|
|
3404
|
+
function applyNetworkOps(rootId, networkOps, directory) {
|
|
3405
|
+
const executed = []
|
|
3406
|
+
if (!Array.isArray(networkOps) || !networkOps.length || !rootId || rootId === 'global') return executed
|
|
3407
|
+
const otherSessions = (directory && Array.isArray(directory.otherSessions)) ? directory.otherSessions : []
|
|
3408
|
+
|
|
3409
|
+
for (const opItem of networkOps.slice(0, 6)) {
|
|
3410
|
+
if (!opItem || typeof opItem !== 'object') continue
|
|
3411
|
+
const op = String(opItem.op || '').trim()
|
|
3412
|
+
if (op !== 'link' && op !== 'unlink') continue
|
|
3413
|
+
const rawQ = String(opItem.targetSessionId || opItem.target || opItem.sessionId || opItem.name || '').trim()
|
|
3414
|
+
if (!rawQ) continue
|
|
3415
|
+
const qLower = rawQ.toLowerCase()
|
|
3416
|
+
const match = otherSessions.find(s =>
|
|
3417
|
+
s.id === rawQ
|
|
3418
|
+
|| String(s.id).toLowerCase().includes(qLower)
|
|
3419
|
+
|| (s.name && String(s.name).toLowerCase().includes(qLower))
|
|
3420
|
+
)
|
|
3421
|
+
const targetSid = match ? match.id : (/^session-/i.test(rawQ) ? rawQ : '')
|
|
3422
|
+
if (!targetSid || targetSid === rootId) continue
|
|
3423
|
+
const r = setPeerLink(rootId, targetSid, op === 'link')
|
|
3424
|
+
if (r && r.ok) {
|
|
3425
|
+
executed.push(`${op === 'link' ? '连接协同窗口' : '断开协同窗口'}:${match ? match.name : targetSid.slice(0, 14)}`)
|
|
2342
3426
|
}
|
|
2343
3427
|
}
|
|
2344
3428
|
return executed
|
|
2345
3429
|
}
|
|
2346
3430
|
|
|
3431
|
+
/** Detect pure beginner progress/status questions where all truth is already in live snapshot + board (zero disk/shell tools needed). */
|
|
3432
|
+
function isPureStatusInquiry(rawText) {
|
|
3433
|
+
const q = String(rawText || '').trim()
|
|
3434
|
+
if (!q || q.length > 90) return false
|
|
3435
|
+
if (/read_file|write_file|edit_file|run_command|list_dir|search_files|执行|运行|测试|跑一下|改一下|写一个|修一下|删除|新建|创建|安装|部署|派发|递话|转告|中断|清[空理]|重设|重置|提炼|浓缩|合并/.test(q)) {
|
|
3436
|
+
return false
|
|
3437
|
+
}
|
|
3438
|
+
return /(?:现在在做什么|在做什么|在干嘛|在干什么|处于什么步骤|什么步骤|第几步|到哪一步|到哪了|做到哪|进度|进展|情况如何|怎么样了|当前状态|实时状态|团队在|主对话在|主代理在|子代理在)/.test(q)
|
|
3439
|
+
}
|
|
3440
|
+
|
|
3441
|
+
/** Detect explicit user requests asking Chief to immediately compress/compact context. */
|
|
3442
|
+
export function isExplicitCompactCommand(rawText) {
|
|
3443
|
+
const q = String(rawText || '').trim()
|
|
3444
|
+
if (!q || q.length > 80) return false
|
|
3445
|
+
if (/不要压缩|别压缩|不用压缩|停止压缩|关闭压缩|取消压缩|为什么|为啥|没触发|未触发|不能|无法|报错|失败|是什么|原理|区别|开关|怎么(?:设置|用|开|关)/.test(q)) {
|
|
3446
|
+
return false
|
|
3447
|
+
}
|
|
3448
|
+
if (/^\/compact(?:\s|$)/i.test(q)) return true
|
|
3449
|
+
if (!/压缩/.test(q)) return false
|
|
3450
|
+
if (/文件|图片|视频|音频|zip|tar|gzip|rar|7z|打包/i.test(q) && !/上下文|对话|会话|历史|记忆|session|context/i.test(q)) {
|
|
3451
|
+
return false
|
|
3452
|
+
}
|
|
3453
|
+
return /^(?:请|麻烦|帮我|给我|你|可以|先|赶紧|立即|立刻|马上|现在|把[\u4e00-\u9fa5]{0,12})*(?:执行|触发|做一下|跑一下|开始|进行|归档并|抢救并)?(?:一键|手动|静默)?(?:当前|一下|下)?(?:上下文|对话|会话|历史|内容|内存)?压缩(?:当前|一下|下)?(?:上下文|对话|会话|历史|内存)?(?:吧|一下|下|呀|啊|哦|嘛|呢|好了|好吗|可以吗|!|!|。|\.)*$/i.test(q)
|
|
3454
|
+
}
|
|
3455
|
+
|
|
2347
3456
|
/**
|
|
2348
3457
|
* Holistic offline/fallback intelligence synthesizer so DSH Chief NEVER
|
|
2349
3458
|
* utters "记忆里没有这条" even if every configured LLM provider is unreachable.
|
|
2350
3459
|
*/
|
|
2351
|
-
function buildSmartFallbackReply({ input, board, liveDigest, directory, facts = [], mailbox = [] }) {
|
|
3460
|
+
function buildSmartFallbackReply({ input, board, liveDigest, directory, facts = [], mailbox = [], conciseBrief = false }) {
|
|
2352
3461
|
const q = String(input || '').trim()
|
|
2353
3462
|
const qLower = q.toLowerCase()
|
|
2354
3463
|
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
3464
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
3465
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
3466
|
+
const donePlan = planSteps.filter(s => s.done)
|
|
2355
3467
|
const doing = tasks.filter(t => t.status === 'doing')
|
|
2356
3468
|
const blocked = tasks.filter(t => t.status === 'blocked')
|
|
2357
3469
|
const todo = tasks.filter(t => t.status === 'todo')
|
|
@@ -2366,10 +3478,14 @@ function buildSmartFallbackReply({ input, board, liveDigest, directory, facts =
|
|
|
2366
3478
|
const cleanMem = (Array.isArray(board && board.memory) ? board.memory : [])
|
|
2367
3479
|
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
2368
3480
|
|
|
2369
|
-
|
|
3481
|
+
if (conciseBrief) {
|
|
3482
|
+
return buildConciseSixLineReport({ board, blocked, doing, todo, done, workers })
|
|
3483
|
+
}
|
|
3484
|
+
|
|
3485
|
+
const asksBounds = /边界|红线|禁止|允许|必做|规矩|约束/.test(q)
|
|
2370
3486
|
const asksTeam = /子代理|团队|谁在|分工|成员|subagent|worker/i.test(qLower)
|
|
2371
3487
|
const asksBlocked = /卡在哪|受阻|阻塞|报错|问题|风险|撞墙|block/i.test(qLower)
|
|
2372
|
-
const asksProgress =
|
|
3488
|
+
const asksProgress = /进展|进度|怎么样|到哪|在做什么|在干嘛|干什么|处于什么步骤|什么步骤|第几步|情况|状态|汇报|总结|下一步|status|progress/i.test(qLower)
|
|
2373
3489
|
|
|
2374
3490
|
const bullets = []
|
|
2375
3491
|
|
|
@@ -2380,7 +3496,7 @@ function buildSmartFallbackReply({ input, board, liveDigest, directory, facts =
|
|
|
2380
3496
|
const pinCount = (pinnedBounds.forbidden?.length || 0) + (pinnedBounds.allowed?.length || 0) + (pinnedBounds.notes?.length || 0)
|
|
2381
3497
|
bullets.push(`- 【生效边界概览】共 ${fList.length + aList.length + nList.length} 条生效(其中 📌 定住全局共享 ${pinCount} 条)。`)
|
|
2382
3498
|
if (fList.length) bullets.push(`- 【禁止红线】${fList.slice(0, 5).map(x => (pinnedBounds.forbidden?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
2383
|
-
if (aList.length) bullets.push(`-
|
|
3499
|
+
if (aList.length) bullets.push(`- 【必做事项】${aList.slice(0, 4).map(x => (pinnedBounds.allowed?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
2384
3500
|
if (nList.length) bullets.push(`- 【注意事项】${nList.slice(0, 3).map(x => (pinnedBounds.notes?.includes(x) ? '📌' : '') + clamp(x, 60)).join(';')}`)
|
|
2385
3501
|
if (!fList.length && !aList.length && !nList.length) {
|
|
2386
3502
|
bullets.push('- 【提示】当前尚未配置边界规则,可在「边界」页添加并点击 📌 定住为跨任务共享,或点「✦ 提炼新边界」。')
|
|
@@ -2442,6 +3558,9 @@ function buildSmartFallbackReply({ input, board, liveDigest, directory, facts =
|
|
|
2442
3558
|
if (cursor.next) curParts.push(`下一步:${clamp(cursor.next, 80)}`)
|
|
2443
3559
|
bullets.push(`- 【实时断点】${curParts.join(';')}`)
|
|
2444
3560
|
}
|
|
3561
|
+
if (planSteps.length > 0) {
|
|
3562
|
+
bullets.push(`- 【小任务板 (${donePlan.length}/${planSteps.length})】${openPlan.length ? '当前待推进:' + clamp(openPlan[0].text, 90) : '全部步骤已勾选完成'}${donePlan.length ? '(最近已完成:' + clamp(donePlan[donePlan.length - 1].text, 55) + ')' : ''}`)
|
|
3563
|
+
}
|
|
2445
3564
|
if (tasks.length > 0) {
|
|
2446
3565
|
bullets.push(`- 【任务盘点】共 ${tasks.length} 项:🟢推进中 ${doing.length} · 🔴受阻 ${blocked.length} · ⏳待办 ${todo.length} · ✅已完成 ${done.length}`)
|
|
2447
3566
|
for (const b of blocked.slice(0, 3)) {
|
|
@@ -2481,6 +3600,8 @@ function buildSmartFallbackReply({ input, board, liveDigest, directory, facts =
|
|
|
2481
3600
|
bullets.push(`- 【参谋建议】当前有 ${blocked.length} 项任务受阻,建议优先排障 #${blocked[0].id},或让我直接向主代理/对应子代理插话调整方案。`)
|
|
2482
3601
|
} else if (doing.length > 0 || runningWorkers.length > 0) {
|
|
2483
3602
|
bullets.push('- 【参谋建议】主线正在推进中;如需纠偏方向或补充约束,可直接告诉我「让 @某成员 注意……」,我立即替你插话传达。')
|
|
3603
|
+
} else if (openPlan.length > 0) {
|
|
3604
|
+
bullets.push(`- 【参谋建议】小任务板下一待办步骤为「${clamp(openPlan[0].text, 55)}」,可直接确认执行或让我转告主对话继续。`)
|
|
2484
3605
|
} else if (todo.length > 0) {
|
|
2485
3606
|
bullets.push(`- 【参谋建议】当前无运行中代理,尚有 ${todo.length} 项待办(首项:#${todo[0].id} ${clamp(todo[0].title, 40)}),可吩咐主对话继续推进。`)
|
|
2486
3607
|
} else if (!bullets.length) {
|
|
@@ -2540,7 +3661,7 @@ export async function consolidateBoundsWithChief(deps, {
|
|
|
2540
3661
|
: { bounds: { allowed: [], forbidden: [], notes: [] }, pinnedBounds: { allowed: [], forbidden: [], notes: [] } }
|
|
2541
3662
|
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2542
3663
|
const pinnedBounds = (board && board.pinnedBounds) || { allowed: [], forbidden: [], notes: [] }
|
|
2543
|
-
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '
|
|
3664
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
2544
3665
|
|
|
2545
3666
|
// Determine which column(s) to consolidate
|
|
2546
3667
|
const targetCols = []
|
|
@@ -2548,15 +3669,16 @@ export async function consolidateBoundsWithChief(deps, {
|
|
|
2548
3669
|
? items.map(x => String(x || '').trim()).filter(Boolean)
|
|
2549
3670
|
: []
|
|
2550
3671
|
|
|
2551
|
-
|
|
2552
|
-
|
|
3672
|
+
const normField = String(field || '').trim().toLowerCase() === 'must' ? 'allowed' : field
|
|
3673
|
+
if (['forbidden', 'allowed', 'notes'].includes(normField)) {
|
|
3674
|
+
const colList = Array.isArray(bounds[normField]) ? bounds[normField] : []
|
|
2553
3675
|
const chosen = explicitItems.length >= 2
|
|
2554
3676
|
? colList.filter(x => explicitItems.includes(x))
|
|
2555
3677
|
: colList
|
|
2556
3678
|
if (chosen.length < 2) {
|
|
2557
|
-
return { ok: false, error: `【${BOUND_COL_LABEL[
|
|
3679
|
+
return { ok: false, error: `【${BOUND_COL_LABEL[normField]}】当前不足 2 条规则,无需浓缩合并。` }
|
|
2558
3680
|
}
|
|
2559
|
-
targetCols.push({ col:
|
|
3681
|
+
targetCols.push({ col: normField, sourceItems: chosen })
|
|
2560
3682
|
} else if (explicitItems.length >= 2) {
|
|
2561
3683
|
// Infer column with most matches, default forbidden
|
|
2562
3684
|
let bestCol = 'forbidden'
|
|
@@ -2704,6 +3826,7 @@ const ORGANIZE_ARCHIVES_SYSTEM = [
|
|
|
2704
3826
|
*/
|
|
2705
3827
|
export async function organizeArchivesWithChief(deps, {
|
|
2706
3828
|
sessionId = '',
|
|
3829
|
+
vaultScope = 'session',
|
|
2707
3830
|
cabinetId = '',
|
|
2708
3831
|
ids = [],
|
|
2709
3832
|
folder = '',
|
|
@@ -2711,7 +3834,14 @@ export async function organizeArchivesWithChief(deps, {
|
|
|
2711
3834
|
instruction = '',
|
|
2712
3835
|
} = {}) {
|
|
2713
3836
|
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
2714
|
-
const
|
|
3837
|
+
const effScope = vaultScope === 'global' ? 'global' : 'session'
|
|
3838
|
+
if (effScope === 'session' && (!rootId || rootId === 'global')) {
|
|
3839
|
+
return {
|
|
3840
|
+
ok: false,
|
|
3841
|
+
error: '当前为空白新对话,尚未建立本会话档案柜;如需整理全局知识请切至「🌐 全局档案柜」',
|
|
3842
|
+
}
|
|
3843
|
+
}
|
|
3844
|
+
const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
|
|
2715
3845
|
const store = loadArchiveStore(targetOpt)
|
|
2716
3846
|
|
|
2717
3847
|
if (!store.items.length) {
|
|
@@ -2957,16 +4087,21 @@ function collectRawSessionEvidence(deps, { sessionId = '', rootId = '', agent =
|
|
|
2957
4087
|
}
|
|
2958
4088
|
}
|
|
2959
4089
|
|
|
2960
|
-
/** High-precision harvest of recent session details into active
|
|
4090
|
+
/** High-precision harvest of recent session details into active working archive cabinet (`pre-compaction` or `manual`). */
|
|
2961
4091
|
export async function harvestTurnDetailsToArchive(deps, {
|
|
2962
4092
|
sessionId = '',
|
|
2963
4093
|
agent = null,
|
|
2964
4094
|
trigger = 'manual',
|
|
2965
4095
|
focusHint = '',
|
|
2966
4096
|
cabinetId = '',
|
|
4097
|
+
vaultScope = 'session',
|
|
2967
4098
|
} = {}) {
|
|
2968
4099
|
const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId, agent)) || String(sessionId || 'global')
|
|
2969
|
-
const
|
|
4100
|
+
const effScope = vaultScope === 'global' ? 'global' : 'session'
|
|
4101
|
+
if (effScope === 'session' && (!rootId || rootId === 'global')) {
|
|
4102
|
+
return { ok: false, error: '当前为空白新对话(未绑定会话 ID),请先发送一条消息或切至「🌐 全局档案柜」再抢救归档' }
|
|
4103
|
+
}
|
|
4104
|
+
const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
|
|
2970
4105
|
const evidence = collectRawSessionEvidence(deps, { sessionId: sessionId || rootId, rootId, agent })
|
|
2971
4106
|
const bodySource = [
|
|
2972
4107
|
focusHint ? `【抢救焦点提示】${cleanMultiline(focusHint, 240)}` : '',
|
|
@@ -3068,22 +4203,34 @@ const PRECIPITATE_EXPERIENCE_SYSTEM = [
|
|
|
3068
4203
|
'}',
|
|
3069
4204
|
].join('\n')
|
|
3070
4205
|
|
|
3071
|
-
/** Purify working archive items into reusable long-term entries saved to `precipitated
|
|
4206
|
+
/** Purify working archive items into reusable long-term entries saved to `precipitated/vault-global.json`. */
|
|
3072
4207
|
export async function precipitateExperienceWithChief(deps, {
|
|
3073
4208
|
sessionId = '',
|
|
4209
|
+
vaultScope = 'global',
|
|
3074
4210
|
op = 'cabinet',
|
|
3075
4211
|
cabinetId = '',
|
|
3076
4212
|
folder = '',
|
|
4213
|
+
ids = [],
|
|
3077
4214
|
clearSource = false,
|
|
3078
4215
|
} = {}) {
|
|
4216
|
+
if (vaultScope !== 'global') {
|
|
4217
|
+
return {
|
|
4218
|
+
ok: false,
|
|
4219
|
+
error: '实行三层档案梯度制度:本会话档案不可直接沉淀入冷库!请先点击「🌐 升级入全局」进入全局档案柜,再从全局档案柜沉淀可复用冷经验。',
|
|
4220
|
+
}
|
|
4221
|
+
}
|
|
3079
4222
|
const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || 'global')
|
|
3080
|
-
const
|
|
4223
|
+
const effScope = 'global'
|
|
4224
|
+
const targetOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: effScope })
|
|
3081
4225
|
const store = loadArchiveStore(targetOpt)
|
|
3082
4226
|
const projectKey = resolveProjectKey(targetOpt.cwd)
|
|
3083
4227
|
|
|
3084
|
-
const
|
|
3085
|
-
?
|
|
3086
|
-
:
|
|
4228
|
+
const idSet = Array.isArray(ids) && ids.length > 0
|
|
4229
|
+
? new Set(ids.map(x => String(x || '').trim()).filter(Boolean))
|
|
4230
|
+
: null
|
|
4231
|
+
const selectedItems = idSet
|
|
4232
|
+
? store.items.filter(it => idSet.has(String(it.id)))
|
|
4233
|
+
: ((op === 'drawer' && folder) ? store.items.filter(it => it.folder === folder) : store.items.slice())
|
|
3087
4234
|
|
|
3088
4235
|
if (!selectedItems.length) {
|
|
3089
4236
|
return { ok: false, error: '当前选定范围暂无工作档案可沉淀' }
|
|
@@ -3164,7 +4311,7 @@ export async function precipitateExperienceWithChief(deps, {
|
|
|
3164
4311
|
|
|
3165
4312
|
let clearedSource = false
|
|
3166
4313
|
if (clearSource) {
|
|
3167
|
-
if (op === 'drawer' && folder) {
|
|
4314
|
+
if (!idSet && op === 'drawer' && folder) {
|
|
3168
4315
|
mutateArchive({ op: 'clearFolder', folder }, targetOpt)
|
|
3169
4316
|
clearedSource = true
|
|
3170
4317
|
} else {
|
|
@@ -3188,6 +4335,196 @@ export async function precipitateExperienceWithChief(deps, {
|
|
|
3188
4335
|
}
|
|
3189
4336
|
}
|
|
3190
4337
|
|
|
4338
|
+
const DISTILL_TO_GLOBAL_SYSTEM = [
|
|
4339
|
+
'你是「DSH 参谋长」的知识萃取总编。请审查当前「本会话工作档案柜」中的临时工作卷宗:',
|
|
4340
|
+
'1. **摘除一次性噪音**:剔除只属于本次调试流水账、临时状态快照或纯闲聊过渡的信息;',
|
|
4341
|
+
'2. **萃取可复用精华**:只摘出并总结未来跨会话仍长期有用的【工程坐标、入口路径、架构契约、核心命令、接口定义、通用踩坑与红线经验】;',
|
|
4342
|
+
'3. **浓缩成全局卷宗**:同类主题合并为 1~4 卷高信息密度、结构清晰的全局档案,保留真实文件名/函数名/命令参数,严禁编造;',
|
|
4343
|
+
'4. **只输出一个合法 JSON 对象**:',
|
|
4344
|
+
'{',
|
|
4345
|
+
' "entries": [',
|
|
4346
|
+
' {',
|
|
4347
|
+
' "title": "全局档案短标题(≤36字)",',
|
|
4348
|
+
' "folder": "coords|incidents|contracts|ops",',
|
|
4349
|
+
' "paperclip": "gold|silver",',
|
|
4350
|
+
' "summary": "一句话可复用价值摘要(≤60字)",',
|
|
4351
|
+
' "tags": ["标签1", "标签2"],',
|
|
4352
|
+
' "points": [',
|
|
4353
|
+
' { "title": "要点标题", "cue": "一句话钩子", "detail": "完整可复用步骤/路径/契约" }',
|
|
4354
|
+
' ],',
|
|
4355
|
+
' "body": "完整精炼正文"',
|
|
4356
|
+
' }',
|
|
4357
|
+
' ]',
|
|
4358
|
+
'}',
|
|
4359
|
+
].join('\n')
|
|
4360
|
+
|
|
4361
|
+
/** Extract, summarize, and distill reusable items from the current Session Cabinet into the Global Vault (`vaultScope: 'global'`). */
|
|
4362
|
+
export async function distillSessionArchivesToGlobal(deps, {
|
|
4363
|
+
sessionId = '',
|
|
4364
|
+
cabinetId = '',
|
|
4365
|
+
ids = null,
|
|
4366
|
+
folder = '',
|
|
4367
|
+
clearSource = false,
|
|
4368
|
+
instruction = '',
|
|
4369
|
+
} = {}) {
|
|
4370
|
+
const rootId = (deps && deps.resolveRootSessionId && deps.resolveRootSessionId(sessionId)) || String(sessionId || '').trim()
|
|
4371
|
+
if (!rootId || rootId === 'global') {
|
|
4372
|
+
return { ok: false, error: '当前未绑定具体对话会话,无法从本局档案柜提炼入全局库' }
|
|
4373
|
+
}
|
|
4374
|
+
|
|
4375
|
+
const sessionOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: 'session' })
|
|
4376
|
+
const globalOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
|
|
4377
|
+
const store = loadArchiveStore(sessionOpt)
|
|
4378
|
+
|
|
4379
|
+
const idSet = Array.isArray(ids) && ids.length > 0
|
|
4380
|
+
? new Set(ids.map(x => String(x || '').trim()).filter(Boolean))
|
|
4381
|
+
: null
|
|
4382
|
+
const folderClean = typeof folder === 'string' ? folder.trim() : ''
|
|
4383
|
+
let selected = idSet
|
|
4384
|
+
? store.items.filter(it => idSet.has(String(it.id)))
|
|
4385
|
+
: (folderClean ? store.items.filter(it => it.folder === folderClean) : store.items.slice())
|
|
4386
|
+
|
|
4387
|
+
if (!selected.length) {
|
|
4388
|
+
return { ok: false, error: '当前本会话档案柜暂无可供提炼的档案条目' }
|
|
4389
|
+
}
|
|
4390
|
+
|
|
4391
|
+
// Prioritize reusable engineering anchors/clips first
|
|
4392
|
+
const clipRank = { gold: 0, silver: 1, copper: 2 }
|
|
4393
|
+
selected = [...selected].sort((a, b) => (clipRank[a.paperclip] ?? 1) - (clipRank[b.paperclip] ?? 1))
|
|
4394
|
+
|
|
4395
|
+
const promptBody = selected.slice(0, 14).map((it, idx) => [
|
|
4396
|
+
`--- 本局档案 #${idx + 1}: 《${it.title}》 (folder=${it.folder}, clip=${it.paperclip}) ---`,
|
|
4397
|
+
`提要: ${it.summary || '无'}`,
|
|
4398
|
+
Array.isArray(it.points) && it.points.length > 0
|
|
4399
|
+
? '记忆点:\n' + it.points.map(p => `- ${p.title}: ${p.detail || p.cue}`).join('\n')
|
|
4400
|
+
: `正文:\n${cleanMultiline(it.body, 1400)}`,
|
|
4401
|
+
].join('\n')).join('\n\n')
|
|
4402
|
+
|
|
4403
|
+
let entriesRaw = null
|
|
4404
|
+
let usedLlm = false
|
|
4405
|
+
try {
|
|
4406
|
+
const llmRes = await callChiefLlm(deps, {
|
|
4407
|
+
sessionId: rootId,
|
|
4408
|
+
system: DISTILL_TO_GLOBAL_SYSTEM,
|
|
4409
|
+
prompt: [
|
|
4410
|
+
instruction ? `用户指定提炼侧重:${clamp(instruction, 240)}\n` : '',
|
|
4411
|
+
`待萃取本局工作档案(共 ${selected.length} 卷):`,
|
|
4412
|
+
cleanMultiline(promptBody, 6800),
|
|
4413
|
+
].filter(Boolean).join('\n'),
|
|
4414
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
4415
|
+
})
|
|
4416
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
4417
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
4418
|
+
if (parsed && Array.isArray(parsed.entries) && parsed.entries.length > 0) {
|
|
4419
|
+
entriesRaw = parsed.entries.slice(0, 4)
|
|
4420
|
+
usedLlm = true
|
|
4421
|
+
}
|
|
4422
|
+
}
|
|
4423
|
+
} catch {}
|
|
4424
|
+
|
|
4425
|
+
if (!entriesRaw) {
|
|
4426
|
+
// Deterministic fallback: distill gold/silver/reusable items grouped cleanly into global vault entries
|
|
4427
|
+
const reusable = selected.filter(it => it.paperclip !== 'copper')
|
|
4428
|
+
const pool = reusable.length ? reusable : selected
|
|
4429
|
+
const lead = pool[0]
|
|
4430
|
+
const mergedPoints = []
|
|
4431
|
+
const bodyBlocks = []
|
|
4432
|
+
const mergedTags = new Set(['全局萃取', ...(instruction ? ['专项提炼'] : [])])
|
|
4433
|
+
for (const it of pool.slice(0, 8)) {
|
|
4434
|
+
for (const tg of (it.tags || [])) mergedTags.add(tg)
|
|
4435
|
+
bodyBlocks.push(`### 《${it.title}》\n${cleanMultiline(it.summary || it.body, 480)}`)
|
|
4436
|
+
if (Array.isArray(it.points) && it.points.length > 0) {
|
|
4437
|
+
for (const pt of it.points.slice(0, 3)) mergedPoints.push(pt)
|
|
4438
|
+
} else {
|
|
4439
|
+
mergedPoints.push({
|
|
4440
|
+
title: clamp(it.title, 32),
|
|
4441
|
+
cue: clamp(it.summary || it.body, 56),
|
|
4442
|
+
detail: cleanMultiline(it.body || it.summary, 420),
|
|
4443
|
+
})
|
|
4444
|
+
}
|
|
4445
|
+
}
|
|
4446
|
+
const validFolders = new Set(['coords', 'incidents', 'contracts', 'ops', 'inbox'])
|
|
4447
|
+
entriesRaw = [{
|
|
4448
|
+
title: clamp(`【全局萃取】${lead.title}${pool.length > 1 ? ` 等 ${pool.length} 卷精选` : ''}`, 56),
|
|
4449
|
+
folder: validFolders.has(lead.folder) ? lead.folder : 'contracts',
|
|
4450
|
+
paperclip: lead.paperclip === 'gold' ? 'gold' : 'silver',
|
|
4451
|
+
summary: clamp(pool.map(x => x.summary || x.title).filter(Boolean).slice(0, 2).join(';'), 140),
|
|
4452
|
+
tags: [...mergedTags].slice(0, 6),
|
|
4453
|
+
points: mergedPoints.slice(0, 10),
|
|
4454
|
+
body: bodyBlocks.join('\n\n'),
|
|
4455
|
+
}]
|
|
4456
|
+
}
|
|
4457
|
+
|
|
4458
|
+
const savedEntries = []
|
|
4459
|
+
const validFolders = new Set(['coords', 'incidents', 'contracts', 'ops', 'inbox'])
|
|
4460
|
+
for (const raw of entriesRaw) {
|
|
4461
|
+
if (!raw || typeof raw !== 'object') continue
|
|
4462
|
+
const title = clamp(raw.title || '全局萃取卷宗', 64)
|
|
4463
|
+
const f = validFolders.has(raw.folder) ? raw.folder : 'contracts'
|
|
4464
|
+
const clip = raw.paperclip === 'gold' ? 'gold' : 'silver'
|
|
4465
|
+
const res = mutateArchive({
|
|
4466
|
+
op: 'save',
|
|
4467
|
+
vaultScope: 'global',
|
|
4468
|
+
folder: f,
|
|
4469
|
+
paperclip: clip,
|
|
4470
|
+
title,
|
|
4471
|
+
summary: clamp(raw.summary || '', 160),
|
|
4472
|
+
tags: Array.isArray(raw.tags) ? raw.tags.slice(0, 8) : ['全局萃取'],
|
|
4473
|
+
points: Array.isArray(raw.points) ? raw.points : [],
|
|
4474
|
+
body: cleanMultiline(raw.body || raw.summary || title, 4000),
|
|
4475
|
+
by: 'DSH 参谋长萃取',
|
|
4476
|
+
rootSessionId: rootId,
|
|
4477
|
+
}, globalOpt)
|
|
4478
|
+
if (res && res.ok && res.item) savedEntries.push(res.item)
|
|
4479
|
+
}
|
|
4480
|
+
|
|
4481
|
+
if (!savedEntries.length) {
|
|
4482
|
+
return { ok: false, error: '全局档案柜写入失败,已保留原有本局工作档案' }
|
|
4483
|
+
}
|
|
4484
|
+
|
|
4485
|
+
let clearedSource = false
|
|
4486
|
+
if (clearSource) {
|
|
4487
|
+
if (!idSet && folderClean) {
|
|
4488
|
+
mutateArchive({ op: 'clearFolder', folder: folderClean, vaultScope: 'session' }, sessionOpt)
|
|
4489
|
+
clearedSource = true
|
|
4490
|
+
} else {
|
|
4491
|
+
mutateArchive({ op: 'clearByIds', ids: selected.map(x => x.id), vaultScope: 'session' }, sessionOpt)
|
|
4492
|
+
clearedSource = true
|
|
4493
|
+
}
|
|
4494
|
+
}
|
|
4495
|
+
|
|
4496
|
+
const summaryReply = `- 【✦ 本局萃取入全局】已从本会话 ${selected.length} 卷工作档案中摘除临时噪音并提炼 **${savedEntries.length} 卷**可复用精华存入「🌐 全局档案柜」${clearedSource ? '(已按勾选清理本局原卷宗)' : '(本局原卷宗无损保留)'}:${savedEntries.map(e => `《${e.title}》`).join('、')}。`
|
|
4497
|
+
mutateChiefState((s) => {
|
|
4498
|
+
const ws = ensureWorkspace(s, rootId)
|
|
4499
|
+
ws.chat.push({
|
|
4500
|
+
id: nextId('chat'),
|
|
4501
|
+
role: 'chief',
|
|
4502
|
+
text: summaryReply,
|
|
4503
|
+
actions: [`萃取入全局 ×${savedEntries.length}`],
|
|
4504
|
+
at: Date.now(),
|
|
4505
|
+
})
|
|
4506
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
4507
|
+
})
|
|
4508
|
+
if (deps && typeof deps.appendBoardLog === 'function') {
|
|
4509
|
+
deps.appendBoardLog(rootId, `✦ 参谋长已从本局 ${selected.length} 卷档案摘出可复用精华,保存 ${savedEntries.length} 卷入全局档案柜`, 'chief')
|
|
4510
|
+
}
|
|
4511
|
+
|
|
4512
|
+
const stNow = loadChiefState()
|
|
4513
|
+
const wsNow = stNow.workspaces ? stNow.workspaces[rootId] : null
|
|
4514
|
+
const flippedIds = wsNow && Array.isArray(wsNow.flippedPrecipitatedIds) ? wsNow.flippedPrecipitatedIds : []
|
|
4515
|
+
return {
|
|
4516
|
+
ok: true,
|
|
4517
|
+
usedLlm,
|
|
4518
|
+
createdCount: savedEntries.length,
|
|
4519
|
+
entries: savedEntries,
|
|
4520
|
+
clearedSource,
|
|
4521
|
+
reply: summaryReply,
|
|
4522
|
+
archives: listArchiveHeaders(rootId, { vaultScope: 'session', includePrecipitated: true, flippedIds }, sessionOpt),
|
|
4523
|
+
globalArchives: listArchiveHeaders(rootId, { vaultScope: 'global', includePrecipitated: true, flippedIds }, globalOpt),
|
|
4524
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
4525
|
+
}
|
|
4526
|
+
}
|
|
4527
|
+
|
|
3191
4528
|
export async function askOrCommandChief(deps, {
|
|
3192
4529
|
sessionId = '',
|
|
3193
4530
|
text = '',
|
|
@@ -3223,9 +4560,15 @@ export async function askOrCommandChief(deps, {
|
|
|
3223
4560
|
const directory = await listPeerDirectory(deps, rootId)
|
|
3224
4561
|
const board = deps.boardForSession(deps.boardFileFor(rootId))
|
|
3225
4562
|
const state = loadChiefState()
|
|
4563
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
4564
|
+
const permissionMode = normalizePermissionMode(effCfg.permissionMode || DEFAULT_CHIEF_PERMISSION_MODE)
|
|
4565
|
+
const isConciseBrief = Boolean(effCfg.tacticalModes && effCfg.tacticalModes.conciseBrief)
|
|
3226
4566
|
const view = clusterView(state, rootId)
|
|
3227
4567
|
const ownWs = ensureWorkspace(state, rootId)
|
|
3228
4568
|
const targetOpt = archiveTargetForRoot(deps, rootId)
|
|
4569
|
+
const peerProgress = Array.isArray(directory.cluster) && directory.cluster.length > 1
|
|
4570
|
+
? collectClusterPeerProgress(deps, directory.cluster, rootId)
|
|
4571
|
+
: []
|
|
3229
4572
|
|
|
3230
4573
|
// Fast path: if user explicitly picked a concrete target pill AND used direct relay mode without asking chief to decompose
|
|
3231
4574
|
if (forcedTarget && forcedTarget !== 'auto') {
|
|
@@ -3265,8 +4608,10 @@ export async function askOrCommandChief(deps, {
|
|
|
3265
4608
|
// Direct natural-language command to organize/curate the Engineering Archive Cabinet (`整理档案` / `收纳档案`)
|
|
3266
4609
|
if (!forcedTarget || forcedTarget === 'auto') {
|
|
3267
4610
|
if (/(?:档案|卷宗|老笔记)/.test(input) && /(?:整理|收纳|归类|分拣|拆解)/.test(input)) {
|
|
4611
|
+
const orgScope = /全局/.test(input) ? 'global' : 'session'
|
|
3268
4612
|
const orgRes = await organizeArchivesWithChief(deps, {
|
|
3269
4613
|
sessionId: rootId,
|
|
4614
|
+
vaultScope: orgScope,
|
|
3270
4615
|
scope: /全部|所有|全柜/.test(input) ? 'all' : 'unorganized',
|
|
3271
4616
|
instruction: input,
|
|
3272
4617
|
})
|
|
@@ -3305,18 +4650,42 @@ export async function askOrCommandChief(deps, {
|
|
|
3305
4650
|
}
|
|
3306
4651
|
}
|
|
3307
4652
|
|
|
3308
|
-
//
|
|
3309
|
-
const
|
|
4653
|
+
// Watch all 3 archive vaults in background (sealed items NEVER leak to Lead unless placed onto desk!)
|
|
4654
|
+
const visibleArchives = collectChiefVisibleArchives(deps, rootId, state)
|
|
4655
|
+
const watchLines = []
|
|
4656
|
+
const fmtWatchTag = (label, it) => `[${label}${it.id ? ` | id=${it.id}` : ''}] 《${clamp(it.title, 36)}》:${clamp(it.summary, 80)}`
|
|
4657
|
+
const watchEntries = [
|
|
4658
|
+
...visibleArchives.deskSessionItems.map(it => fmtWatchTag('桌面·本局(主可见)', it)),
|
|
4659
|
+
...visibleArchives.deskGlobalItems.map(it => fmtWatchTag('桌面·全局(主可见)', it)),
|
|
4660
|
+
...visibleArchives.deskFlippedItems.map(it => fmtWatchTag('桌面·沉淀(主可见)', it)),
|
|
4661
|
+
...visibleArchives.mountedGlobalItems.map(it => fmtWatchTag('全局参阅·主隐', it)),
|
|
4662
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.sessionSealed) || []).map(it => fmtWatchTag('本局封存·主隐', it)),
|
|
4663
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.globalSealed) || []).map(it => fmtWatchTag('全局封存·主隐', it)),
|
|
4664
|
+
...((visibleArchives.sealedWatch && visibleArchives.sealedWatch.precipSealed) || []).map(it => fmtWatchTag('沉淀封存·主隐', it)),
|
|
4665
|
+
]
|
|
4666
|
+
if (watchEntries.length > 0) {
|
|
4667
|
+
watchLines.push('', '## 9. 参谋长三库档案全览(封存项仅参谋长关注、未注入主对话;上桌面备选项主对话亦重点看到;支持许愿框 archiveOps)', ...watchEntries.map(x => '- ' + x))
|
|
4668
|
+
}
|
|
4669
|
+
|
|
4670
|
+
// On-demand lazy archive lookup ONLY when the user explicitly asks Chief about archives (Chief searches Session + System Global Cold Vault on demand)
|
|
4671
|
+
const asksArchiveExplicitly = /(?:档案|卷宗|归档|以前|历史记录|工程坐标|老笔记|全局|沉淀|查一下.*(?:怎么|路径|命令|配置))/.test(input)
|
|
3310
4672
|
const onDemandArchiveLines = []
|
|
3311
4673
|
if (asksArchiveExplicitly) {
|
|
3312
|
-
const
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
|
|
3316
|
-
|
|
3317
|
-
|
|
3318
|
-
|
|
3319
|
-
|
|
4674
|
+
const sessionTarget = rootId && rootId !== 'global' ? archiveTargetForRoot(deps, rootId, { vaultScope: 'session' }) : null
|
|
4675
|
+
const globalTarget = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
|
|
4676
|
+
const foundSess = sessionTarget ? searchArchives(input, { limit: 3, vaultScope: 'session' }, sessionTarget) : { ok: true, hits: [] }
|
|
4677
|
+
const foundGlob = searchGlobalVaultForChief(input, { limit: 3 }, globalTarget)
|
|
4678
|
+
const combinedHits = [
|
|
4679
|
+
...(Array.isArray(foundSess.hits) ? foundSess.hits.map(h => ({ ...h, _scopeLabel: '本会话档案', _target: sessionTarget })) : []),
|
|
4680
|
+
...(Array.isArray(foundGlob.hits) ? foundGlob.hits.map(h => ({ ...h, _scopeLabel: '系统全局档案', _target: globalTarget })) : []),
|
|
4681
|
+
]
|
|
4682
|
+
if (combinedHits.length > 0) {
|
|
4683
|
+
onDemandArchiveLines.push('', '## 7. 按需调取的档案柜卷宗(含本会话档案柜与参谋长专属全局档案柜,仅参谋长侧检索)')
|
|
4684
|
+
for (let i = 0; i < combinedHits.length; i += 1) {
|
|
4685
|
+
const hit = combinedHits[i]
|
|
4686
|
+
onDemandArchiveLines.push(`- 📎 [${hit._scopeLabel}/${hit.folderLabel}] 《${hit.title}》:${hit.summary}`)
|
|
4687
|
+
if (i < 3) {
|
|
4688
|
+
const det = getArchiveDetail(hit.id, rootId, hit._target)
|
|
3320
4689
|
if (det.ok && det.item && Array.isArray(det.item.points)) {
|
|
3321
4690
|
for (const pt of det.item.points.slice(0, 4)) {
|
|
3322
4691
|
onDemandArchiveLines.push(` * ${pt.title}:${clamp(pt.detail || pt.cue, 180)}`)
|
|
@@ -3356,6 +4725,13 @@ export async function askOrCommandChief(deps, {
|
|
|
3356
4725
|
? meaningfulPeers.slice(0, 16).map(t => `- key="${t.key}" | 名称="${t.handle}" | 类型=${t.kind} | 状态=${t.status}${t.taskTitle ? ' | 当前负责: ' + t.taskTitle : ''}`)
|
|
3357
4726
|
: ['- key="lead" | 名称="主对话" | 类型=lead']),
|
|
3358
4727
|
...(hiddenIdleProbes > 0 ? [`(另有 ${hiddenIdleProbes} 个已空闲后台检查点探针已折叠)`] : []),
|
|
4728
|
+
...((directory.otherSessions && directory.otherSessions.length > 0)
|
|
4729
|
+
? [
|
|
4730
|
+
'',
|
|
4731
|
+
'## 1.5 本机其他独立会话窗口(可用许愿框 networkOps 连接 link / 断开 unlink)',
|
|
4732
|
+
...directory.otherSessions.slice(0, 12).map(s => `- sessionId="${s.id}" | 名称="${s.name}" | 状态=${s.status} | 已互联=${s.linked ? '是' : '否'}${s.objective ? ' | 目标=' + clamp(s.objective, 50) : ''}`),
|
|
4733
|
+
]
|
|
4734
|
+
: []),
|
|
3359
4735
|
'',
|
|
3360
4736
|
'## 2. 主对话与子代理【实时对话流现场快照】(Live Transcripts)',
|
|
3361
4737
|
...(liveDigest.summaryLines.length
|
|
@@ -3373,7 +4749,7 @@ export async function askOrCommandChief(deps, {
|
|
|
3373
4749
|
'',
|
|
3374
4750
|
'## 4. 当前生效边界(📌全局定住 vs 本任务)',
|
|
3375
4751
|
`- 禁止红线 (forbidden): ${fmtBoundCol('forbidden')}`,
|
|
3376
|
-
`-
|
|
4752
|
+
`- 必做事项 (allowed): ${fmtBoundCol('allowed')}`,
|
|
3377
4753
|
`- 注意事项 (notes): ${fmtBoundCol('notes')}`,
|
|
3378
4754
|
'',
|
|
3379
4755
|
'## 5. 编号持久记忆条目 (Facts)',
|
|
@@ -3386,10 +4762,20 @@ export async function askOrCommandChief(deps, {
|
|
|
3386
4762
|
.filter(m => m && !isInternalCheckpointNoise(m.title || m.text))
|
|
3387
4763
|
.slice(-6)
|
|
3388
4764
|
.map(m => `- [回合/${m.section}] ${clamp(stripCheckpointNoise(m.title || m.text), 150)}`)),
|
|
4765
|
+
...(peerProgress.length > 0
|
|
4766
|
+
? [
|
|
4767
|
+
'',
|
|
4768
|
+
'## 6.5 当前互通协同网络邻居实时进度(已共享进度)',
|
|
4769
|
+
...peerProgress.map(p => `- 🌐 [${p.title}] ${p.objective ? `目标="${p.objective}" | ` : ''}${p.progressSummary || '暂无板卡进度'}${p.cursorStep ? ` | 当前="${p.cursorStep}"` : ''}`),
|
|
4770
|
+
]
|
|
4771
|
+
: []),
|
|
3389
4772
|
...(view.mailbox.slice(-4).map(m => `- [信箱 ${m.from} → @${m.to}] ${clamp(m.text, 120)}`)),
|
|
3390
4773
|
...onDemandArchiveLines,
|
|
3391
4774
|
...flippedVaultLines,
|
|
4775
|
+
...watchLines,
|
|
3392
4776
|
'',
|
|
4777
|
+
`## 参谋长执行权限与显示模式:permissionMode=${permissionMode}${isConciseBrief ? ' | 极简战报=开启' : ''}`,
|
|
4778
|
+
describeThreePartyBoundariesForPrompt(permissionMode),
|
|
3393
4779
|
'## 用户刚刚对你说的话:',
|
|
3394
4780
|
input,
|
|
3395
4781
|
...(savedImagePaths.length > 0
|
|
@@ -3402,15 +4788,99 @@ export async function askOrCommandChief(deps, {
|
|
|
3402
4788
|
: []),
|
|
3403
4789
|
]
|
|
3404
4790
|
|
|
3405
|
-
const
|
|
4791
|
+
const isBlankContext = liveDigest.summaryLines.length === 0 && !board.objective && !(board.plan || []).length
|
|
4792
|
+
const resolvedCwd = deps && typeof deps.getSessionCwd === 'function' ? deps.getSessionCwd(rootId) : ''
|
|
4793
|
+
const explicitCompactReq = !imageBlocks.length && isExplicitCompactCommand(input)
|
|
4794
|
+
const statusOnlyInquiry = !imageBlocks.length && !explicitCompactReq && isPureStatusInquiry(input)
|
|
4795
|
+
|
|
4796
|
+
const effectiveSystem = [
|
|
4797
|
+
ASK_CHIEF_SYSTEM,
|
|
4798
|
+
...(isConciseBrief ? [CONCISE_BRIEF_ASK_EXTRA] : []),
|
|
4799
|
+
...(isBlankContext
|
|
4800
|
+
? [
|
|
4801
|
+
'',
|
|
4802
|
+
'🌱 【当前处于空白新上下文(主对话尚未开聊)】:',
|
|
4803
|
+
resolvedCwd ? `- 当前已解析工作区根目录:${resolvedCwd}` : '',
|
|
4804
|
+
'- 若用户让你查找/分析/修改当前工作区项目文件,请依据当前 permissionMode 直接调用你的真实 JSON `toolCalls` 工具(如 `list_dir` / `search_files` / `read_file` / `edit_file` / `run_command`)处理并如实汇报;绝对禁止直接向用户输出 `<|DSML|calls>` 等原始工具调用标签!',
|
|
4805
|
+
'- 若尚无主对话历史,除非用户明确命令且会话已存在,不要无故调用 `session_compact`;若用户明确想把任务留给主对话开场接手,可放进 `relays`(`target: "lead"`)由系统自动暂存待领交接包。',
|
|
4806
|
+
].filter(Boolean)
|
|
4807
|
+
: []),
|
|
4808
|
+
...(statusOnlyInquiry
|
|
4809
|
+
? [
|
|
4810
|
+
'',
|
|
4811
|
+
'⚡ 【当前问题属于「主对话/团队实时态势询问」快速通道】:',
|
|
4812
|
+
'- 严禁调用任何工具,严禁输出任何 XML/DSML 工具标签(如 `<|DSML|calls>`),严禁扫盘或运行 Shell!',
|
|
4813
|
+
'- 请直接根据上下文里已经给出的「实时对话流快照」「小任务板 (Plan)」「任务图」「断点游标」与「协同邻居进度」,输出唯一合法 JSON(仅填 `"reply"`,`"toolCalls": []`)。',
|
|
4814
|
+
]
|
|
4815
|
+
: []),
|
|
4816
|
+
'',
|
|
4817
|
+
CHIEF_TOOLS_PROMPT_GUIDE,
|
|
4818
|
+
].join('\n')
|
|
4819
|
+
|
|
4820
|
+
const upsertArchiveFn = async (arc) => {
|
|
4821
|
+
const sc = arc && arc.vaultScope === 'global' ? 'global' : 'session'
|
|
4822
|
+
const opt = archiveTargetForRoot(deps, rootId, { vaultScope: sc })
|
|
4823
|
+
return mutateArchive({
|
|
4824
|
+
op: 'save',
|
|
4825
|
+
session: rootId,
|
|
4826
|
+
folder: (arc && arc.folder) || 'inbox',
|
|
4827
|
+
paperclip: 'silver',
|
|
4828
|
+
title: (arc && arc.title) || '参谋长工作归档',
|
|
4829
|
+
summary: (arc && arc.summary) || '',
|
|
4830
|
+
body: (arc && arc.body) || '',
|
|
4831
|
+
tags: Array.isArray(arc && arc.tags) ? arc.tags : [],
|
|
4832
|
+
by: 'chief',
|
|
4833
|
+
}, opt)
|
|
4834
|
+
}
|
|
4835
|
+
|
|
4836
|
+
const compactNowFn = async (reason) => {
|
|
4837
|
+
if (!rootId || rootId === 'global') {
|
|
4838
|
+
return { ok: false, noop: true, skipped: 'blank-context', error: '当前为空白新对话(未绑定活跃主会话),暂无可压缩的历史上下文' }
|
|
4839
|
+
}
|
|
4840
|
+
if (!deps || typeof deps.compactSessionNow !== 'function') {
|
|
4841
|
+
return { ok: false, skipped: 'no-compaction-service', error: '宿主压缩服务未挂载' }
|
|
4842
|
+
}
|
|
4843
|
+
let usage = null
|
|
4844
|
+
try {
|
|
4845
|
+
usage = typeof deps.measureSessionTokens === 'function'
|
|
4846
|
+
? await deps.measureSessionTokens(rootId)
|
|
4847
|
+
: null
|
|
4848
|
+
} catch {}
|
|
4849
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
4850
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
4851
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
4852
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
4853
|
+
return executeHarvestAndCompact(deps, {
|
|
4854
|
+
sid: rootId,
|
|
4855
|
+
rootId,
|
|
4856
|
+
reason: reason || '参谋长实权工具主动发起抢救与上下文压缩',
|
|
4857
|
+
seq,
|
|
4858
|
+
ratioPct,
|
|
4859
|
+
totalTokens,
|
|
4860
|
+
contextWindow,
|
|
4861
|
+
logLabel: '参谋长主动压缩',
|
|
4862
|
+
})
|
|
4863
|
+
}
|
|
4864
|
+
|
|
4865
|
+
const loopRes = await runChiefAgenticLoop(deps, {
|
|
4866
|
+
rootId,
|
|
3406
4867
|
sessionId: rootId,
|
|
3407
|
-
system:
|
|
3408
|
-
|
|
3409
|
-
maxTokens: SUMMARY_MAX_TOKENS,
|
|
4868
|
+
system: effectiveSystem,
|
|
4869
|
+
initialPrompt: promptLines.join('\n'),
|
|
3410
4870
|
imageBlocks,
|
|
3411
4871
|
allowTextFallbackOnVisionMiss: savedImagePaths.length > 0,
|
|
4872
|
+
permissionMode,
|
|
4873
|
+
board,
|
|
4874
|
+
maxSteps: statusOnlyInquiry ? 1 : 4,
|
|
4875
|
+
readOnlyToolsOnly: false,
|
|
4876
|
+
disableTools: statusOnlyInquiry,
|
|
4877
|
+
callLlmFn: (callOpts) => callChiefLlm(deps, { ...callOpts, maxTokens: SUMMARY_MAX_TOKENS }),
|
|
4878
|
+
extractJsonFn: extractJsonObject,
|
|
4879
|
+
upsertArchiveFn,
|
|
4880
|
+
compactNowFn,
|
|
3412
4881
|
})
|
|
3413
4882
|
|
|
4883
|
+
const llmRes = (loopRes && loopRes.llmRes) || { ok: false, error: 'agentic loop no response' }
|
|
3414
4884
|
if (imageBlocks.length > 0 && !llmRes.ok && !savedImagePaths.length) {
|
|
3415
4885
|
return {
|
|
3416
4886
|
ok: false,
|
|
@@ -3418,7 +4888,22 @@ export async function askOrCommandChief(deps, {
|
|
|
3418
4888
|
}
|
|
3419
4889
|
}
|
|
3420
4890
|
|
|
3421
|
-
let parsed = llmRes.ok ? extractJsonObject(llmRes.text) : null
|
|
4891
|
+
let parsed = (loopRes && loopRes.parsed) || (llmRes.ok ? extractJsonObject(llmRes.text) : null)
|
|
4892
|
+
const loopBadges = Array.isArray(loopRes && loopRes.toolBadges) ? [...loopRes.toolBadges] : []
|
|
4893
|
+
const loopToolRecords = Array.isArray(loopRes && loopRes.toolRecords) ? loopRes.toolRecords : []
|
|
4894
|
+
const compactToolRec = loopToolRecords.find(r => r && r.tool === 'session_compact') || null
|
|
4895
|
+
let forcedCompactOut = null
|
|
4896
|
+
if (explicitCompactReq && !compactToolRec) {
|
|
4897
|
+
forcedCompactOut = await compactNowFn(`用户指令触发:${input}`).catch(err => ({
|
|
4898
|
+
ok: false,
|
|
4899
|
+
error: (err && err.message) || String(err || '压缩执行失败'),
|
|
4900
|
+
}))
|
|
4901
|
+
if (forcedCompactOut && forcedCompactOut.ok) {
|
|
4902
|
+
loopBadges.push(forcedCompactOut.noop ? '🗄️ 已归档(免压)' : '🗜 完成抢救压缩')
|
|
4903
|
+
} else {
|
|
4904
|
+
loopBadges.push('⚠️ 压缩未完成')
|
|
4905
|
+
}
|
|
4906
|
+
}
|
|
3422
4907
|
|
|
3423
4908
|
// Graceful intelligent fallback if LLM is offline / unconfigured / returned non-JSON
|
|
3424
4909
|
if (!parsed) {
|
|
@@ -3460,7 +4945,7 @@ export async function askOrCommandChief(deps, {
|
|
|
3460
4945
|
|
|
3461
4946
|
// 2) Natural-language request to consolidate scattered boundaries into one
|
|
3462
4947
|
if (!imageBlocks.length && /边界|红线/.test(input) && /总结成一条|合并成一条|浓缩|合一|整合/.test(input)) {
|
|
3463
|
-
const targetCol =
|
|
4948
|
+
const targetCol = /允许|必做/.test(input) ? 'allowed' : /注意/.test(input) ? 'notes' : ''
|
|
3464
4949
|
const consRes = await consolidateBoundsWithChief(deps, {
|
|
3465
4950
|
sessionId: rootId,
|
|
3466
4951
|
field: targetCol,
|
|
@@ -3487,27 +4972,147 @@ export async function askOrCommandChief(deps, {
|
|
|
3487
4972
|
}
|
|
3488
4973
|
}
|
|
3489
4974
|
|
|
3490
|
-
//
|
|
3491
|
-
|
|
3492
|
-
|
|
4975
|
+
// 2.5) Wishing Box offline shortcuts: distill to global / reset tasks / unlink peer sessions
|
|
4976
|
+
if (!imageBlocks.length && /(?:提炼|摘取|抽取|总结)/.test(input) && /全局/.test(input)) {
|
|
4977
|
+
const distRes = await distillSessionArchivesToGlobal(deps, {
|
|
4978
|
+
sessionId: rootId,
|
|
4979
|
+
instruction: input,
|
|
4980
|
+
})
|
|
4981
|
+
if (distRes.ok) {
|
|
4982
|
+
mutateChiefState((s) => {
|
|
4983
|
+
const ws = ensureWorkspace(s, rootId)
|
|
4984
|
+
ws.chat.push(
|
|
4985
|
+
{ id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
|
|
4986
|
+
{ id: nextId('chat'), role: 'chief', text: distRes.reply, actions: [`提炼入全局 ×${distRes.createdCount || 0}`], at: Date.now() },
|
|
4987
|
+
)
|
|
4988
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
4989
|
+
})
|
|
4990
|
+
return {
|
|
4991
|
+
ok: true,
|
|
4992
|
+
reply: distRes.reply,
|
|
4993
|
+
relays: [],
|
|
4994
|
+
memoryChanges: [],
|
|
4995
|
+
boardOps: [],
|
|
4996
|
+
archiveOps: [`提炼入全局 ×${distRes.createdCount || 0}`],
|
|
4997
|
+
archives: distRes.archives,
|
|
4998
|
+
view: distRes.view,
|
|
4999
|
+
}
|
|
5000
|
+
}
|
|
5001
|
+
}
|
|
5002
|
+
|
|
5003
|
+
if (!imageBlocks.length && /(?:清空|重设|重置)/.test(input) && /(?:任务|看板)/.test(input)) {
|
|
5004
|
+
const resetRes = deps.runAction
|
|
5005
|
+
? deps.runAction({ action: 'task.reset', status: 'all', resetPlan: /计划|全部/.test(input), session: rootId, by: 'chief' })
|
|
5006
|
+
: { ok: false }
|
|
5007
|
+
if (resetRes && resetRes.ok) {
|
|
5008
|
+
const msg = '- 【已重设任务看板】已按你的要求清空重设本会话任务列表。'
|
|
5009
|
+
mutateChiefState((s) => {
|
|
5010
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5011
|
+
ws.chat.push(
|
|
5012
|
+
{ id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
|
|
5013
|
+
{ id: nextId('chat'), role: 'chief', text: msg, actions: ['重设任务看板'], at: Date.now() },
|
|
5014
|
+
)
|
|
5015
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
5016
|
+
})
|
|
5017
|
+
return {
|
|
5018
|
+
ok: true,
|
|
5019
|
+
reply: msg,
|
|
5020
|
+
relays: [],
|
|
5021
|
+
memoryChanges: [],
|
|
5022
|
+
boardOps: ['重设任务看板'],
|
|
5023
|
+
board: resetRes.board,
|
|
5024
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
5025
|
+
}
|
|
5026
|
+
}
|
|
5027
|
+
}
|
|
5028
|
+
|
|
5029
|
+
if (!imageBlocks.length && /(?:断开|取消|解除)/.test(input) && /(?:协同|网络|连接|关联)/.test(input)) {
|
|
5030
|
+
const linkedPeers = ((directory && directory.otherSessions) || []).filter(p => p.linked)
|
|
5031
|
+
const qLower = input.toLowerCase()
|
|
5032
|
+
const targetsToUnlink = /全部|所有/.test(input)
|
|
5033
|
+
? linkedPeers
|
|
5034
|
+
: linkedPeers.filter(p => qLower.includes(String(p.id).toLowerCase()) || (p.name && qLower.includes(String(p.name).toLowerCase())))
|
|
5035
|
+
const chosen = targetsToUnlink.length > 0 ? targetsToUnlink : (linkedPeers.length === 1 ? linkedPeers : [])
|
|
5036
|
+
if (chosen.length > 0) {
|
|
5037
|
+
const badges = []
|
|
5038
|
+
for (const p of chosen) {
|
|
5039
|
+
const r = setPeerLink(rootId, p.id, false)
|
|
5040
|
+
if (r && r.ok) badges.push(`断开协同:${p.name}`)
|
|
5041
|
+
}
|
|
5042
|
+
if (badges.length > 0) {
|
|
5043
|
+
const msg = `- 【已断开协同网络】${badges.join(';')}`
|
|
5044
|
+
mutateChiefState((s) => {
|
|
5045
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5046
|
+
ws.chat.push(
|
|
5047
|
+
{ id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
|
|
5048
|
+
{ id: nextId('chat'), role: 'chief', text: msg, actions: badges, at: Date.now() },
|
|
5049
|
+
)
|
|
5050
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
5051
|
+
})
|
|
5052
|
+
return {
|
|
5053
|
+
ok: true,
|
|
5054
|
+
reply: msg,
|
|
5055
|
+
relays: [],
|
|
5056
|
+
memoryChanges: [],
|
|
5057
|
+
boardOps: [],
|
|
5058
|
+
networkOps: badges,
|
|
5059
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
5060
|
+
}
|
|
5061
|
+
}
|
|
5062
|
+
}
|
|
5063
|
+
}
|
|
5064
|
+
|
|
5065
|
+
// 2.5) Deterministic reply when user explicitly requested compaction and LLM failed to emit JSON
|
|
5066
|
+
if (forcedCompactOut) {
|
|
5067
|
+
const compactMsg = forcedCompactOut.ok
|
|
5068
|
+
? (forcedCompactOut.noop
|
|
5069
|
+
? `- 【已归档(免压)】已抢救当前现场记录入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''};当前主对话历史暂无需压缩。`
|
|
5070
|
+
: `- 【已完成抢救与上下文压缩】已将关键细节抢救入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},并完成主对话上下文静默压缩。`)
|
|
5071
|
+
: `- 【压缩未完成】${forcedCompactOut.error || '当前暂无可压缩历史或宿主压缩服务暂未就绪。'}`
|
|
5072
|
+
mutateChiefState((s) => {
|
|
5073
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5074
|
+
ws.chat.push(
|
|
5075
|
+
{ id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
|
|
5076
|
+
{ id: nextId('chat'), role: 'chief', text: compactMsg, actions: loopBadges, at: Date.now() },
|
|
5077
|
+
)
|
|
5078
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
5079
|
+
})
|
|
5080
|
+
return {
|
|
5081
|
+
ok: true,
|
|
5082
|
+
reply: compactMsg,
|
|
5083
|
+
relays: [],
|
|
5084
|
+
memoryChanges: [],
|
|
5085
|
+
boardOps: [],
|
|
5086
|
+
actionBadges: loopBadges,
|
|
5087
|
+
toolRecords: loopToolRecords,
|
|
5088
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
5089
|
+
}
|
|
5090
|
+
}
|
|
5091
|
+
|
|
5092
|
+
// 3) If LLM actually returned readable prose (just not wrapped in JSON), strip tool markup first; if empty or JSON fragment, synthesize smart live briefing
|
|
5093
|
+
const strippedPlain = llmRes.ok && llmRes.text ? stripToolCallMarkup(llmRes.text).trim() : ''
|
|
5094
|
+
const usablePlainLlm = strippedPlain && !strippedPlain.startsWith('{') && strippedPlain.length >= 6
|
|
5095
|
+
? cleanMultiline(strippedPlain, 900)
|
|
3493
5096
|
: ''
|
|
3494
5097
|
const archiveFallback = onDemandArchiveLines.length > 1
|
|
3495
5098
|
? ['- 【已从沉淀档案柜按需检索到以下卷宗】', ...onDemandArchiveLines.slice(2)].join('\n')
|
|
3496
5099
|
: ''
|
|
3497
|
-
const
|
|
5100
|
+
const rawFallbackReply = usablePlainLlm || archiveFallback || buildSmartFallbackReply({
|
|
3498
5101
|
input,
|
|
3499
5102
|
board,
|
|
3500
5103
|
liveDigest,
|
|
3501
5104
|
directory,
|
|
3502
5105
|
facts: numberedFacts,
|
|
3503
5106
|
mailbox: view.mailbox,
|
|
5107
|
+
conciseBrief: isConciseBrief,
|
|
3504
5108
|
})
|
|
5109
|
+
const replyText = isConciseBrief ? sanitizeConciseBriefText(rawFallbackReply) : rawFallbackReply
|
|
3505
5110
|
|
|
3506
5111
|
mutateChiefState((s) => {
|
|
3507
5112
|
const ws = ensureWorkspace(s, rootId)
|
|
3508
5113
|
ws.chat.push(
|
|
3509
5114
|
{ id: nextId('chat'), role: 'user', text: userDisplayText, ...imgMeta, actions: [], at: Date.now() },
|
|
3510
|
-
{ id: nextId('chat'), role: 'chief', text: replyText, actions:
|
|
5115
|
+
{ id: nextId('chat'), role: 'chief', text: replyText, actions: loopBadges, at: Date.now() },
|
|
3511
5116
|
)
|
|
3512
5117
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
3513
5118
|
})
|
|
@@ -3517,52 +5122,98 @@ export async function askOrCommandChief(deps, {
|
|
|
3517
5122
|
relays: [],
|
|
3518
5123
|
memoryChanges: [],
|
|
3519
5124
|
boardOps: [],
|
|
5125
|
+
actionBadges: loopBadges,
|
|
5126
|
+
toolRecords: loopToolRecords,
|
|
3520
5127
|
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
3521
5128
|
}
|
|
3522
5129
|
}
|
|
3523
5130
|
|
|
3524
|
-
// Execute decomposed relays
|
|
5131
|
+
// Execute decomposed relays (with blank-context staging into pending-transfer when Lead is not yet alive)
|
|
3525
5132
|
const relayResults = []
|
|
3526
|
-
const actionBadges = []
|
|
5133
|
+
const actionBadges = [...loopBadges]
|
|
3527
5134
|
for (const r of (Array.isArray(parsed.relays) ? parsed.relays : []).slice(0, 8)) {
|
|
3528
5135
|
if (!r || !r.text) continue
|
|
5136
|
+
const targetName = r.target || 'lead'
|
|
3529
5137
|
const deliv = await deliverCrossMessage(deps, {
|
|
3530
5138
|
fromSession: rootId,
|
|
3531
5139
|
fromLabel: 'DSH 参谋长 (代用户传达)',
|
|
3532
|
-
target:
|
|
5140
|
+
target: targetName,
|
|
3533
5141
|
subject: r.subject || '',
|
|
3534
5142
|
text: r.text,
|
|
3535
5143
|
mode: ['steer', 'followup', 'silent'].includes(r.mode) ? r.mode : 'steer',
|
|
3536
5144
|
imageBlocks,
|
|
3537
5145
|
savedImagePaths,
|
|
3538
5146
|
})
|
|
5147
|
+
const isLeadTarget = /^(?:lead|main|主对话)$/i.test(String(targetName).trim())
|
|
5148
|
+
if (isLeadTarget && (!deliv.ok || (isBlankContext && !deliv.deliveredPhysical)) && typeof deps.stagePendingTransfer === 'function') {
|
|
5149
|
+
const staged = deps.stagePendingTransfer(
|
|
5150
|
+
`[DSH 参谋长预派发指令${r.subject ? ' · ' + r.subject : ''}]\n${r.text}`,
|
|
5151
|
+
rootId,
|
|
5152
|
+
{ by: 'chief', subject: r.subject || '' },
|
|
5153
|
+
)
|
|
5154
|
+
if (staged) {
|
|
5155
|
+
relayResults.push({ ...deliv, ok: true, target: '主对话(待领)', mode: 'pending-transfer', stagedPending: true })
|
|
5156
|
+
actionBadges.push('暂存待领 → 主对话')
|
|
5157
|
+
continue
|
|
5158
|
+
}
|
|
5159
|
+
}
|
|
3539
5160
|
relayResults.push(deliv)
|
|
3540
5161
|
if (deliv.ok) actionBadges.push(`${r.mode === 'steer' ? '插话' : '递话'} → ${deliv.target}`)
|
|
3541
5162
|
}
|
|
3542
5163
|
|
|
3543
|
-
// Execute board ops
|
|
5164
|
+
// Execute board ops, wishing-box archive ops & network ops
|
|
3544
5165
|
const executedBoardOps = applyBoardOps(deps, rootId, parsed.boardOps)
|
|
3545
5166
|
for (const b of executedBoardOps) actionBadges.push(b)
|
|
3546
5167
|
|
|
5168
|
+
const archiveExec = await applyArchiveOps(deps, rootId, parsed.archiveOps, { input })
|
|
5169
|
+
const executedArchiveOps = archiveExec.executed || []
|
|
5170
|
+
for (const a of executedArchiveOps) actionBadges.push(a)
|
|
5171
|
+
|
|
5172
|
+
const executedNetworkOps = applyNetworkOps(rootId, parsed.networkOps, directory)
|
|
5173
|
+
for (const n of executedNetworkOps) actionBadges.push(n)
|
|
5174
|
+
|
|
3547
5175
|
// Execute durable memory changes & Prime Minister bound proposals (including N-in-1 consolidation)
|
|
3548
5176
|
let appliedFacts = []
|
|
3549
5177
|
const proposedBounds = []
|
|
3550
5178
|
const existingBounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
3551
5179
|
const rawBoundProposals = Array.isArray(parsed.boundProposals) ? parsed.boundProposals.slice(0, 4) : []
|
|
3552
|
-
const
|
|
3553
|
-
|
|
3554
|
-
|
|
5180
|
+
const cleanedParsedReply = stripToolCallMarkup(parsed.reply || '').trim()
|
|
5181
|
+
const compactOutcomeNote = forcedCompactOut
|
|
5182
|
+
? (forcedCompactOut.ok
|
|
5183
|
+
? (forcedCompactOut.noop
|
|
5184
|
+
? `【已归档(免压)】已将本轮现场记录存入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},宿主历史暂无需进一步压缩。`
|
|
5185
|
+
: `【已完成抢救与上下文压缩】已将关键细节存入本会话档案柜${forcedCompactOut.harvestId ? `(#${forcedCompactOut.harvestId})` : ''},并完成主对话静默压缩。`)
|
|
5186
|
+
: `【压缩未完成】${forcedCompactOut.error || '宿主压缩服务未就绪'}`)
|
|
5187
|
+
: (compactToolRec && compactToolRec.ok === false
|
|
5188
|
+
? `(⚠️ 实测压缩提示:${compactToolRec.error || '压缩未完成'})`
|
|
5189
|
+
: '')
|
|
5190
|
+
const baseParsedReply = cleanedParsedReply || buildSmartFallbackReply({ input, board, liveDigest, directory, facts: numberedFacts, mailbox: view.mailbox, conciseBrief: isConciseBrief }) || '- 【已执行】已按你的吩咐安排妥当。'
|
|
5191
|
+
const combinedParsedReply = compactOutcomeNote
|
|
5192
|
+
? (forcedCompactOut && !forcedCompactOut.ok
|
|
5193
|
+
? `${compactOutcomeNote}\n${baseParsedReply}`
|
|
5194
|
+
: (baseParsedReply.includes('压缩') && baseParsedReply.includes('档案') ? baseParsedReply : `${compactOutcomeNote}\n${baseParsedReply}`))
|
|
5195
|
+
: baseParsedReply
|
|
5196
|
+
const rawReplyText = cleanMultiline(combinedParsedReply, 1000)
|
|
5197
|
+
const replyText = isConciseBrief ? sanitizeConciseBriefText(rawReplyText) : rawReplyText
|
|
5198
|
+
|
|
5199
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
3555
5200
|
|
|
3556
5201
|
mutateChiefState((s) => {
|
|
3557
5202
|
const ws = ensureWorkspace(s, rootId)
|
|
3558
|
-
|
|
5203
|
+
const activeCluster = getLinkedCluster(s, rootId)
|
|
5204
|
+
appliedFacts = applyFactChanges(ws, numberedFacts, parsed.memoryChanges, 'user', {
|
|
5205
|
+
originRootId: rootId,
|
|
5206
|
+
peerRootIds: activeCluster.filter(id => id !== rootId),
|
|
5207
|
+
})
|
|
3559
5208
|
for (const f of appliedFacts) {
|
|
3560
5209
|
actionBadges.push((f.op === 'add' ? '记入:' : f.op === 'edit' ? '修订:' : '移除:') + clamp(f.text, 24))
|
|
3561
5210
|
}
|
|
3562
5211
|
|
|
3563
5212
|
for (const bp of rawBoundProposals) {
|
|
3564
5213
|
if (!bp || typeof bp !== 'object') continue
|
|
3565
|
-
const
|
|
5214
|
+
const rawBpField = String(bp.field || '').trim().toLowerCase()
|
|
5215
|
+
const normBpField = rawBpField === 'must' ? 'allowed' : rawBpField
|
|
5216
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normBpField) ? normBpField : 'forbidden'
|
|
3566
5217
|
const itemText = clamp(bp.item || bp.draftText || bp.text || '', 220)
|
|
3567
5218
|
if (!itemText || secretLike(itemText)) continue
|
|
3568
5219
|
const replaces = Array.isArray(bp.replaces)
|
|
@@ -3610,56 +5261,199 @@ export async function askOrCommandChief(deps, {
|
|
|
3610
5261
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
3611
5262
|
})
|
|
3612
5263
|
|
|
3613
|
-
// Refresh narrative summary in background if facts or
|
|
3614
|
-
const shouldRefreshNarrative = appliedFacts.length > 0
|
|
5264
|
+
// Refresh narrative summary in background if facts, board, archives, or network changed
|
|
5265
|
+
const shouldRefreshNarrative = appliedFacts.length > 0
|
|
5266
|
+
|| executedBoardOps.length > 0
|
|
5267
|
+
|| executedArchiveOps.length > 0
|
|
5268
|
+
|| executedNetworkOps.length > 0
|
|
3615
5269
|
const freshView = await getChiefView(deps, rootId, { autoSummarize: shouldRefreshNarrative })
|
|
5270
|
+
const freshBoard = executedBoardOps.length > 0 && deps.boardForSession && deps.boardFileFor
|
|
5271
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
5272
|
+
: undefined
|
|
5273
|
+
let freshArchives
|
|
5274
|
+
if (executedArchiveOps.length > 0) {
|
|
5275
|
+
try {
|
|
5276
|
+
const sc = rootId && rootId !== 'global' ? 'session' : 'global'
|
|
5277
|
+
const opt = archiveTargetForRoot(deps, rootId, { vaultScope: sc })
|
|
5278
|
+
const flIds = (freshView && freshView.flippedPrecipitatedIds) || []
|
|
5279
|
+
freshArchives = listArchiveHeaders(rootId, { vaultScope: sc, includePrecipitated: true, flippedIds: flIds }, opt)
|
|
5280
|
+
} catch {}
|
|
5281
|
+
}
|
|
3616
5282
|
|
|
3617
5283
|
return {
|
|
3618
5284
|
ok: true,
|
|
3619
5285
|
reply: replyText,
|
|
3620
5286
|
relays: relayResults,
|
|
5287
|
+
actionBadges,
|
|
3621
5288
|
memoryChanges: appliedFacts,
|
|
3622
5289
|
boardOps: executedBoardOps,
|
|
5290
|
+
archiveOps: executedArchiveOps,
|
|
5291
|
+
networkOps: executedNetworkOps,
|
|
3623
5292
|
boundProposals: proposedBounds,
|
|
5293
|
+
toolRecords: loopToolRecords,
|
|
5294
|
+
permissionMode,
|
|
5295
|
+
...(freshBoard ? { board: freshBoard } : {}),
|
|
5296
|
+
...(freshArchives ? { archives: freshArchives } : {}),
|
|
3624
5297
|
view: freshView,
|
|
3625
5298
|
}
|
|
3626
5299
|
}
|
|
3627
5300
|
|
|
5301
|
+
function describeThreePartyBoundariesForPrompt(permissionMode) {
|
|
5302
|
+
const mode = normalizePermissionMode(permissionMode)
|
|
5303
|
+
if (mode === 'read-only') {
|
|
5304
|
+
return '- 三方能力边界 [仅可查看 read-only]:参谋长=仅只读核查/建言/传递档案(禁改文件/跑写命令);主模型(@lead)=按自身会话授权推进;子代理=限于委派只读查证/分析(严守禁止红线)。'
|
|
5305
|
+
}
|
|
5306
|
+
if (mode === 'workspace-write') {
|
|
5307
|
+
return '- 三方能力边界 [工作区内修改 workspace-write]:参谋长=可读写当前工作区内文件、跑区内安全命令、调度子代理(禁越出工作区写盘或破坏性命令);主模型(@lead)=工作区内正常编码与测试(严守红线);子代理=限分配分支/工作区内读写。'
|
|
5308
|
+
}
|
|
5309
|
+
if (mode === 'auto-review') {
|
|
5310
|
+
return '- 三方能力边界 [自动审查 auto-review EXP]:参谋长=工作区内推进+高危终端/越界动作自动拦截进入双人审查;主模型(@lead)=常规读写与构建直行,高危操作需经审查放行;子代理=受同级安全规则约束。'
|
|
5311
|
+
}
|
|
5312
|
+
return '- 三方能力边界 [完全权限 danger-full-access]:参谋长=最高实权(全盘读写、跑测试构建、直接派发/纠偏/中断子代理、维护看板与主动压缩);主模型(@lead)=拥有自身完整工具权限;子代理=在各自沙箱/委派边界内执行并严守禁止红线。'
|
|
5313
|
+
}
|
|
5314
|
+
|
|
3628
5315
|
/**
|
|
3629
|
-
*
|
|
3630
|
-
*
|
|
3631
|
-
*
|
|
5316
|
+
* Multi-Archive Combinatorial Relay (`递话`):
|
|
5317
|
+
* Bundles 1+ archives across Session / Global / Precipitated vaults together with the user's explicit instruction
|
|
5318
|
+
* and delivers them cleanly to `@lead` or the specified target agent.
|
|
3632
5319
|
*/
|
|
3633
|
-
export function
|
|
3634
|
-
const
|
|
3635
|
-
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(
|
|
3636
|
-
const
|
|
3637
|
-
const
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
const
|
|
3643
|
-
const
|
|
3644
|
-
|
|
3645
|
-
const
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
5320
|
+
export async function relayArchivesWithChief(deps, { sessionId, items = [], instruction = '', target = 'lead', mode = 'steer', cabinetId = '' } = {}) {
|
|
5321
|
+
const rawSid = String(sessionId || '').trim()
|
|
5322
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(rawSid)) || rawSid || 'global'
|
|
5323
|
+
const selected = Array.isArray(items) ? items.slice(0, 8) : []
|
|
5324
|
+
const reqText = cleanMultiline(instruction, 800)
|
|
5325
|
+
if (!selected.length && !reqText) {
|
|
5326
|
+
return { ok: false, error: '请先勾选至少 1 份档案或输入带话要求' }
|
|
5327
|
+
}
|
|
5328
|
+
|
|
5329
|
+
const baseOpt = archiveTargetForRoot(deps, rootId, { cabinetId, vaultScope: 'session' })
|
|
5330
|
+
const projectKey = resolveProjectKey(baseOpt.cwd)
|
|
5331
|
+
const loaded = []
|
|
5332
|
+
const scopeLabelMap = { session: '本局档案', global: '全局档案', precipitated: '沉淀冷库' }
|
|
5333
|
+
|
|
5334
|
+
for (const ref of selected) {
|
|
5335
|
+
if (!ref || !ref.id) continue
|
|
5336
|
+
const rawSc = ref.scope || ref.vaultScope
|
|
5337
|
+
const sc = ['session', 'global', 'precipitated'].includes(rawSc) ? rawSc : 'session'
|
|
5338
|
+
let entry = null
|
|
5339
|
+
if (sc === 'precipitated') {
|
|
5340
|
+
const pRes = getPrecipitatedDetail(projectKey, ref.id, rootId, baseOpt)
|
|
5341
|
+
if (pRes && pRes.ok && pRes.item) entry = pRes.item
|
|
5342
|
+
} else {
|
|
5343
|
+
const opt = archiveTargetForRoot(deps, rootId, { cabinetId: sc === 'session' ? cabinetId : '', vaultScope: sc })
|
|
5344
|
+
const aRes = getArchiveDetail(ref.id, rootId, opt)
|
|
5345
|
+
if (aRes && aRes.ok && aRes.item) entry = aRes.item
|
|
5346
|
+
}
|
|
5347
|
+
if (entry) {
|
|
5348
|
+
loaded.push({ scope: sc, scopeLabel: scopeLabelMap[sc], item: entry })
|
|
5349
|
+
} else if (ref.title) {
|
|
5350
|
+
loaded.push({ scope: sc, scopeLabel: scopeLabelMap[sc], item: { id: ref.id, title: ref.title, summary: ref.summary || '', body: '', points: [] } })
|
|
3650
5351
|
}
|
|
3651
5352
|
}
|
|
3652
|
-
|
|
3653
|
-
|
|
5353
|
+
|
|
5354
|
+
if (!loaded.length && selected.length) {
|
|
5355
|
+
return { ok: false, error: '未能读取所选档案内容,请刷新档案列表后重试' }
|
|
3654
5356
|
}
|
|
3655
5357
|
|
|
3656
|
-
const
|
|
3657
|
-
|
|
3658
|
-
|
|
3659
|
-
|
|
5358
|
+
const header = `📎 【参谋长代用户带要求递交工程档案(共 ${loaded.length} 份)】`
|
|
5359
|
+
const reqBlock = reqText
|
|
5360
|
+
? `📝 【用户本次明确要求】:\n${reqText}`
|
|
5361
|
+
: '📝 【用户要求】:请重点结合以下档案内容对照推进当前任务。'
|
|
5362
|
+
const docBlocks = loaded.map((d, idx) => {
|
|
5363
|
+
const it = d.item
|
|
5364
|
+
const pts = Array.isArray(it.points) && it.points.length
|
|
5365
|
+
? it.points.slice(0, 5).map(p => ` - ${p.title}:${clamp(p.detail || p.cue, 160)}`).join('\n')
|
|
5366
|
+
: ''
|
|
5367
|
+
const rawSnippet = cleanMultiline(it.rawBody || it.body || it.summary || '', 360)
|
|
5368
|
+
return [
|
|
5369
|
+
`### ${idx + 1}. [${d.scopeLabel}] 《${clamp(it.title || '未命名档案', 56)}》`,
|
|
5370
|
+
it.summary ? `> 摘要:${clamp(it.summary, 140)}` : '',
|
|
5371
|
+
pts || '',
|
|
5372
|
+
rawSnippet && !pts ? rawSnippet : '',
|
|
5373
|
+
].filter(Boolean).join('\n')
|
|
5374
|
+
})
|
|
3660
5375
|
|
|
3661
|
-
const
|
|
3662
|
-
const
|
|
5376
|
+
const fullText = [header, reqBlock, '', ...docBlocks].join('\n\n')
|
|
5377
|
+
const safeMode = ['steer', 'followup', 'silent'].includes(mode) ? mode : 'steer'
|
|
5378
|
+
const delivery = await deliverCrossMessage(deps, {
|
|
5379
|
+
fromSession: rootId,
|
|
5380
|
+
fromLabel: '用户(经 DSH 参谋长递送档案)',
|
|
5381
|
+
target: target || 'lead',
|
|
5382
|
+
subject: loaded.length === 1 ? `递交档案《${clamp(loaded[0].item.title, 28)}》` : `合并递交 ${loaded.length} 份档案`,
|
|
5383
|
+
text: fullText,
|
|
5384
|
+
mode: safeMode,
|
|
5385
|
+
})
|
|
5386
|
+
|
|
5387
|
+
const titlesStr = loaded.map(d => `《${clamp(d.item.title, 24)}》`).join('、')
|
|
5388
|
+
mutateChiefState((s) => {
|
|
5389
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5390
|
+
ws.chat.push(
|
|
5391
|
+
{
|
|
5392
|
+
id: nextId('chat'),
|
|
5393
|
+
role: 'user',
|
|
5394
|
+
text: `📎 递送档案 ${titlesStr || '(无)'}${reqText ? `\n要求:${reqText}` : ''}`,
|
|
5395
|
+
actions: [],
|
|
5396
|
+
at: Date.now(),
|
|
5397
|
+
},
|
|
5398
|
+
{
|
|
5399
|
+
id: nextId('chat'),
|
|
5400
|
+
role: 'chief',
|
|
5401
|
+
text: delivery.ok
|
|
5402
|
+
? `- 【已按要求合并递话】已将 ${titlesStr} 连同你的要求(${safeMode === 'steer' ? '立即插话' : safeMode === 'silent' ? '静默纸条' : '排入续行'})传达给 ${delivery.target || target || '@lead'}。`
|
|
5403
|
+
: `- 【递话失败】${delivery.error || '目标不可达'}`,
|
|
5404
|
+
actions: delivery.ok ? [`→ ${delivery.target || target || 'lead'} (${loaded.length}卷)`] : ['递话失败'],
|
|
5405
|
+
at: Date.now(),
|
|
5406
|
+
},
|
|
5407
|
+
)
|
|
5408
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
5409
|
+
})
|
|
5410
|
+
|
|
5411
|
+
return {
|
|
5412
|
+
ok: Boolean(delivery && delivery.ok),
|
|
5413
|
+
error: delivery && !delivery.ok ? delivery.error : '',
|
|
5414
|
+
delivery,
|
|
5415
|
+
count: loaded.length,
|
|
5416
|
+
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
5417
|
+
}
|
|
5418
|
+
}
|
|
5419
|
+
|
|
5420
|
+
/**
|
|
5421
|
+
* Prime Minister Boundary Proposal API (`chief_board` action `"bounds.propose"`).
|
|
5422
|
+
* Lead or subagents submit wall-hits / boundary lessons here instead of silently mutating global bounds;
|
|
5423
|
+
* DSH Chief curates them and prompts the user for approval before injecting into `board.bounds`.
|
|
5424
|
+
*/
|
|
5425
|
+
export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, item, items, reason }) {
|
|
5426
|
+
const sid = String(sessionId || (callerAgent && callerAgent.id) || '').trim()
|
|
5427
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, callerAgent)) || sid || 'global'
|
|
5428
|
+
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, callerAgent) : null
|
|
5429
|
+
const speaker = identity && identity.isChild
|
|
5430
|
+
? `@${identity.self}`
|
|
5431
|
+
: (by && by !== 'agent' ? String(by) : '@lead')
|
|
5432
|
+
|
|
5433
|
+
const rawCol = String(field || '').trim().toLowerCase()
|
|
5434
|
+
const normCol = rawCol === 'must' ? 'allowed' : rawCol
|
|
5435
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normCol) ? normCol : 'forbidden'
|
|
5436
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
5437
|
+
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
5438
|
+
|
|
5439
|
+
const rawItems = []
|
|
5440
|
+
if (typeof item === 'string' && item.trim()) rawItems.push(item.trim())
|
|
5441
|
+
if (Array.isArray(items)) {
|
|
5442
|
+
for (const entry of items) {
|
|
5443
|
+
if (typeof entry === 'string' && entry.trim()) rawItems.push(entry.trim())
|
|
5444
|
+
}
|
|
5445
|
+
}
|
|
5446
|
+
if (!rawItems.length) {
|
|
5447
|
+
return { ok: false, error: 'bounds.propose requires item (string) or items (string[])' }
|
|
5448
|
+
}
|
|
5449
|
+
|
|
5450
|
+
const board = deps.boardForSession && deps.boardFileFor && rootId !== 'global'
|
|
5451
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
5452
|
+
: null
|
|
5453
|
+
const existingCol = Array.isArray(board?.bounds?.[col]) ? board.bounds[col] : []
|
|
5454
|
+
|
|
5455
|
+
const proposed = []
|
|
5456
|
+
const skippedDuplicates = []
|
|
3663
5457
|
|
|
3664
5458
|
mutateChiefState((state) => {
|
|
3665
5459
|
const ws = ensureWorkspace(state, rootId)
|
|
@@ -3724,16 +5518,27 @@ export function proposeBoundToChief(deps, { sessionId, callerAgent, by, field, i
|
|
|
3724
5518
|
|
|
3725
5519
|
const TURN_REVIEW_SYSTEM = [
|
|
3726
5520
|
'你是「DSH 参谋长」(宰相级协同与督导中枢)的后台复盘与督导模块。某个对话刚结束一轮输出。',
|
|
3727
|
-
'
|
|
5521
|
+
'请阅读最新对话片段、工作区核心目标、计划步骤、团队状态、生效边界(🚫 禁止红线 / ✅ 必做事项 / 💡 注意事项)、持久记忆与当前开启的战术开关,只输出一个 JSON 对象:',
|
|
3728
5522
|
'',
|
|
3729
5523
|
'1. `memoryChanges`:仅当出现跨轮次持久有效的规矩、分工、关键架构结论或踩坑教训时才新增/修订/删除;普通干活过程返回 `[]`。严禁保存密码或密钥。',
|
|
3730
|
-
'2. `boardOps`:若发现当前 `计划步骤 (Plan)` 明显仍对应旧需求/与最新 `总目标 (Objective)` 严重脱节(stale plan),务必输出 `{ "op": "plan.resetForGoal" }` 或 `{ "op": "plan.set", "steps": [...] }` 自动修正计划;也可更新 `task.update` / `cursor.set
|
|
5524
|
+
'2. `boardOps`:若发现当前 `计划步骤 (Plan)` 明显仍对应旧需求/与最新 `总目标 (Objective)` 严重脱节(stale plan),务必输出 `{ "op": "plan.resetForGoal" }` 或 `{ "op": "plan.set", "steps": [...] }` 自动修正计划;也可更新 `task.update` / `cursor.set`。注意:当 `INTERVENTION_SUPERVISOR` 开启时,核心目标已锁定,严禁输出 `objective.set` 擅改目标!',
|
|
3731
5525
|
'3. `planAssessment`:`{ "stale": true|false, "reason": "…" }`,指明当前计划步骤是否与总目标失配陈旧。',
|
|
3732
|
-
'4. `goalStatus
|
|
3733
|
-
'
|
|
3734
|
-
'
|
|
3735
|
-
' - `
|
|
3736
|
-
'
|
|
5526
|
+
'4. `goalStatus` 与 `unmetMustDo`:当开启 `GOAL_MODE` 或 `INTERVENTION_SUPERVISOR`(主动强介入)时重点评估,取值 `"in_progress" | "achieved" | "blocked"`。',
|
|
5527
|
+
' - **核心目标目的地铁律**:只要 `工作区核心目标 (Objective)` 非空,主动强介入的所有介入判断**一律以该核心目标有无完成作为最终目的地**(仅当核心目标为空时才退回对照最新用户原始诉求)。',
|
|
5528
|
+
' - **必做事项核验铁律**:`已有工作边界` 中的 `必做事项 (allowed)` 为硬性交付清单!在主对话/子代理交上来的作业未完成任何一条适用必做事项或缺少对应交付/验证证据前,**必须将未完成项逐条写入 `unmetMustDo` 数组,并保持 `goalStatus: "in_progress"` 与 `shouldIntervene: true`**(严禁判为 `"achieved"`)!',
|
|
5529
|
+
' - 仅当核心目标与全部适用必做事项均已完成并有实证支撑时,才可设 `goalStatus: "achieved"`(并填 `goalSummary` 与 `goalEvidence`);否则填 `goalMissing`。',
|
|
5530
|
+
'5. `hazardStop`(**强介入紧急安全煞车与撞边界熔断 · 最高优先级,优先于一切续推!**):',
|
|
5531
|
+
' - `{ "triggered": false, "category": "none|irreversible_risk|boundary_collision", "title": "", "reason": "" }`',
|
|
5532
|
+
' - 当 `INTERVENTION_SUPERVISOR` 或 `AUTO_PILOT_SESSION_ONLY` 开启时,你必须严密审查:主/子代理刚刚提出、准备执行、请求用户拍板,或接下来继续推进是否**存在重大不可逆风险,或继续推进必然会撞穿当前生效边界(尤其 🚫 禁止红线)**?',
|
|
5533
|
+
' - **重要提示(下列仅是常见举例,绝不限于此!)**:包括但不限于实际花钱/扣费/下单/付费 API 调用、不可逆删除或清空文件/数据/仓库、下载超大文件占用巨额磁盘或流量、关闭/重启服务器或关键宿主服务、对外公开推送/发布不可撤回变更、破坏宿主机隔离边界、以及任何一旦继续推跑就会导致不可逆损失或必然撞穿红线的情形。',
|
|
5534
|
+
' - 一旦命中任一上述风险或必然撞边界:**必须立即设 `"hazardStop": { "triggered": true, "category": "...", "title": "简短醒目告警标题", "reason": "用清晰人话说清具体会造成什么不可逆损失或必然撞上哪条边界,以及为何必须立即停下等用户处理" }`,并强制设 `"shouldIntervene": false`、`interventionText: ""`**(严禁再推下一轮!)。',
|
|
5535
|
+
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false`、主代理停下时,对照「核心目标 + 必做事项 + 最新用户诉求」逐项核验!只要目标或必做事项尚未真正做完、缺少实测验证证据却自称完成,必须设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或正在等待子代理回信时,设 `shouldIntervene: false`。',
|
|
5536
|
+
'7. `suggestions`(最多 1 条,宁缺毋滥):',
|
|
5537
|
+
' - `"kind": "bound"`:明显撞墙或发现长期红线/必做规矩时请示注入边界;',
|
|
5538
|
+
' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议;',
|
|
5539
|
+
' - `"kind": "advice"`:当主模型陷入明显可替代方案、环境坑点或需提醒用户拍板的关键决策时提出一句话建议,可带 `"popup": true|false`(仅关键分叉/阻塞决策设 `true`)。',
|
|
5540
|
+
'8. `shouldCompactNow` & `compactReason`:仅当 `SMART_COMPACT_CO_MANAGED`(✦ 智选)启用时评估!此时硬性上下文阈值已退让为辅助,由你与主会话共同把控压缩时机:只要一个完整阶段目标刚刚收口、工作流切换阶段、出现大量重复试错/工具噪音日志、或上下文估算已达 ≥30% 且适合归档脱水时,果断设 `shouldCompactNow: true` 并填写一句话 `compactReason`;仅在刚起步或上下文极轻时保持 `false`。',
|
|
5541
|
+
'9. `AUTO_PILOT_SESSION_ONLY`(全自动托管安全边界):当激活标志包含 `AUTO_PILOT_SESSION_ONLY` 时,所有自动决策仅限本对话会话内部!严禁将本会话规律生成 `"pinGlobal": true` 的全局定住边界,严禁跨出本对话去篡改全局档案柜或无关独立窗口;发现跨窗口传递信息时可留待人工审批。',
|
|
3737
5542
|
'',
|
|
3738
5543
|
'输出格式(严格 JSON):',
|
|
3739
5544
|
'{',
|
|
@@ -3744,12 +5549,68 @@ const TURN_REVIEW_SYSTEM = [
|
|
|
3744
5549
|
' "goalSummary": "",',
|
|
3745
5550
|
' "goalEvidence": "",',
|
|
3746
5551
|
' "goalMissing": "",',
|
|
5552
|
+
' "unmetMustDo": [],',
|
|
5553
|
+
' "hazardStop": { "triggered": false, "category": "none", "title": "", "reason": "" },',
|
|
3747
5554
|
' "shouldIntervene": false,',
|
|
3748
5555
|
' "interventionText": "",',
|
|
5556
|
+
' "shouldCompactNow": false,',
|
|
5557
|
+
' "compactReason": "",',
|
|
3749
5558
|
' "suggestions": []',
|
|
3750
5559
|
'}',
|
|
3751
5560
|
].join('\n')
|
|
3752
5561
|
|
|
5562
|
+
/** High-precision backup safety net if the turn-review model missed `hazardStop.triggered` despite unmistakable irreversible hazard or boundary collision cues. */
|
|
5563
|
+
function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, isInterventionActive = false }) {
|
|
5564
|
+
const rawHs = parsed && parsed.hazardStop && typeof parsed.hazardStop === 'object' ? parsed.hazardStop : null
|
|
5565
|
+
if (rawHs && rawHs.triggered === true && (rawHs.reason || rawHs.title)) {
|
|
5566
|
+
return {
|
|
5567
|
+
triggered: true,
|
|
5568
|
+
category: clamp(rawHs.category || 'irreversible_risk', 40) || 'irreversible_risk',
|
|
5569
|
+
title: clamp(rawHs.title || '强介入安全煞车 · 已自动停止', 120),
|
|
5570
|
+
reason: cleanMultiline(rawHs.reason || rawHs.title || '继续推进存在不可逆重大风险或必然撞穿边界,已暂停强介入并等待您的指示。', 520),
|
|
5571
|
+
}
|
|
5572
|
+
}
|
|
5573
|
+
if (!isInterventionActive) {
|
|
5574
|
+
return { triggered: false, category: 'none', title: '', reason: '' }
|
|
5575
|
+
}
|
|
5576
|
+
|
|
5577
|
+
const assistantParts = String(digestText || '').split(/(?:^|\n)Assistant:\s*/)
|
|
5578
|
+
const lastAssistant = assistantParts.length > 1 ? assistantParts[assistantParts.length - 1] : String(digestText || '')
|
|
5579
|
+
const reviewNotes = `${String(parsed?.goalMissing || '')}\n${String(parsed?.interventionText || '')}`
|
|
5580
|
+
|
|
5581
|
+
if (String(parsed?.goalStatus || '') === 'blocked' && /(?:不可逆|重大损失|撞[^\n。]{0,8}(?:红线|边界)|违反[^\n。]{0,8}禁止|花钱|扣费|付费|下单|删库|永久删除|大文件|关闭服务器|停服|破坏宿主机)/.test(reviewNotes)) {
|
|
5582
|
+
return {
|
|
5583
|
+
triggered: true,
|
|
5584
|
+
category: /红线|边界|禁止/.test(reviewNotes) ? 'boundary_collision' : 'irreversible_risk',
|
|
5585
|
+
title: /红线|边界|禁止/.test(reviewNotes) ? '继续推进将撞穿工作边界 · 已急停' : '检测到重大不可逆风险 · 已急停',
|
|
5586
|
+
reason: cleanMultiline(parsed.goalMissing || parsed.interventionText || '继续推进可能导致不可逆损失或触犯工作边界,已立即停止主动强介入。', 520),
|
|
5587
|
+
}
|
|
5588
|
+
}
|
|
5589
|
+
|
|
5590
|
+
const askHighRiskConfirmRe = /(?:需要|请)(?:您|用户)?(?:亲自|人工|手动)?(?:确认|授权|拍板|批准)[^\n。]{0,50}(?:花钱|扣费|付款|付费|下单|充值|永久删除|清空目录|格式化|关闭服务器|停服|重启宿主|下载[^\n。]{0,20}(?:GB|大文件)|不可逆)/i
|
|
5591
|
+
const mConfirm = lastAssistant.match(askHighRiskConfirmRe)
|
|
5592
|
+
if (mConfirm) {
|
|
5593
|
+
return {
|
|
5594
|
+
triggered: true,
|
|
5595
|
+
category: 'irreversible_risk',
|
|
5596
|
+
title: '高危/不可逆操作等待用户拍板 · 已急停',
|
|
5597
|
+
reason: cleanMultiline(`主对话提示需要您确认高风险操作(${mConfirm[0]}),为防止造成不可逆损失,已自动停止强介入推跑。`, 520),
|
|
5598
|
+
}
|
|
5599
|
+
}
|
|
5600
|
+
|
|
5601
|
+
const forbiddenList = Array.isArray(bounds && bounds.forbidden) ? bounds.forbidden : []
|
|
5602
|
+
if (forbiddenList.length > 0 && /(?:继续[^\n。]{0,12}(?:必|将|会)[^\n。]{0,10}(?:触犯|违反|撞上)|已触及[^\n。]{0,8}禁止红线|必然撞边界)/.test(reviewNotes)) {
|
|
5603
|
+
return {
|
|
5604
|
+
triggered: true,
|
|
5605
|
+
category: 'boundary_collision',
|
|
5606
|
+
title: '继续推进必然撞穿禁止红线 · 已急停',
|
|
5607
|
+
reason: cleanMultiline(reviewNotes, 520),
|
|
5608
|
+
}
|
|
5609
|
+
}
|
|
5610
|
+
|
|
5611
|
+
return { triggered: false, category: 'none', title: '', reason: '' }
|
|
5612
|
+
}
|
|
5613
|
+
|
|
3753
5614
|
const reviewTimers = new Map()
|
|
3754
5615
|
const COMPACT_POLL_MS = 180
|
|
3755
5616
|
const COMPACT_IDLE_WAIT_MS = 15_000
|
|
@@ -3797,12 +5658,201 @@ function measureAgentSessionTokensFallback(agent) {
|
|
|
3797
5658
|
}
|
|
3798
5659
|
}
|
|
3799
5660
|
|
|
5661
|
+
/** Record a visible confirmation card in Chief's right-panel chat when autonomous smart compaction finishes. */
|
|
5662
|
+
function recordSmartCompactionChatReceipt(rootId, { cRes, ratioPct = 0, totalTokens = 0, contextWindow = 0, via = '✦ 智选压缩' } = {}) {
|
|
5663
|
+
if (!rootId || rootId === 'global' || !cRes || !cRes.ok || cRes.noop) return
|
|
5664
|
+
const usageNote = totalTokens > 0 && contextWindow > 0
|
|
5665
|
+
? `(压前占用 ${formatCompactTokenShort(totalTokens)}/${formatCompactTokenShort(contextWindow)} · ${Math.round(ratioPct)}%)`
|
|
5666
|
+
: (ratioPct > 0 ? `(压前占用 ${Math.round(ratioPct)}%)` : '')
|
|
5667
|
+
const receiptText = `- 【${via}】已先将本轮关键细节抢救入本会话档案柜(#${cRes.harvestId}),并完成主对话静默压缩${usageNote}。`
|
|
5668
|
+
mutateChiefState((s) => {
|
|
5669
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5670
|
+
ws.chat.push({
|
|
5671
|
+
id: nextId('chat'),
|
|
5672
|
+
role: 'chief',
|
|
5673
|
+
text: receiptText,
|
|
5674
|
+
actions: ['✦ 智选压缩'],
|
|
5675
|
+
at: Date.now(),
|
|
5676
|
+
})
|
|
5677
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
5678
|
+
})
|
|
5679
|
+
}
|
|
5680
|
+
|
|
5681
|
+
/** Shared harvest -> disk verification -> host silent compaction sequence (always harvests into Session Cabinet). */
|
|
5682
|
+
async function executeHarvestAndCompact(deps, {
|
|
5683
|
+
sid,
|
|
5684
|
+
rootId,
|
|
5685
|
+
agent = null,
|
|
5686
|
+
reason = '',
|
|
5687
|
+
seq = 0,
|
|
5688
|
+
ratioPct = 0,
|
|
5689
|
+
totalTokens = 0,
|
|
5690
|
+
contextWindow = 0,
|
|
5691
|
+
logLabel = '自动压缩',
|
|
5692
|
+
} = {}) {
|
|
5693
|
+
if (!sid || !rootId || rootId === 'global') {
|
|
5694
|
+
return { ok: false, noop: true, error: '当前为空白新对话(未绑定活跃主会话),暂无可压缩的历史上下文' }
|
|
5695
|
+
}
|
|
5696
|
+
const focusHint = reason
|
|
5697
|
+
|| (ratioPct > 0
|
|
5698
|
+
? `上下文占用 ${Math.round(ratioPct)}%(${totalTokens}/${contextWindow} tokens),压缩前抢救现场细节。`
|
|
5699
|
+
: '阶段节点前抢救工程现场细节入本会话档案柜。')
|
|
5700
|
+
const harvest = await harvestTurnDetailsToArchive(deps, {
|
|
5701
|
+
sessionId: rootId,
|
|
5702
|
+
agent,
|
|
5703
|
+
vaultScope: 'session',
|
|
5704
|
+
trigger: 'pre-compaction',
|
|
5705
|
+
focusHint,
|
|
5706
|
+
})
|
|
5707
|
+
if (!harvest || !harvest.ok || !harvest.savedId) {
|
|
5708
|
+
return { ok: false, error: 'harvest-failed-abort-compact', detail: harvest && harvest.error }
|
|
5709
|
+
}
|
|
5710
|
+
|
|
5711
|
+
const targetOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
5712
|
+
const verified = getArchiveDetail(harvest.savedId, rootId, targetOpt)
|
|
5713
|
+
if (!verified || !verified.ok || !verified.item) {
|
|
5714
|
+
return { ok: false, error: 'harvest-verify-failed-abort-compact' }
|
|
5715
|
+
}
|
|
5716
|
+
|
|
5717
|
+
const cmdId = `dsh-chief-compact-${Date.now().toString(36)}`
|
|
5718
|
+
let compactRes
|
|
5719
|
+
try {
|
|
5720
|
+
compactRes = await deps.compactSessionNow(sid, cmdId)
|
|
5721
|
+
} catch (err) {
|
|
5722
|
+
const errMsg = (err && err.message) || String(err || 'compaction-failed')
|
|
5723
|
+
if (!/busy running/i.test(errMsg)) {
|
|
5724
|
+
mutateChiefState((s) => {
|
|
5725
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5726
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
5727
|
+
})
|
|
5728
|
+
}
|
|
5729
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
5730
|
+
deps.appendBoardLog(
|
|
5731
|
+
rootId,
|
|
5732
|
+
`⚠️ ${logLabel}未执行(已抢救档案 #${harvest.savedId},计数未变动):${errMsg}`,
|
|
5733
|
+
'chief',
|
|
5734
|
+
)
|
|
5735
|
+
}
|
|
5736
|
+
return { ok: false, error: errMsg, harvestId: harvest.savedId }
|
|
5737
|
+
}
|
|
5738
|
+
|
|
5739
|
+
if (compactRes && compactRes.noop) {
|
|
5740
|
+
mutateChiefState((s) => {
|
|
5741
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5742
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
5743
|
+
})
|
|
5744
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
5745
|
+
deps.appendBoardLog(
|
|
5746
|
+
rootId,
|
|
5747
|
+
`🗄️ ${logLabel}:已先抢救细节入本会话档案柜(#${harvest.savedId}),宿主历史暂无需压缩`,
|
|
5748
|
+
'chief',
|
|
5749
|
+
)
|
|
5750
|
+
}
|
|
5751
|
+
return {
|
|
5752
|
+
ok: true,
|
|
5753
|
+
noop: true,
|
|
5754
|
+
harvestId: harvest.savedId,
|
|
5755
|
+
ratioPct: Math.round(ratioPct),
|
|
5756
|
+
compactRes,
|
|
5757
|
+
}
|
|
5758
|
+
}
|
|
5759
|
+
|
|
5760
|
+
mutateChiefState((s) => {
|
|
5761
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5762
|
+
ws.runtimeGuard.lastCompactedSeq = seq > 0 ? seq : ((ws.runtimeGuard.lastCompactedSeq || 0) + 1)
|
|
5763
|
+
ws.runtimeGuard.lastCompactedAt = Date.now()
|
|
5764
|
+
ws.runtimeGuard.autoCompactCount = (ws.runtimeGuard.autoCompactCount || 0) + 1
|
|
5765
|
+
ws.runtimeGuard.pendingSmartCompact = null
|
|
5766
|
+
})
|
|
5767
|
+
|
|
5768
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
5769
|
+
deps.appendBoardLog(
|
|
5770
|
+
rootId,
|
|
5771
|
+
`🗜️ ${logLabel}:已先抢救细节入本会话档案柜(#${harvest.savedId})并执行静默压缩${ratioPct > 0 ? `(占 ${Math.round(ratioPct)}%)` : ''}`,
|
|
5772
|
+
'chief',
|
|
5773
|
+
)
|
|
5774
|
+
}
|
|
5775
|
+
return {
|
|
5776
|
+
ok: true,
|
|
5777
|
+
noop: false,
|
|
5778
|
+
harvestId: harvest.savedId,
|
|
5779
|
+
ratioPct: Math.round(ratioPct),
|
|
5780
|
+
compactRes,
|
|
5781
|
+
}
|
|
5782
|
+
}
|
|
5783
|
+
|
|
5784
|
+
/** Called by Lead via `chief_board({ action: "context.compact", text })` when `✦ 智选` co-management is enabled. */
|
|
5785
|
+
export async function requestSmartCompactFromLead(deps, {
|
|
5786
|
+
sessionId = '',
|
|
5787
|
+
reason = '',
|
|
5788
|
+
by = 'lead',
|
|
5789
|
+
} = {}) {
|
|
5790
|
+
const sid = String(sessionId || '').trim()
|
|
5791
|
+
if (!sid) return { ok: false, error: '当前未绑定具体会话,无法发起智选压缩' }
|
|
5792
|
+
const rootId = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid) : '') || sid
|
|
5793
|
+
const state = loadChiefState()
|
|
5794
|
+
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
5795
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
5796
|
+
if (!tactical.smartCompact && !tactical.autoCompact) {
|
|
5797
|
+
return { ok: false, error: '当前未开启「✦ 智选」或自动压缩模式,请先在战术菜单打开开关' }
|
|
5798
|
+
}
|
|
5799
|
+
|
|
5800
|
+
const cleanReason = clamp(reason || '主会话判断阶段已收口,主动协同发起归档压缩', 240)
|
|
5801
|
+
mutateChiefState((s) => {
|
|
5802
|
+
const ws = ensureWorkspace(s, rootId)
|
|
5803
|
+
ws.runtimeGuard.pendingSmartCompact = {
|
|
5804
|
+
at: Date.now(),
|
|
5805
|
+
reason: cleanReason,
|
|
5806
|
+
by: clamp(by || 'lead', 40),
|
|
5807
|
+
}
|
|
5808
|
+
})
|
|
5809
|
+
|
|
5810
|
+
let status = 'idle'
|
|
5811
|
+
try {
|
|
5812
|
+
if (deps && typeof deps.getAgentStatus === 'function') {
|
|
5813
|
+
status = deps.getAgentStatus(sid) || 'idle'
|
|
5814
|
+
}
|
|
5815
|
+
} catch {}
|
|
5816
|
+
|
|
5817
|
+
if (status === 'running' || !deps || typeof deps.compactSessionNow !== 'function') {
|
|
5818
|
+
return {
|
|
5819
|
+
ok: true,
|
|
5820
|
+
queued: true,
|
|
5821
|
+
reason: cleanReason,
|
|
5822
|
+
message: '已登记主会话的智选归档压缩请求,本轮收口空闲后将由参谋长抢救细节入本会话档案柜并静默压缩。',
|
|
5823
|
+
}
|
|
5824
|
+
}
|
|
5825
|
+
|
|
5826
|
+
let usage = null
|
|
5827
|
+
try {
|
|
5828
|
+
if (typeof deps.measureSessionTokens === 'function') {
|
|
5829
|
+
usage = await deps.measureSessionTokens(sid)
|
|
5830
|
+
}
|
|
5831
|
+
} catch {}
|
|
5832
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
5833
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
5834
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
5835
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
5836
|
+
|
|
5837
|
+
const execRes = await executeHarvestAndCompact(deps, {
|
|
5838
|
+
sid,
|
|
5839
|
+
rootId,
|
|
5840
|
+
reason: cleanReason,
|
|
5841
|
+
seq,
|
|
5842
|
+
ratioPct,
|
|
5843
|
+
totalTokens,
|
|
5844
|
+
contextWindow,
|
|
5845
|
+
logLabel: '✦ 智选压缩(主会话协同)',
|
|
5846
|
+
})
|
|
5847
|
+
return { ...execRes, compacted: Boolean(execRes && execRes.ok), reason: cleanReason }
|
|
5848
|
+
}
|
|
5849
|
+
|
|
3800
5850
|
/**
|
|
3801
5851
|
* Post-Turn Auto-Compaction Pipeline (strict safety contract):
|
|
3802
5852
|
* 1. NEVER run inside synchronous `turn-stopping` or while agent.status === 'running'. Wait for idle first.
|
|
3803
|
-
* 2.
|
|
3804
|
-
*
|
|
3805
|
-
*
|
|
5853
|
+
* 2. When `smartCompact` (`✦ 智选`) is enabled, hard `compactThresholdPct` is bypassed completely!
|
|
5854
|
+
* Compaction runs ONLY on `pendingSmartCompact` (from Lead or Chief) or Chief's `shouldCompactNow` judgment.
|
|
5855
|
+
* 3. Always harvest into Session Cabinet + verify on disk BEFORE calling `compactSessionNow`.
|
|
3806
5856
|
*/
|
|
3807
5857
|
export async function maybeRunPreCompaction(deps, {
|
|
3808
5858
|
agent = null,
|
|
@@ -3816,10 +5866,23 @@ export async function maybeRunPreCompaction(deps, {
|
|
|
3816
5866
|
|
|
3817
5867
|
const state = loadChiefState()
|
|
3818
5868
|
const effCfg = resolveWorkspaceConfig(state, rootId)
|
|
5869
|
+
if (effCfg.stopped || effCfg.paceMode === 'stopped') {
|
|
5870
|
+
return { ok: false, skipped: 'chief-stopped' }
|
|
5871
|
+
}
|
|
3819
5872
|
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
3820
|
-
|
|
5873
|
+
const wsSnapshot = ensureWorkspace(state, rootId)
|
|
5874
|
+
const pendingSmart = wsSnapshot.runtimeGuard && wsSnapshot.runtimeGuard.pendingSmartCompact
|
|
5875
|
+
|
|
5876
|
+
if (!pendingSmart && !tactical.autoCompact && !tactical.smartCompact) {
|
|
5877
|
+
return { ok: false, skipped: 'disabled' }
|
|
5878
|
+
}
|
|
3821
5879
|
if (!deps || typeof deps.compactSessionNow !== 'function') return { ok: false, skipped: 'no-compaction-service' }
|
|
3822
5880
|
|
|
5881
|
+
// When `✦ 智选` is enabled and no pending smart request exists, hard threshold does NOT trigger!
|
|
5882
|
+
if (!pendingSmart && tactical.smartCompact) {
|
|
5883
|
+
return { ok: false, skipped: 'smart-compact-mode', mode: 'smart' }
|
|
5884
|
+
}
|
|
5885
|
+
|
|
3823
5886
|
const getStatus = () => {
|
|
3824
5887
|
if (typeof deps.getAgentStatus === 'function') return deps.getAgentStatus(sid)
|
|
3825
5888
|
return (agent && agent.status) || 'idle'
|
|
@@ -3836,6 +5899,36 @@ export async function maybeRunPreCompaction(deps, {
|
|
|
3836
5899
|
? await deps.measureSessionTokens(sid, agent)
|
|
3837
5900
|
: measureAgentSessionTokensFallback(agent)
|
|
3838
5901
|
} catch {}
|
|
5902
|
+
|
|
5903
|
+
if (pendingSmart) {
|
|
5904
|
+
const contextWindow = Math.max(1000, Number(usage && usage.contextWindow) || 128_000)
|
|
5905
|
+
const totalTokens = Number(usage && usage.totalTokens) || 0
|
|
5906
|
+
const seq = Math.max(0, Math.round(Number(usage && usage.seq) || 0))
|
|
5907
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
5908
|
+
const out = await executeHarvestAndCompact(deps, {
|
|
5909
|
+
sid,
|
|
5910
|
+
rootId,
|
|
5911
|
+
agent,
|
|
5912
|
+
reason: pendingSmart.reason || '主会话/参谋长智选协同触发压缩',
|
|
5913
|
+
seq,
|
|
5914
|
+
ratioPct,
|
|
5915
|
+
totalTokens,
|
|
5916
|
+
contextWindow,
|
|
5917
|
+
logLabel: '✦ 智选压缩',
|
|
5918
|
+
})
|
|
5919
|
+
const actuallyCompacted = Boolean(out && out.ok && !out.noop)
|
|
5920
|
+
if (actuallyCompacted) {
|
|
5921
|
+
recordSmartCompactionChatReceipt(rootId, {
|
|
5922
|
+
cRes: out,
|
|
5923
|
+
ratioPct,
|
|
5924
|
+
totalTokens,
|
|
5925
|
+
contextWindow,
|
|
5926
|
+
via: '✦ 智选压缩',
|
|
5927
|
+
})
|
|
5928
|
+
}
|
|
5929
|
+
return { ...out, smartCompacted: actuallyCompacted }
|
|
5930
|
+
}
|
|
5931
|
+
|
|
3839
5932
|
if (!usage || !Number(usage.totalTokens)) {
|
|
3840
5933
|
return { ok: false, skipped: 'no-token-usage' }
|
|
3841
5934
|
}
|
|
@@ -3843,53 +5936,53 @@ export async function maybeRunPreCompaction(deps, {
|
|
|
3843
5936
|
const totalTokens = Number(usage.totalTokens) || 0
|
|
3844
5937
|
const seq = Math.max(0, Math.round(Number(usage.seq) || 0))
|
|
3845
5938
|
const ratioPct = (totalTokens / contextWindow) * 100
|
|
3846
|
-
const wsSnapshot = ensureWorkspace(loadChiefState(), rootId)
|
|
3847
5939
|
const lastSeq = (wsSnapshot.runtimeGuard && wsSnapshot.runtimeGuard.lastCompactedSeq) || 0
|
|
3848
5940
|
|
|
3849
|
-
|
|
3850
|
-
|
|
5941
|
+
const thresholdMode = tactical.compactThresholdMode === 'tokens' ? 'tokens' : 'pct'
|
|
5942
|
+
let limitHint = ''
|
|
5943
|
+
if (thresholdMode === 'tokens') {
|
|
5944
|
+
const thresholdTokens = Math.max(COMPACT_TOKEN_HARD_MIN, Number(tactical.compactThresholdTokens) || 64_000)
|
|
5945
|
+
if (totalTokens < thresholdTokens) {
|
|
5946
|
+
return {
|
|
5947
|
+
ok: false,
|
|
5948
|
+
skipped: 'below-threshold',
|
|
5949
|
+
mode: 'tokens',
|
|
5950
|
+
totalTokens,
|
|
5951
|
+
thresholdTokens,
|
|
5952
|
+
thresholdInput: formatCompactTokenShort(thresholdTokens),
|
|
5953
|
+
ratioPct: Math.round(ratioPct),
|
|
5954
|
+
}
|
|
5955
|
+
}
|
|
5956
|
+
limitHint = `上下文占用 ${formatCompactTokenShort(totalTokens)} 已达到自定阈值 ${formatCompactTokenShort(thresholdTokens)}`
|
|
5957
|
+
} else {
|
|
5958
|
+
const minPct = Math.max(COMPACT_THRESHOLD_MIN_PCT, Number(tactical.compactThresholdPct) || 80)
|
|
5959
|
+
if (ratioPct < minPct) {
|
|
5960
|
+
return {
|
|
5961
|
+
ok: false,
|
|
5962
|
+
skipped: 'below-threshold',
|
|
5963
|
+
mode: 'pct',
|
|
5964
|
+
ratioPct: Math.round(ratioPct),
|
|
5965
|
+
thresholdPct: minPct,
|
|
5966
|
+
}
|
|
5967
|
+
}
|
|
5968
|
+
limitHint = `上下文占用已达 ${Math.round(ratioPct)}%(阈值 ${minPct}%,${totalTokens}/${contextWindow} tokens)`
|
|
3851
5969
|
}
|
|
5970
|
+
|
|
3852
5971
|
if (seq > 0 && seq <= lastSeq) {
|
|
3853
5972
|
return { ok: false, skipped: 'already-compacted-seq', seq, lastSeq }
|
|
3854
5973
|
}
|
|
3855
5974
|
|
|
3856
|
-
|
|
3857
|
-
|
|
3858
|
-
|
|
5975
|
+
return executeHarvestAndCompact(deps, {
|
|
5976
|
+
sid,
|
|
5977
|
+
rootId,
|
|
3859
5978
|
agent,
|
|
3860
|
-
|
|
3861
|
-
|
|
5979
|
+
reason: `${limitHint},压缩前抢救现场细节。`,
|
|
5980
|
+
seq,
|
|
5981
|
+
ratioPct,
|
|
5982
|
+
totalTokens,
|
|
5983
|
+
contextWindow,
|
|
5984
|
+
logLabel: '自动压缩',
|
|
3862
5985
|
})
|
|
3863
|
-
if (!harvest || !harvest.ok || !harvest.savedId) {
|
|
3864
|
-
return { ok: false, error: 'harvest-failed-abort-compact', detail: harvest && harvest.error }
|
|
3865
|
-
}
|
|
3866
|
-
|
|
3867
|
-
// Step 2: Double-verify written dossier exists cleanly on disk
|
|
3868
|
-
const targetOpt = archiveTargetForRoot(deps, rootId)
|
|
3869
|
-
const verified = getArchiveDetail(harvest.savedId, rootId, targetOpt)
|
|
3870
|
-
if (!verified || !verified.ok || !verified.item) {
|
|
3871
|
-
return { ok: false, error: 'harvest-verify-failed-abort-compact' }
|
|
3872
|
-
}
|
|
3873
|
-
|
|
3874
|
-
// Step 3: Record compacted seq before triggering host compaction
|
|
3875
|
-
mutateChiefState((s) => {
|
|
3876
|
-
const ws = ensureWorkspace(s, rootId)
|
|
3877
|
-
ws.runtimeGuard.lastCompactedSeq = seq > 0 ? seq : (ws.runtimeGuard.lastCompactedSeq + 1)
|
|
3878
|
-
ws.runtimeGuard.lastCompactedAt = Date.now()
|
|
3879
|
-
})
|
|
3880
|
-
|
|
3881
|
-
// Step 4: Execute compaction safely while agent is idle
|
|
3882
|
-
const cmdId = `dsh-chief-autocompact-${Date.now().toString(36)}`
|
|
3883
|
-
const compactRes = await deps.compactSessionNow(sid, cmdId)
|
|
3884
|
-
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
3885
|
-
deps.appendBoardLog(rootId, `🗜️ 已先抢救入柜(#${harvest.savedId})并自动完成上下文压缩(占 ${Math.round(ratioPct)}%)`, 'chief')
|
|
3886
|
-
}
|
|
3887
|
-
return {
|
|
3888
|
-
ok: true,
|
|
3889
|
-
harvestId: harvest.savedId,
|
|
3890
|
-
ratioPct: Math.round(ratioPct),
|
|
3891
|
-
compactRes,
|
|
3892
|
-
}
|
|
3893
5986
|
}
|
|
3894
5987
|
|
|
3895
5988
|
function extractLatestTurnDigest(agent, turn) {
|
|
@@ -3897,6 +5990,23 @@ function extractLatestTurnDigest(agent, turn) {
|
|
|
3897
5990
|
try {
|
|
3898
5991
|
if (typeof agent.session.deriveMessages === 'function') {
|
|
3899
5992
|
const msgs = agent.session.deriveMessages() || []
|
|
5993
|
+
let latestUserPrompt = ''
|
|
5994
|
+
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
|
5995
|
+
const um = msgs[i]
|
|
5996
|
+
if (!um || um.role !== 'user') continue
|
|
5997
|
+
if (um.source && um.source.kind && um.source.kind !== 'user') continue
|
|
5998
|
+
const uBlocks = Array.isArray(um.content) ? um.content : []
|
|
5999
|
+
const uTxt = uBlocks
|
|
6000
|
+
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
6001
|
+
.map(b => b.text)
|
|
6002
|
+
.join('\n')
|
|
6003
|
+
.trim()
|
|
6004
|
+
if (uTxt && !isInternalCheckpointNoise(uTxt)) {
|
|
6005
|
+
latestUserPrompt = clamp(uTxt, 1000)
|
|
6006
|
+
break
|
|
6007
|
+
}
|
|
6008
|
+
}
|
|
6009
|
+
|
|
3900
6010
|
const tail = msgs.slice(-6)
|
|
3901
6011
|
const lines = []
|
|
3902
6012
|
let hasUser = false
|
|
@@ -3917,7 +6027,7 @@ function extractLatestTurnDigest(agent, turn) {
|
|
|
3917
6027
|
lines.push('Assistant: ' + clamp(txt, 900))
|
|
3918
6028
|
}
|
|
3919
6029
|
}
|
|
3920
|
-
if (lines.length > 0) return { text: lines.join('\n'), hasUser, stamp: msgs.length }
|
|
6030
|
+
if (lines.length > 0) return { text: lines.join('\n'), hasUser, latestUserPrompt, stamp: msgs.length }
|
|
3921
6031
|
}
|
|
3922
6032
|
} catch {}
|
|
3923
6033
|
return null
|
|
@@ -3936,12 +6046,19 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
|
3936
6046
|
const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
3937
6047
|
const effCfg = resolveWorkspaceConfig(state, rootKey)
|
|
3938
6048
|
const paceMode = effCfg.paceMode || 'manual'
|
|
6049
|
+
if (effCfg.stopped || paceMode === 'stopped') {
|
|
6050
|
+
clearTimeout(reviewTimers.get(rootKey))
|
|
6051
|
+
reviewTimers.delete(rootKey)
|
|
6052
|
+
return
|
|
6053
|
+
}
|
|
3939
6054
|
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
6055
|
+
const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
|
|
6056
|
+
const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
|
|
3940
6057
|
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
3941
6058
|
? deps.boardForSession(deps.boardFileFor(rootKey))
|
|
3942
6059
|
: null
|
|
3943
6060
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
3944
|
-
const hasHighPriorityChannel = isGoalMode || tactical.autoCompact || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
|
|
6061
|
+
const hasHighPriorityChannel = isGoalMode || tactical.autoCompact || tactical.smartCompact || pendingSmart || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
|
|
3945
6062
|
|
|
3946
6063
|
// Default 'manual' mode without tactical/goal active: ZERO background LLM calls!
|
|
3947
6064
|
if (!hasHighPriorityChannel && (paceMode === 'manual' || effCfg.autoReview === false)) return
|
|
@@ -3965,29 +6082,44 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
3965
6082
|
const effCfgBefore = resolveWorkspaceConfig(stateBefore, rootId)
|
|
3966
6083
|
const tactical = normalizeTacticalModes(effCfgBefore.tacticalModes)
|
|
3967
6084
|
const paceMode = effCfgBefore.paceMode || 'manual'
|
|
6085
|
+
if (!force && (effCfgBefore.stopped || paceMode === 'stopped')) {
|
|
6086
|
+
return { ok: false, skipped: 'chief-stopped' }
|
|
6087
|
+
}
|
|
6088
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
3968
6089
|
const board = deps.boardForSession && deps.boardFileFor
|
|
3969
6090
|
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
3970
6091
|
: null
|
|
3971
6092
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
3972
|
-
const
|
|
6093
|
+
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
6094
|
+
const smartCoManaged = Boolean(tactical.smartCompact)
|
|
6095
|
+
const hasHighPriority = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || tactical.autoCompact || tactical.smartCompact || pendingSmart
|
|
3973
6096
|
|
|
3974
6097
|
if (!force && !hasHighPriority && paceMode === 'manual') {
|
|
3975
6098
|
return { ok: false, skipped: 'manual' }
|
|
3976
6099
|
}
|
|
3977
6100
|
|
|
3978
|
-
// Always check pre-compaction pipeline first when autoCompact is active
|
|
3979
|
-
if (tactical.autoCompact) {
|
|
3980
|
-
await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) })
|
|
6101
|
+
// Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
|
|
6102
|
+
if (tactical.autoCompact || tactical.smartCompact || pendingSmart) {
|
|
6103
|
+
const preRes = await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) })
|
|
6104
|
+
.catch((err) => {
|
|
6105
|
+
const msg = (err && err.message) || String(err || 'pre-compact-error')
|
|
6106
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
6107
|
+
deps.appendBoardLog(rootId, `⚠️ 自动压缩检测异常:${msg}`, 'chief')
|
|
6108
|
+
}
|
|
6109
|
+
return { ok: false, error: msg }
|
|
6110
|
+
})
|
|
6111
|
+
if (preRes && preRes.ok && preRes.smartCompacted) {
|
|
6112
|
+
return { ok: true, smartCompacted: true, harvestId: preRes.harvestId }
|
|
6113
|
+
}
|
|
3981
6114
|
}
|
|
3982
6115
|
|
|
3983
|
-
// If ONLY autoCompact was on
|
|
3984
|
-
const needsSupervisorLlm = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || paceMode !== 'manual'
|
|
6116
|
+
// If ONLY fixed-threshold autoCompact was on (without smartCompact or supervisor/pace), exit cleanly here
|
|
6117
|
+
const needsSupervisorLlm = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || smartCoManaged || paceMode !== 'manual'
|
|
3985
6118
|
if (!force && !needsSupervisorLlm) return { ok: true, onlyCompactionChecked: true }
|
|
3986
6119
|
|
|
3987
6120
|
const digest = extractLatestTurnDigest(agent, turn)
|
|
3988
6121
|
if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
|
|
3989
6122
|
|
|
3990
|
-
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
3991
6123
|
const cursorKey = `${sid}`
|
|
3992
6124
|
if (!force && wsBefore.reviewCursors[cursorKey] === digest.stamp) {
|
|
3993
6125
|
return { ok: false, skipped: 'same-stamp' }
|
|
@@ -4000,24 +6132,42 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4000
6132
|
const now = Date.now()
|
|
4001
6133
|
const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
|
|
4002
6134
|
const cooldownMs = hasHighPriority
|
|
4003
|
-
? 4_000
|
|
6135
|
+
? (smartCoManaged && !isGoalMode && !tactical.intervention ? 12_000 : 4_000)
|
|
4004
6136
|
: (paceMode === 'smart' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
|
|
4005
6137
|
if (!force && now - lastAt < cooldownMs) return { ok: false, skipped: 'cooldown' }
|
|
4006
6138
|
|
|
4007
|
-
// Wait if supervisor
|
|
4008
|
-
if ((tactical.intervention || isGoalMode) && typeof deps.getAgentStatus === 'function' && !force) {
|
|
6139
|
+
// Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
|
|
6140
|
+
if ((tactical.intervention || isGoalMode || smartCoManaged) && typeof deps.getAgentStatus === 'function' && !force) {
|
|
4009
6141
|
await waitUntilAgentIdle(() => deps.getAgentStatus(sid), 5_000, 150)
|
|
4010
6142
|
}
|
|
4011
6143
|
|
|
4012
6144
|
const directory = await listPeerDirectory(deps, rootId)
|
|
4013
6145
|
const realPeers = directory.targets.filter(t => !/^mnemon-(?:review|run)/i.test(String(t.name || t.handle || '')))
|
|
4014
6146
|
|
|
4015
|
-
|
|
6147
|
+
let liveUsage = null
|
|
6148
|
+
if (smartCoManaged) {
|
|
6149
|
+
try {
|
|
6150
|
+
liveUsage = typeof deps.measureSessionTokens === 'function'
|
|
6151
|
+
? await deps.measureSessionTokens(sid, agent)
|
|
6152
|
+
: measureAgentSessionTokensFallback(agent)
|
|
6153
|
+
} catch {}
|
|
6154
|
+
}
|
|
6155
|
+
|
|
6156
|
+
// In 'smart' background mode (without supervisor/goal), gate LLM call on wall cue or multi-agent human turn;
|
|
6157
|
+
// when ONLY smartCoManaged is enabled in manual pace, evaluate only after enough turns or context pressure.
|
|
4016
6158
|
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify) {
|
|
4017
|
-
if (paceMode === '
|
|
4018
|
-
|
|
6159
|
+
if (smartCoManaged && paceMode === 'manual') {
|
|
6160
|
+
const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
|
|
6161
|
+
const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
|
|
6162
|
+
if ((digest.stamp < 4 && ratio < 0.25) || sinceCompact < 20_000) {
|
|
6163
|
+
return { ok: false, skipped: 'smart-compact-light' }
|
|
6164
|
+
}
|
|
6165
|
+
} else {
|
|
6166
|
+
if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
|
|
6167
|
+
return { ok: false, skipped: 'smart-quiet' }
|
|
6168
|
+
}
|
|
6169
|
+
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
|
|
4019
6170
|
}
|
|
4020
|
-
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
|
|
4021
6171
|
}
|
|
4022
6172
|
|
|
4023
6173
|
if (!deps.callLlmOverride) {
|
|
@@ -4038,22 +6188,30 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4038
6188
|
const activeFlags = [
|
|
4039
6189
|
isGoalMode ? 'GOAL_MODE' : '',
|
|
4040
6190
|
tactical.intervention ? 'INTERVENTION_SUPERVISOR' : '',
|
|
6191
|
+
smartCoManaged ? 'SMART_COMPACT_CO_MANAGED' : '',
|
|
4041
6192
|
tactical.strictVerify ? 'STRICT_VERIFY' : '',
|
|
4042
6193
|
tactical.redlineSentinel ? 'REDLINE_SENTINEL' : '',
|
|
4043
6194
|
tactical.conciseBrief ? 'CONCISE_BRIEF_3_BULLETS' : '',
|
|
6195
|
+
Boolean(paceMode === 'auto' && effCfgBefore.autoPilot && !effCfgBefore.stopped) ? 'AUTO_PILOT_SESSION_ONLY' : '',
|
|
4044
6196
|
].filter(Boolean)
|
|
4045
6197
|
|
|
6198
|
+
const smartUsageHint = smartCoManaged
|
|
6199
|
+
? `智选共管状态(硬阈值已停用):消息序号≈${digest.stamp}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
|
|
6200
|
+
: ''
|
|
6201
|
+
|
|
4046
6202
|
const prompt = [
|
|
4047
6203
|
`当前激活监督模式:${activeFlags.join(' | ') || paceMode}`,
|
|
4048
|
-
|
|
6204
|
+
...(smartUsageHint ? [smartUsageHint] : []),
|
|
6205
|
+
`工作区总目标 (Objective):${(board && board.objective) || '(暂未开启 /goal 固定目标 — 请对照下方最新用户原始诉求核验完成度)'}`,
|
|
6206
|
+
`最新用户原始诉求:${digest.latestUserPrompt || '(见下方对话片段)'}`,
|
|
4049
6207
|
`当前计划步骤 (Plan):${planSteps.length ? planSteps.map((s, i) => `${i + 1}.${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';') : '(空)'}`,
|
|
4050
6208
|
`当前任务列表 (Tasks):${tasks.length ? tasks.slice(0, 10).map(t => `[${t.status}] #${t.id} ${clamp(t.title, 48)}`).join(';') : '(空)'}`,
|
|
4051
6209
|
`刚刚结束回合的对话身份:${speaker}(sessionId=${sid})`,
|
|
4052
6210
|
`活跃团队成员:${activeTargets.map(t => `${t.handle}[key=${t.key}, ${t.status}${t.taskTitle ? ', 任务:' + t.taskTitle : ''}]`).join(';')}${idleCount > 0 ? `(另有 ${idleCount} 名空闲子代理已折叠)` : ''}`,
|
|
4053
6211
|
'',
|
|
4054
|
-
'
|
|
6212
|
+
'已有工作边界(禁止红线严防撞穿;必做事项提交结项前须逐项核验是否完成):',
|
|
4055
6213
|
`- 禁止:${(bounds.forbidden || []).join(';') || '(暂无)'}`,
|
|
4056
|
-
`-
|
|
6214
|
+
`- 必做事项 (allowed · 必须交付确认):${(bounds.allowed || []).join(';') || '(暂无)'}`,
|
|
4057
6215
|
`- 注意:${(bounds.notes || []).join(';') || '(暂无)'}`,
|
|
4058
6216
|
'',
|
|
4059
6217
|
'已有持久记忆条目:',
|
|
@@ -4074,7 +6232,8 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4074
6232
|
const parsed = extractJsonObject(res.text)
|
|
4075
6233
|
if (!parsed) return { ok: false, error: 'non-json-review' }
|
|
4076
6234
|
|
|
4077
|
-
const
|
|
6235
|
+
const cfgNow = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
6236
|
+
const autoPilot = Boolean(cfgNow.paceMode === 'auto' && cfgNow.autoPilot && !cfgNow.stopped)
|
|
4078
6237
|
const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
|
|
4079
6238
|
.map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
|
|
4080
6239
|
.filter(Boolean)
|
|
@@ -4087,12 +6246,26 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4087
6246
|
parsedBoardOps.unshift({ op: 'plan.resetForGoal' })
|
|
4088
6247
|
}
|
|
4089
6248
|
const executedOps = parsedBoardOps.length > 0 && deps.runAction
|
|
4090
|
-
? applyBoardOps(deps, rootId, parsedBoardOps)
|
|
6249
|
+
? applyBoardOps(deps, rootId, parsedBoardOps, { forceSessionOnly: autoPilot })
|
|
4091
6250
|
: []
|
|
4092
6251
|
|
|
4093
|
-
const
|
|
6252
|
+
const unmetMustDo = Array.isArray(parsed.unmetMustDo)
|
|
6253
|
+
? parsed.unmetMustDo.map(x => clamp(String(x || '').trim(), 140)).filter(Boolean).slice(0, 6)
|
|
6254
|
+
: []
|
|
6255
|
+
const hazardInfo = detectEmergencyHazardFallback({
|
|
6256
|
+
parsed,
|
|
6257
|
+
digestText: digest.text,
|
|
6258
|
+
bounds,
|
|
6259
|
+
isInterventionActive: Boolean(tactical.intervention || autoPilot),
|
|
6260
|
+
})
|
|
6261
|
+
const hasObjectiveTarget = Boolean(board && String(board.objective || '').trim())
|
|
6262
|
+
const evalGoalCompletion = isGoalMode || (Boolean(tactical.intervention) && hasObjectiveTarget)
|
|
6263
|
+
const isGoalAchieved = !hazardInfo.triggered
|
|
6264
|
+
&& evalGoalCompletion
|
|
6265
|
+
&& String(parsed.goalStatus || '') === 'achieved'
|
|
6266
|
+
&& unmetMustDo.length === 0
|
|
4094
6267
|
let goalProposalCreated = false
|
|
4095
|
-
if (isGoalAchieved && deps.runAction) {
|
|
6268
|
+
if (isGoalAchieved && deps.runAction && hasObjectiveTarget) {
|
|
4096
6269
|
const existingApproval = board && board.goalApproval
|
|
4097
6270
|
const alreadyPendingSame = existingApproval
|
|
4098
6271
|
&& existingApproval.status === 'pending'
|
|
@@ -4101,7 +6274,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4101
6274
|
const propRes = deps.runAction({
|
|
4102
6275
|
action: 'goal.proposeApproval',
|
|
4103
6276
|
objective: board.objective || '',
|
|
4104
|
-
summary: cleanMultiline(parsed.goalSummary || '
|
|
6277
|
+
summary: cleanMultiline(parsed.goalSummary || '核心目标及必做事项验证均已完成,建议结项。', 320),
|
|
4105
6278
|
evidence: cleanMultiline(parsed.goalEvidence || '', 420),
|
|
4106
6279
|
session: rootId,
|
|
4107
6280
|
by: 'DSH 参谋长',
|
|
@@ -4112,16 +6285,44 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4112
6285
|
|
|
4113
6286
|
let circuitTripped = false
|
|
4114
6287
|
let circuitReason = ''
|
|
6288
|
+
let hazardStopped = false
|
|
6289
|
+
let hazardAlertCreated = null
|
|
4115
6290
|
let interventionMessage = ''
|
|
4116
6291
|
const autoRelays = []
|
|
6292
|
+
const autoBoundUpdates = []
|
|
6293
|
+
let shouldAutoOrganizeSession = false
|
|
6294
|
+
|
|
6295
|
+
const isInternalRelayTarget = (targetRaw) => {
|
|
6296
|
+
const tq = String(targetRaw || '').trim().replace(/^@/, '')
|
|
6297
|
+
if (!tq) return false
|
|
6298
|
+
const lower = tq.toLowerCase()
|
|
6299
|
+
if (['lead', 'main', '主对话', '主代理'].includes(lower)) return true
|
|
6300
|
+
return realPeers.some(p =>
|
|
6301
|
+
p.kind !== 'peer-session'
|
|
6302
|
+
&& p.kind !== 'session'
|
|
6303
|
+
&& (p.key === tq || p.handle === tq || p.id === tq || p.name === tq)
|
|
6304
|
+
)
|
|
6305
|
+
}
|
|
4117
6306
|
|
|
4118
6307
|
mutateChiefState((s) => {
|
|
4119
6308
|
const ws = ensureWorkspace(s, rootId)
|
|
4120
6309
|
ws.reviewCursors[cursorKey] = digest.stamp
|
|
4121
|
-
|
|
6310
|
+
if (autoPilot) {
|
|
6311
|
+
ws.runtimeGuard.autoPilotHadTurn = true
|
|
6312
|
+
}
|
|
6313
|
+
const activeCluster = getLinkedCluster(s, rootId)
|
|
6314
|
+
applyFactChanges(ws, numberedFacts, parsed.memoryChanges, speaker, {
|
|
6315
|
+
originRootId: rootId,
|
|
6316
|
+
peerRootIds: activeCluster.filter(id => id !== rootId),
|
|
6317
|
+
})
|
|
4122
6318
|
|
|
4123
6319
|
// Goal achieved: create user approval suggestion pill (NEVER exit goal mode automatically!)
|
|
4124
6320
|
if (isGoalAchieved) {
|
|
6321
|
+
const goalSig = crypto
|
|
6322
|
+
.createHash('sha1')
|
|
6323
|
+
.update(String((board && board.objective) || '') + '|' + String(parsed.goalEvidence || parsed.goalSummary || ''))
|
|
6324
|
+
.digest('hex')
|
|
6325
|
+
.slice(0, 12)
|
|
4125
6326
|
const hasPendingGoalSug = ws.suggestions.some(
|
|
4126
6327
|
sug => sug.status === 'pending' && sug.kind === 'goal_approval',
|
|
4127
6328
|
)
|
|
@@ -4129,36 +6330,58 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4129
6330
|
const goalSug = normalizeSuggestion({
|
|
4130
6331
|
kind: 'goal_approval',
|
|
4131
6332
|
fromAgent: '🎯 目标督导参谋',
|
|
4132
|
-
title: '🎯
|
|
4133
|
-
reason: cleanMultiline(parsed.goalSummary || '
|
|
6333
|
+
title: '🎯 核心目标与必做事项已达成,请示批准结项',
|
|
6334
|
+
reason: cleanMultiline(parsed.goalSummary || '主对话已完成当前设定核心目标及全部必做事项,请批示是否结束督导。', 220),
|
|
4134
6335
|
evidence: cleanMultiline(parsed.goalEvidence || '', 480),
|
|
4135
6336
|
target: 'board',
|
|
4136
6337
|
targetLabel: '目标结项',
|
|
4137
6338
|
mode: 'silent',
|
|
4138
|
-
draftText: cleanMultiline(parsed.goalSummary || '
|
|
6339
|
+
draftText: cleanMultiline(parsed.goalSummary || '批准结项并退出督导模式', 400),
|
|
4139
6340
|
})
|
|
4140
6341
|
if (goalSug) ws.suggestions.push(goalSug)
|
|
4141
6342
|
}
|
|
6343
|
+
if (ws.runtimeGuard.lastGoalAchievedSig !== goalSig) {
|
|
6344
|
+
ws.runtimeGuard.lastGoalAchievedSig = goalSig
|
|
6345
|
+
ws.chat.push({
|
|
6346
|
+
id: nextId('chat'),
|
|
6347
|
+
role: 'chief',
|
|
6348
|
+
text: `- 【🎯 核心目标已达成 · 停止继续推送】${cleanMultiline(parsed.goalSummary || '核心目标与必做事项均已完成并核验通过。', 260)}`,
|
|
6349
|
+
actions: ['目标达成收口'],
|
|
6350
|
+
at: Date.now(),
|
|
6351
|
+
})
|
|
6352
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
6353
|
+
}
|
|
4142
6354
|
}
|
|
4143
6355
|
|
|
4144
6356
|
for (const sug of rawSuggestions) {
|
|
4145
6357
|
if (sug.kind === 'bound') {
|
|
4146
6358
|
const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
|
|
4147
6359
|
if (colList.some(x => String(x).trim() === sug.draftText)) continue
|
|
6360
|
+
if (autoPilot && sug.draftText) {
|
|
6361
|
+
// Auto-pilot mode: strictly apply bounds into THIS session only (pinned: false), NEVER touch global!
|
|
6362
|
+
sug.pinGlobal = false
|
|
6363
|
+
sug.status = 'applied'
|
|
6364
|
+
autoBoundUpdates.push({ field: sug.boundField, item: sug.draftText })
|
|
6365
|
+
continue
|
|
6366
|
+
}
|
|
4148
6367
|
}
|
|
4149
|
-
if (autoPilot && sug.kind === 'relay' && sug.draftText) {
|
|
6368
|
+
if (autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
4150
6369
|
sug.status = 'applied'
|
|
4151
6370
|
autoRelays.push(sug)
|
|
4152
6371
|
} else {
|
|
4153
6372
|
const dup = ws.suggestions.some(
|
|
4154
6373
|
existing => existing.status === 'pending'
|
|
4155
6374
|
&& existing.kind === sug.kind
|
|
4156
|
-
&& (sug.kind === 'bound'
|
|
6375
|
+
&& (sug.kind === 'bound'
|
|
6376
|
+
? existing.draftText === sug.draftText
|
|
6377
|
+
: (sug.kind === 'advice'
|
|
6378
|
+
? (existing.title === sug.title && existing.draftText === sug.draftText)
|
|
6379
|
+
: (existing.target === sug.target && existing.title === sug.title))),
|
|
4157
6380
|
)
|
|
4158
6381
|
if (!dup) {
|
|
4159
6382
|
const pending = ws.suggestions.filter(item => item.status === 'pending')
|
|
4160
6383
|
if (pending.length >= 5) {
|
|
4161
|
-
const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval') || pending[0]
|
|
6384
|
+
const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval' && item.kind !== 'advice') || pending[0]
|
|
4162
6385
|
victim.status = 'dismissed'
|
|
4163
6386
|
}
|
|
4164
6387
|
ws.suggestions.push(sug)
|
|
@@ -4166,10 +6389,58 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4166
6389
|
}
|
|
4167
6390
|
}
|
|
4168
6391
|
|
|
4169
|
-
|
|
4170
|
-
|
|
4171
|
-
|
|
4172
|
-
|
|
6392
|
+
if (autoPilot && rootId && rootId !== 'global') {
|
|
6393
|
+
const lastOrgAt = Number(ws.runtimeGuard.lastAutoArchiveOrgAt || 0)
|
|
6394
|
+
if (!lastOrgAt || Date.now() - lastOrgAt > 180_000) {
|
|
6395
|
+
shouldAutoOrganizeSession = true
|
|
6396
|
+
}
|
|
6397
|
+
}
|
|
6398
|
+
|
|
6399
|
+
// 0) Emergency hazard / boundary-collision gate takes highest priority under Strong Intervention
|
|
6400
|
+
if (hazardInfo.triggered && (tactical.intervention || autoPilot)) {
|
|
6401
|
+
hazardStopped = true
|
|
6402
|
+
circuitTripped = true
|
|
6403
|
+
circuitReason = hazardInfo.reason || hazardInfo.title
|
|
6404
|
+
if (!ws.config || typeof ws.config !== 'object') ws.config = resolveWorkspaceConfig(s, rootId)
|
|
6405
|
+
ws.config.tacticalModes = {
|
|
6406
|
+
...normalizeTacticalModes(ws.config.tacticalModes),
|
|
6407
|
+
intervention: false,
|
|
6408
|
+
}
|
|
6409
|
+
s.config.tacticalModes = {
|
|
6410
|
+
...normalizeTacticalModes(s.config.tacticalModes),
|
|
6411
|
+
intervention: false,
|
|
6412
|
+
}
|
|
6413
|
+
hazardAlertCreated = {
|
|
6414
|
+
id: nextId('hazard'),
|
|
6415
|
+
category: hazardInfo.category || 'irreversible_risk',
|
|
6416
|
+
title: hazardInfo.title || '强介入紧急煞车 · 已停止推进',
|
|
6417
|
+
reason: hazardInfo.reason || '继续推进可能造成不可逆损失或必然撞穿工作边界,已立即停止强介入。',
|
|
6418
|
+
objective: clamp((board && board.objective) || '', 300),
|
|
6419
|
+
at: Date.now(),
|
|
6420
|
+
}
|
|
6421
|
+
ws.runtimeGuard.hazardAlert = hazardAlertCreated
|
|
6422
|
+
ws.runtimeGuard.circuitBroken = true
|
|
6423
|
+
ws.runtimeGuard.circuitReason = hazardAlertCreated.reason
|
|
6424
|
+
ws.runtimeGuard.interventionTurns = 0
|
|
6425
|
+
ws.runtimeGuard.unchangedCount = 0
|
|
6426
|
+
interventionMessage = ''
|
|
6427
|
+
ws.chat.push({
|
|
6428
|
+
id: nextId('chat'),
|
|
6429
|
+
role: 'chief',
|
|
6430
|
+
text: `- 【🚨 紧急煞车 · 强介入已停】${hazardAlertCreated.title}\n 理由:${hazardAlertCreated.reason}`,
|
|
6431
|
+
actions: ['高危急停'],
|
|
6432
|
+
at: Date.now(),
|
|
6433
|
+
})
|
|
6434
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
6435
|
+
} else {
|
|
6436
|
+
// Intervention Supervisor follow-up + Circuit Breaker
|
|
6437
|
+
const unmetMustDoFallback = unmetMustDo.length > 0
|
|
6438
|
+
? '当前尚有以下【必做事项】未确认交付或缺少验证证据,请逐项补齐并交卷:\n' + unmetMustDo.map((u, idx) => `${idx + 1}. ${u}`).join('\n')
|
|
6439
|
+
: ''
|
|
6440
|
+
const candidateIntervention = parsed.interventionText
|
|
6441
|
+
|| unmetMustDoFallback
|
|
6442
|
+
|| (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
|
|
6443
|
+
if (!isGoalAchieved && tactical.intervention && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress' || unmetMustDo.length > 0) && candidateIntervention) {
|
|
4173
6444
|
const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
|
|
4174
6445
|
const sig = crypto
|
|
4175
6446
|
.createHash('sha1')
|
|
@@ -4188,13 +6459,15 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4188
6459
|
? (ws.runtimeGuard.unchangedCount + 1)
|
|
4189
6460
|
: 1
|
|
4190
6461
|
const nextTurns = ws.runtimeGuard.interventionTurns + 1
|
|
4191
|
-
const
|
|
6462
|
+
const isUnlimitedTurns = tactical.maxInterventionTurns === 0
|
|
6463
|
+
const maxTurns = isUnlimitedTurns ? Infinity : Math.max(1, Number(tactical.maxInterventionTurns) || 10)
|
|
6464
|
+
const unchangedLimit = isUnlimitedTurns ? 8 : 3
|
|
4192
6465
|
|
|
4193
|
-
if (nextTurns > maxTurns || nextUnchanged >=
|
|
6466
|
+
if ((!isUnlimitedTurns && nextTurns > maxTurns) || nextUnchanged >= unchangedLimit) {
|
|
4194
6467
|
circuitTripped = true
|
|
4195
|
-
circuitReason = nextTurns > maxTurns
|
|
6468
|
+
circuitReason = !isUnlimitedTurns && nextTurns > maxTurns
|
|
4196
6469
|
? `接管督导连续介入已达上限 (${maxTurns} 轮),触发安全熔断,已自动退回人工监督。`
|
|
4197
|
-
:
|
|
6470
|
+
: `连续 ${unchangedLimit} 轮检测进展无实质变化,触发死循环熔断,已自动关闭接管督导并交还用户控制。`
|
|
4198
6471
|
if (!ws.config || typeof ws.config !== 'object') ws.config = resolveWorkspaceConfig(s, rootId)
|
|
4199
6472
|
ws.config.tacticalModes = {
|
|
4200
6473
|
...normalizeTacticalModes(ws.config.tacticalModes),
|
|
@@ -4225,8 +6498,72 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4225
6498
|
interventionMessage = cleanMultiline(candidateIntervention, tactical.conciseBrief ? 420 : 1200)
|
|
4226
6499
|
}
|
|
4227
6500
|
}
|
|
6501
|
+
}
|
|
4228
6502
|
})
|
|
4229
6503
|
|
|
6504
|
+
if (hazardStopped && deps && typeof deps.cancelAutoContinue === 'function') {
|
|
6505
|
+
try { deps.cancelAutoContinue(sid, 'hazard-stop') } catch {}
|
|
6506
|
+
if (rootId && rootId !== sid) {
|
|
6507
|
+
try { deps.cancelAutoContinue(rootId, 'hazard-stop') } catch {}
|
|
6508
|
+
}
|
|
6509
|
+
}
|
|
6510
|
+
|
|
6511
|
+
// When both Smart Compact & Intervention trigger on the same turn, harvest + compact FIRST,
|
|
6512
|
+
// then deliver intervention followup into the freshly compacted context!
|
|
6513
|
+
let smartCompacted = false
|
|
6514
|
+
if (smartCoManaged && parsed.shouldCompactNow === true && typeof deps.compactSessionNow === 'function') {
|
|
6515
|
+
const wsNow = ensureWorkspace(loadChiefState(), rootId)
|
|
6516
|
+
const lastCompactedAt = (wsNow.runtimeGuard && wsNow.runtimeGuard.lastCompactedAt) || 0
|
|
6517
|
+
const sinceLast = Date.now() - lastCompactedAt
|
|
6518
|
+
if (force || !lastCompactedAt || sinceLast >= 20_000) {
|
|
6519
|
+
const compactReason = clamp(parsed.compactReason || '参谋长评估当前阶段已收口,执行智选归档压缩', 220)
|
|
6520
|
+
let st = 'idle'
|
|
6521
|
+
try { if (typeof deps.getAgentStatus === 'function') st = deps.getAgentStatus(sid) || 'idle' } catch {}
|
|
6522
|
+
if (st === 'running' && !force && typeof deps.getAgentStatus === 'function') {
|
|
6523
|
+
await waitUntilAgentIdle(() => deps.getAgentStatus(sid), 8_000, 200)
|
|
6524
|
+
try { st = deps.getAgentStatus(sid) || 'idle' } catch {}
|
|
6525
|
+
}
|
|
6526
|
+
if (st === 'running' && !force) {
|
|
6527
|
+
mutateChiefState((s) => {
|
|
6528
|
+
const ws = ensureWorkspace(s, rootId)
|
|
6529
|
+
ws.runtimeGuard.pendingSmartCompact = { at: Date.now(), reason: compactReason, by: 'chief' }
|
|
6530
|
+
})
|
|
6531
|
+
} else {
|
|
6532
|
+
const contextWindow = Math.max(1000, Number(liveUsage && liveUsage.contextWindow) || 128_000)
|
|
6533
|
+
const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
|
|
6534
|
+
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.stamp || 0))
|
|
6535
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
6536
|
+
const cRes = await executeHarvestAndCompact(deps, {
|
|
6537
|
+
sid,
|
|
6538
|
+
rootId,
|
|
6539
|
+
agent,
|
|
6540
|
+
reason: compactReason,
|
|
6541
|
+
seq,
|
|
6542
|
+
ratioPct,
|
|
6543
|
+
totalTokens,
|
|
6544
|
+
contextWindow,
|
|
6545
|
+
logLabel: '✦ 智选压缩(参谋长判断)',
|
|
6546
|
+
}).catch((err) => {
|
|
6547
|
+
const msg = (err && err.message) || String(err || 'smart-compact-error')
|
|
6548
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
6549
|
+
deps.appendBoardLog(rootId, `⚠️ ✦ 智选压缩失败:${msg}`, 'chief')
|
|
6550
|
+
}
|
|
6551
|
+
return { ok: false, error: msg }
|
|
6552
|
+
})
|
|
6553
|
+
if (cRes && cRes.ok && !cRes.noop) {
|
|
6554
|
+
smartCompacted = true
|
|
6555
|
+
recordSmartCompactionChatReceipt(rootId, {
|
|
6556
|
+
cRes,
|
|
6557
|
+
ratioPct,
|
|
6558
|
+
totalTokens,
|
|
6559
|
+
contextWindow,
|
|
6560
|
+
via: '✦ 智选压缩',
|
|
6561
|
+
})
|
|
6562
|
+
}
|
|
6563
|
+
}
|
|
6564
|
+
}
|
|
6565
|
+
}
|
|
6566
|
+
|
|
4230
6567
|
if (interventionMessage) {
|
|
4231
6568
|
const tags = [
|
|
4232
6569
|
tactical.strictVerify ? '严格校验实测' : '',
|
|
@@ -4243,6 +6580,42 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4243
6580
|
})
|
|
4244
6581
|
}
|
|
4245
6582
|
|
|
6583
|
+
if (autoBoundUpdates.length > 0 && deps.runAction) {
|
|
6584
|
+
for (const b of autoBoundUpdates) {
|
|
6585
|
+
deps.runAction({
|
|
6586
|
+
action: 'bounds.add',
|
|
6587
|
+
field: b.field,
|
|
6588
|
+
item: b.item,
|
|
6589
|
+
pinned: false,
|
|
6590
|
+
session: rootId,
|
|
6591
|
+
by: 'DSH 参谋长 (全自动托管)',
|
|
6592
|
+
})
|
|
6593
|
+
executedOps.push(`本局自动边界(${b.field}):${clamp(b.item, 32)}`)
|
|
6594
|
+
}
|
|
6595
|
+
}
|
|
6596
|
+
|
|
6597
|
+
if (shouldAutoOrganizeSession && rootId && rootId !== 'global') {
|
|
6598
|
+
try {
|
|
6599
|
+
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
6600
|
+
const stSess = loadArchiveStore(sessOpt)
|
|
6601
|
+
const unorgCount = (stSess.items || []).filter(
|
|
6602
|
+
it => it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1,
|
|
6603
|
+
).length
|
|
6604
|
+
if (unorgCount >= 3) {
|
|
6605
|
+
mutateChiefState((s) => {
|
|
6606
|
+
const ws = ensureWorkspace(s, rootId)
|
|
6607
|
+
ws.runtimeGuard.lastAutoArchiveOrgAt = Date.now()
|
|
6608
|
+
})
|
|
6609
|
+
await organizeArchivesWithChief(deps, {
|
|
6610
|
+
sessionId: rootId,
|
|
6611
|
+
vaultScope: 'session',
|
|
6612
|
+
scope: 'unorganized',
|
|
6613
|
+
instruction: '全自动托管轮后整理本会话未归档记录(仅限本会话)',
|
|
6614
|
+
}).catch(() => null)
|
|
6615
|
+
}
|
|
6616
|
+
} catch {}
|
|
6617
|
+
}
|
|
6618
|
+
|
|
4246
6619
|
for (const sug of autoRelays) {
|
|
4247
6620
|
await deliverCrossMessage(deps, {
|
|
4248
6621
|
fromSession: rootId,
|
|
@@ -4254,16 +6627,160 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
4254
6627
|
})
|
|
4255
6628
|
}
|
|
4256
6629
|
|
|
6630
|
+
let autoPilotStopRes = null
|
|
6631
|
+
if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
|
|
6632
|
+
autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
6633
|
+
allowStartupGrace: false,
|
|
6634
|
+
directory,
|
|
6635
|
+
fromViewCheck: false,
|
|
6636
|
+
}).catch(() => null)
|
|
6637
|
+
}
|
|
6638
|
+
|
|
4257
6639
|
return {
|
|
4258
6640
|
ok: true,
|
|
4259
6641
|
executedOps,
|
|
4260
6642
|
isStalePlan,
|
|
6643
|
+
unmetMustDo,
|
|
4261
6644
|
goalAchieved: isGoalAchieved,
|
|
4262
6645
|
goalProposalCreated,
|
|
6646
|
+
hazardStopped,
|
|
6647
|
+
...(hazardAlertCreated ? { hazardAlert: hazardAlertCreated } : {}),
|
|
4263
6648
|
intervened: Boolean(interventionMessage),
|
|
6649
|
+
smartCompacted,
|
|
4264
6650
|
circuitTripped,
|
|
4265
6651
|
circuitReason,
|
|
6652
|
+
...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
|
|
6653
|
+
}
|
|
6654
|
+
}
|
|
6655
|
+
|
|
6656
|
+
/**
|
|
6657
|
+
* Anti-idle safeguard for session-scoped Full Auto-Pilot (`paceMode === 'auto'`):
|
|
6658
|
+
* Once Lead and all real non-probe child subagents within THIS session finish working AND
|
|
6659
|
+
* the closing narrative digest has finished catching up, automatically stand down to `manual`
|
|
6660
|
+
* so Chief never idles/spins indefinitely after work completes.
|
|
6661
|
+
*/
|
|
6662
|
+
export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
6663
|
+
const sidRaw = String(sessionId || '').trim()
|
|
6664
|
+
const rootId = String(
|
|
6665
|
+
(deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sidRaw) : sidRaw) || sidRaw || '',
|
|
6666
|
+
).trim()
|
|
6667
|
+
if (!rootId || rootId === 'global') {
|
|
6668
|
+
return { ok: true, stopped: false, reason: 'not-session' }
|
|
6669
|
+
}
|
|
6670
|
+
|
|
6671
|
+
const stBefore = loadChiefState()
|
|
6672
|
+
const effBefore = resolveWorkspaceConfig(stBefore, rootId)
|
|
6673
|
+
const wsBefore = ensureWorkspace(stBefore, rootId)
|
|
6674
|
+
if (effBefore.stopped || effBefore.paceMode !== 'auto' || !effBefore.autoPilot) {
|
|
6675
|
+
return { ok: true, stopped: false, reason: 'not-autopilot' }
|
|
6676
|
+
}
|
|
6677
|
+
if (reviewTimers.has(rootId)) {
|
|
6678
|
+
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
6679
|
+
}
|
|
6680
|
+
|
|
6681
|
+
const hasRunningInSession = (dirObj) => {
|
|
6682
|
+
try {
|
|
6683
|
+
if (deps && typeof deps.getAgentStatus === 'function' && deps.getAgentStatus(rootId) === 'running') {
|
|
6684
|
+
return true
|
|
6685
|
+
}
|
|
6686
|
+
} catch {}
|
|
6687
|
+
try {
|
|
6688
|
+
const agentsMap = deps && deps.runtime && typeof deps.runtime.get === 'function'
|
|
6689
|
+
? deps.runtime.get('agents')
|
|
6690
|
+
: null
|
|
6691
|
+
if (agentsMap && typeof agentsMap[Symbol.iterator] === 'function') {
|
|
6692
|
+
for (const item of agentsMap) {
|
|
6693
|
+
const ag = Array.isArray(item) ? item[1] : item
|
|
6694
|
+
if (!ag || typeof ag !== 'object') continue
|
|
6695
|
+
const agSid = String(ag.id || '').trim()
|
|
6696
|
+
if (!agSid) continue
|
|
6697
|
+
const agRoot = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(agSid, ag) : '') || agSid
|
|
6698
|
+
if (agRoot !== rootId) continue
|
|
6699
|
+
const agName = String(ag.name || ag.handle || '')
|
|
6700
|
+
if (/^mnemon-(?:review|run)/i.test(agName)) continue
|
|
6701
|
+
if (ag.status === 'running') return true
|
|
6702
|
+
}
|
|
6703
|
+
}
|
|
6704
|
+
} catch {}
|
|
6705
|
+
const targets = dirObj && Array.isArray(dirObj.targets) ? dirObj.targets : []
|
|
6706
|
+
for (const t of targets) {
|
|
6707
|
+
if (!t || t.kind === 'peer-session' || t.kind === 'session') continue
|
|
6708
|
+
if (t.rootId && t.rootId !== rootId) continue
|
|
6709
|
+
const tName = String(t.name || t.handle || '')
|
|
6710
|
+
if (/^mnemon-(?:review|run)/i.test(tName)) continue
|
|
6711
|
+
if (t.status === 'running') return true
|
|
6712
|
+
}
|
|
6713
|
+
return false
|
|
6714
|
+
}
|
|
6715
|
+
|
|
6716
|
+
const dirInitial = opts.directory || (deps ? await listPeerDirectory(deps, rootId) : { targets: [] })
|
|
6717
|
+
if (hasRunningInSession(dirInitial)) {
|
|
6718
|
+
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
6719
|
+
}
|
|
6720
|
+
|
|
6721
|
+
if (opts.allowStartupGrace !== false) {
|
|
6722
|
+
const startedAt = Number((wsBefore.runtimeGuard && wsBefore.runtimeGuard.autoPilotStartedAt) || 0)
|
|
6723
|
+
const hadTurn = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.autoPilotHadTurn)
|
|
6724
|
+
if (!hadTurn && startedAt > 0 && Date.now() - startedAt < 15_000) {
|
|
6725
|
+
return { ok: true, stopped: false, reason: 'startup-grace' }
|
|
6726
|
+
}
|
|
6727
|
+
}
|
|
6728
|
+
|
|
6729
|
+
if (opts.currentFresh !== true && deps) {
|
|
6730
|
+
const preView = await getChiefView(deps, rootId, {
|
|
6731
|
+
regenerate: false,
|
|
6732
|
+
autoSummarize: false,
|
|
6733
|
+
_skipAutoPilotCheck: true,
|
|
6734
|
+
}).catch(() => null)
|
|
6735
|
+
const nar = preView && preView.narrative
|
|
6736
|
+
if (nar && nar.hasUnsummarizedChanges && !nar.fresh) {
|
|
6737
|
+
if (nar.summarizing) {
|
|
6738
|
+
return { ok: true, stopped: false, reason: 'summarizing' }
|
|
6739
|
+
}
|
|
6740
|
+
if (preView.models && preView.models.available && !summarizingLocks.has(rootId)) {
|
|
6741
|
+
await getChiefView(deps, rootId, {
|
|
6742
|
+
regenerate: true,
|
|
6743
|
+
autoSummarize: false,
|
|
6744
|
+
_skipAutoPilotCheck: true,
|
|
6745
|
+
}).catch(() => null)
|
|
6746
|
+
}
|
|
6747
|
+
}
|
|
6748
|
+
}
|
|
6749
|
+
|
|
6750
|
+
if (reviewTimers.has(rootId)) {
|
|
6751
|
+
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
6752
|
+
}
|
|
6753
|
+
const dirFinal = deps ? await listPeerDirectory(deps, rootId) : dirInitial
|
|
6754
|
+
if (hasRunningInSession(dirFinal)) {
|
|
6755
|
+
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
4266
6756
|
}
|
|
6757
|
+
|
|
6758
|
+
let stoppedNow = false
|
|
6759
|
+
mutateChiefState((s) => {
|
|
6760
|
+
const ws = ensureWorkspace(s, rootId)
|
|
6761
|
+
const effNow = resolveWorkspaceConfig(s, rootId)
|
|
6762
|
+
if (effNow.stopped || effNow.paceMode !== 'auto' || !effNow.autoPilot) return
|
|
6763
|
+
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
|
|
6764
|
+
ws.config.paceMode = 'manual'
|
|
6765
|
+
ws.config.autoPilot = false
|
|
6766
|
+
ws.config.autoReview = false
|
|
6767
|
+
if (s.config && s.config.paceMode === 'auto') {
|
|
6768
|
+
s.config.paceMode = 'manual'
|
|
6769
|
+
s.config.autoPilot = false
|
|
6770
|
+
s.config.autoReview = false
|
|
6771
|
+
}
|
|
6772
|
+
ws.chat.push({
|
|
6773
|
+
id: nextId('chat'),
|
|
6774
|
+
role: 'chief',
|
|
6775
|
+
text: '- 【⚡→⏸️ 防空转自动收工】本会话主代理与子代理均已结束任务且阶段摘要已收口,已自动退出「全自动托管」退回按需手动,随时可再次手动开启。',
|
|
6776
|
+
actions: ['防空转收工'],
|
|
6777
|
+
at: Date.now(),
|
|
6778
|
+
})
|
|
6779
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
6780
|
+
stoppedNow = true
|
|
6781
|
+
})
|
|
6782
|
+
|
|
6783
|
+
return { ok: true, stopped: stoppedNow, reason: stoppedNow ? 'idle-completed' : 'already-stopped' }
|
|
4267
6784
|
}
|
|
4268
6785
|
|
|
4269
6786
|
export async function handleSuggestionDecision(deps, { sessionId, suggestionId, decision, editedText, boundField, pinGlobal }) {
|
|
@@ -4279,10 +6796,14 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
|
|
|
4279
6796
|
if (!found) return { ok: false, error: '未找到该请示或建议卡片' }
|
|
4280
6797
|
|
|
4281
6798
|
if (decision === 'approve' && found.kind === 'bound') {
|
|
4282
|
-
const
|
|
4283
|
-
|
|
4284
|
-
|
|
4285
|
-
const
|
|
6799
|
+
const rawBf = String(boundField || '').trim().toLowerCase()
|
|
6800
|
+
const normBf = rawBf === 'must' ? 'allowed' : rawBf
|
|
6801
|
+
const rawFoundBf = String(found.boundField || '').trim().toLowerCase()
|
|
6802
|
+
const normFoundBf = rawFoundBf === 'must' ? 'allowed' : rawFoundBf
|
|
6803
|
+
const col = ['forbidden', 'allowed', 'notes'].includes(normBf)
|
|
6804
|
+
? normBf
|
|
6805
|
+
: (['forbidden', 'allowed', 'notes'].includes(normFoundBf) ? normFoundBf : 'forbidden')
|
|
6806
|
+
const BOUND_COL_LABEL = { forbidden: '禁止红线', allowed: '必做事项', notes: '注意事项' }
|
|
4286
6807
|
const colLabel = BOUND_COL_LABEL[col] || '禁止红线'
|
|
4287
6808
|
const ruleText = clamp(editedText || found.draftText || found.title, 220)
|
|
4288
6809
|
if (!ruleText) return { ok: false, error: '边界条文不能为空' }
|
|
@@ -4318,11 +6839,17 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
|
|
|
4318
6839
|
// Broadcast a silent boundary decree so running lead/subagents immediately see the new rule on next pre-step
|
|
4319
6840
|
mutateChiefState((state) => {
|
|
4320
6841
|
const ws = ensureWorkspace(state, rootId)
|
|
6842
|
+
const cluster = getLinkedCluster(state, rootId)
|
|
4321
6843
|
const decree = normalizeMail({
|
|
4322
6844
|
from: 'DSH 参谋长 (边界颁布)',
|
|
4323
|
-
fromSession: '',
|
|
6845
|
+
fromSession: rootId === 'global' ? '' : rootId,
|
|
6846
|
+
fromRootId: rootId === 'global' ? '' : rootId,
|
|
4324
6847
|
to: 'all',
|
|
4325
6848
|
toSession: 'all',
|
|
6849
|
+
toRootId: 'all',
|
|
6850
|
+
participantRoots: cluster,
|
|
6851
|
+
channelType: cluster.length > 1 ? 'broadcast' : 'internal',
|
|
6852
|
+
broadcastId: nextId('bcast'),
|
|
4326
6853
|
subject: `用户已批准${replaces.length ? `浓缩${colLabel}(${replaces.length} 合 1)` : `新${colLabel}`}`,
|
|
4327
6854
|
text: `- 【${colLabel} · ${scopeTag}】${shouldPin ? '📌 ' : ''}${ruleText}${replaces.length ? `\n- 【已整合替代】原 ${replaces.length} 条零散边界已合并为此条总则` : ''}${found.reason ? `\n- 【缘由】${found.reason}` : ''}\n请主代理与全体子代理自即刻起严格遵守!`,
|
|
4328
6855
|
mode: 'silent',
|
|
@@ -4368,18 +6895,26 @@ export async function handleSuggestionDecision(deps, { sessionId, suggestionId,
|
|
|
4368
6895
|
}
|
|
4369
6896
|
}
|
|
4370
6897
|
|
|
4371
|
-
if (decision === 'approve' && found.kind === 'relay') {
|
|
6898
|
+
if (decision === 'approve' && (found.kind === 'relay' || found.kind === 'advice')) {
|
|
4372
6899
|
const body = editedText ? cleanMultiline(editedText, 1200) : found.draftText
|
|
4373
|
-
const
|
|
4374
|
-
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
|
|
4378
|
-
|
|
4379
|
-
|
|
4380
|
-
|
|
6900
|
+
const deliverTarget = found.target || 'lead'
|
|
6901
|
+
const shouldDeliver = Boolean(body && deliverTarget !== 'none' && deliverTarget !== 'chief')
|
|
6902
|
+
const delivery = shouldDeliver
|
|
6903
|
+
? await deliverCrossMessage(deps, {
|
|
6904
|
+
fromSession: rootId,
|
|
6905
|
+
fromLabel: found.kind === 'advice' ? 'DSH 参谋长 (获批进言)' : 'DSH 参谋长 (获批建议)',
|
|
6906
|
+
target: deliverTarget,
|
|
6907
|
+
subject: found.title,
|
|
6908
|
+
text: body,
|
|
6909
|
+
mode: found.mode || (found.kind === 'advice' ? 'followup' : 'steer'),
|
|
6910
|
+
})
|
|
6911
|
+
: { ok: true, skippedDelivery: true }
|
|
6912
|
+
if (found.kind === 'advice' && typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
6913
|
+
deps.appendBoardLog(rootId, `💡 用户已拍板采纳参谋进言:${clamp(found.title, 40)}`, 'user')
|
|
6914
|
+
}
|
|
4381
6915
|
return {
|
|
4382
|
-
ok: delivery.ok,
|
|
6916
|
+
ok: delivery.ok !== false,
|
|
6917
|
+
adviceApplied: found.kind === 'advice',
|
|
4383
6918
|
delivery,
|
|
4384
6919
|
view: await getChiefView(deps, rootId, { autoSummarize: false }),
|
|
4385
6920
|
}
|
|
@@ -4398,6 +6933,25 @@ export function updateChiefConfig(patch) {
|
|
|
4398
6933
|
const ws = sid ? ensureWorkspace(state, sid) : null
|
|
4399
6934
|
const effBefore = resolveWorkspaceConfig(state, sid)
|
|
4400
6935
|
const prevTactical = normalizeTacticalModes(effBefore.tacticalModes)
|
|
6936
|
+
if (typeof safePatch.ackHazardAlertId === 'string' && safePatch.ackHazardAlertId.trim()) {
|
|
6937
|
+
const ackId = safePatch.ackHazardAlertId.trim()
|
|
6938
|
+
if (ws && ws.runtimeGuard && ws.runtimeGuard.hazardAlert && (ackId === '*' || ws.runtimeGuard.hazardAlert.id === ackId)) {
|
|
6939
|
+
ws.runtimeGuard.hazardAlert = null
|
|
6940
|
+
}
|
|
6941
|
+
const hasOtherKeys = Object.keys(safePatch).some(
|
|
6942
|
+
k => k !== 'sessionId' && k !== 'session' && k !== 'ackHazardAlertId',
|
|
6943
|
+
)
|
|
6944
|
+
if (!hasOtherKeys) {
|
|
6945
|
+
const curCfg = resolveWorkspaceConfig(state, sid)
|
|
6946
|
+
return {
|
|
6947
|
+
ok: true,
|
|
6948
|
+
clearedHazardAlert: true,
|
|
6949
|
+
config: { ...curCfg, tacticalModes: { ...curCfg.tacticalModes } },
|
|
6950
|
+
runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
|
|
6951
|
+
}
|
|
6952
|
+
}
|
|
6953
|
+
}
|
|
6954
|
+
|
|
4401
6955
|
if (safePatch.emergencyStopIntervention === true) {
|
|
4402
6956
|
if (ws) {
|
|
4403
6957
|
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
|
|
@@ -4406,6 +6960,7 @@ export function updateChiefConfig(patch) {
|
|
|
4406
6960
|
ws.runtimeGuard.unchangedCount = 0
|
|
4407
6961
|
ws.runtimeGuard.circuitBroken = false
|
|
4408
6962
|
ws.runtimeGuard.circuitReason = ''
|
|
6963
|
+
ws.runtimeGuard.hazardAlert = null
|
|
4409
6964
|
}
|
|
4410
6965
|
state.config.tacticalModes = { ...normalizeTacticalModes(state.config.tacticalModes), intervention: false }
|
|
4411
6966
|
const stoppedCfg = resolveWorkspaceConfig(state, sid)
|
|
@@ -4413,12 +6968,14 @@ export function updateChiefConfig(patch) {
|
|
|
4413
6968
|
ok: true,
|
|
4414
6969
|
emergencyStopped: true,
|
|
4415
6970
|
config: { ...stoppedCfg, tacticalModes: { ...stoppedCfg.tacticalModes } },
|
|
6971
|
+
runtimeGuard: ws ? { ...ws.runtimeGuard } : null,
|
|
4416
6972
|
}
|
|
4417
6973
|
}
|
|
4418
6974
|
|
|
4419
|
-
const
|
|
6975
|
+
const incomingTacticalRaw = safePatch.tacticalModes && typeof safePatch.tacticalModes === 'object'
|
|
4420
6976
|
? safePatch.tacticalModes
|
|
4421
6977
|
: null
|
|
6978
|
+
let incomingTactical = incomingTacticalRaw ? { ...incomingTacticalRaw } : null
|
|
4422
6979
|
if (incomingTactical && incomingTactical.intervention === true && !prevTactical.intervention) {
|
|
4423
6980
|
if (safePatch.confirmedInterventionRisk !== true) {
|
|
4424
6981
|
return {
|
|
@@ -4431,23 +6988,97 @@ export function updateChiefConfig(patch) {
|
|
|
4431
6988
|
ws.runtimeGuard.unchangedCount = 0
|
|
4432
6989
|
ws.runtimeGuard.circuitBroken = false
|
|
4433
6990
|
ws.runtimeGuard.circuitReason = ''
|
|
6991
|
+
ws.runtimeGuard.hazardAlert = null
|
|
6992
|
+
ws.runtimeGuard.lastGoalAchievedSig = ''
|
|
4434
6993
|
}
|
|
4435
6994
|
}
|
|
4436
6995
|
|
|
4437
|
-
const
|
|
6996
|
+
const wantsUnlimitedTurns = Boolean(
|
|
6997
|
+
incomingTactical
|
|
6998
|
+
&& (incomingTactical.maxInterventionTurns === 0 || incomingTactical.maxInterventionTurns === '0')
|
|
6999
|
+
)
|
|
7000
|
+
if (wantsUnlimitedTurns && prevTactical.maxInterventionTurns !== 0 && safePatch.confirmedUnlimitedTurns !== true) {
|
|
7001
|
+
return {
|
|
7002
|
+
ok: false,
|
|
7003
|
+
error: '切换至「♾️ 无限督导轮次」需先通过作者风险确认弹窗(confirmedUnlimitedTurns: true)',
|
|
7004
|
+
}
|
|
7005
|
+
}
|
|
7006
|
+
|
|
7007
|
+
const wantsAutoPilot = Boolean(
|
|
7008
|
+
safePatch.paceMode === 'auto'
|
|
7009
|
+
|| (typeof safePatch.paceMode !== 'string' && safePatch.stopped !== true && safePatch.autoPilot === true)
|
|
7010
|
+
)
|
|
7011
|
+
if (wantsAutoPilot && effBefore.paceMode !== 'auto' && safePatch.confirmedAutoPilot !== true) {
|
|
7012
|
+
return {
|
|
7013
|
+
ok: false,
|
|
7014
|
+
requireAutoPilotConfirm: true,
|
|
7015
|
+
error: '开启「⚡ 全自动托管」需先确认本会话自治范围与防空转退出弹窗(confirmedAutoPilot: true)',
|
|
7016
|
+
}
|
|
7017
|
+
}
|
|
7018
|
+
if (ws && wantsAutoPilot && effBefore.paceMode !== 'auto') {
|
|
7019
|
+
ws.runtimeGuard.autoPilotStartedAt = Date.now()
|
|
7020
|
+
ws.runtimeGuard.autoPilotHadTurn = false
|
|
7021
|
+
}
|
|
7022
|
+
|
|
7023
|
+
let compactLowWarning = ''
|
|
7024
|
+
if (incomingTactical && typeof incomingTactical.compactThresholdInput === 'string') {
|
|
7025
|
+
const parsedTok = parseCompactTokensInput(incomingTactical.compactThresholdInput)
|
|
7026
|
+
if (!parsedTok.ok) {
|
|
7027
|
+
return { ok: false, error: parsedTok.error }
|
|
7028
|
+
}
|
|
7029
|
+
incomingTactical.compactThresholdTokens = parsedTok.tokens
|
|
7030
|
+
incomingTactical.compactThresholdInput = parsedTok.displayInput
|
|
7031
|
+
compactLowWarning = parsedTok.lowWarning || ''
|
|
7032
|
+
} else if (incomingTactical && typeof incomingTactical.compactThresholdTokens === 'number') {
|
|
7033
|
+
const safeTok = Math.max(COMPACT_TOKEN_HARD_MIN, Math.round(incomingTactical.compactThresholdTokens))
|
|
7034
|
+
incomingTactical.compactThresholdTokens = safeTok
|
|
7035
|
+
incomingTactical.compactThresholdInput = formatCompactTokenShort(safeTok)
|
|
7036
|
+
if (safeTok < COMPACT_TOKEN_WARN_FLOOR) {
|
|
7037
|
+
compactLowWarning = `当前阈值(${incomingTactical.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
|
|
7038
|
+
}
|
|
7039
|
+
}
|
|
7040
|
+
|
|
7041
|
+
const applyPatchTo = (targetCfg, allowIntervention, allowAutoPilot = allowIntervention) => {
|
|
4438
7042
|
if (typeof safePatch.modelRef === 'string') targetCfg.modelRef = safePatch.modelRef.trim()
|
|
4439
|
-
if (typeof safePatch.
|
|
4440
|
-
targetCfg.
|
|
4441
|
-
|
|
4442
|
-
|
|
7043
|
+
if (typeof safePatch.permissionMode === 'string' && CHIEF_PERMISSION_MODES.includes(safePatch.permissionMode)) {
|
|
7044
|
+
targetCfg.permissionMode = normalizePermissionMode(safePatch.permissionMode)
|
|
7045
|
+
}
|
|
7046
|
+
if (typeof safePatch.paceMode === 'string' && ['manual', 'smart', 'auto', 'stopped'].includes(safePatch.paceMode)) {
|
|
7047
|
+
const nextPace = (!allowAutoPilot && safePatch.paceMode === 'auto') ? 'manual' : safePatch.paceMode
|
|
7048
|
+
targetCfg.paceMode = nextPace
|
|
7049
|
+
const isStopped = nextPace === 'stopped'
|
|
7050
|
+
targetCfg.stopped = isStopped
|
|
7051
|
+
targetCfg.autoPilot = !isStopped && nextPace === 'auto' && allowAutoPilot
|
|
7052
|
+
targetCfg.autoReview = !isStopped && nextPace !== 'manual'
|
|
7053
|
+
} else if (typeof safePatch.stopped === 'boolean') {
|
|
7054
|
+
targetCfg.stopped = safePatch.stopped
|
|
7055
|
+
if (safePatch.stopped) {
|
|
7056
|
+
targetCfg.paceMode = 'stopped'
|
|
7057
|
+
targetCfg.autoPilot = false
|
|
7058
|
+
targetCfg.autoReview = false
|
|
7059
|
+
} else {
|
|
7060
|
+
if (targetCfg.paceMode === 'stopped') targetCfg.paceMode = 'manual'
|
|
7061
|
+
if (!allowAutoPilot && targetCfg.paceMode === 'auto') targetCfg.paceMode = 'manual'
|
|
7062
|
+
targetCfg.autoPilot = targetCfg.paceMode === 'auto' && allowAutoPilot
|
|
7063
|
+
targetCfg.autoReview = targetCfg.paceMode !== 'manual'
|
|
7064
|
+
}
|
|
4443
7065
|
} else if (typeof safePatch.autoPilot === 'boolean') {
|
|
4444
|
-
|
|
4445
|
-
targetCfg.
|
|
4446
|
-
targetCfg.
|
|
7066
|
+
const nextAuto = Boolean(safePatch.autoPilot && allowAutoPilot)
|
|
7067
|
+
targetCfg.stopped = false
|
|
7068
|
+
targetCfg.paceMode = nextAuto ? 'auto' : 'manual'
|
|
7069
|
+
targetCfg.autoPilot = nextAuto
|
|
7070
|
+
targetCfg.autoReview = nextAuto
|
|
4447
7071
|
}
|
|
4448
|
-
if (
|
|
7072
|
+
if (!allowAutoPilot && targetCfg.paceMode === 'auto') {
|
|
7073
|
+
targetCfg.paceMode = 'manual'
|
|
7074
|
+
targetCfg.autoPilot = false
|
|
7075
|
+
}
|
|
7076
|
+
if (typeof safePatch.autoReview === 'boolean' && typeof safePatch.paceMode !== 'string' && typeof safePatch.stopped !== 'boolean') {
|
|
4449
7077
|
targetCfg.autoReview = safePatch.autoReview
|
|
4450
|
-
if (!safePatch.autoReview)
|
|
7078
|
+
if (!safePatch.autoReview) {
|
|
7079
|
+
targetCfg.stopped = false
|
|
7080
|
+
targetCfg.paceMode = 'manual'
|
|
7081
|
+
}
|
|
4451
7082
|
}
|
|
4452
7083
|
if (incomingTactical) {
|
|
4453
7084
|
const merged = normalizeTacticalModes({
|
|
@@ -4463,16 +7094,22 @@ export function updateChiefConfig(patch) {
|
|
|
4463
7094
|
|
|
4464
7095
|
if (ws) {
|
|
4465
7096
|
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effBefore }
|
|
4466
|
-
applyPatchTo(ws.config, true)
|
|
4467
|
-
// Keep global non-dangerous defaults aligned while NEVER leaking intervention globally!
|
|
4468
|
-
applyPatchTo(state.config, false)
|
|
7097
|
+
applyPatchTo(ws.config, true, true)
|
|
7098
|
+
// Keep global non-dangerous defaults aligned while NEVER leaking intervention or autoPilot globally!
|
|
7099
|
+
applyPatchTo(state.config, false, false)
|
|
4469
7100
|
} else {
|
|
4470
|
-
applyPatchTo(state.config, true)
|
|
7101
|
+
applyPatchTo(state.config, true, false)
|
|
4471
7102
|
}
|
|
4472
7103
|
|
|
4473
7104
|
const finalCfg = resolveWorkspaceConfig(state, sid)
|
|
7105
|
+
if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode === 'tokens' && finalCfg.tacticalModes.compactThresholdTokens < COMPACT_TOKEN_WARN_FLOOR) {
|
|
7106
|
+
compactLowWarning = `当前阈值(${finalCfg.tacticalModes.compactThresholdInput})低于安全建议线 32K,可能导致上下文频繁压缩丢失现场细节`
|
|
7107
|
+
} else if (!compactLowWarning && finalCfg.tacticalModes.compactThresholdMode !== 'tokens' && finalCfg.tacticalModes.compactThresholdPct < COMPACT_PCT_WARN_FLOOR) {
|
|
7108
|
+
compactLowWarning = `当前触发比例(${finalCfg.tacticalModes.compactThresholdPct}%)低于安全建议线 ${COMPACT_PCT_WARN_FLOOR}%,可能导致上下文频繁提前归档压缩`
|
|
7109
|
+
}
|
|
4474
7110
|
return {
|
|
4475
7111
|
ok: true,
|
|
7112
|
+
...(compactLowWarning ? { compactLowWarning } : {}),
|
|
4476
7113
|
config: { ...finalCfg, tacticalModes: { ...finalCfg.tacticalModes } },
|
|
4477
7114
|
}
|
|
4478
7115
|
})
|
|
@@ -4483,7 +7120,16 @@ export function mutateChiefFact(deps, { sessionId, op, id, text, category, pinne
|
|
|
4483
7120
|
return mutateChiefState((state) => {
|
|
4484
7121
|
const ws = ensureWorkspace(state, rootId)
|
|
4485
7122
|
if (op === 'add') {
|
|
4486
|
-
const
|
|
7123
|
+
const cat = category || 'discipline'
|
|
7124
|
+
const activeCluster = getLinkedCluster(state, rootId)
|
|
7125
|
+
const fact = normalizeFact({
|
|
7126
|
+
text,
|
|
7127
|
+
category: cat,
|
|
7128
|
+
by: 'user',
|
|
7129
|
+
pinned: Boolean(pinned),
|
|
7130
|
+
originRootId: rootId === 'global' ? '' : rootId,
|
|
7131
|
+
peerRootIds: cat === 'team' ? activeCluster.filter(pid => pid !== rootId) : [],
|
|
7132
|
+
})
|
|
4487
7133
|
if (!fact) return { ok: false, error: '条目无效或包含敏感凭据' }
|
|
4488
7134
|
ws.facts.push(fact)
|
|
4489
7135
|
if (ws.facts.length > FACTS_CAP) ws.facts = ws.facts.slice(-FACTS_CAP)
|
|
@@ -4548,3 +7194,299 @@ export function readMailboxForAgent(deps, { sessionId, callerAgent, unreadOnly =
|
|
|
4548
7194
|
})
|
|
4549
7195
|
return out.slice(-25)
|
|
4550
7196
|
}
|
|
7197
|
+
|
|
7198
|
+
const COMPACT_ADVISOR_SYSTEM = `你是 DSH 参谋长的「上下文与自动压缩策略顾问」。
|
|
7199
|
+
用户点击了「参谋智设」自动压缩阈值按钮。请结合当前会话的模型上下文窗口、固定开销(系统提示词 + 工具定义)、已用消息数以及当前任务复杂度,给出最合理的自动压缩触发阈值百分比(必须是 5 的倍数,且严格落在给定 [floorPct, 90] 安全区间内)。
|
|
7200
|
+
|
|
7201
|
+
设计原则:
|
|
7202
|
+
1. 若系统提示词+工具开销已经占用了较大比例,或上下文窗口 <= 200K,阈值绝对不能过低,否则连系统提示词都装不满就反复触发压缩,严重降智!
|
|
7203
|
+
2. 若上下文窗口极大(如 1M 上下文,固定开销只占 ~5%),可适当设低(如 25%~40%,即 250K~400K 左右)来保持模型注意力敏锐度与高速响应,同时留出充足工作空间。
|
|
7204
|
+
3. 请仅返回合法 JSON 对象:
|
|
7205
|
+
{
|
|
7206
|
+
"recommendedPct": 30,
|
|
7207
|
+
"reason": "当前 1M 窗口中固定开销约 52K(5%),30%(约 300K)既能维持长程理解又能防止注意力衰退。"
|
|
7208
|
+
}`
|
|
7209
|
+
|
|
7210
|
+
export async function recommendAndSetCompactThreshold(deps, { sessionId = '' } = {}) {
|
|
7211
|
+
const rootId = deps.resolveRootSessionId(sessionId) || String(sessionId || 'global')
|
|
7212
|
+
const rawUsage = typeof deps.measureSessionTokens === 'function'
|
|
7213
|
+
? await Promise.resolve(deps.measureSessionTokens(rootId))
|
|
7214
|
+
: null
|
|
7215
|
+
const usage = (rawUsage && typeof rawUsage === 'object') ? rawUsage : {}
|
|
7216
|
+
|
|
7217
|
+
const contextWindow = Math.max(32000, Number(usage.contextWindow) || 128000)
|
|
7218
|
+
const systemTokens = Math.max(0, Number(usage.systemTokens) || 0)
|
|
7219
|
+
const toolsTokens = Math.max(0, Number(usage.toolsTokens) || 0)
|
|
7220
|
+
const messageTokens = Math.max(0, Number(usage.messageTokens) || 0)
|
|
7221
|
+
const usedTokens = Math.max(0, Number(usage.usedTokens) || (systemTokens + toolsTokens + messageTokens))
|
|
7222
|
+
const overheadTokens = systemTokens + toolsTokens
|
|
7223
|
+
const modelRef = String(usage.modelRef || '').trim()
|
|
7224
|
+
|
|
7225
|
+
const minSafeTokens = Math.max(Math.round(overheadTokens * 2.2), overheadTokens + 45000, 48000)
|
|
7226
|
+
const rawFloorPct = Math.ceil(((minSafeTokens / contextWindow) * 100) / 5) * 5
|
|
7227
|
+
const floorPct = Math.min(85, Math.max(15, rawFloorPct))
|
|
7228
|
+
|
|
7229
|
+
const basePct = contextWindow >= 800000
|
|
7230
|
+
? 35
|
|
7231
|
+
: contextWindow >= 350000
|
|
7232
|
+
? 55
|
|
7233
|
+
: contextWindow >= 180000
|
|
7234
|
+
? 65
|
|
7235
|
+
: 75
|
|
7236
|
+
const heuristicPct = Math.min(90, Math.max(floorPct, basePct))
|
|
7237
|
+
|
|
7238
|
+
const fmtTok = (n) => {
|
|
7239
|
+
const v = Math.max(0, Math.round(Number(n) || 0))
|
|
7240
|
+
if (v >= 1000000) return `${(v / 1000000).toFixed(v % 1000000 === 0 ? 0 : 1)}M`
|
|
7241
|
+
if (v >= 1000) return `${Math.round(v / 1000)}K`
|
|
7242
|
+
return String(v)
|
|
7243
|
+
}
|
|
7244
|
+
|
|
7245
|
+
let finalPct = heuristicPct
|
|
7246
|
+
let llmGuided = false
|
|
7247
|
+
let reason = `当前窗口 ${fmtTok(contextWindow)}(系统与工具固定开销 ~${fmtTok(overheadTokens)}),已自动锁定在 ${finalPct}%(~${fmtTok((contextWindow * finalPct) / 100)}),兼顾推理深度与防劣化安全底线。`
|
|
7248
|
+
|
|
7249
|
+
const board = typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function'
|
|
7250
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
7251
|
+
: null
|
|
7252
|
+
const objective = board && board.objective ? clamp(board.objective, 160) : '(未设总目标)'
|
|
7253
|
+
const activeTaskCount = Array.isArray(board?.tasks)
|
|
7254
|
+
? board.tasks.filter(t => t && (t.status === 'doing' || t.status === 'todo' || t.status === 'blocked')).length
|
|
7255
|
+
: 0
|
|
7256
|
+
|
|
7257
|
+
try {
|
|
7258
|
+
const advisorPrompt = [
|
|
7259
|
+
`- 当前主对话模型: ${modelRef || '默认对话模型'}`,
|
|
7260
|
+
`- 上下文总窗口 (contextWindow): ${contextWindow} tokens (${fmtTok(contextWindow)})`,
|
|
7261
|
+
`- 系统提示词 (systemTokens): ${systemTokens} tokens (${fmtTok(systemTokens)})`,
|
|
7262
|
+
`- 工具定义 (toolsTokens): ${toolsTokens} tokens (${fmtTok(toolsTokens)})`,
|
|
7263
|
+
`- 固定开销合计 (overhead): ${overheadTokens} tokens (${((overheadTokens / contextWindow) * 100).toFixed(1)}%)`,
|
|
7264
|
+
`- 当前已用总上下文: ${usedTokens} tokens (${((usedTokens / contextWindow) * 100).toFixed(1)}%)`,
|
|
7265
|
+
`- 系统硬性安全下限 (floorPct): ${floorPct}% (~${fmtTok((contextWindow * floorPct) / 100)})`,
|
|
7266
|
+
`- 启发式基准建议: ${heuristicPct}%`,
|
|
7267
|
+
`- 当前任务目标: ${objective}(活跃任务 ${activeTaskCount} 项)`,
|
|
7268
|
+
'',
|
|
7269
|
+
`请给出 final recommendedPct(5 的倍数,范围 [${floorPct}, 90])与一句不超过 85 字的中文建议理由。`,
|
|
7270
|
+
].join('\n')
|
|
7271
|
+
|
|
7272
|
+
const llmRes = await callChiefLlm(deps, {
|
|
7273
|
+
sessionId: rootId,
|
|
7274
|
+
system: COMPACT_ADVISOR_SYSTEM,
|
|
7275
|
+
prompt: advisorPrompt,
|
|
7276
|
+
maxTokens: 320,
|
|
7277
|
+
})
|
|
7278
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
7279
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
7280
|
+
if (parsed && Number.isFinite(Number(parsed.recommendedPct))) {
|
|
7281
|
+
const snapped = Math.round(Number(parsed.recommendedPct) / 5) * 5
|
|
7282
|
+
finalPct = Math.min(90, Math.max(floorPct, snapped))
|
|
7283
|
+
if (typeof parsed.reason === 'string' && parsed.reason.trim()) {
|
|
7284
|
+
reason = clamp(parsed.reason.trim(), 180)
|
|
7285
|
+
}
|
|
7286
|
+
llmGuided = true
|
|
7287
|
+
}
|
|
7288
|
+
}
|
|
7289
|
+
} catch {}
|
|
7290
|
+
|
|
7291
|
+
updateChiefConfig({
|
|
7292
|
+
sessionId: rootId,
|
|
7293
|
+
tacticalModes: {
|
|
7294
|
+
compactThresholdPct: finalPct,
|
|
7295
|
+
autoCompact: true,
|
|
7296
|
+
},
|
|
7297
|
+
})
|
|
7298
|
+
|
|
7299
|
+
const view = await getChiefView(deps, rootId, { autoSummarize: false })
|
|
7300
|
+
return {
|
|
7301
|
+
ok: true,
|
|
7302
|
+
recommendedPct: finalPct,
|
|
7303
|
+
triggerTokens: Math.round((contextWindow * finalPct) / 100),
|
|
7304
|
+
overheadTokens,
|
|
7305
|
+
contextWindow,
|
|
7306
|
+
systemTokens,
|
|
7307
|
+
toolsTokens,
|
|
7308
|
+
messageTokens,
|
|
7309
|
+
usedTokens,
|
|
7310
|
+
floorPct,
|
|
7311
|
+
modelRef,
|
|
7312
|
+
llmGuided,
|
|
7313
|
+
reason,
|
|
7314
|
+
view,
|
|
7315
|
+
}
|
|
7316
|
+
}
|
|
7317
|
+
|
|
7318
|
+
const OBJECTIVE_SUGGEST_SYSTEM = [
|
|
7319
|
+
'你是「DSH 参谋长」(宰相级总目标顾问)。用户正准备开启「主动强介入模式」,需要锁定一条「核心目标」作为所有后续参谋介入判断与验收的唯一最终目的地。',
|
|
7320
|
+
'有两种协作模式,请严格遵循:',
|
|
7321
|
+
'1. `mode = "refine"`(微调已有文字):输入框中已有用户自己写下的核心目标草案。你必须在**严格尊重保留用户原有核心意图、主语、约束和具象锚点**的前提下,将其微调润色为一条表述更凝练、验收标准更清晰、适合强介入持续核验的一句话核心目标(不超过 120 字),严禁推翻或另起炉灶。',
|
|
7322
|
+
'2. `mode = "guess"`(建议 / 反复揣摩用户意图):用户未填写核心目标,或认为上一轮建议还不够贴切并**继续点击「建议」让你重新猜**。请综合当前主对话与子代理实时流、最新用户原始诉求、小任务板(Plan)、任务表、必做事项与近期结论,猜出用户此刻最核心的真实落地目标;**严禁与 `已给过的建议列表 (previousSuggestions)` 重复或仅换一两个虚词**,每次重猜都应尝试更贴合场景、不同切入维度或更具体可验收的表述(不超过 120 字)。',
|
|
7323
|
+
'',
|
|
7324
|
+
'只输出一个合法 JSON 对象:',
|
|
7325
|
+
'{',
|
|
7326
|
+
' "suggestion": "建议或微调后的核心目标一句话(≤120字,不要加引号或序号)",',
|
|
7327
|
+
' "rationale": "一句简明大白话说明为何这样拟定/微调(≤55字)"',
|
|
7328
|
+
'}',
|
|
7329
|
+
].join('\n')
|
|
7330
|
+
|
|
7331
|
+
/**
|
|
7332
|
+
* Suggest (with repeated intent guessing) or micro-tune an existing draft Core Objective
|
|
7333
|
+
* when enabling Strong Intervention mode.
|
|
7334
|
+
*/
|
|
7335
|
+
export async function suggestCoreObjectiveWithChief(deps, {
|
|
7336
|
+
sessionId = '',
|
|
7337
|
+
draft = '',
|
|
7338
|
+
mode = 'auto',
|
|
7339
|
+
previousSuggestions = [],
|
|
7340
|
+
} = {}) {
|
|
7341
|
+
const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : sessionId) || String(sessionId || 'global')
|
|
7342
|
+
const rawDraft = String(draft || '').replace(/\s+/g, ' ').trim()
|
|
7343
|
+
const prevList = (Array.isArray(previousSuggestions) ? previousSuggestions : [])
|
|
7344
|
+
.map(x => String(x || '').replace(/\s+/g, ' ').trim())
|
|
7345
|
+
.filter(Boolean)
|
|
7346
|
+
.slice(-12)
|
|
7347
|
+
|
|
7348
|
+
const normalizedDraft = rawDraft.toLowerCase()
|
|
7349
|
+
const isCycleOfPreviousAi = Boolean(
|
|
7350
|
+
rawDraft && prevList.some(p => p.toLowerCase() === normalizedDraft),
|
|
7351
|
+
)
|
|
7352
|
+
const effectiveMode = (mode === 'refine' || (mode === 'auto' && rawDraft && !isCycleOfPreviousAi))
|
|
7353
|
+
? 'refine'
|
|
7354
|
+
: 'guess'
|
|
7355
|
+
|
|
7356
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
7357
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
7358
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
7359
|
+
: null
|
|
7360
|
+
const liveDigest = collectLiveConversationsDigest(deps, rootId, directory)
|
|
7361
|
+
const state = loadChiefState()
|
|
7362
|
+
const view = clusterView(state, rootId)
|
|
7363
|
+
const numberedFacts = view.facts.slice(-8)
|
|
7364
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan.filter(Boolean) : []
|
|
7365
|
+
const openPlan = planSteps.filter(s => !s.done)
|
|
7366
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
7367
|
+
const activeTasks = tasks.filter(t => t && (t.status === 'doing' || t.status === 'todo' || t.status === 'blocked'))
|
|
7368
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
7369
|
+
const leadEntry = (liveDigest.entries || []).find(e => e.kind === 'lead') || (liveDigest.entries || [])[0] || null
|
|
7370
|
+
const latestUser = (leadEntry && leadEntry.lastUser) ? leadEntry.lastUser : ''
|
|
7371
|
+
const existingObj = board && board.objective ? String(board.objective).trim() : ''
|
|
7372
|
+
|
|
7373
|
+
// Build non-repeating deterministic fallback candidates ordered by attempt index
|
|
7374
|
+
const buildFallbackCandidate = () => {
|
|
7375
|
+
if (effectiveMode === 'refine' && rawDraft) {
|
|
7376
|
+
const cleanDraft = clamp(rawDraft.replace(/[。;;]+$/, ''), 96)
|
|
7377
|
+
const refined = /完成|实现|通过|验证|修复|交付|生成|输出/.test(cleanDraft)
|
|
7378
|
+
? `${cleanDraft},确保可实测验收后收尾`
|
|
7379
|
+
: `完成「${cleanDraft}」并完成实测核验`
|
|
7380
|
+
return {
|
|
7381
|
+
suggestion: clamp(refined, 120),
|
|
7382
|
+
rationale: '已保留您原有核心意图,并补充清晰的可验收收口标准。',
|
|
7383
|
+
}
|
|
7384
|
+
}
|
|
7385
|
+
|
|
7386
|
+
const candidates = []
|
|
7387
|
+
if (latestUser) {
|
|
7388
|
+
candidates.push({
|
|
7389
|
+
suggestion: clamp(`彻底完成用户当前诉求「${clamp(latestUser, 72)}」并经实测核验交付`, 120),
|
|
7390
|
+
rationale: '根据主对话最近一次真实诉求提炼的核心目标。',
|
|
7391
|
+
})
|
|
7392
|
+
}
|
|
7393
|
+
if (openPlan.length > 0) {
|
|
7394
|
+
candidates.push({
|
|
7395
|
+
suggestion: clamp(`按小任务板推进完成:${openPlan.slice(0, 2).map(s => clamp(s.text, 38)).join(' → ')}`, 120),
|
|
7396
|
+
rationale: '聚焦小任务板当前尚未勾选的待办节点。',
|
|
7397
|
+
})
|
|
7398
|
+
}
|
|
7399
|
+
if (activeTasks.length > 0) {
|
|
7400
|
+
candidates.push({
|
|
7401
|
+
suggestion: clamp(`攻克在手关键任务(${activeTasks.slice(0, 2).map(t => clamp(t.title, 36)).join('、')})并通过验证`, 120),
|
|
7402
|
+
rationale: '围绕目前推进中与待办的核心任务收敛目标。',
|
|
7403
|
+
})
|
|
7404
|
+
}
|
|
7405
|
+
if (existingObj) {
|
|
7406
|
+
candidates.push({
|
|
7407
|
+
suggestion: clamp(`${existingObj.replace(/[。;;]+$/, '')},完成全部必做事项与实证验收`, 120),
|
|
7408
|
+
rationale: '在当前规划核心目标基础上强化完结验收基准。',
|
|
7409
|
+
})
|
|
7410
|
+
}
|
|
7411
|
+
if (bounds.allowed && bounds.allowed.length > 0) {
|
|
7412
|
+
candidates.push({
|
|
7413
|
+
suggestion: clamp(`推进完成本轮主线研发与交付(必做:${clamp(bounds.allowed[0], 55)})`, 120),
|
|
7414
|
+
rationale: '结合当前必做事项清单拟定的可监督落地目标。',
|
|
7415
|
+
})
|
|
7416
|
+
}
|
|
7417
|
+
if (leadEntry && leadEntry.lastAssistant) {
|
|
7418
|
+
candidates.push({
|
|
7419
|
+
suggestion: clamp(`收口当前主线工作(${clamp(leadEntry.lastAssistant, 68)})并验证通过`, 120),
|
|
7420
|
+
rationale: '结合主对话最新工作现场推断的收尾目标。',
|
|
7421
|
+
})
|
|
7422
|
+
}
|
|
7423
|
+
candidates.push(
|
|
7424
|
+
{
|
|
7425
|
+
suggestion: '完整实现本轮设定功能需求、完成自测校验并清晰交付最终结果',
|
|
7426
|
+
rationale: '通用端到端实现与实测交付目标。',
|
|
7427
|
+
},
|
|
7428
|
+
{
|
|
7429
|
+
suggestion: '排查解决当前阻断卡点与遗留缺陷,确保系统运行稳定并通过复测',
|
|
7430
|
+
rationale: '偏向排查修复与稳定收口的兜底目标。',
|
|
7431
|
+
},
|
|
7432
|
+
)
|
|
7433
|
+
|
|
7434
|
+
const prevNormSet = new Set(prevList.map(x => x.toLowerCase()))
|
|
7435
|
+
const chosen = candidates.find(c => !prevNormSet.has(String(c.suggestion || '').toLowerCase()))
|
|
7436
|
+
|| candidates[prevList.length % candidates.length]
|
|
7437
|
+
return chosen
|
|
7438
|
+
}
|
|
7439
|
+
|
|
7440
|
+
const promptLines = [
|
|
7441
|
+
`当前执行模式: ${effectiveMode === 'refine' ? 'refine(在用户已有核心目标文字上微调润色)' : 'guess(结合现场上下文猜想用户想要的核心目标,允许反复点建议继续猜)'}`,
|
|
7442
|
+
`工作区当前已填核心目标: ${existingObj || '(空)'}`,
|
|
7443
|
+
...(rawDraft ? [`用户输入框当前文字: ${rawDraft}`] : ['用户输入框当前文字: (空)']),
|
|
7444
|
+
...(prevList.length > 0 ? [`已给过的建议(严禁重复或仅微调措辞,须从新角度继续猜):\n${prevList.map((p, i) => ` ${i + 1}. ${p}`).join('\n')}`] : []),
|
|
7445
|
+
`主对话最近用户原始诉求: ${latestUser || '(暂未捕捉)'}`,
|
|
7446
|
+
`小任务板 (Plan) 未完步骤: ${openPlan.slice(0, 4).map(s => clamp(s.text, 60)).join(';') || '(无)'}`,
|
|
7447
|
+
`在手任务 (doing/blocked/todo): ${activeTasks.slice(0, 5).map(t => `[${t.status}] ${clamp(t.title, 48)}`).join(';') || '(无)'}`,
|
|
7448
|
+
`必做事项 (allowed): ${(bounds.allowed || []).slice(0, 4).join(';') || '(无)'}`,
|
|
7449
|
+
`禁止红线 (forbidden): ${(bounds.forbidden || []).slice(0, 4).join(';') || '(无)'}`,
|
|
7450
|
+
`主对话现场摘要: ${leadEntry ? clamp(leadEntry.lastAssistant || '', 260) : '(无)'}`,
|
|
7451
|
+
...(numberedFacts.length ? [`近期重要结论: ${numberedFacts.slice(-4).map(f => clamp(f.text, 90)).join(';')}`] : []),
|
|
7452
|
+
]
|
|
7453
|
+
|
|
7454
|
+
let suggestion = ''
|
|
7455
|
+
let rationale = ''
|
|
7456
|
+
let llmUsed = false
|
|
7457
|
+
|
|
7458
|
+
try {
|
|
7459
|
+
const llmRes = await callChiefLlm(deps, {
|
|
7460
|
+
sessionId: rootId,
|
|
7461
|
+
system: OBJECTIVE_SUGGEST_SYSTEM,
|
|
7462
|
+
prompt: promptLines.join('\n'),
|
|
7463
|
+
maxTokens: 320,
|
|
7464
|
+
})
|
|
7465
|
+
if (llmRes && llmRes.ok && llmRes.text) {
|
|
7466
|
+
const parsed = extractJsonObject(llmRes.text)
|
|
7467
|
+
if (parsed && typeof parsed.suggestion === 'string' && parsed.suggestion.trim()) {
|
|
7468
|
+
const cleaned = cleanMultiline(stripToolCallMarkup(parsed.suggestion), 160).replace(/\s+/g, ' ').trim()
|
|
7469
|
+
const isDuplicateGuess = effectiveMode === 'guess' && prevList.some(p => p.toLowerCase() === cleaned.toLowerCase())
|
|
7470
|
+
if (cleaned && !isDuplicateGuess) {
|
|
7471
|
+
suggestion = clamp(cleaned, 120)
|
|
7472
|
+
rationale = clamp(String(parsed.rationale || '').trim(), 90)
|
|
7473
|
+
llmUsed = true
|
|
7474
|
+
}
|
|
7475
|
+
}
|
|
7476
|
+
}
|
|
7477
|
+
} catch {}
|
|
7478
|
+
|
|
7479
|
+
if (!suggestion) {
|
|
7480
|
+
const fb = buildFallbackCandidate()
|
|
7481
|
+
suggestion = fb.suggestion
|
|
7482
|
+
rationale = fb.rationale
|
|
7483
|
+
}
|
|
7484
|
+
|
|
7485
|
+
return {
|
|
7486
|
+
ok: true,
|
|
7487
|
+
suggestion,
|
|
7488
|
+
rationale: rationale || (effectiveMode === 'refine' ? '已在您原文基础上完成微调。' : '已结合当前对话态势为您揣摩建议。'),
|
|
7489
|
+
mode: effectiveMode,
|
|
7490
|
+
llmUsed,
|
|
7491
|
+
}
|
|
7492
|
+
}
|