dsh-chief 1.2.0 → 1.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +51 -0
- package/README.en.md +28 -13
- package/README.md +27 -12
- package/api-routes.js +1274 -0
- package/archive-cabinets.js +766 -0
- package/archive-core.js +761 -0
- package/archive-dossiers.js +1185 -0
- package/archive-precipitated.js +428 -0
- package/archives.js +63 -2991
- package/auto-continue.js +11 -1
- package/board-actions.js +1879 -0
- package/board-schema.js +580 -0
- package/board-store.js +392 -0
- package/chief-approvals.js +841 -0
- package/chief-archives.js +905 -0
- package/chief-commands.js +2513 -0
- package/chief-compaction.js +591 -0
- package/chief-executor.js +859 -153
- package/chief-models.js +578 -0
- package/chief-network.js +720 -0
- package/chief-review.js +1064 -0
- package/chief-state.js +1777 -0
- package/chief-view.js +553 -0
- package/chief.js +94 -7492
- package/client.js +11959 -10923
- package/digest.js +8 -8
- package/index.js +154 -6095
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/model-tools.js +755 -0
- package/package.json +48 -17
- package/runtime-hooks.js +629 -0
- package/subagent-runtime.js +1399 -0
package/chief-review.js
ADDED
|
@@ -0,0 +1,1064 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chief-review.js
|
|
3
|
+
*
|
|
4
|
+
* Post-turn background review, emergency hazard guard, and idle Auto-Pilot stop control for DSH Chief.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import crypto from 'node:crypto'
|
|
8
|
+
import { loadArchiveStore } from './archives.js'
|
|
9
|
+
import { normalizePermissionMode, permissionRank } from './chief-executor.js'
|
|
10
|
+
import {
|
|
11
|
+
CHAT_CAP,
|
|
12
|
+
REVIEW_DELAY_MS,
|
|
13
|
+
SMART_REVIEW_COOLDOWN_MS,
|
|
14
|
+
AUTO_REVIEW_COOLDOWN_MS,
|
|
15
|
+
SUMMARY_MAX_TOKENS,
|
|
16
|
+
archiveTargetForRoot,
|
|
17
|
+
nextId,
|
|
18
|
+
clamp,
|
|
19
|
+
cleanMultiline,
|
|
20
|
+
hasValidChiefRiskAck,
|
|
21
|
+
pushAuditToWs,
|
|
22
|
+
normalizeSuggestion,
|
|
23
|
+
resolveWorkspaceConfig,
|
|
24
|
+
normalizeTacticalModes,
|
|
25
|
+
queueChiefApproval,
|
|
26
|
+
loadChiefState,
|
|
27
|
+
mutateChiefState,
|
|
28
|
+
getLinkedCluster,
|
|
29
|
+
ensureWorkspace,
|
|
30
|
+
clusterView,
|
|
31
|
+
isInternalCheckpointNoise,
|
|
32
|
+
extractJsonObject,
|
|
33
|
+
} from './chief-state.js'
|
|
34
|
+
import { listChiefModels, callChiefLlm } from './chief-models.js'
|
|
35
|
+
import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
36
|
+
import { summarizingLocks, getChiefView, registerIdleAutoPilotHook } from './chief-view.js'
|
|
37
|
+
import { organizeArchivesWithChief } from './chief-archives.js'
|
|
38
|
+
import {
|
|
39
|
+
waitUntilAgentIdle,
|
|
40
|
+
measureAgentSessionTokensFallback,
|
|
41
|
+
recordSmartCompactionChatReceipt,
|
|
42
|
+
executeHarvestAndCompact,
|
|
43
|
+
maybeRunPreCompaction,
|
|
44
|
+
} from './chief-compaction.js'
|
|
45
|
+
import { applyFactChanges, applyBoardOps } from './chief-commands.js'
|
|
46
|
+
|
|
47
|
+
const TURN_REVIEW_SYSTEM = [
|
|
48
|
+
'你是「DSH 参谋长」(宰相级协同与督导中枢)的后台复盘与督导模块。某个对话刚结束一轮输出。',
|
|
49
|
+
'请阅读最新对话片段、工作区核心目标、计划步骤、团队状态、生效边界(🚫 禁止红线 / ✅ 必做事项 / 💡 注意事项)、持久记忆与当前开启的战术开关,只输出一个 JSON 对象:',
|
|
50
|
+
'',
|
|
51
|
+
'1. `memoryChanges`:仅当出现跨轮次持久有效的规矩、分工、关键架构结论或踩坑教训时才新增/修订/删除;普通干活过程返回 `[]`。严禁保存密码或密钥。',
|
|
52
|
+
'2. `boardOps`:若发现当前 `计划步骤 (Plan)` 明显仍对应旧需求/与最新 `总目标 (Objective)` 严重脱节(stale plan),务必输出 `{ "op": "plan.resetForGoal" }` 或 `{ "op": "plan.set", "steps": [...] }` 自动修正计划;也可更新 `task.update` / `cursor.set`。注意:当 `INTERVENTION_SUPERVISOR` 开启时,核心目标已锁定,严禁输出 `objective.set` 擅改目标!',
|
|
53
|
+
'3. `planAssessment`:`{ "stale": true|false, "reason": "…" }`,指明当前计划步骤是否与总目标失配陈旧。',
|
|
54
|
+
'4. `goalStatus` 与 `unmetMustDo`:当开启 `GOAL_MODE` 或 `INTERVENTION_SUPERVISOR`(主动强介入)时重点评估,取值 `"in_progress" | "achieved" | "blocked"`。',
|
|
55
|
+
' - **核心目标目的地铁律**:只要 `工作区核心目标 (Objective)` 非空,主动强介入的所有介入判断**一律以该核心目标有无完成作为最终目的地**(仅当核心目标为空时才退回对照最新用户原始诉求)。',
|
|
56
|
+
' - **必做事项核验铁律**:`已有工作边界` 中的 `必做事项 (allowed)` 为硬性交付清单!在主对话/子代理交上来的作业未完成任何一条适用必做事项或缺少对应交付/验证证据前,**必须将未完成项逐条写入 `unmetMustDo` 数组,并保持 `goalStatus: "in_progress"` 与 `shouldIntervene: true`**(严禁判为 `"achieved"`)!',
|
|
57
|
+
' - 仅当核心目标与全部适用必做事项均已完成并有实证支撑时,才可设 `goalStatus: "achieved"`(并填 `goalSummary` 与 `goalEvidence`);否则填 `goalMissing`。',
|
|
58
|
+
'5. `hazardStop`(**强介入紧急安全煞车与撞边界熔断 · 最高优先级,优先于一切续推!**):',
|
|
59
|
+
' - `{ "triggered": false, "category": "none|irreversible_risk|boundary_collision", "title": "", "reason": "" }`',
|
|
60
|
+
' - 当 `INTERVENTION_SUPERVISOR` 或 `AUTO_PILOT_SESSION_ONLY` 开启时,你必须严密审查:主/子代理刚刚提出、准备执行、请求用户拍板,或接下来继续推进是否**存在重大不可逆风险,或继续推进必然会撞穿当前生效边界(尤其 🚫 禁止红线)**?',
|
|
61
|
+
' - **重要提示(下列仅是常见举例,绝不限于此!)**:包括但不限于实际花钱/扣费/下单/付费 API 调用、不可逆删除或清空文件/数据/仓库、下载超大文件占用巨额磁盘或流量、关闭/重启服务器或关键宿主服务、对外公开推送/发布不可撤回变更、破坏宿主机隔离边界、以及任何一旦继续推跑就会导致不可逆损失或必然撞穿红线的情形。',
|
|
62
|
+
' - 一旦命中任一上述风险或必然撞边界:**必须立即设 `"hazardStop": { "triggered": true, "category": "...", "title": "简短醒目告警标题", "reason": "用清晰人话说清具体会造成什么不可逆损失或必然撞上哪条边界,以及为何必须立即停下等用户处理" }`,并强制设 `"shouldIntervene": false`、`interventionText: ""`**(严禁再推下一轮!)。',
|
|
63
|
+
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false`、主代理停下时,对照「核心目标 + 必做事项 + 最新用户诉求」逐项核验!只要目标或必做事项尚未真正做完、缺少实测验证证据却自称完成,必须设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或正在等待子代理回信时,设 `shouldIntervene: false`。',
|
|
64
|
+
'7. `suggestions`(最多 1 条,宁缺毋滥):',
|
|
65
|
+
' - `"kind": "bound"`:明显撞墙或发现长期红线/必做规矩时请示注入边界;',
|
|
66
|
+
' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议;',
|
|
67
|
+
' - `"kind": "advice"`:当主模型陷入明显可替代方案、环境坑点或需提醒用户拍板的关键决策时提出一句话建议,可带 `"popup": true|false`(仅关键分叉/阻塞决策设 `true`)。',
|
|
68
|
+
'8. `shouldCompactNow` & `compactReason`:仅当 `SMART_COMPACT_CO_MANAGED`(✦ 智选)启用时评估!此时硬性上下文阈值已退让为辅助,由你与主会话共同把控压缩时机:只要一个完整阶段目标刚刚收口、工作流切换阶段、出现大量重复试错/工具噪音日志、或上下文估算已达 ≥30% 且适合归档脱水时,果断设 `shouldCompactNow: true` 并填写一句话 `compactReason`;仅在刚起步或上下文极轻时保持 `false`。',
|
|
69
|
+
'9. `AUTO_PILOT_SESSION_ONLY`(全自动托管安全边界):当激活标志包含 `AUTO_PILOT_SESSION_ONLY` 时,所有自动决策仅限本对话会话内部!严禁将本会话规律生成 `"pinGlobal": true` 的全局定住边界,严禁跨出本对话去篡改全局档案柜或无关独立窗口;发现跨窗口传递信息时可留待人工审批。',
|
|
70
|
+
'',
|
|
71
|
+
'输出格式(严格 JSON):',
|
|
72
|
+
'{',
|
|
73
|
+
' "memoryChanges": [{ "op": "add", "category": "discipline|architecture|progress|preference|team", "text": "…" }],',
|
|
74
|
+
' "boardOps": [],',
|
|
75
|
+
' "planAssessment": { "stale": false, "reason": "" },',
|
|
76
|
+
' "goalStatus": "in_progress",',
|
|
77
|
+
' "goalSummary": "",',
|
|
78
|
+
' "goalEvidence": "",',
|
|
79
|
+
' "goalMissing": "",',
|
|
80
|
+
' "unmetMustDo": [],',
|
|
81
|
+
' "hazardStop": { "triggered": false, "category": "none", "title": "", "reason": "" },',
|
|
82
|
+
' "shouldIntervene": false,',
|
|
83
|
+
' "interventionText": "",',
|
|
84
|
+
' "shouldCompactNow": false,',
|
|
85
|
+
' "compactReason": "",',
|
|
86
|
+
' "suggestions": []',
|
|
87
|
+
'}',
|
|
88
|
+
].join('\n')
|
|
89
|
+
|
|
90
|
+
/** High-precision backup safety net if the turn-review model missed `hazardStop.triggered` despite unmistakable irreversible hazard or boundary collision cues. */
|
|
91
|
+
function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, isInterventionActive = false }) {
|
|
92
|
+
const rawHs = parsed && parsed.hazardStop && typeof parsed.hazardStop === 'object' ? parsed.hazardStop : null
|
|
93
|
+
if (rawHs && rawHs.triggered === true && (rawHs.reason || rawHs.title)) {
|
|
94
|
+
return {
|
|
95
|
+
triggered: true,
|
|
96
|
+
category: clamp(rawHs.category || 'irreversible_risk', 40) || 'irreversible_risk',
|
|
97
|
+
title: clamp(rawHs.title || '强介入安全煞车 · 已自动停止', 120),
|
|
98
|
+
reason: cleanMultiline(rawHs.reason || rawHs.title || '继续推进存在不可逆重大风险或必然撞穿边界,已暂停强介入并等待您的指示。', 520),
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (!isInterventionActive) {
|
|
102
|
+
return { triggered: false, category: 'none', title: '', reason: '' }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const assistantParts = String(digestText || '').split(/(?:^|\n)Assistant:\s*/)
|
|
106
|
+
const lastAssistant = assistantParts.length > 1 ? assistantParts[assistantParts.length - 1] : String(digestText || '')
|
|
107
|
+
const reviewNotes = `${String(parsed?.goalMissing || '')}\n${String(parsed?.interventionText || '')}`
|
|
108
|
+
|
|
109
|
+
if (String(parsed?.goalStatus || '') === 'blocked' && /(?:不可逆|重大损失|撞[^\n。]{0,8}(?:红线|边界)|违反[^\n。]{0,8}禁止|花钱|扣费|付费|下单|删库|永久删除|大文件|关闭服务器|停服|破坏宿主机)/.test(reviewNotes)) {
|
|
110
|
+
return {
|
|
111
|
+
triggered: true,
|
|
112
|
+
category: /红线|边界|禁止/.test(reviewNotes) ? 'boundary_collision' : 'irreversible_risk',
|
|
113
|
+
title: /红线|边界|禁止/.test(reviewNotes) ? '继续推进将撞穿工作边界 · 已急停' : '检测到重大不可逆风险 · 已急停',
|
|
114
|
+
reason: cleanMultiline(parsed.goalMissing || parsed.interventionText || '继续推进可能导致不可逆损失或触犯工作边界,已立即停止主动强介入。', 520),
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const askHighRiskConfirmRe = /(?:需要|请)(?:您|用户)?(?:亲自|人工|手动)?(?:确认|授权|拍板|批准)[^\n。]{0,50}(?:花钱|扣费|付款|付费|下单|充值|永久删除|清空目录|格式化|关闭服务器|停服|重启宿主|下载[^\n。]{0,20}(?:GB|大文件)|不可逆)/i
|
|
119
|
+
const mConfirm = lastAssistant.match(askHighRiskConfirmRe)
|
|
120
|
+
if (mConfirm) {
|
|
121
|
+
return {
|
|
122
|
+
triggered: true,
|
|
123
|
+
category: 'irreversible_risk',
|
|
124
|
+
title: '高危/不可逆操作等待用户拍板 · 已急停',
|
|
125
|
+
reason: cleanMultiline(`主对话提示需要您确认高风险操作(${mConfirm[0]}),为防止造成不可逆损失,已自动停止强介入推跑。`, 520),
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
const forbiddenList = Array.isArray(bounds && bounds.forbidden) ? bounds.forbidden : []
|
|
130
|
+
if (forbiddenList.length > 0 && /(?:继续[^\n。]{0,12}(?:必|将|会)[^\n。]{0,10}(?:触犯|违反|撞上)|已触及[^\n。]{0,8}禁止红线|必然撞边界)/.test(reviewNotes)) {
|
|
131
|
+
return {
|
|
132
|
+
triggered: true,
|
|
133
|
+
category: 'boundary_collision',
|
|
134
|
+
title: '继续推进必然撞穿禁止红线 · 已急停',
|
|
135
|
+
reason: cleanMultiline(reviewNotes, 520),
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
return { triggered: false, category: 'none', title: '', reason: '' }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const reviewTimers = new Map()
|
|
143
|
+
|
|
144
|
+
function extractLatestTurnDigest(agent, turn) {
|
|
145
|
+
if (!agent || !agent.session) return null
|
|
146
|
+
try {
|
|
147
|
+
if (typeof agent.session.deriveMessages === 'function') {
|
|
148
|
+
const msgs = agent.session.deriveMessages() || []
|
|
149
|
+
let latestUserPrompt = ''
|
|
150
|
+
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
|
151
|
+
const um = msgs[i]
|
|
152
|
+
if (!um || um.role !== 'user') continue
|
|
153
|
+
if (um.source && um.source.kind && um.source.kind !== 'user') continue
|
|
154
|
+
const uBlocks = Array.isArray(um.content) ? um.content : []
|
|
155
|
+
const uTxt = uBlocks
|
|
156
|
+
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
157
|
+
.map(b => b.text)
|
|
158
|
+
.join('\n')
|
|
159
|
+
.trim()
|
|
160
|
+
if (uTxt && !isInternalCheckpointNoise(uTxt)) {
|
|
161
|
+
latestUserPrompt = clamp(uTxt, 1000)
|
|
162
|
+
break
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const tail = msgs.slice(-6)
|
|
167
|
+
const lines = []
|
|
168
|
+
let hasUser = false
|
|
169
|
+
for (const m of tail) {
|
|
170
|
+
if (!m || !m.role) continue
|
|
171
|
+
if (m.source && m.source.kind && m.source.kind !== 'user' && m.role === 'user') continue
|
|
172
|
+
const blocks = Array.isArray(m.content) ? m.content : []
|
|
173
|
+
const txt = blocks
|
|
174
|
+
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
175
|
+
.map(b => b.text)
|
|
176
|
+
.join('\n')
|
|
177
|
+
.trim()
|
|
178
|
+
if (!txt || isInternalCheckpointNoise(txt)) continue
|
|
179
|
+
if (m.role === 'user') {
|
|
180
|
+
hasUser = true
|
|
181
|
+
lines.push('User: ' + clamp(txt, 1200))
|
|
182
|
+
} else if (m.role === 'assistant') {
|
|
183
|
+
lines.push('Assistant: ' + clamp(txt, 900))
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (lines.length > 0) return { text: lines.join('\n'), hasUser, latestUserPrompt, stamp: msgs.length }
|
|
187
|
+
}
|
|
188
|
+
} catch {}
|
|
189
|
+
return null
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const lastReviewAtByRoot = new Map()
|
|
193
|
+
|
|
194
|
+
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
195
|
+
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
196
|
+
if (!sid) return
|
|
197
|
+
// Never waste tokens reviewing internal mnemon checkpoint / probe subagents
|
|
198
|
+
if (/^mnemon-(?:review|run)/i.test(sid) || /^mnemon-(?:review|run)/i.test(String((agent && agent.name) || ''))) {
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
const state = loadChiefState()
|
|
202
|
+
const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
203
|
+
const effCfg = resolveWorkspaceConfig(state, rootKey)
|
|
204
|
+
const paceMode = effCfg.paceMode || 'manual'
|
|
205
|
+
if (effCfg.stopped || paceMode === 'stopped') {
|
|
206
|
+
clearTimeout(reviewTimers.get(rootKey))
|
|
207
|
+
reviewTimers.delete(rootKey)
|
|
208
|
+
return
|
|
209
|
+
}
|
|
210
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
211
|
+
const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
|
|
212
|
+
const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
|
|
213
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
214
|
+
? deps.boardForSession(deps.boardFileFor(rootKey))
|
|
215
|
+
: null
|
|
216
|
+
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
217
|
+
const hasHighPriorityChannel = isGoalMode || tactical.autoCompact || tactical.smartCompact || pendingSmart || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify
|
|
218
|
+
|
|
219
|
+
// Default 'manual' mode without tactical/goal active: ZERO background LLM calls!
|
|
220
|
+
if (!hasHighPriorityChannel && (paceMode === 'manual' || effCfg.autoReview === false)) return
|
|
221
|
+
|
|
222
|
+
clearTimeout(reviewTimers.get(rootKey))
|
|
223
|
+
const delayMs = hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS
|
|
224
|
+
const timer = setTimeout(() => {
|
|
225
|
+
reviewTimers.delete(rootKey)
|
|
226
|
+
runTurnReview(deps, { agent, sessionId: sid, turn }).catch(() => {})
|
|
227
|
+
}, delayMs)
|
|
228
|
+
timer.unref?.()
|
|
229
|
+
reviewTimers.set(rootKey, timer)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
export async function runTurnReview(deps, { agent, sessionId, turn, force = false }) {
|
|
233
|
+
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
234
|
+
if (!sid) return { ok: false, skipped: 'no-session' }
|
|
235
|
+
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, agent)) || sid
|
|
236
|
+
|
|
237
|
+
const stateBefore = loadChiefState()
|
|
238
|
+
const effCfgBefore = resolveWorkspaceConfig(stateBefore, rootId)
|
|
239
|
+
const tactical = normalizeTacticalModes(effCfgBefore.tacticalModes)
|
|
240
|
+
const paceMode = effCfgBefore.paceMode || 'manual'
|
|
241
|
+
if (!force && (effCfgBefore.stopped || paceMode === 'stopped')) {
|
|
242
|
+
return { ok: false, skipped: 'chief-stopped' }
|
|
243
|
+
}
|
|
244
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
245
|
+
const board = deps.boardForSession && deps.boardFileFor
|
|
246
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
247
|
+
: null
|
|
248
|
+
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
249
|
+
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
250
|
+
const smartCoManaged = Boolean(tactical.smartCompact)
|
|
251
|
+
const hasHighPriority = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || tactical.autoCompact || tactical.smartCompact || pendingSmart
|
|
252
|
+
|
|
253
|
+
if (!force && !hasHighPriority && paceMode === 'manual') {
|
|
254
|
+
return { ok: false, skipped: 'manual' }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
|
|
258
|
+
if (tactical.autoCompact || tactical.smartCompact || pendingSmart) {
|
|
259
|
+
const preRes = await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) })
|
|
260
|
+
.catch((err) => {
|
|
261
|
+
const msg = (err && err.message) || String(err || 'pre-compact-error')
|
|
262
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
263
|
+
deps.appendBoardLog(rootId, `⚠️ 自动压缩检测异常:${msg}`, 'chief')
|
|
264
|
+
}
|
|
265
|
+
return { ok: false, error: msg }
|
|
266
|
+
})
|
|
267
|
+
if (preRes && preRes.ok && preRes.smartCompacted) {
|
|
268
|
+
return { ok: true, smartCompacted: true, harvestId: preRes.harvestId }
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// If ONLY fixed-threshold autoCompact was on (without smartCompact or supervisor/pace), exit cleanly here
|
|
273
|
+
const needsSupervisorLlm = isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify || smartCoManaged || paceMode !== 'manual'
|
|
274
|
+
if (!force && !needsSupervisorLlm) return { ok: true, onlyCompactionChecked: true }
|
|
275
|
+
|
|
276
|
+
const digest = extractLatestTurnDigest(agent, turn)
|
|
277
|
+
if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
|
|
278
|
+
|
|
279
|
+
const cursorKey = `${sid}`
|
|
280
|
+
if (!force && wsBefore.reviewCursors[cursorKey] === digest.stamp) {
|
|
281
|
+
return { ok: false, skipped: 'same-stamp' }
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, agent) : null
|
|
285
|
+
if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return { ok: false, skipped: 'mnemon' }
|
|
286
|
+
|
|
287
|
+
const hasWallCue = /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
288
|
+
const now = Date.now()
|
|
289
|
+
const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
|
|
290
|
+
const cooldownMs = hasHighPriority
|
|
291
|
+
? (smartCoManaged && !isGoalMode && !tactical.intervention ? 12_000 : 4_000)
|
|
292
|
+
: (paceMode === 'smart' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
|
|
293
|
+
if (!force && now - lastAt < cooldownMs) return { ok: false, skipped: 'cooldown' }
|
|
294
|
+
|
|
295
|
+
// Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
|
|
296
|
+
if ((tactical.intervention || isGoalMode || smartCoManaged) && typeof deps.getAgentStatus === 'function' && !force) {
|
|
297
|
+
await waitUntilAgentIdle(() => deps.getAgentStatus(sid), 5_000, 150)
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const directory = await listPeerDirectory(deps, rootId)
|
|
301
|
+
const realPeers = directory.targets.filter(t => !/^mnemon-(?:review|run)/i.test(String(t.name || t.handle || '')))
|
|
302
|
+
|
|
303
|
+
let liveUsage = null
|
|
304
|
+
if (smartCoManaged) {
|
|
305
|
+
try {
|
|
306
|
+
liveUsage = typeof deps.measureSessionTokens === 'function'
|
|
307
|
+
? await deps.measureSessionTokens(sid, agent)
|
|
308
|
+
: measureAgentSessionTokensFallback(agent)
|
|
309
|
+
} catch {}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// In 'smart' background mode (without supervisor/goal), gate LLM call on wall cue or multi-agent human turn;
|
|
313
|
+
// when ONLY smartCoManaged is enabled in manual pace, evaluate only after enough turns or context pressure.
|
|
314
|
+
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify) {
|
|
315
|
+
if (smartCoManaged && paceMode === 'manual') {
|
|
316
|
+
const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
|
|
317
|
+
const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
|
|
318
|
+
if ((digest.stamp < 4 && ratio < 0.25) || sinceCompact < 20_000) {
|
|
319
|
+
return { ok: false, skipped: 'smart-compact-light' }
|
|
320
|
+
}
|
|
321
|
+
} else {
|
|
322
|
+
if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
|
|
323
|
+
return { ok: false, skipped: 'smart-quiet' }
|
|
324
|
+
}
|
|
325
|
+
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
if (!deps.callLlmOverride) {
|
|
330
|
+
const modelsInfo = await listChiefModels(deps, false, rootId)
|
|
331
|
+
if (!modelsInfo.available) return { ok: false, skipped: 'no-models' }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
lastReviewAtByRoot.set(rootId, now)
|
|
335
|
+
const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
|
|
336
|
+
const view = clusterView(stateBefore, rootId)
|
|
337
|
+
const numberedFacts = view.facts.slice()
|
|
338
|
+
const bounds = (board && board.bounds) || { allowed: [], forbidden: [], notes: [] }
|
|
339
|
+
const planSteps = Array.isArray(board && board.plan) ? board.plan : []
|
|
340
|
+
const tasks = Array.isArray(board && board.tasks) ? board.tasks : []
|
|
341
|
+
|
|
342
|
+
const activeTargets = realPeers.filter(t => t.key === 'lead' || t.status === 'running').slice(0, 10)
|
|
343
|
+
const idleCount = Math.max(0, realPeers.length - activeTargets.length)
|
|
344
|
+
const activeFlags = [
|
|
345
|
+
isGoalMode ? 'GOAL_MODE' : '',
|
|
346
|
+
tactical.intervention ? 'INTERVENTION_SUPERVISOR' : '',
|
|
347
|
+
smartCoManaged ? 'SMART_COMPACT_CO_MANAGED' : '',
|
|
348
|
+
tactical.strictVerify ? 'STRICT_VERIFY' : '',
|
|
349
|
+
tactical.redlineSentinel ? 'REDLINE_SENTINEL' : '',
|
|
350
|
+
tactical.conciseBrief ? 'CONCISE_BRIEF_3_BULLETS' : '',
|
|
351
|
+
Boolean(paceMode === 'auto' && effCfgBefore.autoPilot && !effCfgBefore.stopped) ? 'AUTO_PILOT_SESSION_ONLY' : '',
|
|
352
|
+
].filter(Boolean)
|
|
353
|
+
|
|
354
|
+
const smartUsageHint = smartCoManaged
|
|
355
|
+
? `智选共管状态(硬阈值已停用):消息序号≈${digest.stamp}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
|
|
356
|
+
: ''
|
|
357
|
+
|
|
358
|
+
const prompt = [
|
|
359
|
+
`当前激活监督模式:${activeFlags.join(' | ') || paceMode}`,
|
|
360
|
+
...(smartUsageHint ? [smartUsageHint] : []),
|
|
361
|
+
`工作区总目标 (Objective):${(board && board.objective) || '(暂未开启 /goal 固定目标 — 请对照下方最新用户原始诉求核验完成度)'}`,
|
|
362
|
+
`最新用户原始诉求:${digest.latestUserPrompt || '(见下方对话片段)'}`,
|
|
363
|
+
`当前计划步骤 (Plan):${planSteps.length ? planSteps.map((s, i) => `${i + 1}.${s.done ? '[✓]' : '[ ]'} ${clamp(s.text, 60)}`).join(';') : '(空)'}`,
|
|
364
|
+
`当前任务列表 (Tasks):${tasks.length ? tasks.slice(0, 10).map(t => `[${t.status}] #${t.id} ${clamp(t.title, 48)}`).join(';') : '(空)'}`,
|
|
365
|
+
`刚刚结束回合的对话身份:${speaker}(sessionId=${sid})`,
|
|
366
|
+
`活跃团队成员:${activeTargets.map(t => `${t.handle}[key=${t.key}, ${t.status}${t.taskTitle ? ', 任务:' + t.taskTitle : ''}]`).join(';')}${idleCount > 0 ? `(另有 ${idleCount} 名空闲子代理已折叠)` : ''}`,
|
|
367
|
+
'',
|
|
368
|
+
'已有工作边界(禁止红线严防撞穿;必做事项提交结项前须逐项核验是否完成):',
|
|
369
|
+
`- 禁止:${(bounds.forbidden || []).join(';') || '(暂无)'}`,
|
|
370
|
+
`- 必做事项 (allowed · 必须交付确认):${(bounds.allowed || []).join(';') || '(暂无)'}`,
|
|
371
|
+
`- 注意:${(bounds.notes || []).join(';') || '(暂无)'}`,
|
|
372
|
+
'',
|
|
373
|
+
'已有持久记忆条目:',
|
|
374
|
+
...(numberedFacts.length ? numberedFacts.map((f, i) => `[${i + 1}] (${f.category}) ${f.text}`) : ['(暂无)']),
|
|
375
|
+
'',
|
|
376
|
+
'本轮最新对话片段:',
|
|
377
|
+
digest.text,
|
|
378
|
+
].join('\n')
|
|
379
|
+
|
|
380
|
+
const res = await callChiefLlm(deps, {
|
|
381
|
+
sessionId: rootId,
|
|
382
|
+
system: TURN_REVIEW_SYSTEM,
|
|
383
|
+
prompt,
|
|
384
|
+
maxTokens: SUMMARY_MAX_TOKENS,
|
|
385
|
+
})
|
|
386
|
+
if (!res.ok) return { ok: false, error: res.error }
|
|
387
|
+
|
|
388
|
+
const parsed = extractJsonObject(res.text)
|
|
389
|
+
if (!parsed) return { ok: false, error: 'non-json-review' }
|
|
390
|
+
|
|
391
|
+
const cfgNow = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
392
|
+
const wsNowPerm = ensureWorkspace(loadChiefState(), rootId)
|
|
393
|
+
const hasAckNow = hasValidChiefRiskAck(wsNowPerm)
|
|
394
|
+
const permNow = normalizePermissionMode(cfgNow.permissionMode, { requireAck: true, hasChiefRiskAck: hasAckNow })
|
|
395
|
+
const permRankNow = permissionRank(permNow)
|
|
396
|
+
const autoPilot = Boolean(cfgNow.paceMode === 'auto' && cfgNow.autoPilot && !cfgNow.stopped)
|
|
397
|
+
const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
|
|
398
|
+
.map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
|
|
399
|
+
.filter(Boolean)
|
|
400
|
+
.slice(0, 1)
|
|
401
|
+
|
|
402
|
+
// Stale plan check & auto-reconcile (L1+ only; L0 Advisor is strictly read-only)
|
|
403
|
+
const isStalePlan = Boolean(parsed.planAssessment && parsed.planAssessment.stale)
|
|
404
|
+
const parsedBoardOps = Array.isArray(parsed.boardOps) ? parsed.boardOps.slice() : []
|
|
405
|
+
if (permRankNow >= 1 && isStalePlan && !parsedBoardOps.some(op => op && (op.op === 'plan.resetForGoal' || op.op === 'plan.set'))) {
|
|
406
|
+
parsedBoardOps.unshift({ op: 'plan.resetForGoal' })
|
|
407
|
+
}
|
|
408
|
+
const executedOps = permRankNow >= 1 && parsedBoardOps.length > 0 && deps.runAction
|
|
409
|
+
? applyBoardOps(deps, rootId, parsedBoardOps, { forceSessionOnly: autoPilot })
|
|
410
|
+
: []
|
|
411
|
+
|
|
412
|
+
const unmetMustDo = Array.isArray(parsed.unmetMustDo)
|
|
413
|
+
? parsed.unmetMustDo.map(x => clamp(String(x || '').trim(), 140)).filter(Boolean).slice(0, 6)
|
|
414
|
+
: []
|
|
415
|
+
const hazardInfo = detectEmergencyHazardFallback({
|
|
416
|
+
parsed,
|
|
417
|
+
digestText: digest.text,
|
|
418
|
+
bounds,
|
|
419
|
+
isInterventionActive: Boolean(tactical.intervention || autoPilot),
|
|
420
|
+
})
|
|
421
|
+
const hasObjectiveTarget = Boolean(board && String(board.objective || '').trim())
|
|
422
|
+
const evalGoalCompletion = isGoalMode || (Boolean(tactical.intervention) && hasObjectiveTarget)
|
|
423
|
+
const isGoalAchieved = !hazardInfo.triggered
|
|
424
|
+
&& evalGoalCompletion
|
|
425
|
+
&& String(parsed.goalStatus || '') === 'achieved'
|
|
426
|
+
&& unmetMustDo.length === 0
|
|
427
|
+
let goalProposalCreated = false
|
|
428
|
+
if (permRankNow >= 1 && isGoalAchieved && deps.runAction && hasObjectiveTarget) {
|
|
429
|
+
const existingApproval = board && board.goalApproval
|
|
430
|
+
const alreadyPendingSame = existingApproval
|
|
431
|
+
&& existingApproval.status === 'pending'
|
|
432
|
+
&& existingApproval.objective === board.objective
|
|
433
|
+
if (!alreadyPendingSame) {
|
|
434
|
+
const propRes = deps.runAction({
|
|
435
|
+
action: 'goal.proposeApproval',
|
|
436
|
+
objective: board.objective || '',
|
|
437
|
+
summary: cleanMultiline(parsed.goalSummary || '核心目标及必做事项验证均已完成,建议结项。', 320),
|
|
438
|
+
evidence: cleanMultiline(parsed.goalEvidence || '', 420),
|
|
439
|
+
session: rootId,
|
|
440
|
+
by: 'DSH 参谋长',
|
|
441
|
+
})
|
|
442
|
+
goalProposalCreated = Boolean(propRes && propRes.ok)
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
let circuitTripped = false
|
|
447
|
+
let circuitReason = ''
|
|
448
|
+
let hazardStopped = false
|
|
449
|
+
let hazardAlertCreated = null
|
|
450
|
+
let interventionMessage = ''
|
|
451
|
+
let interventionForApproval = ''
|
|
452
|
+
let interventionDedupeKey = ''
|
|
453
|
+
const autoRelays = []
|
|
454
|
+
const relaysForApproval = []
|
|
455
|
+
const autoBoundUpdates = []
|
|
456
|
+
let shouldAutoOrganizeSession = false
|
|
457
|
+
|
|
458
|
+
const isInternalRelayTarget = (targetRaw) => {
|
|
459
|
+
const tq = String(targetRaw || '').trim().replace(/^@/, '')
|
|
460
|
+
if (!tq) return false
|
|
461
|
+
const lower = tq.toLowerCase()
|
|
462
|
+
if (['lead', 'main', '主对话', '主代理'].includes(lower)) return true
|
|
463
|
+
return realPeers.some(p =>
|
|
464
|
+
p.kind !== 'peer-session'
|
|
465
|
+
&& p.kind !== 'session'
|
|
466
|
+
&& (p.key === tq || p.handle === tq || p.id === tq || p.name === tq)
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
mutateChiefState((s) => {
|
|
471
|
+
const ws = ensureWorkspace(s, rootId)
|
|
472
|
+
ws.reviewCursors[cursorKey] = digest.stamp
|
|
473
|
+
if (autoPilot) {
|
|
474
|
+
ws.runtimeGuard.autoPilotHadTurn = true
|
|
475
|
+
}
|
|
476
|
+
if (permRankNow >= 1) {
|
|
477
|
+
const activeCluster = getLinkedCluster(s, rootId)
|
|
478
|
+
applyFactChanges(ws, numberedFacts, parsed.memoryChanges, speaker, {
|
|
479
|
+
originRootId: rootId,
|
|
480
|
+
peerRootIds: activeCluster.filter(id => id !== rootId),
|
|
481
|
+
})
|
|
482
|
+
|
|
483
|
+
// Goal achieved: create user approval suggestion pill (NEVER exit goal mode automatically!)
|
|
484
|
+
if (isGoalAchieved) {
|
|
485
|
+
const goalSig = crypto
|
|
486
|
+
.createHash('sha1')
|
|
487
|
+
.update(String((board && board.objective) || '') + '|' + String(parsed.goalEvidence || parsed.goalSummary || ''))
|
|
488
|
+
.digest('hex')
|
|
489
|
+
.slice(0, 12)
|
|
490
|
+
const hasPendingGoalSug = ws.suggestions.some(
|
|
491
|
+
sug => sug.status === 'pending' && sug.kind === 'goal_approval',
|
|
492
|
+
)
|
|
493
|
+
if (!hasPendingGoalSug) {
|
|
494
|
+
const goalSug = normalizeSuggestion({
|
|
495
|
+
kind: 'goal_approval',
|
|
496
|
+
fromAgent: '🎯 目标督导参谋',
|
|
497
|
+
title: '🎯 核心目标与必做事项已达成,请示批准结项',
|
|
498
|
+
reason: cleanMultiline(parsed.goalSummary || '主对话已完成当前设定核心目标及全部必做事项,请批示是否结束督导。', 220),
|
|
499
|
+
evidence: cleanMultiline(parsed.goalEvidence || '', 480),
|
|
500
|
+
target: 'board',
|
|
501
|
+
targetLabel: '目标结项',
|
|
502
|
+
mode: 'silent',
|
|
503
|
+
draftText: cleanMultiline(parsed.goalSummary || '批准结项并退出督导模式', 400),
|
|
504
|
+
})
|
|
505
|
+
if (goalSug) ws.suggestions.push(goalSug)
|
|
506
|
+
}
|
|
507
|
+
if (ws.runtimeGuard.lastGoalAchievedSig !== goalSig) {
|
|
508
|
+
ws.runtimeGuard.lastGoalAchievedSig = goalSig
|
|
509
|
+
ws.chat.push({
|
|
510
|
+
id: nextId('chat'),
|
|
511
|
+
role: 'chief',
|
|
512
|
+
text: `- 【🎯 核心目标已达成 · 停止继续推送】${cleanMultiline(parsed.goalSummary || '核心目标与必做事项均已完成并核验通过。', 260)}`,
|
|
513
|
+
actions: ['目标达成收口'],
|
|
514
|
+
at: Date.now(),
|
|
515
|
+
})
|
|
516
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
for (const sug of rawSuggestions) {
|
|
521
|
+
if (sug.kind === 'bound') {
|
|
522
|
+
const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
|
|
523
|
+
if (colList.some(x => String(x).trim() === sug.draftText)) continue
|
|
524
|
+
if (autoPilot && sug.draftText) {
|
|
525
|
+
sug.pinGlobal = false
|
|
526
|
+
sug.status = 'applied'
|
|
527
|
+
autoBoundUpdates.push({ field: sug.boundField, item: sug.draftText })
|
|
528
|
+
continue
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
if (autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
532
|
+
if (permNow === 'chief' && hasAckNow) {
|
|
533
|
+
sug.status = 'applied'
|
|
534
|
+
autoRelays.push(sug)
|
|
535
|
+
continue
|
|
536
|
+
} else if (permNow === 'strategist') {
|
|
537
|
+
sug.status = 'applied'
|
|
538
|
+
relaysForApproval.push(sug)
|
|
539
|
+
continue
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
const dup = ws.suggestions.some(
|
|
543
|
+
existing => existing.status === 'pending'
|
|
544
|
+
&& existing.kind === sug.kind
|
|
545
|
+
&& (sug.kind === 'bound'
|
|
546
|
+
? existing.draftText === sug.draftText
|
|
547
|
+
: (sug.kind === 'advice'
|
|
548
|
+
? (existing.title === sug.title && existing.draftText === sug.draftText)
|
|
549
|
+
: (existing.target === sug.target && existing.title === sug.title))),
|
|
550
|
+
)
|
|
551
|
+
if (!dup) {
|
|
552
|
+
const pending = ws.suggestions.filter(item => item.status === 'pending')
|
|
553
|
+
if (pending.length >= 5) {
|
|
554
|
+
const victim = pending.find(item => item.kind !== 'bound' && item.kind !== 'goal_approval' && item.kind !== 'advice') || pending[0]
|
|
555
|
+
victim.status = 'dismissed'
|
|
556
|
+
}
|
|
557
|
+
ws.suggestions.push(sug)
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
if (autoPilot && rootId && rootId !== 'global') {
|
|
562
|
+
const lastOrgAt = Number(ws.runtimeGuard.lastAutoArchiveOrgAt || 0)
|
|
563
|
+
if (!lastOrgAt || Date.now() - lastOrgAt > 180_000) {
|
|
564
|
+
shouldAutoOrganizeSession = true
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// 0) Emergency hazard / boundary-collision gate takes highest priority under Strong Intervention
|
|
570
|
+
if (hazardInfo.triggered && (tactical.intervention || autoPilot)) {
|
|
571
|
+
hazardStopped = true
|
|
572
|
+
circuitTripped = true
|
|
573
|
+
circuitReason = hazardInfo.reason || hazardInfo.title
|
|
574
|
+
if (!ws.config || typeof ws.config !== 'object') ws.config = resolveWorkspaceConfig(s, rootId)
|
|
575
|
+
ws.config.tacticalModes = {
|
|
576
|
+
...normalizeTacticalModes(ws.config.tacticalModes),
|
|
577
|
+
intervention: false,
|
|
578
|
+
}
|
|
579
|
+
s.config.tacticalModes = {
|
|
580
|
+
...normalizeTacticalModes(s.config.tacticalModes),
|
|
581
|
+
intervention: false,
|
|
582
|
+
}
|
|
583
|
+
hazardAlertCreated = {
|
|
584
|
+
id: nextId('hazard'),
|
|
585
|
+
category: hazardInfo.category || 'irreversible_risk',
|
|
586
|
+
title: hazardInfo.title || '强介入紧急煞车 · 已停止推进',
|
|
587
|
+
reason: hazardInfo.reason || '继续推进可能造成不可逆损失或必然撞穿工作边界,已立即停止强介入。',
|
|
588
|
+
objective: clamp((board && board.objective) || '', 300),
|
|
589
|
+
at: Date.now(),
|
|
590
|
+
}
|
|
591
|
+
ws.runtimeGuard.hazardAlert = hazardAlertCreated
|
|
592
|
+
ws.runtimeGuard.circuitBroken = true
|
|
593
|
+
ws.runtimeGuard.circuitReason = hazardAlertCreated.reason
|
|
594
|
+
ws.runtimeGuard.interventionTurns = 0
|
|
595
|
+
ws.runtimeGuard.unchangedCount = 0
|
|
596
|
+
interventionMessage = ''
|
|
597
|
+
ws.chat.push({
|
|
598
|
+
id: nextId('chat'),
|
|
599
|
+
role: 'chief',
|
|
600
|
+
text: `- 【🚨 紧急煞车 · 强介入已停】${hazardAlertCreated.title}\n 理由:${hazardAlertCreated.reason}`,
|
|
601
|
+
actions: ['高危急停'],
|
|
602
|
+
at: Date.now(),
|
|
603
|
+
})
|
|
604
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
605
|
+
pushAuditToWs(ws, { mode: permNow, stage: 'safety_guard', decision: 'hazard_stop', operation: '强介入紧急煞车', target: 'lead', reason: hazardAlertCreated.reason, outcome: 'blocked', by: 'chief' })
|
|
606
|
+
} else {
|
|
607
|
+
// Intervention Supervisor follow-up + Circuit Breaker (differentiated across L0 / L1 / L2 / L3)
|
|
608
|
+
const unmetMustDoFallback = unmetMustDo.length > 0
|
|
609
|
+
? '当前尚有以下【必做事项】未确认交付或缺少验证证据,请逐项补齐并交卷:\n' + unmetMustDo.map((u, idx) => `${idx + 1}. ${u}`).join('\n')
|
|
610
|
+
: ''
|
|
611
|
+
const candidateIntervention = parsed.interventionText
|
|
612
|
+
|| unmetMustDoFallback
|
|
613
|
+
|| (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
|
|
614
|
+
if (!isGoalAchieved && tactical.intervention && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress' || unmetMustDo.length > 0) && candidateIntervention) {
|
|
615
|
+
const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
|
|
616
|
+
const sig = crypto
|
|
617
|
+
.createHash('sha1')
|
|
618
|
+
.update(JSON.stringify({
|
|
619
|
+
objective: (board && board.objective) || '',
|
|
620
|
+
goalStatus: parsed.goalStatus || '',
|
|
621
|
+
donePlanCount: planSteps.filter(p => p.done).length,
|
|
622
|
+
doneTaskCount: tasks.filter(t => t.status === 'done').length,
|
|
623
|
+
blockedTaskCount: tasks.filter(t => t.status === 'blocked').length,
|
|
624
|
+
assistantTail: clamp(assistantTail, 140),
|
|
625
|
+
}))
|
|
626
|
+
.digest('hex')
|
|
627
|
+
.slice(0, 12)
|
|
628
|
+
|
|
629
|
+
const prevSig = ws.runtimeGuard.lastDigestHash
|
|
630
|
+
const nextUnchanged = prevSig === sig ? (ws.runtimeGuard.unchangedCount + 1) : 1
|
|
631
|
+
const nextTurns = ws.runtimeGuard.interventionTurns + 1
|
|
632
|
+
const isUnlimitedTurns = tactical.maxInterventionTurns === 0
|
|
633
|
+
const maxTurns = isUnlimitedTurns ? Infinity : Math.max(1, Number(tactical.maxInterventionTurns) || 10)
|
|
634
|
+
const unchangedLimit = isUnlimitedTurns ? 8 : 3
|
|
635
|
+
|
|
636
|
+
if ((!isUnlimitedTurns && nextTurns > maxTurns) || nextUnchanged >= unchangedLimit) {
|
|
637
|
+
circuitTripped = true
|
|
638
|
+
circuitReason = !isUnlimitedTurns && nextTurns > maxTurns
|
|
639
|
+
? `接管督导连续介入已达上限 (${maxTurns} 轮),触发安全熔断,已自动退回人工监督。`
|
|
640
|
+
: `连续 ${unchangedLimit} 轮检测进展无实质变化,触发死循环熔断,已自动关闭接管督导并交还用户控制。`
|
|
641
|
+
if (!ws.config || typeof ws.config !== 'object') ws.config = resolveWorkspaceConfig(s, rootId)
|
|
642
|
+
ws.config.tacticalModes = {
|
|
643
|
+
...normalizeTacticalModes(ws.config.tacticalModes),
|
|
644
|
+
intervention: false,
|
|
645
|
+
}
|
|
646
|
+
s.config.tacticalModes = {
|
|
647
|
+
...normalizeTacticalModes(s.config.tacticalModes),
|
|
648
|
+
intervention: false,
|
|
649
|
+
}
|
|
650
|
+
ws.runtimeGuard.circuitBroken = true
|
|
651
|
+
ws.runtimeGuard.circuitReason = circuitReason
|
|
652
|
+
ws.runtimeGuard.interventionTurns = 0
|
|
653
|
+
ws.runtimeGuard.unchangedCount = 0
|
|
654
|
+
ws.chat.push({
|
|
655
|
+
id: nextId('chat'),
|
|
656
|
+
role: 'chief',
|
|
657
|
+
text: `- 【⚠️ 安全熔断】${circuitReason}`,
|
|
658
|
+
actions: ['熔断停机'],
|
|
659
|
+
at: Date.now(),
|
|
660
|
+
})
|
|
661
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
662
|
+
} else {
|
|
663
|
+
ws.runtimeGuard.lastDigestHash = sig
|
|
664
|
+
ws.runtimeGuard.unchangedCount = nextUnchanged
|
|
665
|
+
ws.runtimeGuard.interventionTurns = nextTurns
|
|
666
|
+
ws.runtimeGuard.circuitBroken = false
|
|
667
|
+
ws.runtimeGuard.circuitReason = ''
|
|
668
|
+
const cleanBody = cleanMultiline(candidateIntervention, tactical.conciseBrief ? 420 : 1200)
|
|
669
|
+
|
|
670
|
+
if (permRankNow === 0) {
|
|
671
|
+
// L0 Advisor: strict read-only inspection brief in panel chat only (never touches board or @lead)
|
|
672
|
+
if (prevSig !== sig || nextTurns === 1) {
|
|
673
|
+
ws.chat.push({
|
|
674
|
+
id: nextId('chat'),
|
|
675
|
+
role: 'chief',
|
|
676
|
+
text: `- 【👁 L0 顾问只读督导巡检】目标核验状态:\`${parsed.goalStatus || 'in_progress'}\`\n- 【诊断与建议】${clamp(cleanBody, 280)}`,
|
|
677
|
+
actions: ['L0 只读巡检', '建议不下发'],
|
|
678
|
+
at: Date.now(),
|
|
679
|
+
})
|
|
680
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
681
|
+
}
|
|
682
|
+
pushAuditToWs(ws, { mode: permNow, stage: 'permission_gate', decision: 'readonly_inspection', operation: '强介入只读巡检', target: 'chief_panel', reason: clamp(cleanBody, 120), outcome: 'ok', by: 'chief' })
|
|
683
|
+
} else if (permRankNow === 1) {
|
|
684
|
+
// L1 Assistant: manages internal Chief board/facts/suggestions only; does NOT inject into @lead
|
|
685
|
+
const sug = normalizeSuggestion({
|
|
686
|
+
kind: 'advice',
|
|
687
|
+
fromAgent: '🗂 L1 助手督导建议',
|
|
688
|
+
title: 'L1 强介入建议(等待拍板,未自动递给主对话)',
|
|
689
|
+
reason: clamp(parsed.goalMissing || 'L1 助手模式不接管主代理工作流,您可一键采纳递交主对话。', 200),
|
|
690
|
+
target: 'lead',
|
|
691
|
+
targetLabel: '主对话',
|
|
692
|
+
mode: 'followup',
|
|
693
|
+
draftText: cleanBody,
|
|
694
|
+
popup: false,
|
|
695
|
+
})
|
|
696
|
+
if (sug) ws.suggestions.push(sug)
|
|
697
|
+
ws.chat.push({
|
|
698
|
+
id: nextId('chat'),
|
|
699
|
+
role: 'chief',
|
|
700
|
+
text: `- 【🗂 L1 助手督导建议】已整理本轮看板进展,并生成待采纳推进建议(L1 不自动插话主对话):\n${clamp(cleanBody, 260)}`,
|
|
701
|
+
actions: ['L1 内务自治', '转人工采纳'],
|
|
702
|
+
at: Date.now(),
|
|
703
|
+
})
|
|
704
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
705
|
+
pushAuditToWs(ws, { mode: permNow, stage: 'permission_gate', decision: 'suggested_only', operation: '强介入转建议卡', target: 'lead', reason: clamp(cleanBody, 120), outcome: 'ok', by: 'chief' })
|
|
706
|
+
} else if (permRankNow === 2) {
|
|
707
|
+
// L2 Strategist: requires explicit user approval popup before sending followup into @lead!
|
|
708
|
+
interventionForApproval = cleanBody
|
|
709
|
+
interventionDedupeKey = `intv:${rootId}:${digest.stamp}:${sig}`
|
|
710
|
+
pushAuditToWs(ws, { mode: permNow, stage: 'permission_gate', decision: 'pending_approval', operation: '强介入督导主对话', target: 'lead', reason: clamp(cleanBody, 120), outcome: 'pending', by: 'chief' })
|
|
711
|
+
} else {
|
|
712
|
+
// L3 Chief of Staff (ack verified): full autonomous intervention
|
|
713
|
+
interventionMessage = cleanBody
|
|
714
|
+
pushAuditToWs(ws, { mode: permNow, stage: 'executor', decision: 'executed', operation: '强介入自动督导推进', target: 'lead', reason: clamp(cleanBody, 120), outcome: 'ok', by: 'chief' })
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
})
|
|
720
|
+
|
|
721
|
+
if (hazardStopped && deps && typeof deps.cancelAutoContinue === 'function') {
|
|
722
|
+
try { deps.cancelAutoContinue(sid, 'hazard-stop') } catch {}
|
|
723
|
+
if (rootId && rootId !== sid) {
|
|
724
|
+
try { deps.cancelAutoContinue(rootId, 'hazard-stop') } catch {}
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// When both Smart Compact & Intervention trigger on the same turn:
|
|
729
|
+
// L3 runs harvest + compact silently first; L2 queues approval popup; L0/L1 never auto-compact.
|
|
730
|
+
let smartCompacted = false
|
|
731
|
+
if (permRankNow >= 2 && smartCoManaged && parsed.shouldCompactNow === true && typeof deps.compactSessionNow === 'function') {
|
|
732
|
+
const wsNow = ensureWorkspace(loadChiefState(), rootId)
|
|
733
|
+
const lastCompactedAt = (wsNow.runtimeGuard && wsNow.runtimeGuard.lastCompactedAt) || 0
|
|
734
|
+
const sinceLast = Date.now() - lastCompactedAt
|
|
735
|
+
if (force || !lastCompactedAt || sinceLast >= 20_000) {
|
|
736
|
+
const compactReason = clamp(parsed.compactReason || '参谋长评估当前阶段已收口,执行智选归档压缩', 220)
|
|
737
|
+
if (permRankNow === 2) {
|
|
738
|
+
queueChiefApproval(rootId, {
|
|
739
|
+
category: 'main_workflow',
|
|
740
|
+
operationLabel: '✦ 智选压缩主对话上下文 (/compact)',
|
|
741
|
+
targetLabel: '当前主会话',
|
|
742
|
+
reason: compactReason,
|
|
743
|
+
impact: '将先抢救摘要入本会话档案柜,随后压缩裁剪主对话历史',
|
|
744
|
+
dedupeKey: `smart_compact:${rootId}:${wsNow.runtimeGuard.lastCompactedSeq || 0}:${digest.stamp}`,
|
|
745
|
+
kind: 'compact',
|
|
746
|
+
payload: { reason: compactReason },
|
|
747
|
+
by: 'chief',
|
|
748
|
+
})
|
|
749
|
+
} else {
|
|
750
|
+
let st = 'idle'
|
|
751
|
+
try { if (typeof deps.getAgentStatus === 'function') st = deps.getAgentStatus(sid) || 'idle' } catch {}
|
|
752
|
+
if (st === 'running' && !force && typeof deps.getAgentStatus === 'function') {
|
|
753
|
+
await waitUntilAgentIdle(() => deps.getAgentStatus(sid), 8_000, 200)
|
|
754
|
+
try { st = deps.getAgentStatus(sid) || 'idle' } catch {}
|
|
755
|
+
}
|
|
756
|
+
if (st === 'running' && !force) {
|
|
757
|
+
mutateChiefState((s) => {
|
|
758
|
+
const ws = ensureWorkspace(s, rootId)
|
|
759
|
+
ws.runtimeGuard.pendingSmartCompact = { at: Date.now(), reason: compactReason, by: 'chief' }
|
|
760
|
+
})
|
|
761
|
+
} else {
|
|
762
|
+
const contextWindow = Math.max(1000, Number(liveUsage && liveUsage.contextWindow) || 128_000)
|
|
763
|
+
const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
|
|
764
|
+
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.stamp || 0))
|
|
765
|
+
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
766
|
+
const cRes = await executeHarvestAndCompact(deps, {
|
|
767
|
+
sid,
|
|
768
|
+
rootId,
|
|
769
|
+
agent,
|
|
770
|
+
reason: compactReason,
|
|
771
|
+
seq,
|
|
772
|
+
ratioPct,
|
|
773
|
+
totalTokens,
|
|
774
|
+
contextWindow,
|
|
775
|
+
logLabel: '✦ 智选压缩(参谋长判断)',
|
|
776
|
+
}).catch((err) => {
|
|
777
|
+
const msg = (err && err.message) || String(err || 'smart-compact-error')
|
|
778
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
779
|
+
deps.appendBoardLog(rootId, `⚠️ ✦ 智选压缩失败:${msg}`, 'chief')
|
|
780
|
+
}
|
|
781
|
+
return { ok: false, error: msg }
|
|
782
|
+
})
|
|
783
|
+
if (cRes && cRes.ok && !cRes.noop) {
|
|
784
|
+
smartCompacted = true
|
|
785
|
+
recordSmartCompactionChatReceipt(rootId, {
|
|
786
|
+
cRes,
|
|
787
|
+
ratioPct,
|
|
788
|
+
totalTokens,
|
|
789
|
+
contextWindow,
|
|
790
|
+
via: '✦ 智选压缩',
|
|
791
|
+
})
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
if (interventionForApproval) {
|
|
799
|
+
queueChiefApproval(rootId, {
|
|
800
|
+
category: 'main_workflow',
|
|
801
|
+
operationLabel: '强介入督导主对话继续推进',
|
|
802
|
+
targetLabel: '主对话 (@lead)',
|
|
803
|
+
reason: '当前处于「L2 · 参谋模式」,强介入向主对话发推进指令前需您逐项授权',
|
|
804
|
+
impact: '点击「允许本次操作」后将立即向主对话唤醒投递以下督导指令',
|
|
805
|
+
preview: clamp(interventionForApproval, 260),
|
|
806
|
+
dedupeKey: interventionDedupeKey,
|
|
807
|
+
kind: 'relay',
|
|
808
|
+
payload: {
|
|
809
|
+
fromSession: rootId,
|
|
810
|
+
fromLabel: 'DSH 参谋 (强介入逐项授权)',
|
|
811
|
+
target: 'lead',
|
|
812
|
+
subject: '参谋强介入督导推进',
|
|
813
|
+
text: interventionForApproval,
|
|
814
|
+
mode: 'followup',
|
|
815
|
+
},
|
|
816
|
+
by: 'chief',
|
|
817
|
+
})
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (interventionMessage) {
|
|
821
|
+
const tags = [
|
|
822
|
+
tactical.strictVerify ? '严格校验实测' : '',
|
|
823
|
+
tactical.redlineSentinel ? '红线哨兵巡检' : '',
|
|
824
|
+
tactical.conciseBrief ? '精炼要点' : '',
|
|
825
|
+
].filter(Boolean).join(' · ')
|
|
826
|
+
await deliverCrossMessage(deps, {
|
|
827
|
+
fromSession: rootId,
|
|
828
|
+
fromLabel: `DSH 参谋长 (接管督导${tags ? '·' + tags : ''})`,
|
|
829
|
+
target: 'lead',
|
|
830
|
+
subject: '参谋长自动督导推进',
|
|
831
|
+
text: interventionMessage,
|
|
832
|
+
mode: 'followup',
|
|
833
|
+
})
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
|
|
837
|
+
for (const b of autoBoundUpdates) {
|
|
838
|
+
deps.runAction({
|
|
839
|
+
action: 'bounds.add',
|
|
840
|
+
field: b.field,
|
|
841
|
+
item: b.item,
|
|
842
|
+
pinned: false,
|
|
843
|
+
session: rootId,
|
|
844
|
+
by: 'DSH 参谋长 (全自动托管)',
|
|
845
|
+
})
|
|
846
|
+
executedOps.push(`本局自动边界(${b.field}):${clamp(b.item, 32)}`)
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
if (permRankNow >= 1 && shouldAutoOrganizeSession && rootId && rootId !== 'global') {
|
|
851
|
+
try {
|
|
852
|
+
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
853
|
+
const stSess = loadArchiveStore(sessOpt)
|
|
854
|
+
const unorgCount = (stSess.items || []).filter(
|
|
855
|
+
it => it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1,
|
|
856
|
+
).length
|
|
857
|
+
if (unorgCount >= 3) {
|
|
858
|
+
mutateChiefState((s) => {
|
|
859
|
+
const ws = ensureWorkspace(s, rootId)
|
|
860
|
+
ws.runtimeGuard.lastAutoArchiveOrgAt = Date.now()
|
|
861
|
+
})
|
|
862
|
+
await organizeArchivesWithChief(deps, {
|
|
863
|
+
sessionId: rootId,
|
|
864
|
+
vaultScope: 'session',
|
|
865
|
+
scope: 'unorganized',
|
|
866
|
+
instruction: '全自动托管轮后整理本会话未归档记录(仅限本会话)',
|
|
867
|
+
}).catch(() => null)
|
|
868
|
+
}
|
|
869
|
+
} catch {}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
for (const sug of relaysForApproval) {
|
|
873
|
+
queueChiefApproval(rootId, {
|
|
874
|
+
category: 'main_workflow',
|
|
875
|
+
operationLabel: '向工作流成员投递自动指令',
|
|
876
|
+
targetLabel: sug.target === 'lead' ? '主对话 (@lead)' : `@${sug.target}`,
|
|
877
|
+
reason: clamp(sug.title || 'L2 参谋模式逐项授权自动递话', 140),
|
|
878
|
+
impact: '允许后将把该条工作流指令投递给目标成员',
|
|
879
|
+
preview: clamp(sug.draftText || '', 240),
|
|
880
|
+
dedupeKey: `autorelay:${rootId}:${digest.stamp}:${sug.target}`,
|
|
881
|
+
kind: 'relay',
|
|
882
|
+
payload: {
|
|
883
|
+
fromSession: rootId,
|
|
884
|
+
fromLabel: 'DSH 参谋 (逐项授权)',
|
|
885
|
+
target: sug.target,
|
|
886
|
+
subject: sug.title,
|
|
887
|
+
text: sug.draftText,
|
|
888
|
+
mode: sug.mode || 'silent',
|
|
889
|
+
},
|
|
890
|
+
by: 'chief',
|
|
891
|
+
})
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
for (const sug of autoRelays) {
|
|
895
|
+
await deliverCrossMessage(deps, {
|
|
896
|
+
fromSession: rootId,
|
|
897
|
+
fromLabel: 'DSH 参谋长 (自动托管)',
|
|
898
|
+
target: sug.target,
|
|
899
|
+
subject: sug.title,
|
|
900
|
+
text: sug.draftText,
|
|
901
|
+
mode: sug.mode || 'silent',
|
|
902
|
+
})
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
let autoPilotStopRes = null
|
|
906
|
+
if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
|
|
907
|
+
autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
908
|
+
allowStartupGrace: false,
|
|
909
|
+
directory,
|
|
910
|
+
fromViewCheck: false,
|
|
911
|
+
}).catch(() => null)
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
return {
|
|
915
|
+
ok: true,
|
|
916
|
+
permissionMode: permNow,
|
|
917
|
+
executedOps,
|
|
918
|
+
isStalePlan,
|
|
919
|
+
unmetMustDo,
|
|
920
|
+
goalAchieved: isGoalAchieved,
|
|
921
|
+
goalProposalCreated,
|
|
922
|
+
hazardStopped,
|
|
923
|
+
...(hazardAlertCreated ? { hazardAlert: hazardAlertCreated } : {}),
|
|
924
|
+
intervened: Boolean(interventionMessage),
|
|
925
|
+
queuedInterventionApproval: Boolean(interventionForApproval),
|
|
926
|
+
smartCompacted,
|
|
927
|
+
circuitTripped,
|
|
928
|
+
circuitReason,
|
|
929
|
+
...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Anti-idle safeguard for session-scoped Full Auto-Pilot (`paceMode === 'auto'`):
|
|
935
|
+
* Once Lead and all real non-probe child subagents within THIS session finish working AND
|
|
936
|
+
* the closing narrative digest has finished catching up, automatically stand down to `manual`
|
|
937
|
+
* so Chief never idles/spins indefinitely after work completes.
|
|
938
|
+
*/
|
|
939
|
+
export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
940
|
+
const sidRaw = String(sessionId || '').trim()
|
|
941
|
+
const rootId = String(
|
|
942
|
+
(deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sidRaw) : sidRaw) || sidRaw || '',
|
|
943
|
+
).trim()
|
|
944
|
+
if (!rootId || rootId === 'global') {
|
|
945
|
+
return { ok: true, stopped: false, reason: 'not-session' }
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
const stBefore = loadChiefState()
|
|
949
|
+
const effBefore = resolveWorkspaceConfig(stBefore, rootId)
|
|
950
|
+
const wsBefore = ensureWorkspace(stBefore, rootId)
|
|
951
|
+
if (effBefore.stopped || effBefore.paceMode !== 'auto' || !effBefore.autoPilot) {
|
|
952
|
+
return { ok: true, stopped: false, reason: 'not-autopilot' }
|
|
953
|
+
}
|
|
954
|
+
if (reviewTimers.has(rootId)) {
|
|
955
|
+
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
const hasRunningInSession = (dirObj) => {
|
|
959
|
+
try {
|
|
960
|
+
if (deps && typeof deps.getAgentStatus === 'function' && deps.getAgentStatus(rootId) === 'running') {
|
|
961
|
+
return true
|
|
962
|
+
}
|
|
963
|
+
} catch {}
|
|
964
|
+
try {
|
|
965
|
+
const agentsMap = deps && deps.runtime && typeof deps.runtime.get === 'function'
|
|
966
|
+
? deps.runtime.get('agents')
|
|
967
|
+
: null
|
|
968
|
+
if (agentsMap && typeof agentsMap[Symbol.iterator] === 'function') {
|
|
969
|
+
for (const item of agentsMap) {
|
|
970
|
+
const ag = Array.isArray(item) ? item[1] : item
|
|
971
|
+
if (!ag || typeof ag !== 'object') continue
|
|
972
|
+
const agSid = String(ag.id || '').trim()
|
|
973
|
+
if (!agSid) continue
|
|
974
|
+
const agRoot = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(agSid, ag) : '') || agSid
|
|
975
|
+
if (agRoot !== rootId) continue
|
|
976
|
+
const agName = String(ag.name || ag.handle || '')
|
|
977
|
+
if (/^mnemon-(?:review|run)/i.test(agName)) continue
|
|
978
|
+
if (ag.status === 'running') return true
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
} catch {}
|
|
982
|
+
const targets = dirObj && Array.isArray(dirObj.targets) ? dirObj.targets : []
|
|
983
|
+
for (const t of targets) {
|
|
984
|
+
if (!t || t.kind === 'peer-session' || t.kind === 'session') continue
|
|
985
|
+
if (t.rootId && t.rootId !== rootId) continue
|
|
986
|
+
const tName = String(t.name || t.handle || '')
|
|
987
|
+
if (/^mnemon-(?:review|run)/i.test(tName)) continue
|
|
988
|
+
if (t.status === 'running') return true
|
|
989
|
+
}
|
|
990
|
+
return false
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
const dirInitial = opts.directory || (deps ? await listPeerDirectory(deps, rootId) : { targets: [] })
|
|
994
|
+
if (hasRunningInSession(dirInitial)) {
|
|
995
|
+
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
if (opts.allowStartupGrace !== false) {
|
|
999
|
+
const startedAt = Number((wsBefore.runtimeGuard && wsBefore.runtimeGuard.autoPilotStartedAt) || 0)
|
|
1000
|
+
const hadTurn = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.autoPilotHadTurn)
|
|
1001
|
+
if (!hadTurn && startedAt > 0 && Date.now() - startedAt < 15_000) {
|
|
1002
|
+
return { ok: true, stopped: false, reason: 'startup-grace' }
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
if (opts.currentFresh !== true && deps) {
|
|
1007
|
+
const preView = await getChiefView(deps, rootId, {
|
|
1008
|
+
regenerate: false,
|
|
1009
|
+
autoSummarize: false,
|
|
1010
|
+
_skipAutoPilotCheck: true,
|
|
1011
|
+
}).catch(() => null)
|
|
1012
|
+
const nar = preView && preView.narrative
|
|
1013
|
+
if (nar && nar.hasUnsummarizedChanges && !nar.fresh) {
|
|
1014
|
+
if (nar.summarizing) {
|
|
1015
|
+
return { ok: true, stopped: false, reason: 'summarizing' }
|
|
1016
|
+
}
|
|
1017
|
+
if (preView.models && preView.models.available && !summarizingLocks.has(rootId)) {
|
|
1018
|
+
await getChiefView(deps, rootId, {
|
|
1019
|
+
regenerate: true,
|
|
1020
|
+
autoSummarize: false,
|
|
1021
|
+
_skipAutoPilotCheck: true,
|
|
1022
|
+
}).catch(() => null)
|
|
1023
|
+
}
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
if (reviewTimers.has(rootId)) {
|
|
1028
|
+
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
1029
|
+
}
|
|
1030
|
+
const dirFinal = deps ? await listPeerDirectory(deps, rootId) : dirInitial
|
|
1031
|
+
if (hasRunningInSession(dirFinal)) {
|
|
1032
|
+
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
let stoppedNow = false
|
|
1036
|
+
mutateChiefState((s) => {
|
|
1037
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1038
|
+
const effNow = resolveWorkspaceConfig(s, rootId)
|
|
1039
|
+
if (effNow.stopped || effNow.paceMode !== 'auto' || !effNow.autoPilot) return
|
|
1040
|
+
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
|
|
1041
|
+
ws.config.paceMode = 'manual'
|
|
1042
|
+
ws.config.autoPilot = false
|
|
1043
|
+
ws.config.autoReview = false
|
|
1044
|
+
if (s.config && s.config.paceMode === 'auto') {
|
|
1045
|
+
s.config.paceMode = 'manual'
|
|
1046
|
+
s.config.autoPilot = false
|
|
1047
|
+
s.config.autoReview = false
|
|
1048
|
+
}
|
|
1049
|
+
ws.chat.push({
|
|
1050
|
+
id: nextId('chat'),
|
|
1051
|
+
role: 'chief',
|
|
1052
|
+
text: '- 【⚡→⏸️ 防空转自动收工】本会话主代理与子代理均已结束任务且阶段摘要已收口,已自动退出「全自动托管」退回按需手动,随时可再次手动开启。',
|
|
1053
|
+
actions: ['防空转收工'],
|
|
1054
|
+
at: Date.now(),
|
|
1055
|
+
})
|
|
1056
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1057
|
+
stoppedNow = true
|
|
1058
|
+
})
|
|
1059
|
+
|
|
1060
|
+
return { ok: true, stopped: stoppedNow, reason: stoppedNow ? 'idle-completed' : 'already-stopped' }
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
registerIdleAutoPilotHook(checkAndStopIdleAutoPilot)
|
|
1064
|
+
|