dsh-chief 1.4.0 → 1.6.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 +74 -0
- package/README.en.md +68 -54
- package/README.md +69 -54
- package/api-routes.js +204 -3
- package/archive-core.js +136 -8
- package/archive-dossiers.js +450 -20
- package/archive-precipitated.js +115 -36
- package/auto-continue.js +13 -5
- package/board-actions.js +120 -10
- package/board-schema.js +331 -6
- package/chief-approvals.js +176 -11
- package/chief-archives.js +158 -30
- package/chief-commands.js +567 -101
- package/chief-compaction.js +1 -0
- package/chief-models.js +264 -27
- package/chief-review.js +455 -107
- package/chief-state.js +918 -33
- package/chief-view.js +20 -14
- package/client.js +13238 -7190
- package/digest.js +22 -10
- package/idle-guard.js +233 -8
- package/locale/en.json +71 -0
- package/locale/zh.json +71 -0
- package/model-tools.js +21 -6
- package/package.json +11 -4
- package/runtime-hooks.js +358 -20
- package/safety/invariant-guards.js +2 -1
- package/subagent-runtime.js +285 -2
package/chief-review.js
CHANGED
|
@@ -7,11 +7,13 @@
|
|
|
7
7
|
import crypto from 'node:crypto'
|
|
8
8
|
import { loadArchiveStore } from './archives.js'
|
|
9
9
|
import { normalizePermissionMode, permissionRank } from './chief-executor.js'
|
|
10
|
+
import { detectPrematurePromiseText } from './idle-guard.js'
|
|
10
11
|
import {
|
|
11
12
|
CHAT_CAP,
|
|
12
13
|
REVIEW_DELAY_MS,
|
|
13
14
|
SMART_REVIEW_COOLDOWN_MS,
|
|
14
15
|
AUTO_REVIEW_COOLDOWN_MS,
|
|
16
|
+
DEFAULT_MANAGED_IDLE_TIMEOUT_MS,
|
|
15
17
|
SUMMARY_MAX_TOKENS,
|
|
16
18
|
archiveTargetForRoot,
|
|
17
19
|
nextId,
|
|
@@ -33,11 +35,12 @@ import {
|
|
|
33
35
|
beginChiefActiveWork,
|
|
34
36
|
updateChiefActiveWork,
|
|
35
37
|
endChiefActiveWork,
|
|
38
|
+
pushAlertEventToWs,
|
|
36
39
|
} from './chief-state.js'
|
|
37
40
|
import { listChiefModels, callChiefLlm } from './chief-models.js'
|
|
38
41
|
import { listPeerDirectory, deliverCrossMessage } from './chief-network.js'
|
|
39
42
|
import { summarizingLocks, getChiefView, registerIdleAutoPilotHook } from './chief-view.js'
|
|
40
|
-
import {
|
|
43
|
+
import { runManagedDreamRoam } from './chief-archives.js'
|
|
41
44
|
import {
|
|
42
45
|
waitUntilAgentIdle,
|
|
43
46
|
measureAgentSessionTokensFallback,
|
|
@@ -46,6 +49,7 @@ import {
|
|
|
46
49
|
maybeRunPreCompaction,
|
|
47
50
|
} from './chief-compaction.js'
|
|
48
51
|
import { applyFactChanges, applyBoardOps } from './chief-commands.js'
|
|
52
|
+
import { executeBatchSuggestions } from './chief-approvals.js'
|
|
49
53
|
|
|
50
54
|
const TURN_REVIEW_SYSTEM = [
|
|
51
55
|
'你是「DSH 参谋长」(宰相级协同与督导中枢)的后台复盘与督导模块。某个对话刚结束一轮输出。',
|
|
@@ -63,7 +67,7 @@ const TURN_REVIEW_SYSTEM = [
|
|
|
63
67
|
' - 当 `INTERVENTION_SUPERVISOR` 或 `AUTO_PILOT_SESSION_ONLY` 开启时,你必须严密审查:主/子代理刚刚提出、准备执行、请求用户拍板,或接下来继续推进是否**存在重大不可逆风险,或继续推进必然会撞穿当前生效边界(尤其 🚫 禁止红线)**?',
|
|
64
68
|
' - **重要提示(下列仅是常见举例,绝不限于此!)**:包括但不限于实际花钱/扣费/下单/付费 API 调用、不可逆删除或清空文件/数据/仓库、下载超大文件占用巨额磁盘或流量、关闭/重启服务器或关键宿主服务、对外公开推送/发布不可撤回变更、破坏宿主机隔离边界、以及任何一旦继续推跑就会导致不可逆损失或必然撞穿红线的情形。',
|
|
65
69
|
' - 一旦命中任一上述风险或必然撞边界:**必须立即设 `"hazardStop": { "triggered": true, "category": "...", "title": "简短醒目告警标题", "reason": "用清晰人话说清具体会造成什么不可逆损失或必然撞上哪条边界,以及为何必须立即停下等用户处理" }`,并强制设 `"shouldIntervene": false`、`interventionText: ""`**(严禁再推下一轮!)。',
|
|
66
|
-
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false
|
|
70
|
+
'6. `shouldIntervene` & `interventionText`:当开启「主动强介入 (`INTERVENTION_SUPERVISOR`)」且 `hazardStop.triggered === false` 时,**触发复盘代表主对话刚刚结束了本轮输出、当前已停下进入空闲 (`status=idle`)**!对照「核心目标 + 必做事项 + 最新用户/参谋诉求」逐项核验:只要目标或必做事项尚未真正做完、主对话仅用「重启 XX / 补跑剩余 N 张 / 接下来写脚本 / 继续推进」等口头预告收尾却未真正调用工具落实、或缺少实测验证证据却自称完成,**必须**设 `shouldIntervene: true` 并写出清晰可执行、可直接投递给 `@lead` 继续推进下一回合的 `interventionText` 督导指令;若处于 `strictVerify` 模式但回复无实测输出证据,务必驳回自称完成并要求补跑验证;若开启 `conciseBrief`,督导指令严格限定在 3 条以内要点。仅当核心目标与必做事项均已完成 (`achieved`)、或确认有活跃子代理正在后台运行等待回信时,才设 `shouldIntervene: false`。',
|
|
67
71
|
'7. `suggestions`(最多 1 条,宁缺毋滥):',
|
|
68
72
|
' - `"kind": "bound"`:明显撞墙或发现长期红线/必做规矩时请示注入边界;',
|
|
69
73
|
' - `"kind": "relay"`:发现明确跨对话信息差时的递话建议;',
|
|
@@ -144,6 +148,58 @@ function detectEmergencyHazardFallback({ parsed, digestText = '', bounds = {}, i
|
|
|
144
148
|
|
|
145
149
|
const reviewTimers = new Map()
|
|
146
150
|
|
|
151
|
+
const DIRECTIVE_SOURCE_KINDS = new Set([
|
|
152
|
+
'',
|
|
153
|
+
'user',
|
|
154
|
+
'dsh-chief-relay',
|
|
155
|
+
'dsh-chief-execution-request',
|
|
156
|
+
'dsh-chief-auto-continue',
|
|
157
|
+
])
|
|
158
|
+
|
|
159
|
+
const HIGH_RISK_FALLBACK_RE = /(?:花钱|扣费|付款|付费|下单|充值|删库|永久删除|清空目录|格式化|关闭服务器|停服|重启宿主|git\s+push|npm\s+publish|请确认|请选择|需要您|请指示|请拍板)/i
|
|
160
|
+
|
|
161
|
+
function extractMessageTextBlocks(msg) {
|
|
162
|
+
const blocks = Array.isArray(msg && msg.content)
|
|
163
|
+
? msg.content
|
|
164
|
+
: (typeof (msg && msg.content) === 'string' ? [{ type: 'text', text: msg.content }] : [])
|
|
165
|
+
const textParts = []
|
|
166
|
+
const toolHints = []
|
|
167
|
+
for (const b of blocks) {
|
|
168
|
+
if (!b || typeof b !== 'object') continue
|
|
169
|
+
if (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
|
|
170
|
+
textParts.push(b.text.trim())
|
|
171
|
+
} else if ((b.type === 'tool_use' || b.type === 'tool-call' || b.type === 'toolCall') && (b.name || b.toolName)) {
|
|
172
|
+
const tName = String(b.name || b.toolName)
|
|
173
|
+
let argHint = ''
|
|
174
|
+
try {
|
|
175
|
+
const rawArgs = b.input || b.arguments || b.args
|
|
176
|
+
const obj = typeof rawArgs === 'string' ? JSON.parse(rawArgs) : rawArgs
|
|
177
|
+
if (obj && typeof obj === 'object') {
|
|
178
|
+
const val = obj.action || obj.command || obj.cmd || obj.path || obj.file_path || obj.agent || obj.title || ''
|
|
179
|
+
if (val) argHint = clamp(String(val), 40)
|
|
180
|
+
}
|
|
181
|
+
} catch {}
|
|
182
|
+
toolHints.push(argHint ? `${tName}(${argHint})` : tName)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
text: textParts.join('\n').trim(),
|
|
187
|
+
toolHints,
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function resolveTurnTag(turn) {
|
|
192
|
+
if (typeof turn === 'number' && Number.isFinite(turn)) return String(turn)
|
|
193
|
+
if (turn && typeof turn === 'object') {
|
|
194
|
+
if (turn.turn !== undefined) return String(turn.turn)
|
|
195
|
+
if (turn.index !== undefined) return String(turn.index)
|
|
196
|
+
if (turn.id !== undefined) return String(turn.id)
|
|
197
|
+
if (turn.ok) return 'ok'
|
|
198
|
+
if (turn.error) return 'err'
|
|
199
|
+
}
|
|
200
|
+
return 't'
|
|
201
|
+
}
|
|
202
|
+
|
|
147
203
|
function extractLatestTurnDigest(agent, turn) {
|
|
148
204
|
if (!agent || !agent.session) return null
|
|
149
205
|
try {
|
|
@@ -153,48 +209,63 @@ function extractLatestTurnDigest(agent, turn) {
|
|
|
153
209
|
for (let i = msgs.length - 1; i >= 0; i -= 1) {
|
|
154
210
|
const um = msgs[i]
|
|
155
211
|
if (!um || um.role !== 'user') continue
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
const uTxt =
|
|
159
|
-
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
160
|
-
.map(b => b.text)
|
|
161
|
-
.join('\n')
|
|
162
|
-
.trim()
|
|
212
|
+
const srcKind = String((um.source && um.source.kind) || '').trim()
|
|
213
|
+
if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
|
|
214
|
+
const uTxt = extractMessageTextBlocks(um).text
|
|
163
215
|
if (uTxt && !isInternalCheckpointNoise(uTxt)) {
|
|
164
216
|
latestUserPrompt = clamp(uTxt, 1000)
|
|
165
217
|
break
|
|
166
218
|
}
|
|
167
219
|
}
|
|
168
220
|
|
|
169
|
-
const
|
|
170
|
-
const
|
|
221
|
+
const scanStart = Math.max(0, msgs.length - 24)
|
|
222
|
+
const collected = []
|
|
171
223
|
let hasUser = false
|
|
172
|
-
|
|
224
|
+
let lastAssistantText = ''
|
|
225
|
+
for (let i = msgs.length - 1; i >= scanStart && collected.length < 8; i -= 1) {
|
|
226
|
+
const m = msgs[i]
|
|
173
227
|
if (!m || !m.role) continue
|
|
174
|
-
|
|
175
|
-
const blocks = Array.isArray(m.content) ? m.content : []
|
|
176
|
-
const txt = blocks
|
|
177
|
-
.filter(b => b && b.type === 'text' && typeof b.text === 'string')
|
|
178
|
-
.map(b => b.text)
|
|
179
|
-
.join('\n')
|
|
180
|
-
.trim()
|
|
181
|
-
if (!txt || isInternalCheckpointNoise(txt)) continue
|
|
228
|
+
const srcKind = String((m.source && m.source.kind) || '').trim()
|
|
182
229
|
if (m.role === 'user') {
|
|
183
|
-
|
|
184
|
-
|
|
230
|
+
if (!DIRECTIVE_SOURCE_KINDS.has(srcKind)) continue
|
|
231
|
+
const uTxt = extractMessageTextBlocks(m).text
|
|
232
|
+
if (!uTxt || isInternalCheckpointNoise(uTxt)) continue
|
|
233
|
+
if (!srcKind || srcKind === 'user') {
|
|
234
|
+
hasUser = true
|
|
235
|
+
collected.push('User: ' + clamp(uTxt, 1200))
|
|
236
|
+
} else {
|
|
237
|
+
collected.push('Chief->Lead: ' + clamp(uTxt, 900))
|
|
238
|
+
}
|
|
185
239
|
} else if (m.role === 'assistant') {
|
|
186
|
-
|
|
240
|
+
const { text: aTxt, toolHints } = extractMessageTextBlocks(m)
|
|
241
|
+
const cleanTxt = aTxt && !isInternalCheckpointNoise(aTxt) ? aTxt : ''
|
|
242
|
+
if (!cleanTxt && !toolHints.length) continue
|
|
243
|
+
if (cleanTxt) {
|
|
244
|
+
if (!lastAssistantText) lastAssistantText = cleanTxt
|
|
245
|
+
collected.push('Assistant: ' + clamp(cleanTxt, 900) + (toolHints.length ? ` [Tools: ${toolHints.slice(0, 4).join(' -> ')}]` : ''))
|
|
246
|
+
} else {
|
|
247
|
+
collected.push('Assistant Tools: ' + toolHints.slice(0, 6).join(' -> '))
|
|
248
|
+
}
|
|
187
249
|
}
|
|
188
250
|
}
|
|
189
|
-
|
|
251
|
+
const lines = collected.reverse()
|
|
252
|
+
if (lines.length > 0) {
|
|
253
|
+
const joined = lines.join('\n')
|
|
254
|
+
const lastMsg = msgs[msgs.length - 1]
|
|
255
|
+
const lastMsgId = String((lastMsg && (lastMsg.id || lastMsg.messageId || lastMsg.timestamp)) || 'm').slice(0, 24)
|
|
256
|
+
const tailHash8 = crypto.createHash('sha1').update(joined).digest('hex').slice(0, 8)
|
|
257
|
+
const stamp = `${resolveTurnTag(turn)}:${msgs.length}:${lastMsgId}:${tailHash8}`
|
|
258
|
+
return { text: joined, hasUser, latestUserPrompt, lastAssistantText, msgCount: msgs.length, stamp }
|
|
259
|
+
}
|
|
190
260
|
}
|
|
191
261
|
} catch {}
|
|
192
262
|
return null
|
|
193
263
|
}
|
|
194
264
|
|
|
195
265
|
const lastReviewAtByRoot = new Map()
|
|
266
|
+
const lastFallbackStampByRoot = new Map()
|
|
196
267
|
|
|
197
|
-
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
268
|
+
export function scheduleChiefTurnReview(deps, { agent, sessionId, turn, abnormalTrigger = '', delayOverrideMs = null }) {
|
|
198
269
|
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
199
270
|
if (!sid) return
|
|
200
271
|
// Never waste tokens reviewing internal mnemon checkpoint / probe subagents
|
|
@@ -204,35 +275,44 @@ export function scheduleChiefTurnReview(deps, { agent, sessionId, turn }) {
|
|
|
204
275
|
const state = loadChiefState()
|
|
205
276
|
const rootKey = (deps && deps.resolveRootSessionId ? deps.resolveRootSessionId(sid, agent) : '') || sid
|
|
206
277
|
const effCfg = resolveWorkspaceConfig(state, rootKey)
|
|
207
|
-
const
|
|
208
|
-
|
|
278
|
+
const runMode = effCfg.runMode || 'off'
|
|
279
|
+
const tactical = normalizeTacticalModes(effCfg.tacticalModes)
|
|
280
|
+
const wsSnap = state.workspaces && state.workspaces[rootKey] ? state.workspaces[rootKey] : null
|
|
281
|
+
const pendingSmart = Boolean(wsSnap && wsSnap.runtimeGuard && wsSnap.runtimeGuard.pendingSmartCompact)
|
|
282
|
+
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
283
|
+
const interventionChannel = Boolean(tactical.intervention)
|
|
284
|
+
|
|
285
|
+
if (effCfg.stopped || (runMode === 'off' && !compactChannel && !interventionChannel)) {
|
|
209
286
|
clearTimeout(reviewTimers.get(rootKey))
|
|
210
287
|
reviewTimers.delete(rootKey)
|
|
211
288
|
return
|
|
212
289
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
290
|
+
|
|
291
|
+
// In PATROL mode: normal turns consume 0 background tokens; wake ONLY on explicit abnormal triggers, compaction, or intervention
|
|
292
|
+
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
293
|
+
if (runMode === 'patrol' && !hasAbnormal && !compactChannel && !interventionChannel) {
|
|
294
|
+
return
|
|
295
|
+
}
|
|
296
|
+
|
|
216
297
|
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
217
298
|
? deps.boardForSession(deps.boardFileFor(rootKey))
|
|
218
299
|
: null
|
|
219
300
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
220
|
-
const hasHighPriorityChannel =
|
|
221
|
-
|
|
222
|
-
// Default 'manual' mode without tactical/goal active: ZERO background LLM calls!
|
|
223
|
-
if (!hasHighPriorityChannel && (paceMode === 'manual' || effCfg.autoReview === false)) return
|
|
301
|
+
const hasHighPriorityChannel = hasAbnormal || isGoalMode || compactChannel || interventionChannel || tactical.redlineSentinel || tactical.strictVerify
|
|
224
302
|
|
|
225
303
|
clearTimeout(reviewTimers.get(rootKey))
|
|
226
|
-
const delayMs =
|
|
304
|
+
const delayMs = delayOverrideMs !== null && Number.isFinite(Number(delayOverrideMs)) && Number(delayOverrideMs) >= 0
|
|
305
|
+
? Math.max(100, Math.round(Number(delayOverrideMs)))
|
|
306
|
+
: (hasHighPriorityChannel ? 1_200 : REVIEW_DELAY_MS)
|
|
227
307
|
const timer = setTimeout(() => {
|
|
228
308
|
reviewTimers.delete(rootKey)
|
|
229
|
-
runTurnReview(deps, { agent, sessionId: sid, turn }).catch(() => {})
|
|
309
|
+
runTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger }).catch(() => {})
|
|
230
310
|
}, delayMs)
|
|
231
311
|
timer.unref?.()
|
|
232
312
|
reviewTimers.set(rootKey, timer)
|
|
233
313
|
}
|
|
234
314
|
|
|
235
|
-
export async function runTurnReview(deps, { agent, sessionId, turn, force = false }) {
|
|
315
|
+
export async function runTurnReview(deps, { agent, sessionId, turn, force = false, abnormalTrigger = '' }) {
|
|
236
316
|
const sid = String(sessionId || (agent && agent.id) || '').trim()
|
|
237
317
|
if (!sid) return { ok: false, skipped: 'no-session' }
|
|
238
318
|
const rootId = (deps.resolveRootSessionId && deps.resolveRootSessionId(sid, agent)) || sid
|
|
@@ -240,25 +320,29 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
240
320
|
const stateBefore = loadChiefState()
|
|
241
321
|
const effCfgBefore = resolveWorkspaceConfig(stateBefore, rootId)
|
|
242
322
|
const tactical = normalizeTacticalModes(effCfgBefore.tacticalModes)
|
|
323
|
+
const runMode = effCfgBefore.runMode || 'off'
|
|
243
324
|
const paceMode = effCfgBefore.paceMode || 'manual'
|
|
244
|
-
|
|
325
|
+
const wsBefore = ensureWorkspace(stateBefore, rootId)
|
|
326
|
+
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
327
|
+
const compactChannel = Boolean(tactical.autoCompact || tactical.smartCompact || pendingSmart)
|
|
328
|
+
const interventionChannel = Boolean(tactical.intervention)
|
|
329
|
+
const hasAbnormal = Boolean(String(abnormalTrigger || '').trim())
|
|
330
|
+
|
|
331
|
+
if (!force && effCfgBefore.stopped) {
|
|
245
332
|
return { ok: false, skipped: 'chief-stopped' }
|
|
246
333
|
}
|
|
247
|
-
|
|
334
|
+
if (!force && runMode === 'off' && !compactChannel && !interventionChannel) {
|
|
335
|
+
return { ok: false, skipped: 'off' }
|
|
336
|
+
}
|
|
248
337
|
const board = deps.boardForSession && deps.boardFileFor
|
|
249
338
|
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
250
339
|
: null
|
|
251
340
|
const isGoalMode = Boolean(board && board.mode === 'goal')
|
|
252
|
-
const pendingSmart = Boolean(wsBefore.runtimeGuard && wsBefore.runtimeGuard.pendingSmartCompact)
|
|
253
341
|
const smartCoManaged = Boolean(tactical.smartCompact)
|
|
254
|
-
const hasHighPriority = isGoalMode ||
|
|
255
|
-
|
|
256
|
-
if (!force && !hasHighPriority && paceMode === 'manual') {
|
|
257
|
-
return { ok: false, skipped: 'manual' }
|
|
258
|
-
}
|
|
342
|
+
const hasHighPriority = hasAbnormal || isGoalMode || interventionChannel || tactical.redlineSentinel || tactical.strictVerify || compactChannel
|
|
259
343
|
|
|
260
344
|
// Always check pre-compaction pipeline first when autoCompact/smartCompact/pendingSmartCompact is active
|
|
261
|
-
if (
|
|
345
|
+
if (compactChannel) {
|
|
262
346
|
const preRes = await maybeRunPreCompaction(deps, { agent, sessionId: sid, rootId, bypassIdleWait: Boolean(force) })
|
|
263
347
|
.catch((err) => {
|
|
264
348
|
const msg = (err && err.message) || String(err || 'pre-compact-error')
|
|
@@ -267,18 +351,35 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
267
351
|
}
|
|
268
352
|
return { ok: false, error: msg }
|
|
269
353
|
})
|
|
270
|
-
if (preRes && preRes.ok && preRes.smartCompacted) {
|
|
354
|
+
if (preRes && preRes.ok && preRes.smartCompacted && !interventionChannel) {
|
|
271
355
|
return { ok: true, smartCompacted: true, harvestId: preRes.harvestId }
|
|
272
356
|
}
|
|
273
357
|
}
|
|
274
358
|
|
|
275
|
-
// If
|
|
276
|
-
|
|
277
|
-
if (!force &&
|
|
359
|
+
// If runMode === 'off' and we only entered for standalone smartCompact/autoCompact pre-check,
|
|
360
|
+
// exit cleanly once autoCompact threshold isn't forcing LLM, except when smartCoManaged or intervention needs evaluation.
|
|
361
|
+
if (!force && runMode === 'off' && !smartCoManaged && !interventionChannel) {
|
|
362
|
+
return { ok: true, onlyCompactionChecked: true }
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
// If ONLY fixed-threshold autoCompact was on (without smartCompact, intervention, patrol-abnormal, or managed), exit cleanly
|
|
366
|
+
const needsSupervisorLlm = (runMode === 'managed')
|
|
367
|
+
|| (runMode === 'patrol' && hasAbnormal)
|
|
368
|
+
|| smartCoManaged
|
|
369
|
+
|| interventionChannel
|
|
370
|
+
|| (force && (isGoalMode || tactical.intervention || tactical.redlineSentinel || tactical.strictVerify))
|
|
371
|
+
if (!force && !needsSupervisorLlm && runMode !== 'patrol') {
|
|
372
|
+
return { ok: true, onlyCompactionChecked: true }
|
|
373
|
+
}
|
|
278
374
|
|
|
279
375
|
const digest = extractLatestTurnDigest(agent, turn)
|
|
280
376
|
if (!digest || !digest.text) return { ok: false, skipped: 'no-digest' }
|
|
281
377
|
|
|
378
|
+
const hasWallCue = hasAbnormal || /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
379
|
+
if (!force && runMode === 'patrol' && !hasWallCue && !smartCoManaged && !interventionChannel) {
|
|
380
|
+
return { ok: false, skipped: 'patrol-no-abnormal' }
|
|
381
|
+
}
|
|
382
|
+
|
|
282
383
|
const cursorKey = `${sid}`
|
|
283
384
|
if (!force && wsBefore.reviewCursors[cursorKey] === digest.stamp) {
|
|
284
385
|
return { ok: false, skipped: 'same-stamp' }
|
|
@@ -287,13 +388,19 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
287
388
|
const identity = deps.resolveAgentIdentity ? deps.resolveAgentIdentity(deps.runtime, sid, agent) : null
|
|
288
389
|
if (identity && /^mnemon-(?:review|run)/i.test(String(identity.self || ''))) return { ok: false, skipped: 'mnemon' }
|
|
289
390
|
|
|
290
|
-
const hasWallCue = /(?:permission denied|eacces|eperm|forbidden|blocked|not allowed|sandbox|read-only|撞墙|受阻|权限拒绝|越界)/i.test(digest.text)
|
|
291
391
|
const now = Date.now()
|
|
292
392
|
const lastAt = Number(lastReviewAtByRoot.get(rootId) || 0)
|
|
293
393
|
const cooldownMs = hasHighPriority
|
|
294
|
-
? (smartCoManaged && !isGoalMode && !tactical.intervention ? 12_000 : 4_000)
|
|
295
|
-
: (
|
|
296
|
-
if (!force && now - lastAt < cooldownMs)
|
|
394
|
+
? (smartCoManaged && !isGoalMode && !tactical.intervention && !hasAbnormal ? 12_000 : 4_000)
|
|
395
|
+
: (runMode === 'patrol' ? (hasWallCue ? 45_000 : SMART_REVIEW_COOLDOWN_MS) : AUTO_REVIEW_COOLDOWN_MS)
|
|
396
|
+
if (!force && now - lastAt < cooldownMs) {
|
|
397
|
+
if (interventionChannel || isGoalMode || hasAbnormal) {
|
|
398
|
+
const waitMs = Math.max(500, cooldownMs - (now - lastAt) + 250)
|
|
399
|
+
scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger, delayOverrideMs: waitMs })
|
|
400
|
+
return { ok: false, skipped: 'cooldown', rescheduled: true, waitMs }
|
|
401
|
+
}
|
|
402
|
+
return { ok: false, skipped: 'cooldown' }
|
|
403
|
+
}
|
|
297
404
|
|
|
298
405
|
// Wait if supervisor/goal/smart-compact is active so turn-stopping settles to idle before evaluating usage
|
|
299
406
|
if ((tactical.intervention || isGoalMode || smartCoManaged) && typeof deps.getAgentStatus === 'function' && !force) {
|
|
@@ -314,17 +421,14 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
314
421
|
|
|
315
422
|
// In 'smart' background mode (without supervisor/goal), gate LLM call on wall cue or multi-agent human turn;
|
|
316
423
|
// when ONLY smartCoManaged is enabled in manual pace, evaluate only after enough turns or context pressure.
|
|
317
|
-
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify) {
|
|
318
|
-
if (smartCoManaged &&
|
|
424
|
+
if (!force && !isGoalMode && !tactical.intervention && !tactical.redlineSentinel && !tactical.strictVerify && !hasAbnormal) {
|
|
425
|
+
if (smartCoManaged && runMode === 'off') {
|
|
319
426
|
const ratio = liveUsage && liveUsage.contextWindow ? (Number(liveUsage.totalTokens) || 0) / Number(liveUsage.contextWindow) : 0
|
|
320
427
|
const sinceCompact = now - ((wsBefore.runtimeGuard && wsBefore.runtimeGuard.lastCompactedAt) || 0)
|
|
321
|
-
if ((digest.
|
|
428
|
+
if ((digest.msgCount < 4 && ratio < 0.25) || sinceCompact < 20_000) {
|
|
322
429
|
return { ok: false, skipped: 'smart-compact-light' }
|
|
323
430
|
}
|
|
324
|
-
} else {
|
|
325
|
-
if (paceMode === 'smart' && !hasWallCue && !(digest.hasUser && realPeers.length > 1)) {
|
|
326
|
-
return { ok: false, skipped: 'smart-quiet' }
|
|
327
|
-
}
|
|
431
|
+
} else if (runMode === 'managed') {
|
|
328
432
|
if (!digest.hasUser && realPeers.length <= 1 && !hasWallCue) return { ok: false, skipped: 'single-quiet' }
|
|
329
433
|
}
|
|
330
434
|
}
|
|
@@ -335,11 +439,13 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
335
439
|
}
|
|
336
440
|
|
|
337
441
|
lastReviewAtByRoot.set(rootId, now)
|
|
338
|
-
const isAutoPilotActiveNow = Boolean(
|
|
442
|
+
const isAutoPilotActiveNow = Boolean(runMode === 'managed' && !effCfgBefore.stopped)
|
|
339
443
|
const reviewWorkId = beginChiefActiveWork(rootId, {
|
|
340
444
|
tone: 'neon',
|
|
341
445
|
tab: '',
|
|
342
|
-
label:
|
|
446
|
+
label: runMode === 'patrol'
|
|
447
|
+
? '参谋长正在巡检异常与诊断边界中...'
|
|
448
|
+
: (isAutoPilotActiveNow ? '参谋长正在托管督导巡检中...' : '参谋长正在后台复盘研判中...'),
|
|
343
449
|
})
|
|
344
450
|
try {
|
|
345
451
|
const speaker = identity && identity.isChild ? `子代理 @${identity.self}` : '主对话 (@lead)'
|
|
@@ -358,15 +464,16 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
358
464
|
tactical.strictVerify ? 'STRICT_VERIFY' : '',
|
|
359
465
|
tactical.redlineSentinel ? 'REDLINE_SENTINEL' : '',
|
|
360
466
|
tactical.conciseBrief ? 'CONCISE_BRIEF_3_BULLETS' : '',
|
|
361
|
-
Boolean(
|
|
467
|
+
Boolean(runMode === 'managed' && !effCfgBefore.stopped) ? 'AUTO_PILOT_SESSION_ONLY' : '',
|
|
468
|
+
hasAbnormal ? `ABNORMAL_PATROL_TRIGGER(${abnormalTrigger})` : '',
|
|
362
469
|
].filter(Boolean)
|
|
363
470
|
|
|
364
471
|
const smartUsageHint = smartCoManaged
|
|
365
|
-
?
|
|
472
|
+
? `智选共管状态(硬阈值已停用):消息数≈${digest.msgCount}${liveUsage && liveUsage.totalTokens ? `,当前估算上下文 ${liveUsage.totalTokens}/${liveUsage.contextWindow} (${Math.round((liveUsage.totalTokens / liveUsage.contextWindow) * 100)}%)` : ''}`
|
|
366
473
|
: ''
|
|
367
474
|
|
|
368
475
|
const prompt = [
|
|
369
|
-
`当前激活监督模式:${activeFlags.join(' | ') ||
|
|
476
|
+
`当前激活监督模式:${activeFlags.join(' | ') || runMode}`,
|
|
370
477
|
...(smartUsageHint ? [smartUsageHint] : []),
|
|
371
478
|
`工作区总目标 (Objective):${(board && board.objective) || '(暂未开启 /goal 固定目标 — 请对照下方最新用户原始诉求核验完成度)'}`,
|
|
372
479
|
`最新用户原始诉求:${digest.latestUserPrompt || '(见下方对话片段)'}`,
|
|
@@ -387,23 +494,73 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
387
494
|
digest.text,
|
|
388
495
|
].join('\n')
|
|
389
496
|
|
|
497
|
+
const reviewReasonKind = hasAbnormal
|
|
498
|
+
? 'wall_blocked'
|
|
499
|
+
: (tactical.intervention ? 'strong_intervention' : 'turn_review')
|
|
390
500
|
const res = await callChiefLlm(deps, {
|
|
391
501
|
sessionId: rootId,
|
|
502
|
+
reasonKind: reviewReasonKind,
|
|
392
503
|
system: TURN_REVIEW_SYSTEM,
|
|
393
504
|
prompt,
|
|
394
505
|
maxTokens: SUMMARY_MAX_TOKENS,
|
|
395
506
|
})
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
507
|
+
const parsed = res && res.ok ? extractJsonObject(res.text) : null
|
|
508
|
+
if (!res.ok || !parsed) {
|
|
509
|
+
const errTag = !res.ok ? (res.error || 'review-llm-failed') : 'non-json-review'
|
|
510
|
+
if (interventionChannel) {
|
|
511
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
512
|
+
deps.appendBoardLog(rootId, `⚠️ 强介入后台复盘异常(${clamp(errTag, 100)}),准备自动重试/兜底检查`, 'chief')
|
|
513
|
+
}
|
|
514
|
+
if (!force && abnormalTrigger !== 'review_retry') {
|
|
515
|
+
scheduleChiefTurnReview(deps, { agent, sessionId: sid, turn, abnormalTrigger: 'review_retry', delayOverrideMs: 5_000 })
|
|
516
|
+
}
|
|
517
|
+
const permCheck = normalizePermissionMode(effCfgBefore.permissionMode, {
|
|
518
|
+
requireAck: true,
|
|
519
|
+
hasChiefRiskAck: hasValidChiefRiskAck(wsBefore),
|
|
520
|
+
})
|
|
521
|
+
const canZeroLlmFallback = permCheck === 'chief'
|
|
522
|
+
&& hasValidChiefRiskAck(wsBefore)
|
|
523
|
+
&& !(identity && identity.isChild)
|
|
524
|
+
&& !HIGH_RISK_FALLBACK_RE.test(digest.lastAssistantText || '')
|
|
525
|
+
const fallbackCue = canZeroLlmFallback ? detectPrematurePromiseText(digest.lastAssistantText || '') : ''
|
|
526
|
+
if (fallbackCue && lastFallbackStampByRoot.get(rootId) !== digest.stamp) {
|
|
527
|
+
lastFallbackStampByRoot.set(rootId, digest.stamp)
|
|
528
|
+
const fbMsg = `【⚡ 参谋长零模型兜底续推】后台复盘模型暂时波动(${clamp(errTag, 60)}),但我检测到你刚才以口头预告下一步(「${fallbackCue}」)直接停在空闲态,且无高危风险提示。请立即调用工具落实该步并验证结果。`
|
|
529
|
+
const fbDeliv = await deliverCrossMessage(deps, {
|
|
530
|
+
fromSession: rootId,
|
|
531
|
+
fromLabel: 'DSH 参谋长 (强介入安全兜底)',
|
|
532
|
+
target: 'lead',
|
|
533
|
+
subject: '口头预告停摆 · 安全兜底推进',
|
|
534
|
+
text: fbMsg,
|
|
535
|
+
mode: 'followup',
|
|
536
|
+
envelopeKind: 'execution_request',
|
|
537
|
+
}).catch(() => null)
|
|
538
|
+
if (fbDeliv && fbDeliv.ok && fbDeliv.deliveredPhysical !== false) {
|
|
539
|
+
mutateChiefState((s) => {
|
|
540
|
+
const ws = ensureWorkspace(s, rootId)
|
|
541
|
+
ws.chat.push({
|
|
542
|
+
id: nextId('chat'),
|
|
543
|
+
role: 'chief',
|
|
544
|
+
kind: 'receipt',
|
|
545
|
+
text: `- 【⚡ 强介入兜底推进】复盘模型暂不可用,已针对口头预告停摆(「${fallbackCue}」)触发安全兜底唤醒 \`@lead\`。`,
|
|
546
|
+
actions: ['⚡ 兜底续推'],
|
|
547
|
+
at: Date.now(),
|
|
548
|
+
})
|
|
549
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
550
|
+
})
|
|
551
|
+
return { ok: true, fallbackIntervened: true, reason: errTag }
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return !res.ok ? { ok: false, error: res.error } : { ok: false, error: 'non-json-review' }
|
|
556
|
+
}
|
|
400
557
|
|
|
401
558
|
const cfgNow = resolveWorkspaceConfig(loadChiefState(), rootId)
|
|
402
559
|
const wsNowPerm = ensureWorkspace(loadChiefState(), rootId)
|
|
403
560
|
const hasAckNow = hasValidChiefRiskAck(wsNowPerm)
|
|
404
561
|
const permNow = normalizePermissionMode(cfgNow.permissionMode, { requireAck: true, hasChiefRiskAck: hasAckNow })
|
|
405
562
|
const permRankNow = permissionRank(permNow)
|
|
406
|
-
const autoPilot = Boolean(cfgNow.
|
|
563
|
+
const autoPilot = Boolean(cfgNow.runMode === 'managed' && !cfgNow.stopped)
|
|
407
564
|
const rawSuggestions = (Array.isArray(parsed.suggestions) ? parsed.suggestions : [])
|
|
408
565
|
.map(raw => normalizeSuggestion({ ...raw, fromAgent: raw?.fromAgent || speaker }))
|
|
409
566
|
.filter(Boolean)
|
|
@@ -468,6 +625,11 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
468
625
|
const autoBoundUpdates = []
|
|
469
626
|
let shouldAutoOrganizeSession = false
|
|
470
627
|
|
|
628
|
+
const hasRunningChild = realPeers.some(p => p.kind === 'subagent' && p.status === 'running')
|
|
629
|
+
const prematureCue = !(identity && identity.isChild)
|
|
630
|
+
? detectPrematurePromiseText(digest.lastAssistantText || '')
|
|
631
|
+
: ''
|
|
632
|
+
|
|
471
633
|
const isInternalRelayTarget = (targetRaw) => {
|
|
472
634
|
const tq = String(targetRaw || '').trim().replace(/^@/, '')
|
|
473
635
|
if (!tq) return false
|
|
@@ -530,8 +692,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
530
692
|
}
|
|
531
693
|
}
|
|
532
694
|
|
|
695
|
+
const useOneStopRunnerNow = Boolean(permNow === 'chief' && hasAckNow && tactical.intervention)
|
|
533
696
|
for (const sug of rawSuggestions) {
|
|
534
|
-
if (sug.kind === 'bound') {
|
|
697
|
+
if (!useOneStopRunnerNow && sug.kind === 'bound') {
|
|
535
698
|
const colList = Array.isArray(bounds[sug.boundField]) ? bounds[sug.boundField] : []
|
|
536
699
|
if (colList.some(x => String(x).trim() === sug.draftText)) continue
|
|
537
700
|
if (autoPilot && sug.draftText) {
|
|
@@ -541,7 +704,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
541
704
|
continue
|
|
542
705
|
}
|
|
543
706
|
}
|
|
544
|
-
if (autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
707
|
+
if (!useOneStopRunnerNow && autoPilot && sug.kind === 'relay' && sug.draftText && isInternalRelayTarget(sug.target)) {
|
|
545
708
|
if (permNow === 'chief' && hasAckNow) {
|
|
546
709
|
sug.status = 'applied'
|
|
547
710
|
autoRelays.push(sug)
|
|
@@ -571,9 +734,9 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
571
734
|
}
|
|
572
735
|
}
|
|
573
736
|
|
|
574
|
-
if (autoPilot && rootId && rootId !== 'global') {
|
|
737
|
+
if (autoPilot && permRankNow >= 1 && rootId && rootId !== 'global') {
|
|
575
738
|
const lastOrgAt = Number(ws.runtimeGuard.lastAutoArchiveOrgAt || 0)
|
|
576
|
-
if (!lastOrgAt || Date.now() - lastOrgAt >
|
|
739
|
+
if (!lastOrgAt || Date.now() - lastOrgAt > 60_000) {
|
|
577
740
|
shouldAutoOrganizeSession = true
|
|
578
741
|
}
|
|
579
742
|
}
|
|
@@ -616,15 +779,41 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
616
779
|
})
|
|
617
780
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
618
781
|
pushAuditToWs(ws, { mode: permNow, stage: 'safety_guard', decision: 'hazard_stop', operation: '强介入紧急煞车', target: 'lead', reason: hazardAlertCreated.reason, outcome: 'blocked', by: 'chief' })
|
|
782
|
+
pushAlertEventToWs(ws, {
|
|
783
|
+
kind: 'hazard_halt',
|
|
784
|
+
level: 'danger',
|
|
785
|
+
title: hazardAlertCreated.title,
|
|
786
|
+
body: hazardAlertCreated.reason,
|
|
787
|
+
dedupeKey: 'haz:' + hazardAlertCreated.id,
|
|
788
|
+
at: hazardAlertCreated.at || Date.now(),
|
|
789
|
+
})
|
|
619
790
|
} else {
|
|
620
791
|
// Intervention Supervisor follow-up + Circuit Breaker (differentiated across L0 / L1 / L2 / L3)
|
|
621
792
|
const unmetMustDoFallback = unmetMustDo.length > 0
|
|
622
793
|
? '当前尚有以下【必做事项】未确认交付或缺少验证证据,请逐项补齐并交卷:\n' + unmetMustDo.map((u, idx) => `${idx + 1}. ${u}`).join('\n')
|
|
623
794
|
: ''
|
|
795
|
+
const goalMissingFallback = cleanMultiline(parsed.goalMissing || '', 420)
|
|
796
|
+
? `对照锁定核心目标尚有未闭环缺口:${cleanMultiline(parsed.goalMissing, 360)}。请基于当前进展立刻调用工具补齐并提交验证结果。`
|
|
797
|
+
: ''
|
|
798
|
+
const prematureFallback = prematureCue && !hasRunningChild
|
|
799
|
+
? `检测到你刚才以口头预告下一步(「${prematureCue}」)直接结束了回合,但核心目标仍未收口。请立即调用工具把该步实际执行到位并验证输出。`
|
|
800
|
+
: ''
|
|
624
801
|
const candidateIntervention = parsed.interventionText
|
|
625
802
|
|| unmetMustDoFallback
|
|
803
|
+
|| goalMissingFallback
|
|
804
|
+
|| prematureFallback
|
|
626
805
|
|| (parsed.nextActionForLead && (parsed.shouldIntervene || parsed.goalStatus === 'in_progress') ? parsed.nextActionForLead : '')
|
|
627
|
-
|
|
806
|
+
const wantsIntervene = Boolean(
|
|
807
|
+
parsed.shouldIntervene
|
|
808
|
+
|| unmetMustDo.length > 0
|
|
809
|
+
|| (parsed.goalStatus === 'in_progress' && (
|
|
810
|
+
Boolean(parsed.interventionText)
|
|
811
|
+
|| Boolean(parsed.nextActionForLead)
|
|
812
|
+
|| Boolean(parsed.goalMissing)
|
|
813
|
+
|| Boolean(prematureCue && !hasRunningChild)
|
|
814
|
+
))
|
|
815
|
+
)
|
|
816
|
+
if (!isGoalAchieved && tactical.intervention && wantsIntervene && candidateIntervention) {
|
|
628
817
|
const assistantTail = (digest.text.split('Assistant:').pop() || digest.text)
|
|
629
818
|
const sig = crypto
|
|
630
819
|
.createHash('sha1')
|
|
@@ -774,7 +963,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
774
963
|
} else {
|
|
775
964
|
const contextWindow = Math.max(1000, Number(liveUsage && liveUsage.contextWindow) || 128_000)
|
|
776
965
|
const totalTokens = Number(liveUsage && liveUsage.totalTokens) || 0
|
|
777
|
-
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.
|
|
966
|
+
const seq = Math.max(0, Math.round(Number(liveUsage && liveUsage.seq) || digest.msgCount || 0))
|
|
778
967
|
const ratioPct = totalTokens > 0 ? (totalTokens / contextWindow) * 100 : 0
|
|
779
968
|
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
780
969
|
tone: 'archive',
|
|
@@ -835,20 +1024,59 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
835
1024
|
})
|
|
836
1025
|
}
|
|
837
1026
|
|
|
1027
|
+
let interventionDeliveredFailed = false
|
|
838
1028
|
if (interventionMessage) {
|
|
839
1029
|
const tags = [
|
|
840
1030
|
tactical.strictVerify ? '严格校验实测' : '',
|
|
841
1031
|
tactical.redlineSentinel ? '红线哨兵巡检' : '',
|
|
842
1032
|
tactical.conciseBrief ? '精炼要点' : '',
|
|
843
1033
|
].filter(Boolean).join(' · ')
|
|
844
|
-
await deliverCrossMessage(deps, {
|
|
1034
|
+
const delivRes = await deliverCrossMessage(deps, {
|
|
845
1035
|
fromSession: rootId,
|
|
846
1036
|
fromLabel: `DSH 参谋长 (接管督导${tags ? '·' + tags : ''})`,
|
|
847
1037
|
target: 'lead',
|
|
848
1038
|
subject: '参谋长自动督导推进',
|
|
849
1039
|
text: interventionMessage,
|
|
850
1040
|
mode: 'followup',
|
|
851
|
-
|
|
1041
|
+
envelopeKind: 'execution_request',
|
|
1042
|
+
}).catch(err => ({ ok: false, deliveredPhysical: false, error: String(err && err.message ? err.message : err) }))
|
|
1043
|
+
const deliveredOk = Boolean(delivRes && delivRes.ok && delivRes.deliveredPhysical !== false)
|
|
1044
|
+
if (deliveredOk) {
|
|
1045
|
+
mutateChiefState((s) => {
|
|
1046
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1047
|
+
const turnIdx = ws.runtimeGuard.interventionTurns || 1
|
|
1048
|
+
ws.chat.push({
|
|
1049
|
+
id: nextId('chat'),
|
|
1050
|
+
role: 'chief',
|
|
1051
|
+
kind: 'receipt',
|
|
1052
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1053
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1054
|
+
text: `- 【⚡ 强介入督导 · 第 ${turnIdx} 轮】已推动 \`@lead\` 继续执行:${clamp(interventionMessage, 220)}`,
|
|
1055
|
+
actions: [`⚡ 强介入督导 #${turnIdx}`],
|
|
1056
|
+
at: Date.now(),
|
|
1057
|
+
})
|
|
1058
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1059
|
+
})
|
|
1060
|
+
} else {
|
|
1061
|
+
interventionDeliveredFailed = true
|
|
1062
|
+
const failReason = (delivRes && (delivRes.note || delivRes.error)) || '目标会话句柄不可用或离线排队'
|
|
1063
|
+
mutateChiefState((s) => {
|
|
1064
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1065
|
+
ws.runtimeGuard.interventionTurns = Math.max(0, (ws.runtimeGuard.interventionTurns || 0) - 1)
|
|
1066
|
+
ws.chat.push({
|
|
1067
|
+
id: nextId('chat'),
|
|
1068
|
+
role: 'chief',
|
|
1069
|
+
kind: 'receipt',
|
|
1070
|
+
text: `- 【⚠️ 强介入督导未能物理唤醒】未能直接推醒 \`@lead\`(${clamp(failReason, 160)}),本轮未计入强介入次数。`,
|
|
1071
|
+
actions: ['⚠️ 强介入未送达'],
|
|
1072
|
+
at: Date.now(),
|
|
1073
|
+
})
|
|
1074
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1075
|
+
})
|
|
1076
|
+
if (typeof deps.appendBoardLog === 'function' && rootId !== 'global') {
|
|
1077
|
+
deps.appendBoardLog(rootId, `⚠️ 强介入督导投递未物理唤醒 @lead:${clamp(failReason, 140)}`, 'chief')
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
852
1080
|
}
|
|
853
1081
|
|
|
854
1082
|
if (permRankNow >= 1 && autoBoundUpdates.length > 0 && deps.runAction) {
|
|
@@ -871,29 +1099,91 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
871
1099
|
}
|
|
872
1100
|
}
|
|
873
1101
|
|
|
874
|
-
|
|
1102
|
+
let dreamRoamRes = null
|
|
1103
|
+
if (autoPilot && permRankNow >= 1 && !hazardStopped && rootId && rootId !== 'global') {
|
|
875
1104
|
try {
|
|
876
1105
|
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
1106
|
+
const globOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'global' })
|
|
877
1107
|
const stSess = loadArchiveStore(sessOpt)
|
|
878
|
-
const
|
|
879
|
-
|
|
880
|
-
).length
|
|
881
|
-
|
|
1108
|
+
const stGlob = loadArchiveStore(globOpt)
|
|
1109
|
+
const hasWatch = Array.isArray(stSess.recentlyUnpinnedWatch) && stSess.recentlyUnpinnedWatch.length > 0
|
|
1110
|
+
const hasUnhookedSess = (stSess.items || []).some(it => !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
|
|
1111
|
+
const hasUnhookedGlob = (stGlob.items || []).some(it => !it.hasHook || it.folder === 'inbox' || it.organizedBy !== 'chief' || (it.points || []).length <= 1)
|
|
1112
|
+
if (hasWatch || ((shouldAutoOrganizeSession || force) && (hasUnhookedSess || hasUnhookedGlob))) {
|
|
882
1113
|
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
883
|
-
tone: '
|
|
1114
|
+
tone: 'dream',
|
|
884
1115
|
tab: 'archive',
|
|
885
|
-
label: '
|
|
1116
|
+
label: '🌙 参谋长正在梦境漫游 · 轻拢卷宗与织就钩子中...',
|
|
886
1117
|
})
|
|
887
1118
|
mutateChiefState((s) => {
|
|
888
1119
|
const ws = ensureWorkspace(s, rootId)
|
|
889
1120
|
ws.runtimeGuard.lastAutoArchiveOrgAt = Date.now()
|
|
890
1121
|
})
|
|
891
|
-
await
|
|
1122
|
+
dreamRoamRes = await runManagedDreamRoam(deps, { sessionId: rootId }).catch(() => null)
|
|
1123
|
+
}
|
|
1124
|
+
} catch {}
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
// L3 Chief + Strong Intervention: One-Stop Task Runner sweeping safe pending suggestions
|
|
1128
|
+
// (excludes guard_wall, goal_approval, pinGlobal global bounds, and superseded L1 fallback advice when live intervention ran)
|
|
1129
|
+
let oneStopReport = null
|
|
1130
|
+
if (permNow === 'chief' && hasAckNow && tactical.intervention && !hazardStopped) {
|
|
1131
|
+
try {
|
|
1132
|
+
const wsLatest = ensureWorkspace(loadChiefState(), rootId)
|
|
1133
|
+
const safePending = (wsLatest.suggestions || []).filter(s =>
|
|
1134
|
+
s
|
|
1135
|
+
&& s.status === 'pending'
|
|
1136
|
+
&& s.kind !== 'guard_wall'
|
|
1137
|
+
&& s.kind !== 'wall_removal'
|
|
1138
|
+
&& s.kind !== 'goal_approval'
|
|
1139
|
+
&& !(s.kind === 'bound' && s.pinGlobal)
|
|
1140
|
+
&& !(interventionMessage && s.title === 'L1 强介入建议(等待拍板,未自动递给主对话)'),
|
|
1141
|
+
)
|
|
1142
|
+
if (safePending.length > 0) {
|
|
1143
|
+
updateChiefActiveWork(rootId, reviewWorkId, {
|
|
1144
|
+
tone: 'neon',
|
|
1145
|
+
tab: 'chief',
|
|
1146
|
+
label: '🏁 参谋长正在一站式推进建议清单中...',
|
|
1147
|
+
})
|
|
1148
|
+
const batchOut = await executeBatchSuggestions(deps, {
|
|
892
1149
|
sessionId: rootId,
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
1150
|
+
ids: safePending.map(s => s.id),
|
|
1151
|
+
includeGoalApproval: false,
|
|
1152
|
+
skipGuardWalls: true,
|
|
1153
|
+
skipGlobalBounds: true,
|
|
1154
|
+
byAutoRunner: true,
|
|
1155
|
+
skipChatReceipt: true,
|
|
1156
|
+
})
|
|
1157
|
+
if (batchOut && (batchOut.executedCount > 0 || batchOut.blockedCount > 0 || batchOut.failedCount > 0)) {
|
|
1158
|
+
oneStopReport = {
|
|
1159
|
+
executedCount: batchOut.executedCount,
|
|
1160
|
+
blockedCount: batchOut.blockedCount,
|
|
1161
|
+
failedCount: batchOut.failedCount,
|
|
1162
|
+
skippedGoalCount: batchOut.skippedGoalCount,
|
|
1163
|
+
summaries: batchOut.summaries || [],
|
|
1164
|
+
}
|
|
1165
|
+
mutateChiefState((s) => {
|
|
1166
|
+
const ws = ensureWorkspace(s, rootId)
|
|
1167
|
+
ws.chat.push({
|
|
1168
|
+
id: nextId('chat'),
|
|
1169
|
+
role: 'chief',
|
|
1170
|
+
kind: 'receipt',
|
|
1171
|
+
isOneStopReport: true,
|
|
1172
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1173
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1174
|
+
text: [
|
|
1175
|
+
`- 【🏁 一站式战报回执】L3 强介入已顺序推进 ${batchOut.executedCount} 项安全建议${batchOut.blockedCount ? ` · 安全护栏拦禁 ${batchOut.blockedCount} 项` : ''}${batchOut.skippedGoalCount ? ` · 保留高危/结项/全局项 ${batchOut.skippedGoalCount} 项待您亲裁` : ''}`,
|
|
1176
|
+
...(batchOut.summaries || []).map(line => ` ${line}`),
|
|
1177
|
+
].join('\n'),
|
|
1178
|
+
actions: [
|
|
1179
|
+
`🏁 一站式执行 ×${batchOut.executedCount}`,
|
|
1180
|
+
...(batchOut.blockedCount ? [`🛡️ 红线拦截 ×${batchOut.blockedCount}`] : []),
|
|
1181
|
+
],
|
|
1182
|
+
at: Date.now(),
|
|
1183
|
+
})
|
|
1184
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1185
|
+
})
|
|
1186
|
+
}
|
|
897
1187
|
}
|
|
898
1188
|
} catch {}
|
|
899
1189
|
}
|
|
@@ -935,6 +1225,7 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
935
1225
|
if (autoPilot && !interventionMessage && autoRelays.length === 0 && !circuitTripped) {
|
|
936
1226
|
autoPilotStopRes = await checkAndStopIdleAutoPilot(deps, rootId, {
|
|
937
1227
|
allowStartupGrace: false,
|
|
1228
|
+
goalAchievedFastStop: Boolean(isGoalAchieved),
|
|
938
1229
|
directory,
|
|
939
1230
|
fromViewCheck: false,
|
|
940
1231
|
}).catch(() => null)
|
|
@@ -950,11 +1241,15 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
950
1241
|
goalProposalCreated,
|
|
951
1242
|
hazardStopped,
|
|
952
1243
|
...(hazardAlertCreated ? { hazardAlert: hazardAlertCreated } : {}),
|
|
953
|
-
intervened: Boolean(interventionMessage),
|
|
1244
|
+
intervened: Boolean(interventionMessage && !interventionDeliveredFailed),
|
|
954
1245
|
queuedInterventionApproval: Boolean(interventionForApproval),
|
|
955
1246
|
smartCompacted,
|
|
956
1247
|
circuitTripped,
|
|
957
1248
|
circuitReason,
|
|
1249
|
+
...(res.thinkingEffort ? { thinkingEffort: res.thinkingEffort } : {}),
|
|
1250
|
+
...(res.thinkingEffortMode ? { thinkingEffortMode: res.thinkingEffortMode } : {}),
|
|
1251
|
+
...(dreamRoamRes ? { dreamRoam: dreamRoamRes } : {}),
|
|
1252
|
+
...(oneStopReport ? { oneStopReport } : {}),
|
|
958
1253
|
...(autoPilotStopRes ? { autoPilotStopped: Boolean(autoPilotStopRes.stopped) } : {}),
|
|
959
1254
|
}
|
|
960
1255
|
} finally {
|
|
@@ -963,10 +1258,13 @@ export async function runTurnReview(deps, { agent, sessionId, turn, force = fals
|
|
|
963
1258
|
}
|
|
964
1259
|
|
|
965
1260
|
/**
|
|
966
|
-
*
|
|
967
|
-
*
|
|
968
|
-
*
|
|
969
|
-
*
|
|
1261
|
+
* 5-Condition Idle Auto-Sleep Guard for Managed mode (`runMode === 'managed'`):
|
|
1262
|
+
* Auto-stands down `managed -> off` ONLY when ALL 5 conditions hold:
|
|
1263
|
+
* (1) Idle timeout elapsed (or goal-achieved fast stand-down) AND 0 running session agents;
|
|
1264
|
+
* (2) 0 `doing` tasks on board;
|
|
1265
|
+
* (3) 0 pending approvals / elevations;
|
|
1266
|
+
* (4) 0 pending/delivered open inquiries;
|
|
1267
|
+
* (5) 0 pending review timers AND empty `recentlyUnpinnedWatch` queue.
|
|
970
1268
|
*/
|
|
971
1269
|
export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
972
1270
|
const sidRaw = String(sessionId || '').trim()
|
|
@@ -980,12 +1278,42 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
980
1278
|
const stBefore = loadChiefState()
|
|
981
1279
|
const effBefore = resolveWorkspaceConfig(stBefore, rootId)
|
|
982
1280
|
const wsBefore = ensureWorkspace(stBefore, rootId)
|
|
983
|
-
if (effBefore.stopped || effBefore.
|
|
984
|
-
return { ok: true, stopped: false, reason: 'not-
|
|
1281
|
+
if (effBefore.stopped || effBefore.runMode !== 'managed') {
|
|
1282
|
+
return { ok: true, stopped: false, reason: 'not-managed' }
|
|
985
1283
|
}
|
|
1284
|
+
if (effBefore.tacticalModes && effBefore.tacticalModes.intervention && !opts.goalAchievedFastStop) {
|
|
1285
|
+
return { ok: true, stopped: false, reason: 'intervention-active' }
|
|
1286
|
+
}
|
|
1287
|
+
// Condition 5a: 0 pending review timers
|
|
986
1288
|
if (reviewTimers.has(rootId)) {
|
|
987
1289
|
return { ok: true, stopped: false, reason: 'review-pending' }
|
|
988
1290
|
}
|
|
1291
|
+
// Condition 3: 0 pending approvals / elevations
|
|
1292
|
+
const hasPendingApr = Array.isArray(wsBefore.pendingApprovals) && wsBefore.pendingApprovals.some(a => a && a.status === 'pending')
|
|
1293
|
+
if (hasPendingApr || wsBefore.pendingElevation) {
|
|
1294
|
+
return { ok: true, stopped: false, reason: 'pending-approvals' }
|
|
1295
|
+
}
|
|
1296
|
+
// Condition 4: 0 pending / delivered inquiries
|
|
1297
|
+
const hasOpenInq = Array.isArray(wsBefore.inquiries) && wsBefore.inquiries.some(q => q && (q.status === 'pending' || q.status === 'delivered'))
|
|
1298
|
+
if (hasOpenInq) {
|
|
1299
|
+
return { ok: true, stopped: false, reason: 'pending-inquiries' }
|
|
1300
|
+
}
|
|
1301
|
+
// Condition 2: 0 doing tasks on board
|
|
1302
|
+
const board = deps && deps.boardForSession && deps.boardFileFor
|
|
1303
|
+
? deps.boardForSession(deps.boardFileFor(rootId))
|
|
1304
|
+
: null
|
|
1305
|
+
const doingTasks = (board && Array.isArray(board.tasks) ? board.tasks : []).filter(t => t && t.status === 'doing')
|
|
1306
|
+
if (doingTasks.length > 0) {
|
|
1307
|
+
return { ok: true, stopped: false, reason: 'tasks-doing' }
|
|
1308
|
+
}
|
|
1309
|
+
// Condition 5b: empty `recentlyUnpinnedWatch` queue
|
|
1310
|
+
try {
|
|
1311
|
+
const sessOpt = archiveTargetForRoot(deps, rootId, { vaultScope: 'session' })
|
|
1312
|
+
const sStore = loadArchiveStore(sessOpt)
|
|
1313
|
+
if (Array.isArray(sStore.recentlyUnpinnedWatch) && sStore.recentlyUnpinnedWatch.length > 0) {
|
|
1314
|
+
return { ok: true, stopped: false, reason: 'unpinned-watch-pending' }
|
|
1315
|
+
}
|
|
1316
|
+
} catch {}
|
|
989
1317
|
|
|
990
1318
|
const hasRunningInSession = (dirObj) => {
|
|
991
1319
|
try {
|
|
@@ -1022,16 +1350,26 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1022
1350
|
return false
|
|
1023
1351
|
}
|
|
1024
1352
|
|
|
1353
|
+
// Condition 1a: 0 running session agents
|
|
1025
1354
|
const dirInitial = opts.directory || (deps ? await listPeerDirectory(deps, rootId) : { targets: [] })
|
|
1026
1355
|
if (hasRunningInSession(dirInitial)) {
|
|
1027
1356
|
return { ok: true, stopped: false, reason: 'agent-running' }
|
|
1028
1357
|
}
|
|
1029
1358
|
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1359
|
+
// Condition 1b: idle timeout elapsed (or explicit goal-achieved fast stand-down)
|
|
1360
|
+
const rg = (wsBefore.runtimeGuard && typeof wsBefore.runtimeGuard === 'object') ? wsBefore.runtimeGuard : {}
|
|
1361
|
+
const lastActivity = Math.max(Number(rg.lastActivityAt) || 0, Number(rg.autoPilotStartedAt) || 0)
|
|
1362
|
+
const idleTimeoutMs = Math.max(50, Number(effBefore.managedIdleTimeoutMs) || DEFAULT_MANAGED_IDLE_TIMEOUT_MS)
|
|
1363
|
+
if (!opts.goalAchievedFastStop) {
|
|
1364
|
+
if (opts.allowStartupGrace !== false) {
|
|
1365
|
+
const startedAt = Number(rg.autoPilotStartedAt || 0)
|
|
1366
|
+
const hadTurn = Boolean(rg.autoPilotHadTurn)
|
|
1367
|
+
if (!hadTurn && startedAt > 0 && Date.now() - startedAt < Math.min(15_000, idleTimeoutMs)) {
|
|
1368
|
+
return { ok: true, stopped: false, reason: 'startup-grace' }
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
if (lastActivity > 0 && Date.now() - lastActivity < idleTimeoutMs) {
|
|
1372
|
+
return { ok: true, stopped: false, reason: 'idle-timeout-not-reached' }
|
|
1035
1373
|
}
|
|
1036
1374
|
}
|
|
1037
1375
|
|
|
@@ -1068,12 +1406,14 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1068
1406
|
mutateChiefState((s) => {
|
|
1069
1407
|
const ws = ensureWorkspace(s, rootId)
|
|
1070
1408
|
const effNow = resolveWorkspaceConfig(s, rootId)
|
|
1071
|
-
if (effNow.stopped || effNow.
|
|
1409
|
+
if (effNow.stopped || effNow.runMode !== 'managed') return
|
|
1072
1410
|
if (!ws.config || typeof ws.config !== 'object') ws.config = { ...effNow }
|
|
1411
|
+
ws.config.runMode = 'off'
|
|
1073
1412
|
ws.config.paceMode = 'manual'
|
|
1074
1413
|
ws.config.autoPilot = false
|
|
1075
1414
|
ws.config.autoReview = false
|
|
1076
|
-
if (s.config && s.config.paceMode === 'auto') {
|
|
1415
|
+
if (s.config && (s.config.runMode === 'managed' || s.config.paceMode === 'auto')) {
|
|
1416
|
+
s.config.runMode = 'off'
|
|
1077
1417
|
s.config.paceMode = 'manual'
|
|
1078
1418
|
s.config.autoPilot = false
|
|
1079
1419
|
s.config.autoReview = false
|
|
@@ -1081,11 +1421,19 @@ export async function checkAndStopIdleAutoPilot(deps, sessionId, opts = {}) {
|
|
|
1081
1421
|
ws.chat.push({
|
|
1082
1422
|
id: nextId('chat'),
|
|
1083
1423
|
role: 'chief',
|
|
1084
|
-
|
|
1085
|
-
|
|
1424
|
+
kind: 'receipt',
|
|
1425
|
+
text: '- 【🤖→⏸ 托管自动休眠】连续闲置达阈值且在途任务、待批弹窗、在途问询与卷宗梳理均已清零,已自动将运行模式切换回「⏸ 关停」以节省 Token,随时可再次开启。',
|
|
1426
|
+
actions: ['托管自动休眠'],
|
|
1086
1427
|
at: Date.now(),
|
|
1087
1428
|
})
|
|
1088
1429
|
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
1430
|
+
pushAlertEventToWs(ws, {
|
|
1431
|
+
kind: 'managed_auto_sleep',
|
|
1432
|
+
level: 'success',
|
|
1433
|
+
title: '🌙 托管已自动休眠收工',
|
|
1434
|
+
body: '连续闲置达阈值且在途任务、待批弹窗与问询均已清零,已切回「⏸ 关停」。',
|
|
1435
|
+
dedupeKey: `sleep:${rootId}:${Math.floor(Date.now() / 15_000)}`,
|
|
1436
|
+
})
|
|
1089
1437
|
stoppedNow = true
|
|
1090
1438
|
})
|
|
1091
1439
|
|